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

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