Itch.io Web Integration

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

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

  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.2
  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. const game = {};
  109. game.cachetime = (new Date()).getTime();
  110. game.url = url;
  111. game.isOwned = dom.querySelector(".purchase_banner_inner .key_row .ownership_reason") !== null;
  112. game.isClaimable = [...dom.querySelectorAll(".buy_btn")].filter(e => e.innerText == "Download or claim").length > 0;
  113. game.isFree = [...dom.querySelectorAll("span[itemprop=price]")].filter(e => e.innerText === "$0.00 USD").length > 0;
  114. game.hasPurchase = [...dom.querySelectorAll("span[itemprop=price]")].filter(e => e.innerText !== "$0.00 USD").length > 0;
  115. game.hasFreeDownload = [...dom.querySelectorAll("a.download_btn,a.buy_btn")].filter(e => e.innerText == "Download" || e.innerText == "Download Now").length > 0;
  116. game.hasCommunityCopies = document.querySelector(".reward_footer") !== null;
  117. const copiesBlock = document.querySelector(".remaining_count");
  118. game.communityCopies = copiesBlock && copiesBlock.innerText.match(/\d+/) && copiesBlock.innerText.match(/\d+/)[0];
  119. game.communityCopies = game.communityCopies || 0;
  120. game.original_price = txt("span.original_price");
  121. game.price = txt("span[itemprop=price]");
  122. game.saleRate = txt(".sale_rate");
  123. game.breadcrumbs = txt(".breadcrumbs");
  124. return game;
  125. }
  126. // Sends an XHR request and parses the results into a game object
  127. async function fetchItchGame(url) {
  128. const response = await Request({method: "GET",
  129. url: url});
  130. if (response.status != 200) {
  131. console.log(`Error ${response.status} fetching page ${url}`);
  132. return null;
  133. }
  134. const parser = new DOMParser();
  135. const dom = parser.parseFromString(response.responseText, 'text/html');
  136. return parsePage(url, dom);
  137. }
  138. // Loads an itch game from cache or fetches the page if needed
  139. async function getItchGame(url) {
  140. let game = getItchGameCache(url);
  141. if (game !== null) {
  142. const isExpired = (new Date()).getTime() - game.cachetime > INVALIDATION_TIME;
  143. // Expiration checking currently disabled
  144. /*if (isExpired) {
  145. game = null;
  146. }*/
  147. }
  148. if (game === null) {
  149. game = await fetchItchGame(url);
  150. if (game !== null)
  151. setItchGameCache(url, game);
  152. }
  153. return game;
  154. }
  155. async function claimClicked(a, game) {
  156. console.log("Attempting to claim " + game.url);
  157. a.innerText += ' ⌛';
  158. a.onclick = null;
  159. const success = await claimGame(game.url);
  160. if (success === true) {
  161. a.style.display = "none";
  162. const ownMark = a.previousElementSibling;
  163. ownMark.innerHTML = `<span title="Successfully claimed">✔️</span>`;
  164. deleteItchGameCache(game.url);
  165. } else {
  166. a.innerHTML = `❗ Error`;
  167. }
  168. }
  169. // Appends the isOwned tag to an anchor link
  170. function appendTags(a, game) {
  171. const div = document.createElement("div");
  172. div.style.display = "inline-block";
  173. const span = document.createElement("span");
  174. div.append(span);
  175. span.style = "margin-left: 5px; background:rgb(230,230,230); padding: 2px; border-radius: 2px";
  176. if (game === null) {
  177. span.innerHTML = `<span title="Status unknown. Try refreshing.">❓</span>`;
  178. } else if (game.isOwned) {
  179. span.innerHTML = `<span title="Game is already claimed on itch.io">✔️</span>`;
  180. } else {
  181. if (!game.isClaimable) {
  182. if (game.hasFreeDownload && !game.hasPurchase) {
  183. span.innerHTML = `<span title="Game is a free download but not claimable">🆓</span>`;
  184. } else if (game.price) {
  185. span.innerHTML = `<span title="🛒 Game costs ${game.price}">🛒</span>`;
  186. } else {
  187. span.innerHTML = `<span title="Status unknown">👽</span>`;
  188. }
  189. } else {
  190. const origPrice = game.original_price ? ` 🛒 Original price: ${game.original_price} 💸 Current Price: ${game.price}` : '';
  191. span.innerHTML = `<span title="Game is claimable but you haven't claimed it.${origPrice}">❌</span>`;
  192. claimBtn = document.createElement("span");
  193. claimBtn.style = `padding: 2px; cursor:pointer; background:rgb(220,220,220); border-radius: 5px`;
  194. claimBtn.className = "ClaimButton";
  195. claimBtn.innerText = "🛄 Claim Game";
  196. claimBtn.onclick = function(event) { claimClicked(event.target, game); };
  197. span.after(claimBtn);
  198. }
  199. }
  200. if (game.hasCommunityCopies) {
  201. const communityTag = document.createElement("span");
  202. communityTag.title = `This game has ${game.communityCopies} Community Copies availible.`;
  203. communityTag.innerText = '👪';
  204. span.append(communityTag);
  205. }
  206. if (game !== null && game.breadcrumbs) {
  207. span.firstChild.title += ' ℹ️ ' + game.breadcrumbs;
  208. if (!a.title)
  209. a.title = game.breadcrumbs;
  210. if (game.breadcrumbs.startsWith("Physical")) {
  211. const physicalTag = document.createElement("span");
  212. physicalTag.title = "Physical game";
  213. physicalTag.innerText = '📖';
  214. span.append(physicalTag);
  215. }
  216. }
  217. a.after(div);
  218. }
  219. function addClickHandler(a) {
  220. a.addEventListener('mouseup', event => {
  221. deleteItchGameCache(event.target.href);
  222. });
  223. }
  224.  
  225. // Handles an itch.io link on a page
  226. async function handleLink(a) {
  227. addClickHandler(a);
  228. const game = await getItchGame(a.href);
  229. appendTags(a, game);
  230. }
  231. function isGameUrl(url) {
  232. return /^https:\/\/[^.]+\.itch\.io\/[^/]+$/.test(url);
  233. }
  234. // Finds all the itch.io links on the current page
  235. function getItchLinks() {
  236. let links = [...document.querySelectorAll("a[href*='itch.io/']")];
  237. links = links.filter(a => isGameUrl(a.href));
  238. links = links.filter(a => !a.classList.contains("return_link"));
  239. links = links.filter(a => { const t = a.textContent.trim(); return t !== "" && t !== "GIF"; });
  240. return links;
  241. }
  242. function handlePage() {
  243. if (isGameUrl(window.location.href)) {
  244. const game = parsePage(window.location.href, document);
  245. setItchGameCache(window.location.href, game);
  246. }
  247. const as = getItchLinks();
  248. as.forEach(handleLink);
  249. }
  250. versionCacheInvalidator();
  251. handlePage();
  252. })();

QingJ © 2025

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