// ==UserScript== // @name Show Metacritic.com ratings // @description Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), 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, GOG, Epic Games Store, save.tv // @namespace cuzi // @icon https://www.metacritic.com/a/img/favicon.svg // @supportURL https://github.com/cvzi/Metacritic-userscript/issues // @contributionURL https://buymeacoff.ee/cuzi // @contributionURL https://ko-fi.com/cuzicvzi // @grant unsafeWindow // @grant GM.xmlHttpRequest // @grant GM.setValue // @grant GM.getValue // @grant GM.registerMenuCommand // @require https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt // @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 Cloudflare Workers® and contain your IP address and browser configuration. // @version 105 // @connect metacritic.com // @connect backend.metacritic.com // @connect met.acritic.workers.dev // @connect imdb.com // @match https://*.bandcamp.com/* // @match https://play.google.com/store/music/album/* // @match https://play.google.com/store/movies/details/* // @match https://music.amazon.com/* // @match https://www.amazon.ca/* // @match https://www.amazon.co.jp/* // @match https://www.amazon.co.uk/* // @match https://smile.amazon.co.uk/* // @match https://www.amazon.com.au/* // @match https://www.amazon.com.mx/* // @match https://www.amazon.com/* // @match https://smile.amazon.com/* // @match https://www.amazon.de/* // @match https://smile.amazon.de/* // @match https://www.amazon.es/* // @match https://www.amazon.fr/* // @match https://www.amazon.in/* // @match https://www.amazon.it/* // @match https://www.imdb.com/title/* // @match https://store.steampowered.com/app/* // @match https://www.gamespot.com/* // @match http://www.serienjunkies.de/* // @match https://www.serienjunkies.de/* // @match https://www.rottentomatoes.com/m/* // @match https://rottentomatoes.com/m/* // @match https://www.rottentomatoes.com/tv/* // @match https://rottentomatoes.com/tv/* // @match https://www.rottentomatoes.com/tv/* // @match https://rottentomatoes.com/tv/* // @match https://www.boxofficemojo.com/movies/* // @match https://www.boxofficemojo.com/release/* // @match https://www.allmovie.com/movie/* // @match https://en.wikipedia.org/* // @match https://www.fandango.com/* // @match https://flixster.com/movie/* // @match https://www.themoviedb.org/movie/* // @match https://www.themoviedb.org/tv/* // @match https://letterboxd.com/film/* // @match https://www.tvmaze.com/shows/* // @match https://www.tvguide.com/tvshows/* // @match https://followshows.com/show/* // @match https://thetvdb.com/series/* // @match https://thetvdb.com/movies/* // @match https://consequenceofsound.net/* // @match https://consequence.net/* // @match https://pitchfork.com/* // @match https://www.last.fm/* // @match https://tvnfo.com/tv/* // @match https://rateyourmusic.com/release/album/* // @match https://open.spotify.com/* // @match https://play.spotify.com/album/* // @match https://www.nme.com/reviews/* // @match https://www.albumoftheyear.org/album/* // @match https://itunes.apple.com/* // @match https://music.apple.com/* // @match https://epguides.com/* // @match https://www.epguides.com/* // @match https://www.netflix.com/* // @match https://www.cc.com/* // @match https://www.amc.com/* // @match https://www.amcplus.com/* // @match https://rlsbb.ru/*/ // @match https://newalbumreleases.net/* // @match https://www.sho.com/* // @match https://www.epicgames.com/store/* // @match https://store.epicgames.com/* // @match https://www.gog.com/* // @match https://www.allmusic.com/album/* // @match https://www.steamgifts.com/giveaway/* // @match https://psa.wf/* // @match https://www.save.tv/* // @match https://www.wikiwand.com/* // @match https://trakt.tv/* // @match http://localhost:7878/* // @downloadURL none // ==/UserScript== /* globals alert, confirm, GM, DOMParser, $, Image, unsafeWindow, parent, Blob, failedImages */ /* jshint asi: true, esversion: 8 */ const scriptName = 'Show Metacritic.com ratings' const baseURL = 'https://www.metacritic.com/' const baseURLmusic = 'https://www.metacritic.com/music/' const baseURLmovie = 'https://www.metacritic.com/movie/' const baseURLpcgame = 'https://www.metacritic.com/game/' const baseURLps4 = 'https://www.metacritic.com/game/' const baseURLxone = 'https://www.metacritic.com/game/' const baseURLtv = 'https://www.metacritic.com/tv/' const baseURLsearch = 'https://backend.metacritic.com/finder/metacritic/search/{query}/web?apiKey={apiKey}&componentName=search-tabs&componentDisplayName=Search+Page+Tab+Filters&componentType=FilterConfig&mcoTypeId={type}&offset=0&limit=30' const baseURLdatabase = 'https://met.acritic.workers.dev/r.php' const baseURLwhitelist = 'https://met.acritic.workers.dev/whitelist.php' const baseURLblacklist = 'https://met.acritic.workers.dev/blacklist.php' const TEMPORARY_BLACKLIST_TIMEOUT = 5 * 60 const windowPositions = [ { bottom: 0, left: 0 }, { bottom: 0, right: 0 }, { top: 0, right: 0 }, { top: 0, left: 0 } ] // Detect dark theme of darkreader.org extension const darkTheme = 'darkreaderScheme' in document.documentElement.dataset && document.documentElement.dataset.darkreaderScheme let myDOMParser = null function domParser () { if (myDOMParser === null) { myDOMParser = new DOMParser() } return myDOMParser } async function versionUpdate () { const version = parseInt(await GM.getValue('version', 0)) if (version <= 104) { // Reset database await GM.setValue('map', '{}') await GM.setValue('black', '[]') await GM.setValue('hovercache', '{}') await GM.setValue('requestcache', '{}') await GM.setValue('temporaryblack', '{}') await GM.setValue('searchcache', false) // Unused await GM.setValue('autosearchcache', false) // Unused } if (version < 105) { await GM.setValue('version', 105) } } const BOX_CSS_DARK_THEME = ` #mcdiv123 { position: fixed; background-color: #262626; border: 2px solid #313131; color: white; } #mcisearchquery { background: #262626; color: white; } #mcisearchbutton { background: rgb(56, 56, 56); color: white; border: 2px solid white; } #mcdiv123 .grespinner { 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); } #mcdiv123searchresults .result { border-top-color: #525252; } #mcdiv123searchresults .result .mcdiv123_score_badge { color: white; } #mcdiv123searchresults .result .mcdiv_release_date { color: silver } .mcdiv123_image_placeholder { background: rgb(64, 64, 64); } #mcdiv123searchresults .result a { color: #09f; } #mcdiv123searchresults .mcdiv_desc { scrollbar-color: #003c09 #00ce7a; } #mcdiv123searchresults .mcdiv_desc::-webkit-scrollbar-thumb { background-color: #003c09; } ` const BOX_CSS = ` #mcdiv123 { position: fixed; background-color: #fff; border: 2px solid #bbb; border-radius: 6px; box-shadow: 0 0 3px 3px rgba(100, 100, 100, 0.2); color: #000; min-width: 150; max-height: 80%; max-width: 640; overflow: auto; padding: 3px; z-index: 2147483601; } #mcisearchquery { background: white; color: black; width: 450px; display: inline; } #mcisearchbutton { background: silver; color: black; border: 2px solid black; padding: 3px; display: inline; margin: 0px 5px; cursor: pointer; } /* http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/ */ #mcdiv123 .grespinner { display: inline-block; height: 20px; width: 20px; 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 { font-size: 12px; max-width: 95% } .mcdiv123_correct_entry { cursor: pointer; color: green; font-size: 25px; margin-top: 10px; } .mcdiv123_correct_entry:hover { color: #41fd41; } .mcdiv123_incorrect { cursor: pointer; float: right; color: crimson; font-size: 11px; } .mcdiv123_incorrect { cursor: pointer; float: right; color: crimson; font-size: 15px; margin-right: 10px; } .mcdiv123_incorrect:hover { cursor: pointer; float: right; color: crimson; font-size: 15px; margin-right: 10px; border:2px solid white; } .mcdiv123_incorrect:hover { border-color: crimson; } #mcdiv123searchresults .result { font: 12px arial,helvetica,serif; border-top-width: 1px; border-top-color: #ccc; border-top-style: solid; padding: 5px } .mcdiv123_cover { max-width: 200px; max-height: 140px; } #mcdiv123searchresults .result .mcdiv123_score_badge { display: inline-block; margin: 3px; font-weight: 600; border-radius: 6px; color: black; padding: 5px; } #mcdiv123searchresults .result .floatleft { float: left; } #mcdiv123searchresults .result .clearleft { clear: left; } #mcdiv123searchresults .result .resultcontent { max-width: 360px; margin-left: 10px; } #mcdiv123searchresults .result .mcdiv_release_date { color: silver } .mcdiv123_image_placeholder { width: 82px; height: 82px; background: rgb(64, 64, 64); border-radius: 8px; } #mcdiv123searchresults .result a { color: #09f; font-weight: 700; text-decoration: none } #mcdiv123searchresults .mcdiv_desc { max-height:120px; overflow-y: auto; scrollbar-color: #d9d9d9 #eee; scrollbar-width: thin; } @media (prefers-color-scheme: dark) { ${BOX_CSS_DARK_THEME} } ${ darkTheme ? BOX_CSS_DARK_THEME : '' } ` async function acceptGDPR (showDialog) { if (showDialog === true) { await GM.setValue('gdpr', null) return acceptGDPR() } return new Promise(function (resolve) { GM.getValue('gdpr', null).then(function (value) { if (value === true) { return resolve(true) } if (value === false) { return resolve(false) } const html = '

