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

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