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-07-29 提交的版本,檢視 最新版本

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