Show Metacritic.com ratings

Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), TV.com, Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, movie.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com

目前為 2020-03-27 提交的版本,檢視 最新版本

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