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

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