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-23 提交的版本,查看 最新版本

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