Show Metacritic.com ratings

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

当前为 2021-01-03 提交的版本,查看 最新版本

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