Greasy Fork is available in English.

Greasyfork script-set-edit button

Add / Remove script into / from script set directly in GF script info page

Fra 12.07.2024. Se den seneste versjonen.

  1. /* eslint-disable no-multi-spaces */
  2. /* eslint-disable no-return-assign */
  3.  
  4. // ==UserScript==
  5. // @name Greasyfork script-set-edit button
  6. // @name:zh-CN Greasyfork 快捷编辑收藏
  7. // @name:zh-TW Greasyfork 快捷編輯收藏
  8. // @name:en Greasyfork script-set-edit button
  9. // @name:en-US Greasyfork script-set-edit button
  10. // @name:fr Greasyfork Set Edit+
  11. // @namespace Greasyfork-Favorite
  12. // @version 0.2.8.1
  13. // @description Add / Remove script into / from script set directly in GF script info page
  14. // @description:zh-CN 在GF脚本页直接编辑收藏集
  15. // @description:zh-TW 在GF腳本頁直接編輯收藏集
  16. // @description:en Add / Remove script into / from script set directly in GF script info page
  17. // @description:en-US Add / Remove script into / from script set directly in GF script info page
  18. // @description:fr Ajouter un script à un jeu de scripts / supprimer un script d'un jeu de scripts directement sur la page d'informations sur les scripts GF
  19. // @author PY-DNG
  20. // @license GPL-3.0-or-later
  21. // @match http*://*.greatest.deepsurf.us/*
  22. // @match http*://*.sleazyfork.org/*
  23. // @match http*://greatest.deepsurf.us/*
  24. // @match http*://sleazyfork.org/*
  25. // @require https://update.greatest.deepsurf.us/scripts/456034/1348286/Basic%20Functions%20%28For%20userscripts%29.js
  26. // @require https://update.greatest.deepsurf.us/scripts/449583/1324274/ConfigManager.js
  27. // @require https://greatest.deepsurf.us/scripts/460385-gm-web-hooks/code/script.js?version=1221394
  28. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAbBJREFUOE+Vk7GKGlEUhr8pAiKKDlqpCDpLUCzWBxCENBa+hBsL9wHsLWxXG4tNtcGH0MIiWopY7JSGEUWsbESwUDMw4Z7siLsZDbnlPff/7n/+e67G38sA6sAXIPVWXgA/gCdgfinRPuhfCoXCw3Q65XA4eLBl6zvw1S2eAZqmvTqOc5/NZhkMBqRSKWzbvgYxgbwquoAX4MGyLHK5HIlEgtFo9C+IOFEAo1gsWsvlUmyPx2MymYxAhsMh6XT6lpM7BXjWdf1xNpuRz+fl8GQywTAMGo0G1WpVnJxOJ692vinADPgcDAaZz+cCOR6PmKZJPB4XUb/fp1wuewF+KoBCf1JVBVE5dDodms3mWdDtdqlUKl6AX+8ALmS9XgtM0/5kvNlspKX9fv8RIgBp4bISCoXo9XqsVitKpRK6rrPb7STQ7XZ7eVRaeAYerz14OBxGOfL7/eIgmUwKzHEcJZEQ1eha1wBqPxqNihufzyeQWCzmtiPPqJYM0jWIyiISibBYLAgEAtTrdVqt1nmQXN0rcH/LicqmVqvRbrdN27bfjbKru+nk7ZD3Z7q4+b++82/YPKIrXsKZ3AAAAABJRU5ErkJggg==
  29. // @grant GM_xmlhttpRequest
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @grant GM_listValues
  33. // @grant GM_deleteValue
  34. // @grant GM_registerMenuCommand
  35. // @grant GM_unregisterMenuCommand
  36. // ==/UserScript==
  37.  
  38. /* global LogLevel DoLog Err $ $All $CrE $AEL $$CrE addStyle detectDom destroyEvent copyProp copyProps parseArgs escJsStr replaceText getUrlArgv dl_browser dl_GM AsyncManager queueTask testChecker registerChecker loadFuncs */
  39. /* global GMXHRHook GMDLHook ConfigManager */
  40.  
  41. const GFScriptSetAPI = (function() {
  42. const API = {
  43. async getScriptSets() {
  44. const userpage = API.getUserpage();
  45. const oDom = await API.getDocument(userpage);
  46.  
  47. const list = Array.from($(oDom, 'ul#user-script-sets').children);
  48. const NoSets = list.length === 1 && list.every(li => li.children.length === 1);
  49. const script_sets = NoSets ? [] : Array.from($(oDom, 'ul#user-script-sets').children).filter(li => li.children.length === 2).map(li => {
  50. try {
  51. return {
  52. name: li.children[0].innerText,
  53. link: li.children[0].href,
  54. linkedit: li.children[1].href,
  55. id: getUrlArgv(li.children[0].href, 'set')
  56. }
  57. } catch(err) {
  58. DoLog(LogLevel.Error, [li, err, li.children.length, li.children[0]?.innerHTML, li.children[1]?.innerHTML], 'error');
  59. Err(err);
  60. }
  61. });
  62.  
  63. return script_sets;
  64. },
  65.  
  66. async getSetScripts(url) {
  67. return [...$All(await API.getDocument(url), '#script-set-scripts>input[name="scripts-included[]"]')].map(input => input.value);
  68. },
  69.  
  70. /**
  71. * @typedef {Object} SetsDataAPI
  72. * @property {Response} resp - api fetch response object
  73. * @property {boolean} ok - resp.ok (resp.status >= 200 && resp.status <= 299)
  74. * @property {(Object|null)} data - api response json data, or null if not resp.ok
  75. */
  76. /**
  77. * @returns {SetsDataAPI}
  78. */
  79. async getSetsData() {
  80. const userpage = API.getUserpage();
  81. const url = (userpage.endsWith('/') ? userpage : userpage + '/') + 'sets'
  82.  
  83. const resp = await fetch(url, { credentials: 'same-origin' });
  84. if (resp.ok) {
  85. return {
  86. ok: true,
  87. resp,
  88. data: await resp.json()
  89. };
  90. } else {
  91. return {
  92. ok: false,
  93. resp,
  94. data: null
  95. };
  96. }
  97. },
  98.  
  99. /**
  100. * @returns {(string|null)} the user's profile page url, from page top-right link <a>.href
  101. */
  102. getUserpage() {
  103. const a = $('#nav-user-info>.user-profile-link>a');
  104. return a ? a.href : null;
  105. },
  106.  
  107. /**
  108. * @returns {(string|null)} the user's id, in string format
  109. */
  110. getUserID() {
  111. const userpage = API.getUserpage(); //https://greatest.deepsurf.us/zh-CN/users/667968-pyudng
  112. return userpage ? userpage.match(/\/users\/(\d+)(-[^\/]*\/*)?/)[1] : null;
  113. },
  114.  
  115. // editCallback recieves:
  116. // true: edit doc load success
  117. // false: already in set
  118. // finishCallback recieves:
  119. // text: successfully added to set with text tip `text`
  120. // true: successfully loaded document but no text tip found
  121. // false: xhr error
  122. addFav(url, sid, editCallback, finishCallback) {
  123. API.modifyFav(url, oDom => {
  124. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  125. if (existingInput) {
  126. editCallback(false);
  127. return false;
  128. }
  129.  
  130. const input = $CrE('input');
  131. input.value = sid;
  132. input.name = 'scripts-included[]';
  133. input.type = 'hidden';
  134. $(oDom, '#script-set-scripts').appendChild(input);
  135. editCallback(true);
  136. }, oDom => {
  137. const status = $(oDom, 'p.notice');
  138. const status_text = status ? status.innerText : true;
  139. finishCallback(status_text);
  140. }, err => finishCallback(false));
  141. },
  142.  
  143. // editCallback recieves:
  144. // true: edit doc load success
  145. // false: already not in set
  146. // finishCallback recieves:
  147. // text: successfully removed from set with text tip `text`
  148. // true: successfully loaded document but no text tip found
  149. // false: xhr error
  150. removeFav(url, sid, editCallback, finishCallback) {
  151. API.modifyFav(url, oDom => {
  152. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  153. if (!existingInput) {
  154. editCallback(false);
  155. return false;
  156. }
  157.  
  158. existingInput.remove();
  159. editCallback(true);
  160. }, oDom => {
  161. const status = $(oDom, 'p.notice');
  162. const status_text = status ? status.innerText : true;
  163. finishCallback(status_text);
  164. }, err => finishCallback(false));
  165. },
  166.  
  167. async modifyFav(url, editCallback, finishCallback, onerror) {
  168. const oDom = await API.getDocument(url);
  169. if (editCallback(oDom) === false) { return false; }
  170.  
  171. const form = $(oDom, '.change-script-set');
  172. const data = new FormData(form);
  173. data.append('save', '1');
  174.  
  175. // Use XMLHttpRequest insteadof GM_xmlhttpRequest because there's unknown issue with GM_xmlhttpRequest
  176. // Use XMLHttpRequest insteadof GM_xmlhttpRequest before Tampermonkey 5.0.0 because of FormData posting issues
  177. if (true || typeof GM_xmlhttpRequest !== 'function' || (GM_info.scriptHandler === 'Tampermonkey' && !API.GM_hasVersion('5.0'))) {
  178. const xhr = new XMLHttpRequest();
  179. xhr.open('POST', API.toAbsoluteURL(form.getAttribute('action')));
  180. xhr.responseType = 'blob';
  181. xhr.onload = async e => finishCallback(await API.parseDocument(xhr.response));
  182. xhr.onerror = onerror;
  183. xhr.send(data);
  184. } else {
  185. GM_xmlhttpRequest({
  186. method: 'POST',
  187. url: API.toAbsoluteURL(form.getAttribute('action')),
  188. data,
  189. responseType: 'blob',
  190. onload: async response => finishCallback(await API.parseDocument(response.response)),
  191. onerror
  192. });
  193. }
  194. },
  195.  
  196. // Download and parse a url page into a html document(dom).
  197. // Returns a promise fulfills with dom
  198. async getDocument(url, retry=5) {
  199. try {
  200. const response = await fetch(url, {
  201. method: 'GET',
  202. cache: 'reload',
  203. });
  204. if (response.status === 200) {
  205. const blob = await response.blob();
  206. const oDom = await API.parseDocument(blob);
  207. return oDom;
  208. } else {
  209. throw new Error(`response.status is not 200 (${response.status})`);
  210. }
  211. } catch(err) {
  212. if (--retry > 0) {
  213. return API.getDocument(url, retry);
  214. } else {
  215. throw err;
  216. }
  217. }
  218.  
  219. /*
  220. return new Promise((resolve, reject) => {
  221. GM_xmlhttpRequest({
  222. method : 'GET',
  223. url : url,
  224. responseType : 'blob',
  225. onload : function(response) {
  226. if (response.status === 200) {
  227. const htmlblob = response.response;
  228. API.parseDocument(htmlblob).then(resolve).catch(reject);
  229. } else {
  230. re(response);
  231. }
  232. },
  233. onerror: err => re(err)
  234. });
  235.  
  236. function re(err) {
  237. DoLog(`Get document failed, retrying: (${retry}) ${url}`);
  238. --retry > 0 ? API.getDocument(url, retry).then(resolve).catch(reject) : reject(err);
  239. }
  240. });
  241. */
  242. },
  243.  
  244. // Returns a promise fulfills with dom
  245. parseDocument(htmlblob) {
  246. return new Promise((resolve, reject) => {
  247. const reader = new FileReader();
  248. reader.onload = function(e) {
  249. const htmlText = reader.result;
  250. const dom = new DOMParser().parseFromString(htmlText, 'text/html');
  251. resolve(dom);
  252. }
  253. reader.onerror = err => reject(err);
  254. reader.readAsText(htmlblob, document.characterSet);
  255. });
  256. },
  257.  
  258. toAbsoluteURL(relativeURL, base=`${location.protocol}//${location.host}/`) {
  259. return new URL(relativeURL, base).href;
  260. },
  261.  
  262. GM_hasVersion(version) {
  263. return hasVersion(GM_info?.version || '0', version);
  264.  
  265. function hasVersion(ver1, ver2) {
  266. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  267.  
  268. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  269. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  270. function compareVersions(a, b) {
  271. if (a == b) {
  272. return 0;
  273. }
  274. let aParts = a.split('.');
  275. let bParts = b.split('.');
  276. for (let i = 0; i < aParts.length; i++) {
  277. let result = compareVersionPart(aParts[i], bParts[i]);
  278. if (result != 0) {
  279. return result;
  280. }
  281. }
  282. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  283. if (bParts.length > aParts.length) {
  284. return -1;
  285. }
  286. return 0;
  287. }
  288.  
  289. function compareVersionPart(partA, partB) {
  290. let partAParts = parseVersionPart(partA);
  291. let partBParts = parseVersionPart(partB);
  292. for (let i = 0; i < partAParts.length; i++) {
  293. // "A string-part that exists is always less than a string-part that doesn't exist"
  294. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  295. return -1;
  296. }
  297. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  298. return 1;
  299. }
  300. if (partAParts[i] > partBParts[i]) {
  301. return 1;
  302. }
  303. if (partAParts[i] < partBParts[i]) {
  304. return -1;
  305. }
  306. }
  307. return 0;
  308. }
  309.  
  310. // It goes number, string, number, string. If it doesn't exist, then
  311. // 0 for numbers, empty string for strings.
  312. function parseVersionPart(part) {
  313. if (!part) {
  314. return [0, "", 0, ""];
  315. }
  316. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  317. return [
  318. partParts[1] ? parseInt(partParts[1]) : 0,
  319. partParts[2],
  320. partParts[3] ? parseInt(partParts[3]) : 0,
  321. partParts[4]
  322. ];
  323. }
  324. }
  325. }
  326. };
  327.  
  328. return API;
  329. }) ();
  330.  
  331. (function __MAIN__() {
  332. 'use strict';
  333.  
  334. const CONST = {
  335. Text: {
  336. 'zh-CN': {
  337. FavEdit: '收藏集:',
  338. Add: '加入此集',
  339. Remove: '移出此集',
  340. Edit: '手动编辑',
  341. EditIframe: '页内编辑',
  342. CloseIframe: '关闭编辑',
  343. CopySID: '复制脚本ID',
  344. Sync: '同步',
  345. NotLoggedIn: '请先登录Greasyfork',
  346. NoSetsYet: '您还没有创建过收藏集',
  347. NewSet: '新建收藏集',
  348. Working: ['工作中...', '就快好了...'],
  349. InSetStatus: ['[ ]', '[✔]'],
  350. Groups: {
  351. Server: 'GreasyFork收藏集',
  352. Local: '本地收藏集',
  353. New: '新建'
  354. },
  355. Refreshing: {
  356. List: '获取收藏集列表...',
  357. Script: '获取收藏集内容...',
  358. Data: '获取收藏集数据...'
  359. },
  360. UseAPI: ['[ ] 使用GF的收藏集API', '[✔]使用GF的收藏集API'],
  361. Error: {
  362. AlreadyExist: '脚本已经在此收藏集中了',
  363. NotExist: '脚本不在此收藏集中',
  364. NetworkError: '网络错误',
  365. Unknown: '未知错误'
  366. }
  367. },
  368. 'zh-TW': {
  369. FavEdit: '收藏集:',
  370. Add: '加入此集',
  371. Remove: '移出此集',
  372. Edit: '手動編輯',
  373. EditIframe: '頁內編輯',
  374. CloseIframe: '關閉編輯',
  375. CopySID: '複製腳本ID',
  376. Sync: '同步',
  377. NotLoggedIn: '請先登錄Greasyfork',
  378. NoSetsYet: '您還沒有創建過收藏集',
  379. NewSet: '新建收藏集',
  380. Working: ['工作中...', '就快好了...'],
  381. InSetStatus: ['[ ]', '[✔]'],
  382. Groups: {
  383. Server: 'GreasyFork收藏集',
  384. Local: '本地收藏集',
  385. New: '新建'
  386. },
  387. Refreshing: {
  388. List: '獲取收藏集清單...',
  389. Script: '獲取收藏集內容...',
  390. Data: '獲取收藏集數據...'
  391. },
  392. UseAPI: ['[ ] 使用GF的收藏集API', '[✔]使用GF的收藏集API'],
  393. Error: {
  394. AlreadyExist: '腳本已經在此收藏集中了',
  395. NotExist: '腳本不在此收藏集中',
  396. NetworkError: '網絡錯誤',
  397. Unknown: '未知錯誤'
  398. }
  399. },
  400. 'en': {
  401. FavEdit: 'Script set: ',
  402. Add: 'Add',
  403. Remove: 'Remove',
  404. Edit: 'Edit Manually',
  405. EditIframe: 'In-Page Edit',
  406. CloseIframe: 'Close Editor',
  407. CopySID: 'Copy Script-ID',
  408. Sync: 'Sync',
  409. NotLoggedIn: 'Login to greasyfork to use script sets',
  410. NoSetsYet: 'You haven\'t created a collection yet',
  411. NewSet: 'Create a new set',
  412. Working: ['Working...', 'Just a moment...'],
  413. InSetStatus: ['[ ]', '[✔]'],
  414. Groups: {
  415. Server: 'GreasyFork',
  416. Local: 'Local',
  417. New: 'New'
  418. },
  419. Refreshing: {
  420. List: 'Fetching script sets...',
  421. Script: 'Fetching set content...',
  422. Data: 'Fetching script sets data...'
  423. },
  424. UseAPI: ['[ ] Use GF API', '[✔] Use GF API'],
  425. Error: {
  426. AlreadyExist: 'Script is already in set',
  427. NotExist: 'Script is not in set yet',
  428. NetworkError: 'Network Error',
  429. Unknown: 'Unknown Error'
  430. }
  431. },
  432. 'default': {
  433. FavEdit: 'Script set: ',
  434. Add: 'Add',
  435. Remove: 'Remove',
  436. Edit: 'Edit Manually',
  437. EditIframe: 'In-Page Edit',
  438. CloseIframe: 'Close Editor',
  439. CopySID: 'Copy Script-ID',
  440. Sync: 'Sync',
  441. NotLoggedIn: 'Login to greasyfork to use script sets',
  442. NoSetsYet: 'You haven\'t created a collection yet',
  443. NewSet: 'Create a new set',
  444. Working: ['Working...', 'Just a moment...'],
  445. InSetStatus: ['[ ]', '[✔]'],
  446. Groups: {
  447. Server: 'GreasyFork',
  448. Local: 'Local',
  449. New: 'New'
  450. },
  451. Refreshing: {
  452. List: 'Fetching script sets...',
  453. Script: 'Fetching set content...',
  454. Data: 'Fetching script sets data...'
  455. },
  456. UseAPI: ['[ ] Use GF API', '[✔] Use GF API'],
  457. Error: {
  458. AlreadyExist: 'Script is already in set',
  459. NotExist: 'Script is not in set yet',
  460. NetworkError: 'Network Error',
  461. Unknown: 'Unknown Error'
  462. }
  463. },
  464. },
  465. URL: {
  466. SetLink: 'https://greatest.deepsurf.us/scripts?set=$ID',
  467. SetEdit: 'https://greatest.deepsurf.us/users/$UID/sets/$ID/edit'
  468. },
  469. ConfigRule: {
  470. 'version-key': 'config-version',
  471. ignores: ['useAPI'],
  472. defaultValues: {
  473. 'script-sets': {
  474. sets: [],
  475. time: 0,
  476. 'config-version': 2,
  477. },
  478. 'useAPI': true
  479. },
  480. 'updaters': {
  481. /*'config-key': [
  482. function() {
  483. // This function contains updater for config['config-key'] from v0 to v1
  484. },
  485. function() {
  486. // This function contains updater for config['config-key'] from v1 to v2
  487. }
  488. ]*/
  489. 'script-sets': [
  490. config => {
  491. // v0 ==> v1
  492. // Fill set.id
  493. const sets = config.sets;
  494. sets.forEach(set => {
  495. const id = getUrlArgv(set.link, 'set');
  496. set.id = id;
  497. set.scripts = null; // After first refresh, it should be an array of SIDs:string
  498. });
  499.  
  500. // Delete old version identifier
  501. delete config.version;
  502.  
  503. return config;
  504. },
  505. /*config => {
  506. // v1 ==> v2
  507. return config
  508. }*/
  509. ]
  510. },
  511. }
  512. };
  513.  
  514. // Get i18n code
  515. let i18n = $('#language-selector-locale') ? $('#language-selector-locale').value : navigator.language;
  516. if (!Object.keys(CONST.Text).includes(i18n)) {i18n = 'default';}
  517.  
  518. const CM = new ConfigManager(CONST.ConfigRule);
  519. const CONFIG = CM.Config;
  520. CM.updateAllConfigs();
  521. debugger;
  522. CM.setDefaults();
  523.  
  524. loadFuncs([{
  525. name: 'Hook GM_xmlhttpRequest',
  526. checker: {
  527. type: 'switch',
  528. value: true
  529. },
  530. func: () => GMXHRHook(5)
  531. }, {
  532. name: 'Favorite panel',
  533. checker: {
  534. type: 'func',
  535. value: () => {
  536. const path = location.pathname.split('/').filter(p=>p);
  537. const index = path.indexOf('scripts');
  538. return [0,1].includes(index) && [undefined, 'code', 'feedback'].includes(path[index+2])
  539. }
  540. },
  541. func: addFavPanel
  542. }, {
  543. name: 'api-doc switch',
  544. checker: {
  545. type: 'switch',
  546. value: true
  547. },
  548. func: e => {
  549. makeBooleanSettings([{
  550. text: CONST.Text[i18n].UseAPI,
  551. key: 'useAPI',
  552. defaultValue: true
  553. }]);
  554. }
  555. }]);
  556.  
  557. function addFavPanel() {
  558. //if (!GFScriptSetAPI.getUserpage()) {return false;}
  559.  
  560. class FavoritePanel {
  561. #CM;
  562. #sid;
  563. #sets;
  564. #elements;
  565. #disabled;
  566.  
  567. constructor(CM) {
  568. this.#CM = CM;
  569. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  570. this.#sets = this.#CM.getConfig('script-sets').sets;
  571. this.#elements = {};
  572. this.disabled = false;
  573.  
  574. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  575. const script_parent = script_after.parentElement;
  576.  
  577. // Container
  578. const script_favorite = this.#elements.container = $$CrE({
  579. tagName: 'div',
  580. props: {
  581. id: 'script-favorite',
  582. innerHTML: CONST.Text[i18n].FavEdit
  583. },
  584. styles: { margin: '0.75em 0' }
  585. });
  586.  
  587. // Selecter
  588. const favorite_groups = this.#elements.select = $$CrE({
  589. tagName: 'select',
  590. props: { id: 'favorite-groups' },
  591. styles: { maxWidth: '40vw' },
  592. listeners: [['change', (() => {
  593. let lastSelected = 0;
  594. const record = () => lastSelected = favorite_groups.selectedIndex;
  595. const recover = () => favorite_groups.selectedIndex = lastSelected;
  596.  
  597. return e => {
  598. const value = favorite_groups.value;
  599. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  600.  
  601. switch (type) {
  602. case 'set-id': {
  603. const set = this.#sets.find(set => set.id === favorite_groups.value);
  604. favorite_edit.href = set.linkedit;
  605. break;
  606. }
  607. case 'command': {
  608. recover();
  609. this.#execCommand(value);
  610. }
  611. }
  612.  
  613. this.#refreshButtonDisplay();
  614. record();
  615. }
  616. }) ()]]
  617. });
  618. favorite_groups.id = 'favorite-groups';
  619.  
  620. // Buttons
  621. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  622. tagName: 'a',
  623. props: {
  624. id, innerHTML,
  625. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  626. },
  627. styles: { margin: '0px 0.5em' },
  628. listeners: [['click', onClick]]
  629. });
  630.  
  631. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text[i18n].Add, e => this.#addFav());
  632. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text[i18n].Remove, e => this.#removeFav());
  633. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text[i18n].Edit, e => {}, true);
  634. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text[i18n].EditIframe, e => this.#editInPage(e));
  635. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text[i18n].CopySID, e => copyText(this.#sid));
  636. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text[i18n].Sync, e => this.#refresh());
  637.  
  638. script_favorite.appendChild(favorite_groups);
  639. script_after.before(script_favorite);
  640. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  641.  
  642. // Text tip
  643. const tip = this.#elements.tip = $CrE('span');
  644. script_favorite.appendChild(tip);
  645.  
  646. // Display cached sets first
  647. this.#displaySets();
  648.  
  649. // Request GF document to update sets
  650. this.#autoRefresh();
  651. }
  652.  
  653. get sid() {
  654. return this.#sid;
  655. }
  656.  
  657. get sets() {
  658. return FavoritePanel.#deepClone(this.#sets);
  659. }
  660.  
  661. get elements() {
  662. return FavoritePanel.#lightClone(this.#elements);
  663. }
  664.  
  665. #refresh() {
  666. const that = this;
  667. const method = CONFIG.useAPI ? 'api' : 'doc';
  668. return {
  669. api: () => this.#refresh_api(),
  670. doc: () => this.#refresh_doc()
  671. }[method]();
  672. }
  673.  
  674. async #refresh_api() {
  675. const CONFIG = this.#CM.Config;
  676.  
  677. this.#disable();
  678. this.#tip(CONST.Text[i18n].Refreshing.Data);
  679.  
  680. // Check login status
  681. if (!GFScriptSetAPI.getUserpage()) {
  682. this.#tip(CONST.Text[i18n].NotLoggedIn);
  683. return;
  684. }
  685.  
  686. // Request sets data api
  687. const api_result = await GFScriptSetAPI.getSetsData();
  688. const sets_data = api_result.data;
  689. const uid = GFScriptSetAPI.getUserID();
  690.  
  691. if (!api_result.ok) {
  692. // When api fails, use doc as fallback
  693. DoLog(LogLevel.Error, 'Sets API failed.');
  694. DoLog(LogLevel.Error, api_result);
  695. return this.#refresh_doc();
  696. }
  697.  
  698. // For forward compatibility, convert all setids and scriptids to string
  699. // and fill property set.link and set.linkedit
  700. for (const set of sets_data) {
  701. // convert set id to string
  702. set.id = set.id.toString();
  703. // https://greatest.deepsurf.us/zh-CN/scripts?set=439237
  704. set.link = replaceText(CONST.URL.SetLink, { $ID: set.id });
  705. // https://greatest.deepsurf.us/zh-CN/users/667968-pyudng/sets/439237/edit
  706. set.linkedit = replaceText(CONST.URL.SetEdit, { $UID: uid, $ID: set.id });
  707.  
  708. // there's two kind of sets: Favorite and non-favorite
  709. // favorite set's data is an array of object, where each object represents a script, with script's properties
  710. // non-favorite set's data is an array of ints, where each int means a script's id
  711. // For forward compatibility, we only store script ids, in string format
  712. set.scripts.forEach((script, i, scripts) => {
  713. if (typeof script === 'number') {
  714. scripts[i] = script.toString();
  715. } else {
  716. scripts[i] = script.id.toString();
  717. }
  718. });
  719. }
  720.  
  721. this.#sets = CONFIG['script-sets'].sets = sets_data;
  722. CONFIG['script-sets'].time = Date.now();
  723.  
  724. this.#tip();
  725. this.#enable();
  726. this.#displaySets();
  727. this.#refreshButtonDisplay();
  728. }
  729.  
  730. // Request document: get sets list and
  731. async #refresh_doc() {
  732. const CONFIG = this.#CM.Config;
  733.  
  734. this.#disable();
  735. this.#tip(CONST.Text[i18n].Refreshing.List);
  736.  
  737. // Check login status
  738. if (!GFScriptSetAPI.getUserpage()) {
  739. this.#tip(CONST.Text[i18n].NotLoggedIn);
  740. return;
  741. }
  742.  
  743. // Refresh sets list
  744. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  745. CONFIG['script-sets'].time = Date.now();
  746. this.#displaySets();
  747.  
  748. // Refresh each set's script list
  749. this.#tip(CONST.Text[i18n].Refreshing.Script);
  750. await Promise.all(this.#sets.map(async set => {
  751. // Fetch scripts
  752. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  753. this.#displaySets();
  754.  
  755. // Save to GM_storage
  756. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  757. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  758. CONFIG['script-sets'].time = Date.now();
  759. }));
  760.  
  761. this.#tip();
  762. this.#enable();
  763. this.#refreshButtonDisplay();
  764. }
  765.  
  766. // Refresh on instance creation.
  767. // This should be running in low-frequecy. Refreshing makes lots of requests which may resul in a 503 error(rate limit) for the user.
  768. #autoRefresh(minTime=1*24*60*60*1000) {
  769. const CONFIG = this.#CM.Config;
  770. const lastRefresh = new Date(CONFIG['script-sets'].time);
  771. if (Date.now() - lastRefresh > minTime) {
  772. this.#refresh();
  773. return true;
  774. } else {
  775. return false;
  776. }
  777. }
  778.  
  779. #addFav() {
  780. const set = this.#getCurrentSet();
  781. const option = set.elmOption;
  782.  
  783. this.#displayNotice(CONST.Text[i18n].Working[0]);
  784. let needRefresh = false;
  785. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  786. if (!editStatus) {
  787. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  788. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  789. } else {
  790. this.#displayNotice(CONST.Text[i18n].Working[1]);
  791. }
  792. }, finishStatus => {
  793. if (finishStatus) {
  794. // Save to this.#sets and GM_storage
  795. if (needRefresh || CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  796. // If scripts property is missing, do sync(refresh)
  797. needRefresh = true;
  798. } else {
  799. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  800. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  801. this.#sets = CM.getConfig('script-sets').sets;
  802. }
  803.  
  804. // Display
  805. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  806. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  807. this.#displaySets();
  808. } else {
  809. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  810. }
  811. });
  812.  
  813. needRefresh && this.#refresh();
  814. }
  815.  
  816. #removeFav() {
  817. const set = this.#getCurrentSet();
  818. const option = set.elmOption;
  819.  
  820. this.#displayNotice(CONST.Text[i18n].Working[0]);
  821. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  822. if (!editStatus) {
  823. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  824. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  825. } else {
  826. this.#displayNotice(CONST.Text[i18n].Working[1]);
  827. }
  828. }, finishStatus => {
  829. if (finishStatus) {
  830. // Save to this.#sets and GM_storage
  831. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  832. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  833. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  834. this.#sets = CM.getConfig('script-sets').sets;
  835.  
  836. // Display
  837. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  838. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  839. this.#displaySets();
  840. } else {
  841. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  842. }
  843. });
  844. }
  845.  
  846. #editInPage(e) {
  847. e.preventDefault();
  848.  
  849. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  850. if (_iframes.length) {
  851. // Iframe exists, close iframe
  852. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  853. _iframes.forEach(ifr => ifr.remove());
  854. this.#refresh();
  855. } else {
  856. // Iframe not exist, make iframe
  857. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  858.  
  859. const iframe = $$CrE({
  860. tagName: 'iframe',
  861. props: {
  862. src: this.#getCurrentSet().linkedit
  863. },
  864. styles: {
  865. width: '100%',
  866. height: '60vh'
  867. },
  868. classes: ['script-edit-page'],
  869. listeners: [['load', e => {
  870. //this.#refresh();
  871. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  872. }]]
  873. });
  874. this.#elements.container.appendChild(iframe);
  875. }
  876. }
  877.  
  878. #displayNotice(text) {
  879. const notice = $CrE('p');
  880. notice.classList.add('notice');
  881. notice.id = 'fav-notice';
  882. notice.innerText = text;
  883. const old_notice = $('#fav-notice');
  884. old_notice && old_notice.parentElement.removeChild(old_notice);
  885. $('#script-content').insertAdjacentElement('afterbegin', notice);
  886. }
  887.  
  888. #tip(text='', timeout=0) {
  889. this.#elements.tip.innerText = text;
  890. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  891. }
  892.  
  893. // Apply this.#sets to gui
  894. #displaySets() {
  895. const elements = this.#elements;
  896.  
  897. // Save selected set
  898. const old_value = elements.select.value;
  899. [...elements.select.children].forEach(child => child.remove());
  900.  
  901. // Make <optgroup>s and <option>s
  902. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  903. this.#sets.forEach(set => {
  904. // Create <option>
  905. set.elmOption = $$CrE({
  906. tagName: 'option',
  907. props: {
  908. innerText: set.name,
  909. value: set.id
  910. }
  911. });
  912. // Display inset status
  913. if (set.scripts) {
  914. const inSet = set.scripts.includes(this.#sid);
  915. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  916. }
  917. // Append <option> into <select>
  918. serverGroup.appendChild(set.elmOption);
  919. });
  920. if (this.#sets.length === 0) {
  921. const optEmpty = elements.optEmpty = $$CrE({
  922. tagName: 'option',
  923. props: {
  924. innerText: CONST.Text[i18n].NoSetsYet,
  925. value: 'empty',
  926. selected: true
  927. }
  928. });
  929. serverGroup.appendChild(optEmpty);
  930. }
  931.  
  932. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  933. const newSet = elements.newSet = $$CrE({
  934. tagName: 'option',
  935. props: {
  936. innerText: CONST.Text[i18n].NewSet,
  937. value: 'new',
  938. }
  939. });
  940. newGroup.appendChild(newSet);
  941. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  942.  
  943. // Adjust <select> width
  944. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  945.  
  946. // Select previous selected set's <option>
  947. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  948. selected && (selected.selected = true);
  949.  
  950. // Set edit-button.href
  951. if (elements.select.value !== 'empty') {
  952. const curset = this.#sets.find(set => set.id === elements.select.value);
  953. elements.btnEdit.href = curset.linkedit;
  954. }
  955.  
  956. // Display correct button
  957. this.#refreshButtonDisplay();
  958. }
  959.  
  960. // Display only add button when script in current set, otherwise remove button
  961. // Disable set-related buttons when not selecting options that not represents a set
  962. #refreshButtonDisplay() {
  963. const set = this.#getCurrentSet();
  964. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  965. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  966. if (!set || !set.scripts) { return null; }
  967. if (set.scripts.includes(this.#sid)) {
  968. this.#elements.btnAdd.style.setProperty('display', 'none');
  969. this.#elements.btnRemove.style.removeProperty('display');
  970. return true;
  971. } else {
  972. this.#elements.btnRemove.style.setProperty('display', 'none');
  973. this.#elements.btnAdd.style.removeProperty('display');
  974. return false;
  975. }
  976. }
  977.  
  978. #execCommand(command) {
  979. switch (command) {
  980. case 'new': {
  981. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  982. window.open(url);
  983. break;
  984. }
  985. case 'empty': {
  986. // Do nothing
  987. break;
  988. }
  989. }
  990. }
  991.  
  992. // Returns null if no <option>s yet
  993. #getCurrentSet() {
  994. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  995. }
  996.  
  997. #disable() {
  998. [
  999. this.#elements.select,
  1000. this.#elements.btnAdd, this.#elements.btnRemove,
  1001. this.#elements.btnEdit, this.#elements.btnIframe,
  1002. this.#elements.btnCopy, this.#elements.btnSync
  1003. ].forEach(element => FavoritePanel.#disableElement(element));
  1004. this.#disabled = true;
  1005. }
  1006.  
  1007. #enable() {
  1008. [
  1009. this.#elements.select,
  1010. this.#elements.btnAdd, this.#elements.btnRemove,
  1011. this.#elements.btnEdit, this.#elements.btnIframe,
  1012. this.#elements.btnCopy, this.#elements.btnSync
  1013. ].forEach(element => FavoritePanel.#enableElement(element));
  1014. this.#disabled = false;
  1015. }
  1016.  
  1017. static #disableElement(element) {
  1018. element.style.filter = 'grayscale(1) brightness(0.95)';
  1019. element.style.opacity = '0.25';
  1020. element.style.pointerEvents = 'none';
  1021. element.tabIndex = -1;
  1022. }
  1023.  
  1024. static #enableElement(element) {
  1025. element.style.removeProperty('filter');
  1026. element.style.removeProperty('opacity');
  1027. element.style.removeProperty('pointer-events');
  1028. element.tabIndex = 0;
  1029. }
  1030.  
  1031. static #deepClone(val) {
  1032. if (typeof structuredClone === 'function') {
  1033. return structuredClone(val);
  1034. } else {
  1035. return JSON.parse(JSON.stringify(val));
  1036. }
  1037. }
  1038.  
  1039. static #lightClone(val) {
  1040. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  1041. return val;
  1042. }
  1043. if (Array.isArray(val)) {
  1044. return val.slice();
  1045. }
  1046. if (typeof val === 'object') {
  1047. return Object.fromEntries(Object.entries(val));
  1048. }
  1049. }
  1050. }
  1051.  
  1052. const panel = new FavoritePanel(CM);
  1053. }
  1054.  
  1055. // Basic functions
  1056. function makeBooleanSettings(settings) {
  1057. for (const setting of settings) {
  1058. makeBooleanMenu(setting.text, setting.key, setting.defaultValue, setting.callback, setting.initCallback);
  1059. }
  1060.  
  1061. function makeBooleanMenu(texts, key, defaultValue=false, callback=null, initCallback=false) {
  1062. const initialVal = GM_getValue(key, defaultValue);
  1063. const initialText = texts[initialVal + 0];
  1064. let id = makeMenu(initialText, onClick);
  1065. initCallback && callback(key, initialVal);
  1066.  
  1067. function onClick() {
  1068. const newValue = !GM_getValue(key, defaultValue);
  1069. const newText = texts[newValue + 0];
  1070. GM_setValue(key, newValue);
  1071. id = makeMenu(newText, onClick, id);
  1072. typeof callback === 'function' && callback(key, newValue);
  1073. }
  1074.  
  1075. function makeMenu(text, func, id) {
  1076. if (GM_info.scriptHandler === 'Tampermonkey' && GM_hasVersion('5.0')) {
  1077. return GM_registerMenuCommand(text, func, {
  1078. id,
  1079. autoClose: false,
  1080. });
  1081. } else {
  1082. GM_unregisterMenuCommand(id);
  1083. return GM_registerMenuCommand(text, func);
  1084. }
  1085. }
  1086. }
  1087.  
  1088. function GM_hasVersion(version) {
  1089. return hasVersion(GM_info?.version || '0', version);
  1090.  
  1091. function hasVersion(ver1, ver2) {
  1092. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  1093.  
  1094. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  1095. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  1096. function compareVersions(a, b) {
  1097. if (a == b) {
  1098. return 0;
  1099. }
  1100. let aParts = a.split('.');
  1101. let bParts = b.split('.');
  1102. for (let i = 0; i < aParts.length; i++) {
  1103. let result = compareVersionPart(aParts[i], bParts[i]);
  1104. if (result != 0) {
  1105. return result;
  1106. }
  1107. }
  1108. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  1109. if (bParts.length > aParts.length) {
  1110. return -1;
  1111. }
  1112. return 0;
  1113. }
  1114.  
  1115. function compareVersionPart(partA, partB) {
  1116. let partAParts = parseVersionPart(partA);
  1117. let partBParts = parseVersionPart(partB);
  1118. for (let i = 0; i < partAParts.length; i++) {
  1119. // "A string-part that exists is always less than a string-part that doesn't exist"
  1120. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  1121. return -1;
  1122. }
  1123. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  1124. return 1;
  1125. }
  1126. if (partAParts[i] > partBParts[i]) {
  1127. return 1;
  1128. }
  1129. if (partAParts[i] < partBParts[i]) {
  1130. return -1;
  1131. }
  1132. }
  1133. return 0;
  1134. }
  1135.  
  1136. // It goes number, string, number, string. If it doesn't exist, then
  1137. // 0 for numbers, empty string for strings.
  1138. function parseVersionPart(part) {
  1139. if (!part) {
  1140. return [0, "", 0, ""];
  1141. }
  1142. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  1143. return [
  1144. partParts[1] ? parseInt(partParts[1]) : 0,
  1145. partParts[2],
  1146. partParts[3] ? parseInt(partParts[3]) : 0,
  1147. partParts[4]
  1148. ];
  1149. }
  1150. }
  1151. }
  1152. }
  1153.  
  1154. // Copy text to clipboard (needs to be called in an user event)
  1155. function copyText(text) {
  1156. // Create a new textarea for copying
  1157. const newInput = document.createElement('textarea');
  1158. document.body.appendChild(newInput);
  1159. newInput.value = text;
  1160. newInput.select();
  1161. document.execCommand('copy');
  1162. document.body.removeChild(newInput);
  1163. }
  1164. })();