Greasyfork script-set-edit button

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

Fra 13.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.5
  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. this.#sets = CONFIG['script-sets'].sets = sets_data;
  721. CONFIG['script-sets'].time = Date.now();
  722.  
  723. this.#tip();
  724. this.#enable();
  725. this.#displaySets();
  726. this.#refreshButtonDisplay();
  727. }
  728.  
  729. // Request document: get sets list and
  730. async #refresh_doc() {
  731. const CONFIG = this.#CM.Config;
  732.  
  733. this.#disable();
  734. this.#tip(CONST.Text[i18n].Refreshing.List);
  735.  
  736. // Check login status
  737. if (!GFScriptSetAPI.getUserpage()) {
  738. this.#tip(CONST.Text[i18n].NotLoggedIn);
  739. return;
  740. }
  741.  
  742. // Refresh sets list
  743. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  744. CONFIG['script-sets'].time = Date.now();
  745. this.#displaySets();
  746.  
  747. // Refresh each set's script list
  748. this.#tip(CONST.Text[i18n].Refreshing.Script);
  749. await Promise.all(this.#sets.map(async set => {
  750. // Fetch scripts
  751. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  752. this.#displaySets();
  753.  
  754. // Save to GM_storage
  755. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  756. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  757. CONFIG['script-sets'].time = Date.now();
  758. }));
  759.  
  760. this.#tip();
  761. this.#enable();
  762. this.#refreshButtonDisplay();
  763. }
  764.  
  765. // Refresh on instance creation.
  766. // This should be running in low-frequecy. Refreshing makes lots of requests which may resul in a 503 error(rate limit) for the user.
  767. #autoRefresh(minTime=1*24*60*60*1000) {
  768. const CONFIG = this.#CM.Config;
  769. const lastRefresh = new Date(CONFIG['script-sets'].time);
  770. if (Date.now() - lastRefresh > minTime) {
  771. this.#refresh();
  772. return true;
  773. } else {
  774. return false;
  775. }
  776. }
  777.  
  778. #addFav() {
  779. const set = this.#getCurrentSet();
  780. const option = set.elmOption;
  781.  
  782. this.#displayNotice(CONST.Text[i18n].Working[0]);
  783. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  784. if (!editStatus) {
  785. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  786. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  787. } else {
  788. this.#displayNotice(CONST.Text[i18n].Working[1]);
  789. }
  790. }, finishStatus => {
  791. if (finishStatus) {
  792. // Save to this.#sets and GM_storage
  793. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  794. // If scripts property is missing, do sync(refresh)
  795. this.#refresh();
  796. } else {
  797. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  798. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  799. this.#sets = CM.getConfig('script-sets').sets;
  800. }
  801.  
  802. // Display
  803. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  804. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  805. this.#displaySets();
  806. } else {
  807. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  808. }
  809. });
  810. }
  811.  
  812. #removeFav() {
  813. const set = this.#getCurrentSet();
  814. const option = set.elmOption;
  815.  
  816. this.#displayNotice(CONST.Text[i18n].Working[0]);
  817. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  818. if (!editStatus) {
  819. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  820. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  821. } else {
  822. this.#displayNotice(CONST.Text[i18n].Working[1]);
  823. }
  824. }, finishStatus => {
  825. if (finishStatus) {
  826. // Save to this.#sets and GM_storage
  827. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  828. // If scripts property is missing, do sync(refresh)
  829. this.#refresh();
  830. } else {
  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.  
  837. // Display
  838. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  839. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  840. this.#displaySets();
  841. } else {
  842. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  843. }
  844. });
  845. }
  846.  
  847. #editInPage(e) {
  848. e.preventDefault();
  849.  
  850. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  851. if (_iframes.length) {
  852. // Iframe exists, close iframe
  853. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  854. _iframes.forEach(ifr => ifr.remove());
  855. this.#refresh();
  856. } else {
  857. // Iframe not exist, make iframe
  858. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  859.  
  860. const iframe = $$CrE({
  861. tagName: 'iframe',
  862. props: {
  863. src: this.#getCurrentSet().linkedit
  864. },
  865. styles: {
  866. width: '100%',
  867. height: '60vh'
  868. },
  869. classes: ['script-edit-page'],
  870. listeners: [['load', e => {
  871. //this.#refresh();
  872. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  873. }]]
  874. });
  875. this.#elements.container.appendChild(iframe);
  876. }
  877. }
  878.  
  879. #displayNotice(text) {
  880. const notice = $CrE('p');
  881. notice.classList.add('notice');
  882. notice.id = 'fav-notice';
  883. notice.innerText = text;
  884. const old_notice = $('#fav-notice');
  885. old_notice && old_notice.parentElement.removeChild(old_notice);
  886. $('#script-content').insertAdjacentElement('afterbegin', notice);
  887. }
  888.  
  889. #tip(text='', timeout=0) {
  890. this.#elements.tip.innerText = text;
  891. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  892. }
  893.  
  894. // Apply this.#sets to gui
  895. #displaySets() {
  896. const elements = this.#elements;
  897.  
  898. // Save selected set
  899. const old_value = elements.select.value;
  900. [...elements.select.children].forEach(child => child.remove());
  901.  
  902. // Make <optgroup>s and <option>s
  903. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  904. this.#sets.forEach(set => {
  905. // Create <option>
  906. set.elmOption = $$CrE({
  907. tagName: 'option',
  908. props: {
  909. innerText: set.name,
  910. value: set.id
  911. }
  912. });
  913. // Display inset status
  914. if (set.scripts) {
  915. const inSet = set.scripts.includes(this.#sid);
  916. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  917. }
  918. // Append <option> into <select>
  919. serverGroup.appendChild(set.elmOption);
  920. });
  921. if (this.#sets.length === 0) {
  922. const optEmpty = elements.optEmpty = $$CrE({
  923. tagName: 'option',
  924. props: {
  925. innerText: CONST.Text[i18n].NoSetsYet,
  926. value: 'empty',
  927. selected: true
  928. }
  929. });
  930. serverGroup.appendChild(optEmpty);
  931. }
  932.  
  933. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  934. const newSet = elements.newSet = $$CrE({
  935. tagName: 'option',
  936. props: {
  937. innerText: CONST.Text[i18n].NewSet,
  938. value: 'new',
  939. }
  940. });
  941. newGroup.appendChild(newSet);
  942. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  943.  
  944. // Adjust <select> width
  945. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  946.  
  947. // Select previous selected set's <option>
  948. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  949. selected && (selected.selected = true);
  950.  
  951. // Set edit-button.href
  952. if (elements.select.value !== 'empty') {
  953. const curset = this.#sets.find(set => set.id === elements.select.value);
  954. elements.btnEdit.href = curset.linkedit;
  955. }
  956.  
  957. // Display correct button
  958. this.#refreshButtonDisplay();
  959. }
  960.  
  961. // Display only add button when script in current set, otherwise remove button
  962. // Disable set-related buttons when not selecting options that not represents a set
  963. #refreshButtonDisplay() {
  964. const set = this.#getCurrentSet();
  965. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  966. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  967. if (!set || !set.scripts) { return null; }
  968. if (set.scripts.includes(this.#sid)) {
  969. this.#elements.btnAdd.style.setProperty('display', 'none');
  970. this.#elements.btnRemove.style.removeProperty('display');
  971. return true;
  972. } else {
  973. this.#elements.btnRemove.style.setProperty('display', 'none');
  974. this.#elements.btnAdd.style.removeProperty('display');
  975. return false;
  976. }
  977. }
  978.  
  979. #execCommand(command) {
  980. switch (command) {
  981. case 'new': {
  982. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  983. window.open(url);
  984. break;
  985. }
  986. case 'empty': {
  987. // Do nothing
  988. break;
  989. }
  990. }
  991. }
  992.  
  993. // Returns null if no <option>s yet
  994. #getCurrentSet() {
  995. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  996. }
  997.  
  998. #disable() {
  999. [
  1000. this.#elements.select,
  1001. this.#elements.btnAdd, this.#elements.btnRemove,
  1002. this.#elements.btnEdit, this.#elements.btnIframe,
  1003. this.#elements.btnCopy, this.#elements.btnSync
  1004. ].forEach(element => FavoritePanel.#disableElement(element));
  1005. this.#disabled = true;
  1006. }
  1007.  
  1008. #enable() {
  1009. [
  1010. this.#elements.select,
  1011. this.#elements.btnAdd, this.#elements.btnRemove,
  1012. this.#elements.btnEdit, this.#elements.btnIframe,
  1013. this.#elements.btnCopy, this.#elements.btnSync
  1014. ].forEach(element => FavoritePanel.#enableElement(element));
  1015. this.#disabled = false;
  1016. }
  1017.  
  1018. static #disableElement(element) {
  1019. element.style.filter = 'grayscale(1) brightness(0.95)';
  1020. element.style.opacity = '0.25';
  1021. element.style.pointerEvents = 'none';
  1022. element.tabIndex = -1;
  1023. }
  1024.  
  1025. static #enableElement(element) {
  1026. element.style.removeProperty('filter');
  1027. element.style.removeProperty('opacity');
  1028. element.style.removeProperty('pointer-events');
  1029. element.tabIndex = 0;
  1030. }
  1031.  
  1032. static #deepClone(val) {
  1033. if (typeof structuredClone === 'function') {
  1034. return structuredClone(val);
  1035. } else {
  1036. return JSON.parse(JSON.stringify(val));
  1037. }
  1038. }
  1039.  
  1040. static #lightClone(val) {
  1041. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  1042. return val;
  1043. }
  1044. if (Array.isArray(val)) {
  1045. return val.slice();
  1046. }
  1047. if (typeof val === 'object') {
  1048. return Object.fromEntries(Object.entries(val));
  1049. }
  1050. }
  1051. }
  1052.  
  1053. const panel = new FavoritePanel(CM);
  1054. }
  1055.  
  1056. // Basic functions
  1057. function makeBooleanSettings(settings) {
  1058. for (const setting of settings) {
  1059. makeBooleanMenu(setting.text, setting.key, setting.defaultValue, setting.callback, setting.initCallback);
  1060. }
  1061.  
  1062. function makeBooleanMenu(texts, key, defaultValue=false, callback=null, initCallback=false) {
  1063. const initialVal = GM_getValue(key, defaultValue);
  1064. const initialText = texts[initialVal + 0];
  1065. let id = makeMenu(initialText, onClick);
  1066. initCallback && callback(key, initialVal);
  1067.  
  1068. function onClick() {
  1069. const newValue = !GM_getValue(key, defaultValue);
  1070. const newText = texts[newValue + 0];
  1071. GM_setValue(key, newValue);
  1072. id = makeMenu(newText, onClick, id);
  1073. typeof callback === 'function' && callback(key, newValue);
  1074. }
  1075.  
  1076. function makeMenu(text, func, id) {
  1077. if (GM_info.scriptHandler === 'Tampermonkey' && GM_hasVersion('5.0')) {
  1078. return GM_registerMenuCommand(text, func, {
  1079. id,
  1080. autoClose: false,
  1081. });
  1082. } else {
  1083. GM_unregisterMenuCommand(id);
  1084. return GM_registerMenuCommand(text, func);
  1085. }
  1086. }
  1087. }
  1088.  
  1089. function GM_hasVersion(version) {
  1090. return hasVersion(GM_info?.version || '0', version);
  1091.  
  1092. function hasVersion(ver1, ver2) {
  1093. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  1094.  
  1095. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  1096. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  1097. function compareVersions(a, b) {
  1098. if (a == b) {
  1099. return 0;
  1100. }
  1101. let aParts = a.split('.');
  1102. let bParts = b.split('.');
  1103. for (let i = 0; i < aParts.length; i++) {
  1104. let result = compareVersionPart(aParts[i], bParts[i]);
  1105. if (result != 0) {
  1106. return result;
  1107. }
  1108. }
  1109. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  1110. if (bParts.length > aParts.length) {
  1111. return -1;
  1112. }
  1113. return 0;
  1114. }
  1115.  
  1116. function compareVersionPart(partA, partB) {
  1117. let partAParts = parseVersionPart(partA);
  1118. let partBParts = parseVersionPart(partB);
  1119. for (let i = 0; i < partAParts.length; i++) {
  1120. // "A string-part that exists is always less than a string-part that doesn't exist"
  1121. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  1122. return -1;
  1123. }
  1124. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  1125. return 1;
  1126. }
  1127. if (partAParts[i] > partBParts[i]) {
  1128. return 1;
  1129. }
  1130. if (partAParts[i] < partBParts[i]) {
  1131. return -1;
  1132. }
  1133. }
  1134. return 0;
  1135. }
  1136.  
  1137. // It goes number, string, number, string. If it doesn't exist, then
  1138. // 0 for numbers, empty string for strings.
  1139. function parseVersionPart(part) {
  1140. if (!part) {
  1141. return [0, "", 0, ""];
  1142. }
  1143. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  1144. return [
  1145. partParts[1] ? parseInt(partParts[1]) : 0,
  1146. partParts[2],
  1147. partParts[3] ? parseInt(partParts[3]) : 0,
  1148. partParts[4]
  1149. ];
  1150. }
  1151. }
  1152. }
  1153. }
  1154.  
  1155. // Copy text to clipboard (needs to be called in an user event)
  1156. function copyText(text) {
  1157. // Create a new textarea for copying
  1158. const newInput = document.createElement('textarea');
  1159. document.body.appendChild(newInput);
  1160. newInput.value = text;
  1161. newInput.select();
  1162. document.execCommand('copy');
  1163. document.body.removeChild(newInput);
  1164. }
  1165. })();