Show Metacritic.com ratings

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

当前为 2019-07-28 提交的版本,查看 最新版本

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