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, GOG, Epic Games Store, save.tv

目前為 2023-06-15 提交的版本,檢視 最新版本

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