GitHub 增强

为 GitHub 增加额外的功能。

目前为 2024-09-30 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Plus
  3. // @name:zh-CN GitHub 增强
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.1.3
  6. // @description Enhance GitHub with additional features.
  7. // @description:zh-CN 为 GitHub 增加额外的功能。
  8. // @author PRO-2684
  9. // @match https://github.com/*
  10. // @run-at document-start
  11. // @icon http://github.com/favicon.ico
  12. // @license gpl-3.0
  13. // @grant GM_setValue
  14. // @grant GM_getValue
  15. // @grant GM_deleteValue
  16. // @grant GM_registerMenuCommand
  17. // @grant GM_unregisterMenuCommand
  18. // @grant GM_addValueChangeListener
  19. // @require https://update.greasyfork.org/scripts/470224/1456932/Tampermonkey%20Config.js
  20. // ==/UserScript==
  21.  
  22. (function() {
  23. 'use strict';
  24. /**
  25. * The color used for logging. Matches the color of the GitHub.
  26. * @type {string}
  27. */
  28. const themeColor = "#f78166";
  29. /**
  30. * Regular expression to match the expanded assets URL. (https://github.com/<username>/<repo>/releases/expanded_assets/<version>)
  31. */
  32. const expandedAssetsRegex = /https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/expanded_assets\/([^/]+)/;
  33. /**
  34. * Data about the release. Maps `owner`, `repo` and `version` to the details of a release. Details are `Promise` objects if exist.
  35. */
  36. let releaseData = {};
  37. /**
  38. * Rate limit data for the GitHub API.
  39. * @type {Object}
  40. * @property {number} limit The maximum number of requests that the consumer is permitted to make per hour.
  41. * @property {number} remaining The number of requests remaining in the current rate limit window.
  42. * @property {number} reset The time at which the current rate limit window resets in UTC epoch seconds.
  43. */
  44. let rateLimit = {
  45. limit: -1,
  46. remaining: -1,
  47. reset: -1
  48. };
  49.  
  50. // Configuration
  51. const configDesc = {
  52. $default: {
  53. autoClose: false
  54. },
  55. token: {
  56. name: "Personal Access Token",
  57. title: "Your personal access token for GitHub API, starting with `github_pat_` (used for increasing rate limit)",
  58. type: "str",
  59. },
  60. debug: {
  61. name: "Debug",
  62. title: "Enable debug mode",
  63. type: "bool",
  64. },
  65. releaseUploader: {
  66. name: "Release Uploader",
  67. title: "Show who uploaded a release asset",
  68. type: "bool",
  69. value: true,
  70. },
  71. releaseDownloads: {
  72. name: "Release Downloads",
  73. title: "Show how many times a release asset has been downloaded",
  74. type: "bool",
  75. value: true,
  76. },
  77. releaseHistogram: {
  78. name: "Release Histogram",
  79. title: "Show a histogram of download counts for each release asset",
  80. type: "bool",
  81. },
  82. trackingPrevention: {
  83. name: "Tracking Prevention",
  84. title: "Prevent some tracking by GitHub",
  85. type: "bool",
  86. value: true,
  87. }
  88. };
  89. const config = new GM_config(configDesc);
  90.  
  91. // General functions
  92. const $ = document.querySelector.bind(document);
  93. const $$ = document.querySelectorAll.bind(document);
  94. /**
  95. * Log the given arguments if debug mode is enabled.
  96. * @param {...any} args The arguments to log.
  97. */
  98. function log(...args) {
  99. if (config.get("debug")) console.log("%c[GitHub Plus]%c", `color:${themeColor};`, "color: unset;", ...args);
  100. }
  101. /**
  102. * Warn the given arguments.
  103. * @param {...any} args The arguments to warn.
  104. */
  105. function warn(...args) {
  106. console.warn("%c[GitHub Plus]%c", `color:${themeColor};`, "color: unset;", ...args);
  107. }
  108. /**
  109. * Fetch the given URL with the personal access token, if given. Also updates rate limit.
  110. * @param {string} url The URL to fetch.
  111. * @param {RequestInit} options The options to pass to `fetch`.
  112. * @returns {Promise<Response>} The response from the fetch.
  113. */
  114. async function fetchWithToken(url, options) {
  115. const token = config.get("token");
  116. if (token) {
  117. if (!options) options = {};
  118. if (!options.headers) options.headers = {};
  119. options.headers.accept = "application/vnd.github+json";
  120. options.headers["X-GitHub-Api-Version"] = "2022-11-28";
  121. options.headers.Authorization = `Bearer ${token}`;
  122. }
  123. const r = await fetch(url, options);
  124. // Update rate limit
  125. rateLimit.limit = parseInt(r.headers.get("X-RateLimit-Limit"));
  126. rateLimit.remaining = parseInt(r.headers.get("X-RateLimit-Remaining"));
  127. rateLimit.reset = parseInt(r.headers.get("X-RateLimit-Reset"));
  128. const resetDate = new Date(rateLimit.reset * 1000).toLocaleString();
  129. log(`Rate limit: remaining ${rateLimit.remaining}/${rateLimit.limit}, resets at ${resetDate}`);
  130. if (r.status === 403 || r.status === 429) { // If we get 403 or 429, we've hit the rate limit.
  131. throw new Error(`Rate limit exceeded! Will reset at ${resetDate}`);
  132. } else if (rateLimit.remaining === 0) {
  133. warn(`Rate limit has been exhausted! Will reset at ${resetDate}`);
  134. }
  135. return r;
  136. }
  137.  
  138. // Release-* features
  139. /**
  140. * Get the release data for the given owner, repo and version.
  141. * @param {string} owner The owner of the repository.
  142. * @param {string} repo The repository name.
  143. * @param {string} version The version tag of the release.
  144. * @returns {Promise<Object>} The release data, which resolves to an object mapping download link to details.
  145. */
  146. async function getReleaseData(owner, repo, version) {
  147. if (!releaseData[owner]) releaseData[owner] = {};
  148. if (!releaseData[owner][repo]) releaseData[owner][repo] = {};
  149. if (!releaseData[owner][repo][version]) {
  150. const promise = fetchWithToken(`https://api.github.com/repos/${owner}/${repo}/releases/tags/${version}`).then(
  151. response => response.json()
  152. ).then(data => {
  153. log(`Fetched release data for ${owner}/${repo}@${version}:`, data);
  154. const assets = {};
  155. for (const asset of data.assets) {
  156. assets[asset.browser_download_url] = {
  157. downloads: asset.download_count,
  158. uploader: {
  159. name: asset.uploader.login,
  160. url: asset.uploader.html_url
  161. }
  162. };
  163. }
  164. log(`Processed release data for ${owner}/${repo}@${version}:`, assets);
  165. return assets;
  166. });
  167. releaseData[owner][repo][version] = promise;
  168. }
  169. return releaseData[owner][repo][version];
  170. }
  171. /**
  172. * Create a link to the uploader's profile.
  173. * @param {Object} uploader The uploader information.
  174. * @param {string} uploader.name The name of the uploader.
  175. * @param {string} uploader.url The URL to the uploader's profile.
  176. */
  177. function createUploaderLink(uploader) {
  178. const link = document.createElement("a");
  179. link.textContent = "@" + uploader.name;
  180. link.href = uploader.url;
  181. link.title = `Uploaded by @${uploader.name}`;
  182. link.setAttribute("class", "color-fg-muted text-sm-left flex-auto ml-md-3 nowrap");
  183. return link;
  184. }
  185. /**
  186. * Create a span element with the given download count.
  187. * @param {number} downloads The download count.
  188. */
  189. function createDownloadCount(downloads) {
  190. const downloadCount = document.createElement("span");
  191. downloadCount.textContent = `${downloads} DL`;
  192. downloadCount.title = `${downloads} downloads`;
  193. downloadCount.setAttribute("class", "color-fg-muted text-sm-left flex-shrink-0 flex-grow-0 ml-md-3 nowrap");
  194. return downloadCount;
  195. }
  196. /**
  197. * Show a histogram of the download counts for the given release entry.
  198. * @param {HTMLElement} asset One of the release assets.
  199. * @param {number} value The download count of the asset.
  200. * @param {number} max The maximum download count of all assets.
  201. */
  202. function showHistogram(asset, value, max) {
  203. asset.style.setProperty("--percent", `${value / max * 100}%`);
  204. }
  205. /**
  206. * Adding additional info (download count) to the release entries under the given element.
  207. * @param {HTMLElement} el The element to search for release entries.
  208. * @param {Object} info Additional information about the release (owner, repo, version).
  209. * @param {string} info.owner The owner of the repository.
  210. * @param {string} info.repo The repository name.
  211. * @param {string} info.version The version of the release.
  212. */
  213. async function addAdditionalInfoToRelease(el, info) {
  214. const entries = el.querySelectorAll("ul > li");
  215. const assets = Array.from(entries).filter(asset => asset.querySelector("svg.octicon-package"));
  216. const releaseData = await getReleaseData(info.owner, info.repo, info.version);
  217. if (!releaseData) return;
  218. const maxDownloads = Math.max(0, ...Object.values(releaseData).map(asset => asset.downloads));
  219. assets.forEach(asset => {
  220. const downloadLink = asset.children[0].querySelector("a")?.href;
  221. const statistics = asset.children[1];
  222. const assetInfo = releaseData[downloadLink];
  223. if (!assetInfo) return;
  224. asset.classList.add("ghp-release-asset");
  225. const size = statistics.querySelector("span.flex-auto");
  226. size.classList.remove("flex-auto");
  227. size.classList.add("flex-shrink-0", "flex-grow-0");
  228. if (config.get("releaseDownloads")) {
  229. const downloadCount = createDownloadCount(assetInfo.downloads);
  230. statistics.prepend(downloadCount);
  231. }
  232. if (config.get("releaseUploader")) {
  233. const uploaderLink = createUploaderLink(assetInfo.uploader);
  234. statistics.prepend(uploaderLink);
  235. }
  236. if (config.get("releaseHistogram") && maxDownloads > 0 && assets.length > 1) {
  237. showHistogram(asset, assetInfo.downloads, maxDownloads);
  238. }
  239. });
  240. }
  241. /**
  242. * Handle the `include-fragment-replace` event.
  243. * @param {CustomEvent} event The event object.
  244. */
  245. function onFragmentReplace(event) {
  246. const self = event.target;
  247. const src = self.src;
  248. const match = expandedAssetsRegex.exec(src);
  249. if (!match) return;
  250. const [_, owner, repo, version] = match;
  251. const info = { owner, repo, version };
  252. const fragment = event.detail.fragment;
  253. log("Found expanded assets:", fragment);
  254. for (const child of fragment.children) {
  255. addAdditionalInfoToRelease(child, info);
  256. }
  257. }
  258. /**
  259. * Find all release entries and setup listeners to show the download count.
  260. */
  261. function setupListeners() {
  262. log("Calling setupListeners");
  263. if (!config.get("releaseDownloads") && !config.get("releaseUploader") && !config.get("releaseHistogram")) return; // No need to run
  264. // IncludeFragmentElement: https://github.com/github/include-fragment-element/blob/main/src/include-fragment-element.ts
  265. const fragments = document.querySelectorAll('[data-hpc] details[data-view-component="true"] include-fragment');
  266. fragments.forEach(fragment => {
  267. fragment.addEventListener("include-fragment-replace", onFragmentReplace, { once: true });
  268. });
  269. }
  270. document.addEventListener("DOMContentLoaded", setupListeners);
  271. // Examine event listeners on `document`, and you can see the event listeners for the `turbo:*` events. (Remember to check `Framework Listeners`)
  272. document.addEventListener("turbo:load", setupListeners);
  273. // Other possible approaches and reasons against them:
  274. // - Use `MutationObserver` - Not efficient
  275. // - Hook `CustomEvent` to make `include-fragment-replace` events bubble - Monkey-patching
  276. // - Patch `IncludeFragmentElement.prototype.fetch`, just like GitHub itself did at `https://github.githubassets.com/assets/app/assets/modules/github/include-fragment-element-hacks.ts`
  277. // - Monkey-patching
  278. // - If using regex to modify the response, it would be tedious to maintain
  279. // - If using `DOMParser`, the same HTML would be parsed twice
  280. document.head.appendChild(document.createElement("style")).textContent = `
  281. @media (min-width: 1012px) { /* Making more room for the additional info */
  282. .ghp-release-asset .col-lg-9 {
  283. width: 60%; /* Originally ~75% */
  284. }
  285. }
  286. .nowrap { /* Preventing text wrapping */
  287. overflow: hidden;
  288. text-overflow: ellipsis;
  289. white-space: nowrap;
  290. }
  291. .ghp-release-asset { /* Styling the histogram */
  292. background: linear-gradient(to right, var(--bgColor-accent-muted) var(--percent, 0%), transparent 0);
  293. }
  294. `;
  295.  
  296. // Tracking prevention
  297. function preventTracking() {
  298. log("Calling preventTracking");
  299. // Prevents tracking data from being sent to `https://collector.github.com/github/collect`
  300. // https://github.githubassets.com/assets/ui/packages/hydro-analytics/hydro-analytics.ts
  301. $("meta[name=visitor-payload]")?.remove(); // const visitorMeta = document.querySelector<HTMLMetaElement>('meta[name=visitor-payload]')
  302. // https://github.githubassets.com/assets/node_modules/@github/hydro-analytics-client/dist/meta-helpers.js
  303. // Breakpoint on function `getOptionsFromMeta` to see the argument `prefix`, which is `octolytics`
  304. // Or investigate `hydro-analytics.ts` mentioned above, you may find: `const options = getOptionsFromMeta('octolytics')`
  305. // Later, this script gathers information from `meta[name^="${prefix}-"]` elements, so we can remove them.
  306. $$("meta[name^=octolytics-]").forEach(meta => meta.remove());
  307. // If `collectorUrl` is not set, the script will throw an error, thus preventing tracking.
  308.  
  309. // Prevents tracking data from being sent to `https://api.github.com/_private/browser/stats`
  310. // From "Network" tab, we can find that this request is sent by `https://github.githubassets.com/assets/ui/packages/stats/stats.ts` at function `safeSend`, who accepts two arguments: `url` and `data`
  311. // Search for this function in the current script, and you will find that it is only called once by function `flushStats`
  312. // `url` parameter is set in this function, by: `const url = ssrSafeDocument?.head?.querySelector<HTMLMetaElement>('meta[name="browser-stats-url"]')?.content`
  313. // So, we can remove this meta tag to prevent tracking.
  314. $("meta[name=browser-stats-url]")?.remove();
  315. // After removing the meta tag, the script will return
  316. }
  317. if (config.get("trackingPrevention")) {
  318. // document.addEventListener("DOMContentLoaded", preventTracking);
  319. // All we need to remove is in the `head` element, so we can run it immediately.
  320. preventTracking();
  321. }
  322.  
  323. log("GitHub Plus has been loaded.");
  324. })();