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

当前为 2020-12-07 提交的版本,查看 最新版本

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