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

当前为 2018-09-14 提交的版本,查看 最新版本

  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.3.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 33
  16. // @connect metacritic.com
  17. // @connect php-cuzi.herokuapp.com
  18. // @include https://*.bandcamp.com/*
  19. // @include https://itunes.apple.com/*/album/*
  20. // @include https://play.google.com/store/music/album/*
  21. // @include https://play.google.com/store/movies/details/*
  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. // @include http://www.tvmaze.com/shows/*
  70. // @include http://www.tvguide.com/tvshows/*
  71. // @include https://www.tvguide.com/tvshows/*
  72. // @include http://followshows.com/show/*
  73. // @include https://followshows.com/show/*
  74. // @include http://thetvdb.com/*tab=series*
  75. // @include https://thetvdb.com/*tab=series*
  76. // @include http://www.thetvdb.com/*tab=series*
  77. // @include https://www.thetvdb.com/*tab=series*
  78. // @include https://www.thetvdb.com/series/*
  79. // @include http://consequenceofsound.net/*
  80. // @include https://consequenceofsound.net/*
  81. // @include http://pitchfork.com/*
  82. // @include https://pitchfork.com/*
  83. // @include http://www.last.fm/*
  84. // @include https://www.last.fm/*
  85. // @include http://tvnfo.com/s/*
  86. // @include https://tvnfo.com/s/*
  87. // @include http://rateyourmusic.com/release/album/*
  88. // @include https://rateyourmusic.com/release/album/*
  89. // @include https://open.spotify.com/*
  90. // @include https://play.spotify.com/album/*
  91. // ==/UserScript==
  92.  
  93.  
  94. var baseURL = "https://www.metacritic.com/";
  95.  
  96. var baseURL_music = "https://www.metacritic.com/music/";
  97. var baseURL_movie = "https://www.metacritic.com/movie/";
  98. var baseURL_pcgame = "https://www.metacritic.com/game/pc/";
  99. var baseURL_ps4 = "https://www.metacritic.com/game/playstation-4/";
  100. var baseURL_xone = "https://www.metacritic.com/game/xbox-one/";
  101. var baseURL_tv = "https://www.metacritic.com/tv/";
  102.  
  103. var baseURL_search = "https://www.metacritic.com/search/{type}/{query}/results";
  104. var baseURL_autosearch = "https://www.metacritic.com/autosearch";
  105.  
  106. var baseURL_database = "https://php-cuzi.herokuapp.com/r.php";
  107. var baseURL_whitelist = "https://php-cuzi.herokuapp.com/whitelist.php";
  108. var baseURL_blacklist = "https://php-cuzi.herokuapp.com/blacklist.php";
  109.  
  110. // http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/
  111. 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%}";
  112.  
  113. function getHostname(url) {
  114. with(document.createElement("a")) {
  115. href = url;
  116. return hostname;
  117. }
  118. }
  119. function absoluteMetaURL(url) {
  120. if(url.startsWith("https://")) {
  121. return url;
  122. }
  123. if(url.startsWith("http://")) {
  124. return "https" + url.substr(4);
  125. }
  126. if(url.startsWith("//")) {
  127. return baseURL + url.substr(2);
  128. }
  129. if(url.startsWith("/")) {
  130. return baseURL + url.substr(1);
  131. }
  132. return baseURL + url;
  133. }
  134.  
  135. function parseLDJSON(condition, keys) {
  136. if(document.querySelector('script[type="application/ld+json"]')) {
  137. var data = [];
  138. var scripts = document.querySelectorAll('script[type="application/ld+json"]');
  139. for(let i = 0; i < scripts.length; i++) {
  140. try {
  141. var jsonld = JSON.parse(scripts[i].innerText);
  142. } catch(e) {
  143. continue;
  144. }
  145. if(jsonld) {
  146. if(Array.isArray(jsonld)) {
  147. data.push(...jsonld)
  148. } else {
  149. data.push(jsonld);
  150. }
  151. }
  152. }
  153. for(let i = 0; i < data.length; i++) {
  154. try {
  155. if(data[i] && data[i] && condition(data[i])) {
  156. if(Array.isArray(keys)) {
  157. let r = [];
  158. for(let j = 0; j < keys.length; j++) {
  159. r.push(data[i][keys[j]]);
  160. }
  161. return r;
  162. } else {
  163. return data[i][keys];
  164. }
  165. }
  166. } catch(e) {
  167. continue;
  168. }
  169. }
  170. }
  171. return null;
  172. }
  173.  
  174.  
  175. function name2metacritic(s) {
  176. return s.normalize('NFKD').replace(/\//g,"").replace(/[\u0300-\u036F]/g, '').replace(/&/g,"and").replace(/\W+/g, " ").toLowerCase().trim().replace(/\W+/g,"-");
  177. }
  178. function minutesSince(time) {
  179. var seconds = ((new Date()).getTime() - time.getTime()) / 1000;
  180. return seconds>60?parseInt(seconds/60)+" min ago":"now";
  181. }
  182. function randomStringId() {
  183. var id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1);
  184. return id10()+id10()+id10()+id10()+id10()+id10();
  185. }
  186. function fixMetacriticURLs(html) {
  187. return html.replace(/<a /g,'<a target="_blank" ').replace(/href="\//g,'href="'+baseURL).replace(/src="\//g,'src="'+baseURL);
  188. }
  189. function searchType2metacritic(type) {
  190. return ({
  191. 'movie' : 'movie',
  192. 'pcgame' : 'game',
  193. 'xonegame' : 'game',
  194. 'ps4game' : 'game',
  195. 'music' : 'album',
  196. 'tv' : 'tv'
  197. })[type];
  198. }
  199. function metacritic2searchType(type) {
  200. return ({
  201. "Album" : "music",
  202. "TV" : "tv",
  203. "Movie" : "movie",
  204. "PC Game" : "pcgame",
  205. "PS4 Game" : "ps4game",
  206. "XONE Game" : "onegame",
  207. "WIIU Game" : "xxxxx",
  208. "3DS Game" : "xxxx"
  209. })[type];
  210. }
  211.  
  212.  
  213. function metaScore(score, word) {
  214. var fg,bg,t;
  215. if(score == null) {
  216. fg = "black";
  217. bg = "#ccc";
  218. t = "tbd";
  219. } else if(score >= 75) {
  220. fg = "white";
  221. bg = "#6c3";
  222. t = parseInt(score);
  223. } else if(score < 40) {
  224. fg = "white";
  225. bg = "#f00";
  226. t = parseInt(score);
  227. } else {
  228. fg = "white";
  229. bg = "#fc3";
  230. t = parseInt(score);
  231. }
  232. 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>';
  233. }
  234.  
  235. function balloonAlert(message, timeout, title, css, click) {
  236. var header;
  237. if(title) {
  238. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title +"</div>";
  239. } else if(title === false) {
  240. header = '';
  241. } else {
  242. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>';
  243. }
  244. var div = $("<div>" + header + '<div style="padding:5px">' + message.split("\n").join("<br>") + "</div></div>");
  245. div.css({
  246. position : "fixed",
  247. top : 10,
  248. left : 10,
  249. maxWidth: 200,
  250. zIndex : "5010002",
  251. background : "rgb(240,240,240)",
  252. border : "2px solid yellow",
  253. borderRadius :"6px",
  254. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  255. fontFamily: "sans-serif",
  256. color: "black"
  257. });
  258. if(css) {
  259. div.css(css);
  260. }
  261. div.appendTo(document.body);
  262. if(click) {
  263. div.click(function(ev) {
  264. $(this).hide(500);
  265. click.call(this,ev);
  266. });
  267. }
  268. if(!click) {
  269. var close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">&#10062;</div>').appendTo(div);
  270. close.click(function(){
  271. $(this.parentNode).hide(1000);
  272. });
  273. }
  274. if(timeout && timeout > 0) {
  275. window.setTimeout(function() {
  276. div.hide(3000);
  277. }, timeout);
  278. }
  279. return div;
  280. }
  281.  
  282.  
  283. function filterUniversalUrl(url) {
  284. try {
  285. url = url.match(/http.+/)[0];
  286. } catch(e) { }
  287. try {
  288. url = url.replace(/https?:\/\/(www.)?/,"");
  289. } catch(e) { }
  290. if(url.startsWith("imdb.com/") && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
  291. // Remove movie subpage from imdb url
  292. return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1];
  293. } else if(url.startsWith("thetvdb.com/")) {
  294. // Do nothing with thetvdb.com urls
  295. return url;
  296. } else if(url.startsWith("boxofficemojo.com/")) {
  297. // Keep the important id= on
  298. try {
  299. var parts = url.split("?");
  300. var page = url[0] + "?";
  301. var idparam = url[1].match(/(id=.+?)(\.|&)/)[1];
  302. return page+idparam;
  303. } catch(e) {
  304. return url;
  305. }
  306. } else {
  307. // Default: Remove parameters
  308. return url.split("?")[0].split("&")[0];
  309. }
  310. }
  311.  
  312. async function addToMap(url, metaurl) {
  313. var data = JSON.parse(await GM.getValue("map","{}"));
  314. var url = filterUniversalUrl(url);
  315. var metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//,"");
  316.  
  317. data[url] = metaurl;
  318. await GM.setValue("map", JSON.stringify(data));
  319. (new Image()).src = baseURL_whitelist + "?docurl="+encodeURIComponent(url)+"&metaurl="+encodeURIComponent(metaurl)+"&ref="+encodeURIComponent(randomStringId());
  320. return [url, metaurl];
  321. }
  322.  
  323. async function addToBlacklist(url, metaurl) {
  324. var data = JSON.parse(await GM.getValue("black","[]"));
  325. var url = filterUniversalUrl(url);
  326. var metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//,"");
  327.  
  328. data.push([url,metaurl]);
  329. await GM.setValue("black", JSON.stringify(data));
  330. (new Image()).src = baseURL_blacklist + "?docurl="+encodeURIComponent(url)+"&metaurl="+encodeURIComponent(metaurl)+"&ref="+encodeURIComponent(randomStringId());
  331. return [url, metaurl];
  332. }
  333.  
  334.  
  335.  
  336.  
  337. async function isBlacklistedUrl(docurl, metaurl) {
  338.  
  339. docurl = filterUniversalUrl(docurl);
  340. docurl = docurl.replace(/https?:\/\/(www.)?/,"");
  341. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//,"");
  342. metaurl = metaurl.replace(/\/\//g,"/").replace(/\/\//g,"/");; // remove double slash
  343. metaurl = metaurl.replace(/^\/+/,""); // remove starting slash
  344. var data = JSON.parse(await GM.getValue("black","[]")); // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  345. for(var i = 0; i < data.length; i++) {
  346. if(data[i][0] == docurl && data[i][1] == metaurl) {
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352.  
  353. async function isBlacklisted(metaurl) {
  354. return await isBlacklistedUrl("" + document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search, metaurl);
  355. }
  356.  
  357.  
  358.  
  359. function listenForHotkeys(code, cb) {
  360. // Call cb() as soon as the code sequence was typed
  361. var i = 0;
  362. $(document).bind("keydown.listenForHotkeys",function(ev) {
  363. if(document.activeElement == document.body) {
  364. if(ev.key != code[i]) {
  365. i = 0;
  366. } else {
  367. i++;
  368. if(i == code.length) {
  369. ev.preventDefault();
  370. $(document).unbind("keydown.listenForHotkeys");
  371. cb();
  372. }
  373. }
  374. }
  375. });
  376. }
  377.  
  378.  
  379. async function metacritic_hoverInfo(url, docurl, cb, errorcb, nocache) {
  380. // Get the metacritic hover info. Requests are cached.
  381. var handleresponse = function(response, cached) {
  382. if(response.status == 200 && response.responseText && cb) {
  383. if(~response.responseText.indexOf('"jsonRedirect"')) { // {"viewer":{},"mixpanelToken":"6e219fd....","mixpanelDistinctId":"255.255.255.255","omnitureDebug":0,"jsonRedirect":"\/movie\/national-lampoons-vacation"}
  384. var blacklistedredirect = false;
  385. var j = JSON.parse(response.responseText);
  386. current.url = absoluteMetaURL(j["jsonRedirect"]);
  387. delete cache[url]; // Delete original url from cache. The redirect URL will then be saved in metacritic_hoverInfo(...)
  388.  
  389. // Blacklist items from database received?
  390. if("blacklist" in j && j.blacklist && j.blacklist.length) {
  391. // Save new blacklist items
  392. GM.getValue("black","[]").then(function(json_data) {
  393. var data = JSON.parse(json_data);
  394. for(var i = 0; i < j.blacklist.length; i++) {
  395. var save_docurl = j.blacklist[i].docurl;
  396. var save_metaurl = j.blacklist[i].metaurl;
  397. data.push([save_docurl,save_metaurl]);
  398. if(j["jsonRedirect"] == "/"+save_metaurl) {
  399. // Redirect is blacklisted!
  400. blacklistedredirect = true;
  401. }
  402. }
  403. GM.setValue("black", JSON.stringify(data));
  404. });
  405. }
  406. if(blacklistedredirect && errorcb) {
  407. // Redirect was blacklisted, show nothing
  408. errorcb(response.responseText, new Date(response.time));
  409. } else {
  410. // Load redirect
  411. metacritic_hoverInfo(absoluteMetaURL(j["jsonRedirect"]), false, cb, errorcb, true);
  412. }
  413. } else {
  414. // Show
  415. cb(response.responseText, new Date(response.time));
  416. }
  417. } else if(response.status != 200 && errorcb) {
  418. errorcb(response.responseText, new Date(response.time));
  419. if(!cached)
  420. console.log("Show metacritic ratings: Error 01:"+response.status+"\n"+url);
  421. } else if(!response.responseText) {
  422. errorcb("", new Date(response.time));
  423. if(!cached)
  424. console.log("Show metacritic ratings: Error 02: response empty. Status:"+response.status+"\n"+url);
  425. }
  426. };
  427.  
  428. var cache = JSON.parse(await GM.getValue("hovercache","{}"));
  429. for(var prop in cache) {
  430. // Delete cached values, that are older than 2 hours
  431. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  432. delete cache[prop];
  433. }
  434. }
  435. if(!nocache && url in cache) {
  436. handleresponse(cache[url], true);
  437. } else {
  438. var requestURL = url;
  439. var requestParams = "hoverinfo=1";
  440. if(docurl && docurl.indexOf("metacritic.com") == -1 && docurl.indexOf(baseURL_database) == -1) {
  441. // Ask database for correct metacritic entry:
  442. requestURL = baseURL_database;
  443. requestParams = "m=" + encodeURIComponent(docurl) + "&a=" + encodeURIComponent(url);
  444. }
  445. GM.xmlHttpRequest({
  446. method: "POST",
  447. url: requestURL,
  448. data: requestParams,
  449. headers: {
  450. "Referer" : url,
  451. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  452. "Host" : getHostname(requestURL), // This is important, otherwise Metacritic refuses to answer!
  453. //"User-Agent" : "MetacriticUserscript "+navigator.userAgent,
  454. "User-Agent" : navigator.userAgent,
  455. "X-Requested-With" : "XMLHttpRequest"
  456. },
  457. onload: function(response) {
  458. response.time = (new Date()).toJSON();
  459. cache[url] = response;
  460. GM.setValue("hovercache",JSON.stringify(cache));
  461. handleresponse(response, false);
  462. },
  463. onerror: function(response) {
  464. console.log("Show metacritic ratings: Hover info error 03: "+response.status+"\nURL: "+requestURL+"\nResponse:\n"+response.responseText);
  465. },
  466. });
  467. }
  468. }
  469. async function metacritic_searchResults(url, cb, errorcb) {
  470. // Get metacritic search results. Requests are cached.
  471. var handleresponse = function(response, cached) {
  472. if(response.results.length && cb) {
  473. cb(response.results, new Date(response.time));
  474. } else if(response.results.length == 0 && errorcb) {
  475. errorcb(response.results, new Date(response.time));
  476. }
  477. };
  478. var cache = JSON.parse(await GM.getValue("searchcache","{}"));
  479. for(var prop in cache) {
  480. // Delete cached values, that are older than 2 hours
  481. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  482. delete cache[prop];
  483. }
  484. }
  485. if(url in cache) {
  486. handleresponse(cache[url], true);
  487. } else {
  488. GM.xmlHttpRequest({
  489. method: "GET",
  490. url: url,
  491. headers: {
  492. "Referer" : url,
  493. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  494. "Host" : "www.metacritic.com",
  495. "User-Agent" : "MetacriticUserscript "+navigator.userAgent,
  496. },
  497. onload: function(response) {
  498. var results = [];
  499. if(!~response.responseText.indexOf("No search results found.")) {
  500. var d = $('<html>').html(response.responseText);
  501. d.find("ul.search_results.module .result").each(function() {
  502. results.push(this.innerHTML);
  503. });
  504. }
  505.  
  506. response = {
  507. time : (new Date()).toJSON(),
  508. results : results,
  509. };
  510. cache[url] = response;
  511. GM.setValue("searchcache",JSON.stringify(cache));
  512. handleresponse(response, false);
  513. },
  514. onerror: function(response) {
  515. console.log("Show metacritic ratings: Search error 04: "+response.status+"\n"+url);
  516. handleresponse({
  517. time : (new Date()).toJSON(),
  518. results : [],
  519. }, false);
  520. }
  521. });
  522. }
  523. }
  524.  
  525. function metacritic_showHoverInfo(url, docurl) {
  526. if(!url) {
  527. return;
  528. }
  529. metacritic_hoverInfo(url, docurl?docurl:false,
  530. // On Success
  531. function(html, time) {
  532. $("#mcdiv123").remove();
  533. var div = $('<div id="mcdiv123"></div>').appendTo(document.body);
  534. div.css({
  535. position:"fixed",
  536. bottom :0,
  537. left: 0,
  538. minWidth: 300,
  539. backgroundColor: "#fff",
  540. border: "2px solid #bbb",
  541. borderRadius:" 6px",
  542. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  543. color: "#000",
  544. padding:" 3px",
  545. zIndex: "5010001",
  546. });
  547. // Functions for communication between page and iframe
  548. // Mozilla can access parent.document
  549. // Chrome can use postMessage()
  550. var frame_status = false; // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  551. function loadExternalImage(url, myframe) {
  552. // Load external image, bypass CSP
  553. GM.xmlHttpRequest({
  554. method: "GET",
  555. url: url,
  556. responseType : "arraybuffer",
  557. onload: function(response) {
  558. myframe.contentWindow.postMessage({
  559. "mcimessage_imgLoaded" : true,
  560. "mcimessage_imgData" : response.response,
  561. "mcimessage_imgOrgSrc" : url
  562. },'*');
  563. }
  564. });
  565. }
  566. var functions = {
  567. "parent" : function() {
  568. var f = parent.document.getElementById('mciframe123');
  569. var lastdiff = -200000;
  570. window.addEventListener("message", function(e){
  571. if(typeof e.data != "object") {
  572. return;
  573. } else if("mcimessage0" in e.data) {
  574. frame_status = true; // Frame content was loaded successfully
  575. } else if("mcimessage1" in e.data) {
  576. f.style.width = parseInt(f.style.width)+10+"px";
  577. if(e.data.heightdiff == lastdiff) {
  578. f.style.height = parseInt(f.style.height)+5+"px";
  579. }
  580. lastdiff = e.data.heightdiff;
  581. } else if("mcimessage2" in e.data) {
  582. f.style.height = parseInt(f.style.height)+15+"px";
  583. f.style.width = "400px";
  584. } else if("mcimessage_loadImg" in e.data) {
  585. loadExternalImage(e.data.mcimessage_imgUrl, f);
  586. } else {
  587. return;
  588. }
  589. f.contentWindow.postMessage({
  590. "mcimessage3" : true,
  591. "mciframe123_clientHeight" : f.clientHeight,
  592. "mciframe123_clientWidth" : f.clientWidth,
  593. },'*');
  594. });
  595. },
  596. "frame" : function() {
  597. parent.postMessage({"mcimessage0":true},'*'); // Loading frame content was successfull
  598. var i = 0;
  599. window.addEventListener("message", function(e){
  600. if(typeof e.data == "object" && "mcimessage_imgLoaded" in e.data) {
  601. // Load external image
  602. var arrayBufferView = new Uint8Array( e.data["mcimessage_imgData"] );
  603. var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
  604. var urlCreator = window.URL || window.webkitURL;
  605. var imageUrl = urlCreator.createObjectURL( blob );
  606. var img = failedImages[e.data["mcimessage_imgOrgSrc"]];
  607. img.src = imageUrl;
  608. }
  609. if(!("mcimessage3" in e.data)) return;
  610. if(e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  611. parent.postMessage({"mcimessage1":1, "heightdiff":document.body.scrollHeight - e.data.mciframe123_clientHeight},'*');
  612. i++;
  613. }
  614. if(i >= 100) {
  615. parent.postMessage({"mcimessage2":1},'*')
  616. i = 0;
  617. }
  618. });
  619. parent.postMessage({"mcimessage1":1,"heightdiff":-100000},'*');
  620. }
  621. };
  622.  
  623. var css = "#hover_div .clr { clear: both}#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;}";
  624.  
  625. var framesrc = 'data:text/html,';
  626. framesrc += encodeURIComponent('<!DOCTYPE html>\
  627. <html lang="en">\
  628. <head>\
  629. <meta charset="utf-8">\
  630. <title>Metacritic info</title>\
  631. <style>body { margin:0px; padding:0px; background:white; }' + css
  632. +'\
  633. </style>\
  634. <script>\
  635. var failedImages = {};\
  636. function detectCSP(img) {\
  637. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {\
  638. return true;\
  639. }\
  640. return false;\
  641. }\
  642. function findCSPerrors() {\
  643. var imgs = document.querySelectorAll("img");\
  644. for(var i = 0; i < imgs.length; i++) {\
  645. if(imgs[i].complete && detectCSP(imgs[i])) {\
  646. fixCSP(imgs[i]);\
  647. }\
  648. }\
  649. }\
  650. function fixCSP(img) {\
  651. console.log("Loading image failed. Bypassing CSP...");\
  652. failedImages[img.src] = img;\
  653. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*"); \
  654. }\
  655. function on_load() {\
  656. ('+functions.frame.toString()+')();\
  657. window.setTimeout(findCSPerrors, 500);\
  658. \
  659. }\
  660. </script>\
  661. </head>\
  662. <body onload="on_load();">\
  663. <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">\
  664. <div class="hover_content">'+fixMetacriticURLs(html)+'</div>\
  665. </div>\
  666. </body>\
  667. </html>');
  668. var frame = $("<iframe></iframe>").appendTo(div);
  669. frame.attr("id","mciframe123");
  670. frame.attr("src",framesrc);
  671. frame.attr("scrolling","auto");
  672. frame.css({
  673. width: 400,
  674. height: 170,
  675. border: "none"
  676. });
  677. window.setTimeout(function() {
  678. if(!frame_status) { // Loading frame content failed.
  679. // Directly inject the html without an iframe (this may break the site or the metacritic)
  680. console.log("Loading iframe content failed. Injecting directly.");
  681. $("head").append("<style>"+css+"</style>");
  682. 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">\
  683. <div class="hover_content">'+fixMetacriticURLs(html)+'</div>\
  684. </div>');
  685. frame.replaceWith(noframe);
  686. }
  687. },2000);
  688. functions.parent();
  689. var sub = $("<div></div>").appendTo(div);
  690. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleTimeString()+" "+time.toLocaleDateString()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  691. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("https://www.","@"))+'</a>').appendTo(sub);
  692. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px; padding-left:5px;">&#10062;</span>').appendTo(sub).click(function() {
  693. document.body.removeChild(this.parentNode.parentNode);
  694. });
  695. $('<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() {
  696. var docurl = document.location.href;
  697. var metaurl = $(this).data("url");
  698. addToMap(docurl, metaurl).then(function(r) {
  699. balloonAlert("Thanks for your submission!\n\nSaved as a correct entry.\n\n"+r[0]+"\n"+r[1], 6000, "Success");
  700. });
  701. });
  702. $('<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() {
  703. if(!confirm("This is NOT the correct entry!\n\nAdd to blacklist?")) return;
  704. var docurl = document.location.href;
  705. var metaurl = $(this).data("url");
  706. addToBlacklist(docurl,metaurl).then(function(r) {
  707. balloonAlert("Thanks for your submission!\n\nSaved to blacklist.\n\n"+r[0]+"\n"+r[1], 6000, "Success");
  708. });
  709.  
  710. // Open search
  711. metacritic_searchcontainer(null, current.searchTerm);
  712. metacritic_search(null, current.searchTerm);
  713. });
  714.  
  715. },
  716. // On error i.e. no result on metacritic.com
  717. async function(html, time) {
  718. // Make search available
  719. metacritic_waitForHotkeys();
  720. var handleresponse = await async function(response) {
  721. var data;
  722. var multiple = false;
  723. try {
  724. data = JSON.parse(response.responseText);
  725. } catch(e) {
  726. console.log("Error in JSON 05: search_term="+current.searchTerm);
  727. console.log(e);
  728. }
  729. if(data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  730. // Remove data with wrong type
  731. data.autoComplete = data.autoComplete.results;
  732. var newdata = [];
  733. data.autoComplete.forEach(function(result) {
  734. if(metacritic2searchType(result.refType) == current.type) {
  735. newdata.push(result);
  736. }
  737. });
  738. data.autoComplete = newdata;
  739. if(data.autoComplete.length == 0) {
  740. // No results
  741. console.log("No results (after filtering by type) for search_term="+current.searchTerm);
  742. } else if(data.autoComplete.length == 1) {
  743. // One result, let's show it
  744. if(! await isBlacklisted(absoluteMetaURL(data.autoComplete[0].url))) {
  745. metacritic_showHoverInfo(absoluteMetaURL(data.autoComplete[0].url));
  746. return;
  747. }
  748. } else {
  749. // More than one result
  750. multiple = true;
  751. console.log("Multiple results for search_term="+current.searchTerm);
  752. var exactMatches = [];
  753. data.autoComplete.forEach(function(result,i) { // Try to find the correct result by matching the search term to exactly one movie title
  754. if(current.searchTerm == result.name) {
  755. exactMatches.push(result);
  756. }
  757. });
  758. if(exactMatches.length == 1) {
  759. // Only one exact match, let's show it
  760. console.log("Only one exact match for search_term="+current.searchTerm);
  761. if(! await isBlacklisted(absoluteMetaURL(exactMatches[0].url))) {
  762. metacritic_showHoverInfo(absoluteMetaURL(exactMatches[0].url));
  763. return;
  764. }
  765. }
  766. }
  767. } else {
  768. console.log("No results (at all) for search_term="+current.searchTerm);
  769. }
  770. // HERE: multiple results or no result. The user may type "meta" now
  771. if(multiple) {
  772. balloonAlert("Multiple metacritic results. Type &#34;meta&#34; for manual search.", 10000, false, {bottom: 5, top:"auto", maxWidth: 400, paddingRight: 5}, metacritic_searchcontainer);
  773. }
  774. };
  775. var cache = JSON.parse(await GM.getValue("autosearchcache","{}"));
  776. for(var prop in cache) {
  777. // Delete cached values, that are older than 2 hours
  778. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  779. delete cache[prop];
  780. }
  781. }
  782. if(current.type == "music") {
  783. current.searchTerm = current.data[0];
  784. } else {
  785. current.searchTerm = current.data.join(" ");
  786. }
  787. if(current.searchTerm in cache) {
  788. handleresponse(cache[current.searchTerm], true);
  789. } else {
  790. GM.xmlHttpRequest({
  791. method: "POST",
  792. url: baseURL_autosearch,
  793. data: "search_term="+encodeURIComponent(current.searchTerm)+"&image_size=98&search_each=1&sort_type=popular",
  794. headers: {
  795. "Referer" : url,
  796. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  797. "Host" : "www.metacritic.com",
  798. "User-Agent" : "MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0",
  799. "X-Requested-With" : "XMLHttpRequest"
  800. },
  801. onload: function(response) {
  802. response = {
  803. time : (new Date()).toJSON(),
  804. responseText : response.responseText,
  805. };
  806. cache[current.searchTerm] = response;
  807. GM.setValue("autosearchcache",JSON.stringify(cache));
  808. handleresponse(response, false);
  809. }
  810. });
  811. }
  812. });
  813. }
  814.  
  815. function metacritic_waitForHotkeys() {
  816. listenForHotkeys("meta",metacritic_searchcontainer);
  817. }
  818.  
  819. function metacritic_searchcontainer(ev, query) {
  820. if(!query) {
  821. if(current.type == "music") {
  822. query = current.data[0];
  823. } else {
  824. query = current.data.join(" ");
  825. }
  826. }
  827. $("#mcdiv123").remove();
  828. var div = $('<div id="mcdiv123"></div>').appendTo(document.body);
  829. div.css({
  830. position:"fixed",
  831. bottom :0,
  832. left: 0,
  833. minWidth: 300,
  834. maxHeight: "80%",
  835. maxWidth: 640,
  836. overflow:"auto",
  837. backgroundColor: "#fff",
  838. border: "2px solid #bbb",
  839. borderRadius:" 6px",
  840. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  841. color: "#000",
  842. padding:" 3px",
  843. zIndex: "5010001",
  844. });
  845. var query = $('<input type="text" size="60" id="mcisearchquery" style="background:white;color:black;">').appendTo(div).focus().val(query).on('keypress', function(e) {
  846. var code = e.keyCode || e.which;
  847. if(code == 13) { // Enter key
  848. metacritic_search.call(this,e);
  849. }
  850. });
  851. $('<button id="mcisearchbutton" style="background:silver;color:black;">').text("Search").appendTo(div).click(metacritic_search);
  852. }
  853.  
  854.  
  855. function metacritic_search(ev, query) {
  856. if(!query) { // Use values from search form
  857. query = $("#mcisearchquery").val();
  858. }
  859. var type = searchType2metacritic(current.type);
  860.  
  861. var style = document.createElement('style');
  862. style.type = 'text/css';
  863. style.innerHTML = CSS;
  864. document.head.appendChild(style);
  865.  
  866. var div = $("#mcdiv123");
  867. var loader = $('<div style="width:20px; height:20px;" class="grespinner"></div>').appendTo($("#mcisearchbutton"));
  868. var url = baseURL_search.replace("{type}",encodeURIComponent(type)).replace("{query}",encodeURIComponent(query));
  869.  
  870. metacritic_searchResults(url,
  871. // On success
  872. function(results, time) {
  873. loader.remove();
  874. var accept = function(ev) {
  875. var a = $(this.parentNode).find("a[href*='metacritic.com']");
  876. var metaurl = a.attr("href");
  877. var docurl = document.location.href;
  878.  
  879. addToMap(docurl,metaurl).then(function() {
  880. metacritic_showHoverInfo(metaurl);
  881. });
  882. };
  883. var denyAll = function(ev) {
  884. var urls = [];
  885. var docurl = document.location.href;
  886. $("#mcdiv123searchresults").find("div.result a[href*='metacritic.com']").each(function() {
  887. addToBlacklist(docurl, this.href);
  888. });
  889. };
  890. var resultdiv = $("#mcdiv123searchresults").length?$("#mcdiv123searchresults").html(""):$('<div id="mcdiv123searchresults"></div>').css("max-width","95%").appendTo(div);
  891. results.forEach(function(html) {
  892. var singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html)+'<div style="clear:left"></div>').appendTo(resultdiv);
  893. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept);
  894. });
  895. resultdiv.find(".metascore_w.album").removeClass("album"); // Remove some classes
  896. var sub = $("<div></div>").appendTo(div);
  897. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleFormat()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  898. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("https://www.","@"))+'</a>').appendTo(sub);
  899. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function() {
  900. document.body.removeChild(this.parentNode.parentNode);
  901. });
  902. $('<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()});
  903. },
  904. // On error i.e. no results
  905. function(results, time) {
  906. loader.remove();
  907. var resultdiv = $("#mcdiv123searchresults").length?$("#mcdiv123searchresults").html(""):$('<div id="mcdiv123searchresults"></div>').appendTo(div);
  908. resultdiv.html("No search results.");
  909. var sub = $("<div></div>").appendTo(div);
  910. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleFormat()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  911. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("https://www.","@"))+'</a>').appendTo(sub);
  912. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function() {
  913. document.body.removeChild(this.parentNode.parentNode);
  914. });
  915. }
  916. );
  917. }
  918.  
  919. var current = {
  920. url : null,
  921. type : null,
  922. data : null, // Array of raw search keys
  923. searchTerm : null
  924. };
  925.  
  926.  
  927. async function showURL(url) {
  928. if(! await isBlacklisted(url)) {
  929. var docurl = document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search;
  930. docurl = filterUniversalUrl(docurl);
  931. metacritic_showHoverInfo(url, docurl);
  932. } else {
  933. console.log(url +" is blacklisted!");
  934. }
  935. }
  936.  
  937.  
  938. var metacritic = {
  939. "mapped" : function metacritic_mapped(url, type) {
  940. // url was in the map/whitelist
  941. current.data = [url]
  942. current.url = url;
  943. current.type = type;
  944. current.searchTerm = url;
  945. showURL(url);
  946. },
  947. "music" : function metacritic_music(artistname, albumname) {
  948. current.data = [albumname.trim(),artistname.trim()]
  949. artistname = name2metacritic(artistname);
  950. albumname = albumname.replace("&"," ");
  951. albumname = name2metacritic(albumname);
  952. var url = baseURL_music + albumname + "/" + artistname;
  953. current.url = url;
  954. current.type = "music";
  955. current.searchTerm = albumname + "/" + artistname;
  956. showURL(url);
  957. },
  958. "movie" : function metacritic_movie(moviename) {
  959. current.data = [moviename.trim()]
  960. moviename = name2metacritic(moviename);
  961. var url = baseURL_movie + moviename;
  962. current.url = url;
  963. current.type = "movie";
  964. current.searchTerm = moviename;
  965. showURL(url);
  966. },
  967. "tv" : function metacritic_tv(seriesname) {
  968. current.data = [seriesname.trim()]
  969. seriesname = name2metacritic(seriesname);
  970. var url = baseURL_tv + seriesname;
  971. current.url = url;
  972. current.type = "tv";
  973. current.searchTerm = seriesname;
  974. showURL(url);
  975. },
  976. "pcgame" : function metacritic_pcgame(gamename) {
  977. current.data = [gamename.trim()]
  978. gamename = name2metacritic(gamename);
  979. var url = baseURL_pcgame + gamename;
  980. current.url = url;
  981. current.type = "pcgame";
  982. current.searchTerm = gamename;
  983. showURL(url);
  984. },
  985. "ps4game" : function metacritic_ps4game(gamename) {
  986. current.data = [gamename.trim()]
  987. gamename = name2metacritic(gamename);
  988. var url = baseURL_ps4 + gamename;
  989. current.url = url;
  990. current.type = "ps4game";
  991. current.searchTerm = gamename;
  992. showURL(url);
  993. },
  994. "xonegame" : function metacritic_xonegame(gamename) {
  995. current.data = [gamename.trim()]
  996. gamename = name2metacritic(gamename);
  997. var url = baseURL_xone + gamename;
  998. current.url = url;
  999. current.type = "xonegame";
  1000. current.searchTerm = gamename;
  1001. showURL(url);
  1002. }
  1003. };
  1004.  
  1005.  
  1006. var Always = () => true;
  1007. var sites = {
  1008. 'bandcamp' : {
  1009. host : ["bandcamp.com"],
  1010. condition : function() {
  1011. return unsafeWindow.TralbumData
  1012. },
  1013. products : [{
  1014. condition : Always,
  1015. type : "music",
  1016. data : () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1017. }]
  1018. },
  1019. 'itunes' : {
  1020. host : ["itunes.apple.com"],
  1021. condition : Always,
  1022. products : [{
  1023. condition : () => ~document.location.href.indexOf("/album/") ,
  1024. type : "music",
  1025. data : () => [document.querySelector("h2.t-hero-subheadline").textContent.trim(), document.querySelector("h1.t-hero-headline").textContent.trim()]
  1026. }]
  1027. },
  1028. 'googleplay' : {
  1029. host : ["play.google.com"],
  1030. condition : Always,
  1031. products : [
  1032. {
  1033. condition : () => ~document.location.href.indexOf("/album/"),
  1034. type : "music",
  1035. data : () => [document.querySelector("*[itemprop=byArtist] a").textContent, document.querySelector("*[itemprop=name]").textContent]
  1036. },
  1037. {
  1038. condition : () => ~document.location.href.indexOf("/movies/details/"),
  1039. type : "movie",
  1040. data : () => document.querySelector("*[itemprop=name]").textContent
  1041. }
  1042. ]
  1043. },
  1044. 'imdb' : {
  1045. host : ["imdb.com"],
  1046. condition : Always,
  1047. products : [
  1048. {
  1049. condition : function() {
  1050. var e = document.querySelector("meta[property='og:type']");
  1051. if(e) {
  1052. return e.content == "video.movie"
  1053. }
  1054. return false;
  1055. },
  1056. type : "movie",
  1057. data : function() {
  1058. if(document.querySelector('script[type="application/ld+json"]')) {
  1059. var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
  1060. return jsonld["name"];
  1061. } else if(document.querySelector("h1[itemprop=name]")) { // Movie homepage (New design 2015-12)
  1062. return document.querySelector("h1[itemprop=name]").firstChild.textContent.trim();
  1063. } else if(document.querySelector("*[itemprop=name] a") && document.querySelector("*[itemprop=name] a").firstChild.data) { // Subpage of a move
  1064. return document.querySelector("*[itemprop=name] a").firstChild.data.trim();
  1065. } else if(document.querySelector(".title-extra[itemprop=name]")) { // Movie homepage: sub-/alternative-/original title
  1066. return document.querySelector(".title-extra[itemprop=name]").firstChild.textContent.replace(/\"/g,"").trim();
  1067. } else { // Movie homepage (old design)
  1068. return document.querySelector("*[itemprop=name]").firstChild.textContent.trim();
  1069. }
  1070. }
  1071. },
  1072. {
  1073. condition : function() {
  1074. var e = document.querySelector("meta[property='og:type']");
  1075. if(e) {
  1076. return e.content == "video.tv_show"
  1077. }
  1078. return false;
  1079. },
  1080. type : "tv",
  1081. data : function() {
  1082. var year = null;
  1083. if(document.querySelector("*[itemprop=name]")) {
  1084. return document.querySelector("*[itemprop=name]").textContent;
  1085. } else {
  1086. var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
  1087. return jsonld["name"];
  1088. }
  1089. }
  1090. }
  1091. ]
  1092. },
  1093. 'steam' : {
  1094. host : ["store.steampowered.com"],
  1095. condition : () => document.querySelector("*[itemprop=name]"),
  1096. products : [{
  1097. condition : Always,
  1098. type : "pcgame",
  1099. data : () => document.querySelector("*[itemprop=name]").textContent
  1100. }]
  1101. },
  1102. 'tv.com' : {
  1103. host : ["www.tv.com"],
  1104. condition : () => document.querySelector("meta[property='og:type']"),
  1105. products : [{
  1106. condition : () => document.querySelector("meta[property='og:type']").content == "tv_show" && document.querySelector("h1[data-name]"),
  1107. type : "tv",
  1108. data : () => document.querySelector("h1[data-name]").dataset.name
  1109. }]
  1110. },
  1111. 'rottentomatoes' : {
  1112. host : ["www.rottentomatoes.com"],
  1113. condition : Always,
  1114. products : [{
  1115. condition : () => document.location.pathname.startsWith("/m/"),
  1116. type : "movie",
  1117. data : () => document.querySelector("h1").firstChild.textContent
  1118. },
  1119. {
  1120. condition : () => document.location.pathname.startsWith("/tv/") ,
  1121. type : "tv",
  1122. data : () => unsafeWindow.BK.TvSeriesTitle
  1123. }
  1124. ]
  1125. },
  1126. 'serienjunkies' : {
  1127. host : ["www.serienjunkies.de"],
  1128. condition : Always,
  1129. products : [{
  1130. condition : () => Always,
  1131. type : "tv",
  1132. data : () => parseLDJSON((j) => (j["@type"] == "TVSeries"), "name")
  1133. }]
  1134. },
  1135. 'gamespot' : {
  1136. host : ["gamespot.com"],
  1137. condition : () => document.querySelector("[itemprop=device]"),
  1138. products : [
  1139. {
  1140. condition : () => ~$("[itemprop=device]").text().indexOf("PC"),
  1141. type : "pcgame",
  1142. data : () => parseLDJSON((j) => (j["@type"] == "VideoGame"), "name")
  1143. },
  1144. {
  1145. condition : () => ~$("[itemprop=device]").text().indexOf("PS4"),
  1146. type : "ps4game",
  1147. data : () => parseLDJSON((j) => (j["@type"] == "VideoGame"), "name")
  1148. },
  1149. {
  1150. condition : () => ~$("[itemprop=device]").text().indexOf("XONE"),
  1151. type : "xonegame",
  1152. data : () => parseLDJSON((j) => (j["@type"] == "VideoGame"), "name")
  1153. }
  1154. ]
  1155. },
  1156. 'amazon' : {
  1157. host : ["amazon."],
  1158. condition : Always,
  1159. products : [
  1160. {
  1161. condition : function() {
  1162. try {
  1163. if(document.querySelector(".nav-categ-image").alt.toLowerCase().indexOf("musi") != -1) {
  1164. return true;
  1165. }
  1166. } catch(e) {}
  1167. var music = ["Music","Musique","Musik","Música","Musica","音楽"];
  1168. return music.some(function(s) {
  1169. if(~document.title.indexOf(s)) {
  1170. return true;
  1171. } else {
  1172. return false;
  1173. }
  1174. });
  1175. },
  1176. type : "music",
  1177. data : function() {
  1178. var artist = document.querySelector("#ProductInfoArtistLink").textContent.trim();
  1179. var title = document.querySelector("#title_feature_div").textContent.trim();
  1180. title = title.replace(/\[([^\]]*)\]/g,""); // Remove [brackets] and their content
  1181. return [artist, title];
  1182. }
  1183. },
  1184. {
  1185. condition : () => (document.getElementById("aiv-content-title") && document.getElementsByClassName("season-single-dark").length),
  1186. type : "tv",
  1187. data : () => document.getElementById("aiv-content-title").firstChild.data.trim()
  1188. },
  1189. {
  1190. condition : () => document.getElementById("aiv-content-title"),
  1191. type : "movie",
  1192. data : () => document.getElementById("aiv-content-title").firstChild.data.trim()
  1193. }
  1194. ]
  1195. },
  1196. 'BoxOfficeMojo' : {
  1197. host : ["boxofficemojo.com"],
  1198. condition : () => ~document.location.search.indexOf("id="),
  1199. products : [{
  1200. condition : () => document.querySelector("#body table:nth-child(2) tr:first-child b"),
  1201. type : "movie",
  1202. data : () => document.querySelector("#body table:nth-child(2) tr:first-child b").firstChild.data
  1203. }]
  1204. },
  1205. 'AllMovie' : {
  1206. host : ["allmovie.com"],
  1207. condition : () => document.querySelector("h2[itemprop=name].movie-title"),
  1208. products : [{
  1209. condition : () => document.querySelector("h2[itemprop=name].movie-title"),
  1210. type : "movie",
  1211. data : () => document.querySelector("h2[itemprop=name].movie-title").firstChild.data.trim()
  1212. }]
  1213. },
  1214. 'en.wikipedia' : {
  1215. host : ["en.wikipedia.org"],
  1216. condition : Always,
  1217. products : [{
  1218. condition : function() {
  1219. if(!document.querySelector(".infobox .summary")) {
  1220. return false;
  1221. }
  1222. var r = /\d\d\d\d films/;
  1223. return $("#catlinks a").filter((i,e) => e.firstChild.data.match(r)).length;
  1224. },
  1225. type : "movie",
  1226. data : () => document.querySelector(".infobox .summary").firstChild.data
  1227. },
  1228. {
  1229. condition : function() {
  1230. if(!document.querySelector(".infobox .summary")) {
  1231. return false;
  1232. }
  1233. var r = /television series/;
  1234. return $("#catlinks a").filter((i,e) => e.firstChild.data.match(r)).length;
  1235. },
  1236. type : "tv",
  1237. data : () => document.querySelector(".infobox .summary").firstChild.data
  1238. }]
  1239. },
  1240. 'movies.com' : {
  1241. host : ["movies.com"],
  1242. condition : () => document.querySelector("meta[property='og:title']"),
  1243. products : [{
  1244. condition : Always,
  1245. type : "movie",
  1246. data : () => document.querySelector("meta[property='og:title']").content
  1247. }]
  1248. },
  1249. 'themoviedb' : {
  1250. host : ["themoviedb.org"],
  1251. condition : () => document.querySelector("meta[property='og:type']"),
  1252. products : [{
  1253. condition : () => document.querySelector("meta[property='og:type']").content == "movie",
  1254. type : "movie",
  1255. data : () => document.querySelector("meta[property='og:title']").content
  1256. },
  1257. {
  1258. condition : () => document.querySelector("meta[property='og:type']").content == "tv_series",
  1259. type : "tv",
  1260. data : () => document.querySelector("meta[property='og:title']").content
  1261. }]
  1262. },
  1263. 'letterboxd' : {
  1264. host : ["letterboxd.com"],
  1265. condition : () => unsafeWindow.filmData && "name" in unsafeWindow.filmData,
  1266. products : [{
  1267. condition : Always,
  1268. type : "movie",
  1269. data : () => unsafeWindow.filmData.name
  1270. }]
  1271. },
  1272. 'TVmaze' : {
  1273. host : ["tvmaze.com"],
  1274. condition : () => document.querySelector("h1"),
  1275. products : [{
  1276. condition : Always,
  1277. type : "tv",
  1278. data : () => document.querySelector("h1").firstChild.data
  1279. }]
  1280. },
  1281. 'TVGuide' : {
  1282. host : ["tvguide.com"],
  1283. condition : Always,
  1284. products : [{
  1285. condition : () => document.location.pathname.startsWith("/tvshows/"),
  1286. type : "tv",
  1287. data : function() {
  1288. if(document.querySelector("meta[itemprop=name]")) {
  1289. return document.querySelector("meta[itemprop=name]").content;
  1290. } else {
  1291. return document.querySelector("meta[property='og:title']").content.split("|")[0];
  1292. }
  1293. }
  1294. }]
  1295. },
  1296. 'followshows' : {
  1297. host : ["followshows.com"],
  1298. condition : Always,
  1299. products : [{
  1300. condition : () => document.querySelector("meta[property='og:type']").content == "video.tv_show",
  1301. type : "tv",
  1302. data : () => document.querySelector("meta[property='og:title']").content
  1303. }]
  1304. },
  1305. 'TheTVDB' : {
  1306. host : ["thetvdb.com"],
  1307. condition : Always,
  1308. products : [{
  1309. condition : () => document.location.pathname.startsWith("/series/") || ~document.location.search.indexOf("tab=series"),
  1310. type : "tv",
  1311. data : () => document.getElementById("series_title").firstChild.data.trim()
  1312. }]
  1313. },
  1314. 'ConsequenceOfSound' : {
  1315. host : ["consequenceofsound.net"],
  1316. condition : () => document.querySelector("#main-content .review-summary"),
  1317. products : [{
  1318. condition : () => document.querySelector("#main-content .review-summary .artwork"),
  1319. type : "music",
  1320. data : function() {
  1321. var d = document.querySelector("#main-content .review-summary")
  1322. var artist = d.querySelector("a[href*='/artist/']").innerText.toLowerCase();
  1323. var album = d.querySelector("img").alt.toLowerCase().replace(artist,"").replace("-","").trim();
  1324. return [artist, album];
  1325. }
  1326. }]
  1327. },
  1328. 'Pitchfork' : {
  1329. host : ["pitchfork.com"],
  1330. condition : () => ~document.location.href.indexOf("/reviews/albums/"),
  1331. products : [{
  1332. condition : () => document.querySelector(".single-album-tombstone"),
  1333. type : "music",
  1334. data : function() {
  1335. var artist, album;
  1336. if(document.querySelector(".single-album-tombstone .artists")) {
  1337. artist = document.querySelector(".single-album-tombstone .artists").innerText.trim();
  1338. } else if(document.querySelector(".single-album-tombstone .artist-list")) {
  1339. artist = document.querySelector(".single-album-tombstone .artist-list").innerText.trim();
  1340. }
  1341. if(document.querySelector(".single-album-tombstone h1.review-title")) {
  1342. album = document.querySelector(".single-album-tombstone h1.review-title").innerText.trim();
  1343. } else if(document.querySelector(".single-album-tombstone h1")) {
  1344. album = document.querySelector(".single-album-tombstone h1").innerText.trim();
  1345. }
  1346. return [artist, album];
  1347. }
  1348. }]
  1349. },
  1350. 'Last.fm' : {
  1351. host : ["last.fm"],
  1352. condition : () => document.querySelector("*[data-page-resource-type]") && document.querySelector("*[data-page-resource-type]").dataset.pageResourceType == "album",
  1353. products : [{
  1354. condition : () => document.querySelector("*[data-page-resource-type]").dataset.pageResourceName,
  1355. type : "music",
  1356. data : function() {
  1357. var artist = document.querySelector("*[data-page-resource-type]").dataset.pageResourceArtistName;
  1358. var album = document.querySelector("*[data-page-resource-type]").dataset.pageResourceName;
  1359. return [artist, album];
  1360. }
  1361. }]
  1362. },
  1363. 'TVNfo' : {
  1364. host : ["tvnfo.com"],
  1365. condition : () => document.querySelector("#tvsign"),
  1366. products : [{
  1367. condition : Always,
  1368. type : "tv",
  1369. data : () => document.querySelector(".heading h1").textContent.trim()
  1370. }]
  1371. },
  1372. 'rateyourmusic' : {
  1373. host : ["rateyourmusic.com"],
  1374. condition : () => document.querySelector("meta[property='og:type']"),
  1375. products : [{
  1376. condition : () => document.querySelector("meta[property='og:type']").content == "music.album",
  1377. type : "music",
  1378. data : function() {
  1379. var artist = document.querySelector(".section_main_info .artist").innerText.trim();
  1380. var album = document.querySelector(".section_main_info .album_title").innerText.trim();
  1381. return [artist, album];
  1382. }
  1383. }]
  1384. },
  1385. 'spotify_webplayer' : {
  1386. host : ["open.spotify.com"],
  1387. condition : () => Always,
  1388. products : [{
  1389. condition : () => document.querySelector("#main .main-view-container .content.album"),
  1390. type : "music",
  1391. data : function() {
  1392. var artist = document.querySelector("#main .media-bd div a[href*='artist']").textContent;
  1393. var album = document.querySelector("#main .media-bd h2").textContent;
  1394. return [artist, album];
  1395. }
  1396. },
  1397. {
  1398. condition : () => document.location.pathname.startsWith("/album/") && document.querySelector("meta[property='og:type']").content == "music.album",
  1399. type : "music",
  1400. data : function() {
  1401. var artist = "";
  1402. var album = document.querySelector("meta[property='og:title']").content;
  1403. return [artist, album];
  1404. }
  1405. }]
  1406. },
  1407. 'spotify' : {
  1408. host : ["play.spotify.com"],
  1409. condition : () => Always,
  1410. products : [{
  1411. condition : () => document.location.pathname.startsWith("/album/"),
  1412. type : "music",
  1413. data : function() {
  1414. var artist = document.querySelector(".context_landing p.secondary-title").textContent;
  1415. var album = document.querySelector(".context_landing p.primary-title").textContent;
  1416. return [artist, album];
  1417. }
  1418. }]
  1419. },
  1420. };
  1421.  
  1422.  
  1423. async function main() {
  1424.  
  1425. var map = false;
  1426.  
  1427. for(var name in sites) {
  1428. var site = sites[name];
  1429. if(site.host.some(function(e) {return ~this.indexOf(e)}, document.location.hostname) && site.condition()) {
  1430. for(var i = 0; i < site.products.length; i++) {
  1431. if(site.products[i].condition()) {
  1432. // Check map for a match
  1433. if(map === false) {
  1434. map = JSON.parse(await GM.getValue("map","{}"));
  1435. }
  1436. var docurl = document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search;
  1437. docurl = filterUniversalUrl(docurl);
  1438. if(docurl in map) {
  1439. // Found in map, show result
  1440. var metaurl = map[docurl];
  1441. metacritic["mapped"].apply(undefined, [absoluteMetaURL(metaurl), site.products[i].type]);
  1442. break;
  1443. }
  1444. // Try to retrieve item name from page
  1445. var data;
  1446. try {
  1447. data = site.products[i].data();
  1448. } catch(e) {
  1449. data = false;
  1450. console.log(e);
  1451. }
  1452. if(data) {
  1453. metacritic[site.products[i].type].apply(undefined, Array.isArray(data)?data:[data]);
  1454. }
  1455. break;
  1456. }
  1457. }
  1458. break;
  1459. }
  1460. }
  1461. }
  1462.  
  1463.  
  1464.  
  1465.  
  1466. (async function() {
  1467.  
  1468. await main();
  1469. var lastLoc = document.location.href;
  1470. var lastContent = document.body.innerText;
  1471. var lastCounter = 0;
  1472. function newpage() {
  1473. if(lastContent == document.body.innerText && lastCounter < 15) {
  1474. window.setTimeout(newpage, 500);
  1475. lastCounter++;
  1476. } else {
  1477. lastCounter = 0;
  1478. main();
  1479. }
  1480. }
  1481. window.setInterval(function() {
  1482. if(document.location.href != lastLoc) {
  1483. lastLoc = document.location.href;
  1484. $("#mcdiv123").remove();
  1485. window.setTimeout(newpage,1000);
  1486. }
  1487. },500);
  1488.  
  1489. })();