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-11-02 提交的版本。查看 最新版本

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