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

  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. // @contributionURL https://buymeacoff.ee/cuzi
  6. // @contributionURL https://ko-fi.com/cuzicvzi
  7. // @grant GM_xmlhttpRequest
  8. // @grant GM_setValue
  9. // @grant GM_getValue
  10. // @grant unsafeWindow
  11. // @grant GM.xmlHttpRequest
  12. // @grant GM.setValue
  13. // @grant GM.getValue
  14. // @require http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
  15. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  16. // @license GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
  17. // @version 55
  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. f.contentWindow.postMessage({
  1301. mcimessage3: true,
  1302. mciframe123_clientHeight: f.clientHeight,
  1303. mciframe123_clientWidth: f.clientWidth
  1304. }, '*')
  1305. })
  1306. },
  1307. frame: function () {
  1308. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1309.  
  1310. let i = 0
  1311. window.addEventListener('message', function (e) {
  1312. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1313. // Load external image
  1314. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1315. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1316. const urlCreator = window.URL || window.webkitURL
  1317. const imageUrl = urlCreator.createObjectURL(blob)
  1318. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1319. img.src = imageUrl
  1320. }
  1321.  
  1322. if (!('mcimessage3' in e.data)) return
  1323.  
  1324. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1325. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1326. i++
  1327. }
  1328. if (i >= 100) {
  1329. parent.postMessage({ mcimessage2: 1 }, '*')
  1330. i = 0
  1331. }
  1332. })
  1333. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1334. }
  1335.  
  1336. }
  1337.  
  1338. const css = `#hover_div .clr { clear: both}
  1339. #hover_div .fl{float: left}
  1340. #hover_div { background-color: #fff; color: #666; font-family:Arial,Helvetica,sans-serif; font-size:12px; font-weight:400; font-style:normal;}
  1341. #hover_div .hoverinfo .hover_left { float: left}
  1342. #hover_div .hoverinfo .product_image_wrapper { color: #999; font-size: 6px; font-weight: normal; min-height: 98px; min-width: 98px;}
  1343. #hover_div .hoverinfo .product_image_wrapper a { color: #999; font-size: 6px; font-weight: normal;}
  1344. #hover_div a * { cursor: pointer}
  1345. #hover_div a { color: #09f; font-weight: bold;}
  1346. #hover_div a:link, #hover_div a:visited { text-decoration: none;}
  1347. #hover_div a:hover { text-decoration: underline;}
  1348. #hover_div .hoverinfo .hover_right { float: left; margin-left: 15px; max-width: 395px;}
  1349. #hover_div .hoverinfo .product_title { color: #333; font-family: georgia,serif; font-size: 24px; line-height: 26px; margin-bottom: 10px;}
  1350. #hover_div .hoverinfo .product_title a { color:#333; font-family: georgia,serif; font-size: 24px;}
  1351. #hover_div .hoverinfo .summary_detail.publisher, .hoverinfo .summary_detail.release_data { float: left}
  1352. #hover_div .hoverinfo .summary_detail { font-size: 11px; margin-bottom: 10px;}
  1353. #hover_div .hoverinfo .summary_detail.product_credits a { color: #999; font-weight: normal; }
  1354. #hover_div .hoverinfo .hr { background-color: #ccc; height: 2px; margin: 15px 0 10px;}
  1355. #hover_div .hoverinfo .hover_scores { width: 100%; border-collapse: collapse; border-spacing: 0;}
  1356. #hover_div .hoverinfo .hover_scores td.num { width: 39px}
  1357. #hover_div .hoverinfo .hover_scores td { vertical-align: middle}
  1358. #hover_div caption, #hover_div th, #hover_div td { font-weight: normal; text-align: left;}
  1359. #hover_div .metascore_anchor, #hover_div a.metascore_w { text-decoration: none !important}
  1360. #hover_div span.metascore_w, #hover_div a.metascore_w { display: inline-block; padding:0px;}
  1361. .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;}
  1362. #hover_div .metascore, #hover_div .metascore a, #hover_div .avguserscore, #hover_div .avguserscore a { color: #fff}
  1363. #hover_div .critscore, #hover_div .critscore a, #hover_div .userscore, #hover_div .userscore a { color: #333}
  1364. .score_tbd { background: #eaeaea; color: #333; font-size: 14px;}
  1365. #hover_div .score_tbd a { color: #333}
  1366. .negative, .score_terrible, .score_unfavorable, .carousel_set a.product_terrible:hover, .carousel_set a.product_unfavorable:hover { background-color: #f00}
  1367. .mixed, .neutral, .score_mixed, .carousel_set a.product_mixed:hover { background-color: #fc3; color: #333;}
  1368. #hover_div .score_mixed a { color: #333}
  1369. .positive, .score_favorable, .score_outstanding, .carousel_set a.product_favorable:hover, .carousel_set a.product_outstanding:hover { background-color: #6c3}
  1370. .critscore_terrible, .critscore_unfavorable { border-color: #f00}
  1371. .critscore_mixed { border-color: #fc3}
  1372. .critscore_favorable, .critscore_outstanding { border-color: #6c3}
  1373. .metascore .score_total, .userscore .score_total { display: none; visibility: hidden;}
  1374. .hoverinfo .metascore_label, .hoverinfo .userscore_label { font-size: 12px; font-weight: bold; line-height: 16px; margin-top: 2%;}
  1375. .hoverinfo .metascore_review_count, .hoverinfo .userscore_review_count { font-size: 11px}
  1376. .hoverinfo .hover_scores td { vertical-align: middle}
  1377. .hoverinfo .hover_scores td.num { width: 39px}
  1378. .hoverinfo .hover_scores td.usr.num { padding-left: 20px}
  1379. .metascore_anchor, a.metascore_w { text-decoration: none !important}
  1380. .metascore_w.album { padding-top:0px; !important}
  1381. .metascore_w.user { border-radius: 55%; color: #fff;}
  1382. .metascore_anchor, .metascore_w.album { padding: 0px;!important, padding-top: 0px;!important}
  1383. a.metascore_w { text-decoration: none!important}
  1384. .metascore_anchor:hover { text-decoration: none!important}
  1385. .metascore_w:hover { text-decoration: none!important}
  1386. span.metascore_w, a.metascore_w { display: inline-block}
  1387. .metascore_w.xlarge, .metascore_w.xl { font-size: 42px}
  1388. .metascore_w.large, .metascore_w.lrg { font-size: 25px}
  1389. .m .metascore_w.medium, .m .metascore_w.med { font-size: 19px}
  1390. .metascore_w.med_small { font-size: 14px}
  1391. .metascore_w.small, .metascore_w.sm { font-size: 12px}
  1392. .metascore_w.tiny { height: 1.9em; font-size: 11px; line-height: 1.9em;}
  1393. .metascore_w.user { border-radius: 55%; color: #fff;}
  1394. .metascore_w.user.small, .metascore_w.user.sm { font-size: 11px}
  1395. .metascore_w.tbd, .metascore_w.score_tbd { color: #000!important; background-color: #ccc;}
  1396. .metascore_w.tbd.hide_tbd, .metascore_w.score_tbd.hide_tbd { visibility: hidden}
  1397. .metascore_w.tbd.no_tbd, .metascore_w.score_tbd.no_tbd { display: none}
  1398. .metascore_w.noscore::before, .metascore_w.score_noscore::before { content: '\u2022\u2022\u2022'}
  1399. .metascore_w.noscore, .metascore_w.score_noscore { color: #fff!important; background-color: #ccc;}
  1400. .metascore_w.rip, .metascore_w.score_rip { border-radius: 4px; color: #fff!important; background-color: #999;}
  1401. .metascore_w.negative, .metascore_w.score_terrible, .metascore_w.score_unfavorable { background-color: #f00}
  1402. .metascore_w.mixed, .metascore_w.forty, .metascore_w.game.fifty, .metascore_w.score_mixed { background-color: #fc3}
  1403. .metascore_w.positive, .metascore_w.sixtyone, .metascore_w.game.seventyfive, .metascore_w.score_favorable, .metascore_w.score_outstanding { background-color: #6c3}
  1404. .metascore_w.indiv { height: 1.9em; width: 1.9em; font-size: 15px; line-height: 1.9em;}
  1405. .metascore_w.indiv.large, .metascore_w.indiv.lrg { font-size: 24px}
  1406. .m .metascore_w.indiv.medium, .m .metascore_w.indiv.med { font-size: 16px}
  1407. .metascore_w.indiv.small, .metascore_w.indiv.sm { font-size: 11px}
  1408. .metascore_w.indiv.perfect { padding-right: 1px}
  1409. .hover_esite { display:none; }
  1410. .promo_amazon .esite_btn { margin: 3px 0 0 7px;}
  1411. .esite_amazon { background-color: #fdc354; border: 1px solid #aaa;}
  1412. .esite_label_wrapper { display:none;}
  1413. .esite_btn { border-radius: 4px; color: #222; font-size: 12px; height: 40px; line-height: 40px; width: 120px;}
  1414. .chart{background-color:inherit!important;margin-top:-3px}
  1415. .chart_bg{width:100%;border-top:3px solid rgba(150,150,150,0.3)}
  1416. .chart .bar{width:100%;height:3px}
  1417. .chart .count{font-size:10px}`
  1418.  
  1419. let framesrc = 'data:text/html,'
  1420. framesrc += encodeURIComponent('<!DOCTYPE html>\
  1421. <html lang="en">\
  1422. <head>\
  1423. <meta charset="utf-8">\
  1424. <title>Metacritic info</title>\
  1425. <style>body { margin:0px; padding:0px; background:white; }' + css +
  1426. '\
  1427. </style>\
  1428. <script>\
  1429. const failedImages = {};\
  1430. function detectCSP(img) {\
  1431. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {\
  1432. return true;\
  1433. }\
  1434. return false;\
  1435. }\
  1436. function findCSPerrors() {\
  1437. const imgs = document.querySelectorAll("img");\
  1438. for(let i = 0; i < imgs.length; i++) {\
  1439. if(imgs[i].complete && detectCSP(imgs[i])) {\
  1440. fixCSP(imgs[i]);\
  1441. }\
  1442. }\
  1443. }\
  1444. function fixCSP(img) {\
  1445. console.log("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");\
  1446. failedImages[img.src] = img;\
  1447. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*"); \
  1448. }\
  1449. function on_load() {\
  1450. (' + functions.frame.toString() + ')();\
  1451. window.setTimeout(findCSPerrors, 500);\
  1452. \
  1453. }\
  1454. </script>\
  1455. </head>\
  1456. <body onload="on_load();">\
  1457. <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">\
  1458. <div class="hover_content">' + html + '</div>\
  1459. </div>\
  1460. </body>\
  1461. </html>')
  1462.  
  1463. const frame = $('<iframe></iframe>').appendTo(div)
  1464. frame.attr('id', 'mciframe123')
  1465. frame.attr('src', framesrc)
  1466. frame.attr('scrolling', 'auto')
  1467. frame.css({
  1468. width: 380,
  1469. height: 150,
  1470. border: 'none'
  1471. })
  1472.  
  1473. window.setTimeout(function () {
  1474. if (!frameStatus) { // Loading frame content failed.
  1475. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1476. console.log('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1477. $('head').append('<style>' + css + '</style>')
  1478. 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">\
  1479. <div class="hover_content">' + html + '</div>\
  1480. </div>')
  1481. frame.replaceWith(noframe)
  1482. }
  1483. }, 2000)
  1484.  
  1485. functions.parent()
  1486.  
  1487. const sub = $('<div></div>').appendTo(div)
  1488. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1489. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1490. $('<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 () {
  1491. const metaurl = $(this).data('url')
  1492. addToTemporaryBlacklist(metaurl)
  1493. document.body.removeChild(this.parentNode.parentNode)
  1494. })
  1495.  
  1496. $('<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 () {
  1497. const docurl = document.location.href
  1498. const metaurl = $(this).data('url')
  1499. addToMap(docurl, metaurl).then(function (r) {
  1500. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1501. })
  1502. })
  1503. $('<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 () {
  1504. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1505. const docurl = document.location.href
  1506. const metaurl = $(this).data('url')
  1507. addToBlacklist(docurl, metaurl).then(function (r) {
  1508. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1509. })
  1510.  
  1511. openSearchBox(true)
  1512. })
  1513.  
  1514. // Store response in cache:
  1515. if (!('cached' in response)) {
  1516. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  1517. }
  1518. }
  1519.  
  1520. const metacritic = {
  1521. mapped: function metacriticMapped (docurl, metaurl, type) {
  1522. // url was in the map/whitelist
  1523. current.data = []
  1524. current.docurl = docurl
  1525. current.metaurl = metaurl
  1526. current.type = type
  1527. current.searchTerm = null
  1528. loadMetacriticUrl()
  1529. },
  1530. music: function metacriticMusic (docurl, artistname, albumname) {
  1531. current.data = [albumname.trim(), artistname.trim()]
  1532. artistname = name2metacritic(artistname)
  1533. albumname = albumname.replace('&', ' ')
  1534. albumname = name2metacritic(albumname)
  1535. current.docurl = docurl
  1536. current.metaurl = baseURLmusic + albumname + '/' + artistname
  1537. current.type = 'music'
  1538. current.searchTerm = albumname + '/' + artistname
  1539. loadMetacriticUrl()
  1540. },
  1541. movie: function metacriticMovie (docurl, moviename) {
  1542. current.data = [moviename.trim()]
  1543. moviename = name2metacritic(moviename)
  1544. current.docurl = docurl
  1545. current.metaurl = baseURLmovie + moviename
  1546. current.type = 'movie'
  1547. current.searchTerm = moviename
  1548. loadMetacriticUrl()
  1549. },
  1550. tv: function metacriticTv (docurl, seriesname) {
  1551. current.data = [seriesname.trim()]
  1552. seriesname = name2metacritic(seriesname)
  1553. current.docurl = docurl
  1554. current.metaurl = baseURLtv + seriesname
  1555. current.type = 'tv'
  1556. current.searchTerm = seriesname
  1557. loadMetacriticUrl()
  1558. },
  1559. pcgame: function metacriticPcgame (docurl, gamename) {
  1560. current.data = [gamename.trim()]
  1561. gamename = name2metacritic(gamename)
  1562. current.docurl = docurl
  1563. current.metaurl = baseURLpcgame + gamename
  1564. current.type = 'pcgame'
  1565. current.searchTerm = gamename
  1566. loadMetacriticUrl()
  1567. },
  1568. ps4game: function metacriticPs4game (docurl, gamename) {
  1569. current.data = [gamename.trim()]
  1570. gamename = name2metacritic(gamename)
  1571. current.docurl = docurl
  1572. current.metaurl = baseURLps4 + gamename
  1573. current.type = 'ps4game'
  1574. current.searchTerm = gamename
  1575. loadMetacriticUrl()
  1576. },
  1577. xonegame: function metacriticXonegame (docurl, gamename) {
  1578. current.data = [gamename.trim()]
  1579. gamename = name2metacritic(gamename)
  1580. current.docurl = docurl
  1581. current.metaurl = baseURLxone + gamename
  1582. current.type = 'xonegame'
  1583. current.searchTerm = gamename
  1584. loadMetacriticUrl()
  1585. }
  1586. }
  1587.  
  1588. const Always = () => true
  1589. const sites = {
  1590. bandcamp: {
  1591. host: ['bandcamp.com'],
  1592. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  1593. products: [{
  1594. condition: Always,
  1595. type: 'music',
  1596. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1597. }]
  1598. },
  1599. itunes: {
  1600. host: ['itunes.apple.com'],
  1601. condition: Always,
  1602. products: [{
  1603. condition: () => ~document.location.href.indexOf('/movie/'),
  1604. type: 'movie',
  1605. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1606. },
  1607. {
  1608. condition: () => ~document.location.href.indexOf('/tv-season/'),
  1609. type: 'tv',
  1610. data: function () {
  1611. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1612. if (~name.indexOf(', Season')) {
  1613. name = name.split(', Season')[0]
  1614. }
  1615. return name
  1616. }
  1617. },
  1618. {
  1619. condition: () => ~document.location.href.indexOf('/album/'),
  1620. type: 'music',
  1621. data: function () {
  1622. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1623. const album = ld[0]
  1624. const artist = ld[1].name
  1625. return [artist, album]
  1626. }
  1627. }]
  1628. },
  1629. 'music.apple': {
  1630. host: ['music.apple.com'],
  1631. condition: Always,
  1632. products: [{
  1633. condition: () => ~document.location.href.indexOf('/album/'),
  1634. type: 'music',
  1635. data: function () {
  1636. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1637. const album = ld[0]
  1638. const artist = ld[1].name
  1639. return [artist, album]
  1640. }
  1641. }]
  1642. },
  1643. googleplay: {
  1644. host: ['play.google.com'],
  1645. condition: Always,
  1646. products: [
  1647. {
  1648. condition: () => ~document.location.href.indexOf('/album/'),
  1649. type: 'music',
  1650. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  1651. },
  1652. {
  1653. condition: () => ~document.location.href.indexOf('/movies/details/'),
  1654. type: 'movie',
  1655. data: () => document.querySelector('*[itemprop=name]').textContent
  1656. }
  1657. ]
  1658. },
  1659. imdb: {
  1660. host: ['imdb.com'],
  1661. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  1662. products: [
  1663. {
  1664. condition: function () {
  1665. const e = document.querySelector("meta[property='og:type']")
  1666. if (e) {
  1667. return e.content === 'video.movie'
  1668. }
  1669. return false
  1670. },
  1671. type: 'movie',
  1672. data: function () {
  1673. if (document.querySelector("meta[property='og:title']") && document.querySelector("meta[property='og:title']").content) { // English/Worldwide title, this is the prefered title for search
  1674. let name = document.querySelector("meta[property='og:title']").content.trim()
  1675. if (name.indexOf('- IMDb') !== -1) {
  1676. name = name.replace('- IMDb', '').trim()
  1677. }
  1678. name = name.replace(/\(\d{4}\)/, '').trim()
  1679. return name
  1680. } else if (document.querySelector('.originalTitle') && document.querySelector('.title_wrapper h1')) { // Use English title 2018
  1681. return document.querySelector('.title_wrapper h1').firstChild.data.trim()
  1682. } else if (document.querySelector('script[type="application/ld+json"]')) { // Use original language title
  1683. return parseLDJSON('name')
  1684. } else if (document.querySelector('h1[itemprop=name]')) { // Movie homepage (New design 2015-12)
  1685. return document.querySelector('h1[itemprop=name]').firstChild.textContent.trim()
  1686. } else if (document.querySelector('*[itemprop=name] a') && document.querySelector('*[itemprop=name] a').firstChild.data) { // Subpage of a move
  1687. return document.querySelector('*[itemprop=name] a').firstChild.data.trim()
  1688. } else if (document.querySelector('.title-extra[itemprop=name]')) { // Movie homepage: sub-/alternative-/original title
  1689. return document.querySelector('.title-extra[itemprop=name]').firstChild.textContent.replace(/"/g, '').trim()
  1690. } else { // Movie homepage (old design)
  1691. return document.querySelector('*[itemprop=name]').firstChild.textContent.trim()
  1692. }
  1693. }
  1694. },
  1695. {
  1696. condition: function () {
  1697. const e = document.querySelector("meta[property='og:type']")
  1698. if (e) {
  1699. return e.content === 'video.tv_show'
  1700. }
  1701. return false
  1702. },
  1703. type: 'tv',
  1704. data: function () {
  1705. if (document.querySelector('*[itemprop=name]')) {
  1706. return document.querySelector('*[itemprop=name]').textContent
  1707. } else {
  1708. const jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText)
  1709. return jsonld.name
  1710. }
  1711. }
  1712. }
  1713. ]
  1714. },
  1715. steam: {
  1716. host: ['store.steampowered.com'],
  1717. condition: () => document.querySelector('*[itemprop=name]'),
  1718. products: [{
  1719. condition: Always,
  1720. type: 'pcgame',
  1721. data: () => document.querySelector('*[itemprop=name]').textContent
  1722. }]
  1723. },
  1724. 'tv.com': {
  1725. host: ['www.tv.com'],
  1726. condition: () => document.querySelector("meta[property='og:type']"),
  1727. products: [{
  1728. condition: () => document.querySelector("meta[property='og:type']").content === 'tv_show' && document.querySelector('h1[data-name]'),
  1729. type: 'tv',
  1730. data: () => document.querySelector('h1[data-name]').dataset.name
  1731. }]
  1732. },
  1733. rottentomatoes: {
  1734. host: ['rottentomatoes.com'],
  1735. condition: Always,
  1736. products: [{
  1737. condition: () => document.location.pathname.startsWith('/m/'),
  1738. type: 'movie',
  1739. data: () => document.querySelector('h1').firstChild.textContent
  1740. },
  1741. {
  1742. condition: () => document.location.pathname.startsWith('/tv/'),
  1743. type: 'tv',
  1744. data: () => unsafeWindow.BK.TvSeriesTitle
  1745. }
  1746. ]
  1747. },
  1748. serienjunkies: {
  1749. host: ['www.serienjunkies.de'],
  1750. condition: Always,
  1751. products: [{
  1752. condition: () => Always,
  1753. type: 'tv',
  1754. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1755. }]
  1756. },
  1757. gamespot: {
  1758. host: ['gamespot.com'],
  1759. condition: () => document.querySelector('[itemprop=device]'),
  1760. products: [
  1761. {
  1762. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  1763. type: 'pcgame',
  1764. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1765. },
  1766. {
  1767. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  1768. type: 'ps4game',
  1769. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1770. },
  1771. {
  1772. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  1773. type: 'xonegame',
  1774. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1775. }
  1776. ]
  1777. },
  1778. amazon: {
  1779. host: ['amazon.'],
  1780. condition: Always,
  1781. products: [
  1782. {
  1783. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  1784. type: 'music',
  1785. data: function () {
  1786. const artist = document.querySelector('.artistLink').textContent.trim()
  1787. let title = document.querySelector('.viewTitle').textContent.trim()
  1788. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1789. if (artist && title) {
  1790. return [artist, title]
  1791. }
  1792. return false
  1793. }
  1794. },
  1795. {
  1796. condition: function () { // "Normal amazon" page
  1797. try {
  1798. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  1799. return true
  1800. }
  1801. } catch (e) {}
  1802. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  1803. return music.some(function (s) {
  1804. if (~document.title.indexOf(s)) {
  1805. return true
  1806. } else {
  1807. return false
  1808. }
  1809. })
  1810. },
  1811. type: 'music',
  1812. data: function () {
  1813. let artist = false
  1814. let title = false
  1815. if (document.querySelector('#ProductInfoArtistLink')) {
  1816. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  1817. } else if (document.querySelector('#bylineInfo .author>*')) {
  1818. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  1819. }
  1820.  
  1821. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  1822. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  1823. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1824. } else if (document.querySelector('#productTitle')) {
  1825. title = document.querySelector('#productTitle').textContent.trim()
  1826. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1827. }
  1828. return [artist, title]
  1829. }
  1830. },
  1831. {
  1832. condition: () => (document.querySelector('[data-automation-id=title]') && (document.getElementsByClassName('av-season-single').length || document.querySelector('[data-automation-id="num-of-seasons-badge"]'))),
  1833. type: 'tv',
  1834. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1835. },
  1836. {
  1837. condition: () => document.querySelector('[data-automation-id=title]'),
  1838. type: 'movie',
  1839. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1840. }
  1841. ]
  1842. },
  1843. BoxOfficeMojo: {
  1844. host: ['boxofficemojo.com'],
  1845. condition: () => Always,
  1846. products: [
  1847. {
  1848. condition: () => document.location.pathname.startsWith('/release/'),
  1849. type: 'movie',
  1850. data: () => document.querySelector('meta[name=title]').content
  1851. },
  1852. {
  1853. // Old page design
  1854. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  1855. type: 'movie',
  1856. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.data
  1857. }]
  1858. },
  1859. AllMovie: {
  1860. host: ['allmovie.com'],
  1861. condition: () => document.querySelector('h2[itemprop=name].movie-title'),
  1862. products: [{
  1863. condition: () => document.querySelector('h2[itemprop=name].movie-title'),
  1864. type: 'movie',
  1865. data: () => document.querySelector('h2[itemprop=name].movie-title').firstChild.data.trim()
  1866. }]
  1867. },
  1868. 'en.wikipedia': {
  1869. host: ['en.wikipedia.org'],
  1870. condition: Always,
  1871. products: [{
  1872. condition: function () {
  1873. if (!document.querySelector('.infobox .summary')) {
  1874. return false
  1875. }
  1876. const r = /\d\d\d\d films/
  1877. return $('#catlinks a').filter((i, e) => e.firstChild.data.match(r)).length
  1878. },
  1879. type: 'movie',
  1880. data: () => document.querySelector('.infobox .summary').firstChild.data
  1881. },
  1882. {
  1883. condition: function () {
  1884. if (!document.querySelector('.infobox .summary')) {
  1885. return false
  1886. }
  1887. const r = /television series/
  1888. return $('#catlinks a').filter((i, e) => e.firstChild.data.match(r)).length
  1889. },
  1890. type: 'tv',
  1891. data: () => document.querySelector('.infobox .summary').firstChild.data
  1892. }]
  1893. },
  1894. 'movies.com': {
  1895. host: ['movies.com'],
  1896. condition: () => document.querySelector("meta[property='og:title']"),
  1897. products: [{
  1898. condition: Always,
  1899. type: 'movie',
  1900. data: () => document.querySelector("meta[property='og:title']").content
  1901. }]
  1902. },
  1903. themoviedb: {
  1904. host: ['themoviedb.org'],
  1905. condition: () => document.querySelector("meta[property='og:type']"),
  1906. products: [{
  1907. condition: () => document.querySelector("meta[property='og:type']").content === 'movie',
  1908. type: 'movie',
  1909. data: () => document.querySelector("meta[property='og:title']").content
  1910. },
  1911. {
  1912. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' || document.querySelector("meta[property='og:type']").content === 'tv_series',
  1913. type: 'tv',
  1914. data: () => document.querySelector("meta[property='og:title']").content
  1915. }]
  1916. },
  1917. letterboxd: {
  1918. host: ['letterboxd.com'],
  1919. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  1920. products: [{
  1921. condition: Always,
  1922. type: 'movie',
  1923. data: () => unsafeWindow.filmData.name
  1924. }]
  1925. },
  1926. TVmaze: {
  1927. host: ['tvmaze.com'],
  1928. condition: () => document.querySelector('h1'),
  1929. products: [{
  1930. condition: Always,
  1931. type: 'tv',
  1932. data: () => document.querySelector('h1').firstChild.data
  1933. }]
  1934. },
  1935. TVGuide: {
  1936. host: ['tvguide.com'],
  1937. condition: Always,
  1938. products: [{
  1939. condition: () => document.location.pathname.startsWith('/tvshows/'),
  1940. type: 'tv',
  1941. data: function () {
  1942. if (document.querySelector('meta[itemprop=name]')) {
  1943. return document.querySelector('meta[itemprop=name]').content
  1944. } else {
  1945. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  1946. }
  1947. }
  1948. }]
  1949. },
  1950. followshows: {
  1951. host: ['followshows.com'],
  1952. condition: Always,
  1953. products: [{
  1954. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  1955. type: 'tv',
  1956. data: () => document.querySelector("meta[property='og:title']").content
  1957. }]
  1958. },
  1959. TheTVDB: {
  1960. host: ['thetvdb.com'],
  1961. condition: Always,
  1962. products: [{
  1963. condition: () => document.location.pathname.startsWith('/series/') || ~document.location.search.indexOf('tab=series'),
  1964. type: 'tv',
  1965. data: () => document.getElementById('series_title').firstChild.data.trim()
  1966. }]
  1967. },
  1968. ConsequenceOfSound: {
  1969. host: ['consequenceofsound.net'],
  1970. condition: () => document.querySelector('#main-content .review-summary'),
  1971. products: [{
  1972. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  1973. type: 'music',
  1974. data: function () {
  1975. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  1976. return [m[1], m[2]]
  1977. }
  1978. }]
  1979. },
  1980. Pitchfork: {
  1981. host: ['pitchfork.com'],
  1982. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  1983. products: [{
  1984. condition: () => document.querySelector('.single-album-tombstone'),
  1985. type: 'music',
  1986. data: function () {
  1987. let artist
  1988. let album
  1989. if (document.querySelector('.single-album-tombstone .artists')) {
  1990. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  1991. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  1992. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  1993. }
  1994. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  1995. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  1996. } else if (document.querySelector('.single-album-tombstone h1')) {
  1997. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  1998. }
  1999.  
  2000. return [artist, album]
  2001. }
  2002. }]
  2003. },
  2004. 'Last.fm': {
  2005. host: ['last.fm'],
  2006. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2007. products: [{
  2008. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2009. type: 'music',
  2010. data: function () {
  2011. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2012. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2013. return [artist, album]
  2014. }
  2015. }]
  2016. },
  2017. TVNfo: {
  2018. host: ['tvnfo.com'],
  2019. condition: () => document.querySelector('#tvsign'),
  2020. products: [{
  2021. condition: Always,
  2022. type: 'tv',
  2023. data: () => document.querySelector('.heading h1').textContent.trim()
  2024. }]
  2025. },
  2026. rateyourmusic: {
  2027. host: ['rateyourmusic.com'],
  2028. condition: () => document.querySelector("meta[property='og:type']"),
  2029. products: [{
  2030. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2031. type: 'music',
  2032. data: function () {
  2033. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2034. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2035. return [artist, album]
  2036. }
  2037. }]
  2038. },
  2039. spotify_webplayer: {
  2040. host: ['open.spotify.com'],
  2041. condition: Always,
  2042. products: [{
  2043. condition: () => document.querySelector('#main .main-view-container .content.album'),
  2044. type: 'music',
  2045. data: function () {
  2046. const artist = document.querySelector("#main .media-bd div a[href*='artist']").textContent
  2047. const album = document.querySelector('#main .media-bd h2').textContent
  2048. return [artist, album]
  2049. }
  2050. },
  2051. {
  2052. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector("meta[property='og:type']").content === 'music.album',
  2053. type: 'music',
  2054. data: function () {
  2055. const artist = ''
  2056. const album = document.querySelector("meta[property='og:title']").content
  2057. return [artist, album]
  2058. }
  2059. }]
  2060. },
  2061. spotify: {
  2062. host: ['play.spotify.com'],
  2063. condition: Always,
  2064. products: [{
  2065. condition: () => document.location.pathname.startsWith('/album/'),
  2066. type: 'music',
  2067. data: function () {
  2068. const artist = document.querySelector('.context_landing p.secondary-title').textContent
  2069. const album = document.querySelector('.context_landing p.primary-title').textContent
  2070. return [artist, album]
  2071. }
  2072. }]
  2073. },
  2074. nme: {
  2075. host: ['nme.com'],
  2076. condition: () => document.location.pathname.startsWith('/reviews/'),
  2077. products: [
  2078. {
  2079. condition: () => document.location.pathname.startsWith('/reviews/movie/'),
  2080. type: 'movie',
  2081. data: function () {
  2082. try {
  2083. return document.querySelector('.title-primary').textContent.match(/‘(.+?)’/)[1]
  2084. } catch (e) {
  2085. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2086. }
  2087. }
  2088. },
  2089. {
  2090. condition: () => document.location.pathname.startsWith('/reviews/album/'),
  2091. type: 'music',
  2092. data: () => document.querySelector('.title-primary').textContent.match(/\s*(.+?)\s*.\s*‘(.+?)’/).slice(1)
  2093. }]
  2094. },
  2095. albumoftheyear: {
  2096. host: ['albumoftheyear.org'],
  2097. condition: Always,
  2098. products: [{
  2099. condition: () => document.location.pathname.startsWith('/album/'),
  2100. type: 'music',
  2101. data: function () {
  2102. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2103. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2104. return [artist, album]
  2105. }
  2106. }]
  2107. },
  2108. epguides: {
  2109. host: ['epguides.com'],
  2110. condition: () => document.getElementById('TVHeader'),
  2111. products: [{
  2112. condition: () => document.getElementById('TVHeader') && document.querySelector('body>div#header h1'),
  2113. type: 'tv',
  2114. data: () => document.querySelector('body>div#header h1').textContent.trim()
  2115. }]
  2116. },
  2117. ShareTV: {
  2118. host: ['sharetv.com'],
  2119. condition: () => document.location.pathname.startsWith('/shows/'),
  2120. products: [{
  2121. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2122. type: 'tv',
  2123. data: () => document.querySelector("meta[property='og:title']").content
  2124. }]
  2125. },
  2126. /*
  2127. netflix: {
  2128. host: ['netflix.com'],
  2129. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2130.  
  2131. // TODO
  2132. // https://www.netflix.com/de/title/70264888
  2133. // https://www.netflix.com/de/title/70178217
  2134. // https://www.netflix.com/de/title/70305892 ## Movie
  2135. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2136.  
  2137. products: [{
  2138. condition: () => parseLDJSON('@type') === 'Movie',
  2139. type: 'movie',
  2140. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2141. },
  2142. {
  2143. condition: () => parseLDJSON('@type') === 'TVSeries',
  2144. type: 'tv',
  2145. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2146. }]
  2147. },
  2148. */
  2149. ComedyCentral: {
  2150. host: ['cc.com'],
  2151. condition: () => document.location.pathname.startsWith('/shows/'),
  2152. products: [{
  2153. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2154. type: 'tv',
  2155. data: () => document.querySelector("meta[property='og:title']").content
  2156. }]
  2157. },
  2158. TVHoard: {
  2159. host: ['tvhoard.com'],
  2160. condition: Always,
  2161. products: [{
  2162. 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'),
  2163. type: 'movie',
  2164. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2165. },
  2166. {
  2167. 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'),
  2168. type: 'tv',
  2169. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2170. }]
  2171. },
  2172. AMC: {
  2173. host: ['amc.com'],
  2174. condition: () => document.location.pathname.startsWith('/shows/'),
  2175. products: [
  2176. {
  2177. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content === 'tv_show',
  2178. type: 'tv',
  2179. data: () => document.querySelector("meta[property='og:title']").content
  2180. }]
  2181. }
  2182.  
  2183. }
  2184.  
  2185. async function main () {
  2186. let dataFound = false
  2187.  
  2188. let map = false
  2189.  
  2190. for (const name in sites) {
  2191. const site = sites[name]
  2192. if (site.host.some(function (e) { return ~this.indexOf(e) }, document.location.hostname) && site.condition()) {
  2193. for (let i = 0; i < site.products.length; i++) {
  2194. if (site.products[i].condition()) {
  2195. // Check map for a match
  2196. if (map === false) {
  2197. map = JSON.parse(await GM.getValue('map', '{}'))
  2198. }
  2199. const docurl = filterUniversalUrl(document.location.href)
  2200. if (docurl in map) {
  2201. // Found in map, show result
  2202. const metaurl = map[docurl]
  2203. metacritic.mapped.apply(undefined, [docurl, absoluteMetaURL(metaurl), site.products[i].type])
  2204. break
  2205. }
  2206. // Try to retrieve item name from page
  2207. let data
  2208. try {
  2209. data = site.products[i].data()
  2210. } catch (e) {
  2211. data = false
  2212. console.log('ShowMetacriticRatings: ' + e)
  2213. }
  2214. if (data) {
  2215. const params = [docurl]
  2216. if (Array.isArray(data)) {
  2217. params.push(...data)
  2218. } else {
  2219. params.push(data)
  2220. }
  2221. metacritic[site.products[i].type].apply(undefined, params)
  2222. dataFound = true
  2223. }
  2224. break
  2225. }
  2226. }
  2227. break
  2228. }
  2229. }
  2230. return dataFound
  2231. }
  2232.  
  2233. (async function () {
  2234. const gdpr = await acceptGDPR()
  2235. if (!gdpr) {
  2236. return
  2237. }
  2238. await versionUpdate()
  2239. const firstRunResult = await main()
  2240. let lastLoc = document.location.href
  2241. const lastContent = document.body.innerText
  2242. let lastCounter = 0
  2243. async function newpage () {
  2244. if (lastContent === document.body.innerText && lastCounter < 15) {
  2245. window.setTimeout(newpage, 500)
  2246. lastCounter++
  2247. } else {
  2248. lastCounter = 0
  2249. const re = await main()
  2250. if (!re) { // No page matched or no data found
  2251. window.setTimeout(newpage, 1000)
  2252. }
  2253. }
  2254. }
  2255. window.setInterval(function () {
  2256. if (document.location.href !== lastLoc) {
  2257. lastLoc = document.location.href
  2258. $('#mcdiv123').remove()
  2259.  
  2260. window.setTimeout(newpage, 1000)
  2261. }
  2262. }, 500)
  2263.  
  2264. if (!firstRunResult) {
  2265. // Initial run had no match, let's try again there may be new content
  2266. window.setTimeout(main, 2000)
  2267. }
  2268. })()