Itch.io Web Integration

Shows if an Itch.io link has been claimed or not

当前为 2020-06-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Itch.io Web Integration
  3. // @namespace Lex@GreasyFork
  4. // @match *://*/*
  5. // @grant GM_xmlhttpRequest
  6. // @grant GM_getValue
  7. // @grant GM_setValue
  8. // @version 0.1.8.5
  9. // @author Lex
  10. // @description Shows if an Itch.io link has been claimed or not
  11. // @connect itch.io
  12. // ==/UserScript==
  13.  
  14. (function(){
  15. 'use strict';
  16.  
  17. const CACHE_VERSION_KEY = "CacheVersion";
  18. const INVALIDATION_TIME = 5*60*60*1000; // 5 hour cache time
  19. const ITCH_GAME_CACHE_KEY = 'ItchGameCache';
  20. var ItchGameCache;
  21. // Promise wrapper for GM_xmlhttpRequest
  22. const Request = details => new Promise((resolve, reject) => {
  23. details.onerror = details.ontimeout = reject;
  24. details.onload = resolve;
  25. GM_xmlhttpRequest(details);
  26. });
  27. function versionCacheInvalidator() {
  28. const sVersion = v => {
  29. if (typeof v !== 'string' || !v.match(/\d+\.\d+/)) return 0;
  30. return parseFloat(v.match(/\d+\.\d+/)[0]);
  31. }
  32. const prev = sVersion(GM_getValue(CACHE_VERSION_KEY, '0.0'));
  33. if (prev < 0.1) {
  34. console.log(`${GM_info.script.version} > ${prev}`);
  35. console.log(`New minor version of ${GM_info.script.name} detected. Invalidating cache.`)
  36. _clearItchCache();
  37. }
  38. GM_setValue(CACHE_VERSION_KEY, GM_info.script.version);
  39. }
  40. function _clearItchCache() {
  41. ItchGameCache = {};
  42. _saveItchCache();
  43. }
  44. function loadItchCache() {
  45. ItchGameCache = JSON.parse(GM_getValue(ITCH_GAME_CACHE_KEY, '{}'));
  46. }
  47. function _saveItchCache() {
  48. if (ItchGameCache === undefined) return;
  49. GM_setValue(ITCH_GAME_CACHE_KEY, JSON.stringify(ItchGameCache));
  50. }
  51. function setItchGameCache(key, game) {
  52. loadItchCache(); // refresh our cache in case another tab has edited it
  53. ItchGameCache[key] = game;
  54. _saveItchCache();
  55. }
  56. function deleteItchGameCache(key) {
  57. if (key === undefined) return;
  58. loadItchCache();
  59. delete ItchGameCache[key];
  60. _saveItchCache();
  61. }
  62. function getItchGameCache(link) {
  63. if (!ItchGameCache) loadItchCache();
  64. if (Object.prototype.hasOwnProperty.call(ItchGameCache, link)) {
  65. return ItchGameCache[link];
  66. }
  67. return null;
  68. }
  69. async function claimGame(url) {
  70. const parser = new DOMParser();
  71. const purchase_url = url + "/purchase";
  72. console.log("Getting purchase page: " + purchase_url);
  73. const purchase_resp = await Request({method: "GET", url: purchase_url});
  74. const purchase_dom = parser.parseFromString(purchase_resp.responseText, 'text/html');
  75. const download_csrf_token = purchase_dom.querySelector("form.form").csrf_token.value;
  76. const download_url_resp = await Request({
  77. method: "POST",
  78. url: url + "/download_url",
  79. headers: {
  80. "Content-Type": "application/x-www-form-urlencoded"
  81. },
  82. data: 'csrf_token='+encodeURIComponent(download_csrf_token)
  83. });
  84. const downloadUrl = JSON.parse(download_url_resp.responseText).url;
  85. console.log("Received download url: " + downloadUrl);
  86.  
  87. const download_resp = await Request({method: "GET", url: downloadUrl});
  88. const dom = parser.parseFromString(download_resp.responseText, 'text/html');
  89. const claimForm = dom.querySelector(".claim_to_download_box form");
  90. const claim_csrf_token = claimForm.csrf_token.value;
  91. const claim_key_url = claimForm.action;
  92.  
  93. console.log("Claiming game using " + claim_key_url);
  94. const claim_key_resp = await Request({
  95. method: "POST",
  96. url: claim_key_url,
  97. headers: {
  98. "Content-Type": "application/x-www-form-urlencoded"
  99. },
  100. data: 'csrf_token='+encodeURIComponent(claim_csrf_token)
  101. });
  102. return /You claimed this/.test(claim_key_resp.responseText);
  103. }
  104. // Parses a DOM into a game object
  105. function parsePage(url, dom) {
  106. // Gets the inner text of an element if it can be found otherwise returns undefined
  107. const txt = query => { const e = dom.querySelector(query); return e && e.innerText.trim(); };
  108. // JSON.parse(document.querySelectorAll(`script[type="application/ld+json"]`)[1].innerText)
  109. const game = {};
  110. game.cachetime = (new Date()).getTime();
  111. game.url = url;
  112. game.title = txt('h1.game_title');
  113. game.isOwned = dom.querySelector(".purchase_banner_inner .key_row .ownership_reason") !== null;
  114. game.isClaimable = [...dom.querySelectorAll(".buy_btn")].find(e => e.innerText == "Download or claim") !== undefined;
  115. game.isFree = [...dom.querySelectorAll("span[itemprop=price]")].find(e => e.innerText === "$0.00 USD") !== undefined;
  116. game.hasPurchase = [...dom.querySelectorAll("span[itemprop=price]")].find(e => e.innerText !== "$0.00 USD") !== undefined;
  117. game.hasFreeDownload = [...dom.querySelectorAll("a.download_btn,a.buy_btn")].find(e => e.innerText == "Download" || e.innerText == "Download Now") !== undefined;
  118. game.hasCommunityCopies = document.querySelector(".reward_footer") !== null;
  119. const copiesBlock = document.querySelector(".remaining_count");
  120. game.communityCopies = copiesBlock && copiesBlock.innerText.match(/\d+/) && copiesBlock.innerText.match(/\d+/)[0];
  121. game.communityCopies = game.communityCopies || 0;
  122. game.original_price = txt("span.original_price");
  123. game.price = txt("span[itemprop=price]");
  124. game.saleRate = txt(".sale_rate");
  125. game.breadcrumbs = txt(".breadcrumbs");
  126. const categoryHeader = [...document.querySelectorAll(".game_info_panel_widget td:first-child")].find(e=>e.innerText === "Category");
  127. if (categoryHeader)
  128. game.category = categoryHeader.nextSibling.innerText;
  129. return game;
  130. }
  131. // Sends an XHR request and parses the results into a game object
  132. async function fetchItchGame(url) {
  133. const response = await Request({method: "GET",
  134. url: url});
  135. if (response.status != 200) {
  136. console.log(`Error ${response.status} fetching page ${url}`);
  137. return null;
  138. }
  139. const parser = new DOMParser();
  140. const dom = parser.parseFromString(response.responseText, 'text/html');
  141. return parsePage(url, dom);
  142. }
  143. // Loads an itch game from cache or fetches the page if needed
  144. async function getItchGame(url) {
  145. let game = getItchGameCache(url);
  146. if (game !== null) {
  147. const isExpired = (new Date()).getTime() - game.cachetime > INVALIDATION_TIME;
  148. // Expiration checking currently disabled
  149. /*if (isExpired) {
  150. game = null;
  151. }*/
  152. }
  153. if (game === null) {
  154. game = await fetchItchGame(url);
  155. if (game !== null)
  156. setItchGameCache(url, game);
  157. }
  158. return game;
  159. }
  160. async function claimClicked(a, game) {
  161. console.log("Attempting to claim " + game.url);
  162. a.innerText += ' ⌛';
  163. a.onclick = null;
  164. const success = await claimGame(game.url);
  165. if (success === true) {
  166. a.style.display = "none";
  167. const ownMark = a.parentElement.firstChild;
  168. ownMark.innerHTML = `<span title="Successfully claimed">✔️</span>`;
  169. deleteItchGameCache(game.url);
  170. } else {
  171. a.innerHTML = `❗ Error`;
  172. }
  173. }
  174. // Appends the isOwned tag to an anchor link
  175. function appendTags(a, game) {
  176. const div = document.createElement("div");
  177. div.style.display = "inline-block";
  178. const span = document.createElement("span");
  179. div.append(span);
  180. span.style = "margin-left: 5px; background:rgb(230,230,230); padding: 2px; border-radius: 2px";
  181. if (game === null) {
  182. span.innerHTML = `<span title="Status unknown. Try refreshing.">❓</span>`;
  183. a.after(div);
  184. return;
  185. }
  186. if (game.isOwned) {
  187. span.innerHTML = `<span title="Game is already claimed on itch.io">✔️</span>`;
  188. } else {
  189. if (!game.isClaimable) {
  190. if (game.hasFreeDownload && !game.hasPurchase) {
  191. span.innerHTML = `<span title="Game is a free download but not claimable">🆓</span>`;
  192. } else if (game.price) {
  193. span.innerHTML = `<span title="🛒 Game costs ${game.price}">🛒</span>`;
  194. } else {
  195. span.innerHTML = `<span title="Status unknown">👽</span>`;
  196. }
  197. } else {
  198. let tooltip = [`Game is claimable but you haven't claimed it.`];
  199. if (game.original_price) tooltip.push(`🛒 Original price: ${game.original_price}`);
  200. if (game.price) tooltip.push(`💸 Current Price: ${game.price}`);
  201. span.innerHTML = `<span title="${tooltip.join(" ")}">❌</span>`;
  202. const claimBtn = document.createElement("span");
  203. claimBtn.style = `margin-left: 2px; padding: 2px; cursor:pointer; background:rgb(220,220,220); border-radius: 5px`;
  204. claimBtn.className = "ClaimButton";
  205. claimBtn.innerText = "🛄 Claim Game";
  206. claimBtn.onclick = function(event) { claimClicked(event.target, game); };
  207. span.after(claimBtn);
  208. }
  209. }
  210. if (game.hasCommunityCopies) {
  211. const communityTag = document.createElement("span");
  212. communityTag.title = `This game has ${game.communityCopies} Community Copies availible.`;
  213. communityTag.innerText = '👪';
  214. span.append(communityTag);
  215. }
  216. if (game.breadcrumbs) {
  217. span.firstChild.title += ' ℹ️ ' + game.breadcrumbs;
  218. if (!a.title)
  219. a.title = game.breadcrumbs;
  220. const tags = {
  221. //"Games": { icon: '🎮', title: "Video game" },
  222. "Tools": { icon: '🛠️', title: "Tool" },
  223. "Game assets": { icon: '🗃️', title: "Game asset" },
  224. "Comics": { icon: '🗨️', title: "Comic" },
  225. "Books": { icon: '📘', title: "Book" },
  226. "Physical games": { icon: '📖', title: "Physical game" },
  227. "Soundtracks": { icon: '🎵', title: "Soundtrack" },
  228. "Game mods": { icon: '⚙️', title: "Game mod" },
  229. }
  230. const category = game.breadcrumbs.split("›")[0].trim();
  231. if (Object.prototype.hasOwnProperty.call(tags, category)) {
  232. const tag = document.createElement("span");
  233. tag.title = tags[category].title;
  234. tag.innerText = tags[category].icon;
  235. span.append(tag);
  236. }
  237. }
  238. a.after(div);
  239. }
  240. function addClickHandler(a) {
  241. a.addEventListener('mouseup', event => {
  242. deleteItchGameCache(event.target.href);
  243. });
  244. }
  245.  
  246. // Handles an itch.io link on a page
  247. async function handleLink(a) {
  248. addClickHandler(a);
  249. const game = await getItchGame(a.href);
  250. appendTags(a, game);
  251. }
  252. function isGameUrl(url) {
  253. return /^https:\/\/[^.]+\.itch\.io\/[^/]+$/.test(url);
  254. }
  255. // Finds all the itch.io links on the current page
  256. function getItchLinks() {
  257. let links = [...document.querySelectorAll("a[href*='itch.io/']")];
  258. links = links.filter(a => isGameUrl(a.href));
  259. links = links.filter(a => !a.classList.contains("return_link"));
  260. links = links.filter(a => { const t = a.textContent.trim(); return t !== "" && t !== "GIF"; });
  261. return links;
  262. }
  263. function handlePage() {
  264. if (isGameUrl(window.location.href)) {
  265. // If we're on an Itch game page, update the cached details
  266. const game = parsePage(window.location.href, document);
  267. setItchGameCache(window.location.href, game);
  268. }
  269. // Try to find any itch links on the page and tag them
  270. const as = getItchLinks();
  271. as.forEach(handleLink);
  272. }
  273. versionCacheInvalidator();
  274. handlePage();
  275. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址