Greasyfork script-set-edit button

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

Verze ze dne 16. 07. 2024. Zobrazit nejnovější verzi.

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