Greasy Fork 还支持 简体中文。

Show Metacritic.com ratings

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

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