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

当前为 2022-02-16 提交的版本,查看 最新版本

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