Greasyfork script-set-edit button

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

As of 2024-07-16. See the latest version.

  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.8
  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. CM.setDefaults();
  522.  
  523. loadFuncs([{
  524. name: 'Hook GM_xmlhttpRequest',
  525. checker: {
  526. type: 'switch',
  527. value: true
  528. },
  529. func: () => GMXHRHook(5)
  530. }, {
  531. name: 'Favorite panel',
  532. checker: {
  533. type: 'func',
  534. value: () => {
  535. const path = location.pathname.split('/').filter(p=>p);
  536. const index = path.indexOf('scripts');
  537. return [0,1].includes(index) && [undefined, 'code', 'feedback'].includes(path[index+2])
  538. }
  539. },
  540. func: addFavPanel
  541. }, {
  542. name: 'api-doc switch',
  543. checker: {
  544. type: 'switch',
  545. value: true
  546. },
  547. func: e => {
  548. makeBooleanSettings([{
  549. text: CONST.Text[i18n].UseAPI,
  550. key: 'useAPI',
  551. defaultValue: true
  552. }]);
  553. }
  554. }]);
  555.  
  556. function addFavPanel() {
  557. //if (!GFScriptSetAPI.getUserpage()) {return false;}
  558.  
  559. class FavoritePanel {
  560. #CM;
  561. #sid;
  562. #sets;
  563. #elements;
  564. #disabled;
  565.  
  566. constructor(CM) {
  567. this.#CM = CM;
  568. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  569. this.#sets = this.#CM.getConfig('script-sets').sets;
  570. this.#elements = {};
  571. this.disabled = false;
  572.  
  573. // Sort sets by name in alphabetical order
  574. FavoritePanel.#sortSetsdata(this.#sets);
  575.  
  576. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  577. const script_parent = script_after.parentElement;
  578.  
  579. // Container
  580. const script_favorite = this.#elements.container = $$CrE({
  581. tagName: 'div',
  582. props: {
  583. id: 'script-favorite',
  584. innerHTML: CONST.Text[i18n].FavEdit
  585. },
  586. styles: { margin: '0.75em 0' }
  587. });
  588.  
  589. // Selecter
  590. const favorite_groups = this.#elements.select = $$CrE({
  591. tagName: 'select',
  592. props: { id: 'favorite-groups' },
  593. styles: { maxWidth: '40vw' },
  594. listeners: [['change', (() => {
  595. let lastSelected = 0;
  596. const record = () => lastSelected = favorite_groups.selectedIndex;
  597. const recover = () => favorite_groups.selectedIndex = lastSelected;
  598.  
  599. return e => {
  600. const value = favorite_groups.value;
  601. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  602.  
  603. switch (type) {
  604. case 'set-id': {
  605. const set = this.#sets.find(set => set.id === favorite_groups.value);
  606. favorite_edit.href = set.linkedit;
  607. break;
  608. }
  609. case 'command': {
  610. recover();
  611. this.#execCommand(value);
  612. }
  613. }
  614.  
  615. this.#refreshButtonDisplay();
  616. record();
  617. }
  618. }) ()]]
  619. });
  620. favorite_groups.id = 'favorite-groups';
  621.  
  622. // Buttons
  623. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  624. tagName: 'a',
  625. props: {
  626. id, innerHTML,
  627. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  628. },
  629. styles: { margin: '0px 0.5em' },
  630. listeners: [['click', onClick]]
  631. });
  632.  
  633. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text[i18n].Add, e => this.#addFav());
  634. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text[i18n].Remove, e => this.#removeFav());
  635. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text[i18n].Edit, e => {}, true);
  636. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text[i18n].EditIframe, e => this.#editInPage(e));
  637. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text[i18n].CopySID, e => copyText(this.#sid));
  638. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text[i18n].Sync, e => this.#refresh());
  639.  
  640. script_favorite.appendChild(favorite_groups);
  641. script_after.before(script_favorite);
  642. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  643.  
  644. // Text tip
  645. const tip = this.#elements.tip = $CrE('span');
  646. script_favorite.appendChild(tip);
  647.  
  648. // Display cached sets first
  649. this.#displaySets();
  650.  
  651. // Request GF document to update sets
  652. this.#autoRefresh();
  653. }
  654.  
  655. get sid() {
  656. return this.#sid;
  657. }
  658.  
  659. get sets() {
  660. return FavoritePanel.#deepClone(this.#sets);
  661. }
  662.  
  663. get elements() {
  664. return FavoritePanel.#lightClone(this.#elements);
  665. }
  666.  
  667. #refresh() {
  668. const that = this;
  669. const method = CONFIG.useAPI ? 'api' : 'doc';
  670. return {
  671. api: () => this.#refresh_api(),
  672. doc: () => this.#refresh_doc()
  673. }[method]();
  674. }
  675.  
  676. async #refresh_api() {
  677. const CONFIG = this.#CM.Config;
  678.  
  679. this.#disable();
  680. this.#tip(CONST.Text[i18n].Refreshing.Data);
  681.  
  682. // Check login status
  683. if (!GFScriptSetAPI.getUserpage()) {
  684. this.#tip(CONST.Text[i18n].NotLoggedIn);
  685. return;
  686. }
  687.  
  688. // Request sets data api
  689. const api_result = await GFScriptSetAPI.getSetsData();
  690. const sets_data = api_result.data;
  691. const uid = GFScriptSetAPI.getUserID();
  692.  
  693. if (!api_result.ok) {
  694. // When api fails, use doc as fallback
  695. DoLog(LogLevel.Error, 'Sets API failed.');
  696. DoLog(LogLevel.Error, api_result);
  697. return this.#refresh_doc();
  698. }
  699.  
  700. // For forward compatibility, convert all setids and scriptids to string
  701. // and fill property set.link and set.linkedit
  702. for (const set of sets_data) {
  703. // convert set id to string
  704. set.id = set.id.toString();
  705. // https://greatest.deepsurf.us/zh-CN/scripts?set=439237
  706. set.link = replaceText(CONST.URL.SetLink, { $ID: set.id });
  707. // https://greatest.deepsurf.us/zh-CN/users/667968-pyudng/sets/439237/edit
  708. set.linkedit = replaceText(CONST.URL.SetEdit, { $UID: uid, $ID: set.id });
  709.  
  710. // there's two kind of sets: Favorite and non-favorite
  711. // favorite set's data is an array of object, where each object represents a script, with script's properties
  712. // non-favorite set's data is an array of ints, where each int means a script's id
  713. // For forward compatibility, we only store script ids, in string format
  714. set.scripts.forEach((script, i, scripts) => {
  715. if (typeof script === 'number') {
  716. scripts[i] = script.toString();
  717. } else {
  718. scripts[i] = script.id.toString();
  719. }
  720. });
  721. }
  722.  
  723. // Sort sets by name in alphabetical order
  724. FavoritePanel.#sortSetsdata(sets_data);
  725.  
  726. this.#sets = CONFIG['script-sets'].sets = sets_data;
  727. CONFIG['script-sets'].time = Date.now();
  728.  
  729. this.#tip();
  730. this.#enable();
  731. this.#displaySets();
  732. this.#refreshButtonDisplay();
  733. }
  734.  
  735. // Request document: get sets list and
  736. async #refresh_doc() {
  737. const CONFIG = this.#CM.Config;
  738.  
  739. this.#disable();
  740. this.#tip(CONST.Text[i18n].Refreshing.List);
  741.  
  742. // Check login status
  743. if (!GFScriptSetAPI.getUserpage()) {
  744. this.#tip(CONST.Text[i18n].NotLoggedIn);
  745. return;
  746. }
  747.  
  748. // Refresh sets list
  749. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  750. CONFIG['script-sets'].time = Date.now();
  751. this.#displaySets();
  752.  
  753. // Refresh each set's script list
  754. this.#tip(CONST.Text[i18n].Refreshing.Script);
  755. await Promise.all(this.#sets.map(async set => {
  756. // Fetch scripts
  757. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  758. this.#displaySets();
  759.  
  760. // Save to GM_storage
  761. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  762. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  763. CONFIG['script-sets'].time = Date.now();
  764. }));
  765.  
  766. this.#tip();
  767. this.#enable();
  768. this.#refreshButtonDisplay();
  769. }
  770.  
  771. // Refresh on instance creation.
  772. // This should be running in low-frequecy. Refreshing makes lots of requests which may resul in a 503 error(rate limit) for the user.
  773. #autoRefresh(minTime=1*24*60*60*1000) {
  774. const CONFIG = this.#CM.Config;
  775. const lastRefresh = new Date(CONFIG['script-sets'].time);
  776. if (Date.now() - lastRefresh > minTime) {
  777. this.#refresh();
  778. return true;
  779. } else {
  780. return false;
  781. }
  782. }
  783.  
  784. #addFav() {
  785. const set = this.#getCurrentSet();
  786. const option = set.elmOption;
  787.  
  788. this.#displayNotice(CONST.Text[i18n].Working[0]);
  789. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  790. if (!editStatus) {
  791. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  792. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  793. } else {
  794. this.#displayNotice(CONST.Text[i18n].Working[1]);
  795. }
  796. }, finishStatus => {
  797. if (finishStatus) {
  798. // Save to this.#sets and GM_storage
  799. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  800. // If scripts property is missing, do sync(refresh)
  801. this.#refresh();
  802. } else {
  803. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  804. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  805. this.#sets = CM.getConfig('script-sets').sets;
  806. }
  807.  
  808. // Display
  809. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  810. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  811. this.#displaySets();
  812. } else {
  813. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  814. }
  815. });
  816. }
  817.  
  818. #removeFav() {
  819. const set = this.#getCurrentSet();
  820. const option = set.elmOption;
  821.  
  822. this.#displayNotice(CONST.Text[i18n].Working[0]);
  823. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  824. if (!editStatus) {
  825. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  826. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  827. } else {
  828. this.#displayNotice(CONST.Text[i18n].Working[1]);
  829. }
  830. }, finishStatus => {
  831. if (finishStatus) {
  832. // Save to this.#sets and GM_storage
  833. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  834. // If scripts property is missing, do sync(refresh)
  835. this.#refresh();
  836. } else {
  837. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  838. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  839. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  840. this.#sets = CM.getConfig('script-sets').sets;
  841. }
  842.  
  843. // Display
  844. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  845. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  846. this.#displaySets();
  847. } else {
  848. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  849. }
  850. });
  851. }
  852.  
  853. #editInPage(e) {
  854. e.preventDefault();
  855.  
  856. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  857. if (_iframes.length) {
  858. // Iframe exists, close iframe
  859. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  860. _iframes.forEach(ifr => ifr.remove());
  861. this.#refresh();
  862. } else {
  863. // Iframe not exist, make iframe
  864. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  865.  
  866. const iframe = $$CrE({
  867. tagName: 'iframe',
  868. props: {
  869. src: this.#getCurrentSet().linkedit
  870. },
  871. styles: {
  872. width: '100%',
  873. height: '60vh'
  874. },
  875. classes: ['script-edit-page'],
  876. listeners: [['load', e => {
  877. //this.#refresh();
  878. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  879. }]]
  880. });
  881. this.#elements.container.appendChild(iframe);
  882. }
  883. }
  884.  
  885. #displayNotice(text) {
  886. const notice = $CrE('p');
  887. notice.classList.add('notice');
  888. notice.id = 'fav-notice';
  889. notice.innerText = text;
  890. const old_notice = $('#fav-notice');
  891. old_notice && old_notice.parentElement.removeChild(old_notice);
  892. $('#script-content').insertAdjacentElement('afterbegin', notice);
  893. }
  894.  
  895. #tip(text='', timeout=0) {
  896. this.#elements.tip.innerText = text;
  897. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  898. }
  899.  
  900. // Apply this.#sets to gui
  901. #displaySets() {
  902. const elements = this.#elements;
  903.  
  904. // Save selected set
  905. const old_value = elements.select.value;
  906. [...elements.select.children].forEach(child => child.remove());
  907.  
  908. // Make <optgroup>s and <option>s
  909. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  910. this.#sets.forEach(set => {
  911. // Create <option>
  912. set.elmOption = $$CrE({
  913. tagName: 'option',
  914. props: {
  915. innerText: set.name,
  916. value: set.id
  917. }
  918. });
  919. // Display inset status
  920. if (set.scripts) {
  921. const inSet = set.scripts.includes(this.#sid);
  922. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  923. }
  924. // Append <option> into <select>
  925. serverGroup.appendChild(set.elmOption);
  926. });
  927. if (this.#sets.length === 0) {
  928. const optEmpty = elements.optEmpty = $$CrE({
  929. tagName: 'option',
  930. props: {
  931. innerText: CONST.Text[i18n].NoSetsYet,
  932. value: 'empty',
  933. selected: true
  934. }
  935. });
  936. serverGroup.appendChild(optEmpty);
  937. }
  938.  
  939. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  940. const newSet = elements.newSet = $$CrE({
  941. tagName: 'option',
  942. props: {
  943. innerText: CONST.Text[i18n].NewSet,
  944. value: 'new',
  945. }
  946. });
  947. newGroup.appendChild(newSet);
  948. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  949.  
  950. // Adjust <select> width
  951. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  952.  
  953. // Select previous selected set's <option>
  954. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  955. selected && (selected.selected = true);
  956.  
  957. // Set edit-button.href
  958. if (elements.select.value !== 'empty') {
  959. const curset = this.#sets.find(set => set.id === elements.select.value);
  960. elements.btnEdit.href = curset.linkedit;
  961. }
  962.  
  963. // Display correct button
  964. this.#refreshButtonDisplay();
  965. }
  966.  
  967. // Display only add button when script in current set, otherwise remove button
  968. // Disable set-related buttons when not selecting options that not represents a set
  969. #refreshButtonDisplay() {
  970. const set = this.#getCurrentSet();
  971. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  972. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  973. if (!set || !set.scripts) { return null; }
  974. if (set.scripts.includes(this.#sid)) {
  975. this.#elements.btnAdd.style.setProperty('display', 'none');
  976. this.#elements.btnRemove.style.removeProperty('display');
  977. return true;
  978. } else {
  979. this.#elements.btnRemove.style.setProperty('display', 'none');
  980. this.#elements.btnAdd.style.removeProperty('display');
  981. return false;
  982. }
  983. }
  984.  
  985. #execCommand(command) {
  986. switch (command) {
  987. case 'new': {
  988. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  989. window.open(url);
  990. break;
  991. }
  992. case 'empty': {
  993. // Do nothing
  994. break;
  995. }
  996. }
  997. }
  998.  
  999. // Returns null if no <option>s yet
  1000. #getCurrentSet() {
  1001. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  1002. }
  1003.  
  1004. #disable() {
  1005. [
  1006. this.#elements.select,
  1007. this.#elements.btnAdd, this.#elements.btnRemove,
  1008. this.#elements.btnEdit, this.#elements.btnIframe,
  1009. this.#elements.btnCopy, this.#elements.btnSync
  1010. ].forEach(element => FavoritePanel.#disableElement(element));
  1011. this.#disabled = true;
  1012. }
  1013.  
  1014. #enable() {
  1015. [
  1016. this.#elements.select,
  1017. this.#elements.btnAdd, this.#elements.btnRemove,
  1018. this.#elements.btnEdit, this.#elements.btnIframe,
  1019. this.#elements.btnCopy, this.#elements.btnSync
  1020. ].forEach(element => FavoritePanel.#enableElement(element));
  1021. this.#disabled = false;
  1022. }
  1023.  
  1024. static #disableElement(element) {
  1025. element.style.filter = 'grayscale(1) brightness(0.95)';
  1026. element.style.opacity = '0.25';
  1027. element.style.pointerEvents = 'none';
  1028. element.tabIndex = -1;
  1029. }
  1030.  
  1031. static #enableElement(element) {
  1032. element.style.removeProperty('filter');
  1033. element.style.removeProperty('opacity');
  1034. element.style.removeProperty('pointer-events');
  1035. element.tabIndex = 0;
  1036. }
  1037.  
  1038. static #deepClone(val) {
  1039. if (typeof structuredClone === 'function') {
  1040. return structuredClone(val);
  1041. } else {
  1042. return JSON.parse(JSON.stringify(val));
  1043. }
  1044. }
  1045.  
  1046. static #lightClone(val) {
  1047. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  1048. return val;
  1049. }
  1050. if (Array.isArray(val)) {
  1051. return val.slice();
  1052. }
  1053. if (typeof val === 'object') {
  1054. return Object.fromEntries(Object.entries(val));
  1055. }
  1056. }
  1057.  
  1058. static #sortSetsdata(sets_data) {
  1059. // Sort sets by name in alphabetical order
  1060. const sorted_names = sets_data.map(set => set.name).sort();
  1061. if (sorted_names.includes('Favorite')) {
  1062. // Keep set `Favorite` at first place
  1063. sorted_names.splice(0, 0, sorted_names.splice(sorted_names.indexOf('Favorite'), 1)[0]);
  1064. }
  1065. sets_data.sort((setA, setB) => sorted_names.indexOf(setA.name) - sorted_names.indexOf(setB.name));
  1066. }
  1067. }
  1068.  
  1069. const panel = new FavoritePanel(CM);
  1070. }
  1071.  
  1072. // Basic functions
  1073. function makeBooleanSettings(settings) {
  1074. for (const setting of settings) {
  1075. makeBooleanMenu(setting.text, setting.key, setting.defaultValue, setting.callback, setting.initCallback);
  1076. }
  1077.  
  1078. function makeBooleanMenu(texts, key, defaultValue=false, callback=null, initCallback=false) {
  1079. const initialVal = GM_getValue(key, defaultValue);
  1080. const initialText = texts[initialVal + 0];
  1081. let id = makeMenu(initialText, onClick);
  1082. initCallback && callback(key, initialVal);
  1083.  
  1084. function onClick() {
  1085. const newValue = !GM_getValue(key, defaultValue);
  1086. const newText = texts[newValue + 0];
  1087. GM_setValue(key, newValue);
  1088. id = makeMenu(newText, onClick, id);
  1089. typeof callback === 'function' && callback(key, newValue);
  1090. }
  1091.  
  1092. function makeMenu(text, func, id) {
  1093. if (GM_info.scriptHandler === 'Tampermonkey' && GM_hasVersion('5.0')) {
  1094. return GM_registerMenuCommand(text, func, {
  1095. id,
  1096. autoClose: false,
  1097. });
  1098. } else {
  1099. GM_unregisterMenuCommand(id);
  1100. return GM_registerMenuCommand(text, func);
  1101. }
  1102. }
  1103. }
  1104.  
  1105. function GM_hasVersion(version) {
  1106. return hasVersion(GM_info?.version || '0', version);
  1107.  
  1108. function hasVersion(ver1, ver2) {
  1109. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  1110.  
  1111. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  1112. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  1113. function compareVersions(a, b) {
  1114. if (a == b) {
  1115. return 0;
  1116. }
  1117. let aParts = a.split('.');
  1118. let bParts = b.split('.');
  1119. for (let i = 0; i < aParts.length; i++) {
  1120. let result = compareVersionPart(aParts[i], bParts[i]);
  1121. if (result != 0) {
  1122. return result;
  1123. }
  1124. }
  1125. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  1126. if (bParts.length > aParts.length) {
  1127. return -1;
  1128. }
  1129. return 0;
  1130. }
  1131.  
  1132. function compareVersionPart(partA, partB) {
  1133. let partAParts = parseVersionPart(partA);
  1134. let partBParts = parseVersionPart(partB);
  1135. for (let i = 0; i < partAParts.length; i++) {
  1136. // "A string-part that exists is always less than a string-part that doesn't exist"
  1137. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  1138. return -1;
  1139. }
  1140. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  1141. return 1;
  1142. }
  1143. if (partAParts[i] > partBParts[i]) {
  1144. return 1;
  1145. }
  1146. if (partAParts[i] < partBParts[i]) {
  1147. return -1;
  1148. }
  1149. }
  1150. return 0;
  1151. }
  1152.  
  1153. // It goes number, string, number, string. If it doesn't exist, then
  1154. // 0 for numbers, empty string for strings.
  1155. function parseVersionPart(part) {
  1156. if (!part) {
  1157. return [0, "", 0, ""];
  1158. }
  1159. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  1160. return [
  1161. partParts[1] ? parseInt(partParts[1]) : 0,
  1162. partParts[2],
  1163. partParts[3] ? parseInt(partParts[3]) : 0,
  1164. partParts[4]
  1165. ];
  1166. }
  1167. }
  1168. }
  1169. }
  1170.  
  1171. // Copy text to clipboard (needs to be called in an user event)
  1172. function copyText(text) {
  1173. // Create a new textarea for copying
  1174. const newInput = document.createElement('textarea');
  1175. document.body.appendChild(newInput);
  1176. newInput.value = text;
  1177. newInput.select();
  1178. document.execCommand('copy');
  1179. document.body.removeChild(newInput);
  1180. }
  1181. })();