Greasy Fork++

添加各种功能并改善 Greasy Fork 体验

当前为 2023-09-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Greasy Fork++
  3. // @namespace https://github.com/iFelix18
  4. // @version 3.2.28
  5. // @author CY Fung <https://greasyfork.org/users/371179> & Davide <iFelix18@protonmail.com>
  6. // @icon https://www.google.com/s2/favicons?domain=https://greasyfork.org
  7. // @description Adds various features and improves the Greasy Fork experience
  8. // @description:de Fügt verschiedene Funktionen hinzu und verbessert das Greasy Fork-Erlebnis
  9. // @description:es Agrega varias funciones y mejora la experiencia de Greasy Fork
  10. // @description:fr Ajoute diverses fonctionnalités et améliore l'expérience Greasy Fork
  11. // @description:it Aggiunge varie funzionalità e migliora l'esperienza di Greasy Fork
  12. // @description:ru Добавляет различные функции и улучшает работу с Greasy Fork
  13. // @description:zh-CN 添加各种功能并改善 Greasy Fork 体验
  14. // @description:zh-TW 加入多種功能並改善Greasy Fork的體驗
  15. // @description:ja Greasy Forkの体験を向上させる様々な機能を追加
  16. // @description:ko Greasy Fork 경험을 향상시키고 다양한 기능을 추가
  17. // @copyright 2023, CY Fung (https://greasyfork.org/users/371179); 2021, Davide (https://github.com/iFelix18)
  18. // @license MIT
  19. // @require https://fastly.jsdelivr.net/gh/sizzlemctwizzle/GM_config@06f2015c04db3aaab9717298394ca4f025802873/gm_config.min.js
  20. // @require https://fastly.jsdelivr.net/npm/@violentmonkey/shortcut@1.4.1/dist/index.min.js
  21. // @require https://fastly.jsdelivr.net/gh/cyfung1031/userscript-supports@3fa07109efca28a21094488431363862ccd52d7c/library/WinComm.min.js
  22. // @match *://greasyfork.org/*
  23. // @match *://sleazyfork.org/*
  24. // @connect greasyfork.org
  25. // @compatible chrome
  26. // @compatible edge
  27. // @compatible firefox
  28. // @compatible safari
  29. // @compatible brave
  30. // @grant GM.deleteValue
  31. // @grant GM.getValue
  32. // @grant GM.notification
  33. // @grant GM.registerMenuCommand
  34. // @grant GM.setValue
  35. // @grant unsafeWindow
  36. // @run-at document-start
  37. // @inject-into content
  38. // ==/UserScript==
  39.  
  40. /* global GM_config, VM, GM, WinComm */
  41.  
  42. /**
  43. * @typedef { typeof import("./library/WinComm.js") } WinComm
  44. */
  45.  
  46. // console.log(GM)
  47.  
  48. /** @type {WinComm} */
  49. const WinComm = this.WinComm;
  50.  
  51. // -------- UU Fucntion - original code: https://fastly.jsdelivr.net/npm/@ifelix18/utils@6.5.0/lib/index.min.js --------
  52. // optimized by CY Fung to remove $ dependency and observe creation
  53. const UU = (function () {
  54. const scriptName = GM.info.script.name; // not name_i18n
  55. const scriptVersion = GM.info.script.version;
  56. const authorMatch = /^(.*?)\s<\S[^\s@]*@\S[^\s.]*\.\S+>$/.exec(GM.info.script.author);
  57. const author = authorMatch ? authorMatch[1] : GM.info.script.author;
  58. let scriptId = scriptName.toLowerCase().replace(/\s/g, "-");
  59. let loggingEnabled = false;
  60.  
  61. const log = (message) => {
  62. if (loggingEnabled) {
  63. console.log(`${scriptName}:`, message);
  64. }
  65. };
  66.  
  67. const error = (message) => {
  68. console.error(`${scriptName}:`, message);
  69. };
  70.  
  71. const warn = (message) => {
  72. console.warn(`${scriptName}:`, message);
  73. };
  74.  
  75. const alert = (message) => {
  76. window.alert(`${scriptName}: ${message}`);
  77. };
  78.  
  79. /** @param {string} text */
  80. const short = (text, length) => {
  81. const s = text.split(" ");
  82. const l = Number(length);
  83. return s.length > l
  84. ? `${s.slice(0, l).join(" ")} [...]`
  85. : text;
  86. };
  87.  
  88. const addStyle = (css) => {
  89. const head = document.head || document.querySelector("head");
  90. const style = document.createElement("style");
  91. style.textContent = css;
  92. head.appendChild(style);
  93. };
  94.  
  95. const init = async (options = {}) => {
  96. scriptId = options.id || scriptId;
  97. loggingEnabled = typeof options.logging === "boolean" ? options.logging : false;
  98. console.info(
  99. `%c${scriptName}\n%cv${scriptVersion}${author ? ` by ${author}` : ""} is running!`,
  100. "color:red;font-weight:700;font-size:18px;text-transform:uppercase",
  101. ""
  102. );
  103. };
  104.  
  105. return {
  106. init,
  107. log,
  108. error,
  109. warn,
  110. alert,
  111. short,
  112. addStyle
  113. };
  114. })();
  115.  
  116. // -------- UU Fucntion - original code: https://fastly.jsdelivr.net/npm/@ifelix18/utils@6.5.0/lib/index.min.js --------
  117.  
  118.  
  119. const mWindow = (() => {
  120.  
  121.  
  122. const fields = {
  123. hideBlacklistedScripts: {
  124. label: 'Hide blacklisted scripts:<br><span>Choose which lists to activate in the section below, press <b>Ctrl + Alt + B</b> to show Blacklisted scripts</span>',
  125. section: ['Features'],
  126. labelPos: 'right',
  127. type: 'checkbox',
  128. default: true
  129. },
  130. hideHiddenScript: {
  131. label: 'Hide scripts:<br><span>Add a button to hide the script<br>See and edit the list of hidden scripts below, press <b>Ctrl + Alt + H</b> to show Hidden script',
  132. labelPos: 'right',
  133. type: 'checkbox',
  134. default: true
  135. },
  136. showInstallButton: {
  137. label: 'Install button:<br><span>Add to the scripts list a button to install the script directly</span>',
  138. labelPos: 'right',
  139. type: 'checkbox',
  140. default: true
  141. },
  142. showTotalInstalls: {
  143. label: 'Installations:<br><span>Shows the number of daily and total installations on the user profile</span>',
  144. labelPos: 'right',
  145. type: 'checkbox',
  146. default: true
  147. },
  148. milestoneNotification: {
  149. label: 'Milestone notifications:<br><span>Get notified whenever your total installs got over any of these milestone<br>Separate milestones with a comma, leave blank to turn off notifications</span>',
  150. labelPos: 'left',
  151. type: 'text',
  152. title: 'Separate milestones with a comma!',
  153. size: 150,
  154. default: '10, 100, 500, 1000, 2500, 5000, 10000, 100000, 1000000'
  155. },
  156. nonLatins: {
  157. label: 'Non-Latin:<br><span>This list blocks all scripts with non-Latin characters in the title/description</span>',
  158. section: ['Lists'],
  159. labelPos: 'right',
  160. type: 'checkbox',
  161. default: false // not true
  162. },
  163. blacklist: {
  164. label: 'Blacklist:<br><span>A "non-opinionable" list that blocks all scripts with emoji in the title/description, references to "bots", "cheats" and some online game sites, and other "bullshit"</span>',
  165. labelPos: 'right',
  166. type: 'checkbox',
  167. default: true
  168. },
  169. customBlacklist: {
  170. label: 'Custom Blacklist:<br><span>Personal blacklist defined by a set of unwanted words<br>Separate unwanted words with a comma (example: YouTube, Facebook, pizza), leave blank to disable this list</span>',
  171. labelPos: 'left',
  172. type: 'text',
  173. title: 'Separate unwanted words with a comma!',
  174. size: 150,
  175. default: ''
  176. },
  177. hiddenList: {
  178. label: 'Hidden Scripts:<br><span>Block individual undesired scripts by their unique IDs<br>Separate IDs with a comma</span>',
  179. labelPos: 'left',
  180. type: 'textarea',
  181. title: 'Separate IDs with a comma!',
  182. default: '',
  183. save: false
  184. },
  185. logging: {
  186. label: 'Logging',
  187. section: ['Developer options'],
  188. labelPos: 'right',
  189. type: 'checkbox',
  190. default: false
  191. },
  192. debugging: {
  193. label: 'Debugging',
  194. labelPos: 'right',
  195. type: 'checkbox',
  196. default: false
  197. }
  198. }
  199.  
  200. const logo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAASFBMVEVHcEwBAQEDAwMAAAACAgIBAQEAAAAREREDAwMBAQH///8WFhYuLi7U1NSdnZ1bW1vExMTq6uqtra309PRERETf399ycnKGhoaVOQEOAAAACnRSTlMAg87/rjLgE1rzhWrqxgAABexJREFUaN61WouSpCAMVPEJKCqi//+nF4IKKig6e1SduzfupEkT8oIkiRlVVdRpnmdlQ0hTZnme1kVV4Zvk96Fla8nH0ZSI8rP0Ks2uwi1Ilv4EURW5K5xS0slhMb/BkD0hrMk/q1HVeSP6QVILMFIY8wagn6ojTV5Xn8RnbFZaoAPQc9bR3gXQ/yaWvYYA8VfKKeXACZVnAE1V9o4on/izWPsb/q9Ji3j5OcrjhiCXohsAQso6lh6QL9qOEd6GAAbKYAInAFAiiqYC5LMeLIaFKeppR3h/BiAkj6CpLuEPmbbHngUBhFZsdAGiaUL5xLBzRrAAZBlk5wpnVJEohHTbuZoAD0uhMUu+uY/bLZHaryBCH4vQCuugbnSoYf5sk+llKWaEETT/Qu2TecmSHaF1KPT6gmkM4hNLLkIR2l/guAZK1fQrS3kVXmChEX5mKb0xICH/gKXrQtf2pbhlyfqFoL/1LUOVEbFwcsuSs5GfAcjJ8dVkknbafpYUfUXSQYWqRP81THcs8fbVMmTVaQU6ENNOdyxNgGRYmFsp2/mQaFiKzGeC1IcVmAjrDjq4LAF9RgdF13CAo3cTDRcAP2OOCjX6UAwCPpbWyGZsCWTMAM0YTGF2Eg0XAD8bramue9jocGVpi5y7LbUUVRO0dRINF2D9bN/PBSqgAizt8gHByJAUddEyTqa7rYF57oZkkgiYj48lYeVTuuh4Hw1A8pWhxr68snQYioOxHSm6A2gq1wuZz68suUMKELst8oCLfAew+rzMecmOLO251wYwa4CDmd4B8GyPM1YDlyXeUp8Gx412A9Chy6vP9cXO0kW+5e6N104vH68sXeW/jwzptss8OihFf1UAY2dVkgDCdQz8dfiv1m3sZek62rcIsJlr/5uADv1bhNqzxrcIb3VIkzz06m9YykMAM39kidIoAG+5R7icHlm6BViUVDqSZknpfd8NZh2MO1Xz+JKlcYsfZeK3UqjBTDRexn680PVoSxMFBiCST6RJJmXzg2FTegaPzyRWRWu9cERAHW4o6jANmPU0Ewwqe36wa8j1wyQLADHyk1FphM760H1sBY/+PtS5ECQTvucHynoapYPiZJKFDoSNnFxZYl0QYG2gQExtcJFN8LNl1voHOA++5yQelh5yVPhRopma8M3OALMO8p0GhgDT+lgKDatBhhvN5gcuRWaZJeQ8CzVBLmBLd2tgdrLND9xFxh9CW8JABYRSNQVYugJYK8rB2bn5gWOmaM4dzmXQVjvuidMzS3YfpEm9uPnBtp5yNFRJLRUTb9OaiN1x+06uk0q4+cG+U+SqCeoKLmMwrYkp1pYWRbUvgoDjDZng7EScG3/wSxAyK7+/Xvrgl974JZ1gp69r1Bc7LvUlXhEIsSxh4lWU5Ecdwixh6lhlhPwvlkyZlpIvCFEspW4B8h9YWguQYOZynzZEsJTvRWBPxwDABnKuXWJY2ovAKu8H9h7gkSXblqqFIB8AHlhyekbGUk2PYUbXtvgAXGnYjfWwNA+QcDHN3+x2Q2rngENgiSeeAUZfjDMVHkSn1m2GGBVwCh0d8NlfhJ4owiyE+VjiPV0WKQ7tHCxD1h6DeQ7PAMKWvUcERtt2PDakkio9f/1pkdcsxMOSLq7ldD5LAJf3BeCaCfQmDl57s/Xak4sHEJiPjOcdN4f61+n8CDDQaX/iIk8KcrOTDqCC4Km3tdw9AeBM1+dq1IqRE0stI8LbWk6K7AmAjYPeX/jEdF/qJtgpX+pDzfH9eCVunFyt1UEQUt8dUHwE2BE6b2f8A8I1WMxqGLQfyqu7I8zmOwBh08TJrfy36+ANw1XcQdrHEXOeWeTf5edRJ7JV+t/o+UKTc+hRxx8oF+lLaxKCvTmw1vcRshcAbGFZ8eFUv4kF4NnHewn5pM91sauv7z9gumDPPNgoobBq54/XHraLGyAZXPLqaFrnzIMpKoeR/3BxY7t6woWY2hYqZZ0u2DOPeZzZr1dP7OUZbk4MVE+wecrmqcn+5vLMevsneP3ncfwDNtu0vRpuz80AAAAASUVORK5CYII='
  201.  
  202. const locales = { /* cSpell: disable */
  203. de: {
  204. downgrade: 'Auf zurückstufen',
  205. hide: '❌ Dieses skript ausblenden',
  206. install: 'Installieren',
  207. notHide: '✔️ Dieses skript nicht ausblenden',
  208. milestone: 'Herzlichen Glückwunsch, Ihre Skripte haben den Meilenstein von insgesamt $1 Installationen überschritten!',
  209. reinstall: 'Erneut installieren',
  210. update: 'Auf aktualisieren'
  211. },
  212. en: {
  213. downgrade: 'Downgrade to',
  214. hide: '❌ Hide this script',
  215. install: 'Install',
  216. notHide: '✔️ Not hide this script',
  217. milestone: 'Congrats, your scripts got over the milestone of $1 total installs!',
  218. reinstall: 'Reinstall',
  219. update: 'Update to'
  220. },
  221. es: {
  222. downgrade: 'Degradar a',
  223. hide: '❌ Ocultar este script',
  224. install: 'Instalar',
  225. notHide: '✔️ No ocultar este script',
  226. milestone: '¡Felicidades, sus scripts superaron el hito de $1 instalaciones totales!',
  227. reinstall: 'Reinstalar',
  228. update: 'Actualizar a'
  229. },
  230. fr: {
  231. downgrade: 'Revenir à',
  232. hide: '❌ Cacher ce script',
  233. install: 'Installer',
  234. notHide: '✔️ Ne pas cacher ce script',
  235. milestone: 'Félicitations, vos scripts ont franchi le cap des $1 installations au total!',
  236. reinstall: 'Réinstaller',
  237. update: 'Mettre à'
  238. },
  239. it: {
  240. downgrade: 'Riporta a',
  241. hide: '❌ Nascondi questo script',
  242. install: 'Installa',
  243. notHide: '✔️ Non nascondere questo script',
  244. milestone: 'Congratulazioni, i tuoi script hanno superato il traguardo di $1 installazioni totali!',
  245. reinstall: 'Reinstalla',
  246. update: 'Aggiorna a'
  247. },
  248. ru: {
  249. downgrade: 'Откатить до',
  250. hide: '❌ Скрыть этот скрипт',
  251. install: 'Установить',
  252. notHide: '✔️ Не скрывать этот сценарий',
  253. milestone: 'Поздравляем, ваши скрипты преодолели рубеж в $1 установок!',
  254. reinstall: 'Переустановить',
  255. update: 'Обновить до'
  256. },
  257. 'zh-CN': {
  258. downgrade: '降级到',
  259. hide: '❌ 隐藏此脚本',
  260. install: '安装',
  261. notHide: '✔️ 不隐藏此脚本',
  262. milestone: '恭喜,您的脚本超过了 $1 次总安装的里程碑!',
  263. reinstall: '重新安装',
  264. update: '更新到'
  265. },
  266. 'zh-TW': {
  267. downgrade: '降級至',
  268. hide: '❌ 隱藏此腳本',
  269. install: '安裝',
  270. notHide: '✔️ 不隱藏此腳本',
  271. milestone: '恭喜,您的腳本安裝總數已超過 $1!',
  272. reinstall: '重新安裝',
  273. update: '更新至'
  274. },
  275. 'ja': {
  276. downgrade: 'ダウングレードする',
  277. hide: '❌ このスクリプトを隠す',
  278. install: 'インストール',
  279. notHide: '✔️ このスクリプトを隠さない',
  280. milestone: 'おめでとうございます、あなたのスクリプトの合計インストール回数が $1 を超えました!',
  281. reinstall: '再インストール',
  282. update: '更新する'
  283. },
  284. 'ko': {
  285. downgrade: '다운그레이드하기',
  286. hide: '❌ 이 스크립트 숨기기',
  287. install: '설치',
  288. notHide: '✔️ 이 스크립트 숨기지 않기',
  289. milestone: '축하합니다, 스크립트의 총 설치 횟수가 $1을 넘었습니다!',
  290. reinstall: '재설치',
  291. update: '업데이트하기'
  292. }
  293.  
  294. };
  295.  
  296. const blacklist = [ /* cSpell: disable-next-line */
  297. '\\bagar((\\.)?io)?\\b', '\\bagma((\\.)?io)?\\b', '\\baimbot\\b', '\\barras((\\.)?io)?\\b', '\\bbot(s)?\\b', '\\bbubble((\\.)?am)?\\b', '\\bcheat(s)?\\b', '\\bdiep((\\.)?io)?\\b', '\\bfreebitco((\\.)?in)?\\b', '\\bgota((\\.)?io)?\\b', '\\bhack(s)?\\b', '\\bkrunker((\\.)?io)?\\b', '\\blostworld((\\.)?io)?\\b', '\\bmoomoo((\\.)?io)?\\b', '\\broblox(\\.com)?\\b', '\\bshell\\sshockers\\b', '\\bshellshock((\\.)?io)?\\b', '\\bshellshockers\\b', '\\bskribbl((\\.)?io)?\\b', '\\bslither((\\.)?io)?\\b', '\\bsurviv((\\.)?io)?\\b', '\\btaming((\\.)?io)?\\b', '\\bvenge((\\.)?io)?\\b', '\\bvertix((\\.)?io)?\\b', '\\bzombs((\\.)?io)?\\b', '\\p{Extended_Pictographic}'
  298. ];
  299.  
  300.  
  301. const settingsCSS = `
  302.  
  303. /*
  304. #greasyfork-plus label::before {
  305. content:'';
  306. display:block;
  307. position:absolute;
  308. left:0;
  309. right:0;
  310. top:0;
  311. bottom:0;
  312. z-index:1;
  313. }
  314. #greasyfork-plus label {
  315. position:relative;
  316. z-index:0;
  317. }
  318. */
  319.  
  320. html {
  321. color: #222;
  322. background: #f9f9f9;
  323. }
  324.  
  325. #greasyfork-plus{
  326. --config-var-display: flex;
  327. }
  328. #greasyfork-plus * {
  329. font-family:Open Sans,sans-serif,Segoe UI Emoji !important;
  330. font-size:12px
  331. }
  332. #greasyfork-plus .section_header[class] {
  333. background-color:#670000;
  334. background-image:linear-gradient(#670000,#900);
  335. border:1px solid transparent;
  336. color:#fff
  337. }
  338. #greasyfork-plus .field_label[class]{
  339. margin-bottom:4px
  340. }
  341. #greasyfork-plus .field_label[class] span{
  342. font-size:95%;
  343. font-style:italic;
  344. opacity:.8;
  345. }
  346. #greasyfork-plus .field_label[class] b{
  347. color:#670000
  348. }
  349. #greasyfork-plus_logging_var[class],
  350. #greasyfork-plus_debugging_var[class] {
  351. --config-var-display: inline-flex;
  352. }
  353. #greasyfork-plus #greasyfork-plus_logging_var label.field_label[class],
  354. #greasyfork-plus #greasyfork-plus_debugging_var label.field_label[class] {
  355. margin-bottom:0;
  356. align-self: center;
  357. }
  358. #greasyfork-plus .config_var[class]{
  359. display:var(--config-var-display);
  360. position: relative;
  361. }
  362. #greasyfork-plus_customBlacklist_var[class],
  363. #greasyfork-plus_hiddenList_var[class],
  364. #greasyfork-plus_milestoneNotification_var[class]{
  365. flex-direction:column;
  366. margin-left:21px;
  367. }
  368.  
  369. #greasyfork-plus_customBlacklist_var[class]::before,
  370. #greasyfork-plus_hiddenList_var[class]::before,
  371. #greasyfork-plus_milestoneNotification_var[class]::before{
  372. /* content: "◉"; */
  373. content: "◎";
  374. position: absolute;
  375. left: auto;
  376. top: auto;
  377. margin-left: -16px;
  378. }
  379. #greasyfork-plus_field_customBlacklist[class],
  380. #greasyfork-plus_field_milestoneNotification[class]{
  381. flex:1;
  382. }
  383. #greasyfork-plus_field_hiddenList[class]{
  384. box-sizing:border-box;
  385. overflow:hidden;
  386. resize:none;
  387. width:100%
  388. }
  389.  
  390. body > #greasyfork-plus_wrapper:only-child {
  391. box-sizing: border-box;
  392. overflow: auto;
  393. max-height: calc(100vh - 72px);
  394. padding: 12px;
  395. /* overflow: auto; */
  396. scrollbar-gutter: both-edges;
  397. background: rgba(127,127,127,0.05);
  398. border: 1px solid rgba(127,127,127,0.5);
  399. }
  400.  
  401. #greasyfork-plus_wrapper > #greasyfork-plus_buttons_holder:last-child {
  402. position: fixed;
  403. bottom: 0;
  404. right: 0;
  405. margin: 0 12px 6px 0;
  406. }
  407.  
  408. #greasyfork-plus .saveclose_buttons[class] {
  409. padding: 4px 14px;
  410. margin: 6px;
  411. }
  412. #greasyfork-plus .section_header_holder#greasyfork-plus_section_2[class] {
  413. position: fixed;
  414. left: 0;
  415. bottom: 0;
  416. margin: 8px;
  417. }
  418. #greasyfork-plus .section_header#greasyfork-plus_section_header_2[class] {
  419. background: #000;
  420. color: #eee;
  421. }
  422.  
  423. #greasyfork-plus_header[class]{
  424. font-size: 16pt;
  425. font-weight: bold;
  426. }
  427.  
  428. `;
  429.  
  430. const pageCSS = `
  431.  
  432. .script-list li.blacklisted{
  433. display:none;
  434. background:#321919;
  435. color:#e8e6e3
  436. }
  437. .script-list li.hidden{
  438. display:none;
  439. background:#321932;
  440. color:#e8e6e3
  441. }
  442. .script-list li.blacklisted a:not(.install-link),.script-list li.hidden a:not(.install-link){
  443. color:#ff8484
  444. }
  445. #script-info.hidden,#script-info.hidden .user-content{
  446. background:#321932;
  447. color:#e8e6e3
  448. }
  449. #script-info.hidden a:not(.install-link):not(.install-help-link){
  450. color:#ff8484
  451. }
  452. #script-info.hidden code{
  453. background-color:transparent
  454. }
  455. html {
  456. --block-btn-color:#111;
  457. --block-btn-bgcolor:#eee;
  458. }
  459. #script-info.hidden, #script-info.hidden .user-content {
  460. --block-btn-color:#eee;
  461. --block-btn-bgcolor:#111;
  462. }
  463.  
  464. [style-54998]{
  465. float:right;
  466. font-size: 70%;
  467. text-decoration:none;
  468. }
  469.  
  470. [style-16377]{
  471. cursor:pointer;
  472. font-size:70%;
  473. white-space:nowrap;
  474. border: 1px solid #888;
  475. background: var(--block-btn-bgcolor, #eee);
  476. color: var(--block-btn-color);
  477. border-radius: 4px;
  478. padding: 0px 6px;
  479. margin: 0 8px;
  480. }
  481. [style-77329] {
  482. cursor: pointer;
  483. margin-left: 1ex;
  484. white-space: nowrap;
  485. float: right;
  486. border: 1px solid #888;
  487. background: var(--block-btn-bgcolor, #eee);
  488. color: var(--block-btn-color);
  489. border-radius: 4px;
  490. padding: 0px 6px;
  491. }
  492.  
  493. a#hyperlink-35389,
  494. a#hyperlink-40361,
  495. a#hyperlink-35389:visited,
  496. a#hyperlink-40361:visited,
  497. a#hyperlink-35389:hover,
  498. a#hyperlink-40361:hover,
  499. a#hyperlink-35389:focus,
  500. a#hyperlink-40361:focus,
  501. a#hyperlink-35389:active,
  502. a#hyperlink-40361:active {
  503.  
  504. border: none !important;
  505. outline: none !important;
  506. box-shadow: none !important;
  507. appearance: none !important;
  508. background: none !important;
  509. color:inherit !important;
  510. }
  511.  
  512. a#hyperlink-35389{
  513. opacity: var(--hyperlink-blacklisted-option-opacity);
  514.  
  515. }
  516. a#hyperlink-40361{
  517. opacity: var(--hyperlink-hidden-option-opacity);
  518. }
  519.  
  520.  
  521. html {
  522.  
  523. --hyperlink-blacklisted-option-opacity: 0.5;
  524. --hyperlink-hidden-option-opacity: 0.5;
  525. }
  526.  
  527.  
  528. .list-option.list-current[class] > a[href] {
  529.  
  530. text-decoration:none;
  531. }
  532.  
  533. html {
  534. --blacklisted-display: none;
  535. --hidden-display: none;
  536. }
  537.  
  538. [blacklisted-shown] {
  539. --blacklisted-display: list-item;
  540. --hyperlink-blacklisted-option-opacity: 1;
  541. }
  542. [hidden-shown] {
  543. --hidden-display: list-item;
  544. --hyperlink-hidden-option-opacity: 1;
  545. }
  546.  
  547. .script-list li.blacklisted{
  548. display: var(--blacklisted-display);
  549.  
  550. }
  551.  
  552. .script-list li.hidden{
  553. display: var(--hidden-display);
  554.  
  555. }
  556.  
  557. .install-link.install-status-checking,
  558. .install-link.install-status-checking:visited,
  559. .install-link.install-status-checking:active,
  560. .install-link.install-status-checking:hover,
  561. .install-help-link.install-status-checking {
  562. background-color: #405458;
  563. }
  564.  
  565. div.previewable{
  566. display: flex;
  567. flex-direction: column;
  568. }
  569. .script-version-ainfo-span {
  570. align-self:end;
  571. font-size: 90%;
  572. padding: 4px 8px;
  573. margin: 0;
  574. }
  575. [style*="display:"] + .script-version-ainfo-span{
  576. display: none;
  577. }
  578.  
  579.  
  580. /* Greasy Fork Enhance - Flat Layout */
  581.  
  582. [greasyfork-enhance-k37*="|flat-layout|"] ol.script-list > li > article > h2 {
  583. width: 0;
  584. flex-grow: 1;
  585. flex-basis: 60%;
  586. }
  587.  
  588. [greasyfork-enhance-k37*="|flat-layout|"] ol.script-list > li > article > div.script-meta-block {
  589. width: auto;
  590. flex-basis: 40%;
  591. flex-shrink: 0;
  592. flex-grow: 0;
  593. }
  594.  
  595. [greasyfork-enhance-k37*="|flat-layout|"] .script-list li:not(.ad-entry) {
  596. padding: 1em;
  597. margin: 0;
  598. }
  599.  
  600. [greasyfork-enhance-k37*="|flat-layout|"] .script-list li:not(.ad-entry) article {
  601. padding: 0;
  602. margin: 0;
  603. }
  604.  
  605. [greasyfork-enhance-k37*="|flat-layout|"] #script-info div.script-meta-block + #additional-info {
  606.  
  607. max-width: calc( 100% - 340px );
  608. min-height: 300px;
  609. box-sizing: border-box;
  610. }
  611.  
  612. [greasyfork-enhance-k37*="|basic|"] ul.outline {
  613. margin-bottom: -99vh;
  614.  
  615. }
  616.  
  617.  
  618. `
  619.  
  620. const window = {};
  621.  
  622. /** @param {typeof WinComm.createInstance} createInstance */
  623. function contentScriptText(shObject, createInstance) {
  624.  
  625. /*
  626. *
  627.  
  628. return new Promise((resolve, reject) => {
  629. const external = unsafeWindow.external;
  630. console.log(334, external)
  631. const scriptHandler = GM.info.scriptHandler;
  632. if (external && external.Violentmonkey && (scriptHandler || 'Violentmonkey') === 'Violentmonkey' ) {
  633. external.Violentmonkey.isInstalled(name, namespace).then((data) => resolve(data));
  634. return;
  635. }
  636.  
  637. if (external && external.Tampermonkey && (scriptHandler || 'Tampermonkey') === 'Tampermonkey') {
  638. external.Tampermonkey.isInstalled(name, namespace, (data) => {
  639. (data.installed) ? resolve(data.version) : resolve();
  640. });
  641. return;
  642. }
  643.  
  644. resolve();
  645. });
  646.  
  647. */
  648.  
  649. if (document.querySelector('#greasyfork-enhance-basic')) {
  650.  
  651.  
  652.  
  653. const setScriptOnDisabled = async (style) => {
  654.  
  655. try {
  656. const pd = Object.getOwnPropertyDescriptor(style.constructor.prototype, 'disabled');
  657. const { get, set } = pd;
  658. Object.defineProperty(style, 'disabled', {
  659. get() {
  660. return get.call(this);
  661. },
  662. set(nv) {
  663. let r = set.call(this, nv);
  664. Promise.resolve().then(chHead);
  665. return r;
  666. }
  667. })
  668. } catch (e) {
  669.  
  670. }
  671. };
  672.  
  673. document.addEventListener('style-s48', function (evt) {
  674. const target = (evt || 0).target || 0;
  675. if (!target) return;
  676. setScriptOnDisabled(target)
  677.  
  678. }, true);
  679.  
  680.  
  681. const isScriptEnabled = (style) => {
  682.  
  683. if (style instanceof HTMLStyleElement) {
  684. if (!style.hasAttribute('s48')) {
  685. style.setAttribute('s48', '');
  686. style.dispatchEvent(new CustomEvent('style-s48'));
  687. // setScriptOnDisabled(style);
  688. }
  689. return style.disabled !== true;
  690. }
  691. return false;
  692. }
  693. const chHead = () => {
  694. let p = [];
  695. if (isScriptEnabled(document.getElementById('greasyfork-enhance-basic')))
  696. p.push('basic');
  697. if (isScriptEnabled(document.getElementById('greasyfork-enhance-flat-layout')))
  698. p.push('flat-layout');
  699. if (isScriptEnabled(document.getElementById('greasyfork-enhance-animation')))
  700. p.push('animation');
  701. if (p.length >= 1)
  702. document.documentElement.setAttribute('greasyfork-enhance-k37', `|${p.join('|')}|`);
  703. else
  704. document.documentElement.removeAttribute('greasyfork-enhance-k37');
  705. }
  706. const moHead = new MutationObserver(chHead);
  707. moHead.observe(document.head, { subtree: false, childList: true });
  708. chHead();
  709.  
  710. /*
  711. const outline = document.querySelector('aside.panel > ul.outline');
  712. if(outline) {
  713. const div = document.createElement('div');
  714. //outline.replaceWith(div);
  715. //div.appendChild(outline)
  716. }
  717. */
  718.  
  719. // Promise.resolve().then(()=>{
  720. // let outline = document.querySelector('[greasyfork-enhance-k37*="|basic|"] header + aside.panel ul.outline');
  721. // if(outline){
  722. // let aside = outline.closest('aside.panel');
  723. // let header = aside.parentNode.querySelector('header');
  724. // let p = header.getBoundingClientRect().height;
  725.  
  726. // document.body.parentNode.insertBefore(aside, document.body);
  727. // // outline.style.top='0'
  728. // p+=(parseFloat(getComputedStyle(outline).marginTop.replace('px',''))||0)
  729. // outline.style.marginTop= p.toFixed(2)+'px';
  730. // }
  731.  
  732. // })
  733.  
  734. }
  735.  
  736.  
  737.  
  738. const { scriptHandler, scriptName, scriptVersion, scriptNamespace, communicationId } = shObject;
  739.  
  740. const wincomm = createInstance(communicationId);
  741.  
  742. const external = window.external;
  743.  
  744. if (external[scriptHandler]) 1;
  745. else if (external && external.Violentmonkey && (scriptHandler || 'Violentmonkey') === 'Violentmonkey') scriptHandler = 'Violentmonkey';
  746. else if (external && external.Tampermonkey && (scriptHandler || 'Tampermonkey') === 'Tampermonkey') scriptHandler = 'Tampermonkey';
  747.  
  748. const manager = external[scriptHandler];
  749.  
  750. if (!manager) {
  751.  
  752. wincomm.send('userScriptManagerNotDetected', {
  753. code: 1
  754. });
  755. return;
  756.  
  757. }
  758.  
  759.  
  760. const pnIsInstalled2 = (type, scriptName, scriptNamespace) => new Promise((resolve, reject) => {
  761. const result = manager.isInstalled(scriptName, scriptNamespace);
  762. if (result instanceof Promise) {
  763. result.then((result) => resolve({
  764. type,
  765. result: typeof result === 'string' ? { version: result } : result
  766. })).catch(reject);
  767. } else {
  768. resolve({
  769. type,
  770. result: typeof result === 'string' ? { version: result } : result
  771. })
  772. }
  773.  
  774. }).catch(console.warn);
  775.  
  776.  
  777. const pnIsInstalled3 = (type, scriptName, scriptNamespace) => new Promise((resolve, reject) => {
  778. try {
  779. manager.isInstalled(scriptName, scriptNamespace, (result) => {
  780. resolve({
  781. type,
  782. result: typeof result === 'string' ? { version: result } : result
  783. })
  784.  
  785. });
  786. } catch (e) {
  787. reject(e);
  788. }
  789. }).catch(console.warn);
  790.  
  791.  
  792.  
  793. const enableScriptInstallChecker = (r) => {
  794.  
  795. const { type, result } = r;
  796. let version = result.version;
  797. // console.log(type, result, version)
  798. if (version !== scriptVersion) return;
  799.  
  800. const pnIsInstalled = type < 25 ? pnIsInstalled2 : pnIsInstalled3;
  801.  
  802. wincomm.hook('_$GreasyFork$Msg$OnScriptInstallCheck', {
  803.  
  804. 'installedVersion.req': (d, evt) => {
  805. pnIsInstalled(type, d.data.name, d.data.namespace).then((r) => {
  806. if (r && 'result' in r) {
  807. wincomm.response(evt, 'installedVersion.res', {
  808. version: r.result ? (r.result.version || '') : ''
  809. });
  810. }
  811. })
  812. }
  813.  
  814. });
  815.  
  816. wincomm.send('ready', { type });
  817.  
  818. // console.log('enableScriptInstallChecker', r)
  819.  
  820.  
  821. }
  822.  
  823. const kl = manager.isInstalled.length;
  824.  
  825. if (!(kl === 2 || kl === 3)) return;
  826. const puds = kl === 2 ? [
  827. pnIsInstalled2(21, scriptName, scriptNamespace), // scriptName is GM.info.script.name not GM.info.script.name_i18n
  828. pnIsInstalled2(20, scriptName, '')
  829. ] : [
  830. pnIsInstalled3(31, scriptName, scriptNamespace),
  831. pnIsInstalled3(30, scriptName, '')
  832. ];
  833.  
  834. Promise.all(puds).then((rs) => {
  835. const [r1, r0] = rs;
  836. if (r0 && r0.result && r0.result.version) enableScriptInstallChecker(r0); // '3.1.4'
  837. else if (r1 && r1.result && r1.result.version) enableScriptInstallChecker(r1);
  838. });
  839.  
  840.  
  841.  
  842. // console.log(327, shObject, scriptHandler);
  843.  
  844. }
  845.  
  846.  
  847.  
  848. return { fields, logo, locales, blacklist, settingsCSS, pageCSS, contentScriptText }
  849.  
  850.  
  851.  
  852. })();
  853.  
  854. (async () => {
  855.  
  856. function fixValue(key, def, test) {
  857. return GM.getValue(key, def).then((v) => test(v) || GM.deleteValue(key))
  858. }
  859.  
  860. function numberArr(arrVal) {
  861. if (!arrVal || typeof arrVal.length !== 'number') return [];
  862. return arrVal.filter(e => typeof e === 'number' && !isNaN(e))
  863. }
  864.  
  865. const isScriptFirstUse = await GM.getValue('firstUse', true);
  866. await Promise.all([
  867. fixValue('hiddenList', [], v => v && typeof v === 'object' && typeof v.length === 'number' && (v.length === 0 || typeof v[0] === 'number')),
  868. fixValue('lastMilestone', 0, v => v && typeof v === 'number' && v >= 0)
  869. ])
  870.  
  871. function createRE(t, ...opt) {
  872. try {
  873. return new RegExp(t, ...opt);
  874. } catch (e) { }
  875. return null;
  876. }
  877.  
  878. const useHashedScriptName = true;
  879. const fixLibraryScriptCodeLink = true;
  880. const addAdditionInfoLengthHint = true;
  881.  
  882. const id = 'greasyfork-plus';
  883. const title = `${GM.info.script.name} v${GM.info.script.version} Settings`;
  884. const fields = mWindow.fields;
  885. const logo = mWindow.logo;
  886. const nonLatins = /[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/gu;
  887. const blacklist = createRE((mWindow.blacklist || []).join('|'), 'giu');
  888. const hiddenList = numberArr(await GM.getValue('hiddenList', []));
  889. const lang = document.documentElement.lang;
  890. const locales = mWindow.locales;
  891.  
  892. function hiddenListStrToArr(str) {
  893. if (!str || typeof str !== 'string') str = '';
  894. return [...new Set(str ? numberArr(str.split(',').map(e => parseInt(e))) : [])];
  895. }
  896.  
  897. const gmc = new GM_config({
  898. id,
  899. title,
  900. fields,
  901. css: mWindow.settingsCSS,
  902. events: {
  903. init: () => {
  904. gmc.initializedResolve && gmc.initializedResolve();
  905. gmc.initializedResolve = null;
  906.  
  907. },
  908. /** @param {Document} document */
  909. open: async (document) => {
  910. const textarea = document.querySelector(`#${id}_field_hiddenList`);
  911.  
  912. const hiddenSet = new Set(numberArr(await GM.getValue('hiddenList', [])));
  913. if (hiddenSet.size !== 0) {
  914. const unsavedHiddenList = hiddenListStrToArr(gmc.get('hiddenList'));
  915. const unsavedHiddenSet = new Set(unsavedHiddenList);
  916.  
  917. const hasDifferentItems = [...hiddenSet].some(item => !unsavedHiddenSet.has(item)) || [...unsavedHiddenSet].some(item => !hiddenSet.has(item));
  918.  
  919. if (hasDifferentItems) {
  920.  
  921. gmc.fields.hiddenList.value = [...hiddenSet].sort((a, b) => a - b).join(', ');
  922.  
  923. gmc.close();
  924. gmc.open();
  925.  
  926. }
  927.  
  928.  
  929. }
  930.  
  931. const resize = (target) => {
  932. target.style.height = '';
  933. target.style.height = `${target.scrollHeight}px`;
  934. };
  935.  
  936. if (textarea) {
  937. resize(textarea);
  938. textarea.addEventListener('input', (event) => resize(event.target));
  939.  
  940. }
  941.  
  942. document.body.addEventListener('mousedown', (event) => {
  943. if (event.detail > 1 && !event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && !event.defaultPrevented) {
  944. event.preventDefault();
  945. event.stopPropagation();
  946. event.stopImmediatePropagation();
  947. }
  948. }, true);
  949. },
  950. save: async (forgotten) => {
  951.  
  952. if (gmc.isOpen) {
  953. await GM.setValue('hiddenList', hiddenListStrToArr(forgotten.hiddenList));
  954.  
  955. UU.alert('settings saved');
  956. gmc.close();
  957. setTimeout(() => window.location.reload(false), 500);
  958. }
  959. }
  960. }
  961. });
  962. gmc.initialized = new Promise(r => (gmc.initializedResolve = r));
  963. await gmc.initialized.then();
  964. const customBlacklistRE = createRE((gmc.get('customBlacklist') || '').replace(/\s/g, '').split(',').join('|'), 'giu');
  965.  
  966. if (typeof GM.registerMenuCommand === 'function') {
  967. GM.registerMenuCommand('Configure', () => gmc.open());
  968. GM.registerMenuCommand('Reset Everything', () => {
  969. Promise.all([
  970. GM.deleteValue('hiddenList'),
  971. GM.deleteValue('lastMilestone'),
  972. GM.deleteValue('firstUse')
  973. ]).then(() => {
  974. setTimeout(() => window.location.reload(false), 50);
  975. })
  976. });
  977. }
  978.  
  979. UU.init({ id, logging: gmc.get('logging') });
  980. UU.log(nonLatins);
  981. UU.log(blacklist);
  982. UU.log(hiddenList);
  983.  
  984. const _VM = (typeof VM !== 'undefined' ? VM : null) || {
  985. shortcut: {
  986. register: () => { }
  987. }
  988. };
  989.  
  990.  
  991. function fixLibraryCodeURL(code_url) {
  992. code_url = code_url.replace(/\/scripts\/(\d+)(\-[^\/]+)\/code\//, '/scripts/$1/code/');
  993. let qm = code_url.indexOf('?');
  994. let s1 = code_url.substring(0, qm);
  995. let s2 = code_url.substring(qm + 1);
  996. code_url = `${decodeURI(s1)}?${s2}`;
  997. return code_url;
  998. }
  999.  
  1000. function setClickToSelect(elm) {
  1001. elm.addEventListener('click', function () {
  1002. if (window.getSelection() + "" === "") {
  1003. if (typeof this.select === 'function') {
  1004. this.select();
  1005. } else {
  1006. const range = document.createRange(); // Create a range object
  1007. range.selectNode(this); // Select the text within the element
  1008. const selection = window.getSelection(); // Get the selection object
  1009. selection.removeAllRanges(); // First clear any existing selections
  1010. selection.addRange(range); // Add the new range to the selection
  1011. }
  1012. }
  1013. });
  1014. elm.addEventListener('drag', function (evt) {
  1015. evt.preventDefault();
  1016. });
  1017. elm.addEventListener('drop', function (evt) {
  1018. evt.preventDefault();
  1019. });
  1020. elm.addEventListener('dragstart', function (evt) {
  1021. evt.preventDefault();
  1022. });
  1023. }
  1024.  
  1025. const copyText = typeof (((window.navigator || 0).clipboard || 0).writeText) === 'function' ? (text) => {
  1026. navigator.clipboard.writeText(text).then(function () {
  1027. //
  1028. }).catch(function (err) {
  1029. alert("Unable to Copy");
  1030. });
  1031. } : (text) => {
  1032. const textToCopy = document.createElement('strong');
  1033. textToCopy.style.position = 'fixed';
  1034. textToCopy.style.opacity = '0';
  1035. textToCopy.style.top = '-900vh';
  1036. textToCopy.textContent = text;
  1037. document.body.appendChild(textToCopy);
  1038.  
  1039. const range = document.createRange(); // Create a range object
  1040. range.selectNode(textToCopy); // Select the text within the element
  1041.  
  1042. const selection = window.getSelection(); // Get the selection object
  1043. selection.removeAllRanges(); // First clear any existing selections
  1044. selection.addRange(range); // Add the new range to the selection
  1045.  
  1046. try {
  1047. document.execCommand('copy'); // Try to copy the selected text
  1048. } catch (err) {
  1049. alert("Unable to Copy");
  1050. }
  1051.  
  1052. selection.removeAllRanges(); // Remove the selection range after copying
  1053. textToCopy.remove();
  1054. };
  1055.  
  1056.  
  1057. let avoidDuplication = 0;
  1058. const avoidDuplicationF = () => {
  1059. const p = avoidDuplication;
  1060. avoidDuplication = Date.now();
  1061. if (avoidDuplication - p < 30) return false;
  1062. return true;
  1063. }
  1064. // https://violentmonkey.github.io/vm-shortcut/
  1065. const shortcuts = [
  1066. ['ctrlcmd-alt-keys', () => avoidDuplicationF() && gmc.open()],
  1067. ['ctrlcmd-alt-keyb', () => avoidDuplicationF() && toggleListDisplayingItem('blacklisted')],
  1068. ['ctrlcmd-alt-keyh', () => avoidDuplicationF() && toggleListDisplayingItem('hidden')]
  1069. ]
  1070. for (const [scKey, scFn] of shortcuts) {
  1071. _VM.shortcut.register(scKey, scFn);
  1072. }
  1073.  
  1074. const addSettingsToMenu = () => {
  1075. const nav = document.querySelector('#site-nav > nav')
  1076. if (!nav) return;
  1077.  
  1078. const scriptName = GM.info.script.name;
  1079. const scriptVersion = GM.info.script.version;
  1080. const menu = document.createElement('li');
  1081. menu.classList.add(id);
  1082. menu.setAttribute('alt', `${scriptName} ${scriptVersion}`);
  1083. menu.setAttribute('title', `${scriptName} ${scriptVersion}`);
  1084. const link = document.createElement('a');
  1085. link.setAttribute('href', '#');
  1086. link.textContent = GM.info.script.name;
  1087. menu.appendChild(link);
  1088. nav.insertBefore(menu, document.querySelector('#site-nav > nav > li:first-of-type'));
  1089.  
  1090. menu.addEventListener('click', (e) => {
  1091. e.preventDefault();
  1092. e.stopPropagation();
  1093. e.stopImmediatePropagation();
  1094. gmc.open();
  1095. });
  1096. };
  1097.  
  1098.  
  1099. const toggleListDisplayingItem = (t) => {
  1100.  
  1101. const m = document.documentElement;
  1102.  
  1103. const p = t + '-shown';
  1104. let currentIsShown = m.hasAttribute(p)
  1105. if (!currentIsShown) {
  1106. m.setAttribute(p, '')
  1107. } else {
  1108. m.removeAttribute(p)
  1109. }
  1110.  
  1111. }
  1112.  
  1113. const createListOptionGroup = () => {
  1114.  
  1115. const html = `<div class="list-option-group" id="${id}-options">${GM.info.script.name} Lists:<ul>
  1116. <li class="list-option blacklisted"><a href="#" id="hyperlink-35389"></a></li>
  1117. <li class="list-option hidden"><a href="#" id="hyperlink-40361"></a></li>
  1118. </ul></div>`;
  1119. const firstOptionGroup = document.querySelector('.list-option-groups > div');
  1120. firstOptionGroup && firstOptionGroup.insertAdjacentHTML('beforebegin', html);
  1121.  
  1122. const blacklistedOption = document.querySelector(`#${id}-options li.blacklisted`);
  1123. blacklistedOption && blacklistedOption.addEventListener('click', (evt) => {
  1124. evt.preventDefault();
  1125. toggleListDisplayingItem('blacklisted');
  1126. }, false);
  1127.  
  1128. const hiddenOption = document.querySelector(`#${id}-options li.hidden`);
  1129. hiddenOption && hiddenOption.addEventListener('click', (evt) => {
  1130. evt.preventDefault();
  1131. toggleListDisplayingItem('hidden');
  1132. }, false);
  1133.  
  1134. }
  1135.  
  1136. const addOptions = () => {
  1137.  
  1138. const gn = () => {
  1139.  
  1140. let aBlackList = document.querySelector('#hyperlink-35389');
  1141. let aHidden = document.querySelector('#hyperlink-40361');
  1142. if (!aBlackList || !aHidden) return;
  1143. aBlackList.textContent = `Blacklisted scripts (${document.querySelectorAll('.script-list li.blacklisted').length})`;
  1144. aHidden.textContent = `Hidden scripts (${document.querySelectorAll('.script-list li.hidden').length})`
  1145.  
  1146. }
  1147. const callback = (entries) => {
  1148. if (entries && entries.length >= 1) requestAnimationFrame(gn);
  1149. }
  1150.  
  1151. const setupScriptList = async () => {
  1152. let scriptList;
  1153. let i = 8;
  1154. while (i-- > 0) {
  1155. scriptList = document.querySelector('.script-list li')
  1156. if (scriptList) scriptList = scriptList.closest('.script-list')
  1157. if (scriptList) break;
  1158. await new Promise(r => requestAnimationFrame(r))
  1159. }
  1160. if (!scriptList) return;
  1161. createListOptionGroup();
  1162. const mo = new MutationObserver(callback);
  1163. mo.observe(scriptList, { childList: true, subtree: true });
  1164. gn();
  1165. }
  1166. setupScriptList();
  1167.  
  1168. };
  1169.  
  1170.  
  1171. /**
  1172. * Get script data from Greasy Fork API
  1173. *
  1174. * @param {number} id Script ID
  1175. * @returns {Promise} Script data
  1176. */
  1177. let networkMP1 = Promise.resolve();
  1178. let networkMP2 = Promise.resolve();
  1179. let previousIsCache = false;
  1180. // let ss = [];
  1181. // var sum = function(nums) {
  1182. // var total = 0;
  1183. // for (var i = 0, len = nums.length; i < len; i++) total += nums[i];
  1184. // return total;
  1185. // };
  1186. const getScriptData = async (id, noCache) => {
  1187. if (!(id >= 0)) return Promise.resolve()
  1188. const url = `https://${window.location.hostname}/scripts/${id}.json`;
  1189. return new Promise((resolve, reject) => {
  1190.  
  1191. networkMP1 = networkMP1.then(() => new Promise(unlock => {
  1192.  
  1193. const maxAgeInSeconds = 900;
  1194. const rd = previousIsCache ? 1 : Math.floor(Math.random() * 80 + 80);
  1195. let fetchStart = 0;
  1196. new Promise(r => setTimeout(r, rd))
  1197. .then(() => {
  1198. fetchStart = Date.now();
  1199. })
  1200. .then(() => fetch(url, noCache ? {
  1201. method: 'GET',
  1202. cache: 'reload',
  1203. credentials: 'omit',
  1204. headers: new Headers({
  1205. 'Cache-Control': `max-age=${maxAgeInSeconds}`,
  1206. })
  1207. } : {
  1208. method: 'GET',
  1209. cache: 'force-cache',
  1210. credentials: 'omit',
  1211. headers: new Headers({
  1212. 'Cache-Control': `max-age=${maxAgeInSeconds}`,
  1213. }),
  1214. }))
  1215. .then((response) => {
  1216.  
  1217. let fetchStop = Date.now();
  1218. // const dd = fetchStop - fetchStart;
  1219. // dd (cache) = {min: 1, max: 8, avg: 3.7}
  1220. // dd (normal) = {min: 136, max: 316, avg: 162.62}
  1221.  
  1222. // ss.push(dd)
  1223. // ss.maxValue = Math.max(...ss);
  1224. // ss.minValue = Math.min(...ss);
  1225. // ss.avgValue = sum(ss)/ss.length;
  1226. // console.log(dd)
  1227. // console.log(ss)
  1228. previousIsCache = (fetchStop - fetchStart) < (3.7 + 162.62) / 2;
  1229. UU.log(`${response.status}: ${response.url}`)
  1230. // UU.log(response)
  1231. if (response.ok === true) {
  1232. unlock();
  1233. return response.json()
  1234. }
  1235. if (response.status === 503) {
  1236. return new Promise(r => setTimeout(r, 270 + rd)).then(() => {
  1237. unlock();
  1238. return getScriptData(id, true);
  1239. });
  1240. }
  1241. if (response.status === 404) {
  1242. // script XXXX has been reported and is pending review by a moderator.
  1243. unlock();
  1244. return null
  1245. }
  1246. console.warn(response.status, response);
  1247. new Promise(r => setTimeout(r, 470)).then(unlock); // reload later
  1248. })
  1249. .then((data) => resolve(data))
  1250. .catch((e) => {
  1251. unlock();
  1252. UU.log(id, url)
  1253. console.warn(e)
  1254. // reject(e)
  1255. })
  1256.  
  1257. })).catch(() => { })
  1258.  
  1259. });
  1260. }
  1261.  
  1262. /**
  1263. * Get user data from Greasy Fork API
  1264. *
  1265. * @param {string} userID User ID
  1266. * @returns {Promise} User data
  1267. */
  1268. const getUserData = (userID, noCache) => {
  1269.  
  1270. if (!(userID >= 0)) return Promise.resolve()
  1271.  
  1272. const url = `https://${window.location.hostname}/users/${userID}.json`;
  1273. return new Promise((resolve, reject) => {
  1274.  
  1275.  
  1276. networkMP2 = networkMP2.then(() => new Promise(unlock => {
  1277.  
  1278. const maxAgeInSeconds = 900;
  1279. const rd = Math.floor(Math.random() * 80 + 80);
  1280.  
  1281. new Promise(r => setTimeout(r, rd))
  1282. .then(() => fetch(url, noCache ? {
  1283. method: 'GET',
  1284. cache: 'reload',
  1285. credentials: 'omit',
  1286. headers: new Headers({
  1287. 'Cache-Control': `max-age=${maxAgeInSeconds}`,
  1288. })
  1289. } : {
  1290. method: 'GET',
  1291. cache: 'force-cache',
  1292. credentials: 'omit',
  1293. headers: new Headers({
  1294. 'Cache-Control': `max-age=${maxAgeInSeconds}`,
  1295. }),
  1296. }))
  1297. .then((response) => {
  1298. UU.log(`${response.status}: ${response.url}`)
  1299. if (response.ok === true) {
  1300. unlock();
  1301. return response.json()
  1302. }
  1303. if (response.status === 503) {
  1304. return new Promise(r => setTimeout(r, 270 + rd)).then(() => {
  1305. unlock();
  1306. return getUserData(userID, true); // reload later
  1307. });
  1308. }
  1309. if (response.status === 404) {
  1310. // user XXXX has been reported and is pending review by a moderator. ????
  1311. unlock();
  1312. return null
  1313. }
  1314. console.warn(response.status, response);
  1315. new Promise(r => setTimeout(r, 470)).then(unlock);
  1316. })
  1317. .then((data) => resolve(data))
  1318. .catch((e) => {
  1319. setTimeout(() => {
  1320. unlock()
  1321. }, 270)
  1322. UU.log(userID, url)
  1323. console.warn(e)
  1324. // reject(e)
  1325. })
  1326.  
  1327.  
  1328.  
  1329. })).catch(() => { })
  1330.  
  1331. });
  1332. }
  1333. const getTotalInstalls = (data) => {
  1334. if (!data || !data.scripts) return;
  1335. return new Promise((resolve, reject) => {
  1336. const totalInstalls = [];
  1337.  
  1338. data.scripts.forEach((element) => {
  1339. totalInstalls.push(parseInt(element.total_installs, 10));
  1340. });
  1341.  
  1342. resolve(totalInstalls.reduce((a, b) => a + b, 0));
  1343. });
  1344. };
  1345.  
  1346.  
  1347. const communicationId = WinComm.newCommunicationId();
  1348. const wincomm = WinComm.createInstance(communicationId);
  1349.  
  1350.  
  1351. const isInstalled = (script) => {
  1352. return new Promise((resolve, reject) => {
  1353.  
  1354. promiseScriptCheck.then(d => {
  1355.  
  1356. if (!d) return null;
  1357.  
  1358. const data = d.data;
  1359. const al = data.type % 10;
  1360. if (al === 0) {
  1361. // no namespace
  1362. resolve([null, script.name, '']);
  1363. } else if (al === 1) {
  1364. // namespace
  1365.  
  1366. if (!script.namespace) {
  1367.  
  1368. getScriptData(script.id).then((script) => {
  1369. resolve([null, script.name, script.namespace]);
  1370. });
  1371.  
  1372. } else {
  1373.  
  1374. resolve([null, script.name, script.namespace]);
  1375. }
  1376.  
  1377. }
  1378.  
  1379.  
  1380. })
  1381.  
  1382.  
  1383. }).then((res) => {
  1384.  
  1385.  
  1386. return new Promise((resolve, reject) => {
  1387.  
  1388. if (!res) return '';
  1389.  
  1390.  
  1391. const [_, name, namespace] = res;
  1392. wincomm.request('installedVersion.req', {
  1393. name,
  1394. namespace
  1395. }).then(d => {
  1396. resolve(d.data.version)
  1397. })
  1398.  
  1399. })
  1400.  
  1401. })
  1402.  
  1403. /*
  1404. const external = unsafeWindow.external;
  1405. const scriptHandler = GM.info.scriptHandler;
  1406. if (external && external.Violentmonkey && (scriptHandler || 'Violentmonkey') === 'Violentmonkey') {
  1407. external.Violentmonkey.isInstalled(name, namespace).then((data) => resolve(data));
  1408. return;
  1409. }
  1410.  
  1411. if (external && external.Tampermonkey && (scriptHandler || 'Tampermonkey') === 'Tampermonkey') {
  1412. external.Tampermonkey.isInstalled(name, namespace, (data) => {
  1413. (data.installed) ? resolve(data.version) : resolve();
  1414. });
  1415. return;
  1416. }
  1417. */
  1418.  
  1419.  
  1420. };
  1421.  
  1422. const compareVersions = (v1, v2) => {
  1423. if (!v1 || !v2) return NaN;
  1424. if (v1 === null || v2 === null) return NaN;
  1425. if (v1 === v2) return 0;
  1426.  
  1427. const sv1 = v1.split('.').map((index) => parseInt(index));
  1428. const sv2 = v2.split('.').map((index) => parseInt(index));
  1429.  
  1430. for (let index = 0; index < Math.max(sv1.length, sv2.length); index++) {
  1431. if (isNaN(sv1[index]) || isNaN(sv2[index])) return NaN;
  1432. if (sv1[index] > sv2[index]) return 1;
  1433. if (sv1[index] < sv2[index]) return -1;
  1434. }
  1435.  
  1436. return 0;
  1437. };
  1438.  
  1439.  
  1440. /**
  1441. * Return label for the hide script button
  1442. *
  1443. * @param {boolean} hidden Is hidden
  1444. * @returns {string} Label
  1445. */
  1446. const blockLabel = (hidden) => {
  1447. return hidden ? (locales[lang] ? locales[lang].notHide : locales.en.notHide) : (locales[lang] ? locales[lang].hide : locales.en.hide)
  1448. }
  1449.  
  1450. /**
  1451. * Return label for the install button
  1452. *
  1453. * @param {number} update Update value
  1454. * @returns {string} Label
  1455. */
  1456. const installLabel = (update) => {
  1457. switch (update) {
  1458. case 0: {
  1459. return locales[lang] ? locales[lang].reinstall : locales.en.reinstall
  1460. }
  1461. case 1: {
  1462. return locales[lang] ? locales[lang].update : locales.en.update
  1463. }
  1464. case -1: {
  1465. return locales[lang] ? locales[lang].downgrade : locales.en.downgrade
  1466. }
  1467. default: {
  1468. return locales[lang] ? locales[lang].install : locales.en.install
  1469. }
  1470. }
  1471. }
  1472.  
  1473. const hideBlacklistedScript = (element, list) => {
  1474. if (!element) return;
  1475. const scriptLink = element.querySelector('.script-link')
  1476.  
  1477. const name = scriptLink ? scriptLink.textContent : '';
  1478. const descriptionElem = element.querySelector('.script-description')
  1479. const description = descriptionElem ? descriptionElem.textContent : '';
  1480.  
  1481. if (!name) return;
  1482.  
  1483. switch (list) {
  1484. case 'nonLatins':
  1485. if ((nonLatins.test(name) || nonLatins.test(description)) && !element.classList.contains('blacklisted')) {
  1486. element.classList.add('blacklisted', 'non-latins');
  1487. if (gmc.get('hideBlacklistedScripts') && gmc.get('debugging')) {
  1488. let scriptLink = element.querySelector('.script-link');
  1489. if (scriptLink) { scriptLink.textContent += ' (non-latin)'; }
  1490. }
  1491. }
  1492. break;
  1493. case 'blacklist':
  1494. if (blacklist && (blacklist.test(name) || blacklist.test(description)) && !element.classList.contains('blacklisted')) {
  1495. element.classList.add('blacklisted', 'blacklist');
  1496. if (gmc.get('hideBlacklistedScripts') && gmc.get('debugging')) {
  1497. let scriptLink = element.querySelector('.script-link');
  1498. if (scriptLink) { scriptLink.textContent += ' (blacklist)'; }
  1499. }
  1500. }
  1501. break;
  1502. case 'customBlacklist': {
  1503. const customBlacklist = customBlacklistRE;
  1504. if (customBlacklist && (customBlacklist.test(name) || customBlacklist.test(description)) && !element.classList.contains('blacklisted')) {
  1505. element.classList.add('blacklisted', 'custom-blacklist');
  1506. if (gmc.get('hideBlacklistedScripts') && gmc.get('debugging')) {
  1507. let scriptLink = element.querySelector('.script-link');
  1508. if (scriptLink) { scriptLink.textContent += ' (custom-blacklist)'; }
  1509. }
  1510. }
  1511. break;
  1512. }
  1513. default:
  1514. UU.log('No blacklists');
  1515. break;
  1516. }
  1517. };
  1518.  
  1519. const hideHiddenScript = (element, id, list) => {
  1520. id = +id;
  1521. if (!(id >= 0)) return;
  1522.  
  1523. const isInHiddenList = () => hiddenList.indexOf(id) !== -1;
  1524. const updateScriptLink = (shouldHide) => {
  1525. if (gmc.get('hideHiddenScript') && gmc.get('debugging')) {
  1526. let scriptLink = element.querySelector('.script-link');
  1527. if (scriptLink) {
  1528. if (shouldHide) {
  1529. scriptLink.innerHTML += ' (hidden)';
  1530. } else {
  1531. scriptLink.innerHTML = scriptLink.innerHTML.replace(' (hidden)', '');
  1532. }
  1533. }
  1534. }
  1535. };
  1536.  
  1537. // Check for initial state and set it
  1538. if (isInHiddenList()) {
  1539. element.classList.add('hidden');
  1540. updateScriptLink(true);
  1541. }
  1542.  
  1543. // Add button to hide the script
  1544. const insertButtonHTML = (selector, html) => {
  1545. const target = element.querySelector(selector);
  1546. if (!target) return;
  1547. let p = document.createElement('template');
  1548. p.innerHTML = html;
  1549. target.parentNode.insertBefore(p.content.firstChild, target.nextSibling);
  1550. };
  1551.  
  1552. const isHidden = element.classList.contains('hidden');
  1553. const blockButtonHTML = `<span class=block-button role=button style-16377>${blockLabel(isHidden)}</span>`;
  1554. const blockButtonHeaderHTML = `<span class=block-button role=button style-77329 style="">${blockLabel(isHidden)}</span>`;
  1555.  
  1556. insertButtonHTML('.badge-js, .badge-css', blockButtonHTML);
  1557. insertButtonHTML('header h2', blockButtonHeaderHTML);
  1558.  
  1559. // Add event listener
  1560. const button = element.querySelector('.block-button');
  1561. if (button) {
  1562. button.addEventListener('click', (event) => {
  1563. event.stopPropagation();
  1564. event.stopImmediatePropagation();
  1565.  
  1566. if (!isInHiddenList()) {
  1567. hiddenList.push(id);
  1568. GM.setValue('hiddenList', hiddenList);
  1569.  
  1570. element.classList.add('hidden');
  1571. updateScriptLink(true);
  1572.  
  1573. } else {
  1574. const index = hiddenList.indexOf(id);
  1575. hiddenList.splice(index, 1);
  1576. GM.setValue('hiddenList', hiddenList);
  1577.  
  1578. element.classList.remove('hidden');
  1579. updateScriptLink(false);
  1580. }
  1581.  
  1582. const blockBtn = element.querySelector('.block-button');
  1583. if (blockBtn) blockBtn.textContent = blockLabel(element.classList.contains('hidden'));
  1584. });
  1585. }
  1586. };
  1587.  
  1588. const insertButtonHTML = (element, selector, html) => {
  1589. const target = element.querySelector(selector);
  1590. if (!target) return;
  1591. let p = document.createElement('template');
  1592. p.innerHTML = html;
  1593. let button = p.content.firstChild
  1594. target.parentNode.insertBefore(button, target.nextSibling);
  1595. return button;
  1596. };
  1597.  
  1598. const addInstallButton = (element, url) => {
  1599. return insertButtonHTML(element, '.badge-js, .badge-css', `<a class="install-link" href="${url}" style-54998></a>`);
  1600. };
  1601.  
  1602. async function digestMessage(message, algo) {
  1603. const encoder = new TextEncoder();
  1604. const data = encoder.encode(message);
  1605. const hash = await crypto.subtle.digest(algo, data);
  1606. return hash;
  1607. }
  1608.  
  1609. function qexString(buffer) {
  1610. const byteArray = new Uint8Array(buffer);
  1611. const len = byteArray.length;
  1612. const hexCodes = new Array(len * 2);
  1613. const chars = 'a4b3c5d7e6f9h2t';
  1614. for (let i = 0, j = 0; i < len; i++) {
  1615. const byte = byteArray[i];
  1616. hexCodes[j++] = chars[byte >> 4];
  1617. hexCodes[j++] = chars[byte & 0x0F];
  1618. };
  1619. return hexCodes.join('');
  1620. }
  1621.  
  1622. const showInstallButton = async (scriptID, element) => {
  1623.  
  1624. // if(document.querySelector(`li[data-script-id="${scriptID}"]`))
  1625. let _baseScript = null;
  1626. if (element.nodeName === 'LI' && element.hasAttribute('data-script-id') && element.getAttribute('data-script-id') === `${scriptID}` && element.getAttribute('data-script-language') === 'js') {
  1627.  
  1628. const version = element.getAttribute('data-script-version') || ''
  1629. const name = element.getAttribute('data-script-name') || ''
  1630. // if (!/[^\x00-\x7F]/.test(name)) {
  1631.  
  1632. const scriptName = useHashedScriptName ? qexString(await digestMessage(`${+scriptID} ${version}`, 'SHA-1')).substring(0, 8) : encodeURI(name);
  1633. const token = useHashedScriptName ? `${scriptName.substring(0, 2)}${scriptName.substring(scriptName.length - 2, scriptName.length)}` : String.fromCharCode(Date.now() % 26 + 97) + Math.floor(Math.random() * 19861 + 19861).toString(36);
  1634. // let scriptFilename = `${encodeURI(name)}.user.js`;
  1635. const scriptFilename = `${scriptName}.user.js`;
  1636. _baseScript = {
  1637. id: +scriptID,
  1638. // name: name,
  1639. code_url: `https://${location.hostname}/scripts/${scriptID}-${token}/code/${scriptFilename}`,
  1640. version: version
  1641. }
  1642. // }
  1643.  
  1644. }
  1645.  
  1646. const baseScript = _baseScript || (await getScriptData(scriptID));
  1647.  
  1648.  
  1649. if ((element.nodeName === 'LI' && element.getAttribute('data-script-type') === 'library') || (baseScript.code_url.includes('.js?version='))) {
  1650.  
  1651. const script = baseScript.code_url.includes('.js?version=') ? baseScript : (await getScriptData(scriptID));
  1652. if (script.code_url.includes('.js?version=')) {
  1653.  
  1654.  
  1655. const code_url = fixLibraryCodeURL(script.code_url);
  1656.  
  1657. const button = addInstallButton(element, code_url);
  1658. button.textContent = `Copy URL`;
  1659. button.addEventListener('click', function (evt) {
  1660.  
  1661. const target = (evt || 0).target;
  1662. if (!target) return;
  1663.  
  1664. let a = target.nodeName === 'A' ? target : target.querySelector('a[href]');
  1665.  
  1666. if (!a) return;
  1667. let href = target.getAttribute('href');
  1668. if (!href) return;
  1669.  
  1670. evt.preventDefault();
  1671.  
  1672. copyText(href);
  1673.  
  1674.  
  1675. });
  1676.  
  1677. }
  1678.  
  1679.  
  1680. } else {
  1681.  
  1682.  
  1683. if (!baseScript || !baseScript.code_url || !baseScript.version) return;
  1684. const button = addInstallButton(element, baseScript.code_url);
  1685. button.classList.add('install-status-checking');
  1686. button.textContent = `${installLabel()} ${baseScript.version}`;
  1687. const script = baseScript && baseScript.name && baseScript.namespace ? baseScript : (await getScriptData(scriptID));
  1688. if (!script) return;
  1689.  
  1690. const installed = await isInstalled(script);
  1691. const version = (
  1692. baseScript.version && script.version && compareVersions(baseScript.version, script.version) === 1
  1693. ) ? baseScript.version : script.version;
  1694.  
  1695. const update = compareVersions(version, installed); // NaN 1 -1 0
  1696. const label = installLabel(update);
  1697. button.textContent = `${label} ${version}`;
  1698. button.classList.remove('install-status-checking');
  1699.  
  1700.  
  1701. }
  1702.  
  1703. }
  1704.  
  1705.  
  1706. const foundScriptList = async (scriptList) => {
  1707.  
  1708. let rid = 0;
  1709. let g = () => {
  1710. if (!scriptList || scriptList.isConnected !== true) return;
  1711.  
  1712. const scriptElements = scriptList.querySelectorAll('li[data-script-id]:not([e8kk])');
  1713.  
  1714. for (const element of scriptElements) {
  1715. element.setAttribute('e8kk', '1');
  1716.  
  1717. const scriptID = +element.getAttribute('data-script-id');
  1718. if (!(scriptID > 0)) continue;
  1719.  
  1720. // blacklisted scripts
  1721. if (gmc.get('nonLatins')) hideBlacklistedScript(element, 'nonLatins');
  1722. if (gmc.get('blacklist')) hideBlacklistedScript(element, 'blacklist');
  1723. if (gmc.get('customBlacklist')) hideBlacklistedScript(element, 'customBlacklist');
  1724.  
  1725. // hidden scripts
  1726. if (gmc.get('hideHiddenScript')) hideHiddenScript(element, scriptID, true);
  1727.  
  1728. // install button
  1729. if (gmc.get('showInstallButton')) {
  1730. showInstallButton(scriptID, element)
  1731. }
  1732. }
  1733.  
  1734. }
  1735. let f = (entries) => {
  1736. const tid = ++rid
  1737. if (entries && entries.length) requestAnimationFrame(() => {
  1738. if (tid === rid) g();
  1739. });
  1740. }
  1741. let mo = new MutationObserver(f);
  1742. mo.observe(scriptList, { subtree: true, childList: true });
  1743.  
  1744. g();
  1745.  
  1746. }
  1747.  
  1748. let promiseScriptCheckResolve = null;
  1749. const promiseScriptCheck = new Promise(resolve => {
  1750. promiseScriptCheckResolve = resolve
  1751. });
  1752.  
  1753. const milestoneNotificationFn = async (o) => {
  1754.  
  1755. const { userLink, userID } = o;
  1756.  
  1757.  
  1758. const milestones = gmc.get('milestoneNotification').replace(/\s/g, '').split(',').map(Number);
  1759.  
  1760. if (!userID) return;
  1761.  
  1762. const userData = await getUserData(+userID.match(/\d+(?=\D)/g));
  1763. if (!userData) return;
  1764.  
  1765. const [totalInstalls, lastMilestone] = await Promise.all([
  1766. getTotalInstalls(userData),
  1767. GM.getValue('lastMilestone', 0)]);
  1768.  
  1769. const milestone = milestones.filter(milestone => totalInstalls >= milestone).pop();
  1770.  
  1771. UU.log(`total installs are "${totalInstalls}", milestone reached is "${milestone}", last milestone reached is "${lastMilestone}"`);
  1772.  
  1773. if (milestone <= lastMilestone) return;
  1774.  
  1775. if (milestone && milestone >= 0) {
  1776.  
  1777.  
  1778. GM.setValue('lastMilestone', milestone);
  1779.  
  1780. const lang = document.documentElement.lang;
  1781. const text = (locales[lang] ? locales[lang].milestone : locales.en.milestone).replace('$1', milestone.toLocaleString());
  1782.  
  1783. if (typeof GM.notification === 'function') {
  1784. GM.notification({
  1785. text,
  1786. title: GM.info.script.name,
  1787. image: logo,
  1788. onclick: () => {
  1789. window.location = `https://${window.location.hostname}${userID}#user-script-list-section`;
  1790. }
  1791. });
  1792. } else {
  1793. UU.alert(text);
  1794. }
  1795.  
  1796. }
  1797.  
  1798. }
  1799. const onReady = async () => {
  1800.  
  1801. try {
  1802.  
  1803. const gminfo = GM.info || 0;
  1804. if (gminfo) {
  1805.  
  1806. const gminfoscript = gminfo.script || 0;
  1807.  
  1808.  
  1809. const scriptHandlerObject = {
  1810. scriptHandler: gminfo.scriptHandler || '',
  1811. scriptName: gminfoscript.name || '', // not name_i18n
  1812. scriptVersion: gminfoscript.version || '',
  1813. scriptNamespace: gminfoscript.namespace || '',
  1814. communicationId
  1815. };
  1816.  
  1817.  
  1818. wincomm.hook('_$GreasyFork$Msg$OnScriptInstallFeedback',
  1819. {
  1820.  
  1821. ready: (d, evt) => promiseScriptCheckResolve(d),
  1822. userScriptManagerNotDetected: (d, evt) => promiseScriptCheckResolve(null),
  1823. 'installedVersion.res': wincomm.handleResponse
  1824.  
  1825.  
  1826. })
  1827.  
  1828.  
  1829. document.head.appendChild(document.createElement('script')).textContent = `;(${mWindow.contentScriptText})(${JSON.stringify(scriptHandlerObject)}, ${WinComm.createInstance});`;
  1830.  
  1831.  
  1832. }
  1833.  
  1834.  
  1835. addSettingsToMenu();
  1836.  
  1837.  
  1838. setTimeout(() => {
  1839. let installBtn = document.querySelector('a[data-script-id][data-script-version]')
  1840. let scriptID = installBtn && installBtn.textContent ? +installBtn.getAttribute('data-script-id') : 0;
  1841. if (scriptID > 0) {
  1842. getScriptData(scriptID, true);
  1843. } else {
  1844.  
  1845.  
  1846. const userLink = document.querySelector('#site-nav .user-profile-link a[href]');
  1847. let userID = userLink ? userLink.getAttribute('href') : '';
  1848.  
  1849. userID = userID ? /users\/(\d+)/.exec(userID) : null;
  1850. if (userID) userID = userID[1];
  1851. if (userID) {
  1852. userID = +userID;
  1853. if (userID > 0) {
  1854. getUserData(userID, true);
  1855. }
  1856. }
  1857.  
  1858.  
  1859. }
  1860. }, 740);
  1861.  
  1862. const userLink = document.querySelector('.user-profile-link a[href]');
  1863. const userID = userLink ? userLink.getAttribute('href') : undefined;
  1864.  
  1865. UU.addStyle(mWindow.pageCSS);
  1866. // blacklisted scripts / hidden scripts / install button
  1867. if (window.location.pathname !== userID && !/discussions/.test(window.location.pathname) && (gmc.get('hideBlacklistedScripts') || gmc.get('hideHiddenScript') || gmc.get('showInstallButton'))) {
  1868.  
  1869. const scriptList = document.querySelector('.script-list');
  1870. if (scriptList) {
  1871. foundScriptList(scriptList);
  1872. } else {
  1873. const timeout = Date.now() + 3000;
  1874. /** @type {MutationObserver | null} */
  1875. let mo = null;
  1876. const mutationCallbackForScriptList = () => {
  1877. if (!mo) return;
  1878. const scriptList = document.querySelector('.script-list');
  1879. if (scriptList) {
  1880. mo.disconnect();
  1881. mo.takeRecords();
  1882. mo = null;
  1883. foundScriptList(scriptList);
  1884. } else if (Date.now() > timeout) {
  1885. mo.disconnect();
  1886. mo.takeRecords();
  1887. mo = null;
  1888. }
  1889. }
  1890. mo = new MutationObserver(mutationCallbackForScriptList);
  1891. mo.observe(document, { subtree: true, childList: true });
  1892. }
  1893.  
  1894.  
  1895. // hidden scripts on details page
  1896. const installLinkElement = document.querySelector('#script-info .install-link[data-script-id]');
  1897. if (gmc.get('hideHiddenScript') && installLinkElement) {
  1898. const id = +installLinkElement.getAttribute('data-script-id');
  1899. hideHiddenScript(document.querySelector('#script-info'), id, false);
  1900. }
  1901.  
  1902. // add options and style for blacklisted/hidden scripts
  1903. if (gmc.get('hideBlacklistedScripts') || gmc.get('hideHiddenScript')) {
  1904. addOptions();
  1905. }
  1906.  
  1907. if (installLinkElement && location.pathname.includes('/scripts/')) {
  1908.  
  1909. installLinkElement.addEventListener('click', async function (e) {
  1910. if (e && e.isTrusted && location.pathname.includes('/scripts/')) {
  1911.  
  1912. await new Promise(r => setTimeout(r, 800));
  1913. await new Promise(r => window.requestAnimationFrame(r));
  1914. await new Promise(r => setTimeout(r, 100));
  1915. document.dispatchEvent(new Event("DOMContentLoaded"));
  1916. }
  1917. })
  1918. }
  1919. }
  1920.  
  1921. // total installs
  1922. if (gmc.get('showTotalInstalls') && document.querySelector('#user-script-list')) {
  1923. const dailyInstalls = [];
  1924. const totalInstalls = [];
  1925.  
  1926. const dailyInstallElements = document.querySelectorAll('#user-script-list li dd.script-list-daily-installs');
  1927. for (const element of dailyInstallElements) {
  1928. dailyInstalls.push(parseInt(element.textContent.replace(/\D/g, ''), 10));
  1929. }
  1930.  
  1931. const totalInstallElements = document.querySelectorAll('#user-script-list li dd.script-list-total-installs');
  1932. for (const element of totalInstallElements) {
  1933. totalInstalls.push(parseInt(element.textContent.replace(/\D/g, ''), 10));
  1934. }
  1935.  
  1936. const dailyInstallsSum = dailyInstalls.reduce((a, b) => a + b, 0);
  1937. const totalInstallsSum = totalInstalls.reduce((a, b) => a + b, 0);
  1938.  
  1939. const convertLi = (li) => {
  1940.  
  1941. if (!li) return null;
  1942. const a = li.firstElementChild
  1943. if (a === null) return li;
  1944. if (a === li.lastElementChild && a.nodeName === 'A') return a;
  1945.  
  1946.  
  1947. return null;
  1948. }
  1949.  
  1950. const plusSign = document.querySelector('#user-script-list-section a[rel="next"][href*="page="], #user-script-list-section a[rel="prev"][href*="page="]') ? '+' : '';
  1951.  
  1952. const dailyOption = convertLi(document.querySelector('#script-list-sort .list-option:nth-child(1)'));
  1953. dailyOption && dailyOption.insertAdjacentHTML('beforeend', `<span> (${dailyInstallsSum.toLocaleString()}${plusSign})</span>`);
  1954.  
  1955. const totalOption = convertLi(document.querySelector('#script-list-sort .list-option:nth-child(2)'));
  1956. totalOption && totalOption.insertAdjacentHTML('beforeend', `<span> (${totalInstallsSum.toLocaleString()}${plusSign})</span>`);
  1957. }
  1958.  
  1959. // milestone notification
  1960. if (gmc.get('milestoneNotification')) {
  1961. milestoneNotificationFn({ userLink, userID });
  1962. }
  1963.  
  1964. if (isScriptFirstUse) GM.setValue('firstUse', false).then(() => {
  1965. gmc.open();
  1966. });
  1967.  
  1968. if (fixLibraryScriptCodeLink) {
  1969.  
  1970.  
  1971. let xpath = "//code[contains(text(), '.js?version=')]";
  1972. let snapshot = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1973.  
  1974. for (let i = 0; i < snapshot.snapshotLength; i++) {
  1975. let element = snapshot.snapshotItem(i);
  1976. if (element.firstElementChild) continue;
  1977. element.textContent = element.textContent.replace(/\bhttps:\/\/(greasyfork|sleazyfork)\.org\/scripts\/\d+\-[^\/]+\/code\/[^\.]+\.js\?version=\d+\b/, (_) => {
  1978. return fixLibraryCodeURL(_);
  1979. });
  1980. element.parentNode.insertBefore(document.createTextNode('\u200B'), element);
  1981. element.style.display = 'inline-flex';
  1982. setClickToSelect(element);
  1983. }
  1984.  
  1985.  
  1986. }
  1987.  
  1988.  
  1989.  
  1990.  
  1991. if (addAdditionInfoLengthHint && location.pathname.includes('/scripts/') && location.pathname.includes('/versions')) {
  1992.  
  1993. function contentLength(text) {
  1994. return text.replace(/\n/g, ' ').length;
  1995. }
  1996. function contentLengthMax() {
  1997. return 50000;
  1998. }
  1999. let _spanContent = null;
  2000. function updateText(ainfo, span) {
  2001. const value = ainfo.value;
  2002. if (typeof value !== 'string') return;
  2003.  
  2004. if (_spanContent !== value) {
  2005. _spanContent = value;
  2006. span.textContent = `Text Length: ${contentLength(value)} / ${contentLengthMax()}`;
  2007.  
  2008.  
  2009. }
  2010. }
  2011. function onChange(evt) {
  2012. let ainfo = (evt || 0).target;
  2013. if (!ainfo) return;
  2014. let span = ainfo.parentNode.querySelector('.script-version-ainfo-span');
  2015. if (!span) return;
  2016.  
  2017. updateText(ainfo, span);
  2018.  
  2019. }
  2020. function kbEvent(evt) {
  2021. Promise.resolve().then(() => {
  2022. onChange(evt);
  2023.  
  2024. })
  2025. }
  2026. for (const ainfo of document.querySelectorAll('textarea[id^="script-version-additional-info"]')) {
  2027. let span = document.createElement('span');
  2028. span.classList.add('script-version-ainfo-span');
  2029. ainfo.addEventListener('change', onChange, false);
  2030. ainfo.addEventListener('keydown', kbEvent, false);
  2031. ainfo.addEventListener('keypress', kbEvent, false);
  2032. ainfo.addEventListener('keyup', kbEvent, false);
  2033. updateText(ainfo, span);
  2034. ainfo.parentNode.insertBefore(span, ainfo.nextSibling);
  2035.  
  2036.  
  2037. }
  2038.  
  2039.  
  2040. }
  2041.  
  2042. } catch (e) {
  2043. console.log(e);
  2044. }
  2045.  
  2046.  
  2047.  
  2048. }
  2049.  
  2050.  
  2051.  
  2052.  
  2053. Promise.resolve().then(() => {
  2054. if (document.readyState !== 'loading') {
  2055. onReady();
  2056. } else {
  2057. window.addEventListener("DOMContentLoaded", onReady, false);
  2058. }
  2059. });
  2060.  
  2061. })();