Privacy Policy for "Show Metacritic.com ratings"

General Data Protection Regulation (GDPR)

We are a Data Controller of your information.

"Show Metacritic.com ratings" 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:

"Show Metacritic.com ratings" 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.

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 GDPR Privacy Policy Generator and the App Privacy Policy Generator.

In certain circumstances, you have the following data protection rights:

Log Files

"Show Metacritic.com ratings" 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.

Privacy Policies

You may consult this list to find the Privacy Policy for each of the advertising partners of "Show Metacritic.com ratings".

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 "Show Metacritic.com ratings", 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.

Note that "Show Metacritic.com ratings" has no access to or control over these cookies that are used by third-party advertisers.

Third Party Privacy Policies

"Show Metacritic.com ratings"\'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:

You can choose to disable cookies through your individual browser options.

Children\'s Information

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.

"Show Metacritic.com ratings" 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.

Online Privacy Policy Only

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 "Show Metacritic.com ratings". This policy is not applicable to any information collected offline or via channels other than this program. Our GDPR Privacy Policy was generated from the GDPR Privacy Policy Generator.

Contact

Contact us via github https://github.com/cvzi/Metacritic-userscript or email cuzi@openmail.cc

Consent

By using our program ("userscript"), you hereby consent to our Privacy Policy and agree to its terms.

