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

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