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

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