Greasy Fork is available in English.

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

Установить этот скрипт?
Рекомендуемый автором скрипт

Вам также может понравится Show Rottentomatoes meter.

Установить этот скрипт
  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/a/img/favicon.svg
  6. // @supportURL https://github.com/cvzi/Metacritic-userscript/issues
  7. // @contributionURL https://buymeacoff.ee/cuzi
  8. // @contributionURL https://ko-fi.com/cuzicvzi
  9. // @grant unsafeWindow
  10. // @grant GM.xmlHttpRequest
  11. // @grant GM.setValue
  12. // @grant GM.getValue
  13. // @grant GM.registerMenuCommand
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/3.7.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 102
  18. // @connect metacritic.com
  19. // @connect met.acritic.workers.dev
  20. // @connect imdb.com
  21. // @connect internal-prod.apigee.fandom.net
  22. // @match https://*.bandcamp.com/*
  23. // @match https://play.google.com/store/music/album/*
  24. // @match https://play.google.com/store/movies/details/*
  25. // @match https://music.amazon.com/*
  26. // @match https://www.amazon.ca/*
  27. // @match https://www.amazon.co.jp/*
  28. // @match https://www.amazon.co.uk/*
  29. // @match https://smile.amazon.co.uk/*
  30. // @match https://www.amazon.com.au/*
  31. // @match https://www.amazon.com.mx/*
  32. // @match https://www.amazon.com/*
  33. // @match https://smile.amazon.com/*
  34. // @match https://www.amazon.de/*
  35. // @match https://smile.amazon.de/*
  36. // @match https://www.amazon.es/*
  37. // @match https://www.amazon.fr/*
  38. // @match https://www.amazon.in/*
  39. // @match https://www.amazon.it/*
  40. // @match https://www.imdb.com/title/*
  41. // @match https://store.steampowered.com/app/*
  42. // @match https://www.gamespot.com/*
  43. // @match http://www.serienjunkies.de/*
  44. // @match https://www.serienjunkies.de/*
  45. // @match https://www.rottentomatoes.com/m/*
  46. // @match https://rottentomatoes.com/m/*
  47. // @match https://www.rottentomatoes.com/tv/*
  48. // @match https://rottentomatoes.com/tv/*
  49. // @match https://www.rottentomatoes.com/tv/*
  50. // @match https://rottentomatoes.com/tv/*
  51. // @match https://www.boxofficemojo.com/movies/*
  52. // @match https://www.boxofficemojo.com/release/*
  53. // @match https://www.allmovie.com/movie/*
  54. // @match https://en.wikipedia.org/*
  55. // @match https://www.fandango.com/*
  56. // @match https://flixster.com/movie/*
  57. // @match https://www.themoviedb.org/movie/*
  58. // @match https://www.themoviedb.org/tv/*
  59. // @match https://letterboxd.com/film/*
  60. // @match https://www.tvmaze.com/shows/*
  61. // @match https://www.tvguide.com/tvshows/*
  62. // @match https://followshows.com/show/*
  63. // @match https://thetvdb.com/series/*
  64. // @match https://thetvdb.com/movies/*
  65. // @match https://consequenceofsound.net/*
  66. // @match https://consequence.net/*
  67. // @match https://pitchfork.com/*
  68. // @match https://www.last.fm/*
  69. // @match https://tvnfo.com/tv/*
  70. // @match https://rateyourmusic.com/release/album/*
  71. // @match https://open.spotify.com/*
  72. // @match https://play.spotify.com/album/*
  73. // @match https://www.nme.com/reviews/*
  74. // @match https://www.albumoftheyear.org/album/*
  75. // @match https://itunes.apple.com/*
  76. // @match https://music.apple.com/*
  77. // @match https://epguides.com/*
  78. // @match https://www.epguides.com/*
  79. // @match https://www.netflix.com/*
  80. // @match https://www.cc.com/*
  81. // @match https://www.amc.com/*
  82. // @match https://www.amcplus.com/*
  83. // @match https://rlsbb.ru/*/
  84. // @match https://newalbumreleases.net/*
  85. // @match https://www.sho.com/*
  86. // @match https://www.epicgames.com/store/*
  87. // @match https://store.epicgames.com/*
  88. // @match https://www.gog.com/*
  89. // @match https://www.allmusic.com/album/*
  90. // @match https://www.steamgifts.com/giveaway/*
  91. // @match https://psa.wf/*
  92. // @match https://www.save.tv/*
  93. // @match https://www.wikiwand.com/*
  94. // @match https://trakt.tv/*
  95. // @match http://localhost:7878/*
  96. // ==/UserScript==
  97.  
  98. /* globals alert, confirm, GM, DOMParser, $, Image, unsafeWindow, parent, Blob, failedImages */
  99. /* jshint asi: true, esversion: 8 */
  100.  
  101. const scriptName = 'Show Metacritic.com ratings'
  102.  
  103. const baseURL = 'https://www.metacritic.com/'
  104.  
  105. const baseURLmusic = 'https://www.metacritic.com/music/'
  106. const baseURLmovie = 'https://www.metacritic.com/movie/'
  107. const baseURLpcgame = 'https://www.metacritic.com/game/pc/'
  108. const baseURLps4 = 'https://www.metacritic.com/game/playstation-4/'
  109. const baseURLxone = 'https://www.metacritic.com/game/xbox-one/'
  110. const baseURLtv = 'https://www.metacritic.com/tv/'
  111.  
  112. const baseURLsearch = 'https://internal-prod.apigee.fandom.net/v1/xapi/finder/metacritic/search/{query}/web?apiKey={apiKey}&componentName=search-tabs&componentDisplayName=Search+Page+Tab+Filters&componentType=FilterConfig&mcoTypeId={type}&offset=0&limit=30'
  113.  
  114. const baseURLdatabase = 'https://met.acritic.workers.dev/r.php'
  115. const baseURLwhitelist = 'https://met.acritic.workers.dev/whitelist.php'
  116. const baseURLblacklist = 'https://met.acritic.workers.dev/blacklist.php'
  117.  
  118. const TEMPORARY_BLACKLIST_TIMEOUT = 5 * 60
  119.  
  120. const windowPositions = [
  121. {
  122. bottom: 0,
  123. left: 0
  124. },
  125. {
  126. bottom: 0,
  127. right: 0
  128. },
  129. {
  130. top: 0,
  131. right: 0
  132. },
  133. {
  134. top: 0,
  135. left: 0
  136. }
  137. ]
  138.  
  139. // Detect dark theme of darkreader.org extension
  140. const darkTheme = 'darkreaderScheme' in document.documentElement.dataset && document.documentElement.dataset.darkreaderScheme
  141.  
  142. let myDOMParser = null
  143. function domParser () {
  144. if (myDOMParser === null) {
  145. myDOMParser = new DOMParser()
  146. }
  147. return myDOMParser
  148. }
  149.  
  150. async function versionUpdate () {
  151. const version = parseInt(await GM.getValue('version', 0))
  152. if (version <= 93) {
  153. // Reset database
  154. await GM.setValue('map', '{}')
  155. await GM.setValue('black', '[]')
  156. await GM.setValue('hovercache', '{}')
  157. await GM.setValue('requestcache', '{}')
  158. await GM.setValue('temporaryblack', '{}')
  159. await GM.setValue('searchcache', false) // Unused
  160. await GM.setValue('autosearchcache', false) // Unused
  161. }
  162. if (version < 94) {
  163. await GM.setValue('version', 94)
  164. }
  165. }
  166.  
  167. const BOX_CSS_DARK_THEME = `
  168. #mcdiv123 {
  169. position: fixed;
  170. background-color: #262626;
  171. border: 2px solid #313131;
  172. color: white;
  173. }
  174.  
  175. #mcisearchquery {
  176. background: #262626;
  177. color: white;
  178. }
  179.  
  180. #mcisearchbutton {
  181. background: rgb(56, 56, 56);
  182. color: white;
  183. border: 2px solid white;
  184. }
  185. #mcdiv123 .grespinner {
  186. border-left: 6px solid rgba(0,174,239,.15);
  187. border-right: 6px solid rgba(0,174,239,.15);
  188. border-bottom: 6px solid rgba(0,174,239,.15);
  189. border-top: 6px solid rgba(0,174,239,.8);
  190. }
  191.  
  192. #mcdiv123searchresults .result {
  193. border-top-color: #525252;
  194. }
  195.  
  196.  
  197. #mcdiv123searchresults .result .mcdiv123_score_badge {
  198. color: white;
  199. }
  200.  
  201.  
  202. #mcdiv123searchresults .result .mcdiv_release_date {
  203. color: silver
  204. }
  205.  
  206. .mcdiv123_image_placeholder {
  207. background: rgb(64, 64, 64);
  208. }
  209.  
  210. #mcdiv123searchresults .result a {
  211. color: #09f;
  212. }
  213.  
  214. #mcdiv123searchresults .mcdiv_desc {
  215. scrollbar-color: #003c09 #00ce7a;
  216. }
  217. #mcdiv123searchresults .mcdiv_desc::-webkit-scrollbar-thumb {
  218. background-color: #003c09;
  219. }
  220. `
  221.  
  222. const BOX_CSS = `
  223. #mcdiv123 {
  224. position: fixed;
  225. background-color: #fff;
  226. border: 2px solid #bbb;
  227. border-radius: 6px;
  228. box-shadow: 0 0 3px 3px rgba(100, 100, 100, 0.2);
  229. color: #000;
  230. min-width: 150;
  231. max-height: 80%;
  232. max-width: 640;
  233. overflow: auto;
  234. padding: 3px;
  235. z-index: 2147483601;
  236. }
  237.  
  238. #mcisearchquery {
  239. background: white;
  240. color: black;
  241. width: 450px;
  242. display: inline;
  243. }
  244.  
  245. #mcisearchbutton {
  246. background: silver;
  247. color: black;
  248. border: 2px solid black;
  249. padding: 3px;
  250. display: inline;
  251. margin: 0px 5px;
  252. cursor: pointer;
  253. }
  254.  
  255. /* http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/ */
  256. #mcdiv123 .grespinner {
  257. display: inline-block;
  258. height: 20px;
  259. width: 20px;
  260. margin: 0 auto;
  261. position: relative;
  262. animation: rotation .6s infinite linear;
  263. border-left: 6px solid rgba(0,174,239,.15);
  264. border-right: 6px solid rgba(0,174,239,.15);
  265. border-bottom: 6px solid rgba(0,174,239,.15);
  266. border-top: 6px solid rgba(0,174,239,.8);
  267. border-radius: 100%
  268. }
  269.  
  270. @keyframes rotation {
  271. from {
  272. transform: rotate(0)
  273. }
  274.  
  275. to {
  276. transform: rotate(359deg)
  277. }
  278. }
  279.  
  280. #mcdiv123searchresults {
  281. font-size: 12px;
  282. max-width: 95%
  283. }
  284.  
  285. .mcdiv123_correct_entry {
  286. cursor: pointer;
  287. color: green;
  288. font-size: 25px;
  289. margin-top: 10px;
  290. }
  291. .mcdiv123_correct_entry:hover {
  292. color: #41fd41;
  293. }
  294.  
  295. .mcdiv123_incorrect {
  296. cursor: pointer;
  297. float: right;
  298. color: crimson;
  299. font-size: 11px;
  300. }
  301. .mcdiv123_incorrect {
  302. cursor: pointer;
  303. float: right;
  304. color: crimson;
  305. font-size: 15px;
  306. margin-right: 10px;
  307. }
  308. .mcdiv123_incorrect:hover {
  309. cursor: pointer;
  310. float: right;
  311. color: crimson;
  312. font-size: 15px;
  313. margin-right: 10px;
  314. border:2px solid white;
  315. }
  316. .mcdiv123_incorrect:hover {
  317. border-color: crimson;
  318. }
  319.  
  320. #mcdiv123searchresults .result {
  321. font: 12px arial,helvetica,serif;
  322. border-top-width: 1px;
  323. border-top-color: #ccc;
  324. border-top-style: solid;
  325. padding: 5px
  326. }
  327.  
  328. .mcdiv123_cover {
  329. max-width: 200px;
  330. max-height: 140px;
  331. }
  332.  
  333. #mcdiv123searchresults .result .mcdiv123_score_badge {
  334. display: inline-block;
  335. margin: 3px;
  336. font-weight: 600;
  337. border-radius: 6px;
  338. color: black;
  339. padding: 5px;
  340. }
  341.  
  342. #mcdiv123searchresults .result .floatleft {
  343. float: left;
  344. }
  345.  
  346. #mcdiv123searchresults .result .clearleft {
  347. clear: left;
  348. }
  349.  
  350. #mcdiv123searchresults .result .resultcontent {
  351. max-width: 360px;
  352. margin-left: 10px;
  353. }
  354.  
  355. #mcdiv123searchresults .result .mcdiv_release_date {
  356. color: silver
  357. }
  358.  
  359. .mcdiv123_image_placeholder {
  360. width: 82px;
  361. height: 82px;
  362. background: rgb(64, 64, 64);
  363. border-radius: 8px;
  364. }
  365.  
  366. #mcdiv123searchresults .result a {
  367. color: #09f;
  368. font-weight: 700;
  369. text-decoration: none
  370. }
  371.  
  372. #mcdiv123searchresults .mcdiv_desc {
  373. max-height:120px;
  374. overflow-y: auto;
  375. scrollbar-color: #d9d9d9 #eee;
  376. scrollbar-width: thin;
  377. }
  378.  
  379. @media (prefers-color-scheme: dark) {
  380. ${BOX_CSS_DARK_THEME}
  381. }
  382.  
  383. ${
  384. darkTheme ? BOX_CSS_DARK_THEME : ''
  385. }
  386. `
  387.  
  388. async function acceptGDPR (showDialog) {
  389. if (showDialog === true) {
  390. await GM.setValue('gdpr', null)
  391. return acceptGDPR()
  392. }
  393. return new Promise(function (resolve) {
  394. GM.getValue('gdpr', null).then(function (value) {
  395. if (value === true) {
  396. return resolve(true)
  397. }
  398. if (value === false) {
  399. return resolve(false)
  400. }
  401. 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>'
  402. const div = document.body.appendChild(document.createElement('div'))
  403. div.innerHTML = html
  404. 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'
  405. div.appendChild(document.createElement('br'))
  406. const acceptButton = div.appendChild(document.createElement('button'))
  407. 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')
  408. acceptButton.appendChild(document.createTextNode('Accept'))
  409. acceptButton.addEventListener('click', function () {
  410. div.remove()
  411. resolve(true)
  412. GM.setValue('gdpr', true)
  413. })
  414. const declineButton = div.appendChild(document.createElement('button'))
  415. 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')
  416. declineButton.appendChild(document.createTextNode('Decline'))
  417. declineButton.addEventListener('click', function () {
  418. alert('You may uninstall the userscript now.')
  419. div.remove()
  420. resolve(false)
  421. GM.setValue('gdpr', false)
  422. })
  423. const space = div.appendChild(document.createElement('div'))
  424. space.style = 'height:2000px;'
  425. div.scrollIntoView()
  426. window.setTimeout(function () {
  427. 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.')
  428. }, 20)
  429. })
  430. })
  431. }
  432.  
  433. function delay (ms) {
  434. return new Promise(function (resolve) {
  435. window.setTimeout(() => resolve(), ms)
  436. })
  437. }
  438.  
  439. function absoluteMetaURL (url) {
  440. if (url.startsWith('https://')) {
  441. return url
  442. }
  443. if (url.startsWith('http://')) {
  444. return 'https' + url.substr(4)
  445. }
  446. if (url.startsWith('//')) {
  447. return baseURL + url.substr(2)
  448. }
  449. if (url.startsWith('/')) {
  450. return baseURL + url.substr(1)
  451. }
  452. return baseURL + url
  453. }
  454.  
  455. const parseLDJSONCache = {}
  456. function parseLDJSON (keys, condition) {
  457. if (document.querySelector('script[type="application/ld+json"]')) {
  458. const xmlEntitiesElement = document.createElement('div')
  459. const xmlEntitiesPattern = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig
  460. const xmlEntities = function (s) {
  461. s = s.replace(xmlEntitiesPattern, (m) => {
  462. xmlEntitiesElement.innerHTML = m
  463. return xmlEntitiesElement.textContent
  464. })
  465. return s
  466. }
  467. const decodeXmlEntities = function (jsonObj) {
  468. // Traverse through object, decoding all strings
  469. if (jsonObj !== null && typeof jsonObj === 'object') {
  470. Object.entries(jsonObj).forEach(([key, value]) => {
  471. // key is either an array index or object key
  472. jsonObj[key] = decodeXmlEntities(value)
  473. })
  474. } else if (typeof jsonObj === 'string') {
  475. return xmlEntities(jsonObj)
  476. }
  477. return jsonObj
  478. }
  479.  
  480. const data = []
  481. const scripts = document.querySelectorAll('script[type="application/ld+json"]')
  482. for (let i = 0; i < scripts.length; i++) {
  483. let jsonld
  484. if (scripts[i].innerText in parseLDJSONCache) {
  485. jsonld = parseLDJSONCache[scripts[i].innerText]
  486. } else {
  487. try {
  488. jsonld = JSON.parse(scripts[i].innerText)
  489. parseLDJSONCache[scripts[i].innerText] = jsonld
  490. } catch (e) {
  491. parseLDJSONCache[scripts[i].innerText] = null
  492. continue
  493. }
  494. }
  495. if (jsonld) {
  496. if (Array.isArray(jsonld)) {
  497. data.push(...jsonld)
  498. } else {
  499. data.push(jsonld)
  500. }
  501. }
  502. }
  503. for (let i = 0; i < data.length; i++) {
  504. try {
  505. if (data[i] && data[i] && (typeof condition !== 'function' || condition(data[i]))) {
  506. if (Array.isArray(keys)) {
  507. const r = []
  508. for (let j = 0; j < keys.length; j++) {
  509. r.push(data[i][keys[j]])
  510. }
  511. return decodeXmlEntities(r)
  512. } else if (keys) {
  513. return decodeXmlEntities(data[i][keys])
  514. } else if (typeof condition === 'function') {
  515. return decodeXmlEntities(data[i]) // Return whole object
  516. }
  517. }
  518. } catch (e) {
  519. continue
  520. }
  521. }
  522. return decodeXmlEntities(data)
  523. }
  524. return null
  525. }
  526.  
  527. function name2metacritic (s) {
  528. const mc = s.normalize('NFKD').replace(/\//g, '').replace(/[\u0300-\u036F]/g, '').replace(/&/g, 'and').replace(/\W+/g, ' ').toLowerCase().trim().replace(/\W+/g, '-')
  529. if (!mc) {
  530. throw new Error("name2metacritic converted '" + s + "' to empty string")
  531. }
  532. return mc
  533. }
  534. function minutesSince (time) {
  535. const seconds = ((new Date()).getTime() - time.getTime()) / 1000
  536. return seconds > 60 ? parseInt(seconds / 60) + ' min ago' : 'now'
  537. }
  538. function randomStringId () {
  539. const id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1)
  540. return id10() + id10() + id10() + id10() + id10() + id10()
  541. }
  542. function fixMetacriticURLs (html) {
  543. return html.replace(/<a /g, '<a target="_blank" ').replace(/href="\//g, 'href="' + baseURL).replace(/src="\//g, 'src="' + baseURL)
  544. }
  545. function searchType2fandomProdApigee (type) {
  546. return ({
  547. tv: '1',
  548. movie: '2',
  549. pcgame: '13',
  550. xonegame: '13',
  551. ps4game: '13',
  552. music: '4' // TODO this is probably wrong, music seems to be unsupported at the moment
  553. })[type]
  554. }
  555. function fandomProdApigee2metacriticUrl (type) {
  556. return ({
  557. 1: 'tv',
  558. 2: 'movie',
  559. 13: 'game',
  560. 4: 'music' // TODO this is probably wrong, music seems to be unsupported at the moment
  561. })[type]
  562. }
  563.  
  564. function badgeColor (score, type = '') {
  565. const colors = {
  566. universalAcclaim: '#6c3',
  567. generallyFavorable: '#00ce7a',
  568. mixedOrAverage: '#ffbd3f',
  569. generallyUnfavorable: '#ff6874',
  570. overwhelmingDislike: '#f00',
  571. tbd: '#fff'
  572. }
  573.  
  574. if (type.indexOf('game') !== -1) {
  575. if (score > 89) {
  576. return colors.universalAcclaim
  577. }
  578. if (score > 74) {
  579. return colors.generallyFavorable
  580. }
  581. if (score > 49) {
  582. return colors.mixedOrAverage
  583. }
  584. if (score > 19) {
  585. return colors.generallyUnfavorable
  586. }
  587. if (score > 0) {
  588. return colors.overwhelmingDislike
  589. }
  590. return colors.tbd
  591. } else {
  592. if (score > 80) {
  593. return colors.universalAcclaim
  594. }
  595. if (score > 60) {
  596. return colors.generallyFavorable
  597. }
  598. if (score > 39) {
  599. return colors.mixedOrAverage
  600. }
  601. if (score > 19) {
  602. return colors.generallyUnfavorable
  603. }
  604. if (score > 0) {
  605. return colors.overwhelmingDislike
  606. }
  607. return colors.tbd
  608. }
  609. }
  610.  
  611. function replaceBrackets (str) {
  612. str = str.replace(/\([^(]*\)/g, '')
  613. str = str.replace(/\[[^\]]*\]/g, '')
  614. return str.trim()
  615. }
  616. function removeSymbols (str) {
  617. str = str.replace(/[^\s0-9A-Za-zÀ-ÖØ-öø-ÿ]*/gi, '').trim()
  618. return str.trim()
  619. }
  620. const dashRegExp = /[-\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D]/
  621. function removeAnythingAfterDash (str) {
  622. str = str.split(dashRegExp)[0]
  623. return str.trim()
  624. }
  625.  
  626. function broadenSearch (data, step, type) {
  627. if (type === 'pcgame') {
  628. if (step > 0) {
  629. data[0] = replaceBrackets(data[0])
  630. } else if (step > 1) {
  631. data[0] = removeSymbols(data[0])
  632. } else if (step > 2) {
  633. data[0] = removeAnythingAfterDash(data[0])
  634. }
  635. } else {
  636. data = data.map(removeSymbols)
  637. }
  638. return data
  639. }
  640.  
  641. function balloonAlert (message, timeout, title, css, click) {
  642. let header
  643. if (title) {
  644. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title + '</div>'
  645. } else if (title === false) {
  646. header = ''
  647. } else {
  648. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>'
  649. }
  650. const div = $('<div>' + header + '<div style="padding:5px">' + message.split('\n').join('<br>') + '</div></div>')
  651. div.css({
  652. position: 'fixed',
  653. top: 10,
  654. left: 10,
  655. maxWidth: 200,
  656. zIndex: '2147483601',
  657. background: 'rgb(240,240,240)',
  658. border: '2px solid yellow',
  659. borderRadius: '6px',
  660. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  661. fontFamily: 'sans-serif',
  662. color: 'black'
  663. })
  664. if (css) {
  665. div.css(css)
  666. }
  667. div.appendTo(document.body)
  668.  
  669. if (click) {
  670. div.click(function (ev) {
  671. $(this).hide(500)
  672. click.call(this, ev)
  673. })
  674. }
  675.  
  676. if (!click) {
  677. const close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">&#10062;</div>').appendTo(div)
  678. close.click(function () {
  679. $(this.parentNode).hide(1000)
  680. })
  681. }
  682.  
  683. if (timeout && timeout > 0) {
  684. window.setTimeout(function () {
  685. div.hide(3000)
  686. }, timeout)
  687. }
  688. return div
  689. }
  690.  
  691. function filterUniversalUrl (url) {
  692. try {
  693. url = url.match(/http.+/)[0]
  694. } catch (e) { }
  695.  
  696. try {
  697. url = url.replace(/https?:\/\/(www.)?/, '')
  698. } catch (e) { }
  699.  
  700. if (url.indexOf('#') !== -1) {
  701. url = url.split('#')[0]
  702. }
  703.  
  704. if (url.startsWith('imdb.com/') && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
  705. // Remove movie subpage from imdb url
  706. return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1]
  707. } else if (url.startsWith('boxofficemojo.com/') && url.indexOf('id=') !== -1) {
  708. // Keep the important id= on
  709. try {
  710. const parts = url.split('?')
  711. const page = parts[0] + '?'
  712. const idparam = parts[1].match(/(id=.+?)(\.|&)/)[1]
  713. return page + idparam
  714. } catch (e) {
  715. return url
  716. }
  717. } else {
  718. // Default: Remove parameters
  719. return url.split('?')[0].split('&')[0]
  720. }
  721. }
  722.  
  723. async function addToMap (url, metaurl) {
  724. const data = JSON.parse(await GM.getValue('map', '{}'))
  725.  
  726. url = filterUniversalUrl(url)
  727. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  728.  
  729. data[url] = metaurl
  730.  
  731. await GM.setValue('map', JSON.stringify(data));
  732.  
  733. (new Image()).src = baseURLwhitelist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  734. return [url, metaurl]
  735. }
  736.  
  737. async function addToTemporaryBlacklist (metaurl) {
  738. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  739.  
  740. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  741. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  742. metaurl = metaurl.replace(/^\/+/, '')
  743.  
  744. data[metaurl] = (new Date()).toJSON()
  745.  
  746. // Remove old entries
  747. const now = (new Date()).getTime()
  748. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  749. for (const prop in data) {
  750. if (now - (new Date(data[prop].time)).getTime() > timeout) {
  751. delete data[prop]
  752. }
  753. }
  754.  
  755. await GM.setValue('temporaryblack', JSON.stringify(data))
  756.  
  757. return true
  758. }
  759.  
  760. async function removeFromTemporaryBlacklist (metaurl) {
  761. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  762.  
  763. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  764. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  765. metaurl = metaurl.replace(/^\/+/, '')
  766.  
  767. if (metaurl in data) {
  768. delete data[metaurl]
  769. await GM.setValue('temporaryblack', JSON.stringify(data))
  770. }
  771. }
  772.  
  773. async function isTemporaryBlacklisted (metaurl) {
  774. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  775.  
  776. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  777. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  778. metaurl = metaurl.replace(/^\/+/, '')
  779.  
  780. if (metaurl in data) {
  781. const now = (new Date()).getTime()
  782. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  783. if (now - (new Date(data[metaurl])).getTime() < timeout) {
  784. return true
  785. }
  786. }
  787. return false
  788. }
  789.  
  790. async function addToBlacklist (url, metaurl) {
  791. const data = JSON.parse(await GM.getValue('black', '[]'))
  792.  
  793. url = filterUniversalUrl(url)
  794. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  795.  
  796. data.push([url, metaurl])
  797.  
  798. await GM.setValue('black', JSON.stringify(data));
  799.  
  800. (new Image()).src = baseURLblacklist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  801. return [url, metaurl]
  802. }
  803.  
  804. async function removeFromBlacklist (docurl, metaurl) {
  805. docurl = filterUniversalUrl(docurl)
  806. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  807.  
  808. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  809. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  810. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  811.  
  812. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  813. const found = []
  814. for (let i = 0; i < data.length; i++) {
  815. if (data[i][0] === docurl && data[i][1] === metaurl) {
  816. found.push(i)
  817. }
  818. }
  819. for (let i = found.length - 1; i >= 0; i--) {
  820. data.pop(i)
  821. }
  822.  
  823. await GM.setValue('black', JSON.stringify(data))
  824. }
  825.  
  826. async function isBlacklistedUrl (docurl, metaurl) {
  827. docurl = filterUniversalUrl(docurl)
  828. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  829.  
  830. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  831. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  832. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  833.  
  834. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  835. for (let i = 0; i < data.length; i++) {
  836. if (data[i][0] === docurl && data[i][1] === metaurl) {
  837. return true
  838. }
  839. }
  840. return false
  841. }
  842.  
  843. let listenForHotkeysActive = false
  844. function listenForHotkeys (code, cb) {
  845. // Call cb() as soon as the code sequence was typed
  846. if (listenForHotkeysActive) {
  847. return
  848. }
  849. listenForHotkeysActive = true
  850. let i = 0
  851. $(document).bind('keydown.listenForHotkeys', function (ev) {
  852. if (document.activeElement === document.body) {
  853. if (ev.key !== code[i]) {
  854. i = 0
  855. } else {
  856. i++
  857. if (i === code.length) {
  858. ev.preventDefault()
  859. $(document).unbind('keydown.listenForHotkeys')
  860. cb()
  861. }
  862. }
  863. }
  864. })
  865. }
  866.  
  867. function waitForHotkeysMETA () {
  868. listenForHotkeys('meta', (ev) => openSearchBox())
  869. }
  870.  
  871. async function handleJSONredirect (response) {
  872. let blacklistedredirect = false
  873. const j = JSON.parse(response.responseText)
  874.  
  875. // Blacklist items from database received?
  876. if ('blacklist' in j && j.blacklist && j.blacklist.length) {
  877. // Save new blacklist items
  878. const data = JSON.parse(await GM.getValue('black', '[]'))
  879. for (let i = 0; i < j.blacklist.length; i++) {
  880. const saveDocurl = j.blacklist[i].docurl
  881. const saveMetaurl = j.blacklist[i].metaurl
  882.  
  883. data.push([saveDocurl, saveMetaurl])
  884. if (j.jsonRedirect === '/' + saveMetaurl) {
  885. // Redirect is blacklisted!
  886. blacklistedredirect = true
  887. }
  888. }
  889. await GM.setValue('black', JSON.stringify(data))
  890. }
  891. if (blacklistedredirect) {
  892. // Redirect was blacklisted, show nothing
  893. console.debug('ShowMetacriticRatings: Redirect was blacklisted -> show nothing')
  894. return null
  895. } else {
  896. // Load redirect
  897. current.metaurl = absoluteMetaURL(j.jsonRedirect)
  898. response = await asyncRequest({
  899. url: current.metaurl
  900. }).catch(function (response) {
  901. console.error('ShowMetacriticRatings: Error 01')
  902. })
  903. return response
  904. }
  905. }
  906.  
  907. function extractHoverFromFullPage (response) {
  908. let html = 'ShowMetacriticRatings:<br>Error occured in extractHoverFromFullPage()'
  909. try {
  910. // Try parsing HTML
  911. const doc = domParser().parseFromString(response.responseText, 'text/html')
  912.  
  913. let content = null
  914. // Try to get the review containers from the bottom of the page below the actors
  915. const carouselItems = doc.querySelectorAll('.c-reviewsSection_carouselContainer .c-reviewsOverview_overviewDetails')
  916. if (carouselItems.length > 0) {
  917. content = Array.from(carouselItems).map(e => e.outerHTML).join('\n\n')
  918. } else {
  919. // Fallback: Try to get the review containers from the right side of the page next to the poster/screenshot
  920. content = doc.querySelector('.c-productHero_scoreInfo').innerHTML
  921. }
  922.  
  923. if (!content) {
  924. throw new Error('No content found')
  925. }
  926.  
  927. html = `
  928. <div id="hover_div_a20230915">
  929.  
  930. ${content}
  931.  
  932. </div>
  933. `
  934. } catch (e) {
  935. console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e)
  936. // fallback to cutting out the relevant parts
  937. const parts = response.responseText.split('c-productHero_score-container')
  938.  
  939. html = '<div class="' + parts[1].split('c-ratingReviewWrapper')[0] + '"></div></div>'
  940. if (html.length > 5000) {
  941. // Probably something went wrong, let's cut the response to prevent too long content
  942. console.warn('ShowMetacriticRatings: Cutting response to 5000 chars')
  943. html = html.substring(0, 5000)
  944. }
  945. }
  946. return html
  947. }
  948.  
  949. function asyncRequest (data) {
  950. return new Promise(function (resolve, reject) {
  951. isInRequestCache(data).then(function (cachedValue) {
  952. if (cachedValue) {
  953. console.debug(`${scriptName}: asyncRequest() Cache hit for`, data)
  954. return window.setTimeout(() => resolve(cachedValue), 10)
  955. }
  956. const defaultHeaders = {
  957. Referer: data.url,
  958. 'User-Agent': navigator.userAgent
  959. }
  960. const defaultData = {
  961. method: 'GET',
  962. onload: function (response) {
  963. storeInRequestCache(data, response)
  964. resolve(response)
  965. },
  966. onerror: (response) => reject(response)
  967. }
  968. if ('headers' in data) {
  969. data.headers = Object.assign(defaultHeaders, data.headers)
  970. } else {
  971. data.headers = defaultHeaders
  972. }
  973. data = Object.assign(defaultData, data)
  974. console.debug(`${scriptName}: asyncRequest() GM.xmlHttpRequest`, data)
  975. GM.xmlHttpRequest(data)
  976. })
  977. })
  978. }
  979.  
  980. async function storeInRequestCache (requestData, response) {
  981. const newkey = JSON.stringify({
  982. url: requestData.url,
  983. method: requestData.method || 'GET',
  984. data: requestData.data || null
  985. })
  986. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  987. const now = (new Date()).getTime()
  988. const timeout = 15 * 60 * 1000
  989. for (const prop in cache) {
  990. // Delete cached values, that are older than 15 minutes
  991. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  992. delete cache[prop]
  993. }
  994. }
  995.  
  996. const newobj = {}
  997. for (const key in response) {
  998. newobj[key] = response[key]
  999. }
  1000. newobj.responseText = '' + response.responseText
  1001. newobj.cached = true
  1002. if (!('time' in newobj)) {
  1003. newobj.time = (new Date()).toJSON()
  1004. }
  1005.  
  1006. cache[newkey] = newobj
  1007.  
  1008. await GM.setValue('requestcache', JSON.stringify(cache))
  1009. }
  1010.  
  1011. async function isInRequestCache (requestData) {
  1012. const key = JSON.stringify({
  1013. url: requestData.url,
  1014. method: requestData.method || 'GET',
  1015. data: requestData.data || null
  1016. })
  1017.  
  1018. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  1019. const now = (new Date()).getTime()
  1020. const timeout = 15 * 60 * 1000
  1021. for (const prop in cache) {
  1022. // Delete cached values, that are older than 15 minutes
  1023. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1024. delete cache[prop]
  1025. }
  1026. }
  1027.  
  1028. if (key in cache) {
  1029. return cache[key]
  1030. } else {
  1031. return false
  1032. }
  1033. }
  1034.  
  1035. async function storeInHoverCache (metaurl, response, orgMetaUrl) {
  1036. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  1037. const now = (new Date()).getTime()
  1038. const timeout = 2 * 60 * 60 * 1000
  1039. for (const prop in cache) {
  1040. // Delete cached values, that are older than 2 hours
  1041. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1042. delete cache[prop]
  1043. }
  1044. }
  1045.  
  1046. const newobj = {}
  1047. for (const key in response) {
  1048. newobj[key] = response[key]
  1049. }
  1050. newobj.responseText = '' + response.responseText
  1051. newobj.cached = true
  1052. if (!('time' in newobj)) {
  1053. newobj.time = (new Date()).toJSON()
  1054. }
  1055.  
  1056. cache[metaurl] = newobj
  1057. if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect
  1058. cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl }
  1059. }
  1060.  
  1061. await GM.setValue('hovercache', JSON.stringify(cache))
  1062. }
  1063.  
  1064. async function isInHoverCache (metaurl) {
  1065. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  1066. const now = (new Date()).getTime()
  1067. const timeout = 2 * 60 * 60 * 1000
  1068. for (const prop in cache) {
  1069. // Delete cached values, that are older than 2 hours
  1070. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1071. delete cache[prop]
  1072. }
  1073. }
  1074.  
  1075. function resolveRedirects (cacheEntry) {
  1076. if (cacheEntry.redirect) {
  1077. const newkey = cacheEntry.redirect
  1078. if (newkey in cache) {
  1079. const value = cache[newkey]
  1080. delete cache[newkey]
  1081. return resolveRedirects(value)
  1082. }
  1083. } else {
  1084. return cacheEntry
  1085. }
  1086. return false
  1087. }
  1088.  
  1089. if (metaurl in cache) {
  1090. const value = cache[metaurl]
  1091. delete cache[metaurl]
  1092. return resolveRedirects(value)
  1093. } else {
  1094. return false
  1095. }
  1096. }
  1097.  
  1098. async function loadHoverInfo () {
  1099. const cacheResponse = await isInHoverCache(current.metaurl)
  1100. if (cacheResponse !== false) {
  1101. console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`)
  1102. if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) {
  1103. return await handleJSONredirect(cacheResponse)
  1104. }
  1105. return cacheResponse
  1106. }
  1107. const requestURL = baseURLdatabase
  1108. const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl)
  1109.  
  1110. let response = await asyncRequest({
  1111. method: 'POST',
  1112. url: requestURL,
  1113. data: requestParams,
  1114. headers: {
  1115. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  1116. }
  1117. }).catch(function (response) {
  1118. console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status)
  1119. })
  1120.  
  1121. if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) {
  1122. response = await handleJSONredirect(response)
  1123. }
  1124.  
  1125. if (response.status >= 500) {
  1126. // Metacritic server error, try again after 2 seconds
  1127. console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1128. await delay(2000)
  1129. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  1130. console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1131. })
  1132. if (response.status > 300) {
  1133. console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1134. } else {
  1135. const newobj = {}
  1136. for (const key in response) {
  1137. newobj[key] = response[key]
  1138. }
  1139. newobj.responseText = extractHoverFromFullPage(response)
  1140. response = newobj
  1141. }
  1142. }
  1143.  
  1144. // Extract relevant data from HTML
  1145. if (!('time' in response)) {
  1146. response.time = (new Date()).toJSON()
  1147. }
  1148. if (response.status === 200 && response.responseText) {
  1149. const newobj = {}
  1150. for (const key in response) {
  1151. newobj[key] = response[key]
  1152. }
  1153. newobj.responseText = extractHoverFromFullPage(response)
  1154. response = newobj
  1155. return response
  1156. } else {
  1157. const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status)
  1158. error.status = response.status
  1159. error.responseText = response.responseText
  1160. throw error
  1161. }
  1162. }
  1163.  
  1164. function changePosition () {
  1165. // Cycle through positions
  1166. GM.getValue('position', JSON.stringify(windowPositions[0])).then(function (s) {
  1167. let index
  1168. for (index = 0; index < windowPositions.length; index++) {
  1169. if (JSON.stringify(windowPositions[index]) === s) {
  1170. break
  1171. }
  1172. }
  1173. const nextIndex = (index + 1) % windowPositions.length
  1174. GM.setValue('position', JSON.stringify(windowPositions[nextIndex])).then(function () {
  1175. document.location.reload()
  1176. })
  1177. })
  1178. }
  1179.  
  1180. function onSizeChanged () {
  1181. GM.getValue('size', 100).then(function (size) {
  1182. if (size && size !== 100) {
  1183. size = parseInt(size)
  1184. $('#mcdiv123').css('transform', `scale(${size}%)`)
  1185. }
  1186. })
  1187. }
  1188.  
  1189. function changeSizeEnlarge () {
  1190. GM.getValue('size', 100).then((size) => {
  1191. GM.setValue('size', parseInt(size) + 5).then(onSizeChanged)
  1192. })
  1193. }
  1194.  
  1195. function changeSizeShrink () {
  1196. GM.getValue('size', 100).then((size) => {
  1197. GM.setValue('size', parseInt(size) - 5).then(onSizeChanged)
  1198. })
  1199. }
  1200.  
  1201. const current = {
  1202. metaurl: false,
  1203. docurl: false,
  1204. type: false,
  1205. data: [], // Array of raw search keys
  1206. searchTerm: false,
  1207. product: null,
  1208. broadenCounter: 0
  1209. }
  1210.  
  1211. async function onBlacklistedPage () {
  1212. GM.registerMenuCommand('Show Metacritic.com ratings - Remove from Blacklist', () => removeFromBlacklistAndReload())
  1213. }
  1214.  
  1215. async function removeFromBlacklistAndReload () {
  1216. await removeFromBlacklist(current.docurl, current.metaurl)
  1217. await removeFromTemporaryBlacklist(current.metaurl)
  1218. main()
  1219. }
  1220.  
  1221. async function loadMetacriticUrl (fromSearch) {
  1222. if (!current.metaurl) {
  1223. alert('ShowMetacriticRatings: Error 04')
  1224. return
  1225. }
  1226. const orgMetaUrl = current.metaurl
  1227. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1228. waitForHotkeysMETA()
  1229. onBlacklistedPage()
  1230. return
  1231. }
  1232.  
  1233. if (await isTemporaryBlacklisted(current.metaurl)) {
  1234. console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`)
  1235. waitForHotkeysMETA()
  1236. onBlacklistedPage()
  1237. return
  1238. }
  1239.  
  1240. const response = await loadHoverInfo().catch(async function (response) {
  1241. if (response instanceof Error || (response && response.stack && response.message)) {
  1242. if (!fromSearch && ('status' in response && response.status === 404)) {
  1243. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): status=404', response)
  1244. // No results
  1245. let broadenFct = broadenSearch // global broadenSearch function is the default
  1246. if ('broaden' in current.product) {
  1247. // try product 'broaden'-function if it is defined
  1248. broadenFct = current.product.broaden
  1249. }
  1250. const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1251. if (JSON.stringify(newData) !== JSON.stringify(current.data)) {
  1252. current.data = newData
  1253. metacritic[current.type](current.docurl, current.product, ...newData)
  1254. } else if (JSON.stringify(newData) === JSON.stringify(current.data)) {
  1255. // Same data as before, try once again to broaden
  1256. const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1257. if (JSON.stringify(newData2) !== JSON.stringify(current.data)) {
  1258. current.data = newData2
  1259. metacritic[current.type](current.docurl, current.product, ...newData2)
  1260. } else {
  1261. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps')
  1262. }
  1263. } else {
  1264. console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData)
  1265. }
  1266. } else {
  1267. console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response)
  1268. }
  1269. }
  1270.  
  1271. if (!fromSearch) {
  1272. startSearch()
  1273. }
  1274. })
  1275.  
  1276. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1277. waitForHotkeysMETA()
  1278. onBlacklistedPage()
  1279. return
  1280. }
  1281.  
  1282. if (typeof response !== 'undefined') {
  1283. showHoverInfo(response, orgMetaUrl)
  1284. } else {
  1285. waitForHotkeysMETA()
  1286. }
  1287. }
  1288.  
  1289. async function startSearch () {
  1290. waitForHotkeysMETA()
  1291.  
  1292. if (current.type === 'music') {
  1293. current.searchTerm = current.data[0]
  1294. } else {
  1295. current.searchTerm = current.data.join(' ')
  1296. }
  1297. const items = await fandomProdApigeeSearch(current.searchTerm, current.type)
  1298.  
  1299. if (!items) {
  1300. alert('ShowMetacriticRatings: Error 05 item=', items)
  1301. }
  1302.  
  1303. let multiple = false
  1304. if (items.length === 0) {
  1305. // No results
  1306. console.debug('ShowMetacriticRatings: No results for searchTerm=' + current.searchTerm)
  1307. } else if (items.length === 1) {
  1308. // One result, let's show it
  1309. const itemURL = absoluteMetaURL(items[0].metacriticUrl)
  1310. if (!await isBlacklistedUrl(document.location.href, itemURL)) {
  1311. current.metaurl = itemURL
  1312. loadMetacriticUrl(true)
  1313. return
  1314. } else {
  1315. onBlacklistedPage()
  1316. return
  1317. }
  1318. } else {
  1319. // More than one result
  1320. multiple = true
  1321. console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm)
  1322. const exactMatches = []
  1323. items.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title
  1324. if (current.searchTerm.toLowerCase() === result.title.toLowerCase()) {
  1325. exactMatches.push(result)
  1326. }
  1327. })
  1328. if (exactMatches.length === 0) {
  1329. // Try to be a bit more fuzzy
  1330. items.forEach(function (result, i) {
  1331. if (removeSymbols(current.searchTerm.toLowerCase()) === removeSymbols(result.title.toLowerCase())) {
  1332. exactMatches.push(result)
  1333. }
  1334. })
  1335. }
  1336. if (exactMatches.length === 1) {
  1337. // Only one exact match, let's show it
  1338. console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm)
  1339. const itemURL = absoluteMetaURL(exactMatches[0].metacriticUrl)
  1340. if (!await isBlacklistedUrl(document.location.href, itemURL)) {
  1341. current.metaurl = itemURL
  1342. loadMetacriticUrl(true)
  1343. return
  1344. } else {
  1345. onBlacklistedPage()
  1346. return
  1347. }
  1348. }
  1349. }
  1350.  
  1351. // HERE: multiple results or no result. The user may type "meta" now
  1352. if (multiple) {
  1353. balloonAlert('Multiple metacritic results. Type &#34;meta&#34; for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5, cursor: 'pointer' }, () => openSearchBox(true))
  1354. }
  1355. }
  1356.  
  1357. function openSearchBox (search) {
  1358. let query
  1359. if (current.type === 'music') {
  1360. query = current.data[0]
  1361. } else {
  1362. query = current.data.join(' ')
  1363. }
  1364. $('#mcdiv123').remove()
  1365.  
  1366. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1367. div.css({
  1368. minWidth: 300,
  1369. bottom: 0,
  1370. left: 0
  1371. })
  1372.  
  1373. GM.getValue('position', false).then(function (s) {
  1374. if (s) {
  1375. div.css({
  1376. top: '',
  1377. left: '',
  1378. bottom: '',
  1379. right: ''
  1380. })
  1381. div.css(JSON.parse(s))
  1382. }
  1383. })
  1384.  
  1385. $('<input type="text" id="mcisearchquery">').appendTo(div).focus().val(query).on('keypress', function (e) {
  1386. const code = e.keyCode || e.which
  1387. if (code === 13) { // Enter key
  1388. searchBoxSearch(e, $('#mcisearchquery').val())
  1389. }
  1390. })
  1391. $('<button id="mcisearchbutton">').text('Search').appendTo(div).click((ev) => searchBoxSearch(ev, $('#mcisearchquery').val()))
  1392. }
  1393.  
  1394. async function getFandomProdApigeeApiKey () {
  1395. let apiKey = await GM.getValue('fandomProdApigeeKey', false)
  1396. if (!apiKey) {
  1397. apiKey = await findFandomProdApigeeApiKey()
  1398. }
  1399.  
  1400. const lastUpdate = await GM.getValue('fandomProdApigeeTime', false)
  1401. if (!lastUpdate || (new Date()).getTime() - (new Date(lastUpdate)).getTime() > 7 * 24 * 60 * 60 * 1000) {
  1402. // Update api key once a week
  1403. const newApiKey = await findFandomProdApigeeApiKey()
  1404. if (newApiKey) {
  1405. apiKey = newApiKey
  1406. }
  1407. }
  1408.  
  1409. if (!apiKey) {
  1410. console.debug('ShowMetacriticRatings: Fallback to hard-coded api key')
  1411. apiKey = '1MOZgmNFxvmljaQR1X9KAij9Mo4xAY3u'
  1412. }
  1413. return apiKey
  1414. }
  1415.  
  1416. async function findFandomProdApigeeApiKey () {
  1417. // Get a new Api key from the metacritic website search results page
  1418. const url = 'https://www.metacritic.com/search/Fly/'
  1419. try {
  1420. const response = await asyncRequest({ url })
  1421. const m = response.responseText.match(/\?apiKey=(\w{20,})/)
  1422. if (m) {
  1423. const apiKey = m[1]
  1424. console.debug('ShowMetacriticRatings: Api key updated', apiKey)
  1425. await GM.setValue('fandomProdApigeeKey', apiKey)
  1426. await GM.setValue('fandomProdApigeeTime', (new Date()).toJSON())
  1427. return apiKey
  1428. }
  1429. } catch (e) {
  1430. console.error('ShowMetacriticRatings: findFandomProdApigeeApiKey() Error:', e)
  1431. }
  1432. console.error('ShowMetacriticRatings: Could not find fandomProdApigee api key')
  1433. return false
  1434. }
  1435.  
  1436. async function fandomProdApigeeSearch (query, searchType) {
  1437. const apiKey = await getFandomProdApigeeApiKey()
  1438.  
  1439. const type = searchType2fandomProdApigee(searchType)
  1440. const url = baseURLsearch.replace('{type}', encodeURIComponent(type)).replace('{query}', encodeURIComponent(query)).replace('{apiKey}', encodeURIComponent(apiKey))
  1441.  
  1442. const response = await asyncRequest({ url })
  1443.  
  1444. if (response.status !== 200) {
  1445. console.error('ShowMetacriticRatings: fandomProdApigeeSearch() response != 200: ', response)
  1446. }
  1447.  
  1448. const obj = JSON.parse(response.responseText)
  1449. return obj.data.items.map(item => {
  1450. // Improve results by adding the metacritic url
  1451. let itemUrl = 'criticScoreSummary' in item && 'url' in item.criticScoreSummary ? item.criticScoreSummary.url : null
  1452. if (!itemUrl) {
  1453. itemUrl = `${baseURL}${fandomProdApigee2metacriticUrl(item.typeId)}/${item.slug}/`
  1454. }
  1455. item.metacriticUrl = itemUrl.replace('/critic-reviews/', '/')
  1456. return item
  1457. })
  1458. }
  1459.  
  1460. async function searchBoxSearch (ev, query) {
  1461. if (!query) { // Use values from search form
  1462. query = current.searchTerm
  1463. }
  1464.  
  1465. const div = $('#mcdiv123')
  1466. div.css({
  1467. minWidth: '550px'
  1468. })
  1469. const loader = $('<div class="grespinner"></div>').appendTo($('#mcisearchbutton'))
  1470.  
  1471. const resultItems = await fandomProdApigeeSearch(query, current.type).catch(function (response) {
  1472. alert('Search failed!\n' + response.finalUrl + '\nStatus: ' + response.status + '\n' + response.responseText ? response.responseText.substring(0, 500) : 'Empty response')
  1473. })
  1474.  
  1475. const results = []
  1476. resultItems.forEach(item => {
  1477. let img = `<svg class="mcdiv123_image_placeholder" viewBox="0 0 176 40"">
  1478. <path d="M17.2088 32.937L20.6188 29.527L14.0522 22.9604C13.7757 22.6839 13.4762 22.3383 13.3149 21.9466C12.9462 21.1632 12.7849 19.942 13.6835 19.0434C14.7895 17.9375 16.2641 18.3983 17.6926 19.8268L24.0058 26.14L27.4159 22.73L20.8262 16.1403C20.5497 15.8638 20.2271 15.4491 20.0659 15.1034C19.6281 14.2049 19.6511 13.0758 20.4576 12.2694C21.5866 11.1404 23.0612 11.5551 24.6971 13.191L30.8259 19.3199L34.236 15.9099L27.6002 9.27409C24.2362 5.91013 21.0796 6.02534 18.9138 8.19118C18.0843 9.02065 17.5774 9.8962 17.324 10.887C17.1166 11.7395 17.0475 12.6841 17.2318 13.6979L17.1857 13.744C15.5268 13.0528 13.6374 13.4675 12.1859 14.9191C10.2504 16.8545 10.3196 18.9052 10.55 20.1033L10.4809 20.1724L8.79888 18.813L5.84965 21.7622C6.88648 22.7069 8.1307 23.859 9.53619 25.2645L17.2088 32.937V32.937Z"></path> <path d="M19.9822 8.05032e-06C14.6789 0.00472041 9.59462 2.11554 5.84741 5.86828C2.10021 9.62102 -0.00310998 14.7084 3.45157e-06 20.0117C0.00307557 25.315 2.11239 30.4 5.86407 34.1484C9.61575 37.8968 14.7026 40.0016 20.006 40C25.3093 39.9984 30.3949 37.8906 34.1443 34.14C37.8938 30.3893 40.0001 25.3031 40 19.9998V19.9764C39.9938 14.6731 37.8814 9.58935 34.1275 5.8432C30.3736 2.09705 25.2855 -0.00474688 19.9822 8.05032e-06ZM19.8908 4.27438C24.0447 4.27063 28.0301 5.91689 30.9704 8.85113C33.9107 11.7854 35.5652 15.7673 35.57 19.9212V19.9393C35.57 24.0932 33.9201 28.0769 30.9833 31.0145C28.0465 33.9522 24.0632 35.6031 19.9093 35.6043C15.7555 35.6055 11.7712 33.9569 8.83271 31.0209C5.89421 28.085 4.24207 24.1022 4.23964 19.9484C4.23727 15.7946 5.88474 11.8099 8.81975 8.87064C11.7548 5.93134 15.737 4.27808 19.8908 4.27438Z"></path> <path d="M46.5464 27.9426H51.1377V19.1013C51.1377 18.7291 51.1687 18.2948 51.3238 17.9225C51.603 17.147 52.3165 16.2163 53.5264 16.2163C55.0154 16.2163 55.6979 17.5192 55.6979 19.4426V27.9426H60.2891V19.0703C60.2891 18.6981 60.3512 18.2017 60.4753 17.8605C60.7855 16.9608 61.561 16.2163 62.6468 16.2163C64.1669 16.2163 64.8804 17.4882 64.8804 19.6908V27.9426H69.4716V19.0083C69.4716 14.4791 67.2691 12.4316 64.353 12.4316C63.2362 12.4316 62.3056 12.6798 61.468 13.1762C60.7545 13.6105 60.072 14.1999 59.5136 15.0065H59.4516C58.8001 13.4243 57.249 12.4316 55.2946 12.4316C52.6888 12.4316 51.3548 13.8587 50.7034 14.8203H50.6103L50.3932 12.7729H46.4224C46.4844 14.1068 46.5464 15.72 46.5464 17.6123V27.9426V27.9426Z"></path> <path d="M85.8077 21.8623C85.8697 21.5211 85.9628 20.8075 85.9628 20.001C85.9628 16.2473 84.1015 12.4316 79.2 12.4316C73.9263 12.4316 71.5376 16.6816 71.5376 20.5284C71.5376 25.2747 74.4847 28.2838 79.6343 28.2838C81.6817 28.2838 83.5741 27.9426 85.1252 27.3221L84.5047 24.1269C83.2328 24.5302 81.9299 24.7473 80.3168 24.7473C78.1142 24.7473 76.1909 23.8167 76.0358 21.8623H85.8077ZM76.0047 18.636C76.1288 17.3641 76.9354 15.5649 78.9208 15.5649C81.0923 15.5649 81.5887 17.4882 81.5887 18.636H76.0047Z"></path> <path d="M88.617 9.48442V12.7727H86.6006V16.2472H88.617V22.4516C88.617 24.5921 89.0513 26.0501 89.9199 26.9498C90.6645 27.7253 91.9363 28.2837 93.4564 28.2837C94.7904 28.2837 95.9071 28.0976 96.5276 27.8494L96.4966 24.2819C96.1553 24.3439 95.69 24.4059 95.1006 24.4059C93.6736 24.4059 93.2393 23.5684 93.2393 21.7381V16.2472H96.6207V12.7727H93.2393V8.42969L88.617 9.48442V9.48442Z"></path> <path d="M111.213 18.9773C111.213 15.4097 109.6 12.4316 104.543 12.4316C101.782 12.4316 99.704 13.1762 98.6492 13.7656L99.5179 16.8057C100.511 16.1853 102.155 15.6579 103.706 15.6579C106.032 15.6579 106.467 16.8057 106.467 17.6123V17.8294C101.1 17.7984 97.5635 19.6908 97.5635 23.6305C97.5635 26.0502 99.3938 28.2838 102.465 28.2838C104.264 28.2838 105.815 27.6324 106.808 26.4225H106.901L107.18 27.9426H111.43C111.275 27.105 111.213 25.709 111.213 24.251V18.9773V18.9773ZM106.622 22.4207C106.622 22.6999 106.591 22.9791 106.529 23.2273C106.219 24.1889 105.257 24.9645 104.078 24.9645C103.023 24.9645 102.217 24.3751 102.217 23.1652C102.217 21.3349 104.14 20.7455 106.622 20.7765V22.4207V22.4207Z"></path> <path d="M125.003 24.0648C124.289 24.3751 123.421 24.5612 122.304 24.5612C120.008 24.5612 118.147 23.1032 118.147 20.3112C118.116 17.8294 119.729 16.0612 122.211 16.0612C123.452 16.0612 124.289 16.2784 124.848 16.5265L125.592 13.0211C124.6 12.6488 123.235 12.4316 121.994 12.4316C116.348 12.4316 113.308 16.0612 113.308 20.4973C113.308 25.2747 116.441 28.2838 121.342 28.2838C123.142 28.2838 124.724 27.9426 125.561 27.5703L125.003 24.0648Z"></path> <path d="M127.373 27.9426H132.088V20.2492C132.088 19.8769 132.119 19.5046 132.181 19.1944C132.491 17.7364 133.67 16.8057 135.407 16.8057C135.935 16.8057 136.338 16.8678 136.679 16.9608V12.4937C136.338 12.4316 136.121 12.4316 135.686 12.4316C134.228 12.4316 132.367 13.3623 131.592 15.5649H131.468L131.312 12.7729H127.249C127.311 14.0758 127.373 15.5338 127.373 17.7674V27.9426V27.9426Z"></path> <path d="M143.042 27.9424V12.7727H138.327V27.9424H143.042ZM140.685 6.16504C139.165 6.16504 138.172 7.18877 138.203 8.55373C138.172 9.85665 139.165 10.9114 140.654 10.9114C142.205 10.9114 143.197 9.85665 143.197 8.55373C143.166 7.18877 142.205 6.16504 140.685 6.16504Z"></path> <path d="M146.661 9.48442V12.7727H144.645V16.2472H146.661V22.4516C146.661 24.5921 147.095 26.0501 147.964 26.9498C148.708 27.7253 149.98 28.2837 151.5 28.2837C152.834 28.2837 153.951 28.0976 154.572 27.8494L154.541 24.2819C154.199 24.3439 153.734 24.4059 153.145 24.4059C151.718 24.4059 151.283 23.5684 151.283 21.7381V16.2472H154.665V12.7727H151.283V8.42969L146.661 9.48442Z"></path> <path d="M161.316 27.9424V12.7727H156.6V27.9424H161.316ZM158.958 6.16504C157.438 6.16504 156.445 7.18877 156.476 8.55373C156.445 9.85665 157.438 10.9114 158.927 10.9114C160.478 10.9114 161.471 9.85665 161.471 8.55373C161.44 7.18877 160.478 6.16504 158.958 6.16504V6.16504Z"></path> <path d="M175.11 24.0648C174.396 24.3751 173.528 24.5612 172.411 24.5612C170.115 24.5612 168.254 23.1032 168.254 20.3112C168.223 17.8294 169.836 16.0612 172.318 16.0612C173.559 16.0612 174.396 16.2784 174.955 16.5265L175.699 13.0211C174.707 12.6488 173.342 12.4316 172.101 12.4316C166.455 12.4316 163.415 16.0612 163.415 20.4973C163.415 25.2747 166.548 28.2838 171.449 28.2838C173.248 28.2838 174.831 27.9426 175.668 27.5703L175.11 24.0648Z"></path>
  1479. </svg>`
  1480. if (item.images.length > 0) {
  1481. img = `<img class="mcdiv123_cover" src="https://www.metacritic.com/a/img/${item.images[0].bucketType}${item.images[0].bucketPath}">`
  1482. }
  1483.  
  1484. let score = ''
  1485. if ('criticScoreSummary' in item && 'score' in item.criticScoreSummary && item.criticScoreSummary.score > 0) {
  1486. const bgColor = badgeColor(item.criticScoreSummary.score, item.type)
  1487. score = `<div class="mcdiv123_score_badge" style="background: ${bgColor}">${item.criticScoreSummary.score}</div>`
  1488. }
  1489.  
  1490. results.push(`
  1491. <div>
  1492. <div class="floatleft">
  1493. ${img}
  1494. </div>
  1495. <div class="floatleft resultcontent">
  1496. <a style="font-size:17px" href="${item.metacriticUrl}">
  1497. ${item.title}
  1498. </a>
  1499. <span style="font-weight:800;">${item.premiereYear ? item.premiereYear : (item.releaseDate ? item.releaseDate.substring(0, 4) : '')}</span>
  1500. ${score}
  1501. <div>
  1502. ${item.genres.map(g => g.name).join(' • ')}
  1503. <br>
  1504. <span class="mcdiv_release_date">${item.releaseDate ? item.releaseDate : ''}</span>
  1505. <div class="mcdiv_desc">
  1506. ${item.description}
  1507. </div>
  1508. </div>
  1509. </div>
  1510. <div class="floatleft mcdiv123_correct_entry" title="Assist us: This is the correct entry!">&check;</div>
  1511. <div class="clear:left"></div>
  1512. </div>
  1513. `
  1514. )
  1515. })
  1516.  
  1517. const websiteSearchUrl = `${baseURL}search/${encodeURIComponent(query)}/`
  1518.  
  1519. if (results && results.length > 0) {
  1520. // Show results
  1521. loader.remove()
  1522.  
  1523. const accept = function (ev) {
  1524. const parentDiv = $(this).closest('.result')
  1525. const a = parentDiv.find("a[href*='metacritic.com']")
  1526. const metaurl = a.attr('href')
  1527. const docurl = document.location.href
  1528.  
  1529. const resultDivParent = parentDiv.parent()
  1530. resultDivParent.html('')
  1531. resultDivParent.append(loader)
  1532.  
  1533. removeFromBlacklist(docurl, metaurl).then(function () {
  1534. addToMap(docurl, metaurl).then(function () {
  1535. current.metaurl = metaurl
  1536. loadMetacriticUrl().then(() => loader.remove())
  1537. })
  1538. })
  1539. }
  1540. const denyAll = function (ev) {
  1541. const docurl = document.location.href
  1542. $('#mcdiv123searchresults').find("div.result a[href*='metacritic.com']").each(function () {
  1543. addToBlacklist(docurl, this.href)
  1544. })
  1545. }
  1546.  
  1547. const resultdiv = $('#mcdiv123searchresults').length
  1548. ? $('#mcdiv123searchresults').html('')
  1549. : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1550. results.forEach(function (html) {
  1551. const singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html) + '<div style="clear:left"></div>').appendTo(resultdiv)
  1552. singleresult.find('.mcdiv123_correct_entry').click(accept)
  1553. })
  1554. resultdiv.find('.metascore_w.album').removeClass('album') // Remove some classes
  1555. resultdiv.find('.must-see').remove() // Remove some elements
  1556.  
  1557. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1558. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + websiteSearchUrl + '" title="Open Metacritic">' + decodeURI(websiteSearchUrl.replace('https://www.', '')) + '</a>').appendTo(sub)
  1559. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1560. document.body.removeChild(this.parentNode.parentNode)
  1561. })
  1562. $('<span class="mcdiv123_incorrect" title="Assist us: None of the above is the correct item!">&cross;</span>').appendTo(sub).click(function () { if (confirm('None of the above is the correct item\nConfirm?')) denyAll() })
  1563. } else {
  1564. // No results
  1565. loader.remove()
  1566. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1567. resultdiv.html('No search results.')
  1568.  
  1569. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1570. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + websiteSearchUrl + '" title="Open Metacritic">' + decodeURI(websiteSearchUrl.replace('https://www.', '')) + '</a>').appendTo(sub)
  1571. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1572. document.body.removeChild(this.parentNode.parentNode)
  1573. })
  1574. }
  1575. }
  1576.  
  1577. function showHoverInfo (response, orgMetaUrl) {
  1578. const html = fixMetacriticURLs(response.responseText)
  1579. const time = new Date(response.time)
  1580. const url = response.finalUrl
  1581.  
  1582. $('#mcdiv123').remove()
  1583. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1584. div.css({
  1585. bottom: 0,
  1586. left: 0
  1587. })
  1588.  
  1589. div.css('transform-origin', 'bottom left')
  1590. GM.getValue('position', false).then(function (s) {
  1591. if (s) {
  1592. div.css({
  1593. top: '',
  1594. left: '',
  1595. bottom: '',
  1596. right: ''
  1597. })
  1598. const parsedPosition = JSON.parse(s)
  1599. div.css(parsedPosition)
  1600. div.css('transform-origin', Object.keys(parsedPosition).join(' '))
  1601. }
  1602. })
  1603. onSizeChanged()
  1604.  
  1605. // Functions for communication between page and iframe
  1606. // Mozilla can access parent.document
  1607. // Chrome can use postMessage()
  1608. let frameStatus = false // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  1609. async function tryToLoadMoreMetacriticDetails (myframe) {
  1610. console.log('ShowMetacriticRatings: tryToLoadMoreMetacriticDetails current', current)
  1611. if (!current.metaurl) {
  1612. return
  1613. }
  1614.  
  1615. let url = current.metaurl
  1616. if (url.endsWith('/')) {
  1617. url = url + 'details/'
  1618. } else {
  1619. url = url + '/details/'
  1620. }
  1621.  
  1622. const response = await asyncRequest({ url })
  1623. const doc = domParser().parseFromString(response.responseText, 'text/html')
  1624.  
  1625. const titleA = doc.querySelector('.c-productSubpageHeader_back')
  1626. titleA.querySelectorAll('.c-productSubpageHeader_backIcon').forEach(e => e.remove())
  1627. const titleHTML = titleA.outerHTML
  1628.  
  1629. const image = doc.querySelector('picture img')
  1630. image.style.display = ''
  1631. const imageHTML = image.outerHTML
  1632.  
  1633. let detailsTable = Array.from(doc.querySelectorAll('.c-movieDetails_sectionContainer')).map(e => Array.from(e.children).map(e => e.textContent.trim()))
  1634.  
  1635. detailsTable = detailsTable.filter(columns => {
  1636. if (columns[0].search(/release date/i) !== -1) {
  1637. return true
  1638. }
  1639. if (columns[0].search(/genres/i) !== -1) {
  1640. return true
  1641. }
  1642. if (columns[0].search(/developer/i) !== -1) {
  1643. return true
  1644. }
  1645. if (columns[0].search(/publisher/i) !== -1) {
  1646. return true
  1647. }
  1648. return false
  1649. }).map(columns => columns.join(': '))
  1650.  
  1651. const html = imageHTML + '<br>' + titleHTML + '<br>' + detailsTable.join('<br>')
  1652.  
  1653. myframe.contentWindow.postMessage({
  1654. mcimessage_addhtml: true,
  1655. mcimessage_element_id: 'metacritic_extra_data',
  1656. mcimessage_element_style: 'display:none;',
  1657. mcimessage_html: html
  1658. }, '*')
  1659.  
  1660. // Wait to show the extra data to avoid making the frame to big
  1661. window.setTimeout(function () {
  1662. myframe.contentWindow.postMessage({
  1663. mcimessage_showelement: true,
  1664. mcimessage_selector: '#metacritic_extra_data'
  1665. }, '*')
  1666. }, 1000)
  1667. }
  1668. function loadExternalImage (url, myframe) {
  1669. // Load external image, bypass CSP
  1670. GM.xmlHttpRequest({
  1671. method: 'GET',
  1672. url,
  1673. responseType: 'arraybuffer',
  1674. onload: function (response) {
  1675. myframe.contentWindow.postMessage({
  1676. mcimessage_imgLoaded: true,
  1677. mcimessage_imgData: response.response,
  1678. mcimessage_imgOrgSrc: url
  1679. }, '*')
  1680. }
  1681. })
  1682. }
  1683. const functions = {
  1684. parent: function () {
  1685. const f = parent.document.getElementById('mciframe123')
  1686. let lastdiff = -200000
  1687. window.addEventListener('message', function (e) {
  1688. if (typeof e.data !== 'object') {
  1689. return
  1690. } else if ('mcimessage0' in e.data) {
  1691. frameStatus = true // Frame content was loaded successfully
  1692. tryToLoadMoreMetacriticDetails(f)
  1693. } else if ('mcimessage1' in e.data) {
  1694. f.style.width = parseInt(f.style.width) + 5 + 'px'
  1695. if (e.data.heightdiff === lastdiff) {
  1696. f.style.height = parseInt(f.style.height) + 10 + 'px'
  1697. }
  1698. lastdiff = e.data.heightdiff
  1699. } else if ('mcimessage2' in e.data) {
  1700. f.style.height = parseInt(f.style.height) + 10 + 'px'
  1701. } else if ('mcimessage_loadImg' in e.data) {
  1702. loadExternalImage(e.data.mcimessage_imgUrl, f)
  1703. } else {
  1704. return
  1705. }
  1706. if (f.contentWindow != null) {
  1707. f.contentWindow.postMessage({
  1708. mcimessage3: true,
  1709. mciframe123_clientHeight: f.clientHeight,
  1710. mciframe123_clientWidth: f.clientWidth
  1711. }, '*')
  1712. }
  1713. })
  1714. },
  1715. frame: function () {
  1716. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1717.  
  1718. let i = 0
  1719. window.addEventListener('message', function (e) {
  1720. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1721. // Load external image
  1722. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1723. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1724. const urlCreator = window.URL || window.webkitURL
  1725. const imageUrl = urlCreator.createObjectURL(blob)
  1726. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1727. img.src = imageUrl
  1728. }
  1729. if (typeof e.data === 'object' && 'mcimessage_addhtml' in e.data) {
  1730. const div = document.body.appendChild(document.createElement('div'))
  1731. div.setAttribute('id', e.data.mcimessage_element_id)
  1732. div.setAttribute('style', e.data.mcimessage_element_style)
  1733. div.innerHTML = e.data.mcimessage_html
  1734. }
  1735. if (typeof e.data === 'object' && 'mcimessage_showelement' in e.data) {
  1736. document.querySelector(e.data.mcimessage_selector).style.display = ''
  1737. }
  1738.  
  1739. if (!('mcimessage3' in e.data)) return
  1740.  
  1741. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1742. parent.postMessage({ mcimessage2: 1 }, '*')
  1743. i++
  1744. }
  1745. if (i >= 100) {
  1746. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1747. i = 0
  1748. }
  1749. })
  1750. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1751. }
  1752.  
  1753. }
  1754.  
  1755. const css = `
  1756. #hover_div_a20230915{font-family:sans-serif;color:#262626;font-size:1rem;line-height:1.625rem}#hover_div_a202309:hover15 a,#hover_div_a20230915 a:hover{text-decoration:none}#hover_div_a20230915 a:hover{color:#09f}#hover_div_a20230915 a{color:#000;text-decoration:none;}#hover_div_a20230915 a:focus{color:grey}#hover_div_a20230915 .g-border-black,#hover_div_a20230915 .g-border-gray100{border-color:#000}#hover_div_a20230915 .g-color-black,#hover_div_a20230915 .g-color-gray100{color:#000}#hover_div_a20230915 .g-border-gray98{border-color:#191919}#hover_div_a20230915 .g-color-gray98{color:#191919}#hover_div_a20230915 .g-border-gray90{border-color:#262626}#hover_div_a20230915 .g-color-gray90{color:#262626}#hover_div_a20230915 .g-border-gray80{border-color:#404040}#hover_div_a20230915 .g-color-gray80{color:#404040}#hover_div_a20230915 .g-border-gray70{border-color:#666}#hover_div_a20230915 .g-color-gray70{color:#666}#hover_div_a20230915 .g-border-gray60{border-color:grey}#hover_div_a20230915 .g-color-gray60{color:grey}#hover_div_a20230915 .g-border-gray50{border-color:#999}#hover_div_a20230915 .g-color-gray50{color:#999}#hover_div_a20230915 .g-border-gray40{border-color:#bfbfbf}#hover_div_a20230915 .g-color-gray40{color:#bfbfbf}#hover_div_a20230915 .g-border-gray30{border-color:#d8d8d8}#hover_div_a20230915 .g-color-gray30{color:#d8d8d8}#hover_div_a20230915 .g-border-gray20{border-color:#e6e6e6}#hover_div_a20230915 .g-color-gray20{color:#e6e6e6}#hover_div_a20230915 .g-border-gray10{border-color:#f2f2f2}#hover_div_a20230915 .g-color-gray10{color:#f2f2f2}#hover_div_a20230915 .g-border-gray0,#hover_div_a20230915 .g-border-white{border-color:#fff}#hover_div_a20230915 .g-color-gray0,#hover_div_a20230915 .g-color-white{color:#fff}#hover_div_a20230915 .g-border-red{border-color:#eb0036}#hover_div_a20230915 .g-color-red{color:#eb0036}#hover_div_a20230915 .g-border-green{border-color:#01b44f}#hover_div_a20230915 .g-color-green{color:#01b44f}#hover_div_a20230915 .g-width-large{width:1.5rem}#hover_div_a20230915 .g-height-large{height:1.5rem}#hover_div_a20230915 .g-width-100{width:100%}#hover_div_a20230915 .g-height-100{height:100%}#hover_div_a20230915 .g-text-large{font-size:1.5rem;line-height:2rem}#hover_div_a20230915 .g-text-xxsmall{font-size:xx-small}#hover_div_a20230915 .g-text-bold{font-weight:700}#hover_div_a20230915 .g-text-link{text-decoration:underline}#hover_div_a20230915 .u-block{display:block}#hover_div_a20230915 .u-flexbox{display:flex}#hover_div_a20230915 .u-flexbox-column{display:flex;flex-direction:column}#hover_div_a20230915 .u-flexbox-justifyCenter{justify-content:center}#hover_div_a20230915 .u-flexbox-alignCenter{align-items:center}#hover_div_a20230915 .u-grid{display:grid;grid-gap:0;grid-gap:var(--grid-gap,0)}#hover_div_a20230915 .u-grid-2column{-ms-grid-columns:50% 50%;display:grid;grid-template:auto/repeat(2,1fr)}#hover_div_a20230915 .u-grid-3column{-ms-grid-columns:33.3% 33.3% 33.3%;display:grid;grid-template:auto/repeat(3,1fr)}#hover_div_a20230915 .u-grid-4column{-ms-grid-columns:25% 25% 25% 25%;display:grid;grid-template:auto/repeat(4,1fr)}#hover_div_a20230915 .u-grid-5column{-ms-grid-columns:20% 20% 20% 20% 20%;display:grid;grid-template:auto/repeat(5,1fr)}#hover_div_a20230915 .u-grid-7column{-ms-grid-columns:14.2857% 14.2857% 14.2857% 14.2857% 14.2857% 14.2857% 14.2857%;display:grid;grid-template:auto/repeat(7,1fr)}#hover_div_a20230915 .u-grid-column-span2{grid-column-end:span 2}#hover_div_a20230915 .u-grid-column-span3{grid-column-end:span 3}#hover_div_a20230915 .u-grid-column-span4{grid-column-end:span 4}#hover_div_a20230915 .u-text-center{text-align:center}#hover_div_a20230915 .c-siteReviewScore_large{border-radius:0.5rem;height:4rem;width:4rem;font-size:2rem}#hover_div_a20230915 .c-siteReviewScore_user{border-radius:50%}#hover_div_a20230915 .c-reviewsStats{padding:1rem 0;grid-template-columns:1fr 1fr 1fr;justify-content:space-evenly;font-size:0.75rem;line-height:1.25rem}#hover_div_a20230915 div[class^=c-reviewsStats_]:first-child,#hover_div_a20230915 div[class^=c-reviewsStats_]:nth-child(2){border-right:0.0625rem solid #d8d8d8}#hover_div_a20230915 .c-ScoreCardGraph{overflow:hidden;white-space:nowrap}#hover_div_a20230915 .c-ScoreCardGraph > div{margin-left:0.25rem;padding:0 0.25rem;text-align:right;height:0.5rem;min-width:2rem;line-height:1rem}#hover_div_a20230915 .c-ScoreCardGraph > div:first-child{margin-left:0}#hover_div_a20230915 .c-ScoreCardGraph_scoreTitle{letter-spacing:0.25rem}#hover_div_a20230915 .c-ScoreCardGraph_scoreSentiment{color:#00ce7a}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphPositive{background:#00ce7a;border-radius:0.25rem 0 0 0.25rem}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphNeutral{background:#ffbd3f}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphNegative{background:#ff6874;border-radius:0 0.25rem 0.25rem 0}#hover_div_a20230915 .gray{background:#bfbfbf;height:1rem;display:inline-block}#hover_div_a20230915 .c-ScoreCard_scoreContent{display:flex;align-content:flex-start;flex-wrap:nowrap;grid-gap:10px;gap:10px;width:100%;justify-content:space-between;align-items:stretch}#hover_div_a20230915 .c-ScoreCard_scoreContent_text{line-height:normal;display:flex;flex-direction:column;justify-content:space-between}#hover_div_a20230915 .c-ScoreCard_scoreContent_number > .c-siteReviewScore_background-critic_large,#hover_div_a20230915 .c-ScoreCard_scoreContent_number > .c-siteReviewScore_background-critic_large .c-siteReviewScore_large{width:4rem;height:4rem}#hover_div_a20230915 .c-ScoreCard_scoreSentiment{font-size:1rem;line-height:1.25rem;text-transform:capitalize}#hover_div_a20230915 .c-ScoreCard_scoreTitle{letter-spacing:0.25rem}#hover_div_a20230915 .c-reviewsOverview_overviewDetails{grid-template-columns:1fr 1fr;grid-gap:1.25rem;border-top:1px solid #262626;margin-top:auto;padding:2px}#hover_div_a20230915 .c-reviewsOverview_overviewDetails:first-child{border-top:0 solid #262626}#hover_div_a20230915 .c-siteReviewScore_green{background:#00ce7a}#hover_div_a20230915 .c-siteReviewScore_yellow{background:#ffbd3f}#hover_div_a20230915 .c-siteReviewScore_red{background:#ff6874}#hover_div_a20230915 .c-siteReviewScore_grey{background:#404040}#hover_div_a20230915 .c-siteReviewScore_tbdCritic,#hover_div_a20230915 .c-siteReviewScore_tbdUser{border-width:0.125rem;border-style:solid}#hover_div_a20230915 .o-inlineScore{border-radius:0.25rem;font-size:1.25rem;font-weight:700;color:#404040;width:2.5rem;height:2.5rem;display:inline-flex;justify-content:center;align-items:center;text-decoration:none!important}#hover_div_a20230915 .o-inlineScore-green{background:#00ce7a}#hover_div_a20230915 .o-inlineScore-yellow{background:#ffbd3f}#hover_div_a20230915 .o-inlineScore-red{background:#ff6874}#hover_div_a20230915 .o-inlineScore-tbd{border:1px solid grey}#hover_div_a20230915 .u-pointer{cursor:pointer}#hover_div_a20230915 .c-siteReviewScore_green{background:#00ce7a}#hover_div_a20230915 .c-siteReviewScore_yellow{background:#ffbd3f}#hover_div_a20230915 .c-siteReviewScore_red{background:#ff6874}#hover_div_a20230915 .c-siteReviewScore_grey{background:#404040}#hover_div_a20230915 .c-siteReviewScore_tbdCritic,#hover_div_a20230915 .c-siteReviewScore_tbdUser{border-width:0.125rem;border-style:solid}#hover_div_a20230915{max-width:440px}
  1757. `
  1758.  
  1759. const cssDark = `
  1760. html {
  1761. scrollbar-color: #003c09 #00ce7a;
  1762. }
  1763. *::-webkit-scrollbar-thumb {
  1764. background-color: #003c09;
  1765. }
  1766. body {
  1767. background:#262626;
  1768. color:white;
  1769. }
  1770.  
  1771. #metacritic_extra_data {
  1772. color:white;
  1773. }
  1774. #metacritic_extra_data a:hover {
  1775. color: white;
  1776. }
  1777. #metacritic_extra_data a {
  1778. color: #5799ef;
  1779. text-decoration: none;
  1780. }
  1781.  
  1782. #hover_div_a20230915 {
  1783. color: #d1d1d1;
  1784. }
  1785. #hover_div_a20230915 a:hover {
  1786. color: #09f;
  1787. }
  1788. #hover_div_a20230915 a {
  1789. color: #ffffff;
  1790. text-decoration: none;
  1791. }
  1792. #hover_div_a20230915 a:focus {
  1793. color: rgb(184, 184, 184);
  1794. }
  1795. #hover_div_a20230915 .g-border-black,
  1796. #hover_div_a20230915 .g-border-gray100 {
  1797. border-color: #ffffff;
  1798. }
  1799. #hover_div_a20230915 .g-color-black,
  1800. #hover_div_a20230915 .g-color-gray100 {
  1801. color: #ffffff;
  1802. }
  1803. #hover_div_a20230915 .g-border-gray98 {
  1804. border-color: #d6d6d6;
  1805. }
  1806. #hover_div_a20230915 .g-color-gray98 {
  1807. color: #d6d6d6;
  1808. }
  1809. #hover_div_a20230915 .g-border-gray90 {
  1810. border-color: #d3d3d3;
  1811. }
  1812. #hover_div_a20230915 .g-color-gray90 {
  1813. color: #d3d3d3;
  1814. }
  1815. #hover_div_a20230915 .g-border-gray80 {
  1816. border-color: #404040;
  1817. }
  1818. #hover_div_a20230915 .g-color-gray80 {
  1819. color: #404040;
  1820. }
  1821. #hover_div_a20230915 .g-border-gray70 {
  1822. border-color: #666;
  1823. }
  1824. #hover_div_a20230915 .g-color-gray70 {
  1825. color: #666;
  1826. }
  1827. #hover_div_a20230915 .g-border-gray60 {
  1828. border-color: grey;
  1829. }
  1830. #hover_div_a20230915 .g-color-gray60 {
  1831. color: grey;
  1832. }
  1833. #hover_div_a20230915 .c-reviewsOverview_overviewDetails {
  1834. border-top: 1px solid #d1d1d1;
  1835. }
  1836. #hover_div_a20230915 .c-reviewsOverview_overviewDetails:first-child {
  1837. border-top: 0 solid #d1d1d1;
  1838. }
  1839. #hover_div_a20230915 .c-siteReviewScore_grey {
  1840. background: #404040;
  1841. }
  1842. #hover_div_a20230915 .o-inlineScore {
  1843. color: #404040;
  1844. }
  1845. #hover_div_a20230915 .o-inlineScore-tbd {
  1846. border: 1px solid grey;
  1847. }
  1848. #hover_div_a20230915 .u-pointer {
  1849. cursor: pointer;
  1850. }
  1851. #hover_div_a20230915 .c-siteReviewScore_grey {
  1852. background: #404040;
  1853. }
  1854. `
  1855.  
  1856. let framesrc = 'data:text/html,'
  1857. framesrc += encodeURIComponent(`<!DOCTYPE html>
  1858. <html lang="en">
  1859. <head>
  1860. <meta charset="utf-8">
  1861. <title>Metacritic info</title>
  1862. <style>
  1863. html {
  1864. scrollbar-width: thin;
  1865. scrollbar-color: #dfdfdf white;
  1866. }
  1867. /* Chrome, Edge, and Safari */
  1868. *::-webkit-scrollbar {
  1869. width: 10px;
  1870. }
  1871.  
  1872. *::-webkit-scrollbar-track {
  1873. background: transparent;
  1874. }
  1875.  
  1876. *::-webkit-scrollbar-thumb {
  1877. background-color: #dfdfdf;
  1878. border-radius: 10px;
  1879. border: 0px none transparent;
  1880. }
  1881.  
  1882. body {
  1883. margin:0px;
  1884. padding:0px;
  1885. background:white;
  1886. }
  1887.  
  1888. ${css}
  1889.  
  1890. #metacritic_extra_data {
  1891. font-family: sans-serif;
  1892. color:black;
  1893. }
  1894.  
  1895. #metacritic_extra_data a:hover {
  1896. color: #054585;
  1897. }
  1898. #metacritic_extra_data a {
  1899. color: #06c;
  1900. text-decoration: none;
  1901. }
  1902.  
  1903. @media (prefers-color-scheme: dark) {
  1904. ${cssDark}
  1905. }
  1906.  
  1907. ${
  1908. darkTheme ? cssDark : ''
  1909. }
  1910.  
  1911. </style>
  1912. <script>
  1913. const failedImages = {};
  1914. function detectCSP(img) {
  1915. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {
  1916. return true;
  1917. }
  1918. return false;
  1919. }
  1920. function findCSPerrors() {
  1921. const imgs = document.querySelectorAll("img");
  1922. for(let i = 0; i < imgs.length; i++) {
  1923. if(imgs[i].complete && detectCSP(imgs[i])) {
  1924. fixCSP(imgs[i]);
  1925. }
  1926. }
  1927. }
  1928. function fixCSP(img) {
  1929. console.debug("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");
  1930. failedImages[img.src] = img;
  1931. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*");
  1932. }
  1933. function on_load() {
  1934. (${functions.frame.toString()})();
  1935. window.setTimeout(findCSPerrors, 500);
  1936. }
  1937. </script>
  1938. </head>
  1939. <body onload="on_load();">
  1940. <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">
  1941. <div class="hover_content">${html}</div>
  1942. </div>
  1943. </body>
  1944. </html>`)
  1945.  
  1946. const frame = $('<iframe></iframe>')
  1947. frame.attr('id', 'mciframe123')
  1948. frame.attr('src', framesrc)
  1949. frame.attr('scrolling', 'auto')
  1950. frame.css({
  1951. width: 440,
  1952. height: 110,
  1953. border: 'none',
  1954. opacity: '0.1',
  1955. transition: 'opacity 1s'
  1956. })
  1957. frame.appendTo(div)
  1958. window.setTimeout(function () {
  1959. frame.css('opacity', '1.0')
  1960. }, 1000)
  1961.  
  1962. window.setTimeout(function () {
  1963. if (!frameStatus) { // Loading frame content failed.
  1964. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1965. console.debug('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1966. $('head').append(`<style>${css}\n\n@media (prefers-color-scheme: dark) {\n${cssDark}\n}\n</style>`)
  1967. 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">
  1968. <div class="hover_content">${html}</div>
  1969. </div>`)
  1970. frame.replaceWith(noframe)
  1971. }
  1972. }, 2000)
  1973.  
  1974. functions.parent()
  1975.  
  1976. const sub = $('<div></div>').appendTo(div)
  1977. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1978. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1979. $('<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 () {
  1980. const metaurl = $(this).data('url')
  1981. addToTemporaryBlacklist(metaurl)
  1982. document.body.removeChild(this.parentNode.parentNode)
  1983. })
  1984.  
  1985. $('<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 () {
  1986. const docurl = document.location.href
  1987. const metaurl = $(this).data('url')
  1988. addToMap(docurl, metaurl).then(function (r) {
  1989. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1990. })
  1991. })
  1992. $('<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 () {
  1993. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1994. const docurl = document.location.href
  1995. const metaurl = $(this).data('url')
  1996. addToBlacklist(docurl, metaurl).then(function (r) {
  1997. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1998. })
  1999.  
  2000. openSearchBox(true)
  2001. })
  2002.  
  2003. // Store response in cache:
  2004. if (!('cached' in response)) {
  2005. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  2006. }
  2007. }
  2008.  
  2009. function metacriticGeneralProductSetup () {
  2010. current.broadenCounter = 0
  2011. }
  2012.  
  2013. const metacritic = {
  2014. mapped: function metacriticMapped (docurl, product, metaurl, type, searchTerm) {
  2015. // url was in the map/whitelist
  2016. current.data = searchTerm ? [searchTerm] : []
  2017. current.docurl = docurl
  2018. current.product = product
  2019. current.metaurl = metaurl
  2020. current.type = type
  2021. current.searchTerm = searchTerm || null
  2022. loadMetacriticUrl()
  2023. },
  2024. music: function metacriticMusic (docurl, product, artistname, albumname) {
  2025. current.data = [albumname.trim(), artistname.trim()]
  2026. artistname = name2metacritic(artistname)
  2027. albumname = albumname.replace('&', ' ')
  2028. albumname = name2metacritic(albumname)
  2029. current.docurl = docurl
  2030. current.product = product
  2031. current.metaurl = baseURLmusic + albumname + '/' + artistname
  2032. current.type = 'music'
  2033. current.searchTerm = albumname + '/' + artistname
  2034. loadMetacriticUrl()
  2035. },
  2036. movie: function metacriticMovie (docurl, product, moviename) {
  2037. current.data = [moviename.trim()]
  2038. moviename = name2metacritic(moviename)
  2039. current.docurl = docurl
  2040. current.product = product
  2041. current.metaurl = baseURLmovie + moviename
  2042. current.type = 'movie'
  2043. current.searchTerm = moviename
  2044. loadMetacriticUrl()
  2045. },
  2046. tv: function metacriticTv (docurl, product, seriesname) {
  2047. current.data = [seriesname.trim()]
  2048. seriesname = name2metacritic(seriesname)
  2049. current.docurl = docurl
  2050. current.product = product
  2051. current.metaurl = baseURLtv + seriesname
  2052. current.type = 'tv'
  2053. current.searchTerm = seriesname
  2054. loadMetacriticUrl()
  2055. },
  2056. pcgame: function metacriticPcgame (docurl, product, gamename) {
  2057. current.data = [gamename.trim()]
  2058. gamename = name2metacritic(gamename)
  2059. current.docurl = docurl
  2060. current.product = product
  2061. current.metaurl = baseURLpcgame + gamename
  2062. current.type = 'pcgame'
  2063. current.searchTerm = gamename
  2064. loadMetacriticUrl()
  2065. },
  2066. ps4game: function metacriticPs4game (docurl, product, gamename) {
  2067. current.data = [gamename.trim()]
  2068. gamename = name2metacritic(gamename)
  2069. current.docurl = docurl
  2070. current.product = product
  2071. current.metaurl = baseURLps4 + gamename
  2072. current.type = 'ps4game'
  2073. current.searchTerm = gamename
  2074. loadMetacriticUrl()
  2075. },
  2076. xonegame: function metacriticXonegame (docurl, product, gamename) {
  2077. current.data = [gamename.trim()]
  2078. gamename = name2metacritic(gamename)
  2079. current.docurl = docurl
  2080. current.product = product
  2081. current.metaurl = baseURLxone + gamename
  2082. current.type = 'xonegame'
  2083. current.searchTerm = gamename
  2084. loadMetacriticUrl()
  2085. }
  2086. }
  2087.  
  2088. const Always = () => true
  2089. const sites = {
  2090. bandcamp: {
  2091. host: ['bandcamp.com'],
  2092. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  2093. products: [{
  2094. condition: Always,
  2095. type: 'music',
  2096. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  2097. }]
  2098. },
  2099. itunes: {
  2100. host: ['itunes.apple.com'],
  2101. condition: Always,
  2102. products: [{
  2103. condition: () => ~document.location.href.indexOf('/movie/'),
  2104. type: 'movie',
  2105. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2106. },
  2107. {
  2108. condition: () => ~document.location.href.indexOf('/tv-season/'),
  2109. type: 'tv',
  2110. data: function () {
  2111. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2112. if (~name.indexOf(', Season')) {
  2113. name = name.split(', Season')[0]
  2114. }
  2115. return name
  2116. }
  2117. },
  2118. {
  2119. condition: () => ~document.location.href.indexOf('/album/'),
  2120. type: 'music',
  2121. data: function () {
  2122. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2123. const album = ld[0]
  2124. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2125. return [artist, album]
  2126. }
  2127. }]
  2128. },
  2129. 'music.apple': {
  2130. host: ['music.apple.com'],
  2131. condition: Always,
  2132. products: [{
  2133. condition: () => ~document.location.href.indexOf('/album/') && parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum')).length > 1,
  2134. type: 'music',
  2135. data: function () {
  2136. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2137. const album = ld[0]
  2138. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2139. return [artist, album]
  2140. }
  2141. }]
  2142. },
  2143. googleplay: {
  2144. host: ['play.google.com'],
  2145. condition: Always,
  2146. products: [
  2147. {
  2148. condition: () => ~document.location.href.indexOf('/album/'),
  2149. type: 'music',
  2150. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  2151. },
  2152. {
  2153. condition: () => ~document.location.href.indexOf('/movies/details/'),
  2154. type: 'movie',
  2155. data: () => document.querySelector('*[itemprop=name]').textContent
  2156. }
  2157. ]
  2158. },
  2159. imdb: {
  2160. host: ['imdb.com'],
  2161. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  2162. products: [
  2163. {
  2164. condition: () => document.querySelector('a[href*="/criticreviews/"'),
  2165. type: 'mapped',
  2166. data: async function () {
  2167. // This is used if there is a metacritic link on the imdb page
  2168. const criticsUrl = document.querySelector('a[href*="/criticreviews/"').href.toString()
  2169. const response = await asyncRequest({ url: criticsUrl }).catch(function (response) {
  2170. console.warn('ShowMetacriticRatings: Error imdb01\nurl=' + criticsUrl + '\nstatus=' + response.status)
  2171. })
  2172. const m = response.responseText.match(/(https:\/\/www\.metacritic\.com\/(\w+)\/[^?&"']+)/)
  2173. console.debug('ShowMetacriticRatings: Metacritic link found on imdb:', m[2], m[1])
  2174. const query = document.querySelector('[data-testid="hero__pageTitle"]') ? document.querySelector('[data-testid="hero__pageTitle"]').textContent : null
  2175. return [m[1], m[2], query]
  2176. }
  2177. },
  2178. {
  2179. condition: function () {
  2180. const e = document.querySelector("meta[property='og:type']")
  2181. if (e && e.content === 'video.movie') {
  2182. return true
  2183. } else if (document.querySelector('[data-testid="hero__pageTitle"]') && !document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  2184. return true
  2185. }
  2186. return false
  2187. },
  2188. type: 'movie',
  2189. data: async function () {
  2190. // If the page is not in English or the browser is not in English, request page in English.
  2191. // Then the title in <h1> will be the English title and Metacritic always uses the English title.
  2192. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  2193. const imdbID = document.location.pathname.match(/\/title\/(\w+)/)[1]
  2194. const homePageUrl = 'https://www.imdb.com/title/' + imdbID + '/?ref_=nv_sr_1'
  2195. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  2196. const langM = document.cookie.match(/lc-main=([^;]+)/)
  2197. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  2198. document.cookie = 'lc-main=en-US'
  2199. const response = await asyncRequest({
  2200. url: homePageUrl,
  2201. headers: {
  2202. 'Accept-Language': 'en-US,en'
  2203. }
  2204. }).catch(function (response) {
  2205. console.warn('ShowMetacriticRatings: Error imdb02\nurl=' + homePageUrl + '\nstatus=' + response.status)
  2206. })
  2207. document.cookie = 'lc-main=' + langBefore
  2208. // Extract <h1> title
  2209. const parts = response.responseText.split('</span></h1>')[0].split('>')
  2210. console.debug('ShowMetacriticRatings: Movie title from English page:', parts[parts.length - 1])
  2211. return parts[parts.length - 1]
  2212. } else if (document.querySelector('script[type="application/ld+json"]')) {
  2213. const ld = parseLDJSON(['name', 'alternateName'])
  2214. if (ld.length > 1 && ld[1]) {
  2215. console.debug('ShowMetacriticRatings: Movie ld+json alternateName', ld[1])
  2216. return ld[1]
  2217. }
  2218. console.debug('ShowMetacriticRatings: Movie ld+json name', ld[0])
  2219. return ld[0]
  2220. } else {
  2221. const m = document.title.match(/(.+?)\s+(\((\d+)\))? - /)
  2222. console.debug('ShowMetacriticRatings: Movie <title>', m[1])
  2223. return m[1]
  2224. }
  2225. }
  2226. },
  2227. {
  2228. condition: function () {
  2229. const e = document.querySelector("meta[property='og:type']")
  2230. if (e && e.content === 'video.tv_show') {
  2231. return true
  2232. } else if (document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  2233. return true
  2234. }
  2235. return false
  2236. },
  2237. type: 'tv',
  2238. data: async function () {
  2239. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  2240. const imdbID = document.location.pathname.match(/\/title\/(\w+)/)[1]
  2241. const homePageUrl = 'https://www.imdb.com/title/' + imdbID + '/?ref_=nv_sr_1'
  2242. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  2243. const langM = document.cookie.match(/lc-main=([^;]+)/)
  2244. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  2245. document.cookie = 'lc-main=en-US'
  2246. const response = await asyncRequest({
  2247. url: homePageUrl,
  2248. headers: {
  2249. 'Accept-Language': 'en-US,en'
  2250. }
  2251. }).catch(function (response) {
  2252. console.warn('ShowMetacriticRatings: Error imdb03\nurl=' + homePageUrl + '\nstatus=' + response.status)
  2253. })
  2254. document.cookie = 'lc-main=' + langBefore
  2255. // Extract <h1> title
  2256. const parts = response.responseText.split('</span></h1>')[0].split('>')
  2257. console.debug('ShowMetacriticRatings: TV title from English page:', parts[parts.length - 1])
  2258. return parts[parts.length - 1]
  2259. } else if (document.querySelector('script[type="application/ld+json"]')) {
  2260. const ld = parseLDJSON(['name', 'alternateName'])
  2261. if (ld.length > 1 && ld[1]) {
  2262. console.debug('ShowMetacriticRatings: TV ld+json alternateName', ld[1])
  2263. return ld[1]
  2264. }
  2265. console.debug('ShowMetacriticRatings: TV ld+json name', ld[0])
  2266. return ld[0]
  2267. } else {
  2268. const m = document.title.match(/(.+?)\s+\(.+(\d{4}).+/)
  2269. console.debug('ShowMetacriticRatings: TV <title>', m[1])
  2270. return m[1]
  2271. }
  2272. }
  2273. }
  2274. ]
  2275. },
  2276. steam: {
  2277. host: ['store.steampowered.com'],
  2278. condition: () => document.querySelector('*[itemprop=name]'),
  2279. products: [{
  2280. condition: Always,
  2281. type: 'pcgame',
  2282. data: () => document.querySelector('*[itemprop=name]').textContent
  2283. }]
  2284. },
  2285. rottentomatoes: {
  2286. host: ['rottentomatoes.com'],
  2287. condition: Always,
  2288. products: [{
  2289. condition: () => document.location.pathname.startsWith('/m/'),
  2290. type: 'movie',
  2291. data: () => document.querySelector('h1').firstChild.textContent
  2292. },
  2293. {
  2294. condition: () => document.location.pathname.startsWith('/tv/'),
  2295. type: 'tv',
  2296. data: () => unsafeWindow.BK.TvSeriesTitle
  2297. }
  2298. ]
  2299. },
  2300. serienjunkies: {
  2301. host: ['www.serienjunkies.de'],
  2302. condition: Always,
  2303. products: [{
  2304. condition: () => document.getElementById('serienlinksbreit2aktuell'),
  2305. type: 'tv',
  2306. data: () => document.querySelector('h1').textContent.trim()
  2307. },
  2308. {
  2309. condition: () => document.location.pathname.search(/vod\/film\/.{3,}/) !== -1,
  2310. type: 'movie',
  2311. data: () => document.querySelector('h1').textContent.trim()
  2312. }]
  2313. },
  2314. gamespot: {
  2315. host: ['gamespot.com'],
  2316. condition: () => document.querySelector('[itemprop=device]') || document.location.pathname.startsWith('/reviews/'),
  2317. products: [
  2318. {
  2319. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  2320. type: 'pcgame',
  2321. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  2322. },
  2323. {
  2324. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  2325. type: 'ps4game',
  2326. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  2327. },
  2328. {
  2329. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  2330. type: 'xonegame',
  2331. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  2332. },
  2333. {
  2334. condition: () => document.querySelector('.system.system--simple.system--pc'),
  2335. type: 'pcgame',
  2336. data: () => document.querySelector('h1').textContent.trim().split('Review')[0].trim()
  2337. },
  2338. {
  2339. condition: () => document.querySelector('.system.system--simple.system--ps5'),
  2340. type: 'ps4game',
  2341. data: () => document.querySelector('h1').textContent.trim().split('Review')[0].trim()
  2342. },
  2343. {
  2344. condition: () => document.querySelector('.system.system--simple.system--xbsx'),
  2345. type: 'xonegame',
  2346. data: () => document.querySelector('h1').textContent.trim().split('Review')[0].trim()
  2347. }
  2348. ]
  2349. },
  2350. amazon: {
  2351. host: ['amazon.'],
  2352. condition: Always,
  2353. products: [
  2354. {
  2355. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  2356. type: 'music',
  2357. data: function () {
  2358. const artist = document.querySelector('.artistLink').textContent.trim()
  2359. let title = document.querySelector('.viewTitle').textContent.trim()
  2360. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2361. if (artist && title) {
  2362. return [artist, title]
  2363. }
  2364. return false
  2365. }
  2366. },
  2367. {
  2368. condition: function () { // "Normal amazon" page
  2369. try {
  2370. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  2371. return true
  2372. }
  2373. } catch (e) {}
  2374. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  2375. return music.some(function (s) {
  2376. if (~document.title.indexOf(s)) {
  2377. return true
  2378. } else {
  2379. return false
  2380. }
  2381. })
  2382. },
  2383. type: 'music',
  2384. data: function () {
  2385. let artist = false
  2386. let title = false
  2387. if (document.querySelector('#ProductInfoArtistLink')) {
  2388. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  2389. } else if (document.querySelector('#bylineInfo .author>*')) {
  2390. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  2391. }
  2392.  
  2393. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  2394. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  2395. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2396. } else if (document.querySelector('#productTitle')) {
  2397. title = document.querySelector('#productTitle').textContent.trim()
  2398. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2399. }
  2400. return [artist, title]
  2401. }
  2402. },
  2403. {
  2404. condition: () => (document.querySelector('[data-automation-id=title]') && (
  2405. document.getElementsByClassName('av-season-single').length ||
  2406. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  2407. document.getElementById('tab-selector-episodes') ||
  2408. document.getElementById('av-droplist-av-atf-season-selector')
  2409. )),
  2410. type: 'tv',
  2411. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  2412. },
  2413. {
  2414. condition: () => ((
  2415. document.getElementsByClassName('av-season-single').length ||
  2416. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  2417. document.getElementById('tab-selector-episodes') ||
  2418. document.getElementById('av-droplist-av-atf-season-selector')
  2419. ) && Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).some((x) => x != null)),
  2420. type: 'tv',
  2421. data: () => Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).filter((x) => x != null)[0][1]
  2422. },
  2423. {
  2424. condition: () => document.querySelector('[data-automation-id=title]'),
  2425. type: 'movie',
  2426. data: () => document.querySelector('[data-automation-id=title]').textContent.trim().replace(/\[.{1,8}\]/, '')
  2427. },
  2428. {
  2429. condition: () => document.querySelector('#watchNowContainer a[href*="/gp/video/"]'),
  2430. type: 'movie',
  2431. data: () => document.getElementById('productTitle').textContent.trim()
  2432. }
  2433. ]
  2434. },
  2435. BoxOfficeMojo: {
  2436. host: ['boxofficemojo.com'],
  2437. condition: () => Always,
  2438. products: [
  2439. {
  2440. condition: () => document.location.pathname.startsWith('/release/'),
  2441. type: 'movie',
  2442. data: () => document.querySelector('meta[name=title]').content
  2443. },
  2444. {
  2445. // Old page design
  2446. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  2447. type: 'movie',
  2448. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.textContent
  2449. }]
  2450. },
  2451. AllMovie: {
  2452. host: ['allmovie.com'],
  2453. condition: () => document.querySelector('h2.movie-title'),
  2454. products: [{
  2455. condition: () => document.querySelector('h2.movie-title'),
  2456. type: 'movie',
  2457. data: () => document.querySelector('h2.movie-title').firstChild.textContent.trim()
  2458. }]
  2459. },
  2460. 'en.wikipedia': {
  2461. host: ['en.wikipedia.org'],
  2462. condition: Always,
  2463. products: [{
  2464. condition: function () {
  2465. if (!document.querySelector('.infobox .summary')) {
  2466. return false
  2467. }
  2468. const r = /\d\d\d\d films/
  2469. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2470. },
  2471. type: 'movie',
  2472. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2473. },
  2474. {
  2475. condition: function () {
  2476. if (!document.querySelector('.infobox .summary')) {
  2477. return false
  2478. }
  2479. const r = /television series/
  2480. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2481. },
  2482. type: 'tv',
  2483. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2484. }]
  2485. },
  2486. fandango: {
  2487. host: ['fandango.com'],
  2488. condition: () => document.querySelector("meta[property='og:title']"),
  2489. products: [{
  2490. condition: Always,
  2491. type: 'movie',
  2492. data: () => document.querySelector("meta[property='og:title']").content.match(/(.+?)\s+\(\d{4}\)/)[1].trim()
  2493. }]
  2494. },
  2495. flixster: {
  2496. host: ['flixster.com'],
  2497. condition: () => Always,
  2498. products: [{
  2499. condition: () => parseLDJSON('@type') === 'Movie',
  2500. type: 'movie',
  2501. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2502. }]
  2503. },
  2504. themoviedb: {
  2505. host: ['themoviedb.org'],
  2506. condition: () => document.querySelector("meta[property='og:type']"),
  2507. products: [{
  2508. condition: () => document.querySelector("meta[property='og:type']").content === 'movie' ||
  2509. document.querySelector("meta[property='og:type']").content === 'video.movie',
  2510. type: 'movie',
  2511. data: () => document.querySelector("meta[property='og:title']").content
  2512. },
  2513. {
  2514. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' ||
  2515. document.querySelector("meta[property='og:type']").content === 'tv_series' ||
  2516. document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2517. type: 'tv',
  2518. data: () => document.querySelector("meta[property='og:title']").content
  2519. }]
  2520. },
  2521. letterboxd: {
  2522. host: ['letterboxd.com'],
  2523. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  2524. products: [{
  2525. condition: Always,
  2526. type: 'movie',
  2527. data: () => unsafeWindow.filmData.name
  2528. }]
  2529. },
  2530. TVmaze: {
  2531. host: ['tvmaze.com'],
  2532. condition: () => document.querySelector('h1'),
  2533. products: [{
  2534. condition: Always,
  2535. type: 'tv',
  2536. data: () => document.querySelector('h1').firstChild.textContent
  2537. }]
  2538. },
  2539. TVGuide: {
  2540. host: ['tvguide.com'],
  2541. condition: Always,
  2542. products: [{
  2543. condition: () => document.location.pathname.startsWith('/tvshows/'),
  2544. type: 'tv',
  2545. data: function () {
  2546. if (document.querySelector('meta[itemprop=name]')) {
  2547. return document.querySelector('meta[itemprop=name]').content
  2548. } else {
  2549. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  2550. }
  2551. }
  2552. }]
  2553. },
  2554. followshows: {
  2555. host: ['followshows.com'],
  2556. condition: Always,
  2557. products: [{
  2558. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  2559. type: 'tv',
  2560. data: () => document.querySelector("meta[property='og:title']").content.replace(/\(\d{4}\)$/, '')
  2561. }]
  2562. },
  2563. TheTVDB: {
  2564. host: ['thetvdb.com'],
  2565. condition: Always,
  2566. products: [{
  2567. condition: () => document.location.pathname.startsWith('/series/'),
  2568. type: 'tv',
  2569. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2570. },
  2571. {
  2572. condition: () => document.location.pathname.startsWith('/movies/'),
  2573. type: 'movie',
  2574. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2575. }]
  2576. },
  2577. ConsequenceOfSound: {
  2578. host: ['consequence.net', 'consequenceofsound.net'],
  2579. condition: () => document.querySelector('#main-content .review-summary'),
  2580. products: [
  2581. {
  2582. condition: () => document.querySelector('meta[name="cXenseParse:cns-artist-names"]') && document.querySelector('em'),
  2583. type: 'music',
  2584. data: function () {
  2585. window.setInterval(function () {
  2586. if (document.getElementById('ot-sdk-btn-floating')) {
  2587. document.getElementById('ot-sdk-btn-floating').remove()
  2588. }
  2589. }, 5000)
  2590. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2591. const arr = Array.from(document.querySelectorAll('em')).map((em) => em.textContent.trim())
  2592. const counts = {}
  2593. for (const num of arr) {
  2594. counts[num] = counts[num] ? counts[num] + 1 : 1
  2595. }
  2596. const max = Math.max(...Object.values(counts))
  2597. const maxIndex = Object.values(counts).indexOf(max)
  2598. const title = Object.keys(counts)[maxIndex]
  2599. return [artist, title]
  2600. }
  2601. },
  2602. {
  2603. condition: () => document.title.match(/'(.*?)'\s*Album/i) && document.querySelector('meta[name="cXenseParse:cns-artist-names"]'),
  2604. type: 'music',
  2605. data: function () {
  2606. window.setInterval(function () {
  2607. if (document.getElementById('ot-sdk-btn-floating')) {
  2608. document.getElementById('ot-sdk-btn-floating').remove()
  2609. }
  2610. }, 5000)
  2611. const title = document.title.match(/'(.*?)'\s*Album/i)[1]
  2612. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2613. return [artist, title]
  2614. }
  2615. },
  2616. {
  2617. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  2618. type: 'music',
  2619. data: function () {
  2620. window.setInterval(function () {
  2621. if (document.getElementById('ot-sdk-btn-floating')) {
  2622. document.getElementById('ot-sdk-btn-floating').remove()
  2623. }
  2624. }, 5000)
  2625. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  2626. return [m[1], m[2]]
  2627. }
  2628. },
  2629. {
  2630. condition: () => document.location.pathname.indexOf('/album-review') !== -1 && document.querySelector('a.tag[href*="/artist/"'),
  2631. type: 'music',
  2632. data: function () {
  2633. window.setInterval(function () {
  2634. if (document.getElementById('ot-sdk-btn-floating')) {
  2635. document.getElementById('ot-sdk-btn-floating').remove()
  2636. }
  2637. }, 5000)
  2638. const artistAndTitleWithDash = document.location.pathname.match(/album-review-([\w-]+)/)[1]
  2639. const artistWithDash = document.querySelector('a.tag[href*="/artist/"').pathname.match(/artist\/([\w-]+)/)[1]
  2640. const titleWithDash = artistAndTitleWithDash.replace(artistWithDash, '')
  2641. const title = titleWithDash.replace('-', ' ').trim()
  2642. const artist = artistWithDash.replace('-', ' ').trim()
  2643. return [artist, title]
  2644. }
  2645. }]
  2646. },
  2647. Pitchfork: {
  2648. host: ['pitchfork.com'],
  2649. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  2650. products: [{
  2651. condition: () => document.querySelector('.single-album-tombstone'),
  2652. type: 'music',
  2653. data: function () {
  2654. let artist
  2655. let album
  2656. if (document.querySelector('.single-album-tombstone .artists')) {
  2657. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  2658. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  2659. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  2660. }
  2661. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  2662. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  2663. } else if (document.querySelector('.single-album-tombstone h1')) {
  2664. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  2665. }
  2666.  
  2667. return [artist, album]
  2668. }
  2669. }]
  2670. },
  2671. 'Last.fm': {
  2672. host: ['last.fm'],
  2673. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2674. products: [{
  2675. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2676. type: 'music',
  2677. data: function () {
  2678. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2679. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2680. return [artist, album]
  2681. }
  2682. }]
  2683. },
  2684. TVNfo: {
  2685. host: ['tvnfo.com'],
  2686. condition: () => document.querySelector('#title #name'),
  2687. products: [{
  2688. condition: Always,
  2689. type: 'tv',
  2690. data: function () {
  2691. const years = document.querySelector('#title #years').textContent.trim()
  2692. const title = document.querySelector('#title #name').textContent.replace(years, '').trim()
  2693. return title
  2694. }
  2695. }]
  2696. },
  2697. rateyourmusic: {
  2698. host: ['rateyourmusic.com'],
  2699. condition: () => document.querySelector("meta[property='og:type']"),
  2700. products: [{
  2701. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2702. type: 'music',
  2703. data: function () {
  2704. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2705. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2706. return [artist, album]
  2707. }
  2708. }]
  2709. },
  2710. spotify: {
  2711. host: ['open.spotify.com'],
  2712. condition: Always,
  2713. products: [{
  2714. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector('.Root__main-view h1'),
  2715. type: 'music',
  2716. data: function () {
  2717. const album = document.querySelector('.Root__main-view h1').textContent.trim()
  2718. let artist = []
  2719. document.querySelector('.Root__main-view h1').parentNode.parentNode.parentNode.querySelectorAll('a[href*="/artist/"]').forEach(function (a) {
  2720. artist.push(a.textContent.trim())
  2721. })
  2722. artist = artist.join(' ')
  2723. return [artist, album]
  2724. }
  2725. }]
  2726. },
  2727. nme: {
  2728. host: ['nme.com'],
  2729. condition: () => document.location.pathname.startsWith('/reviews/'),
  2730. products: [
  2731. {
  2732. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/film-reviews"]'),
  2733. type: 'movie',
  2734. data: function () {
  2735. try {
  2736. return document.title.match(/[‘'](.+?)[’']/)[1]
  2737. } catch (e) {
  2738. try {
  2739. return document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2740. } catch (e) {
  2741. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2742. }
  2743. }
  2744. }
  2745. },
  2746. {
  2747. condition: () => document.querySelector('#nme-music-header'),
  2748. type: 'music',
  2749. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/\s*(.+?)\s*.\s*[‘'](.+?)[’']/).slice(1)
  2750. },
  2751. {
  2752. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/tv-reviews"]'),
  2753. type: 'tv',
  2754. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2755. }]
  2756. },
  2757. albumoftheyear: {
  2758. host: ['albumoftheyear.org'],
  2759. condition: Always,
  2760. products: [{
  2761. condition: () => document.location.pathname.startsWith('/album/'),
  2762. type: 'music',
  2763. data: function () {
  2764. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2765. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2766. return [artist, album]
  2767. }
  2768. }]
  2769. },
  2770. epguides: {
  2771. host: ['epguides.com'],
  2772. condition: () => document.getElementById('eplist'),
  2773. products: [{
  2774. condition: () => document.getElementById('eplist') && document.querySelector('.center.titleblock h2'),
  2775. type: 'tv',
  2776. data: () => document.querySelector('.center.titleblock h2').textContent.trim()
  2777. }]
  2778. },
  2779. /*
  2780. netflix: {
  2781. host: ['netflix.com'],
  2782. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2783.  
  2784. // TODO
  2785. // https://www.netflix.com/de/title/70264888
  2786. // https://www.netflix.com/de/title/70178217
  2787. // https://www.netflix.com/de/title/70305892 ## Movie
  2788. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2789.  
  2790. products: [{
  2791. condition: () => parseLDJSON('@type') === 'Movie',
  2792. type: 'movie',
  2793. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2794. },
  2795. {
  2796. condition: () => parseLDJSON('@type') === 'TVSeries',
  2797. type: 'tv',
  2798. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2799. }]
  2800. },
  2801. */
  2802. ComedyCentral: {
  2803. host: ['cc.com'],
  2804. condition: () => document.location.pathname.startsWith('/shows/'),
  2805. products: [{
  2806. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2807. type: 'tv',
  2808. data: () => document.querySelector("meta[property='og:title']").content.replace('| Comedy Central', '').trim()
  2809. },
  2810. {
  2811. condition: () => document.location.pathname.split('/').length === 3 && document.title.match(/(.+?)\s+-\s+Series/),
  2812. type: 'tv',
  2813. data: () => document.title.match(/(.+?)\s+-\s+Series/)[1]
  2814. }]
  2815. },
  2816. AMC: {
  2817. host: ['amc.com'],
  2818. condition: () => document.location.pathname.startsWith('/shows/'),
  2819. products: [
  2820. {
  2821. condition: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1'),
  2822. type: 'tv',
  2823. data: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1').textContent
  2824. },
  2825. {
  2826. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2827. type: 'tv',
  2828. data: () => document.querySelector('.video-card-description h1').textContent.trim()
  2829. }]
  2830. },
  2831. AMCplus: {
  2832. host: ['amcplus.com'],
  2833. condition: () => Always,
  2834. products: [
  2835. {
  2836. condition: () => document.title.match(/Watch .+? |/),
  2837. type: 'tv',
  2838. data: () => document.title.match(/Watch (.+?) |/)[1].trim()
  2839. }]
  2840. },
  2841. RlsBB: {
  2842. host: ['rlsbb.ru'],
  2843. condition: () => document.querySelectorAll('.post').length === 1,
  2844. products: [
  2845. {
  2846. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/movies/"]'),
  2847. type: 'movie',
  2848. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+\d{4}/)[1].trim()
  2849. },
  2850. {
  2851. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/tv-shows/"]'),
  2852. type: 'tv',
  2853. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+S\d{2}/)[1].trim()
  2854. }]
  2855. },
  2856. newalbumreleases: {
  2857. host: ['newalbumreleases.net'],
  2858. condition: () => document.querySelectorAll('#content .single').length === 1,
  2859. products: [
  2860. {
  2861. condition: () => document.querySelector('#content .single .cover .entry'),
  2862. type: 'music',
  2863. data: function () {
  2864. const mArtist = document.querySelector('#content .single .cover .entry').textContent.match(/Artist.\s*(.+)\s+/i)
  2865. if (mArtist) {
  2866. const mAlbum = document.querySelector('#content .single .cover .entry').textContent.match(/Album.\s*(.+)\s+/i)
  2867. if (mAlbum) {
  2868. return [mArtist[1], mAlbum[1]]
  2869. }
  2870. }
  2871. }
  2872. }]
  2873. },
  2874. showtime: {
  2875. host: ['sho.com'],
  2876. condition: Always,
  2877. products: [
  2878. {
  2879. condition: () => parseLDJSON('@type') === 'Movie',
  2880. type: 'movie',
  2881. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2882. },
  2883. {
  2884. condition: () => parseLDJSON('@type') === 'TVSeries',
  2885. type: 'tv',
  2886. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2887. }]
  2888. },
  2889. epicgames: {
  2890. host: ['www.epicgames.com', 'store.epicgames.com'],
  2891. condition: () => document.querySelector('.meta-schema'),
  2892. products: [{
  2893. condition: Always,
  2894. type: 'pcgame',
  2895. data: function () {
  2896. try {
  2897. return document.querySelector('.meta-schema').nextElementSibling.firstElementChild.lastElementChild.firstElementChild.firstElementChild.firstElementChild.textContent
  2898. } catch (e) {
  2899. return document.querySelector('h1').textContent
  2900. }
  2901. }
  2902. }]
  2903. },
  2904. gog: {
  2905. host: ['www.gog.com'],
  2906. condition: () => document.querySelector('.productcard-basics__title'),
  2907. products: [
  2908. {
  2909. condition: () => document.location.pathname.split('/').length > 2 && (
  2910. document.location.pathname.split('/')[1] === 'game' ||
  2911. document.location.pathname.split('/')[2] === 'game'),
  2912. type: 'pcgame',
  2913. data: () => document.querySelector('.productcard-basics__title').textContent
  2914. },
  2915. {
  2916. condition: () => document.location.pathname.split('/').length > 2 && (
  2917. document.location.pathname.split('/')[1] === 'movie' ||
  2918. document.location.pathname.split('/')[2] === 'movie'),
  2919. type: 'movie',
  2920. data: () => document.querySelector('.productcard-basics__title').textContent
  2921. }
  2922. ]
  2923. },
  2924. steamgifts: {
  2925. host: ['www.steamgifts.com'],
  2926. condition: () => document.querySelector('.featured__heading__medium'),
  2927. products: [{
  2928. condition: Always,
  2929. type: 'pcgame',
  2930. data: () => document.querySelector('.featured__heading__medium').innerText
  2931. }]
  2932. },
  2933. allmusic: {
  2934. host: ['allmusic.com'],
  2935. condition: Always,
  2936. products: [{
  2937. condition: () => document.location.pathname.indexOf('/album/') !== -1,
  2938. type: 'music',
  2939. data: function () {
  2940. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2941. const album = ld[0]
  2942. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2943. return [artist, album]
  2944. }
  2945. }]
  2946. },
  2947. psapm: {
  2948. host: ['psa.wf'],
  2949. condition: Always,
  2950. products: [
  2951. {
  2952. condition: () => document.location.pathname.startsWith('/movie/'),
  2953. type: 'movie',
  2954. data: function () {
  2955. const title = document.querySelector('h1').textContent.trim()
  2956. const m = title.match(/(.+)\((\d+)\)$/)
  2957. if (m) {
  2958. return m[1].trim()
  2959. } else {
  2960. return title
  2961. }
  2962. }
  2963. },
  2964. {
  2965. condition: () => document.location.pathname.startsWith('/tv-show/'),
  2966. type: 'tv',
  2967. data: () => document.querySelector('h1').textContent.trim()
  2968. }
  2969. ]
  2970. },
  2971. 'save.tv': {
  2972. host: ['save.tv'],
  2973. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2974. products: [
  2975. {
  2976. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2977. type: 'movie',
  2978. data: function () {
  2979. let title = null
  2980. if (document.querySelector("span[data-bind='text:OrigTitle']")) {
  2981. title = document.querySelector("span[data-bind='text:OrigTitle']").textContent
  2982. } else {
  2983. title = document.querySelector("h2[data-bind='text:Title']").textContent
  2984. }
  2985. let year = null
  2986. if (document.querySelector("span[data-bind='text:ProductionYear']")) {
  2987. year = parseInt(document.querySelector("span[data-bind='text:ProductionYear']").textContent)
  2988. }
  2989. return [title, year]
  2990. }
  2991. }
  2992. ]
  2993. },
  2994. wikiwand: {
  2995. host: ['www.wikiwand.com'],
  2996. condition: Always,
  2997. products: [{
  2998. condition: function () {
  2999. const title = document.querySelector('h1').textContent.toLowerCase()
  3000. const subtitle = document.querySelector('h2[class*="subtitle"]') ? document.querySelector('h2[class*="subtitle"]').textContent.toLowerCase() : ''
  3001. if (title.indexOf('film') === -1 && !subtitle) {
  3002. return false
  3003. }
  3004. return title.indexOf('film') !== -1 ||
  3005. subtitle.indexOf('film') !== -1 ||
  3006. subtitle.indexOf('movie') !== -1
  3007. },
  3008. type: 'movie',
  3009. data: () => document.querySelector('h1').textContent.replace(/\((\d{4} )?film\)/i, '').trim()
  3010. },
  3011. {
  3012. condition: function () {
  3013. const title = document.querySelector('h1').textContent.toLowerCase()
  3014. const subtitle = document.querySelector('h2[class*="subtitle"]') ? document.querySelector('h2[class*="subtitle"]').textContent.toLowerCase() : ''
  3015. if (title.indexOf('tv series') === -1 && !subtitle) {
  3016. return false
  3017. }
  3018. return title.indexOf('tv series') !== -1 ||
  3019. subtitle.indexOf('television') !== -1 ||
  3020. subtitle.indexOf('tv series') !== -1
  3021. },
  3022. type: 'tv',
  3023. data: () => document.querySelector('h1').textContent.replace(/\(tv series\)/i, '').trim()
  3024. }]
  3025. },
  3026. radarr: {
  3027. host: ['*'],
  3028. condition: () => document.location.pathname.startsWith('/movie/'),
  3029. products: [{
  3030. condition: () => document.querySelector('[class*="MovieDetails-title"] span'),
  3031. type: 'movie',
  3032. data: () => document.querySelector('[class*="MovieDetails-title"] span').textContent.trim()
  3033. }]
  3034. },
  3035. trakt: {
  3036. host: ['trakt.tv'],
  3037. condition: Always,
  3038. products: [
  3039. {
  3040. condition: () => document.location.pathname.startsWith('/movies/'),
  3041. type: 'movie',
  3042. data: () => Array.from(document.querySelector('.summary h1').childNodes).filter(node => node.nodeType === node.TEXT_NODE).map(node => node.textContent).join(' ').trim()
  3043. },
  3044. {
  3045. condition: () => document.location.pathname.startsWith('/shows/'),
  3046. type: 'tv',
  3047. data: () => Array.from(document.querySelector('.summary h1').childNodes).filter(node => node.nodeType === node.TEXT_NODE).map(node => node.textContent).join(' ').trim()
  3048. }
  3049. ]
  3050. }
  3051.  
  3052. }
  3053.  
  3054. async function main () {
  3055. let dataFound = false
  3056.  
  3057. let map = false
  3058.  
  3059. for (const name in sites) {
  3060. const site = sites[name]
  3061. if (site.host.some(function (e) { return ~this.indexOf(e) || e === '*' }, document.location.hostname) && site.condition()) {
  3062. for (let i = 0; i < site.products.length; i++) {
  3063. if (site.products[i].condition()) {
  3064. // Check map for a match
  3065. if (map === false) {
  3066. map = JSON.parse(await GM.getValue('map', '{}'))
  3067. }
  3068. const docurl = filterUniversalUrl(document.location.href)
  3069. if (docurl in map) {
  3070. // Found in map, show result
  3071. const metaurl = map[docurl]
  3072. metacriticGeneralProductSetup()
  3073. metacritic.mapped.apply(undefined, [docurl, site.products[i], absoluteMetaURL(metaurl), site.products[i].type])
  3074. dataFound = true
  3075. break
  3076. }
  3077. // Try to retrieve item name from page
  3078. let data
  3079. try {
  3080. data = await site.products[i].data()
  3081. } catch (e) {
  3082. data = false
  3083. console.error(`ShowMetacriticRatings: Error in data() of site='${name}', type='${site.products[i].type}'`)
  3084. console.error(e)
  3085. }
  3086. if (data) {
  3087. const params = [docurl, site.products[i]]
  3088. if (Array.isArray(data)) {
  3089. params.push(...data)
  3090. } else {
  3091. params.push(data)
  3092. }
  3093. metacriticGeneralProductSetup()
  3094. metacritic[site.products[i].type].apply(undefined, params)
  3095. dataFound = true
  3096. }
  3097. break
  3098. }
  3099. }
  3100. break
  3101. }
  3102. }
  3103. return dataFound
  3104. }
  3105.  
  3106. (async function () {
  3107. const gdpr = await acceptGDPR()
  3108. if (!gdpr) {
  3109. GM.registerMenuCommand('Show Metacritic.com ratings - Accept terms of service', () => acceptGDPR(true).then((yes) => yes && document.location.reload()))
  3110. return
  3111. }
  3112. await versionUpdate()
  3113.  
  3114. if (!document.getElementById('mcdiv123_box_css')) {
  3115. const style = document.createElement('style')
  3116. style.setAttribute('id', 'mcdiv123_box_css')
  3117. style.innerHTML = BOX_CSS
  3118. document.head.appendChild(style)
  3119. }
  3120.  
  3121. const firstRunResult = await main()
  3122.  
  3123. GM.registerMenuCommand('Show Metacritic.com ratings - Search now', () => openSearchBox())
  3124. GM.registerMenuCommand('Show Metacritic.com ratings - Change corner', () => changePosition())
  3125. GM.registerMenuCommand('Show Metacritic.com ratings - Enlarge', () => changeSizeEnlarge())
  3126. GM.registerMenuCommand('Show Metacritic.com ratings - Shrink', () => changeSizeShrink())
  3127.  
  3128. let lastLoc = document.location.href
  3129. let lastContent = document.body.innerText
  3130. let lastCounter = 0
  3131. async function newpage () {
  3132. if (lastContent === document.body.innerText && lastCounter < 15) {
  3133. window.setTimeout(newpage, 500)
  3134. lastCounter++
  3135. } else {
  3136. lastContent = document.body.innerText
  3137. lastCounter = 0
  3138. const re = await main()
  3139. if (!re) { // No page matched or no data found
  3140. window.setTimeout(newpage, 1000)
  3141. }
  3142. }
  3143. }
  3144. window.setInterval(function () {
  3145. if (document.location.href !== lastLoc) {
  3146. lastLoc = document.location.href
  3147. $('#mcdiv123').remove()
  3148.  
  3149. window.setTimeout(newpage, 1000)
  3150. }
  3151. }, 500)
  3152.  
  3153. if (!firstRunResult) {
  3154. // Initial run had no match, let's try again there may be new content
  3155. window.setTimeout(main, 2000)
  3156. }
  3157. })()