' const div = document.body.appendChild(document.createElement('div')) div.innerHTML = html 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:16px' div.appendChild(document.createElement('br')) const acceptButton = div.appendChild(document.createElement('button')) acceptButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer') acceptButton.appendChild(document.createTextNode('Accept')) acceptButton.addEventListener('click', function () { div.remove() resolve(true) GM.setValue('gdpr', true) }) const declineButton = div.appendChild(document.createElement('button')) declineButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer') declineButton.appendChild(document.createTextNode('Decline')) declineButton.addEventListener('click', function () { alert('You may uninstall the userscript now.') div.remove() resolve(false) GM.setValue('gdpr', false) }) const space = div.appendChild(document.createElement('div')) space.style = 'height:2000px;' div.scrollIntoView() window.setTimeout(function () { 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.') }, 20) }) }) } function delay (ms) { return new Promise(function (resolve) { window.setTimeout(() => resolve(), ms) }) } function absoluteMetaURL (url) { if (url.startsWith('https://')) { return url } if (url.startsWith('http://')) { return 'https' + url.substr(4) } if (url.startsWith('//')) { return baseURL + url.substr(2) } if (url.startsWith('/')) { return baseURL + url.substr(1) } url = url.replace('/game/pc/', '/game/').replace('/game/playstation-4/', '/game/').replace('/game/xbox-one/', '/game/') return baseURL + url } const parseLDJSONCache = {} function parseLDJSON (keys, condition) { if (document.querySelector('script[type="application/ld+json"]')) { const xmlEntitiesElement = document.createElement('div') const xmlEntitiesPattern = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig const xmlEntities = function (s) { s = s.replace(xmlEntitiesPattern, (m) => { xmlEntitiesElement.innerHTML = m return xmlEntitiesElement.textContent }) return s } const decodeXmlEntities = function (jsonObj) { // Traverse through object, decoding all strings if (jsonObj !== null && typeof jsonObj === 'object') { Object.entries(jsonObj).forEach(([key, value]) => { // key is either an array index or object key jsonObj[key] = decodeXmlEntities(value) }) } else if (typeof jsonObj === 'string') { return xmlEntities(jsonObj) } return jsonObj } const data = [] const scripts = document.querySelectorAll('script[type="application/ld+json"]') for (let i = 0; i < scripts.length; i++) { let jsonld if (scripts[i].innerText in parseLDJSONCache) { jsonld = parseLDJSONCache[scripts[i].innerText] } else { try { jsonld = JSON.parse(scripts[i].innerText) parseLDJSONCache[scripts[i].innerText] = jsonld } catch (e) { parseLDJSONCache[scripts[i].innerText] = null continue } } if (jsonld) { if (Array.isArray(jsonld)) { data.push(...jsonld) } else { data.push(jsonld) } } } for (let i = 0; i < data.length; i++) { try { if (data[i] && data[i] && (typeof condition !== 'function' || condition(data[i]))) { if (Array.isArray(keys)) { const r = [] for (let j = 0; j < keys.length; j++) { r.push(data[i][keys[j]]) } return decodeXmlEntities(r) } else if (keys) { return decodeXmlEntities(data[i][keys]) } else if (typeof condition === 'function') { return decodeXmlEntities(data[i]) // Return whole object } } } catch (e) { continue } } return decodeXmlEntities(data) } return null } function name2metacritic (s) { const mc = s.normalize('NFKD').replace(/\//g, '').replace(/[\u0300-\u036F]/g, '').replace(/&/g, 'and').replace(/\W+/g, ' ').toLowerCase().trim().replace(/\W+/g, '-') if (!mc) { throw new Error("name2metacritic converted '" + s + "' to empty string") } return mc } function minutesSince (time) { const seconds = ((new Date()).getTime() - time.getTime()) / 1000 return seconds > 60 ? parseInt(seconds / 60) + ' min ago' : 'now' } function randomStringId () { const id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1) return id10() + id10() + id10() + id10() + id10() + id10() } function fixMetacriticURLs (html) { return html.replace(/ 89) { return colors.universalAcclaim } if (score > 74) { return colors.generallyFavorable } if (score > 49) { return colors.mixedOrAverage } if (score > 19) { return colors.generallyUnfavorable } if (score > 0) { return colors.overwhelmingDislike } return colors.tbd } else { if (score > 80) { return colors.universalAcclaim } if (score > 60) { return colors.generallyFavorable } if (score > 39) { return colors.mixedOrAverage } if (score > 19) { return colors.generallyUnfavorable } if (score > 0) { return colors.overwhelmingDislike } return colors.tbd } } function replaceBrackets (str) { str = str.replace(/\([^(]*\)/g, '') str = str.replace(/\[[^\]]*\]/g, '') return str.trim() } function removeSymbols (str) { str = str.replace(/[^\s0-9A-Za-zÀ-ÖØ-öø-ÿ]*/gi, '').trim() return str.trim() } const dashRegExp = /[-\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D]/ function removeAnythingAfterDash (str) { str = str.split(dashRegExp)[0] return str.trim() } function broadenSearch (data, step, type) { if (type === 'pcgame') { if (step > 0) { data[0] = replaceBrackets(data[0]) } else if (step > 1) { data[0] = removeSymbols(data[0]) } else if (step > 2) { data[0] = removeAnythingAfterDash(data[0]) } } else { data = data.map(removeSymbols) } return data } function balloonAlert (message, timeout, title, css, click) { let header if (title) { header = '
' + title + '
' } else if (title === false) { header = '' } else { header = '
Userscript alert
' } const div = $('
' + header + '
' + message.split('\n').join('
') + '
') div.css({ position: 'fixed', top: 10, left: 10, maxWidth: 200, zIndex: '2147483601', background: 'rgb(240,240,240)', border: '2px solid yellow', borderRadius: '6px', boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)', fontFamily: 'sans-serif', color: 'black' }) if (css) { div.css(css) } div.appendTo(document.body) if (click) { div.click(function (ev) { $(this).hide(500) click.call(this, ev) }) } if (!click) { const close = $('
').appendTo(div) close.click(function () { $(this.parentNode).hide(1000) }) } if (timeout && timeout > 0) { window.setTimeout(function () { div.hide(3000) }, timeout) } return div } function filterUniversalUrl (url) { try { url = url.match(/http.+/)[0] } catch (e) { } try { url = url.replace(/https?:\/\/(www.)?/, '') } catch (e) { } if (url.indexOf('#') !== -1) { url = url.split('#')[0] } if (url.startsWith('imdb.com/') && url.match(/(imdb\.com\/\w+\/\w+\/)/)) { // Remove movie subpage from imdb url return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1] } else if (url.startsWith('boxofficemojo.com/') && url.indexOf('id=') !== -1) { // Keep the important id= on try { const parts = url.split('?') const page = parts[0] + '?' const idparam = parts[1].match(/(id=.+?)(\.|&)/)[1] return page + idparam } catch (e) { return url } } else { // Default: Remove parameters return url.split('?')[0].split('&')[0] } } async function addToMap (url, metaurl) { const data = JSON.parse(await GM.getValue('map', '{}')) url = filterUniversalUrl(url) metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') data[url] = metaurl await GM.setValue('map', JSON.stringify(data)); (new Image()).src = baseURLwhitelist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId()) return [url, metaurl] } async function addToTemporaryBlacklist (metaurl) { const data = JSON.parse(await GM.getValue('temporaryblack', '{}')) metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') metaurl = metaurl.replace(/^\/+/, '') data[metaurl] = (new Date()).toJSON() // Remove old entries const now = (new Date()).getTime() const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000 for (const prop in data) { if (now - (new Date(data[prop].time)).getTime() > timeout) { delete data[prop] } } await GM.setValue('temporaryblack', JSON.stringify(data)) return true } async function removeFromTemporaryBlacklist (metaurl) { const data = JSON.parse(await GM.getValue('temporaryblack', '{}')) metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') metaurl = metaurl.replace(/^\/+/, '') if (metaurl in data) { delete data[metaurl] await GM.setValue('temporaryblack', JSON.stringify(data)) } } async function isTemporaryBlacklisted (metaurl) { const data = JSON.parse(await GM.getValue('temporaryblack', '{}')) metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') metaurl = metaurl.replace(/^\/+/, '') if (metaurl in data) { const now = (new Date()).getTime() const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000 if (now - (new Date(data[metaurl])).getTime() < timeout) { return true } } return false } async function addToBlacklist (url, metaurl) { const data = JSON.parse(await GM.getValue('black', '[]')) url = filterUniversalUrl(url) metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') data.push([url, metaurl]) await GM.setValue('black', JSON.stringify(data)); (new Image()).src = baseURLblacklist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId()) return [url, metaurl] } async function removeFromBlacklist (docurl, metaurl) { docurl = filterUniversalUrl(docurl) docurl = docurl.replace(/https?:\/\/(www.)?/, '') metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash metaurl = metaurl.replace(/^\/+/, '') // remove starting slash const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ] const found = [] for (let i = 0; i < data.length; i++) { if (data[i][0] === docurl && data[i][1] === metaurl) { found.push(i) } } for (let i = found.length - 1; i >= 0; i--) { data.pop(i) } await GM.setValue('black', JSON.stringify(data)) } async function isBlacklistedUrl (docurl, metaurl) { docurl = filterUniversalUrl(docurl) docurl = docurl.replace(/https?:\/\/(www.)?/, '') metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '') metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash metaurl = metaurl.replace(/^\/+/, '') // remove starting slash const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ] for (let i = 0; i < data.length; i++) { if (data[i][0] === docurl && data[i][1] === metaurl) { return true } } return false } let listenForHotkeysActive = false function listenForHotkeys (code, cb) { // Call cb() as soon as the code sequence was typed if (listenForHotkeysActive) { return } listenForHotkeysActive = true let i = 0 $(document).bind('keydown.listenForHotkeys', function (ev) { if (document.activeElement === document.body) { if (ev.key !== code[i]) { i = 0 } else { i++ if (i === code.length) { ev.preventDefault() $(document).unbind('keydown.listenForHotkeys') cb() } } } }) } function waitForHotkeysMETA () { listenForHotkeys('meta', (ev) => openSearchBox()) } async function handleJSONredirect (response) { let blacklistedredirect = false const j = JSON.parse(response.responseText) // Blacklist items from database received? if ('blacklist' in j && j.blacklist && j.blacklist.length) { // Save new blacklist items const data = JSON.parse(await GM.getValue('black', '[]')) for (let i = 0; i < j.blacklist.length; i++) { const saveDocurl = j.blacklist[i].docurl const saveMetaurl = j.blacklist[i].metaurl data.push([saveDocurl, saveMetaurl]) if (j.jsonRedirect === '/' + saveMetaurl) { // Redirect is blacklisted! blacklistedredirect = true } } await GM.setValue('black', JSON.stringify(data)) } if (blacklistedredirect) { // Redirect was blacklisted, show nothing console.debug('ShowMetacriticRatings: Redirect was blacklisted -> show nothing') return null } else { // Load redirect current.metaurl = absoluteMetaURL(j.jsonRedirect) response = await asyncRequest({ url: current.metaurl }).catch(function (response) { console.error('ShowMetacriticRatings: Error 01') }) return response } } function extractHoverFromFullPage (response) { let html = 'ShowMetacriticRatings:
Error occured in extractHoverFromFullPage()' try { // Try parsing HTML const doc = domParser().parseFromString(response.responseText, 'text/html') let content = null // Try to get the review containers from the bottom of the page below the actors const carouselItems = doc.querySelectorAll('.c-reviewsSection_carouselContainer .c-reviewsOverview_overviewDetails') if (carouselItems.length > 0) { content = Array.from(carouselItems).map(e => e.outerHTML).join('\n\n') } else { // Fallback: Try to get the review containers from the right side of the page next to the poster/screenshot content = doc.querySelector('.c-productHero_scoreInfo').innerHTML } // Get the game row with the other platform scores const gameRow = doc.querySelector('.c-PageProductGame_row') if (gameRow) { gameRow.querySelectorAll('.c-gamePlatformTile').forEach(e => { const desc = e.querySelector('.c-gamePlatformTile-description') if (desc.textContent.indexOf('PlayStation') !== -1) { e.remove() } }) gameRow.querySelectorAll('.c-gamePlatformTile-description').forEach(e => { e.textContent = e.querySelector('svg title').textContent }) content += `\n\n` } if (!content) { throw new Error('No content found') } html = `
${content}
` } catch (e) { console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e) // fallback to cutting out the relevant parts const parts = response.responseText.split('c-productHero_score-container') html = '
' if (html.length > 5000) { // Probably something went wrong, let's cut the response to prevent too long content console.warn('ShowMetacriticRatings: Cutting response to 5000 chars') html = html.substring(0, 5000) } } return html } function asyncRequest (data) { return new Promise(function (resolve, reject) { isInRequestCache(data).then(function (cachedValue) { if (cachedValue) { console.debug(`${scriptName}: asyncRequest() Cache hit for`, data) return window.setTimeout(() => resolve(cachedValue), 10) } const defaultHeaders = { Referer: data.url, 'User-Agent': navigator.userAgent } const defaultData = { method: 'GET', onload: function (response) { storeInRequestCache(data, response) resolve(response) }, onerror: (response) => reject(response) } if ('headers' in data) { data.headers = Object.assign(defaultHeaders, data.headers) } else { data.headers = defaultHeaders } data = Object.assign(defaultData, data) console.debug(`${scriptName}: asyncRequest() GM.xmlHttpRequest`, data) GM.xmlHttpRequest(data) }) }) } async function storeInRequestCache (requestData, response) { const newkey = JSON.stringify({ url: requestData.url, method: requestData.method || 'GET', data: requestData.data || null }) const cache = JSON.parse(await GM.getValue('requestcache', '{}')) const now = (new Date()).getTime() const timeout = 15 * 60 * 1000 for (const prop in cache) { // Delete cached values, that are older than 15 minutes if (now - (new Date(cache[prop].time)).getTime() > timeout) { delete cache[prop] } } const newobj = {} for (const key in response) { newobj[key] = response[key] } newobj.responseText = '' + response.responseText newobj.cached = true if (!('time' in newobj)) { newobj.time = (new Date()).toJSON() } cache[newkey] = newobj await GM.setValue('requestcache', JSON.stringify(cache)) } async function isInRequestCache (requestData) { const key = JSON.stringify({ url: requestData.url, method: requestData.method || 'GET', data: requestData.data || null }) const cache = JSON.parse(await GM.getValue('requestcache', '{}')) const now = (new Date()).getTime() const timeout = 15 * 60 * 1000 for (const prop in cache) { // Delete cached values, that are older than 15 minutes if (now - (new Date(cache[prop].time)).getTime() > timeout) { delete cache[prop] } } if (key in cache) { return cache[key] } else { return false } } async function storeInHoverCache (metaurl, response, orgMetaUrl) { const cache = JSON.parse(await GM.getValue('hovercache', '{}')) const now = (new Date()).getTime() const timeout = 2 * 60 * 60 * 1000 for (const prop in cache) { // Delete cached values, that are older than 2 hours if (now - (new Date(cache[prop].time)).getTime() > timeout) { delete cache[prop] } } const newobj = {} for (const key in response) { newobj[key] = response[key] } newobj.responseText = '' + response.responseText newobj.cached = true if (!('time' in newobj)) { newobj.time = (new Date()).toJSON() } cache[metaurl] = newobj if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl } } await GM.setValue('hovercache', JSON.stringify(cache)) } async function isInHoverCache (metaurl) { const cache = JSON.parse(await GM.getValue('hovercache', '{}')) const now = (new Date()).getTime() const timeout = 2 * 60 * 60 * 1000 for (const prop in cache) { // Delete cached values, that are older than 2 hours if (now - (new Date(cache[prop].time)).getTime() > timeout) { delete cache[prop] } } function resolveRedirects (cacheEntry) { if (cacheEntry.redirect) { const newkey = cacheEntry.redirect if (newkey in cache) { const value = cache[newkey] delete cache[newkey] return resolveRedirects(value) } } else { return cacheEntry } return false } if (metaurl in cache) { const value = cache[metaurl] delete cache[metaurl] return resolveRedirects(value) } else { return false } } async function loadHoverInfo () { const cacheResponse = await isInHoverCache(current.metaurl) if (cacheResponse !== false) { console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`) if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) { return await handleJSONredirect(cacheResponse) } return cacheResponse } const requestURL = baseURLdatabase const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl) let response = await asyncRequest({ method: 'POST', url: requestURL, data: requestParams, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).catch(function (response) { console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status) }) if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) { response = await handleJSONredirect(response) } if (response.status >= 500) { // Metacritic server error, try again after 2 seconds console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status) await delay(2000) response = await asyncRequest({ url: current.metaurl }).catch(function (response) { console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status) }) if (response.status > 300) { console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status) } else { const newobj = {} for (const key in response) { newobj[key] = response[key] } newobj.responseText = extractHoverFromFullPage(response) response = newobj } } // Extract relevant data from HTML if (!('time' in response)) { response.time = (new Date()).toJSON() } if (response.status === 200 && response.responseText) { const newobj = {} for (const key in response) { newobj[key] = response[key] } newobj.responseText = extractHoverFromFullPage(response) response = newobj return response } else { const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status) error.status = response.status error.responseText = response.responseText throw error } } function changePosition () { // Cycle through positions GM.getValue('position', JSON.stringify(windowPositions[0])).then(function (s) { let index for (index = 0; index < windowPositions.length; index++) { if (JSON.stringify(windowPositions[index]) === s) { break } } const nextIndex = (index + 1) % windowPositions.length GM.setValue('position', JSON.stringify(windowPositions[nextIndex])).then(function () { document.location.reload() }) }) } function onSizeChanged () { GM.getValue('size', 100).then(function (size) { if (size && size !== 100) { size = parseInt(size) $('#mcdiv123').css('transform', `scale(${size}%)`) } }) } function changeSizeEnlarge () { GM.getValue('size', 100).then((size) => { GM.setValue('size', parseInt(size) + 5).then(onSizeChanged) }) } function changeSizeShrink () { GM.getValue('size', 100).then((size) => { GM.setValue('size', parseInt(size) - 5).then(onSizeChanged) }) } const current = { metaurl: false, docurl: false, type: false, data: [], // Array of raw search keys searchTerm: false, product: null, broadenCounter: 0 } async function onBlacklistedPage () { GM.registerMenuCommand('Show Metacritic.com ratings - Remove from Blacklist', () => removeFromBlacklistAndReload()) } async function removeFromBlacklistAndReload () { await removeFromBlacklist(current.docurl, current.metaurl) await removeFromTemporaryBlacklist(current.metaurl) main() } async function loadMetacriticUrl (fromSearch) { if (!current.metaurl) { alert('ShowMetacriticRatings: Error 04') return } const orgMetaUrl = current.metaurl if (await isBlacklistedUrl(document.location.href, current.metaurl)) { waitForHotkeysMETA() onBlacklistedPage() return } if (await isTemporaryBlacklisted(current.metaurl)) { console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`) waitForHotkeysMETA() onBlacklistedPage() return } const response = await loadHoverInfo().catch(async function (response) { if (response instanceof Error || (response && response.stack && response.message)) { if (!fromSearch && ('status' in response && response.status === 404)) { console.debug('ShowMetacriticRatings: loadMetacriticUrl(): status=404', response) // No results let broadenFct = broadenSearch // global broadenSearch function is the default if ('broaden' in current.product) { // try product 'broaden'-function if it is defined broadenFct = current.product.broaden } const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type) if (JSON.stringify(newData) !== JSON.stringify(current.data)) { current.data = newData metacritic[current.type](current.docurl, current.product, ...newData) } else if (JSON.stringify(newData) === JSON.stringify(current.data)) { // Same data as before, try once again to broaden const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type) if (JSON.stringify(newData2) !== JSON.stringify(current.data)) { current.data = newData2 metacritic[current.type](current.docurl, current.product, ...newData2) } else { console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps') } } else { console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData) } } else { console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response) } } if (!fromSearch) { startSearch() } }) if (await isBlacklistedUrl(document.location.href, current.metaurl)) { waitForHotkeysMETA() onBlacklistedPage() return } if (typeof response !== 'undefined') { showHoverInfo(response, orgMetaUrl) } else { waitForHotkeysMETA() } } async function startSearch () { waitForHotkeysMETA() if (current.type === 'music') { current.searchTerm = current.data[0] } else { current.searchTerm = current.data.join(' ') } const items = await fandomProdApigeeSearch(current.searchTerm, current.type) if (!items) { alert('ShowMetacriticRatings: Error 05 item=', items) } let multiple = false if (items.length === 0) { // No results console.debug('ShowMetacriticRatings: No results for searchTerm=' + current.searchTerm) } else if (items.length === 1) { // One result, let's show it const itemURL = absoluteMetaURL(items[0].metacriticUrl) if (!await isBlacklistedUrl(document.location.href, itemURL)) { current.metaurl = itemURL loadMetacriticUrl(true) return } else { onBlacklistedPage() return } } else { // More than one result multiple = true console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm) const exactMatches = [] items.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title if (current.searchTerm.toLowerCase() === result.title.toLowerCase()) { exactMatches.push(result) } }) if (exactMatches.length === 0) { // Try to be a bit more fuzzy items.forEach(function (result, i) { if (removeSymbols(current.searchTerm.toLowerCase()) === removeSymbols(result.title.toLowerCase())) { exactMatches.push(result) } }) } if (exactMatches.length === 1) { // Only one exact match, let's show it console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm) const itemURL = absoluteMetaURL(exactMatches[0].metacriticUrl) if (!await isBlacklistedUrl(document.location.href, itemURL)) { current.metaurl = itemURL loadMetacriticUrl(true) return } else { onBlacklistedPage() return } } } // HERE: multiple results or no result. The user may type "meta" now if (multiple) { balloonAlert('Multiple metacritic results. Type "meta" for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5, cursor: 'pointer' }, () => openSearchBox(true)) } } function openSearchBox (search) { let query if (current.type === 'music') { query = current.data[0] } else { query = current.data.join(' ') } $('#mcdiv123').remove() const div = $('
').appendTo(document.body) div.css({ minWidth: 300, bottom: 0, left: 0 }) GM.getValue('position', false).then(function (s) { if (s) { div.css({ top: '', left: '', bottom: '', right: '' }) div.css(JSON.parse(s)) } }) $('').appendTo(div).focus().val(query).on('keypress', function (e) { const code = e.keyCode || e.which if (code === 13) { // Enter key searchBoxSearch(e, $('#mcisearchquery').val()) } }) $('