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, movie.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com

当前为 2020-03-27 提交的版本,查看 最新版本

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