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), TV.com, 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

当前为 2021-12-23 提交的版本,查看 最新版本

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