[GMT] Tags Helper

Improvements for working with groups of tags + increased efficiency of new requests creation

当前为 2021-07-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name [GMT] Tags Helper
  3. // @namespace https://greasyfork.org/users/321857-anakunda
  4. // @version 1.01.2
  5. // @match https://*/artist.php?id=*
  6. // @match https://*/artist.php?*&id=*
  7. // @match https://*/requests.php
  8. // @match https://*/requests.php?submit=true&*
  9. // @match https://*/requests.php?type=*
  10. // @match https://*/requests.php?page=*
  11. // @match https://*/requests.php?action=new*
  12. // @match https://*/requests.php?action=view&id=*
  13. // @match https://*/requests.php?action=view&*&id=*
  14. // @match https://*/requests.php?action=edit&id=*
  15. // @match https://*/torrents.php?id=*
  16. // @match https://*/torrents.php
  17. // @match https://*/torrents.php?action=advanced&*
  18. // @match https://*/torrents.php?*&action=advanced
  19. // @match https://*/torrents.php?*&action=advanced&*
  20. // @match https://*/torrents.php?action=basic&*
  21. // @match https://*/torrents.php?*&action=basic
  22. // @match https://*/torrents.php?*&action=basic&*
  23. // @match https://*/torrents.php?page=*
  24. // @match https://*/torrents.php?action=notify
  25. // @match https://*/torrents.php?action=notify&*
  26. // @match https://*/torrents.php?type=*
  27. // @match https://*/collages.php?id=*
  28. // @match https://*/collages.php?page=*&id=*
  29. // @match https://*/collages.php?action=new
  30. // @match https://*/collages.php?action=edit&collageid=*
  31. // @match https://*/bookmarks.php?type=*
  32. // @match https://*/bookmarks.php?page=*
  33. // @match https://*/upload.php
  34. // @match https://*/upload.php&url=*
  35. // @match https://*/upload.php&tags=*
  36. // @match https://*/bookmarks.php?type=torrents
  37. // @match https://*/bookmarks.php?page=*&type=torrents
  38. // @match https://*/top10.php
  39. // @match https://*/top10.php?*
  40. // @run-at document-end
  41. // @author Anakunda
  42. // @copyright 2021, Anakunda (https://greasyfork.org/users/321857-anakunda)
  43. // @license GPL-3.0-or-later
  44. // @grant GM_getValue
  45. // @grant GM_setClipboard
  46. // @grant GM_registerMenuCommand
  47. // @require https://openuserjs.org/src/libs/Anakunda/QobuzLib.js
  48. // @require https://openuserjs.org/src/libs/Anakunda/GazelleTagManager.js
  49. // @description Improvements for working with groups of tags + increased efficiency of new requests creation
  50. // ==/UserScript==
  51.  
  52. (function() {
  53. 'use strict';
  54.  
  55. const hasStyleSheet = styleSheet => document.styleSheetSets && document.styleSheetSets.contains(styleSheet);
  56. const isLightTheme = ['postmod', 'shiro', 'layer_cake', 'proton', 'red_light'].some(hasStyleSheet);
  57. const isDarkTheme = ['kuro', 'minimal', 'red_dark'].some(hasStyleSheet);
  58. const uriTest = /^(https?:\/\/.+)$/i;
  59. const isFirefox = /\b(?:Firefox)\b/.test(navigator.userAgent) || Boolean(window.InstallTrigger);
  60. const fieldNames = ['tags', 'tagname', 'taglist'];
  61. const exclusions = GM_getValue('exclusions', [
  62. '/^(?:\\d{4}s)$/i',
  63. '/^(?:delete\.this\.tag)$/i',
  64. ]).map(function(expr) {
  65. const m = /^\/(.+)\/([dgimsuy]*)$/.exec(expr);
  66. if (m != null) return new RegExp(m[1], m[2]);
  67. }).filter(it => it instanceof RegExp);
  68.  
  69. const getTagsFromIterable = iterable => Array.from(iterable)
  70. .filter(elem => elem.offsetWidth > 0 && elem.offsetHeight > 0 && elem.pathname && elem.search
  71. && fieldNames.some(URLSearchParams.prototype.has.bind(new URLSearchParams(elem.search))))
  72. .map(elem => elem.textContent.trim())
  73. .filter(tag => /^([a-z\d\.]+)$/.test(tag) && !exclusions.some(rx => rx.test(tag)));
  74.  
  75. const contextId = 'cae67c72-9aa7-4b96-855e-73cb23f5c7f8';
  76. let menuHooks = 0, menuInvoker;
  77.  
  78. function createMenu() {
  79. const menu = document.createElement('menu');
  80. menu.type = 'context';
  81. menu.id = contextId;
  82. menu.className = 'tags-helper';
  83.  
  84. function addMenuItem(label, callback) {
  85. if (label) {
  86. let menuItem = document.createElement('MENUITEM');
  87. menuItem.label = label;
  88. if (typeof callback == 'function') menuItem.onclick = callback;
  89. menu.append(menuItem);
  90. }
  91. return menu.children.length;
  92. }
  93.  
  94. addMenuItem('Copy tags to clipboard', function(evt) {
  95. console.assert(menuInvoker instanceof HTMLElement, 'menuInvoker instanceof HTMLElement')
  96. if (!(menuInvoker instanceof HTMLElement)) throw 'Invalid invoker';
  97. const tags = getTagsFromIterable(menuInvoker.getElementsByTagName('A'));
  98. if (tags.length > 0) GM_setClipboard(tags.join(', '), 'text');
  99. });
  100. addMenuItem('Make new request using these tags', function(evt) {
  101. console.assert(menuInvoker instanceof HTMLElement, 'menuInvoker instanceof HTMLElement')
  102. if (!(menuInvoker instanceof HTMLElement)) throw 'Invalid invoker';
  103. const tags = getTagsFromIterable(menuInvoker.getElementsByTagName('A'));
  104. if (tags.length > 0) document.location.assign('/requests.php?' + new URLSearchParams({
  105. action: 'new',
  106. tags: JSON.stringify(tags),
  107. }).toString());
  108. });
  109. addMenuItem('Make new upload using these tags', function(evt) {
  110. console.assert(menuInvoker instanceof HTMLElement, 'menuInvoker instanceof HTMLElement')
  111. if (!(menuInvoker instanceof HTMLElement)) throw 'Invalid invoker';
  112. const tags = getTagsFromIterable(menu.getElementsByTagName('A'));
  113. if (tags.length > 0) document.location.assign('/upload.php?' + new URLSearchParams({
  114. tags: JSON.stringify(tags),
  115. }).toString());
  116. });
  117. document.body.append(menu);
  118. }
  119.  
  120. function setElemHandlers(elem) {
  121. console.assert(elem instanceof HTMLElement);
  122. elem.addEventListener('click', function(evt) {
  123. if (evt.altKey) evt.preventDefault(); else return;
  124. const tags = getTagsFromIterable(evt.currentTarget.getElementsByTagName('A'));
  125. if (tags.length > 0) if (evt.ctrlKey) document.location.assign('/requests.php?' + new URLSearchParams({
  126. action: 'new',
  127. tags: JSON.stringify(tags)
  128. }).toString()); else if (evt.shiftKey) document.location.assign('/upload.php?' + new URLSearchParams({
  129. tags: JSON.stringify(tags)
  130. }).toString()); else {
  131. GM_setClipboard(tags.join(', '), 'text');
  132. evt.currentTarget.style.backgroundColor = isDarkTheme ? 'darkgreen' : 'lightgreen';
  133. setTimeout(elem => { elem.style.backgroundColor = null }, 1000, evt.currentTarget);
  134. }
  135. return false;
  136. });
  137. elem.ondragover = evt => false;
  138. elem.ondragenter = evt => { evt.currentTarget.style.backgroundColor = 'lawngreen' };
  139. elem[isFirefox ? 'ondragexit' : 'ondragleave'] = evt => { evt.currentTarget.style.backgroundColor = null };
  140. elem.draggable = true;
  141. elem.ondragstart = function(evt) {
  142. //evt.dataTransfer.clearData('text/uri-list');
  143. //evt.dataTransfer.clearData('text/x-moz-url');
  144. evt.dataTransfer.setData('text/plain',
  145. getTagsFromIterable(evt.currentTarget.getElementsByTagName('A')).join(', '));
  146. console.debug(evt.currentTarget, evt.currentTarget.getElementsByTagName('A'),
  147. getTagsFromIterable(evt.currentTarget.getElementsByTagName('A')));
  148. };
  149. elem.ondrop = function(evt) {
  150. evt.preventDefault();
  151. let links = evt.dataTransfer.getData('text/uri-list');
  152. if (links) links = links.split(/\r?\n/); else {
  153. links = evt.dataTransfer.getData('text/x-moz-url');
  154. if (links) links = links.split(/\r?\n/).filter((item, ndx) => ndx % 2 == 0);
  155. else if (links = evt.dataTransfer.getData('text/plain'))
  156. links = links.split(/\r?\n/).filter(RegExp.prototype.test.bind(uriTest));
  157. }
  158. if (Array.isArray(links) && links.length > 0) {
  159. const tags = getTagsFromIterable(evt.currentTarget.getElementsByTagName('A'));
  160. if (tags.length > 0) if (evt.shiftKey) document.location.assign('/upload.php?' + new URLSearchParams({
  161. url: links[0],
  162. tags: JSON.stringify(tags),
  163. }).toString()); else document.location.assign('/requests.php?' + new URLSearchParams({
  164. action: 'new',
  165. url: links[0],
  166. tags: JSON.stringify(tags),
  167. }).toString());
  168. }
  169. evt.currentTarget.style.backgroundColor = null;
  170. return false;
  171. };
  172. elem.oncontextmenu = evt => { menuInvoker = evt.currentTarget };
  173. elem.setAttribute('contextmenu', contextId);
  174. ++menuHooks;
  175. elem.title = `Alt + click => copy tags to clipboard
  176. Ctrl + Alt + click => make new request using these tags
  177. Shift + Alt + click => make new upload using these tags
  178. ---
  179. Drag & drop active link here => make new request using these tags
  180. Shift + Drag & drop active link here => make new upload using these tags
  181. Drag this tags area and drop to any text input to get inserted all tags as comma-separated list
  182. --or-- use context menu (older browsers only)`;
  183. }
  184.  
  185. switch (document.location.pathname) {
  186. case '/requests.php':
  187. case '/upload.php': {
  188. const urlParams = new URLSearchParams(document.location.search);
  189. try {
  190. let tags = urlParams.get('tags');
  191. if (tags && (tags = JSON.parse(tags)).length > 0) {
  192. const input = document.getElementById('tags');
  193. if (input != null) input.value = tags.join(', ');
  194. }
  195. } catch(e) { }
  196. const url = urlParams.get('url');
  197. if (uriTest.test(url)) {
  198. let ua = document.getElementById('ua-data');
  199. function feedData() {
  200. ua.value = url;
  201. if ((ua = document.getElementById('autofill-form-2')) == null) return; // assertion failed
  202. if (typeof ua.onclick == 'function') ua.onclick(); else ua.click();
  203. }
  204. if (ua != null) feedData(); else {
  205. const container = document.querySelector('form#request_form > table > tbody');
  206. if (container != null) {
  207. let counters = [0, 0], timeStamp = Date.now();
  208. const mo = new MutationObserver(function(mutationsList) {
  209. ++counters[0];
  210. for (let mutation of mutationsList) for (let node of mutation.addedNodes) {
  211. ++counters[1];
  212. if (node.nodeName != 'TR' || (ua = node.querySelector('textarea#ua-data')) == null) continue;
  213. console.log('Found UA data by trigger:', counters, (Date.now() - timeStamp) / 1000);
  214. clearTimeout(timer);
  215. return feedData();
  216. }
  217. }), timer = setTimeout(mo => { mo.disconnect() }, 10000, mo);
  218. mo.observe(container, { childList: true });
  219. }
  220. }
  221. }
  222. break;
  223. }
  224. }
  225.  
  226. document.body.querySelectorAll('div.tags').forEach(setElemHandlers);
  227.  
  228. (function() {
  229. const tagsBox = document.body.querySelector('div.box_tags');
  230. if (tagsBox != null) setElemHandlers(tagsBox); else return;
  231. const head = tagsBox.querySelector('div.head');
  232. if (head == null) return;
  233. const span = document.createElement('SPAN'), a = document.createElement('A');
  234. span.style.float = 'right';
  235. a.className = 'brackets';
  236. a.textContent = 'Copy';
  237. a.href = '#';
  238. a.onclick = function(evt) {
  239. let tags = getTagsFromIterable(tagsBox.querySelectorAll('* > li > a'));
  240. if (tags.length <= 0) return false;
  241. GM_setClipboard(tags.join(', '), 'text');
  242. evt.currentTarget.style.color = isDarkTheme ? 'darkgreen' : 'lightgreen';
  243. setTimeout(elem => {elem.style.color = null }, 1000, evt.currentTarget);
  244. return false;
  245. };
  246. span.append(a);
  247. head.append(span);
  248. })();
  249.  
  250. if (menuHooks > 0) createMenu();
  251.  
  252. function inputDataHandler(evt) {
  253. switch (evt.type) {
  254. case 'paste': var tags = evt.clipboardData.getData('text/plain'); break;
  255. case 'drop': tags = evt.dataTransfer.getData('text/plain'); break;
  256. }
  257. if (!tags) return;
  258. tags = new TagManager(...tags.split(/[\r\n\,\;\|\>]+/).map(expr => expr.trim()).filter(Boolean))
  259. if (tags.length > 0) tags = tags.toString(); else return;
  260. switch (evt.type) {
  261. case 'paste': {
  262. const cursor = evt.target.selectionStart + tags.length;
  263. evt.target.value = evt.target.value.slice(0, evt.target.selectionStart) +
  264. tags + evt.target.value.slice(evt.target.selectionEnd);
  265. evt.target.selectionEnd = evt.target.selectionStart = cursor;
  266. break;
  267. }
  268. case 'drop':
  269. evt.target.value = tags;
  270. break;
  271. }
  272. return false;
  273. }
  274.  
  275. for (let input of document.body.querySelectorAll(fieldNames.map(name => `input[name="${name}"]`).join(', ')))
  276. input.onpaste = input.ondrop = inputDataHandler;
  277. })();