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

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