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

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