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

目前為 2017-12-08 提交的版本,檢視 最新版本

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