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-08-18 提交的版本,檢視 最新版本

  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 89
  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 <= 51) {
  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 < 55) {
  159. await GM.setValue('version', 55)
  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. method: 'POST',
  633. url: current.metaurl,
  634. data: 'hoverinfo=1',
  635. headers: {
  636. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  637. 'X-Requested-With': 'XMLHttpRequest'
  638. }
  639. }).catch(function (response) {
  640. console.error('ShowMetacriticRatings: Error 01')
  641. })
  642. return response
  643. }
  644. }
  645.  
  646. function extractHoverFromFullPage (response) {
  647. let html = 'ShowMetacriticRatings:<br>Error occured in extractHoverFromFullPage()'
  648. try {
  649. // Try parsing HTML
  650. const doc = domParser().parseFromString(response.responseText, 'text/html')
  651. doc.querySelector('.product_page_title h1')
  652. doc.querySelector('.summary_img')
  653. doc.querySelectorAll('.details_section')
  654. doc.querySelectorAll('#nav_to_metascore .distribution')
  655.  
  656. let pageUrl = ''
  657. let imgSrc = ''
  658. let imgAlt = ''
  659. let title = ''
  660. let publisher = ''
  661. let releaseDate = ''
  662. let starring = ''
  663. let criticsScore = ''
  664. let criticsClass = ''
  665. let criticsNumber = ''
  666. let criticsCharts = ''
  667. let userScore = ''
  668. let userClass = ''
  669. let userNumber = ''
  670. let userCharts = ''
  671.  
  672. pageUrl = response.finalUrl + (response.finalUrl.endsWith('/') ? '' : '/')
  673. imgSrc = doc.querySelector('.summary_img').src
  674. imgAlt = doc.querySelector('.summary_img').alt
  675. title = doc.querySelector('.product_page_title h1').textContent
  676. if (doc.querySelector('.details_section .distributor a')) { publisher = doc.querySelector('.details_section .distributor a').textContent }
  677.  
  678. if (doc.querySelector('.details_section .release_date span:nth-child(2)')) {
  679. const date = doc.querySelector('.details_section .release_date span:nth-child(2)').textContent
  680. releaseDate = `
  681. <div class="summary_detail release_data">
  682. <span class="label">Release Date:</span>
  683. <span class="data">${date}</span>
  684. </div>`
  685. }
  686.  
  687. if (doc.querySelector('.details_section.summary_cast span:nth-child(2)')) {
  688. const stars = doc.querySelector('.details_section.summary_cast span:nth-child(2)').innerHTML
  689. starring = `
  690. <div>
  691. <div class="summary_detail product_credits">
  692. <span class="label">Starring:</span>
  693. <span class="data">
  694. ${stars}
  695. </span>
  696. </div>
  697. </div>`
  698. }
  699.  
  700. criticsClass = 'metascore_w medium tbd'
  701. criticsScore = 'tbd'
  702. userClass = 'metascore_w medium user tbd'
  703. userScore = 'tbd'
  704.  
  705. if (doc.querySelector('.score_details .based_on')) {
  706. criticsNumber = doc.querySelector('.score_details .based_on').textContent.match(/\d+/)
  707. } else {
  708. criticsNumber = 'By'
  709. }
  710. if (doc.querySelector('.user_score_summary .based_on')) {
  711. userNumber = doc.querySelector('.user_score_summary .based_on').textContent.match(/\d+/)
  712. } else {
  713. userNumber = 'User'
  714. }
  715.  
  716. // Remove text from distribution charts:
  717. let label = doc.querySelector('#nav_to_metascore .charts .label.fl')
  718. while (label) {
  719. label.parentNode.title = label.textContent.trim() + ' ' + label.parentNode.querySelector('.count').textContent.trim()
  720. label.remove()
  721. label = doc.querySelector('#nav_to_metascore .charts .label.fl')
  722. }
  723. const scores = doc.querySelectorAll('#nav_to_metascore .distribution .metascore_w')
  724. if (scores.length === 2) {
  725. criticsScore = scores[0].innerText
  726. criticsClass = scores[0].className.replace('larger', 'medium')
  727. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  728. criticsCharts = '<td class="meta">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  729. userScore = scores[1].innerText
  730. userClass = scores[1].className.replace('larger', 'medium')
  731. scores[1].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  732. userCharts = '<td class="usr">' + scores[1].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  733. } else if (scores.length === 1) {
  734. if (scores[0].className.indexOf('user') === -1) {
  735. criticsScore = scores[0].innerText
  736. criticsClass = scores[0].className.replace('larger', 'medium')
  737. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  738. criticsCharts = '<td class="meta">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  739. } else {
  740. userScore = scores[0].innerText
  741. userClass = scores[0].className.replace('larger', 'medium')
  742. scores[0].parentNode.parentNode.querySelector('.charts').style.width = '40px'
  743. userCharts = '<td class="usr">' + scores[0].parentNode.parentNode.querySelector('.charts').outerHTML + '</td>'
  744. }
  745. }
  746.  
  747. html = `
  748. <div class="hoverinfo">
  749. <div class="hover_left">
  750. <div class="product_image_wrapper">
  751. <a target="_blank" href="${pageUrl}">
  752. <img class="product_image large_image" src="${imgSrc}" alt="${imgAlt}" />
  753. </a>
  754. </div>
  755. </div>
  756. <div class="hover_right">
  757. <h2 class="product_title">
  758. <a target="_blank" href="${pageUrl}">${title}</a>
  759. </h2>
  760. <div>
  761. <div class="summary_detail publisher">
  762. <span class="data">${publisher}</span>
  763. <span>&nbsp;|&nbsp;&nbsp;</span>
  764. </div>
  765. ${releaseDate}
  766. <div class="clr"></div>
  767. </div>
  768. ${starring}
  769. <div class="hr">
  770. &nbsp;
  771. </div>
  772.  
  773. <table class="hover_scores ">
  774. <tr>
  775. <td class="meta num">
  776. <a target="_blank" class="metascore_anchor" href="${pageUrl}#nav_to_metascore">
  777. <span class="${criticsClass}">${criticsScore}</span>
  778. </a>
  779. </td>
  780. <td class="meta txt">
  781. <div class="metascore_label">Metascore</div>
  782. <div class="metascore_review_count">
  783. <a target="_blank" href="${pageUrl}#nav_to_metascore">
  784. <span>${criticsNumber}</span> critics
  785. </a>
  786. </div>
  787. </td>
  788. ${criticsCharts}
  789. <td class="usr num">
  790.  
  791. <a target="_blank" class="metascore_anchor" href="${pageUrl}#nav_to_metascore">
  792. <span class="${userClass}">${userScore}</span>
  793. </a>
  794.  
  795. </td>
  796. <td class="usr txt">
  797. <div class="userscore_label">User Score</div>
  798. <div class="userscore_review_count">
  799. <a target="_blank" href="${pageUrl}#nav_to_metascore">
  800. <span>${userNumber}</span> Ratings
  801. </a>
  802. </div>
  803. </td>
  804. ${userCharts}
  805. </tr>
  806. </table>
  807.  
  808. </div>
  809.  
  810. <div class="clr"></div>
  811. </div>
  812. `
  813. } catch (e) {
  814. console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e)
  815.  
  816. // fallback to cutting out the relevant parts
  817.  
  818. let parts = response.responseText.split('class="score_details')
  819. const textPart = '<div class="' + parts[1].split('</div>')[0] + '</div>'
  820.  
  821. let titleText = '<div class="product_page_title' + response.responseText.split('class="product_page_title')[1].split('</div>')[0]
  822. titleText = titleText.split('<h1>').join('<h1 style="padding:0px; margin:2px">') + '</div>'
  823.  
  824. parts = response.responseText.split('id="nav_to_metascore"')
  825. let metaScorePart = '<div ' + parts[1].split('<div class="subsection_title"')[0] + '</div></div>'
  826.  
  827. metaScorePart = metaScorePart.split('href="">').join('href="' + response.finalUrl + '">')
  828. metaScorePart = metaScorePart.split('section_title bold">').join('section_title bold">' + titleText)
  829.  
  830. html = metaScorePart.split('<div class="distribution">').join(textPart + '<div class="distribution">')
  831.  
  832. if (html.indexOf('products_module') !== -1) {
  833. // Critic reviews are not available for this Series yet -> Cut the preview for other series
  834. html = html.split('products_module')[0] + '"></div>'
  835. }
  836.  
  837. if (html.length > 5000) {
  838. // Probably something went wrong, let's cut the response to prevent too long content
  839. console.warn('ShowMetacriticRatings: Cutting response to 5000 chars')
  840. html = html.substr(0, 5000)
  841. }
  842. }
  843. return html
  844. }
  845.  
  846. function asyncRequest (data) {
  847. return new Promise(function (resolve, reject) {
  848. isInRequestCache(data).then(function (cachedValue) {
  849. if (cachedValue) {
  850. return window.setTimeout(() => resolve(cachedValue), 10)
  851. }
  852. const defaultHeaders = {
  853. Referer: data.url,
  854. // Host: getHostname(data.url),
  855. 'User-Agent': navigator.userAgent
  856. }
  857. const defaultData = {
  858. method: 'GET',
  859. onload: function (response) {
  860. storeInRequestCache(data, response)
  861. resolve(response)
  862. },
  863. onerror: (response) => reject(response)
  864. }
  865. if ('headers' in data) {
  866. data.headers = Object.assign(defaultHeaders, data.headers)
  867. } else {
  868. data.headers = defaultHeaders
  869. }
  870. data = Object.assign(defaultData, data)
  871. GM.xmlHttpRequest(data)
  872. })
  873. })
  874. }
  875.  
  876. async function storeInRequestCache (requestData, response) {
  877. const newkey = JSON.stringify({
  878. url: requestData.url,
  879. method: requestData.method || 'GET',
  880. data: requestData.data || null
  881. })
  882. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  883. const now = (new Date()).getTime()
  884. const timeout = 15 * 60 * 1000
  885. for (const prop in cache) {
  886. // Delete cached values, that are older than 15 minutes
  887. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  888. delete cache[prop]
  889. }
  890. }
  891.  
  892. const newobj = {}
  893. for (const key in response) {
  894. newobj[key] = response[key]
  895. }
  896. newobj.responseText = '' + response.responseText
  897. newobj.cached = true
  898. if (!('time' in newobj)) {
  899. newobj.time = (new Date()).toJSON()
  900. }
  901.  
  902. cache[newkey] = newobj
  903.  
  904. await GM.setValue('requestcache', JSON.stringify(cache))
  905. }
  906.  
  907. async function isInRequestCache (requestData) {
  908. const key = JSON.stringify({
  909. url: requestData.url,
  910. method: requestData.method || 'GET',
  911. data: requestData.data || null
  912. })
  913.  
  914. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  915. const now = (new Date()).getTime()
  916. const timeout = 15 * 60 * 1000
  917. for (const prop in cache) {
  918. // Delete cached values, that are older than 15 minutes
  919. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  920. delete cache[prop]
  921. }
  922. }
  923.  
  924. if (key in cache) {
  925. return cache[key]
  926. } else {
  927. return false
  928. }
  929. }
  930.  
  931. async function storeInHoverCache (metaurl, response, orgMetaUrl) {
  932. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  933. const now = (new Date()).getTime()
  934. const timeout = 2 * 60 * 60 * 1000
  935. for (const prop in cache) {
  936. // Delete cached values, that are older than 2 hours
  937. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  938. delete cache[prop]
  939. }
  940. }
  941.  
  942. const newobj = {}
  943. for (const key in response) {
  944. newobj[key] = response[key]
  945. }
  946. newobj.responseText = '' + response.responseText
  947. newobj.cached = true
  948. if (!('time' in newobj)) {
  949. newobj.time = (new Date()).toJSON()
  950. }
  951.  
  952. cache[metaurl] = newobj
  953. if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect
  954. cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl }
  955. }
  956.  
  957. await GM.setValue('hovercache', JSON.stringify(cache))
  958. }
  959.  
  960. async function isInHoverCache (metaurl) {
  961. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  962. const now = (new Date()).getTime()
  963. const timeout = 2 * 60 * 60 * 1000
  964. for (const prop in cache) {
  965. // Delete cached values, that are older than 2 hours
  966. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  967. delete cache[prop]
  968. }
  969. }
  970.  
  971. function resolveRedirects (cacheEntry) {
  972. if (cacheEntry.redirect) {
  973. const newkey = cacheEntry.redirect
  974. if (newkey in cache) {
  975. const value = cache[newkey]
  976. delete cache[newkey]
  977. return resolveRedirects(value)
  978. }
  979. } else {
  980. return cacheEntry
  981. }
  982. return false
  983. }
  984.  
  985. if (metaurl in cache) {
  986. const value = cache[metaurl]
  987. delete cache[metaurl]
  988. return resolveRedirects(value)
  989. } else {
  990. return false
  991. }
  992. }
  993.  
  994. async function loadHoverInfo () {
  995. const cacheResponse = await isInHoverCache(current.metaurl)
  996. if (cacheResponse !== false) {
  997. console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`)
  998. if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) {
  999. return await handleJSONredirect(cacheResponse)
  1000. }
  1001. return cacheResponse
  1002. }
  1003. const requestURL = baseURLdatabase
  1004. const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl)
  1005.  
  1006. let response = await asyncRequest({
  1007. method: 'POST',
  1008. url: requestURL,
  1009. data: requestParams,
  1010. headers: {
  1011. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  1012. }
  1013. }).catch(function (response) {
  1014. console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status)
  1015. })
  1016.  
  1017. if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) {
  1018. response = await handleJSONredirect(response)
  1019. }
  1020.  
  1021. if (response.status >= 500) {
  1022. // Metacritic server error, try again after 2 seconds
  1023. console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1024. await delay(2000)
  1025. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  1026. console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1027. })
  1028. if (response.status > 300) {
  1029. console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1030. } else {
  1031. const newobj = {}
  1032. for (const key in response) {
  1033. newobj[key] = response[key]
  1034. }
  1035. newobj.responseText = extractHoverFromFullPage(response)
  1036. response = newobj
  1037. }
  1038. }
  1039.  
  1040. if (response.responseText && response.responseText.indexOf('<title>500 Page') !== -1) {
  1041. // Hover info not available for this url, try again with GET
  1042. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  1043. console.warn('ShowMetacriticRatings: Error 03\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1044. })
  1045.  
  1046. const newobj = {}
  1047. for (const key in response) {
  1048. newobj[key] = response[key]
  1049. }
  1050. newobj.responseText = extractHoverFromFullPage(response)
  1051. response = newobj
  1052. }
  1053.  
  1054. if (!('time' in response)) {
  1055. response.time = (new Date()).toJSON()
  1056. }
  1057. if (response.status === 200 && response.responseText) {
  1058. return response
  1059. } else {
  1060. const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status)
  1061. error.status = response.status
  1062. error.responseText = response.responseText
  1063. throw error
  1064. }
  1065. }
  1066.  
  1067. function changePosition () {
  1068. // Cycle through positions
  1069. GM.getValue('position', JSON.stringify(windowPositions[0])).then(function (s) {
  1070. let index
  1071. for (index = 0; index < windowPositions.length; index++) {
  1072. if (JSON.stringify(windowPositions[index]) === s) {
  1073. break
  1074. }
  1075. }
  1076. const nextIndex = (index + 1) % windowPositions.length
  1077. GM.setValue('position', JSON.stringify(windowPositions[nextIndex])).then(function () {
  1078. document.location.reload()
  1079. })
  1080. })
  1081. }
  1082.  
  1083. const current = {
  1084. metaurl: false,
  1085. docurl: false,
  1086. type: false,
  1087. data: [], // Array of raw search keys
  1088. searchTerm: false,
  1089. product: null,
  1090. broadenCounter: 0
  1091. }
  1092.  
  1093. async function loadMetacriticUrl (fromSearch) {
  1094. if (!current.metaurl) {
  1095. alert('ShowMetacriticRatings: Error 04')
  1096. return
  1097. }
  1098. const orgMetaUrl = current.metaurl
  1099. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1100. waitForHotkeysMETA()
  1101. return
  1102. }
  1103.  
  1104. if (await isTemporaryBlacklisted(current.metaurl)) {
  1105. console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`)
  1106. waitForHotkeysMETA()
  1107. return
  1108. }
  1109.  
  1110. const response = await loadHoverInfo().catch(async function (response) {
  1111. if (response instanceof Error || (response && response.stack && response.message)) {
  1112. if (!fromSearch && ('status' in response && response.status === 404)) {
  1113. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): status=404')
  1114. // No results
  1115. let broadenFct = broadenSearch // global broadenSearch function is the default
  1116. if ('broaden' in current.product) {
  1117. // try product 'broaden'-function if it is defined
  1118. broadenFct = current.product.broaden
  1119. }
  1120. const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1121. if (JSON.stringify(newData) !== JSON.stringify(current.data)) {
  1122. current.data = newData
  1123. metacritic[current.type](current.docurl, current.product, ...newData)
  1124. } else if (JSON.stringify(newData) === JSON.stringify(current.data)) {
  1125. // Same data as before, try once again to broaden
  1126. const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1127. if (JSON.stringify(newData2) !== JSON.stringify(current.data)) {
  1128. current.data = newData2
  1129. metacritic[current.type](current.docurl, current.product, ...newData2)
  1130. } else {
  1131. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps')
  1132. }
  1133. } else {
  1134. console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData)
  1135. }
  1136. } else {
  1137. console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response)
  1138. }
  1139. }
  1140.  
  1141. if (fromSearch) {
  1142. startSearch()
  1143. }
  1144. })
  1145.  
  1146. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1147. waitForHotkeysMETA()
  1148. return
  1149. }
  1150.  
  1151. if (typeof response !== 'undefined') {
  1152. showHoverInfo(response, orgMetaUrl)
  1153. } else {
  1154. waitForHotkeysMETA()
  1155. }
  1156. }
  1157.  
  1158. async function startSearch () {
  1159. waitForHotkeysMETA()
  1160.  
  1161. const cache = JSON.parse(await GM.getValue('autosearchcache', '{}'))
  1162. const now = (new Date()).getTime()
  1163. const timeout = 2 * 60 * 60 * 1000
  1164. for (const prop in cache) {
  1165. // Delete cached values, that are older than 2 hours
  1166. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1167. delete cache[prop]
  1168. }
  1169. }
  1170.  
  1171. if (current.type === 'music') {
  1172. current.searchTerm = current.data[0]
  1173. } else {
  1174. current.searchTerm = current.data.join(' ')
  1175. }
  1176. let response
  1177. if (current.searchTerm in cache) {
  1178. response = cache[current.searchTerm]
  1179. } else {
  1180. response = await asyncRequest({
  1181. method: 'POST',
  1182. url: baseURLautosearch,
  1183. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1184. headers: {
  1185. Referer: current.metaurl,
  1186. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1187. // Host: 'www.metacritic.com',
  1188. 'User-Agent': 'MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0',
  1189. 'X-Requested-With': 'XMLHttpRequest'
  1190. }
  1191. })
  1192. response = {
  1193. time: (new Date()).toJSON(),
  1194. json: JSON.parse(response.responseText)
  1195. }
  1196. cache[current.searchTerm] = response
  1197. await GM.setValue('autosearchcache', JSON.stringify(cache))
  1198. }
  1199.  
  1200. if (!response || !('json' in response)) {
  1201. alert('ShowMetacriticRatings: Error 05')
  1202. }
  1203. const data = response.json
  1204. let multiple = false
  1205. if (data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  1206. // Remove data with wrong type
  1207. data.autoComplete = data.autoComplete.results
  1208.  
  1209. const newdata = []
  1210. data.autoComplete.forEach(function (result) {
  1211. if (metacritic2searchType(result.refType) === current.type) {
  1212. newdata.push(result)
  1213. }
  1214. })
  1215. data.autoComplete = newdata
  1216. if (data.autoComplete.length === 0) {
  1217. // No results
  1218. console.debug('ShowMetacriticRatings: No results (after filtering by type) for searchTerm=' + current.searchTerm)
  1219. } else if (data.autoComplete.length === 1) {
  1220. // One result, let's show it
  1221. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(data.autoComplete[0].url))) {
  1222. current.metaurl = absoluteMetaURL(data.autoComplete[0].url)
  1223. loadMetacriticUrl(true)
  1224. return
  1225. }
  1226. } else {
  1227. // More than one result
  1228. multiple = true
  1229. console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm)
  1230. const exactMatches = []
  1231. data.autoComplete.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title
  1232. if (current.searchTerm === result.name) {
  1233. exactMatches.push(result)
  1234. }
  1235. })
  1236. if (exactMatches.length === 1) {
  1237. // Only one exact match, let's show it
  1238. console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm)
  1239. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(exactMatches[0].url))) {
  1240. current.metaurl = absoluteMetaURL(exactMatches[0].url)
  1241. loadMetacriticUrl(true)
  1242. return
  1243. }
  1244. }
  1245. }
  1246. } else {
  1247. console.debug('ShowMetacriticRatings: No results (at all) for searchTerm=' + current.searchTerm)
  1248. }
  1249. // HERE: multiple results or no result. The user may type "meta" now
  1250. if (multiple) {
  1251. balloonAlert('Multiple metacritic results. Type &#34;meta&#34; for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5 }, () => openSearchBox(true))
  1252. }
  1253. }
  1254.  
  1255. function openSearchBox (search) {
  1256. let query
  1257. if (current.type === 'music') {
  1258. query = current.data[0]
  1259. } else {
  1260. query = current.data.join(' ')
  1261. }
  1262. $('#mcdiv123').remove()
  1263. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1264. div.css({
  1265. position: 'fixed',
  1266. bottom: 0,
  1267. left: 0,
  1268. minWidth: 300,
  1269. maxHeight: '80%',
  1270. maxWidth: 640,
  1271. overflow: 'auto',
  1272. backgroundColor: '#fff',
  1273. border: '2px solid #bbb',
  1274. borderRadius: ' 6px',
  1275. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1276. color: '#000',
  1277. padding: ' 3px',
  1278. zIndex: '2147483601'
  1279. })
  1280.  
  1281. GM.getValue('position', false).then(function (s) {
  1282. if (s) {
  1283. div.css({
  1284. top: '',
  1285. left: '',
  1286. bottom: '',
  1287. right: ''
  1288. })
  1289. div.css(JSON.parse(s))
  1290. }
  1291. })
  1292.  
  1293. $('<input type="text" size="60" id="mcisearchquery" style="background:white;color:black;">').appendTo(div).focus().val(query).on('keypress', function (e) {
  1294. const code = e.keyCode || e.which
  1295. if (code === 13) { // Enter key
  1296. searchBoxSearch(e, $('#mcisearchquery').val())
  1297. }
  1298. })
  1299. $('<button id="mcisearchbutton" style="background:silver;color:black;">').text('Search').appendTo(div).click((ev) => searchBoxSearch(ev, $('#mcisearchquery').val()))
  1300. }
  1301. async function searchBoxSearch (ev, query) {
  1302. if (!query) { // Use values from search form
  1303. query = current.searchTerm
  1304. }
  1305.  
  1306. const type = searchType2metacritic(current.type)
  1307.  
  1308. const style = document.createElement('style')
  1309. style.type = 'text/css'
  1310. style.innerHTML = CSS
  1311. document.head.appendChild(style)
  1312.  
  1313. const div = $('#mcdiv123')
  1314. const loader = $('<div style="width:20px; height:20px;display:inline-block" class="grespinner"></div>').appendTo($('#mcisearchbutton'))
  1315.  
  1316. const url = baseURLsearch.replace('{type}', encodeURIComponent(type)).replace('{query}', encodeURIComponent(query))
  1317.  
  1318. const response = await asyncRequest({
  1319. url,
  1320. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1321. headers: {
  1322. Referer: url,
  1323. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1324. // Host: 'www.metacritic.com',
  1325. 'User-Agent': 'MetacriticUserscript ' + navigator.userAgent
  1326. }
  1327. }).catch(function (response) {
  1328. alert('Search failed!\n' + response.finalUrl + '\nStatus: ' + response.status + '\n' + response.responseText ? response.responseText.substring(0, 500) : 'Empty response')
  1329. })
  1330.  
  1331. const results = []
  1332. if (!~response.responseText.indexOf('No search results found.')) {
  1333. const d = $('<html>').html(response.responseText)
  1334. d.find('ul.search_results.module .result').each(function () {
  1335. results.push(this.innerHTML)
  1336. })
  1337. }
  1338.  
  1339. if (results && results.length > 0) {
  1340. // Show results
  1341. loader.remove()
  1342.  
  1343. const accept = function (ev) {
  1344. const parentDiv = $(this.parentNode)
  1345. const a = parentDiv.find("a[href*='metacritic.com']")
  1346. const metaurl = a.attr('href')
  1347. const docurl = document.location.href
  1348.  
  1349. const resultDivParent = parentDiv.parent()
  1350. resultDivParent.html('')
  1351. resultDivParent.append(loader)
  1352.  
  1353. removeFromBlacklist(docurl, metaurl).then(function () {
  1354. addToMap(docurl, metaurl).then(function () {
  1355. current.metaurl = metaurl
  1356. loadMetacriticUrl().then(() => loader.remove())
  1357. })
  1358. })
  1359. }
  1360. const denyAll = function (ev) {
  1361. const docurl = document.location.href
  1362. $('#mcdiv123searchresults').find("div.result a[href*='metacritic.com']").each(function () {
  1363. addToBlacklist(docurl, this.href)
  1364. })
  1365. }
  1366.  
  1367. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').css('max-width', '95%').appendTo(div)
  1368. results.forEach(function (html) {
  1369. const singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html) + '<div style="clear:left"></div>').appendTo(resultdiv)
  1370. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept)
  1371. })
  1372. resultdiv.find('.metascore_w.album').removeClass('album') // Remove some classes
  1373. resultdiv.find('.must-see').remove() // Remove some elements
  1374.  
  1375. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1376. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1377. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1378. document.body.removeChild(this.parentNode.parentNode)
  1379. })
  1380. $('<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() })
  1381. } else {
  1382. // No results
  1383. loader.remove()
  1384. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1385. resultdiv.html('No search results.')
  1386.  
  1387. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1388. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1389. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1390. document.body.removeChild(this.parentNode.parentNode)
  1391. })
  1392. }
  1393. }
  1394.  
  1395. function showHoverInfo (response, orgMetaUrl) {
  1396. const html = fixMetacriticURLs(response.responseText)
  1397. const time = new Date(response.time)
  1398. const url = response.finalUrl
  1399.  
  1400. $('#mcdiv123').remove()
  1401. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1402. div.css({
  1403. position: 'fixed',
  1404. bottom: 0,
  1405. left: 0,
  1406. minWidth: 300,
  1407. backgroundColor: '#fff',
  1408. border: '2px solid #bbb',
  1409. borderRadius: ' 6px',
  1410. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1411. color: '#000',
  1412. padding: ' 3px',
  1413. zIndex: '2147483601'
  1414. })
  1415.  
  1416. GM.getValue('position', false).then(function (s) {
  1417. if (s) {
  1418. div.css({
  1419. top: '',
  1420. left: '',
  1421. bottom: '',
  1422. right: ''
  1423. })
  1424. div.css(JSON.parse(s))
  1425. }
  1426. })
  1427.  
  1428. // Functions for communication between page and iframe
  1429. // Mozilla can access parent.document
  1430. // Chrome can use postMessage()
  1431. let frameStatus = false // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  1432. function loadExternalImage (url, myframe) {
  1433. // Load external image, bypass CSP
  1434. GM.xmlHttpRequest({
  1435. method: 'GET',
  1436. url,
  1437. responseType: 'arraybuffer',
  1438. onload: function (response) {
  1439. myframe.contentWindow.postMessage({
  1440. mcimessage_imgLoaded: true,
  1441. mcimessage_imgData: response.response,
  1442. mcimessage_imgOrgSrc: url
  1443. }, '*')
  1444. }
  1445. })
  1446. }
  1447. const functions = {
  1448. parent: function () {
  1449. const f = parent.document.getElementById('mciframe123')
  1450. let lastdiff = -200000
  1451. window.addEventListener('message', function (e) {
  1452. if (typeof e.data !== 'object') {
  1453. return
  1454. } else if ('mcimessage0' in e.data) {
  1455. frameStatus = true // Frame content was loaded successfully
  1456. } else if ('mcimessage1' in e.data) {
  1457. f.style.width = parseInt(f.style.width) + 10 + 'px'
  1458. if (e.data.heightdiff === lastdiff) {
  1459. f.style.height = parseInt(f.style.height) + 5 + 'px'
  1460. }
  1461. lastdiff = e.data.heightdiff
  1462. } else if ('mcimessage2' in e.data) {
  1463. f.style.height = parseInt(f.style.height) + 15 + 'px'
  1464. f.style.width = '400px'
  1465. } else if ('mcimessage_loadImg' in e.data) {
  1466. loadExternalImage(e.data.mcimessage_imgUrl, f)
  1467. } else {
  1468. return
  1469. }
  1470. if (f.contentWindow != null) {
  1471. f.contentWindow.postMessage({
  1472. mcimessage3: true,
  1473. mciframe123_clientHeight: f.clientHeight,
  1474. mciframe123_clientWidth: f.clientWidth
  1475. }, '*')
  1476. }
  1477. })
  1478. },
  1479. frame: function () {
  1480. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1481.  
  1482. let i = 0
  1483. window.addEventListener('message', function (e) {
  1484. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1485. // Load external image
  1486. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1487. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1488. const urlCreator = window.URL || window.webkitURL
  1489. const imageUrl = urlCreator.createObjectURL(blob)
  1490. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1491. img.src = imageUrl
  1492. }
  1493.  
  1494. if (!('mcimessage3' in e.data)) return
  1495.  
  1496. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1497. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1498. i++
  1499. }
  1500. if (i >= 100) {
  1501. parent.postMessage({ mcimessage2: 1 }, '*')
  1502. i = 0
  1503. }
  1504. })
  1505. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1506. }
  1507.  
  1508. }
  1509.  
  1510. const css = `#hover_div .clr { clear: both}
  1511. #hover_div .fl{float: left}
  1512. #hover_div { background-color: #fff; color: #666; font-family:Arial,Helvetica,sans-serif; font-size:12px; font-weight:400; font-style:normal;}
  1513. #hover_div .hoverinfo .hover_left { float: left}
  1514. #hover_div .hoverinfo .product_image_wrapper { color: #999; font-size: 6px; font-weight: normal; min-height: 98px; min-width: 98px;}
  1515. #hover_div .hoverinfo .product_image_wrapper a { color: #999; font-size: 6px; font-weight: normal;}
  1516. #hover_div a * { cursor: pointer}
  1517. #hover_div a { color: #09f; font-weight: bold;}
  1518. #hover_div a:link, #hover_div a:visited { text-decoration: none;}
  1519. #hover_div a:hover { text-decoration: underline;}
  1520. #hover_div .hoverinfo .hover_right { float: left; margin-left: 15px; max-width: 395px;}
  1521. #hover_div .hoverinfo .product_title { color: #333; font-family: georgia,serif; font-size: 24px; line-height: 26px; margin-bottom: 10px;}
  1522. #hover_div .hoverinfo .product_title a { color:#333; font-family: georgia,serif; font-size: 24px;}
  1523. #hover_div .hoverinfo .summary_detail.publisher, .hoverinfo .summary_detail.release_data { float: left}
  1524. #hover_div .hoverinfo .summary_detail { font-size: 11px; margin-bottom: 10px;}
  1525. #hover_div .hoverinfo .summary_detail.product_credits a { color: #999; font-weight: normal; }
  1526. #hover_div .hoverinfo .hr { background-color: #ccc; height: 2px; margin: 15px 0 10px;}
  1527. #hover_div .hoverinfo .hover_scores { width: 100%; border-collapse: collapse; border-spacing: 0;}
  1528. #hover_div .hoverinfo .hover_scores td.num { width: 39px}
  1529. #hover_div .hoverinfo .hover_scores td { vertical-align: middle}
  1530. #hover_div caption, #hover_div th, #hover_div td { font-weight: normal; text-align: left;}
  1531. #hover_div .metascore_anchor, #hover_div a.metascore_w { text-decoration: none !important}
  1532. #hover_div span.metascore_w, #hover_div a.metascore_w { display: inline-block; padding:0px;}
  1533. .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;}
  1534. #hover_div .metascore, #hover_div .metascore a, #hover_div .avguserscore, #hover_div .avguserscore a { color: #fff}
  1535. #hover_div .critscore, #hover_div .critscore a, #hover_div .userscore, #hover_div .userscore a { color: #333}
  1536. .score_tbd { background: #eaeaea; color: #333; font-size: 14px;}
  1537. #hover_div .score_tbd a { color: #333}
  1538. #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}
  1539. #hover_div.mixed, .neutral,#hover_div .score_mixed,#hover_div .carousel_set a.product_mixed:hover { background-color: #fc3; color: #333;}
  1540. #hover_div .score_mixed a { color: #333}
  1541. #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}
  1542. .critscore_terrible, .critscore_unfavorable { border-color: #f00}
  1543. .critscore_mixed { border-color: #fc3}
  1544. .critscore_favorable, .critscore_outstanding { border-color: #6c3}
  1545. .metascore .score_total, .userscore .score_total { display: none; visibility: hidden;}
  1546. .hoverinfo .metascore_label, .hoverinfo .userscore_label { font-size: 12px; font-weight: bold; line-height: 16px; margin-top: 2%;}
  1547. .hoverinfo .metascore_review_count, .hoverinfo .userscore_review_count { font-size: 11px}
  1548. .hoverinfo .hover_scores td { vertical-align: middle}
  1549. .hoverinfo .hover_scores td.num { width: 39px}
  1550. .hoverinfo .hover_scores td.usr.num { padding-left: 20px}
  1551. .metascore_anchor, a.metascore_w { text-decoration: none !important}
  1552. .metascore_w.album { padding-top:0px; !important}
  1553. .metascore_w.user { border-radius: 55%; color: #fff;}
  1554. .metascore_anchor, .metascore_w.album { padding: 0px;!important, padding-top: 0px;!important}
  1555. a.metascore_w { text-decoration: none!important}
  1556. .metascore_anchor:hover { text-decoration: none!important}
  1557. .metascore_w:hover { text-decoration: none!important}
  1558. span.metascore_w, a.metascore_w { display: inline-block}
  1559. .metascore_w.xlarge, .metascore_w.xl { font-size: 42px}
  1560. .metascore_w.large, .metascore_w.lrg { font-size: 25px}
  1561. .m .metascore_w.medium, .m .metascore_w.med { font-size: 19px}
  1562. .metascore_w.med_small { font-size: 14px}
  1563. .metascore_w.small, .metascore_w.sm { font-size: 12px}
  1564. .metascore_w.tiny { height: 1.9em; font-size: 11px; line-height: 1.9em;}
  1565. .metascore_w.user { border-radius: 55%; color: #fff;}
  1566. .metascore_w.user.small, .metascore_w.user.sm { font-size: 11px}
  1567. .metascore_w.tbd, .metascore_w.score_tbd { color: #000!important; background-color: #ccc;}
  1568. .metascore_w.tbd.hide_tbd, .metascore_w.score_tbd.hide_tbd { visibility: hidden}
  1569. .metascore_w.tbd.no_tbd, .metascore_w.score_tbd.no_tbd { display: none}
  1570. .metascore_w.noscore::before, .metascore_w.score_noscore::before { content: '\u2022\u2022\u2022'}
  1571. .metascore_w.noscore, .metascore_w.score_noscore { color: #fff!important; background-color: #ccc;}
  1572. .metascore_w.rip, .metascore_w.score_rip { border-radius: 4px; color: #fff!important; background-color: #999;}
  1573. .metascore_w.negative, .metascore_w.score_terrible, .metascore_w.score_unfavorable { background-color: #f00}
  1574. .metascore_w.mixed, .metascore_w.forty, .metascore_w.game.fifty, .metascore_w.score_mixed { background-color: #fc3}
  1575. .metascore_w.positive, .metascore_w.sixtyone, .metascore_w.game.seventyfive, .metascore_w.score_favorable, .metascore_w.score_outstanding { background-color: #6c3}
  1576. .metascore_w.indiv { height: 1.9em; width: 1.9em; font-size: 15px; line-height: 1.9em;}
  1577. .metascore_w.indiv.large, .metascore_w.indiv.lrg { font-size: 24px}
  1578. .m .metascore_w.indiv.medium, .m .metascore_w.indiv.med { font-size: 16px}
  1579. .metascore_w.indiv.small, .metascore_w.indiv.sm { font-size: 11px}
  1580. .metascore_w.indiv.perfect { padding-right: 1px}
  1581. .hover_esite { display:none; }
  1582. .promo_amazon .esite_btn { margin: 3px 0 0 7px;}
  1583. .esite_amazon { background-color: #fdc354; border: 1px solid #aaa;}
  1584. .esite_label_wrapper { display:none;}
  1585. .esite_btn { border-radius: 4px; color: #222; font-size: 12px; height: 40px; line-height: 40px; width: 120px;}
  1586. .chart{background-color:inherit!important;margin-top:-3px}
  1587. .chart_bg{width:100%;border-top:3px solid rgba(150,150,150,0.3)}
  1588. .chart .bar{width:100%;height:3px}
  1589. .chart .count{font-size:10px}`
  1590.  
  1591. let framesrc = 'data:text/html,'
  1592. framesrc += encodeURIComponent(`<!DOCTYPE html>
  1593. <html lang="en">
  1594. <head>
  1595. <meta charset="utf-8">
  1596. <title>Metacritic info</title>
  1597. <style>body { margin:0px; padding:0px; background:white; }${css}
  1598. </style>
  1599. <script>
  1600. const failedImages = {};
  1601. function detectCSP(img) {
  1602. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {
  1603. return true;
  1604. }
  1605. return false;
  1606. }
  1607. function findCSPerrors() {
  1608. const imgs = document.querySelectorAll("img");
  1609. for(let i = 0; i < imgs.length; i++) {
  1610. if(imgs[i].complete && detectCSP(imgs[i])) {
  1611. fixCSP(imgs[i]);
  1612. }
  1613. }
  1614. }
  1615. function fixCSP(img) {
  1616. console.debug("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");
  1617. failedImages[img.src] = img;
  1618. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*");
  1619. }
  1620. function on_load() {
  1621. (${functions.frame.toString()})();
  1622. window.setTimeout(findCSPerrors, 500);
  1623. }
  1624. </script>
  1625. </head>
  1626. <body onload="on_load();">
  1627. <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">
  1628. <div class="hover_content">${html}</div>
  1629. </div>
  1630. </body>
  1631. </html>`)
  1632.  
  1633. const frame = $('<iframe></iframe>').appendTo(div)
  1634. frame.attr('id', 'mciframe123')
  1635. frame.attr('src', framesrc)
  1636. frame.attr('scrolling', 'auto')
  1637. frame.css({
  1638. width: 380,
  1639. height: 150,
  1640. border: 'none'
  1641. })
  1642.  
  1643. window.setTimeout(function () {
  1644. if (!frameStatus) { // Loading frame content failed.
  1645. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1646. console.debug('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1647. $('head').append(`<style>${css}</style>`)
  1648. 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">
  1649. <div class="hover_content">${html}</div>
  1650. </div>`)
  1651. frame.replaceWith(noframe)
  1652. }
  1653. }, 2000)
  1654.  
  1655. functions.parent()
  1656.  
  1657. const sub = $('<div></div>').appendTo(div)
  1658. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1659. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1660. $('<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 () {
  1661. const metaurl = $(this).data('url')
  1662. addToTemporaryBlacklist(metaurl)
  1663. document.body.removeChild(this.parentNode.parentNode)
  1664. })
  1665.  
  1666. $('<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 () {
  1667. const docurl = document.location.href
  1668. const metaurl = $(this).data('url')
  1669. addToMap(docurl, metaurl).then(function (r) {
  1670. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1671. })
  1672. })
  1673. $('<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 () {
  1674. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1675. const docurl = document.location.href
  1676. const metaurl = $(this).data('url')
  1677. addToBlacklist(docurl, metaurl).then(function (r) {
  1678. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1679. })
  1680.  
  1681. openSearchBox(true)
  1682. })
  1683.  
  1684. // Store response in cache:
  1685. if (!('cached' in response)) {
  1686. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  1687. }
  1688. }
  1689.  
  1690. function metacriticGeneralProductSetup () {
  1691. current.broadenCounter = 0
  1692. }
  1693.  
  1694. const metacritic = {
  1695. mapped: function metacriticMapped (docurl, product, metaurl, type) {
  1696. // url was in the map/whitelist
  1697. current.data = []
  1698. current.docurl = docurl
  1699. current.product = product
  1700. current.metaurl = metaurl
  1701. current.type = type
  1702. current.searchTerm = null
  1703. loadMetacriticUrl()
  1704. },
  1705. music: function metacriticMusic (docurl, product, artistname, albumname) {
  1706. current.data = [albumname.trim(), artistname.trim()]
  1707. artistname = name2metacritic(artistname)
  1708. albumname = albumname.replace('&', ' ')
  1709. albumname = name2metacritic(albumname)
  1710. current.docurl = docurl
  1711. current.product = product
  1712. current.metaurl = baseURLmusic + albumname + '/' + artistname
  1713. current.type = 'music'
  1714. current.searchTerm = albumname + '/' + artistname
  1715. loadMetacriticUrl()
  1716. },
  1717. movie: function metacriticMovie (docurl, product, moviename) {
  1718. current.data = [moviename.trim()]
  1719. moviename = name2metacritic(moviename)
  1720. current.docurl = docurl
  1721. current.product = product
  1722. current.metaurl = baseURLmovie + moviename
  1723. current.type = 'movie'
  1724. current.searchTerm = moviename
  1725. loadMetacriticUrl()
  1726. },
  1727. tv: function metacriticTv (docurl, product, seriesname) {
  1728. current.data = [seriesname.trim()]
  1729. seriesname = name2metacritic(seriesname)
  1730. current.docurl = docurl
  1731. current.product = product
  1732. current.metaurl = baseURLtv + seriesname
  1733. current.type = 'tv'
  1734. current.searchTerm = seriesname
  1735. loadMetacriticUrl()
  1736. },
  1737. pcgame: function metacriticPcgame (docurl, product, gamename) {
  1738. current.data = [gamename.trim()]
  1739. gamename = name2metacritic(gamename)
  1740. current.docurl = docurl
  1741. current.product = product
  1742. current.metaurl = baseURLpcgame + gamename
  1743. current.type = 'pcgame'
  1744. current.searchTerm = gamename
  1745. loadMetacriticUrl()
  1746. },
  1747. ps4game: function metacriticPs4game (docurl, product, gamename) {
  1748. current.data = [gamename.trim()]
  1749. gamename = name2metacritic(gamename)
  1750. current.docurl = docurl
  1751. current.product = product
  1752. current.metaurl = baseURLps4 + gamename
  1753. current.type = 'ps4game'
  1754. current.searchTerm = gamename
  1755. loadMetacriticUrl()
  1756. },
  1757. xonegame: function metacriticXonegame (docurl, product, gamename) {
  1758. current.data = [gamename.trim()]
  1759. gamename = name2metacritic(gamename)
  1760. current.docurl = docurl
  1761. current.product = product
  1762. current.metaurl = baseURLxone + gamename
  1763. current.type = 'xonegame'
  1764. current.searchTerm = gamename
  1765. loadMetacriticUrl()
  1766. }
  1767. }
  1768.  
  1769. const Always = () => true
  1770. const sites = {
  1771. bandcamp: {
  1772. host: ['bandcamp.com'],
  1773. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  1774. products: [{
  1775. condition: Always,
  1776. type: 'music',
  1777. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1778. }]
  1779. },
  1780. itunes: {
  1781. host: ['itunes.apple.com'],
  1782. condition: Always,
  1783. products: [{
  1784. condition: () => ~document.location.href.indexOf('/movie/'),
  1785. type: 'movie',
  1786. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1787. },
  1788. {
  1789. condition: () => ~document.location.href.indexOf('/tv-season/'),
  1790. type: 'tv',
  1791. data: function () {
  1792. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1793. if (~name.indexOf(', Season')) {
  1794. name = name.split(', Season')[0]
  1795. }
  1796. return name
  1797. }
  1798. },
  1799. {
  1800. condition: () => ~document.location.href.indexOf('/album/'),
  1801. type: 'music',
  1802. data: function () {
  1803. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1804. const album = ld[0]
  1805. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1806. return [artist, album]
  1807. }
  1808. }]
  1809. },
  1810. 'music.apple': {
  1811. host: ['music.apple.com'],
  1812. condition: Always,
  1813. products: [{
  1814. condition: () => ~document.location.href.indexOf('/album/') && parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum')).length > 1,
  1815. type: 'music',
  1816. data: function () {
  1817. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1818. const album = ld[0]
  1819. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1820. return [artist, album]
  1821. }
  1822. }]
  1823. },
  1824. googleplay: {
  1825. host: ['play.google.com'],
  1826. condition: Always,
  1827. products: [
  1828. {
  1829. condition: () => ~document.location.href.indexOf('/album/'),
  1830. type: 'music',
  1831. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  1832. },
  1833. {
  1834. condition: () => ~document.location.href.indexOf('/movies/details/'),
  1835. type: 'movie',
  1836. data: () => document.querySelector('*[itemprop=name]').textContent
  1837. }
  1838. ]
  1839. },
  1840. imdb: {
  1841. host: ['imdb.com'],
  1842. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  1843. products: [
  1844. {
  1845. condition: () => document.querySelector('a[href*="/criticreviews/"'),
  1846. type: 'mapped',
  1847. data: async function () {
  1848. // This is used if there is a metacritic link on the imdb page
  1849. const criticsUrl = document.querySelector('a[href*="/criticreviews/"').href.toString()
  1850. const response = await asyncRequest({ url: criticsUrl }).catch(function (response) {
  1851. console.warn('ShowMetacriticRatings: Error imdb01\nurl=' + criticsUrl + '\nstatus=' + response.status)
  1852. })
  1853. const m = response.responseText.match(/(https:\/\/www\.metacritic\.com\/\w+\/[^?&"']+)/)
  1854. console.debug('ShowMetacriticRatings: Metacritic link found on imdb:', m[1])
  1855. return m[1]
  1856. }
  1857. },
  1858. {
  1859. condition: function () {
  1860. const e = document.querySelector("meta[property='og:type']")
  1861. if (e && e.content === 'video.movie') {
  1862. return true
  1863. } else if (document.querySelector('[data-testid="hero__pageTitle"]') && !document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1864. return true
  1865. }
  1866. return false
  1867. },
  1868. type: 'movie',
  1869. data: async function () {
  1870. // If the page is not in English or the browser is not in English, request page in English.
  1871. // Then the title in <h1> will be the English title and Metacritic always uses the English title.
  1872. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  1873. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  1874. const langM = document.cookie.match(/lc-main=([^;]+)/)
  1875. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  1876. document.cookie = 'lc-main=en-US'
  1877. const response = await asyncRequest({
  1878. url: document.location.href,
  1879. headers: {
  1880. 'Accept-Language': 'en-US,en'
  1881. }
  1882. }).catch(function (response) {
  1883. console.warn('ShowMetacriticRatings: Error imdb02\nurl=' + document.location.href + '\nstatus=' + response.status)
  1884. })
  1885. document.cookie = 'lc-main=' + langBefore
  1886. // Extract <h1> title
  1887. const parts = response.responseText.split('</span></h1>')[0].split('>')
  1888. console.debug('ShowMetacriticRatings: Movie title from English page:', parts[parts.length - 1])
  1889. return parts[parts.length - 1]
  1890. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1891. const ld = parseLDJSON(['name', 'alternateName'])
  1892. if (ld.length > 1 && ld[1]) {
  1893. console.debug('ShowMetacriticRatings: Movie ld+json alternateName', ld[1])
  1894. return ld[1]
  1895. }
  1896. console.debug('ShowMetacriticRatings: Movie ld+json name', ld[0])
  1897. return ld[0]
  1898. } else {
  1899. console.debug('ShowMetacriticRatings: Movie <title>', document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1])
  1900. return document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1]
  1901. }
  1902. }
  1903. },
  1904. {
  1905. condition: function () {
  1906. const e = document.querySelector("meta[property='og:type']")
  1907. if (e && e.content === 'video.tv_show') {
  1908. return true
  1909. } else if (document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1910. return true
  1911. }
  1912. return false
  1913. },
  1914. type: 'tv',
  1915. data: async function () {
  1916. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  1917. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  1918. const langM = document.cookie.match(/lc-main=([^;]+)/)
  1919. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  1920. document.cookie = 'lc-main=en-US'
  1921. const response = await asyncRequest({
  1922. url: document.location.href,
  1923. headers: {
  1924. 'Accept-Language': 'en-US,en'
  1925. }
  1926. }).catch(function (response) {
  1927. console.warn('ShowMetacriticRatings: Error imdb03\nurl=' + document.location.href + '\nstatus=' + response.status)
  1928. })
  1929. document.cookie = 'lc-main=' + langBefore
  1930. // Extract <h1> title
  1931. const parts = response.responseText.split('</span></h1>')[0].split('>')
  1932. console.debug('ShowMetacriticRatings: TV title from English page:', parts[parts.length - 1])
  1933. return parts[parts.length - 1]
  1934. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1935. const ld = parseLDJSON(['name', 'alternateName'])
  1936. if (ld.length > 1 && ld[1]) {
  1937. console.debug('ShowMetacriticRatings: TV ld+json alternateName', ld[1])
  1938. return ld[1]
  1939. }
  1940. console.debug('ShowMetacriticRatings: TV ld+json name', ld[0])
  1941. return ld[0]
  1942. } else {
  1943. console.debug('ShowMetacriticRatings: TV <title>', document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1])
  1944. return document.title.match(/(.+?)\s+\(TV/)[1]
  1945. }
  1946. }
  1947. }
  1948. ]
  1949. },
  1950. steam: {
  1951. host: ['store.steampowered.com'],
  1952. condition: () => document.querySelector('*[itemprop=name]'),
  1953. products: [{
  1954. condition: Always,
  1955. type: 'pcgame',
  1956. data: () => document.querySelector('*[itemprop=name]').textContent
  1957. }]
  1958. },
  1959. rottentomatoes: {
  1960. host: ['rottentomatoes.com'],
  1961. condition: Always,
  1962. products: [{
  1963. condition: () => document.location.pathname.startsWith('/m/'),
  1964. type: 'movie',
  1965. data: () => document.querySelector('h1').firstChild.textContent
  1966. },
  1967. {
  1968. condition: () => document.location.pathname.startsWith('/tv/'),
  1969. type: 'tv',
  1970. data: () => unsafeWindow.BK.TvSeriesTitle
  1971. }
  1972. ]
  1973. },
  1974. serienjunkies: {
  1975. host: ['www.serienjunkies.de'],
  1976. condition: Always,
  1977. products: [{
  1978. condition: () => Always,
  1979. type: 'tv',
  1980. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1981. }]
  1982. },
  1983. gamespot: {
  1984. host: ['gamespot.com'],
  1985. condition: () => document.querySelector('[itemprop=device]'),
  1986. products: [
  1987. {
  1988. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  1989. type: 'pcgame',
  1990. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1991. },
  1992. {
  1993. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  1994. type: 'ps4game',
  1995. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1996. },
  1997. {
  1998. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  1999. type: 'xonegame',
  2000. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  2001. }
  2002. ]
  2003. },
  2004. amazon: {
  2005. host: ['amazon.'],
  2006. condition: Always,
  2007. products: [
  2008. {
  2009. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  2010. type: 'music',
  2011. data: function () {
  2012. const artist = document.querySelector('.artistLink').textContent.trim()
  2013. let title = document.querySelector('.viewTitle').textContent.trim()
  2014. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2015. if (artist && title) {
  2016. return [artist, title]
  2017. }
  2018. return false
  2019. }
  2020. },
  2021. {
  2022. condition: function () { // "Normal amazon" page
  2023. try {
  2024. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  2025. return true
  2026. }
  2027. } catch (e) {}
  2028. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  2029. return music.some(function (s) {
  2030. if (~document.title.indexOf(s)) {
  2031. return true
  2032. } else {
  2033. return false
  2034. }
  2035. })
  2036. },
  2037. type: 'music',
  2038. data: function () {
  2039. let artist = false
  2040. let title = false
  2041. if (document.querySelector('#ProductInfoArtistLink')) {
  2042. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  2043. } else if (document.querySelector('#bylineInfo .author>*')) {
  2044. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  2045. }
  2046.  
  2047. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  2048. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  2049. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2050. } else if (document.querySelector('#productTitle')) {
  2051. title = document.querySelector('#productTitle').textContent.trim()
  2052. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  2053. }
  2054. return [artist, title]
  2055. }
  2056. },
  2057. {
  2058. condition: () => (document.querySelector('[data-automation-id=title]') && (
  2059. document.getElementsByClassName('av-season-single').length ||
  2060. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  2061. document.getElementById('tab-selector-episodes') ||
  2062. document.getElementById('av-droplist-av-atf-season-selector')
  2063. )),
  2064. type: 'tv',
  2065. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  2066. },
  2067. {
  2068. condition: () => ((
  2069. document.getElementsByClassName('av-season-single').length ||
  2070. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  2071. document.getElementById('tab-selector-episodes') ||
  2072. document.getElementById('av-droplist-av-atf-season-selector')
  2073. ) && Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).some((x) => x != null)),
  2074. type: 'tv',
  2075. data: () => Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).filter((x) => x != null)[0][1]
  2076. },
  2077. {
  2078. condition: () => document.querySelector('[data-automation-id=title]'),
  2079. type: 'movie',
  2080. data: () => document.querySelector('[data-automation-id=title]').textContent.trim().replace(/\[.{1,8}\]/, '')
  2081. }
  2082. ]
  2083. },
  2084. BoxOfficeMojo: {
  2085. host: ['boxofficemojo.com'],
  2086. condition: () => Always,
  2087. products: [
  2088. {
  2089. condition: () => document.location.pathname.startsWith('/release/'),
  2090. type: 'movie',
  2091. data: () => document.querySelector('meta[name=title]').content
  2092. },
  2093. {
  2094. // Old page design
  2095. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  2096. type: 'movie',
  2097. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.textContent
  2098. }]
  2099. },
  2100. AllMovie: {
  2101. host: ['allmovie.com'],
  2102. condition: () => document.querySelector('h2.movie-title'),
  2103. products: [{
  2104. condition: () => document.querySelector('h2.movie-title'),
  2105. type: 'movie',
  2106. data: () => document.querySelector('h2.movie-title').firstChild.textContent.trim()
  2107. }]
  2108. },
  2109. 'en.wikipedia': {
  2110. host: ['en.wikipedia.org'],
  2111. condition: Always,
  2112. products: [{
  2113. condition: function () {
  2114. if (!document.querySelector('.infobox .summary')) {
  2115. return false
  2116. }
  2117. const r = /\d\d\d\d films/
  2118. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2119. },
  2120. type: 'movie',
  2121. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2122. },
  2123. {
  2124. condition: function () {
  2125. if (!document.querySelector('.infobox .summary')) {
  2126. return false
  2127. }
  2128. const r = /television series/
  2129. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2130. },
  2131. type: 'tv',
  2132. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2133. }]
  2134. },
  2135. fandango: {
  2136. host: ['fandango.com'],
  2137. condition: () => document.querySelector("meta[property='og:title']"),
  2138. products: [{
  2139. condition: Always,
  2140. type: 'movie',
  2141. data: () => document.querySelector("meta[property='og:title']").content.match(/(.+?)\s+\(\d{4}\)/)[1].trim()
  2142. }]
  2143. },
  2144. flixster: {
  2145. host: ['www.flixster.com'],
  2146. condition: () => Always,
  2147. products: [{
  2148. condition: () => parseLDJSON('@type') === 'Movie',
  2149. type: 'movie',
  2150. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2151. }]
  2152. },
  2153. themoviedb: {
  2154. host: ['themoviedb.org'],
  2155. condition: () => document.querySelector("meta[property='og:type']"),
  2156. products: [{
  2157. condition: () => document.querySelector("meta[property='og:type']").content === 'movie',
  2158. type: 'movie',
  2159. data: () => document.querySelector("meta[property='og:title']").content
  2160. },
  2161. {
  2162. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' || document.querySelector("meta[property='og:type']").content === 'tv_series',
  2163. type: 'tv',
  2164. data: () => document.querySelector("meta[property='og:title']").content
  2165. }]
  2166. },
  2167. letterboxd: {
  2168. host: ['letterboxd.com'],
  2169. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  2170. products: [{
  2171. condition: Always,
  2172. type: 'movie',
  2173. data: () => unsafeWindow.filmData.name
  2174. }]
  2175. },
  2176. TVmaze: {
  2177. host: ['tvmaze.com'],
  2178. condition: () => document.querySelector('h1'),
  2179. products: [{
  2180. condition: Always,
  2181. type: 'tv',
  2182. data: () => document.querySelector('h1').firstChild.textContent
  2183. }]
  2184. },
  2185. TVGuide: {
  2186. host: ['tvguide.com'],
  2187. condition: Always,
  2188. products: [{
  2189. condition: () => document.location.pathname.startsWith('/tvshows/'),
  2190. type: 'tv',
  2191. data: function () {
  2192. if (document.querySelector('meta[itemprop=name]')) {
  2193. return document.querySelector('meta[itemprop=name]').content
  2194. } else {
  2195. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  2196. }
  2197. }
  2198. }]
  2199. },
  2200. followshows: {
  2201. host: ['followshows.com'],
  2202. condition: Always,
  2203. products: [{
  2204. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  2205. type: 'tv',
  2206. data: () => document.querySelector("meta[property='og:title']").content
  2207. }]
  2208. },
  2209. TheTVDB: {
  2210. host: ['thetvdb.com'],
  2211. condition: Always,
  2212. products: [{
  2213. condition: () => document.location.pathname.startsWith('/series/'),
  2214. type: 'tv',
  2215. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2216. },
  2217. {
  2218. condition: () => document.location.pathname.startsWith('/movies/'),
  2219. type: 'movie',
  2220. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2221. }]
  2222. },
  2223. ConsequenceOfSound: {
  2224. host: ['consequence.net', 'consequenceofsound.net'],
  2225. condition: () => document.querySelector('#main-content .review-summary'),
  2226. products: [
  2227. {
  2228. condition: () => document.querySelector('meta[name="cXenseParse:cns-artist-names"]') && document.querySelector('em'),
  2229. type: 'music',
  2230. data: function () {
  2231. window.setInterval(function () {
  2232. if (document.getElementById('ot-sdk-btn-floating')) {
  2233. document.getElementById('ot-sdk-btn-floating').remove()
  2234. }
  2235. }, 5000)
  2236. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2237. const arr = Array.from(document.querySelectorAll('em')).map((em) => em.textContent.trim())
  2238. const counts = {}
  2239. for (const num of arr) {
  2240. counts[num] = counts[num] ? counts[num] + 1 : 1
  2241. }
  2242. const max = Math.max(...Object.values(counts))
  2243. const maxIndex = Object.values(counts).indexOf(max)
  2244. const title = Object.keys(counts)[maxIndex]
  2245. return [artist, title]
  2246. }
  2247. },
  2248. {
  2249. condition: () => document.title.match(/'(.*?)'\s*Album/i) && document.querySelector('meta[name="cXenseParse:cns-artist-names"]'),
  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 title = document.title.match(/'(.*?)'\s*Album/i)[1]
  2258. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2259. return [artist, title]
  2260. }
  2261. },
  2262. {
  2263. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  2264. type: 'music',
  2265. data: function () {
  2266. window.setInterval(function () {
  2267. if (document.getElementById('ot-sdk-btn-floating')) {
  2268. document.getElementById('ot-sdk-btn-floating').remove()
  2269. }
  2270. }, 5000)
  2271. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  2272. return [m[1], m[2]]
  2273. }
  2274. },
  2275. {
  2276. condition: () => document.location.pathname.indexOf('/album-review') !== -1 && document.querySelector('a.tag[href*="/artist/"'),
  2277. type: 'music',
  2278. data: function () {
  2279. window.setInterval(function () {
  2280. if (document.getElementById('ot-sdk-btn-floating')) {
  2281. document.getElementById('ot-sdk-btn-floating').remove()
  2282. }
  2283. }, 5000)
  2284. const artistAndTitleWithDash = document.location.pathname.match(/album-review-([\w-]+)/)[1]
  2285. const artistWithDash = document.querySelector('a.tag[href*="/artist/"').pathname.match(/artist\/([\w-]+)/)[1]
  2286. const titleWithDash = artistAndTitleWithDash.replace(artistWithDash, '')
  2287. const title = titleWithDash.replace('-', ' ').trim()
  2288. const artist = artistWithDash.replace('-', ' ').trim()
  2289. return [artist, title]
  2290. }
  2291. }]
  2292. },
  2293. Pitchfork: {
  2294. host: ['pitchfork.com'],
  2295. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  2296. products: [{
  2297. condition: () => document.querySelector('.single-album-tombstone'),
  2298. type: 'music',
  2299. data: function () {
  2300. let artist
  2301. let album
  2302. if (document.querySelector('.single-album-tombstone .artists')) {
  2303. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  2304. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  2305. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  2306. }
  2307. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  2308. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  2309. } else if (document.querySelector('.single-album-tombstone h1')) {
  2310. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  2311. }
  2312.  
  2313. return [artist, album]
  2314. }
  2315. }]
  2316. },
  2317. 'Last.fm': {
  2318. host: ['last.fm'],
  2319. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2320. products: [{
  2321. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2322. type: 'music',
  2323. data: function () {
  2324. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2325. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2326. return [artist, album]
  2327. }
  2328. }]
  2329. },
  2330. TVNfo: {
  2331. host: ['tvnfo.com'],
  2332. condition: () => document.querySelector('.ui.breadcrumb a[href*="/series"]'),
  2333. products: [{
  2334. condition: Always,
  2335. type: 'tv',
  2336. data: function () {
  2337. const years = document.querySelector('#title h1 .years').textContent.trim()
  2338. const title = document.querySelector('#title h1').textContent.replace(years, '').trim()
  2339. return title
  2340. }
  2341. }]
  2342. },
  2343. rateyourmusic: {
  2344. host: ['rateyourmusic.com'],
  2345. condition: () => document.querySelector("meta[property='og:type']"),
  2346. products: [{
  2347. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2348. type: 'music',
  2349. data: function () {
  2350. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2351. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2352. return [artist, album]
  2353. }
  2354. }]
  2355. },
  2356. spotify: {
  2357. host: ['open.spotify.com'],
  2358. condition: Always,
  2359. products: [{
  2360. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector('.Root__main-view h1'),
  2361. type: 'music',
  2362. data: function () {
  2363. const album = document.querySelector('.Root__main-view h1').textContent.trim()
  2364. let artist = []
  2365. document.querySelector('.Root__main-view h1').parentNode.parentNode.parentNode.querySelectorAll('a[href*="/artist/"]').forEach(function (a) {
  2366. artist.push(a.textContent.trim())
  2367. })
  2368. artist = artist.join(' ')
  2369. return [artist, album]
  2370. }
  2371. }]
  2372. },
  2373. nme: {
  2374. host: ['nme.com'],
  2375. condition: () => document.location.pathname.startsWith('/reviews/'),
  2376. products: [
  2377. {
  2378. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/film-reviews"]'),
  2379. type: 'movie',
  2380. data: function () {
  2381. try {
  2382. return document.title.match(/[‘'](.+?)[’']/)[1]
  2383. } catch (e) {
  2384. try {
  2385. return document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2386. } catch (e) {
  2387. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2388. }
  2389. }
  2390. }
  2391. },
  2392. {
  2393. condition: () => document.querySelector('#nme-music-header'),
  2394. type: 'music',
  2395. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/\s*(.+?)\s*.\s*[‘'](.+?)[’']/).slice(1)
  2396. },
  2397. {
  2398. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/tv-reviews"]'),
  2399. type: 'tv',
  2400. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2401. }]
  2402. },
  2403. albumoftheyear: {
  2404. host: ['albumoftheyear.org'],
  2405. condition: Always,
  2406. products: [{
  2407. condition: () => document.location.pathname.startsWith('/album/'),
  2408. type: 'music',
  2409. data: function () {
  2410. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2411. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2412. return [artist, album]
  2413. }
  2414. }]
  2415. },
  2416. epguides: {
  2417. host: ['epguides.com'],
  2418. condition: () => document.getElementById('eplist'),
  2419. products: [{
  2420. condition: () => document.getElementById('eplist') && document.querySelector('.center.titleblock h2'),
  2421. type: 'tv',
  2422. data: () => document.querySelector('.center.titleblock h2').textContent.trim()
  2423. }]
  2424. },
  2425. ShareTV: {
  2426. host: ['sharetv.com'],
  2427. condition: () => document.location.pathname.startsWith('/shows/'),
  2428. products: [{
  2429. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2430. type: 'tv',
  2431. data: () => document.querySelector("meta[property='og:title']").content
  2432. }]
  2433. },
  2434. /*
  2435. netflix: {
  2436. host: ['netflix.com'],
  2437. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2438.  
  2439. // TODO
  2440. // https://www.netflix.com/de/title/70264888
  2441. // https://www.netflix.com/de/title/70178217
  2442. // https://www.netflix.com/de/title/70305892 ## Movie
  2443. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2444.  
  2445. products: [{
  2446. condition: () => parseLDJSON('@type') === 'Movie',
  2447. type: 'movie',
  2448. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2449. },
  2450. {
  2451. condition: () => parseLDJSON('@type') === 'TVSeries',
  2452. type: 'tv',
  2453. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2454. }]
  2455. },
  2456. */
  2457. ComedyCentral: {
  2458. host: ['cc.com'],
  2459. condition: () => document.location.pathname.startsWith('/shows/'),
  2460. products: [{
  2461. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2462. type: 'tv',
  2463. data: () => document.querySelector("meta[property='og:title']").content.replace('| Comedy Central', '').trim()
  2464. },
  2465. {
  2466. condition: () => document.location.pathname.split('/').length === 3 && document.title.match(/(.+?)\s+-\s+Series/),
  2467. type: 'tv',
  2468. data: () => document.title.match(/(.+?)\s+-\s+Series/)[1]
  2469. }]
  2470. },
  2471. TVHoard: {
  2472. host: ['tvhoard.com'],
  2473. condition: Always,
  2474. products: [{
  2475. 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'),
  2476. type: 'movie',
  2477. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2478. },
  2479. {
  2480. 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'),
  2481. type: 'tv',
  2482. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2483. }]
  2484. },
  2485. AMC: {
  2486. host: ['amc.com'],
  2487. condition: () => document.location.pathname.startsWith('/shows/'),
  2488. products: [
  2489. {
  2490. condition: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1'),
  2491. type: 'tv',
  2492. data: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1').textContent
  2493. },
  2494. {
  2495. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2496. type: 'tv',
  2497. data: () => document.querySelector('.video-card-description h1').textContent.trim()
  2498. }]
  2499. },
  2500. AMCplus: {
  2501. host: ['amcplus.com'],
  2502. condition: () => Always,
  2503. products: [
  2504. {
  2505. condition: () => document.title.match(/Watch .+? |/),
  2506. type: 'tv',
  2507. data: () => document.title.match(/Watch (.+?) |/)[1].trim()
  2508. }]
  2509. },
  2510. RlsBB: {
  2511. host: ['comment.rlsbb.ru'],
  2512. condition: () => document.querySelectorAll('.post').length === 1,
  2513. products: [
  2514. {
  2515. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/movies/"]'),
  2516. type: 'movie',
  2517. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+\d{4}/)[1].trim()
  2518. },
  2519. {
  2520. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/tv-shows/"]'),
  2521. type: 'tv',
  2522. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+S\d{2}/)[1].trim()
  2523. }]
  2524. },
  2525. newalbumreleases: {
  2526. host: ['newalbumreleases.net'],
  2527. condition: () => document.querySelectorAll('#content .single').length === 1,
  2528. products: [
  2529. {
  2530. condition: () => document.querySelector('#content .single .cover .entry'),
  2531. type: 'music',
  2532. data: function () {
  2533. const mArtist = document.querySelector('#content .single .cover .entry').textContent.match(/Artist.\s*(.+)\s+/i)
  2534. if (mArtist) {
  2535. const mAlbum = document.querySelector('#content .single .cover .entry').textContent.match(/Album.\s*(.+)\s+/i)
  2536. if (mAlbum) {
  2537. return [mArtist[1], mAlbum[1]]
  2538. }
  2539. }
  2540. }
  2541. }]
  2542. },
  2543. showtime: {
  2544. host: ['sho.com'],
  2545. condition: Always,
  2546. products: [
  2547. {
  2548. condition: () => parseLDJSON('@type') === 'Movie',
  2549. type: 'movie',
  2550. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2551. },
  2552. {
  2553. condition: () => parseLDJSON('@type') === 'TVSeries',
  2554. type: 'tv',
  2555. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2556. }]
  2557. },
  2558. epicgames: {
  2559. host: ['www.epicgames.com', 'store.epicgames.com'],
  2560. condition: () => document.querySelector('.meta-schema'),
  2561. products: [{
  2562. condition: Always,
  2563. type: 'pcgame',
  2564. data: () => document.querySelector('.meta-schema').nextElementSibling.firstElementChild.lastElementChild.firstElementChild.firstElementChild.firstElementChild.textContent
  2565. }]
  2566. },
  2567. gog: {
  2568. host: ['www.gog.com'],
  2569. condition: () => document.querySelector('.productcard-basics__title'),
  2570. products: [
  2571. {
  2572. condition: () => document.location.pathname.slice(1, 5) === 'game',
  2573. type: 'pcgame',
  2574. data: () => document.querySelector('.productcard-basics__title').textContent
  2575. },
  2576. {
  2577. condition: () => document.location.pathname.slice(1, 6) === 'movie',
  2578. type: 'movie',
  2579. data: () => document.querySelector('.productcard-basics__title').textContent
  2580. }
  2581. ]
  2582. },
  2583. steamgifts: {
  2584. host: ['www.steamgifts.com'],
  2585. condition: () => document.querySelector('.featured__heading__medium'),
  2586. products: [{
  2587. condition: Always,
  2588. type: 'pcgame',
  2589. data: () => document.querySelector('.featured__heading__medium').innerText
  2590. }]
  2591. },
  2592. allmusic: {
  2593. host: ['allmusic.com'],
  2594. condition: Always,
  2595. products: [{
  2596. condition: () => document.location.pathname.indexOf('/album/') !== -1,
  2597. type: 'music',
  2598. data: function () {
  2599. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2600. const album = ld[0]
  2601. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2602. return [artist, album]
  2603. }
  2604. }]
  2605. },
  2606. psapm: {
  2607. host: ['psa.pm'],
  2608. condition: Always,
  2609. products: [
  2610. {
  2611. condition: () => document.location.pathname.startsWith('/movie/'),
  2612. type: 'movie',
  2613. data: function () {
  2614. const title = document.querySelector('h1').textContent.trim()
  2615. const m = title.match(/(.+)\((\d+)\)$/)
  2616. if (m) {
  2617. return m[1].trim()
  2618. } else {
  2619. return title
  2620. }
  2621. }
  2622. },
  2623. {
  2624. condition: () => document.location.pathname.startsWith('/tv-show/'),
  2625. type: 'tv',
  2626. data: () => document.querySelector('h1').textContent.trim()
  2627. }
  2628. ]
  2629. },
  2630. 'save.tv': {
  2631. host: ['save.tv'],
  2632. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2633. products: [
  2634. {
  2635. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2636. type: 'movie',
  2637. data: function () {
  2638. let title = null
  2639. if (document.querySelector("span[data-bind='text:OrigTitle']")) {
  2640. title = document.querySelector("span[data-bind='text:OrigTitle']").textContent
  2641. } else {
  2642. title = document.querySelector("h2[data-bind='text:Title']").textContent
  2643. }
  2644. let year = null
  2645. if (document.querySelector("span[data-bind='text:ProductionYear']")) {
  2646. year = parseInt(document.querySelector("span[data-bind='text:ProductionYear']").textContent)
  2647. }
  2648. return [title, year]
  2649. }
  2650. }
  2651. ]
  2652. },
  2653. aRGENTeaM: {
  2654. host: ['argenteam.net'],
  2655. condition: Always,
  2656. products: [
  2657. {
  2658. condition: () => document.location.pathname.startsWith('/movie/'),
  2659. type: 'movie',
  2660. data: function () {
  2661. const partes = document.title.split('•')
  2662. const SinArgenteam = partes[1].trim()
  2663. const SoloTitulo = SinArgenteam.split('(')[0].trim()
  2664. const Year = SinArgenteam.split('(')[1].split(')')[0]
  2665. return [SoloTitulo, Year]
  2666. }
  2667. },
  2668. {
  2669. condition: () => document.location.pathname.startsWith('/episode/'),
  2670. type: 'tv',
  2671. data: () => document.querySelector('.pserie h1').firstChild.textContent.trim()
  2672. }
  2673. ]
  2674. }
  2675.  
  2676. }
  2677.  
  2678. async function main () {
  2679. let dataFound = false
  2680.  
  2681. let map = false
  2682.  
  2683. for (const name in sites) {
  2684. const site = sites[name]
  2685. if (site.host.some(function (e) { return ~this.indexOf(e) }, document.location.hostname) && site.condition()) {
  2686. for (let i = 0; i < site.products.length; i++) {
  2687. if (site.products[i].condition()) {
  2688. // Check map for a match
  2689. if (map === false) {
  2690. map = JSON.parse(await GM.getValue('map', '{}'))
  2691. }
  2692. const docurl = filterUniversalUrl(document.location.href)
  2693. if (docurl in map) {
  2694. // Found in map, show result
  2695. const metaurl = map[docurl]
  2696. metacriticGeneralProductSetup()
  2697. metacritic.mapped.apply(undefined, [docurl, site.products[i], absoluteMetaURL(metaurl), site.products[i].type])
  2698. dataFound = true
  2699. break
  2700. }
  2701. // Try to retrieve item name from page
  2702. let data
  2703. try {
  2704. data = await site.products[i].data()
  2705. } catch (e) {
  2706. data = false
  2707. console.error(`ShowMetacriticRatings: Error in data() of site='${name}', type='${site.products[i].type}'`)
  2708. console.error(e)
  2709. }
  2710. if (data) {
  2711. const params = [docurl, site.products[i]]
  2712. if (Array.isArray(data)) {
  2713. params.push(...data)
  2714. } else {
  2715. params.push(data)
  2716. }
  2717. metacriticGeneralProductSetup()
  2718. metacritic[site.products[i].type].apply(undefined, params)
  2719. dataFound = true
  2720. }
  2721. break
  2722. }
  2723. }
  2724. break
  2725. }
  2726. }
  2727. return dataFound
  2728. }
  2729.  
  2730. (async function () {
  2731. const gdpr = await acceptGDPR()
  2732. if (!gdpr) {
  2733. GM.registerMenuCommand('Show Metacritic.com ratings - Accept terms of service', () => acceptGDPR(true).then((yes) => yes && document.location.reload()))
  2734. return
  2735. }
  2736. await versionUpdate()
  2737. const firstRunResult = await main()
  2738.  
  2739. GM.registerMenuCommand('Show Metacritic.com ratings - Search now', () => openSearchBox())
  2740. GM.registerMenuCommand('Show Metacritic.com ratings - Change corner', () => changePosition())
  2741.  
  2742. let lastLoc = document.location.href
  2743. let lastContent = document.body.innerText
  2744. let lastCounter = 0
  2745. async function newpage () {
  2746. if (lastContent === document.body.innerText && lastCounter < 15) {
  2747. window.setTimeout(newpage, 500)
  2748. lastCounter++
  2749. } else {
  2750. lastContent = document.body.innerText
  2751. lastCounter = 0
  2752. const re = await main()
  2753. if (!re) { // No page matched or no data found
  2754. window.setTimeout(newpage, 1000)
  2755. }
  2756. }
  2757. }
  2758. window.setInterval(function () {
  2759. if (document.location.href !== lastLoc) {
  2760. lastLoc = document.location.href
  2761. $('#mcdiv123').remove()
  2762.  
  2763. window.setTimeout(newpage, 1000)
  2764. }
  2765. }, 500)
  2766.  
  2767. if (!firstRunResult) {
  2768. // Initial run had no match, let's try again there may be new content
  2769. window.setTimeout(main, 2000)
  2770. }
  2771. })()