Show Metacritic.com ratings

Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, fandango.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com

当前为 2022-02-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Show Metacritic.com ratings
  3. // @description Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, fandango.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com
  4. // @namespace cuzi
  5. // @icon https://www.metacritic.com/images/icons/metacritic-icon.svg
  6. // @supportURL https://github.com/cvzi/Metacritic-userscript/issues
  7. // @contributionURL https://buymeacoff.ee/cuzi
  8. // @contributionURL https://ko-fi.com/cuzicvzi
  9. // @grant unsafeWindow
  10. // @grant GM.xmlHttpRequest
  11. // @grant GM.setValue
  12. // @grant GM.getValue
  13. // @grant GM.registerMenuCommand
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
  15. // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
  16. // @antifeature tracking When a metacritic rating is displayed, we may store the url of the current website and the metacritic url in our database. Log files are temporarily retained by our database hoster heroku.com and contain your IP address and browser configuration.
  17. // @version 75
  18. // @connect metacritic.com
  19. // @connect php-cuzi.herokuapp.com
  20. // @include https://*.bandcamp.com/*
  21. // @include https://play.google.com/store/music/album/*
  22. // @include https://play.google.com/store/movies/details/*
  23. // @include https://music.amazon.com/*
  24. // @include https://www.amazon.com/*
  25. // @include https://smile.amazon.com/*
  26. // @include https://www.amazon.co.uk/*
  27. // @include https://smile.amazon.co.uk/*
  28. // @include https://www.amazon.fr/*
  29. // @include https://www.amazon.de/*
  30. // @include https://smile.amazon.de/*
  31. // @include https://www.amazon.es/*
  32. // @include https://www.amazon.ca/*
  33. // @include https://www.amazon.in/*
  34. // @include https://www.amazon.it/*
  35. // @include https://www.amazon.co.jp/*
  36. // @include https://www.amazon.com.mx/*
  37. // @include https://www.amazon.com.au/*
  38. // @include https://www.imdb.com/title/*
  39. // @include https://store.steampowered.com/app/*
  40. // @include https://www.gamespot.com/*
  41. // @include https://www.serienjunkies.de/*
  42. // @include https://www.rottentomatoes.com/m/*
  43. // @include https://rottentomatoes.com/m/*
  44. // @include https://www.rottentomatoes.com/tv/*
  45. // @include https://rottentomatoes.com/tv/*
  46. // @include https://www.rottentomatoes.com/tv/*/s*/
  47. // @include https://rottentomatoes.com/tv/*/s*/
  48. // @include https://www.boxofficemojo.com/movies/*
  49. // @include https://www.boxofficemojo.com/release/*
  50. // @include https://www.allmovie.com/movie/*
  51. // @include https://en.wikipedia.org/*
  52. // @include https://www.fandango.com/*
  53. // @include https://www.flixster.com/movie/*
  54. // @include https://www.themoviedb.org/movie/*
  55. // @include https://www.themoviedb.org/tv/*
  56. // @include https://letterboxd.com/film/*
  57. // @exclude https://letterboxd.com/film/*/image*
  58. // @include https://www.tvmaze.com/shows/*
  59. // @include https://www.tvguide.com/tvshows/*
  60. // @include https://followshows.com/show/*
  61. // @include https://thetvdb.com/series/*
  62. // @include https://thetvdb.com/movies/*
  63. // @include https://consequenceofsound.net/*
  64. // @include https://consequence.net/*
  65. // @include https://pitchfork.com/*
  66. // @include https://www.last.fm/*
  67. // @include https://tvnfo.com/s/*
  68. // @include https://rateyourmusic.com/release/album/*
  69. // @include https://open.spotify.com/*
  70. // @include https://play.spotify.com/album/*
  71. // @include https://www.nme.com/reviews/*
  72. // @include https://www.albumoftheyear.org/album/*
  73. // @include https://itunes.apple.com/*/movie/*
  74. // @include https://itunes.apple.com/*/album/*
  75. // @include https://music.apple.com/*/album/*
  76. // @include https://itunes.apple.com/*/tv-season/*
  77. // @include https://epguides.com/*
  78. // @include https://www.epguides.com/*
  79. // @include https://sharetv.com/shows/*
  80. // @include https://www.netflix.com/*
  81. // @include https://www.cc.com/*
  82. // @include https://www.tvhoard.com/*
  83. // @include https://www.amc.com/*
  84. // @include https://www.amcplus.com/*
  85. // @include https://rlsbb.ru/*/
  86. // @include https://newalbumreleases.net/*
  87. // @include https://www.sho.com/*
  88. // @include https://www.epicgames.com/store/*
  89. // @include https://www.gog.com/*
  90. // @include https://www.allmusic.com/album/*
  91. // ==/UserScript==
  92.  
  93. /* globals alert, confirm, GM, DOMParser, $, Image, unsafeWindow, parent, Blob */
  94.  
  95. const baseURL = 'https://www.metacritic.com/'
  96.  
  97. const baseURLmusic = 'https://www.metacritic.com/music/'
  98. const baseURLmovie = 'https://www.metacritic.com/movie/'
  99. const baseURLpcgame = 'https://www.metacritic.com/game/pc/'
  100. const baseURLps4 = 'https://www.metacritic.com/game/playstation-4/'
  101. const baseURLxone = 'https://www.metacritic.com/game/xbox-one/'
  102. const baseURLtv = 'https://www.metacritic.com/tv/'
  103.  
  104. const baseURLsearch = 'https://www.metacritic.com/search/{type}/{query}/results'
  105. const baseURLautosearch = 'https://www.metacritic.com/autosearch'
  106.  
  107. const baseURLdatabase = 'https://php-cuzi.herokuapp.com/r.php'
  108. const baseURLwhitelist = 'https://php-cuzi.herokuapp.com/whitelist.php'
  109. const baseURLblacklist = 'https://php-cuzi.herokuapp.com/blacklist.php'
  110.  
  111. const TEMPORARY_BLACKLIST_TIMEOUT = 5 * 60
  112.  
  113. // http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/
  114. const CSS = '#mcdiv123 .grespinner{height:16px;width:16px;margin:0 auto;position:relative;animation:rotation .6s infinite linear;border-left:6px solid rgba(0,174,239,.15);border-right:6px solid rgba(0,174,239,.15);border-bottom:6px solid rgba(0,174,239,.15);border-top:6px solid rgba(0,174,239,.8);border-radius:100%}@keyframes rotation{from{transform:rotate(0)}to{transform:rotate(359deg)}}#mcdiv123searchresults .result{font:12px arial,helvetica,serif;border-top-width:1px;border-top-color:#ccc;border-top-style:solid;padding:5px}#mcdiv123searchresults .result .result_type{display:inline}#mcdiv123searchresults .result .result_wrap{float:left;width:100%}#mcdiv123searchresults .result .has_score{padding-left:42px}#mcdiv123searchresults .result .basic_stats{height:1%;overflow:hidden}#mcdiv123searchresults .result h3{font-size:14px;font-weight:700}#mcdiv123searchresults .result a{color:#09f;font-weight:700;text-decoration:none}#mcdiv123searchresults .metascore_w.game.seventyfive,#mcdiv123searchresults .metascore_w.positive,#mcdiv123searchresults .metascore_w.score_favorable,#mcdiv123searchresults .metascore_w.score_outstanding,#mcdiv123searchresults .metascore_w.sixtyone{background-color:#6c3}#mcdiv123searchresults .metascore_w.forty,#mcdiv123searchresults .metascore_w.game.fifty,#mcdiv123searchresults .metascore_w.mixed,#mcdiv123searchresults .metascore_w.score_mixed{background-color:#fc3}#mcdiv123searchresults .metascore_w.negative,#mcdiv123searchresults .metascore_w.score_terrible,#mcdiv123searchresults .metascore_w.score_unfavorable{background-color:red}#mcdiv123searchresults a.metascore_w,#mcdiv123searchresults span.metascore_w{display:inline-block}#mcdiv123searchresults .result .metascore_w{color:#fff!important;font-family:Arial,Helvetica,sans-serif;font-size:17px;font-style:normal!important;font-weight:700!important;height:2em;line-height:2em;text-align:center;vertical-align:middle;width:2em;float:left;margin:0 0 0 -42px}#mcdiv123searchresults .result .more_stats{font-size:10px;color:#444}#mcdiv123searchresults .result .release_date .data{font-weight:700;color:#000}#mcdiv123searchresults ol,#mcdiv123searchresults ul{list-style:none}#mcdiv123searchresults .result li.stat{background:0 0;display:inline;float:left;margin:0;padding:0 6px 0 0;white-space:nowrap}#mcdiv123searchresults .result .deck{margin:3px 0 0}#mcdiv123searchresults .result .basic_stat{display:inline;float:right;overflow:hidden;width:100%}'
  115.  
  116. let myDOMParser = null
  117. function domParser () {
  118. if (myDOMParser === null) {
  119. myDOMParser = new DOMParser()
  120. }
  121. return myDOMParser
  122. }
  123.  
  124. async function versionUpdate () {
  125. const version = parseInt(await GM.getValue('version', 0))
  126. if (version <= 51) {
  127. // Reset database
  128. await GM.setValue('map', '{}')
  129. await GM.setValue('black', '[]')
  130. await GM.setValue('hovercache', '{}')
  131. await GM.setValue('requestcache', '{}')
  132. await GM.setValue('searchcache', '{}')
  133. await GM.setValue('autosearchcache', '{}')
  134. await GM.setValue('temporaryblack', '{}')
  135. }
  136. if (version < 55) {
  137. await GM.setValue('version', 55)
  138. }
  139. }
  140.  
  141. async function acceptGDPR (showDialog) {
  142. if (showDialog === true) {
  143. await GM.setValue('gdpr', null)
  144. return acceptGDPR()
  145. }
  146. return new Promise(function (resolve) {
  147. GM.getValue('gdpr', null).then(function (value) {
  148. if (value === true) {
  149. return resolve(true)
  150. }
  151. if (value === false) {
  152. return resolve(false)
  153. }
  154. const html = '<h1>Privacy Policy for &quot;Show Metacritic.com ratings&quot;</h1><h2>General Data Protection Regulation (GDPR)</h2><p>We are a Data Controller of your information.</p> <p>&quot;Show Metacritic.com ratings&quot; legal basis for collecting and using the personal information described in this Privacy Policy depends on the Personal Information we collect and the specific context in which we collect the information:</p><ul> <li>&quot;Show Metacritic.com ratings&quot; needs to perform a contract with you</li> <li>You have given &quot;Show Metacritic.com ratings&quot; permission to do so</li> <li>Processing your personal information is in &quot;Show Metacritic.com ratings&quot; legitimate interests</li> <li>&quot;Show Metacritic.com ratings&quot; needs to comply with the law</li></ul> <p>&quot;Show Metacritic.com ratings&quot; will retain your personal information only for as long as is necessary for the purposes set out in this Privacy Policy. We will retain and use your information to the extent necessary to comply with our legal obligations, resolve disputes, and enforce our policies.</p> <p>If you are a resident of the European Economic Area (EEA), you have certain data protection rights. If you wish to be informed what Personal Information we hold about you and if you want it to be removed from our systems, please contact us. Our Privacy Policy was generated with the help of <a href="https://www.gdprprivacypolicy.net/">GDPR Privacy Policy Generator</a> and the <a href="https://www.app-privacy-policy.com">App Privacy Policy Generator</a>.</p><p>In certain circumstances, you have the following data protection rights:</p><ul> <li>The right to access, update or to delete the information we have on you.</li> <li>The right of rectification.</li> <li>The right to object.</li> <li>The right of restriction.</li> <li>The right to data portability</li> <li>The right to withdraw consent</li></ul><h2>Log Files</h2><p>&quot;Show Metacritic.com ratings&quot; follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services\' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users\' movement on the website, and gathering demographic information.</p><h2>Privacy Policies</h2><P>You may consult this list to find the Privacy Policy for each of the advertising partners of &quot;Show Metacritic.com ratings&quot;.</p><p>Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on &quot;Show Metacritic.com ratings&quot;, which are sent directly to users\' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.</p><p>Note that &quot;Show Metacritic.com ratings&quot; has no access to or control over these cookies that are used by third-party advertisers.</p><h2>Third Party Privacy Policies</h2><p>&quot;Show Metacritic.com ratings&quot;\'s Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.List of these Privacy Policies and their links: <ul> <li>Heroku: <a href="https://www.salesforce.com/company/privacy/">https://www.salesforce.com/company/privacy/</a></li> <li>www.metacritic.com: <a href="https://privacy.cbs/">https://privacy.cbs/</a></li></ul></p><p>You can choose to disable cookies through your individual browser options.</p><h2>Children\'s Information</h2><p>Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.</p><p>&quot;Show Metacritic.com ratings&quot; does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.</p><h2>Online Privacy Policy Only</h2><p>Our Privacy Policy created at GDPRPrivacyPolicy.net) applies only to our online activities and is valid for users of our program with regards to the information that they shared and/or collect in &quot;Show Metacritic.com ratings&quot;. This policy is not applicable to any information collected offline or via channels other than this program. <a href="https://gdprprivacypolicy.net">Our GDPR Privacy Policy</a> was generated from the GDPR Privacy Policy Generator.</p><h2>Contact</h2><p>Contact us via github <a href="https://github.com/cvzi/Metacritic-userscript">https://github.com/cvzi/Metacritic-userscript</a> or email cuzi@openmail.cc</p><h2>Consent</h2><p>By using our program ("userscript"), you hereby consent to our Privacy Policy and agree to its terms.</p>'
  155. const div = document.body.appendChild(document.createElement('div'))
  156. div.innerHTML = html
  157. div.style = 'z-index:9999;position:absolute;min-height:100%;top:0px; left:0px; right:0px; padding:10px; background:white; color:black; font-family:serif; font-size:16px'
  158. div.appendChild(document.createElement('br'))
  159. const acceptButton = div.appendChild(document.createElement('button'))
  160. acceptButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
  161. acceptButton.appendChild(document.createTextNode('Accept'))
  162. acceptButton.addEventListener('click', function () {
  163. div.remove()
  164. resolve(true)
  165. GM.setValue('gdpr', true)
  166. })
  167. const declineButton = div.appendChild(document.createElement('button'))
  168. declineButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
  169. declineButton.appendChild(document.createTextNode('Decline'))
  170. declineButton.addEventListener('click', function () {
  171. alert('You may uninstall the userscript now.')
  172. div.remove()
  173. resolve(false)
  174. GM.setValue('gdpr', false)
  175. })
  176. const space = div.appendChild(document.createElement('div'))
  177. space.style = 'height:2000px;'
  178. div.scrollIntoView()
  179. window.setTimeout(function () {
  180. alert('ShowMetacriticRatings:\n\nWhen you use this script, data will be sent to our database and to metacritic.com. This data includes the url of the website that you are browsing, the metacritic page url, your IP adress, browser configuration and language preferences. We only store the url of the website and the metacritic url and no personal information. Log files are temporarily retained and contain your IP address. We have no control over which data is stored by metacritic.com and our hoster heroku.com, see their respective privacy policies for more information (see "Third Party Privacy Policies").\n\nPlease read and accept our privacy policy now or uninstall this userscript.')
  181. }, 20)
  182. })
  183. })
  184. }
  185.  
  186. function delay (ms) {
  187. return new Promise(function (resolve) {
  188. window.setTimeout(() => resolve(), ms)
  189. })
  190. }
  191.  
  192. function getHostname (url) {
  193. const a = document.createElement('a')
  194. a.href = url
  195. return a.hostname
  196. }
  197. function absoluteMetaURL (url) {
  198. if (url.startsWith('https://')) {
  199. return url
  200. }
  201. if (url.startsWith('http://')) {
  202. return 'https' + url.substr(4)
  203. }
  204. if (url.startsWith('//')) {
  205. return baseURL + url.substr(2)
  206. }
  207. if (url.startsWith('/')) {
  208. return baseURL + url.substr(1)
  209. }
  210. return baseURL + url
  211. }
  212.  
  213. const parseLDJSONCache = {}
  214. function parseLDJSON (keys, condition) {
  215. if (document.querySelector('script[type="application/ld+json"]')) {
  216. const data = []
  217. const scripts = document.querySelectorAll('script[type="application/ld+json"]')
  218. for (let i = 0; i < scripts.length; i++) {
  219. let jsonld
  220. if (scripts[i].innerText in parseLDJSONCache) {
  221. jsonld = parseLDJSONCache[scripts[i].innerText]
  222. } else {
  223. try {
  224. jsonld = JSON.parse(scripts[i].innerText)
  225. parseLDJSONCache[scripts[i].innerText] = jsonld
  226. } catch (e) {
  227. parseLDJSONCache[scripts[i].innerText] = null
  228. continue
  229. }
  230. }
  231. if (jsonld) {
  232. if (Array.isArray(jsonld)) {
  233. data.push(...jsonld)
  234. } else {
  235. data.push(jsonld)
  236. }
  237. }
  238. }
  239. for (let i = 0; i < data.length; i++) {
  240. try {
  241. if (data[i] && data[i] && (typeof condition !== 'function' || condition(data[i]))) {
  242. if (Array.isArray(keys)) {
  243. const r = []
  244. for (let j = 0; j < keys.length; j++) {
  245. r.push(data[i][keys[j]])
  246. }
  247. return r
  248. } else if (keys) {
  249. return data[i][keys]
  250. } else if (typeof condition === 'function') {
  251. return data[i] // Return whole object
  252. }
  253. }
  254. } catch (e) {
  255. continue
  256. }
  257. }
  258. return data
  259. }
  260. return null
  261. }
  262.  
  263. function name2metacritic (s) {
  264. const mc = s.normalize('NFKD').replace(/\//g, '').replace(/[\u0300-\u036F]/g, '').replace(/&/g, 'and').replace(/\W+/g, ' ').toLowerCase().trim().replace(/\W+/g, '-')
  265. if (!mc) {
  266. throw new Error("name2metacritic converted '" + s + "' to empty string")
  267. }
  268. return mc
  269. }
  270. function minutesSince (time) {
  271. const seconds = ((new Date()).getTime() - time.getTime()) / 1000
  272. return seconds > 60 ? parseInt(seconds / 60) + ' min ago' : 'now'
  273. }
  274. function randomStringId () {
  275. const id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1)
  276. return id10() + id10() + id10() + id10() + id10() + id10()
  277. }
  278. function fixMetacriticURLs (html) {
  279. return html.replace(/<a /g, '<a target="_blank" ').replace(/href="\//g, 'href="' + baseURL).replace(/src="\//g, 'src="' + baseURL)
  280. }
  281. function searchType2metacritic (type) {
  282. return ({
  283. movie: 'movie',
  284. pcgame: 'game',
  285. xonegame: 'game',
  286. ps4game: 'game',
  287. music: 'album',
  288. tv: 'tv'
  289. })[type]
  290. }
  291. function metacritic2searchType (type) {
  292. return ({
  293. Album: 'music',
  294. TV: 'tv',
  295. Movie: 'movie',
  296. 'PC Game': 'pcgame',
  297. 'PS4 Game': 'ps4game',
  298. 'XONE Game': 'onegame',
  299. 'WIIU Game': 'xxxxx',
  300. '3DS Game': 'xxxx'
  301. })[type]
  302. }
  303.  
  304. function replaceBrackets (str) {
  305. str = str.replace(/\([^\(]*\)/g, '')
  306. str = str.replace(/\[[^\]]*\]/g, '')
  307. return str.trim()
  308. }
  309. function removeSymbols (str) {
  310. str = str.replace(/[^\s0-9A-Za-zÀ-ÖØ-öø-ÿ]*/gi, '').trim()
  311. return str.trim()
  312. }
  313. const dashRegExp = new RegExp('[-\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D]')
  314. function removeAnythingAfterDash (str) {
  315. str = str.split(dashRegExp)[0]
  316. return str.trim()
  317. }
  318.  
  319. function broadenSearch (data, step, type) {
  320. if (type === 'pcgame') {
  321. if (step > 0) {
  322. data[0] = replaceBrackets(data[0])
  323. } else if (step > 1) {
  324. data[0] = removeSymbols(data[0])
  325. } else if (step > 2) {
  326. data[0] = removeAnythingAfterDash(data[0])
  327. }
  328. }
  329. return data
  330. }
  331.  
  332. function balloonAlert (message, timeout, title, css, click) {
  333. let header
  334. if (title) {
  335. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title + '</div>'
  336. } else if (title === false) {
  337. header = ''
  338. } else {
  339. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>'
  340. }
  341. const div = $('<div>' + header + '<div style="padding:5px">' + message.split('\n').join('<br>') + '</div></div>')
  342. div.css({
  343. position: 'fixed',
  344. top: 10,
  345. left: 10,
  346. maxWidth: 200,
  347. zIndex: '2147483601',
  348. background: 'rgb(240,240,240)',
  349. border: '2px solid yellow',
  350. borderRadius: '6px',
  351. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  352. fontFamily: 'sans-serif',
  353. color: 'black'
  354. })
  355. if (css) {
  356. div.css(css)
  357. }
  358. div.appendTo(document.body)
  359.  
  360. if (click) {
  361. div.click(function (ev) {
  362. $(this).hide(500)
  363. click.call(this, ev)
  364. })
  365. }
  366.  
  367. if (!click) {
  368. const close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">&#10062;</div>').appendTo(div)
  369. close.click(function () {
  370. $(this.parentNode).hide(1000)
  371. })
  372. }
  373.  
  374. if (timeout && timeout > 0) {
  375. window.setTimeout(function () {
  376. div.hide(3000)
  377. }, timeout)
  378. }
  379. return div
  380. }
  381.  
  382. function filterUniversalUrl (url) {
  383. try {
  384. url = url.match(/http.+/)[0]
  385. } catch (e) { }
  386.  
  387. try {
  388. url = url.replace(/https?:\/\/(www.)?/, '')
  389. } catch (e) { }
  390.  
  391. if (url.indexOf('#') !== -1) {
  392. url = url.split('#')[0]
  393. }
  394.  
  395. if (url.startsWith('imdb.com/') && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
  396. // Remove movie subpage from imdb url
  397. return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1]
  398. } else if (url.startsWith('boxofficemojo.com/') && url.indexOf('id=') !== -1) {
  399. // Keep the important id= on
  400. try {
  401. const parts = url.split('?')
  402. const page = parts[0] + '?'
  403. const idparam = parts[1].match(/(id=.+?)(\.|&)/)[1]
  404. return page + idparam
  405. } catch (e) {
  406. return url
  407. }
  408. } else {
  409. // Default: Remove parameters
  410. return url.split('?')[0].split('&')[0]
  411. }
  412. }
  413.  
  414. async function addToMap (url, metaurl) {
  415. const data = JSON.parse(await GM.getValue('map', '{}'))
  416.  
  417. url = filterUniversalUrl(url)
  418. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  419.  
  420. data[url] = metaurl
  421.  
  422. await GM.setValue('map', JSON.stringify(data));
  423.  
  424. (new Image()).src = baseURLwhitelist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  425. return [url, metaurl]
  426. }
  427.  
  428. async function removeFromMap (url) {
  429. const data = JSON.parse(await GM.getValue('map', '{}'))
  430.  
  431. url = filterUniversalUrl(url)
  432. if (url in data) {
  433. delete data[url]
  434. await GM.setValue('map', JSON.stringify(data))
  435. }
  436. }
  437.  
  438. async function addToTemporaryBlacklist (metaurl) {
  439. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  440.  
  441. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  442. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  443. metaurl = metaurl.replace(/^\/+/, '')
  444.  
  445. data[metaurl] = (new Date()).toJSON()
  446.  
  447. // Remove old entries
  448. const now = (new Date()).getTime()
  449. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  450. for (const prop in data) {
  451. if (now - (new Date(data[prop].time)).getTime() > timeout) {
  452. delete data[prop]
  453. }
  454. }
  455.  
  456. await GM.setValue('temporaryblack', JSON.stringify(data))
  457.  
  458. return true
  459. }
  460.  
  461. async function isTemporaryBlacklisted (metaurl) {
  462. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  463.  
  464. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  465. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  466. metaurl = metaurl.replace(/^\/+/, '')
  467.  
  468. if (metaurl in data) {
  469. const now = (new Date()).getTime()
  470. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  471. if (now - (new Date(data[metaurl])).getTime() < timeout) {
  472. return true
  473. }
  474. }
  475. return false
  476. }
  477.  
  478. async function addToBlacklist (url, metaurl) {
  479. const data = JSON.parse(await GM.getValue('black', '[]'))
  480.  
  481. url = filterUniversalUrl(url)
  482. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  483.  
  484. data.push([url, metaurl])
  485.  
  486. await GM.setValue('black', JSON.stringify(data));
  487.  
  488. (new Image()).src = baseURLblacklist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  489. return [url, metaurl]
  490. }
  491.  
  492. async function removeFromBlacklist (docurl, metaurl) {
  493. docurl = filterUniversalUrl(docurl)
  494. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  495.  
  496. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  497. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  498. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  499.  
  500. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  501. const found = []
  502. for (let i = 0; i < data.length; i++) {
  503. if (data[i][0] === docurl && data[i][1] === metaurl) {
  504. found.push(i)
  505. }
  506. }
  507. for (let i = found.length - 1; i >= 0; i--) {
  508. data.pop(i)
  509. }
  510.  
  511. await GM.setValue('black', JSON.stringify(data))
  512. }
  513.  
  514. async function isBlacklistedUrl (docurl, metaurl) {
  515. docurl = filterUniversalUrl(docurl)
  516. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  517.  
  518. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  519. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  520. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  521.  
  522. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  523. for (let i = 0; i < data.length; i++) {
  524. if (data[i][0] === docurl && data[i][1] === metaurl) {
  525. return true
  526. }
  527. }
  528. return false
  529. }
  530.  
  531. let listenForHotkeysActive = false
  532. function listenForHotkeys (code, cb) {
  533. // Call cb() as soon as the code sequence was typed
  534. if (listenForHotkeysActive) {
  535. return
  536. }
  537. listenForHotkeysActive = true
  538. let i = 0
  539. $(document).bind('keydown.listenForHotkeys', function (ev) {
  540. if (document.activeElement === document.body) {
  541. if (ev.key !== code[i]) {
  542. i = 0
  543. } else {
  544. i++
  545. if (i === code.length) {
  546. ev.preventDefault()
  547. $(document).unbind('keydown.listenForHotkeys')
  548. cb()
  549. }
  550. }
  551. }
  552. })
  553. }
  554.  
  555. function waitForHotkeysMETA () {
  556. listenForHotkeys('meta', (ev) => openSearchBox())
  557. }
  558.  
  559. function asyncRequest (data) {
  560. return new Promise(async function (resolve, reject) {
  561. const cachedValue = await isInRequestCache(data)
  562. if (cachedValue) {
  563. return resolve(cachedValue)
  564. }
  565. const defaultHeaders = {
  566. Referer: data.url,
  567. // Host: getHostname(data.url),
  568. 'User-Agent': navigator.userAgent
  569. }
  570. const defaultData = {
  571. method: 'GET',
  572. onload: function (response) {
  573. storeInRequestCache(data, response)
  574. resolve(response)
  575. },
  576. onerror: (response) => reject(response)
  577. }
  578. if ('headers' in data) {
  579. data.headers = Object.assign(defaultHeaders, data.headers)
  580. } else {
  581. data.headers = defaultHeaders
  582. }
  583.  
  584. data = Object.assign(defaultData, data)
  585. GM.xmlHttpRequest(data)
  586. })
  587. }
  588.  
  589. async function handleJSONredirect (response) {
  590. let blacklistedredirect = false
  591. const j = JSON.parse(response.responseText)
  592.  
  593. // Blacklist items from database received?
  594. if ('blacklist' in j && j.blacklist && j.blacklist.length) {
  595. // Save new blacklist items
  596. const data = JSON.parse(await GM.getValue('black', '[]'))
  597. for (let i = 0; i < j.blacklist.length; i++) {
  598. const saveDocurl = j.blacklist[i].docurl
  599. const saveMetaurl = j.blacklist[i].metaurl
  600.  
  601. data.push([saveDocurl, saveMetaurl])
  602. if (j.jsonRedirect === '/' + saveMetaurl) {
  603. // Redirect is blacklisted!
  604. blacklistedredirect = true
  605. }
  606. }
  607. await GM.setValue('black', JSON.stringify(data))
  608. }
  609. if (blacklistedredirect) {
  610. // Redirect was blacklisted, show nothing
  611. console.debug('ShowMetacriticRatings: Redirect was blacklisted -> show nothing')
  612. return null
  613. } else {
  614. // Load redirect
  615. current.metaurl = absoluteMetaURL(j.jsonRedirect)
  616. response = await asyncRequest({
  617. method: 'POST',
  618. url: current.metaurl,
  619. data: 'hoverinfo=1',
  620. headers: {
  621. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  622. 'X-Requested-With': 'XMLHttpRequest'
  623. }
  624. }).catch(function (response) {
  625. console.error('ShowMetacriticRatings: Error 01')
  626. })
  627. return response
  628. }
  629. }
  630.  
  631. function extractHoverFromFullPage (response) {
  632. let html = 'ShowMetacriticRatings:<br>Error occured in extractHoverFromFullPage()'
  633. try {
  634. // Try parsing HTML
  635. const doc = domParser().parseFromString(response.responseText, 'text/html')
  636. doc.querySelector('.product_page_title h1')
  637. doc.querySelector('.summary_img')
  638. doc.querySelectorAll('.details_section')
  639. doc.querySelectorAll('#nav_to_metascore .distribution')
  640.  
  641. let pageUrl = ''
  642. let imgSrc = ''
  643. let imgAlt = ''
  644. let title = ''
  645. let publisher = ''
  646. let releaseDate = ''
  647. let starring = ''
  648. let criticsScore = ''
  649. let criticsClass = ''
  650. let criticsNumber = ''
  651. let criticsCharts = ''
  652. let userScore = ''
  653. let userClass = ''
  654. let userNumber = ''
  655. let userCharts = ''
  656.  
  657. pageUrl = response.finalUrl + (response.finalUrl.endsWith('/') ? '' : '/')
  658. imgSrc = doc.querySelector('.summary_img').src
  659. imgAlt = doc.querySelector('.summary_img').alt
  660. title = doc.querySelector('.product_page_title h1').textContent
  661. if (doc.querySelector('.details_section .distributor a')) { publisher = doc.querySelector('.details_section .distributor a').textContent }
  662.  
  663. if (doc.querySelector('.details_section .release_date span:nth-child(2)')) {
  664. const date = doc.querySelector('.details_section .release_date span:nth-child(2)').textContent
  665. releaseDate = `
  666. <div class="summary_detail release_data">
  667. <span class="label">Release Date:</span>
  668. <span class="data">${date}</span>
  669. </div>`
  670. }
  671.  
  672. if (doc.querySelector('.details_section.summary_cast span:nth-child(2)')) {
  673. const stars = doc.querySelector('.details_section.summary_cast span:nth-child(2)').innerHTML
  674. starring = `
  675. <div>
  676. <div class="summary_detail product_credits">
  677. <span class="label">Starring:</span>
  678. <span class="data">
  679. ${stars}
  680. </span>
  681. </div>
  682. </div>`
  683. }
  684.  
  685. criticsClass = 'metascore_w medium tbd'
  686. criticsScore = 'tbd'
  687. userClass = 'metascore_w medium user tbd'
  688. userScore = 'tbd'
  689.  
  690. if (doc.querySelector('.score_details .based_on')) {
  691. criticsNumber = doc.querySelector('.score_details .based_on').textContent.match(/\d+/)
  692. } else {
  693. criticsNumber = 'By'
  694. }
  695. if (doc.querySelector('.user_score_summary .based_on')) {
  696. userNumber = doc.querySelector('.user_score_summary .based_on').textContent.match(/\d+/)
  697. } else {
  698. userNumber = 'User'
  699. }
  700.  
  701. // Remove text from distribution charts:
  702. let label = doc.querySelector('#nav_to_metascore .charts .label.fl')
  703. while (label) {
  704. label.parentNode.title = label.textContent.trim() + ' ' + label.parentNode.querySelector('.count').textContent.trim()
  705. label.remove()
  706. label = doc.querySelector('#nav_to_metascore .charts .label.fl')
  707. }
  708. const scores = doc.querySelectorAll('#nav_to_metascore .distribution .metascore_w')
  709. if (scores.length === 2) {
  710. criticsScore = scores[0].innerText
  711. criticsClass = scores[0].className.replace('larger', 'medium')
  712. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  713. criticsCharts = '<td class="meta">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  714. userScore = scores[1].innerText
  715. userClass = scores[1].className.replace('larger', 'medium')
  716. scores[1].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  717. userCharts = '<td class="usr">' + scores[1].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  718. } else if (scores.length === 1) {
  719. if (scores[0].className.indexOf('user') === -1) {
  720. criticsScore = scores[0].innerText
  721. criticsClass = scores[0].className.replace('larger', 'medium')
  722. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  723. criticsCharts = '<td class="meta">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  724. } else {
  725. userScore = scores[0].innerText
  726. userClass = scores[0].className.replace('larger', 'medium')
  727. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  728. userCharts = '<td class="usr">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  729. }
  730. }
  731.  
  732. html = `
  733. <div class="hoverinfo">
  734. <div class="hover_left">
  735. <div class="product_image_wrapper">
  736. <a target="_blank" href="${pageUrl}">
  737. <img class="product_image large_image" src="${imgSrc}" alt="${imgAlt}" />
  738. </a>
  739. </div>
  740. </div>
  741. <div class="hover_right">
  742. <h2 class="product_title">
  743. <a target="_blank" href="${pageUrl}">${title}</a>
  744. </h2>
  745. <div>
  746. <div class="summary_detail publisher">
  747. <span class="data">${publisher}</span>
  748. <span>&nbsp;|&nbsp;&nbsp;</span>
  749. </div>
  750. ${releaseDate}
  751. <div class="clr"></div>
  752. </div>
  753. ${starring}
  754. <div class="hr">
  755. &nbsp;
  756. </div>
  757.  
  758. <table class="hover_scores ">
  759. <tr>
  760. <td class="meta num">
  761. <a target="_blank" class="metascore_anchor" href="${pageUrl}#nav_to_metascore">
  762. <span class="${criticsClass}">${criticsScore}</span>
  763. </a>
  764. </td>
  765. <td class="meta txt">
  766. <div class="metascore_label">Metascore</div>
  767. <div class="metascore_review_count">
  768. <a target="_blank" href="${pageUrl}#nav_to_metascore">
  769. <span>${criticsNumber}</span> critics
  770. </a>
  771. </div>
  772. </td>
  773. ${criticsCharts}
  774. <td class="usr num">
  775.  
  776. <a target="_blank" class="metascore_anchor" href="${pageUrl}#nav_to_metascore">
  777. <span class="${userClass}">${userScore}</span>
  778. </a>
  779.  
  780. </td>
  781. <td class="usr txt">
  782. <div class="userscore_label">User Score</div>
  783. <div class="userscore_review_count">
  784. <a target="_blank" href="${pageUrl}#nav_to_metascore">
  785. <span>${userNumber}</span> Ratings
  786. </a>
  787. </div>
  788. </td>
  789. ${userCharts}
  790. </tr>
  791. </table>
  792.  
  793. </div>
  794.  
  795. <div class="clr"></div>
  796. </div>
  797. `
  798. } catch (e) {
  799. console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e)
  800.  
  801. // fallback to cutting out the relevant parts
  802.  
  803. let parts = response.responseText.split('class="score_details')
  804. const textPart = '<div class="' + parts[1].split('</div>')[0] + '</div>'
  805.  
  806. let titleText = '<div class="product_page_title' + response.responseText.split('class="product_page_title')[1].split('</div>')[0]
  807. titleText = titleText.split('<h1>').join('<h1 style="padding:0px; margin:2px">') + '</div>'
  808.  
  809. parts = response.responseText.split('id="nav_to_metascore"')
  810. let metaScorePart = '<div ' + parts[1].split('<div class="subsection_title"')[0] + '</div></div>'
  811.  
  812. metaScorePart = metaScorePart.split('href="">').join('href="' + response.finalUrl + '">')
  813. metaScorePart = metaScorePart.split('section_title bold">').join('section_title bold">' + titleText)
  814.  
  815. html = metaScorePart.split('<div class="distribution">').join(textPart + '<div class="distribution">')
  816.  
  817. if (html.indexOf('products_module') !== -1) {
  818. // Critic reviews are not available for this Series yet -> Cut the preview for other series
  819. html = html.split('products_module')[0] + '"></div>'
  820. }
  821.  
  822. if (html.length > 5000) {
  823. // Probably something went wrong, let's cut the response to prevent too long content
  824. console.warn('ShowMetacriticRatings: Cutting response to 5000 chars')
  825. html = html.substr(0, 5000)
  826. }
  827. }
  828. return html
  829. }
  830.  
  831. async function storeInRequestCache (requestData, response) {
  832. if ('onload' in requestData) {
  833. delete requestData.onload
  834. }
  835. if ('onerror' in requestData) {
  836. delete requestData.onerror
  837. }
  838. const newkey = JSON.stringify(requestData)
  839. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  840. const now = (new Date()).getTime()
  841. const timeout = 15 * 60 * 1000
  842. for (const prop in cache) {
  843. // Delete cached values, that are older than 15 minutes
  844. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  845. delete cache[prop]
  846. }
  847. }
  848.  
  849. const newobj = {}
  850. for (const key in response) {
  851. newobj[key] = response[key]
  852. }
  853. newobj.responseText = '' + response.responseText
  854. newobj.cached = true
  855. if (!('time' in newobj)) {
  856. newobj.time = (new Date()).toJSON()
  857. }
  858.  
  859. cache[newkey] = newobj
  860.  
  861. await GM.setValue('requestcache', JSON.stringify(cache))
  862. }
  863.  
  864. async function isInRequestCache (requestData) {
  865. if ('onload' in requestData) {
  866. delete requestData.onload
  867. }
  868. if ('onerror' in requestData) {
  869. delete requestData.onerror
  870. }
  871. const key = JSON.stringify(requestData)
  872.  
  873. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  874. const now = (new Date()).getTime()
  875. const timeout = 15 * 60 * 1000
  876. for (const prop in cache) {
  877. // Delete cached values, that are older than 15 minutes
  878. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  879. delete cache[prop]
  880. }
  881. }
  882.  
  883. if (key in cache) {
  884. return cache[key]
  885. } else {
  886. return false
  887. }
  888. }
  889.  
  890. async function storeInHoverCache (metaurl, response, orgMetaUrl) {
  891. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  892. const now = (new Date()).getTime()
  893. const timeout = 2 * 60 * 60 * 1000
  894. for (const prop in cache) {
  895. // Delete cached values, that are older than 2 hours
  896. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  897. delete cache[prop]
  898. }
  899. }
  900.  
  901. const newobj = {}
  902. for (const key in response) {
  903. newobj[key] = response[key]
  904. }
  905. newobj.responseText = '' + response.responseText
  906. newobj.cached = true
  907. if (!('time' in newobj)) {
  908. newobj.time = (new Date()).toJSON()
  909. }
  910.  
  911. cache[metaurl] = newobj
  912. if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect
  913. cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl }
  914. }
  915.  
  916. await GM.setValue('hovercache', JSON.stringify(cache))
  917. }
  918.  
  919. async function isInHoverCache (metaurl) {
  920. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  921. const now = (new Date()).getTime()
  922. const timeout = 2 * 60 * 60 * 1000
  923. for (const prop in cache) {
  924. // Delete cached values, that are older than 2 hours
  925. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  926. delete cache[prop]
  927. }
  928. }
  929.  
  930. function resolveRedirects (cacheEntry) {
  931. if (cacheEntry.redirect) {
  932. const newkey = cacheEntry.redirect
  933. if (newkey in cache) {
  934. const value = cache[newkey]
  935. delete cache[newkey]
  936. return resolveRedirects(value)
  937. }
  938. } else {
  939. return cacheEntry
  940. }
  941. return false
  942. }
  943.  
  944. if (metaurl in cache) {
  945. const value = cache[metaurl]
  946. delete cache[metaurl]
  947. return resolveRedirects(value)
  948. } else {
  949. return false
  950. }
  951. }
  952.  
  953. async function loadHoverInfo () {
  954. const cacheResponse = await isInHoverCache(current.metaurl)
  955. if (cacheResponse !== false) {
  956. console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`)
  957. if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) {
  958. return await handleJSONredirect(cacheResponse)
  959. }
  960. return cacheResponse
  961. }
  962. const requestURL = baseURLdatabase
  963. const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl)
  964.  
  965. let response = await asyncRequest({
  966. method: 'POST',
  967. url: requestURL,
  968. data: requestParams,
  969. headers: {
  970. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  971. }
  972. }).catch(function (response) {
  973. console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status)
  974. })
  975.  
  976. if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) {
  977. response = await handleJSONredirect(response)
  978. }
  979.  
  980. if (response.status >= 500) {
  981. // Metacritic server error, try again after 2 seconds
  982. console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status)
  983. await delay(2000)
  984. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  985. console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status)
  986. })
  987. if (response.status > 300) {
  988. console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status)
  989. } else {
  990. const newobj = {}
  991. for (const key in response) {
  992. newobj[key] = response[key]
  993. }
  994. newobj.responseText = extractHoverFromFullPage(response)
  995. response = newobj
  996. }
  997. }
  998.  
  999. if (response.responseText && response.responseText.indexOf('<title>500 Page') !== -1) {
  1000. // Hover info not available for this url, try again with GET
  1001. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  1002. console.warn('ShowMetacriticRatings: Error 03\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1003. })
  1004.  
  1005. const newobj = {}
  1006. for (const key in response) {
  1007. newobj[key] = response[key]
  1008. }
  1009. newobj.responseText = extractHoverFromFullPage(response)
  1010. response = newobj
  1011. }
  1012.  
  1013. if (!('time' in response)) {
  1014. response.time = (new Date()).toJSON()
  1015. }
  1016. if (response.status === 200 && response.responseText) {
  1017. return response
  1018. } else {
  1019. const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status)
  1020. error.status = response.status
  1021. error.responseText = response.responseText
  1022. throw error
  1023. }
  1024. }
  1025.  
  1026. const current = {
  1027. metaurl: false,
  1028. docurl: false,
  1029. type: false,
  1030. data: [], // Array of raw search keys
  1031. searchTerm: false,
  1032. product: null,
  1033. broadenCounter: 0
  1034. }
  1035.  
  1036. async function loadMetacriticUrl (fromSearch) {
  1037. if (!current.metaurl) {
  1038. alert('ShowMetacriticRatings: Error 04')
  1039. return
  1040. }
  1041. const orgMetaUrl = current.metaurl
  1042. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1043. waitForHotkeysMETA()
  1044. return
  1045. }
  1046.  
  1047. if (await isTemporaryBlacklisted(current.metaurl)) {
  1048. console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`)
  1049. waitForHotkeysMETA()
  1050. return
  1051. }
  1052.  
  1053. const response = await loadHoverInfo().catch(async function (response) {
  1054. if (response instanceof Error || (response && response.stack && response.message)) {
  1055. if (!fromSearch && ('status' in response && response.status === 404)) {
  1056. // No results
  1057. let broadenFct = broadenSearch // global broadenSearch function is the default
  1058. if ('broaden' in current.product) {
  1059. // try product 'broaden'-function if it is defined
  1060. broadenFct = current.product.broaden
  1061. }
  1062. const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1063. if (newData !== current.data) {
  1064. current.data = newData
  1065. metacritic[current.type](current.docurl, current.product, ...newData)
  1066. } else if (newData === current.data) {
  1067. // Same data as before, try once again to broaden
  1068. const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1069. if (newData2 !== current.data) {
  1070. current.data = newData2
  1071. metacritic[current.type](current.docurl, current.product, ...newData2)
  1072. } else {
  1073. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps')
  1074. }
  1075. } else {
  1076. console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData)
  1077. }
  1078. } else {
  1079. console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response)
  1080. }
  1081. }
  1082.  
  1083. if (fromSearch) {
  1084. startSearch()
  1085. }
  1086. })
  1087.  
  1088. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1089. waitForHotkeysMETA()
  1090. return
  1091. }
  1092.  
  1093. if (typeof response !== 'undefined') {
  1094. showHoverInfo(response, orgMetaUrl)
  1095. } else {
  1096. waitForHotkeysMETA()
  1097. }
  1098. }
  1099.  
  1100. async function startSearch () {
  1101. waitForHotkeysMETA()
  1102.  
  1103. const cache = JSON.parse(await GM.getValue('autosearchcache', '{}'))
  1104. const now = (new Date()).getTime()
  1105. const timeout = 2 * 60 * 60 * 1000
  1106. for (const prop in cache) {
  1107. // Delete cached values, that are older than 2 hours
  1108. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1109. delete cache[prop]
  1110. }
  1111. }
  1112.  
  1113. if (current.type === 'music') {
  1114. current.searchTerm = current.data[0]
  1115. } else {
  1116. current.searchTerm = current.data.join(' ')
  1117. }
  1118. let response
  1119. if (current.searchTerm in cache) {
  1120. response = cache[current.searchTerm]
  1121. } else {
  1122. response = await asyncRequest({
  1123. method: 'POST',
  1124. url: baseURLautosearch,
  1125. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1126. headers: {
  1127. Referer: current.metaurl,
  1128. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1129. // Host: 'www.metacritic.com',
  1130. 'User-Agent': 'MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0',
  1131. 'X-Requested-With': 'XMLHttpRequest'
  1132. }
  1133. })
  1134. response = {
  1135. time: (new Date()).toJSON(),
  1136. json: JSON.parse(response.responseText)
  1137. }
  1138. cache[current.searchTerm] = response
  1139. await GM.setValue('autosearchcache', JSON.stringify(cache))
  1140. }
  1141.  
  1142. if (!response || !('json' in response)) {
  1143. alert('ShowMetacriticRatings: Error 05')
  1144. }
  1145. const data = response.json
  1146. let multiple = false
  1147. if (data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  1148. // Remove data with wrong type
  1149. data.autoComplete = data.autoComplete.results
  1150.  
  1151. const newdata = []
  1152. data.autoComplete.forEach(function (result) {
  1153. if (metacritic2searchType(result.refType) === current.type) {
  1154. newdata.push(result)
  1155. }
  1156. })
  1157. data.autoComplete = newdata
  1158. if (data.autoComplete.length === 0) {
  1159. // No results
  1160. console.debug('ShowMetacriticRatings: No results (after filtering by type) for searchTerm=' + current.searchTerm)
  1161. } else if (data.autoComplete.length === 1) {
  1162. // One result, let's show it
  1163. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(data.autoComplete[0].url))) {
  1164. current.metaurl = absoluteMetaURL(data.autoComplete[0].url)
  1165. loadMetacriticUrl(true)
  1166. return
  1167. }
  1168. } else {
  1169. // More than one result
  1170. multiple = true
  1171. console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm)
  1172. const exactMatches = []
  1173. data.autoComplete.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title
  1174. if (current.searchTerm === result.name) {
  1175. exactMatches.push(result)
  1176. }
  1177. })
  1178. if (exactMatches.length === 1) {
  1179. // Only one exact match, let's show it
  1180. console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm)
  1181. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(exactMatches[0].url))) {
  1182. current.metaurl = absoluteMetaURL(exactMatches[0].url)
  1183. loadMetacriticUrl(true)
  1184. return
  1185. }
  1186. }
  1187. }
  1188. } else {
  1189. console.debug('ShowMetacriticRatings: No results (at all) for searchTerm=' + current.searchTerm)
  1190. }
  1191. // HERE: multiple results or no result. The user may type "meta" now
  1192. if (multiple) {
  1193. balloonAlert('Multiple metacritic results. Type &#34;meta&#34; for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5 }, () => openSearchBox(true))
  1194. }
  1195. }
  1196.  
  1197. function openSearchBox (search) {
  1198. let query
  1199. if (current.type === 'music') {
  1200. query = current.data[0]
  1201. } else {
  1202. query = current.data.join(' ')
  1203. }
  1204. $('#mcdiv123').remove()
  1205. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1206. div.css({
  1207. position: 'fixed',
  1208. bottom: 0,
  1209. left: 0,
  1210. minWidth: 300,
  1211. maxHeight: '80%',
  1212. maxWidth: 640,
  1213. overflow: 'auto',
  1214. backgroundColor: '#fff',
  1215. border: '2px solid #bbb',
  1216. borderRadius: ' 6px',
  1217. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1218. color: '#000',
  1219. padding: ' 3px',
  1220. zIndex: '2147483601'
  1221. })
  1222. $('<input type="text" size="60" id="mcisearchquery" style="background:white;color:black;">').appendTo(div).focus().val(query).on('keypress', function (e) {
  1223. const code = e.keyCode || e.which
  1224. if (code === 13) { // Enter key
  1225. searchBoxSearch(e, $('#mcisearchquery').val())
  1226. }
  1227. })
  1228. $('<button id="mcisearchbutton" style="background:silver;color:black;">').text('Search').appendTo(div).click((ev) => searchBoxSearch(ev, $('#mcisearchquery').val()))
  1229. }
  1230. async function searchBoxSearch (ev, query) {
  1231. if (!query) { // Use values from search form
  1232. query = current.searchTerm
  1233. }
  1234.  
  1235. const type = searchType2metacritic(current.type)
  1236.  
  1237. const style = document.createElement('style')
  1238. style.type = 'text/css'
  1239. style.innerHTML = CSS
  1240. document.head.appendChild(style)
  1241.  
  1242. const div = $('#mcdiv123')
  1243. const loader = $('<div style="width:20px; height:20px;display:inline-block" class="grespinner"></div>').appendTo($('#mcisearchbutton'))
  1244.  
  1245. const url = baseURLsearch.replace('{type}', encodeURIComponent(type)).replace('{query}', encodeURIComponent(query))
  1246.  
  1247. const response = await asyncRequest({
  1248. url: url,
  1249. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1250. headers: {
  1251. Referer: url,
  1252. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1253. // Host: 'www.metacritic.com',
  1254. 'User-Agent': 'MetacriticUserscript ' + navigator.userAgent
  1255. }
  1256. }).catch(function (response) {
  1257. alert('Search failed!\n' + response.finalUrl + '\nStatus: ' + response.status + '\n' + response.responseText ? response.responseText.substring(0, 500) : 'Empty response')
  1258. })
  1259.  
  1260. const results = []
  1261. if (!~response.responseText.indexOf('No search results found.')) {
  1262. const d = $('<html>').html(response.responseText)
  1263. d.find('ul.search_results.module .result').each(function () {
  1264. results.push(this.innerHTML)
  1265. })
  1266. }
  1267.  
  1268. if (results && results.length > 0) {
  1269. // Show results
  1270. loader.remove()
  1271.  
  1272. const accept = function (ev) {
  1273. const parentDiv = $(this.parentNode)
  1274. const a = parentDiv.find("a[href*='metacritic.com']")
  1275. const metaurl = a.attr('href')
  1276. const docurl = document.location.href
  1277.  
  1278. const resultDivParent = parentDiv.parent()
  1279. resultDivParent.html('')
  1280. resultDivParent.append(loader)
  1281.  
  1282. removeFromBlacklist(docurl, metaurl).then(function () {
  1283. addToMap(docurl, metaurl).then(function () {
  1284. current.metaurl = metaurl
  1285. loadMetacriticUrl().then(() => loader.remove())
  1286. })
  1287. })
  1288. }
  1289. const denyAll = function (ev) {
  1290. const docurl = document.location.href
  1291. $('#mcdiv123searchresults').find("div.result a[href*='metacritic.com']").each(function () {
  1292. addToBlacklist(docurl, this.href)
  1293. })
  1294. }
  1295.  
  1296. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').css('max-width', '95%').appendTo(div)
  1297. results.forEach(function (html) {
  1298. const singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html) + '<div style="clear:left"></div>').appendTo(resultdiv)
  1299. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept)
  1300. })
  1301. resultdiv.find('.metascore_w.album').removeClass('album') // Remove some classes
  1302. resultdiv.find('.must-see').remove() // Remove some elements
  1303.  
  1304. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1305. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1306. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1307. document.body.removeChild(this.parentNode.parentNode)
  1308. })
  1309. $('<span title="Assist us: None of the above is the correct item!" style="cursor:pointer; float:right; color:crimson; font-size: 11px;">&cross;</span>').appendTo(sub).click(function () { if (confirm('None of the above is the correct item\nConfirm?')) denyAll() })
  1310. } else {
  1311. // No results
  1312. loader.remove()
  1313. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1314. resultdiv.html('No search results.')
  1315.  
  1316. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1317. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1318. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1319. document.body.removeChild(this.parentNode.parentNode)
  1320. })
  1321. }
  1322. }
  1323.  
  1324. function showHoverInfo (response, orgMetaUrl) {
  1325. const html = fixMetacriticURLs(response.responseText)
  1326. const time = new Date(response.time)
  1327. const url = response.finalUrl
  1328.  
  1329. $('#mcdiv123').remove()
  1330. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1331. div.css({
  1332. position: 'fixed',
  1333. bottom: 0,
  1334. left: 0,
  1335. minWidth: 300,
  1336. backgroundColor: '#fff',
  1337. border: '2px solid #bbb',
  1338. borderRadius: ' 6px',
  1339. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1340. color: '#000',
  1341. padding: ' 3px',
  1342. zIndex: '2147483601'
  1343. })
  1344.  
  1345. // Functions for communication between page and iframe
  1346. // Mozilla can access parent.document
  1347. // Chrome can use postMessage()
  1348. let frameStatus = false // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  1349. function loadExternalImage (url, myframe) {
  1350. // Load external image, bypass CSP
  1351. GM.xmlHttpRequest({
  1352. method: 'GET',
  1353. url: url,
  1354. responseType: 'arraybuffer',
  1355. onload: function (response) {
  1356. myframe.contentWindow.postMessage({
  1357. mcimessage_imgLoaded: true,
  1358. mcimessage_imgData: response.response,
  1359. mcimessage_imgOrgSrc: url
  1360. }, '*')
  1361. }
  1362. })
  1363. }
  1364. const functions = {
  1365. parent: function () {
  1366. const f = parent.document.getElementById('mciframe123')
  1367. let lastdiff = -200000
  1368. window.addEventListener('message', function (e) {
  1369. if (typeof e.data !== 'object') {
  1370. return
  1371. } else if ('mcimessage0' in e.data) {
  1372. frameStatus = true // Frame content was loaded successfully
  1373. } else if ('mcimessage1' in e.data) {
  1374. f.style.width = parseInt(f.style.width) + 10 + 'px'
  1375. if (e.data.heightdiff === lastdiff) {
  1376. f.style.height = parseInt(f.style.height) + 5 + 'px'
  1377. }
  1378. lastdiff = e.data.heightdiff
  1379. } else if ('mcimessage2' in e.data) {
  1380. f.style.height = parseInt(f.style.height) + 15 + 'px'
  1381. f.style.width = '400px'
  1382. } else if ('mcimessage_loadImg' in e.data) {
  1383. loadExternalImage(e.data.mcimessage_imgUrl, f)
  1384. } else {
  1385. return
  1386. }
  1387. if (f.contentWindow != null) {
  1388. f.contentWindow.postMessage({
  1389. mcimessage3: true,
  1390. mciframe123_clientHeight: f.clientHeight,
  1391. mciframe123_clientWidth: f.clientWidth
  1392. }, '*')
  1393. }
  1394. })
  1395. },
  1396. frame: function () {
  1397. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1398.  
  1399. let i = 0
  1400. window.addEventListener('message', function (e) {
  1401. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1402. // Load external image
  1403. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1404. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1405. const urlCreator = window.URL || window.webkitURL
  1406. const imageUrl = urlCreator.createObjectURL(blob)
  1407. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1408. img.src = imageUrl
  1409. }
  1410.  
  1411. if (!('mcimessage3' in e.data)) return
  1412.  
  1413. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1414. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1415. i++
  1416. }
  1417. if (i >= 100) {
  1418. parent.postMessage({ mcimessage2: 1 }, '*')
  1419. i = 0
  1420. }
  1421. })
  1422. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1423. }
  1424.  
  1425. }
  1426.  
  1427. const css = `#hover_div .clr { clear: both}
  1428. #hover_div .fl{float: left}
  1429. #hover_div { background-color: #fff; color: #666; font-family:Arial,Helvetica,sans-serif; font-size:12px; font-weight:400; font-style:normal;}
  1430. #hover_div .hoverinfo .hover_left { float: left}
  1431. #hover_div .hoverinfo .product_image_wrapper { color: #999; font-size: 6px; font-weight: normal; min-height: 98px; min-width: 98px;}
  1432. #hover_div .hoverinfo .product_image_wrapper a { color: #999; font-size: 6px; font-weight: normal;}
  1433. #hover_div a * { cursor: pointer}
  1434. #hover_div a { color: #09f; font-weight: bold;}
  1435. #hover_div a:link, #hover_div a:visited { text-decoration: none;}
  1436. #hover_div a:hover { text-decoration: underline;}
  1437. #hover_div .hoverinfo .hover_right { float: left; margin-left: 15px; max-width: 395px;}
  1438. #hover_div .hoverinfo .product_title { color: #333; font-family: georgia,serif; font-size: 24px; line-height: 26px; margin-bottom: 10px;}
  1439. #hover_div .hoverinfo .product_title a { color:#333; font-family: georgia,serif; font-size: 24px;}
  1440. #hover_div .hoverinfo .summary_detail.publisher, .hoverinfo .summary_detail.release_data { float: left}
  1441. #hover_div .hoverinfo .summary_detail { font-size: 11px; margin-bottom: 10px;}
  1442. #hover_div .hoverinfo .summary_detail.product_credits a { color: #999; font-weight: normal; }
  1443. #hover_div .hoverinfo .hr { background-color: #ccc; height: 2px; margin: 15px 0 10px;}
  1444. #hover_div .hoverinfo .hover_scores { width: 100%; border-collapse: collapse; border-spacing: 0;}
  1445. #hover_div .hoverinfo .hover_scores td.num { width: 39px}
  1446. #hover_div .hoverinfo .hover_scores td { vertical-align: middle}
  1447. #hover_div caption, #hover_div th, #hover_div td { font-weight: normal; text-align: left;}
  1448. #hover_div .metascore_anchor, #hover_div a.metascore_w { text-decoration: none !important}
  1449. #hover_div span.metascore_w, #hover_div a.metascore_w { display: inline-block; padding:0px;}
  1450. .metascore_w { background-color: transparent; color: #fff !important; font-family: Arial,Helvetica,sans-serif; font-size: 17px; font-style: normal !important; font-weight: bold !important; height: 2em; line-height: 2em; text-align: center; vertical-align: middle; width: 2em;}
  1451. #hover_div .metascore, #hover_div .metascore a, #hover_div .avguserscore, #hover_div .avguserscore a { color: #fff}
  1452. #hover_div .critscore, #hover_div .critscore a, #hover_div .userscore, #hover_div .userscore a { color: #333}
  1453. .score_tbd { background: #eaeaea; color: #333; font-size: 14px;}
  1454. #hover_div .score_tbd a { color: #333}
  1455. .negative, .score_terrible, .score_unfavorable, .carousel_set a.product_terrible:hover, .carousel_set a.product_unfavorable:hover { background-color: #f00}
  1456. .mixed, .neutral, .score_mixed, .carousel_set a.product_mixed:hover { background-color: #fc3; color: #333;}
  1457. #hover_div .score_mixed a { color: #333}
  1458. .positive, .score_favorable, .score_outstanding, .carousel_set a.product_favorable:hover, .carousel_set a.product_outstanding:hover { background-color: #6c3}
  1459. .critscore_terrible, .critscore_unfavorable { border-color: #f00}
  1460. .critscore_mixed { border-color: #fc3}
  1461. .critscore_favorable, .critscore_outstanding { border-color: #6c3}
  1462. .metascore .score_total, .userscore .score_total { display: none; visibility: hidden;}
  1463. .hoverinfo .metascore_label, .hoverinfo .userscore_label { font-size: 12px; font-weight: bold; line-height: 16px; margin-top: 2%;}
  1464. .hoverinfo .metascore_review_count, .hoverinfo .userscore_review_count { font-size: 11px}
  1465. .hoverinfo .hover_scores td { vertical-align: middle}
  1466. .hoverinfo .hover_scores td.num { width: 39px}
  1467. .hoverinfo .hover_scores td.usr.num { padding-left: 20px}
  1468. .metascore_anchor, a.metascore_w { text-decoration: none !important}
  1469. .metascore_w.album { padding-top:0px; !important}
  1470. .metascore_w.user { border-radius: 55%; color: #fff;}
  1471. .metascore_anchor, .metascore_w.album { padding: 0px;!important, padding-top: 0px;!important}
  1472. a.metascore_w { text-decoration: none!important}
  1473. .metascore_anchor:hover { text-decoration: none!important}
  1474. .metascore_w:hover { text-decoration: none!important}
  1475. span.metascore_w, a.metascore_w { display: inline-block}
  1476. .metascore_w.xlarge, .metascore_w.xl { font-size: 42px}
  1477. .metascore_w.large, .metascore_w.lrg { font-size: 25px}
  1478. .m .metascore_w.medium, .m .metascore_w.med { font-size: 19px}
  1479. .metascore_w.med_small { font-size: 14px}
  1480. .metascore_w.small, .metascore_w.sm { font-size: 12px}
  1481. .metascore_w.tiny { height: 1.9em; font-size: 11px; line-height: 1.9em;}
  1482. .metascore_w.user { border-radius: 55%; color: #fff;}
  1483. .metascore_w.user.small, .metascore_w.user.sm { font-size: 11px}
  1484. .metascore_w.tbd, .metascore_w.score_tbd { color: #000!important; background-color: #ccc;}
  1485. .metascore_w.tbd.hide_tbd, .metascore_w.score_tbd.hide_tbd { visibility: hidden}
  1486. .metascore_w.tbd.no_tbd, .metascore_w.score_tbd.no_tbd { display: none}
  1487. .metascore_w.noscore::before, .metascore_w.score_noscore::before { content: '\u2022\u2022\u2022'}
  1488. .metascore_w.noscore, .metascore_w.score_noscore { color: #fff!important; background-color: #ccc;}
  1489. .metascore_w.rip, .metascore_w.score_rip { border-radius: 4px; color: #fff!important; background-color: #999;}
  1490. .metascore_w.negative, .metascore_w.score_terrible, .metascore_w.score_unfavorable { background-color: #f00}
  1491. .metascore_w.mixed, .metascore_w.forty, .metascore_w.game.fifty, .metascore_w.score_mixed { background-color: #fc3}
  1492. .metascore_w.positive, .metascore_w.sixtyone, .metascore_w.game.seventyfive, .metascore_w.score_favorable, .metascore_w.score_outstanding { background-color: #6c3}
  1493. .metascore_w.indiv { height: 1.9em; width: 1.9em; font-size: 15px; line-height: 1.9em;}
  1494. .metascore_w.indiv.large, .metascore_w.indiv.lrg { font-size: 24px}
  1495. .m .metascore_w.indiv.medium, .m .metascore_w.indiv.med { font-size: 16px}
  1496. .metascore_w.indiv.small, .metascore_w.indiv.sm { font-size: 11px}
  1497. .metascore_w.indiv.perfect { padding-right: 1px}
  1498. .hover_esite { display:none; }
  1499. .promo_amazon .esite_btn { margin: 3px 0 0 7px;}
  1500. .esite_amazon { background-color: #fdc354; border: 1px solid #aaa;}
  1501. .esite_label_wrapper { display:none;}
  1502. .esite_btn { border-radius: 4px; color: #222; font-size: 12px; height: 40px; line-height: 40px; width: 120px;}
  1503. .chart{background-color:inherit!important;margin-top:-3px}
  1504. .chart_bg{width:100%;border-top:3px solid rgba(150,150,150,0.3)}
  1505. .chart .bar{width:100%;height:3px}
  1506. .chart .count{font-size:10px}`
  1507.  
  1508. let framesrc = 'data:text/html,'
  1509. framesrc += encodeURIComponent('<!DOCTYPE html>\
  1510. <html lang="en">\
  1511. <head>\
  1512. <meta charset="utf-8">\
  1513. <title>Metacritic info</title>\
  1514. <style>body { margin:0px; padding:0px; background:white; }' + css +
  1515. '\
  1516. </style>\
  1517. <script>\
  1518. const failedImages = {};\
  1519. function detectCSP(img) {\
  1520. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {\
  1521. return true;\
  1522. }\
  1523. return false;\
  1524. }\
  1525. function findCSPerrors() {\
  1526. const imgs = document.querySelectorAll("img");\
  1527. for(let i = 0; i < imgs.length; i++) {\
  1528. if(imgs[i].complete && detectCSP(imgs[i])) {\
  1529. fixCSP(imgs[i]);\
  1530. }\
  1531. }\
  1532. }\
  1533. function fixCSP(img) {\
  1534. console.debug("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");\
  1535. failedImages[img.src] = img;\
  1536. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*"); \
  1537. }\
  1538. function on_load() {\
  1539. (' + functions.frame.toString() + ')();\
  1540. window.setTimeout(findCSPerrors, 500);\
  1541. \
  1542. }\
  1543. </script>\
  1544. </head>\
  1545. <body onload="on_load();">\
  1546. <div style="border:0px solid; display:block; position:relative; border-radius:0px; padding:0px; margin:0px; box-shadow:none;" class="hover_div" id="hover_div">\
  1547. <div class="hover_content">' + html + '</div>\
  1548. </div>\
  1549. </body>\
  1550. </html>')
  1551.  
  1552. const frame = $('<iframe></iframe>').appendTo(div)
  1553. frame.attr('id', 'mciframe123')
  1554. frame.attr('src', framesrc)
  1555. frame.attr('scrolling', 'auto')
  1556. frame.css({
  1557. width: 380,
  1558. height: 150,
  1559. border: 'none'
  1560. })
  1561.  
  1562. window.setTimeout(function () {
  1563. if (!frameStatus) { // Loading frame content failed.
  1564. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1565. console.debug('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1566. $('head').append('<style>' + css + '</style>')
  1567. const noframe = $('<div style="border:0px solid; display:block; position:relative; border-radius:0px; padding:0px; margin:0px; box-shadow:none;" class="hover_div" id="hover_div">\
  1568. <div class="hover_content">' + html + '</div>\
  1569. </div>')
  1570. frame.replaceWith(noframe)
  1571. }
  1572. }, 2000)
  1573.  
  1574. functions.parent()
  1575.  
  1576. const sub = $('<div></div>').appendTo(div)
  1577. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1578. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1579. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px; padding-left:5px;">&#10062;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1580. const metaurl = $(this).data('url')
  1581. addToTemporaryBlacklist(metaurl)
  1582. document.body.removeChild(this.parentNode.parentNode)
  1583. })
  1584.  
  1585. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; float:right; color:green; font-size: 11px;">&check;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1586. const docurl = document.location.href
  1587. const metaurl = $(this).data('url')
  1588. addToMap(docurl, metaurl).then(function (r) {
  1589. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1590. })
  1591. })
  1592. $('<span title="Assist us: This is NOT the correct entry!" style="cursor:pointer; float:right; color:crimson; font-size: 11px;">&cross;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1593. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1594. const docurl = document.location.href
  1595. const metaurl = $(this).data('url')
  1596. addToBlacklist(docurl, metaurl).then(function (r) {
  1597. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1598. })
  1599.  
  1600. openSearchBox(true)
  1601. })
  1602.  
  1603. // Store response in cache:
  1604. if (!('cached' in response)) {
  1605. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  1606. }
  1607. }
  1608.  
  1609. function metacritic_general_product_setup () {
  1610. current.broadenCounter = 0
  1611. }
  1612.  
  1613. const metacritic = {
  1614. mapped: function metacriticMapped (docurl, product, metaurl, type) {
  1615. // url was in the map/whitelist
  1616. current.data = []
  1617. current.docurl = docurl
  1618. current.product = product
  1619. current.metaurl = metaurl
  1620. current.type = type
  1621. current.searchTerm = null
  1622. loadMetacriticUrl()
  1623. },
  1624. music: function metacriticMusic (docurl, product, artistname, albumname) {
  1625. current.data = [albumname.trim(), artistname.trim()]
  1626. artistname = name2metacritic(artistname)
  1627. albumname = albumname.replace('&', ' ')
  1628. albumname = name2metacritic(albumname)
  1629. current.docurl = docurl
  1630. current.product = product
  1631. current.metaurl = baseURLmusic + albumname + '/' + artistname
  1632. current.type = 'music'
  1633. current.searchTerm = albumname + '/' + artistname
  1634. loadMetacriticUrl()
  1635. },
  1636. movie: function metacriticMovie (docurl, product, moviename) {
  1637. current.data = [moviename.trim()]
  1638. moviename = name2metacritic(moviename)
  1639. current.docurl = docurl
  1640. current.product = product
  1641. current.metaurl = baseURLmovie + moviename
  1642. current.type = 'movie'
  1643. current.searchTerm = moviename
  1644. loadMetacriticUrl()
  1645. },
  1646. tv: function metacriticTv (docurl, product, seriesname) {
  1647. current.data = [seriesname.trim()]
  1648. seriesname = name2metacritic(seriesname)
  1649. current.docurl = docurl
  1650. current.product = product
  1651. current.metaurl = baseURLtv + seriesname
  1652. current.type = 'tv'
  1653. current.searchTerm = seriesname
  1654. loadMetacriticUrl()
  1655. },
  1656. pcgame: function metacriticPcgame (docurl, product, gamename) {
  1657. current.data = [gamename.trim()]
  1658. gamename = name2metacritic(gamename)
  1659. current.docurl = docurl
  1660. current.product = product
  1661. current.metaurl = baseURLpcgame + gamename
  1662. current.type = 'pcgame'
  1663. current.searchTerm = gamename
  1664. loadMetacriticUrl()
  1665. },
  1666. ps4game: function metacriticPs4game (docurl, product, gamename) {
  1667. current.data = [gamename.trim()]
  1668. gamename = name2metacritic(gamename)
  1669. current.docurl = docurl
  1670. current.product = product
  1671. current.metaurl = baseURLps4 + gamename
  1672. current.type = 'ps4game'
  1673. current.searchTerm = gamename
  1674. loadMetacriticUrl()
  1675. },
  1676. xonegame: function metacriticXonegame (docurl, product, gamename) {
  1677. current.data = [gamename.trim()]
  1678. gamename = name2metacritic(gamename)
  1679. current.docurl = docurl
  1680. current.product = product
  1681. current.metaurl = baseURLxone + gamename
  1682. current.type = 'xonegame'
  1683. current.searchTerm = gamename
  1684. loadMetacriticUrl()
  1685. }
  1686. }
  1687.  
  1688. const Always = () => true
  1689. const sites = {
  1690. bandcamp: {
  1691. host: ['bandcamp.com'],
  1692. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  1693. products: [{
  1694. condition: Always,
  1695. type: 'music',
  1696. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1697. }]
  1698. },
  1699. itunes: {
  1700. host: ['itunes.apple.com'],
  1701. condition: Always,
  1702. products: [{
  1703. condition: () => ~document.location.href.indexOf('/movie/'),
  1704. type: 'movie',
  1705. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1706. },
  1707. {
  1708. condition: () => ~document.location.href.indexOf('/tv-season/'),
  1709. type: 'tv',
  1710. data: function () {
  1711. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1712. if (~name.indexOf(', Season')) {
  1713. name = name.split(', Season')[0]
  1714. }
  1715. return name
  1716. }
  1717. },
  1718. {
  1719. condition: () => ~document.location.href.indexOf('/album/'),
  1720. type: 'music',
  1721. data: function () {
  1722. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1723. const album = ld[0]
  1724. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1725. return [artist, album]
  1726. }
  1727. }]
  1728. },
  1729. 'music.apple': {
  1730. host: ['music.apple.com'],
  1731. condition: Always,
  1732. products: [{
  1733. condition: () => ~document.location.href.indexOf('/album/') && parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum')).length > 1,
  1734. type: 'music',
  1735. data: function () {
  1736. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1737. const album = ld[0]
  1738. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1739. return [artist, album]
  1740. }
  1741. }]
  1742. },
  1743. googleplay: {
  1744. host: ['play.google.com'],
  1745. condition: Always,
  1746. products: [
  1747. {
  1748. condition: () => ~document.location.href.indexOf('/album/'),
  1749. type: 'music',
  1750. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  1751. },
  1752. {
  1753. condition: () => ~document.location.href.indexOf('/movies/details/'),
  1754. type: 'movie',
  1755. data: () => document.querySelector('*[itemprop=name]').textContent
  1756. }
  1757. ]
  1758. },
  1759. imdb: {
  1760. host: ['imdb.com'],
  1761. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  1762. products: [
  1763. {
  1764. condition: function () {
  1765. const e = document.querySelector("meta[property='og:type']")
  1766. if (e && e.content === 'video.movie') {
  1767. return true
  1768. } else if (document.querySelector('[data-testid="hero-title-block__title"]') && !document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1769. // New design 2020-12
  1770. return true
  1771. }
  1772. return false
  1773. },
  1774. type: 'movie',
  1775. data: function () {
  1776. if (document.querySelector('[data-testid="hero-title-block__title"]')) {
  1777. // New design 2020-12
  1778. return document.querySelector('[data-testid="hero-title-block__title"]').textContent
  1779. } else if (document.querySelector("meta[property='og:title']") && document.querySelector("meta[property='og:title']").content) { // English/Worldwide title, this is the prefered title for search
  1780. let name = document.querySelector("meta[property='og:title']").content.trim()
  1781. if (name.indexOf('- IMDb') !== -1) {
  1782. name = name.replace('- IMDb', '').trim()
  1783. }
  1784. name = name.replace(/\(\d{4}\)/, '').trim()
  1785. return name
  1786. } else if (document.querySelector('.originalTitle') && document.querySelector('.title_wrapper h1')) { // Use English title 2018
  1787. return document.querySelector('.title_wrapper h1').firstChild.textContent.trim()
  1788. } else if (document.querySelector('script[type="application/ld+json"]')) { // Use original language title
  1789. return parseLDJSON('name')
  1790. } else if (document.querySelector('h1[itemprop=name]')) { // Movie homepage (New design 2015-12)
  1791. return document.querySelector('h1[itemprop=name]').firstChild.textContent.trim()
  1792. } else if (document.querySelector('*[itemprop=name] a') && document.querySelector('*[itemprop=name] a').firstChild.textContent) { // Subpage of a move
  1793. return document.querySelector('*[itemprop=name] a').firstChild.textContent.trim()
  1794. } else if (document.querySelector('.title-extra[itemprop=name]')) { // Movie homepage: sub-/alternative-/original title
  1795. return document.querySelector('.title-extra[itemprop=name]').firstChild.textContent.replace(/"/g, '').trim()
  1796. } else if (document.querySelector('*[itemprop=name]')) { // Movie homepage (old design)
  1797. return document.querySelector('*[itemprop=name]').firstChild.textContent.trim()
  1798. } else {
  1799. return document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1]
  1800. }
  1801. }
  1802. },
  1803. {
  1804. condition: function () {
  1805. const e = document.querySelector("meta[property='og:type']")
  1806. if (e && e.content === 'video.tv_show') {
  1807. return true
  1808. } else if (document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1809. // New design 2020-12
  1810. return true
  1811. }
  1812. return false
  1813. },
  1814. type: 'tv',
  1815. data: function () {
  1816. if (document.querySelector('[data-testid="hero-title-block__title"]')) {
  1817. // New design 2020-12
  1818. return document.querySelector('[data-testid="hero-title-block__title"]').textContent
  1819. } else if (document.querySelector('*[itemprop=name]')) {
  1820. return document.querySelector('*[itemprop=name]').textContent
  1821. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1822. const jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText)
  1823. return jsonld.name
  1824. } else {
  1825. return document.title.match(/(.+?)\s+\(TV/)[1]
  1826. }
  1827. }
  1828. }
  1829. ]
  1830. },
  1831. steam: {
  1832. host: ['store.steampowered.com'],
  1833. condition: () => document.querySelector('*[itemprop=name]'),
  1834. products: [{
  1835. condition: Always,
  1836. type: 'pcgame',
  1837. data: () => document.querySelector('*[itemprop=name]').textContent
  1838. }]
  1839. },
  1840. rottentomatoes: {
  1841. host: ['rottentomatoes.com'],
  1842. condition: Always,
  1843. products: [{
  1844. condition: () => document.location.pathname.startsWith('/m/'),
  1845. type: 'movie',
  1846. data: () => document.querySelector('h1').firstChild.textContent
  1847. },
  1848. {
  1849. condition: () => document.location.pathname.startsWith('/tv/'),
  1850. type: 'tv',
  1851. data: () => unsafeWindow.BK.TvSeriesTitle
  1852. }
  1853. ]
  1854. },
  1855. serienjunkies: {
  1856. host: ['www.serienjunkies.de'],
  1857. condition: Always,
  1858. products: [{
  1859. condition: () => Always,
  1860. type: 'tv',
  1861. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1862. }]
  1863. },
  1864. gamespot: {
  1865. host: ['gamespot.com'],
  1866. condition: () => document.querySelector('[itemprop=device]'),
  1867. products: [
  1868. {
  1869. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  1870. type: 'pcgame',
  1871. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1872. },
  1873. {
  1874. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  1875. type: 'ps4game',
  1876. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1877. },
  1878. {
  1879. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  1880. type: 'xonegame',
  1881. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1882. }
  1883. ]
  1884. },
  1885. amazon: {
  1886. host: ['amazon.'],
  1887. condition: Always,
  1888. products: [
  1889. {
  1890. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  1891. type: 'music',
  1892. data: function () {
  1893. const artist = document.querySelector('.artistLink').textContent.trim()
  1894. let title = document.querySelector('.viewTitle').textContent.trim()
  1895. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1896. if (artist && title) {
  1897. return [artist, title]
  1898. }
  1899. return false
  1900. }
  1901. },
  1902. {
  1903. condition: function () { // "Normal amazon" page
  1904. try {
  1905. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  1906. return true
  1907. }
  1908. } catch (e) {}
  1909. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  1910. return music.some(function (s) {
  1911. if (~document.title.indexOf(s)) {
  1912. return true
  1913. } else {
  1914. return false
  1915. }
  1916. })
  1917. },
  1918. type: 'music',
  1919. data: function () {
  1920. let artist = false
  1921. let title = false
  1922. if (document.querySelector('#ProductInfoArtistLink')) {
  1923. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  1924. } else if (document.querySelector('#bylineInfo .author>*')) {
  1925. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  1926. }
  1927.  
  1928. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  1929. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  1930. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1931. } else if (document.querySelector('#productTitle')) {
  1932. title = document.querySelector('#productTitle').textContent.trim()
  1933. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1934. }
  1935. return [artist, title]
  1936. }
  1937. },
  1938. {
  1939. condition: () => (document.querySelector('[data-automation-id=title]') && (
  1940. document.getElementsByClassName('av-season-single').length ||
  1941. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1942. document.getElementById('tab-selector-episodes') ||
  1943. document.getElementById('av-droplist-av-atf-season-selector')
  1944. )),
  1945. type: 'tv',
  1946. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1947. },
  1948. {
  1949. condition: () => ((
  1950. document.getElementsByClassName('av-season-single').length ||
  1951. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1952. document.getElementById('tab-selector-episodes') ||
  1953. document.getElementById('av-droplist-av-atf-season-selector')
  1954. ) && Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).some((x) => x != null)),
  1955. type: 'tv',
  1956. data: () => Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).filter((x) => x != null)[0][1]
  1957. },
  1958. {
  1959. condition: () => document.querySelector('[data-automation-id=title]'),
  1960. type: 'movie',
  1961. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1962. }
  1963. ]
  1964. },
  1965. BoxOfficeMojo: {
  1966. host: ['boxofficemojo.com'],
  1967. condition: () => Always,
  1968. products: [
  1969. {
  1970. condition: () => document.location.pathname.startsWith('/release/'),
  1971. type: 'movie',
  1972. data: () => document.querySelector('meta[name=title]').content
  1973. },
  1974. {
  1975. // Old page design
  1976. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  1977. type: 'movie',
  1978. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.textContent
  1979. }]
  1980. },
  1981. AllMovie: {
  1982. host: ['allmovie.com'],
  1983. condition: () => document.querySelector('h2.movie-title'),
  1984. products: [{
  1985. condition: () => document.querySelector('h2.movie-title'),
  1986. type: 'movie',
  1987. data: () => document.querySelector('h2.movie-title').firstChild.textContent.trim()
  1988. }]
  1989. },
  1990. 'en.wikipedia': {
  1991. host: ['en.wikipedia.org'],
  1992. condition: Always,
  1993. products: [{
  1994. condition: function () {
  1995. if (!document.querySelector('.infobox .summary')) {
  1996. return false
  1997. }
  1998. const r = /\d\d\d\d films/
  1999. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2000. },
  2001. type: 'movie',
  2002. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2003. },
  2004. {
  2005. condition: function () {
  2006. if (!document.querySelector('.infobox .summary')) {
  2007. return false
  2008. }
  2009. const r = /television series/
  2010. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2011. },
  2012. type: 'tv',
  2013. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2014. }]
  2015. },
  2016. fandango: {
  2017. host: ['fandango.com'],
  2018. condition: () => document.querySelector("meta[property='og:title']"),
  2019. products: [{
  2020. condition: Always,
  2021. type: 'movie',
  2022. data: () => document.querySelector("meta[property='og:title']").content.match(/(.+?)\s+\(\d{4}\)/)[1].trim()
  2023. }]
  2024. },
  2025. flixster: {
  2026. host: ['www.flixster.com'],
  2027. condition: () => Always,
  2028. products: [{
  2029. condition: () => parseLDJSON('@type') === 'Movie',
  2030. type: 'movie',
  2031. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2032. }]
  2033. },
  2034. themoviedb: {
  2035. host: ['themoviedb.org'],
  2036. condition: () => document.querySelector("meta[property='og:type']"),
  2037. products: [{
  2038. condition: () => document.querySelector("meta[property='og:type']").content === 'movie',
  2039. type: 'movie',
  2040. data: () => document.querySelector("meta[property='og:title']").content
  2041. },
  2042. {
  2043. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' || document.querySelector("meta[property='og:type']").content === 'tv_series',
  2044. type: 'tv',
  2045. data: () => document.querySelector("meta[property='og:title']").content
  2046. }]
  2047. },
  2048. letterboxd: {
  2049. host: ['letterboxd.com'],
  2050. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  2051. products: [{
  2052. condition: Always,
  2053. type: 'movie',
  2054. data: () => unsafeWindow.filmData.name
  2055. }]
  2056. },
  2057. TVmaze: {
  2058. host: ['tvmaze.com'],
  2059. condition: () => document.querySelector('h1'),
  2060. products: [{
  2061. condition: Always,
  2062. type: 'tv',
  2063. data: () => document.querySelector('h1').firstChild.textContent
  2064. }]
  2065. },
  2066. TVGuide: {
  2067. host: ['tvguide.com'],
  2068. condition: Always,
  2069. products: [{
  2070. condition: () => document.location.pathname.startsWith('/tvshows/'),
  2071. type: 'tv',
  2072. data: function () {
  2073. if (document.querySelector('meta[itemprop=name]')) {
  2074. return document.querySelector('meta[itemprop=name]').content
  2075. } else {
  2076. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  2077. }
  2078. }
  2079. }]
  2080. },
  2081. followshows: {
  2082. host: ['followshows.com'],
  2083. condition: Always,
  2084. products: [{
  2085. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  2086. type: 'tv',
  2087. data: () => document.querySelector("meta[property='og:title']").content
  2088. }]
  2089. },
  2090. TheTVDB: {
  2091. host: ['thetvdb.com'],
  2092. condition: Always,
  2093. products: [{
  2094. condition: () => document.location.pathname.startsWith('/series/'),
  2095. type: 'tv',
  2096. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2097. },
  2098. {
  2099. condition: () => document.location.pathname.startsWith('/movies/'),
  2100. type: 'movie',
  2101. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2102. }]
  2103. },
  2104. ConsequenceOfSound: {
  2105. host: ['consequence.net', 'consequenceofsound.net'],
  2106. condition: () => document.querySelector('#main-content .review-summary'),
  2107. products: [
  2108. {
  2109. condition: () => document.querySelector('meta[name="cXenseParse:cns-artist-names"]') && document.querySelector('em'),
  2110. type: 'music',
  2111. data: function () {
  2112. window.setInterval(function () {
  2113. if (document.getElementById('ot-sdk-btn-floating')) {
  2114. document.getElementById('ot-sdk-btn-floating').remove()
  2115. }
  2116. }, 5000)
  2117. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2118. const arr = Array.from(document.querySelectorAll('em')).map((em) => em.textContent.trim())
  2119. const counts = {}
  2120. for (const num of arr) {
  2121. counts[num] = counts[num] ? counts[num] + 1 : 1
  2122. }
  2123. const max = Math.max(...Object.values(counts))
  2124. const maxIndex = Object.values(counts).indexOf(max)
  2125. const title = Object.keys(counts)[maxIndex]
  2126. return [artist, title]
  2127. }
  2128. },
  2129. {
  2130. condition: () => document.title.match(/'(.*?)'\s*Album/i) && document.querySelector('meta[name="cXenseParse:cns-artist-names"]'),
  2131. type: 'music',
  2132. data: function () {
  2133. window.setInterval(function () {
  2134. if (document.getElementById('ot-sdk-btn-floating')) {
  2135. document.getElementById('ot-sdk-btn-floating').remove()
  2136. }
  2137. }, 5000)
  2138. const title = document.title.match(/'(.*?)'\s*Album/i)[1]
  2139. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2140. return [artist, title]
  2141. }
  2142. },
  2143. {
  2144. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  2145. type: 'music',
  2146. data: function () {
  2147. window.setInterval(function () {
  2148. if (document.getElementById('ot-sdk-btn-floating')) {
  2149. document.getElementById('ot-sdk-btn-floating').remove()
  2150. }
  2151. }, 5000)
  2152. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  2153. return [m[1], m[2]]
  2154. }
  2155. },
  2156. {
  2157. condition: () => document.location.pathname.indexOf('/album-review') !== -1 && document.querySelector('a.tag[href*="/artist/"'),
  2158. type: 'music',
  2159. data: function () {
  2160. window.setInterval(function () {
  2161. if (document.getElementById('ot-sdk-btn-floating')) {
  2162. document.getElementById('ot-sdk-btn-floating').remove()
  2163. }
  2164. }, 5000)
  2165. const artistAndTitleWithDash = document.location.pathname.match(/album-review-([\w-]+)/)[1]
  2166. const artistWithDash = document.querySelector('a.tag[href*="/artist/"').pathname.match(/artist\/([\w-]+)/)[1]
  2167. const titleWithDash = artistAndTitleWithDash.replace(artistWithDash, '')
  2168. const title = titleWithDash.replace('-', ' ').trim()
  2169. const artist = artistWithDash.replace('-', ' ').trim()
  2170. return [artist, title]
  2171. }
  2172. }]
  2173. },
  2174. Pitchfork: {
  2175. host: ['pitchfork.com'],
  2176. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  2177. products: [{
  2178. condition: () => document.querySelector('.single-album-tombstone'),
  2179. type: 'music',
  2180. data: function () {
  2181. let artist
  2182. let album
  2183. if (document.querySelector('.single-album-tombstone .artists')) {
  2184. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  2185. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  2186. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  2187. }
  2188. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  2189. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  2190. } else if (document.querySelector('.single-album-tombstone h1')) {
  2191. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  2192. }
  2193.  
  2194. return [artist, album]
  2195. }
  2196. }]
  2197. },
  2198. 'Last.fm': {
  2199. host: ['last.fm'],
  2200. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2201. products: [{
  2202. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2203. type: 'music',
  2204. data: function () {
  2205. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2206. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2207. return [artist, album]
  2208. }
  2209. }]
  2210. },
  2211. TVNfo: {
  2212. host: ['tvnfo.com'],
  2213. condition: () => document.querySelector('.ui.breadcrumb a[href*="/series"]'),
  2214. products: [{
  2215. condition: Always,
  2216. type: 'tv',
  2217. data: function () {
  2218. const years = document.querySelector('#title h1 .years').textContent.trim()
  2219. const title = document.querySelector('#title h1').textContent.replace(years, '').trim()
  2220. return title
  2221. }
  2222. }]
  2223. },
  2224. rateyourmusic: {
  2225. host: ['rateyourmusic.com'],
  2226. condition: () => document.querySelector("meta[property='og:type']"),
  2227. products: [{
  2228. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2229. type: 'music',
  2230. data: function () {
  2231. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2232. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2233. return [artist, album]
  2234. }
  2235. }]
  2236. },
  2237. spotify: {
  2238. host: ['open.spotify.com'],
  2239. condition: Always,
  2240. products: [{
  2241. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector('.Root__main-view h1'),
  2242. type: 'music',
  2243. data: function () {
  2244. const album = document.querySelector('.Root__main-view h1').textContent.trim()
  2245. let artist = []
  2246. document.querySelector('.Root__main-view h1').parentNode.parentNode.parentNode.querySelectorAll('a[href*="/artist/"]').forEach(function (a) {
  2247. artist.push(a.textContent.trim())
  2248. })
  2249. artist = artist.join(' ')
  2250. return [artist, album]
  2251. }
  2252. }]
  2253. },
  2254. nme: {
  2255. host: ['nme.com'],
  2256. condition: () => document.location.pathname.startsWith('/reviews/'),
  2257. products: [
  2258. {
  2259. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/film-reviews"]'),
  2260. type: 'movie',
  2261. data: function () {
  2262. try {
  2263. return document.title.match(/[‘'](.+?)[’']/)[1]
  2264. } catch (e) {
  2265. try {
  2266. return document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2267. } catch (e) {
  2268. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2269. }
  2270. }
  2271. }
  2272. },
  2273. {
  2274. condition: () => document.querySelector('#nme-music-header'),
  2275. type: 'music',
  2276. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/\s*(.+?)\s*.\s*[‘'](.+?)[’']/).slice(1)
  2277. },
  2278. {
  2279. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/tv-reviews"]'),
  2280. type: 'tv',
  2281. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2282. }]
  2283. },
  2284. albumoftheyear: {
  2285. host: ['albumoftheyear.org'],
  2286. condition: Always,
  2287. products: [{
  2288. condition: () => document.location.pathname.startsWith('/album/'),
  2289. type: 'music',
  2290. data: function () {
  2291. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2292. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2293. return [artist, album]
  2294. }
  2295. }]
  2296. },
  2297. epguides: {
  2298. host: ['epguides.com'],
  2299. condition: () => document.getElementById('eplist'),
  2300. products: [{
  2301. condition: () => document.getElementById('eplist') && document.querySelector('.center.titleblock h2'),
  2302. type: 'tv',
  2303. data: () => document.querySelector('.center.titleblock h2').textContent.trim()
  2304. }]
  2305. },
  2306. ShareTV: {
  2307. host: ['sharetv.com'],
  2308. condition: () => document.location.pathname.startsWith('/shows/'),
  2309. products: [{
  2310. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2311. type: 'tv',
  2312. data: () => document.querySelector("meta[property='og:title']").content
  2313. }]
  2314. },
  2315. /*
  2316. netflix: {
  2317. host: ['netflix.com'],
  2318. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2319.  
  2320. // TODO
  2321. // https://www.netflix.com/de/title/70264888
  2322. // https://www.netflix.com/de/title/70178217
  2323. // https://www.netflix.com/de/title/70305892 ## Movie
  2324. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2325.  
  2326. products: [{
  2327. condition: () => parseLDJSON('@type') === 'Movie',
  2328. type: 'movie',
  2329. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2330. },
  2331. {
  2332. condition: () => parseLDJSON('@type') === 'TVSeries',
  2333. type: 'tv',
  2334. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2335. }]
  2336. },
  2337. */
  2338. ComedyCentral: {
  2339. host: ['cc.com'],
  2340. condition: () => document.location.pathname.startsWith('/shows/'),
  2341. products: [{
  2342. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2343. type: 'tv',
  2344. data: () => document.querySelector("meta[property='og:title']").content.replace('| Comedy Central', '').trim()
  2345. },
  2346. {
  2347. condition: () => document.location.pathname.split('/').length === 3 && document.title.match(/(.+?)\s+-\s+Series/),
  2348. type: 'tv',
  2349. data: () => document.title.match(/(.+?)\s+-\s+Series/)[1]
  2350. }]
  2351. },
  2352. TVHoard: {
  2353. host: ['tvhoard.com'],
  2354. condition: Always,
  2355. products: [{
  2356. condition: () => document.location.pathname.split('/').length === 3 && document.location.pathname.split('/')[1] === 'titles' && !document.querySelector('app-root title-secondary-details-panel .seasons') && document.querySelector('app-root title-page-container h1.title a'),
  2357. type: 'movie',
  2358. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2359. },
  2360. {
  2361. condition: () => document.location.pathname.split('/').length === 3 && document.location.pathname.split('/')[1] === 'titles' && document.querySelector('app-root title-secondary-details-panel .seasons') && document.querySelector('app-root title-page-container h1.title a'),
  2362. type: 'tv',
  2363. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2364. }]
  2365. },
  2366. AMC: {
  2367. host: ['amc.com'],
  2368. condition: () => document.location.pathname.startsWith('/shows/'),
  2369. products: [
  2370. {
  2371. condition: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1'),
  2372. type: 'tv',
  2373. data: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1').textContent
  2374. },
  2375. {
  2376. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2377. type: 'tv',
  2378. data: () => document.querySelector('.video-card-description h1').textContent.trim()
  2379. }]
  2380. },
  2381. AMCplus: {
  2382. host: ['amcplus.com'],
  2383. condition: () => Always,
  2384. products: [
  2385. {
  2386. condition: () => document.title.match(/Watch .+? |/),
  2387. type: 'tv',
  2388. data: () => document.title.match(/Watch (.+?) |/)[1].trim()
  2389. }]
  2390. },
  2391. RlsBB: {
  2392. host: ['rlsbb.ru'],
  2393. condition: () => document.querySelectorAll('.post').length === 1,
  2394. products: [
  2395. {
  2396. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/movies/"]'),
  2397. type: 'movie',
  2398. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+\d{4}/)[1].trim()
  2399. },
  2400. {
  2401. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/tv-shows/"]'),
  2402. type: 'tv',
  2403. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+S\d{2}/)[1].trim()
  2404. }]
  2405. },
  2406. newalbumreleases: {
  2407. host: ['newalbumreleases.net'],
  2408. condition: () => document.querySelectorAll('#content .single').length === 1,
  2409. products: [
  2410. {
  2411. condition: () => document.querySelector('#content .single .cover .entry'),
  2412. type: 'music',
  2413. data: function () {
  2414. const mArtist = document.querySelector('#content .single .cover .entry').textContent.match(/Artist.\s*(.+)\s+/i)
  2415. if (mArtist) {
  2416. const mAlbum = document.querySelector('#content .single .cover .entry').textContent.match(/Album.\s*(.+)\s+/i)
  2417. if (mAlbum) {
  2418. return [mArtist[1], mAlbum[1]]
  2419. }
  2420. }
  2421. }
  2422. }]
  2423. },
  2424. showtime: {
  2425. host: ['sho.com'],
  2426. condition: Always,
  2427. products: [
  2428. {
  2429. condition: () => parseLDJSON('@type') === 'Movie',
  2430. type: 'movie',
  2431. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2432. },
  2433. {
  2434. condition: () => parseLDJSON('@type') === 'TVSeries',
  2435. type: 'tv',
  2436. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2437. }]
  2438. },
  2439. epicgames: {
  2440. host: ['www.epicgames.com'],
  2441. condition: () => document.querySelector('div[data-component="PDPTitleHeader"]'),
  2442. products: [{
  2443. condition: Always,
  2444. type: 'pcgame',
  2445. data: () => document.querySelector('div[data-component="PDPTitleHeader"]').firstElementChild.textContent
  2446. }]
  2447. },
  2448. gog: {
  2449. host: ['www.gog.com'],
  2450. condition: () => document.querySelector('.productcard-basics__title'),
  2451. products: [
  2452. {
  2453. condition: () => document.location.pathname.slice(1, 5) === 'game',
  2454. type: 'pcgame',
  2455. data: () => document.querySelector('.productcard-basics__title').textContent
  2456. },
  2457. {
  2458. condition: () => document.location.pathname.slice(1, 6) === 'movie',
  2459. type: 'movie',
  2460. data: () => document.querySelector('.productcard-basics__title').textContent
  2461. }
  2462. ]
  2463. },
  2464. allmusic: {
  2465. host: ['allmusic.com'],
  2466. condition: Always,
  2467. products: [{
  2468. condition: () => document.location.pathname.indexOf('/album/') !== -1,
  2469. type: 'music',
  2470. data: function () {
  2471. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2472. const album = ld[0]
  2473. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2474. return [artist, album]
  2475. }
  2476. }]
  2477. }
  2478.  
  2479. }
  2480.  
  2481. async function main () {
  2482. let dataFound = false
  2483.  
  2484. let map = false
  2485.  
  2486. for (const name in sites) {
  2487. const site = sites[name]
  2488. if (site.host.some(function (e) { return ~this.indexOf(e) }, document.location.hostname) && site.condition()) {
  2489. for (let i = 0; i < site.products.length; i++) {
  2490. if (site.products[i].condition()) {
  2491. // Check map for a match
  2492. if (map === false) {
  2493. map = JSON.parse(await GM.getValue('map', '{}'))
  2494. }
  2495. const docurl = filterUniversalUrl(document.location.href)
  2496. if (docurl in map) {
  2497. // Found in map, show result
  2498. const metaurl = map[docurl]
  2499. metacritic_general_product_setup()
  2500. metacritic.mapped.apply(undefined, [docurl, site.products[i], absoluteMetaURL(metaurl), site.products[i].type])
  2501. dataFound = true
  2502. break
  2503. }
  2504. // Try to retrieve item name from page
  2505. let data
  2506. try {
  2507. data = site.products[i].data()
  2508. } catch (e) {
  2509. data = false
  2510. console.error(`ShowMetacriticRatings: Error in data() of site='${name}', type='${site.products[i].type}'`)
  2511. console.error(e)
  2512. }
  2513. if (data) {
  2514. const params = [docurl, site.products[i]]
  2515. if (Array.isArray(data)) {
  2516. params.push(...data)
  2517. } else {
  2518. params.push(data)
  2519. }
  2520. metacritic_general_product_setup()
  2521. metacritic[site.products[i].type].apply(undefined, params)
  2522. dataFound = true
  2523. }
  2524. break
  2525. }
  2526. }
  2527. break
  2528. }
  2529. }
  2530. return dataFound
  2531. }
  2532.  
  2533. (async function () {
  2534. const gdpr = await acceptGDPR()
  2535. if (!gdpr) {
  2536. GM.registerMenuCommand('Show Metacritic.com ratings - Accept terms of service', () => acceptGDPR(true).then((yes) => yes && document.location.reload()))
  2537. return
  2538. }
  2539. await versionUpdate()
  2540. const firstRunResult = await main()
  2541.  
  2542. GM.registerMenuCommand('Show Metacritic.com ratings - Search now', () => openSearchBox())
  2543.  
  2544. let lastLoc = document.location.href
  2545. let lastContent = document.body.innerText
  2546. let lastCounter = 0
  2547. async function newpage () {
  2548. if (lastContent === document.body.innerText && lastCounter < 15) {
  2549. window.setTimeout(newpage, 500)
  2550. lastCounter++
  2551. } else {
  2552. lastContent = document.body.innerText
  2553. lastCounter = 0
  2554. const re = await main()
  2555. if (!re) { // No page matched or no data found
  2556. window.setTimeout(newpage, 1000)
  2557. }
  2558. }
  2559. }
  2560. window.setInterval(function () {
  2561. if (document.location.href !== lastLoc) {
  2562. lastLoc = document.location.href
  2563. $('#mcdiv123').remove()
  2564.  
  2565. window.setTimeout(newpage, 1000)
  2566. }
  2567. }, 500)
  2568.  
  2569. if (!firstRunResult) {
  2570. // Initial run had no match, let's try again there may be new content
  2571. window.setTimeout(main, 2000)
  2572. }
  2573. })()