Dynamic Include Sites Script (Protocol-Independent)

Run on default & user-defined sites using wildcard patterns (ignores protocols), with full management features.

Tento skript by nemal byť nainštalovaný priamo. Je to knižnica pre ďalšie skripty, ktorú by mali používať cez meta príkaz // @require https://update.greatest.deepsurf.us/scripts/526770/1541997/Dynamic%20Include%20Sites%20Script%20%28Protocol-Independent%29.js

  1. // ==UserScript==
  2. // @name Site Filter (Protocol-Independent)
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.2
  5. // @description Manage allowed sites dynamically and reference this in other scripts.
  6. // @author blvdmd
  7. // @match *://*/*
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_download
  12. // @run-at document-start
  13. // ==/UserScript==
  14.  
  15. (function () {
  16. 'use strict';
  17.  
  18. const USE_EMOJI_FOR_STATUS = true; // Configurable flag to use emoji for true/false status
  19. const SHOW_STATUS_ONLY_IF_TRUE = true; // Configurable flag to show status only if any value is true
  20.  
  21. // ✅ Wait for `SCRIPT_STORAGE_KEY` to be set
  22. function waitForScriptStorageKey(maxWait = 1000) {
  23. return new Promise(resolve => {
  24. const startTime = Date.now();
  25. const interval = setInterval(() => {
  26. if (typeof window.SCRIPT_STORAGE_KEY !== 'undefined') {
  27. clearInterval(interval);
  28. resolve(window.SCRIPT_STORAGE_KEY);
  29. } else if (Date.now() - startTime > maxWait) {
  30. clearInterval(interval);
  31. console.error("🚨 SCRIPT_STORAGE_KEY is not set! Make sure your script sets it **before** @require.");
  32. resolve(null);
  33. }
  34. }, 50);
  35. });
  36. }
  37.  
  38. (async function initialize() {
  39. async function waitForDocumentReady() {
  40. if (document.readyState === "complete") return;
  41. return new Promise(resolve => {
  42. window.addEventListener("load", resolve, { once: true });
  43. });
  44. }
  45. // ✅ Wait for the script storage key
  46. const key = await waitForScriptStorageKey();
  47. if (!key) return;
  48.  
  49. // ✅ Ensure the document is fully loaded before setting `shouldRunOnThisSite`
  50. await waitForDocumentReady();
  51.  
  52. const STORAGE_KEY = `additionalSites_${key}`;
  53.  
  54. function getDefaultList() {
  55. return typeof window.GET_DEFAULT_LIST === "function" ? window.GET_DEFAULT_LIST() : [];
  56. }
  57.  
  58. function normalizeUrl(url) {
  59. if (typeof url !== 'string') {
  60. url = String(url);
  61. }
  62. return url.replace(/^https?:\/\//, '');
  63. }
  64.  
  65. let additionalSites = GM_getValue(STORAGE_KEY, []);
  66.  
  67. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  68. if (typeof item === 'string') {
  69. return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  70. }
  71. return { ...item, pattern: normalizeUrl(item.pattern) };
  72. });
  73.  
  74. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  75. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  76. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  77. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  78. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  79. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  80. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  81.  
  82. async function shouldRunOnThisSite() {
  83. const currentFullPath = normalizeUrl(`${window.location.href}`);
  84. return mergedSites.some(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  85. }
  86.  
  87. function wildcardToRegex(pattern) {
  88. return new RegExp("^" + pattern
  89. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&')
  90. .replace(/\./g, '\\.')
  91. .replace(/\?/g, '\\?')
  92. .replace(/\*/g, '.*')
  93. + "$");
  94. }
  95.  
  96. function addCurrentSiteMenu() {
  97. const currentHost = window.location.hostname;
  98. const currentPath = window.location.pathname;
  99. const domainParts = currentHost.split('.');
  100. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  101. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  102.  
  103. const options = [
  104. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  105. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  106. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  107. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  108. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  109. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  110. ];
  111.  
  112. const userChoice = prompt(
  113. "Select an option to add the site:\n" +
  114. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  115. "\nEnter a number or cancel."
  116. );
  117.  
  118. if (!userChoice) return;
  119. const selectedIndex = parseInt(userChoice, 10) - 1;
  120. if (selectedIndex >= 0 && selectedIndex < options.length) {
  121. let pattern = normalizeUrl(options[selectedIndex].pattern);
  122. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  123. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  124. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  125. }
  126.  
  127. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", "n").toLowerCase() === 'y';
  128. const postProcessingRequired = prompt("Is post-processing required? (y/n)", "n").toLowerCase() === 'y';
  129.  
  130. const entry = { pattern, preProcessingRequired, postProcessingRequired };
  131.  
  132. if (!additionalSites.some(item => item.pattern === pattern)) {
  133. additionalSites.push(entry);
  134. GM_setValue(STORAGE_KEY, additionalSites);
  135. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  136. if (typeof item === 'string') {
  137. return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  138. }
  139. return { ...item, pattern: normalizeUrl(item.pattern) };
  140. });
  141. alert(`✅ Added site with pattern: ${pattern}`);
  142. } else {
  143. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  144. }
  145. }
  146. }
  147.  
  148. function viewIncludedSites() {
  149. const siteList = additionalSites.map(item => {
  150. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  151. return `${item.pattern}${status ? ` (${status})` : ''}`;
  152. }).join("\n");
  153. alert(`🔍 Included Sites:\n${siteList || "No sites added yet."}`);
  154. }
  155.  
  156. function deleteEntries() {
  157. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  158. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  159. additionalSites.map((item, index) => `${index + 1}. ${item.pattern}`).join("\n"));
  160. if (!userChoice) return;
  161. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  162. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  163. GM_setValue(STORAGE_KEY, additionalSites);
  164. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  165. if (typeof item === 'string') {
  166. return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  167. }
  168. return { ...item, pattern: normalizeUrl(item.pattern) };
  169. });
  170. alert("✅ Selected entries have been deleted.");
  171. }
  172.  
  173. function editEntry() {
  174. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  175. const userChoice = prompt("Select an entry to edit:\n" +
  176. additionalSites.map((item, index) => {
  177. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  178. return `${index + 1}. ${item.pattern}${status ? ` (${status})` : ''}`;
  179. }).join("\n"));
  180. if (!userChoice) return;
  181. const selectedIndex = parseInt(userChoice, 10) - 1;
  182. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  183. const entry = additionalSites[selectedIndex];
  184. const newPattern = normalizeUrl(prompt("Edit the pattern:", entry.pattern));
  185. if (!newPattern || !newPattern.trim()) return;
  186.  
  187. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", entry.preProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  188. const postProcessingRequired = prompt("Is post-processing required? (y/n)", entry.postProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  189.  
  190. entry.pattern = newPattern.trim();
  191. entry.preProcessingRequired = preProcessingRequired;
  192. entry.postProcessingRequired = postProcessingRequired;
  193. GM_setValue(STORAGE_KEY, additionalSites);
  194. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  195. if (typeof item === 'string') {
  196. return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  197. }
  198. return { ...item, pattern: normalizeUrl(item.pattern) };
  199. });
  200. alert("✅ Entry updated.");
  201. }
  202.  
  203. function clearAllEntries() {
  204. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  205. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  206. additionalSites = [];
  207. GM_setValue(STORAGE_KEY, additionalSites);
  208. mergedSites = [...getDefaultList()].map(item => {
  209. if (typeof item === 'string') {
  210. return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  211. }
  212. return { ...item, pattern: normalizeUrl(item.pattern) };
  213. });
  214. alert("✅ All user-defined entries cleared.");
  215. }
  216. }
  217.  
  218. // function exportAdditionalSites() {
  219. // GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  220. // alert("📤 Additional sites exported as JSON.");
  221. // }
  222.  
  223. function exportAdditionalSites() {
  224. const data = JSON.stringify(additionalSites, null, 2);
  225. const blob = new Blob([data], { type: 'application/json' });
  226. const url = URL.createObjectURL(blob);
  227. const a = document.createElement('a');
  228. a.href = url;
  229. a.download = 'additionalSites_backup.json';
  230. document.body.appendChild(a);
  231. a.click();
  232. document.body.removeChild(a);
  233. URL.revokeObjectURL(url);
  234. alert("📤 Additional sites exported as JSON.");
  235. }
  236.  
  237. // function importAdditionalSites() {
  238. // const input = document.createElement("input");
  239. // input.type = "file";
  240. // input.accept = ".json";
  241. // input.onchange = event => {
  242. // const reader = new FileReader();
  243. // reader.onload = e => {
  244. // additionalSites = JSON.parse(e.target.result);
  245. // GM_setValue(STORAGE_KEY, additionalSites);
  246. // mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  247. // if (typeof item === 'string') {
  248. // return { pattern: normalizeUrl(item), preProcessingRequired: false, postProcessingRequired: false };
  249. // }
  250. // return { ...item, pattern: normalizeUrl(item.pattern) };
  251. // });
  252. // alert("📥 Sites imported successfully.");
  253. // };
  254. // reader.readAsText(event.target.files[0]);
  255. // };
  256. // input.click();
  257. // }
  258.  
  259. function importAdditionalSites() {
  260. const input = document.createElement('input');
  261. input.type = 'file';
  262. input.accept = '.json';
  263. input.style.display = 'none';
  264. input.onchange = event => {
  265. const reader = new FileReader();
  266. reader.onload = e => {
  267. try {
  268. const importedData = JSON.parse(e.target.result);
  269. if (Array.isArray(importedData)) {
  270. additionalSites = importedData.map(item => {
  271. if (typeof item === 'string') {
  272. return normalizeUrl(item);
  273. } else if (typeof item === 'object' && item.pattern) {
  274. return { ...item, pattern: normalizeUrl(item.pattern) };
  275. }
  276. throw new Error('Invalid data format');
  277. });
  278. GM_setValue(STORAGE_KEY, additionalSites);
  279. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(item => {
  280. if (typeof item === 'string') {
  281. return normalizeUrl(item);
  282. }
  283. return { ...item, pattern: normalizeUrl(item.pattern) };
  284. });
  285. alert('📥 Sites imported successfully.');
  286. } else {
  287. throw new Error('Invalid data format');
  288. }
  289. } catch (error) {
  290. alert('❌ Failed to import sites: ' + error.message);
  291. }
  292. };
  293. reader.readAsText(event.target.files[0]);
  294. };
  295. document.body.appendChild(input);
  296. input.click();
  297. document.body.removeChild(input);
  298. }
  299.  
  300. function formatStatus(preProcessingRequired, postProcessingRequired) {
  301. if (SHOW_STATUS_ONLY_IF_TRUE && !preProcessingRequired && !postProcessingRequired) {
  302. return '';
  303. }
  304. const preStatus = USE_EMOJI_FOR_STATUS ? (preProcessingRequired ? '✅' : '✖️') : (preProcessingRequired ? 'true' : 'false');
  305. const postStatus = USE_EMOJI_FOR_STATUS ? (postProcessingRequired ? '✅' : '✖️') : (postProcessingRequired ? 'true' : 'false');
  306. return `Pre: ${preStatus}, Post: ${postStatus}`;
  307. }
  308.  
  309. window.shouldRunOnThisSite = shouldRunOnThisSite;
  310. window.isPreProcessingRequired = function() {
  311. const currentFullPath = normalizeUrl(`${window.location.href}`);
  312. const entry = mergedSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  313. return entry ? entry.preProcessingRequired : false;
  314. };
  315. window.isPostProcessingRequired = function() {
  316. const currentFullPath = normalizeUrl(`${window.location.href}`);
  317. const entry = mergedSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  318. return entry ? entry.postProcessingRequired : false;
  319. };
  320. })();
  321. })();
  322.  
  323. //To use this in another script use @require
  324.  
  325. // // @run-at document-end
  326. // // ==/UserScript==
  327.  
  328. // window.SCRIPT_STORAGE_KEY = "magnetLinkHashChecker"; // UNIQUE STORAGE KEY
  329.  
  330.  
  331. // window.GET_DEFAULT_LIST = function() {
  332. // return [
  333. // { pattern: "*1337x.*", preProcessingRequired: false, postProcessingRequired: false },
  334. // { pattern: "*yts.*", preProcessingRequired: true, postProcessingRequired: true },
  335. // { pattern: "*torrentgalaxy.*", preProcessingRequired: false, postProcessingRequired: true },
  336. // { pattern: "*bitsearch.*", preProcessingRequired: false, postProcessingRequired: false },
  337. // { pattern: "*thepiratebay.*", preProcessingRequired: false, postProcessingRequired: false },
  338. // { pattern: "*ext.*", preProcessingRequired: false, postProcessingRequired: false }
  339. // ];
  340. // };
  341.  
  342.  
  343. // (async function () {
  344. // 'use strict';
  345.  
  346. // // ✅ Wait until `shouldRunOnThisSite` is available
  347. // while (typeof shouldRunOnThisSite === 'undefined') {
  348. // await new Promise(resolve => setTimeout(resolve, 50));
  349. // }
  350.  
  351. // if (!(await shouldRunOnThisSite())) return;
  352. // //alert("running");
  353.  
  354. // console.log("Pre-Customization enabled for this site: " + isPreProcessingRequired() );
  355. // console.log("Post-Customization enabled for this site: " + isPostProcessingRequired() );
  356.  
  357. // const OFFCLOUD_CACHE_API_URL = 'https://offcloud.com/api/cache';