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, argenteam.net

当前为 2024-01-29 提交的版本,查看 最新版本

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