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

当前为 2023-10-31 提交的版本,查看 最新版本

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