Itch.io Web Integration

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

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

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

QingJ © 2025

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