EntryList

Common functions for working on lists of entries

目前为 2019-10-06 提交的版本,查看 最新版本

此脚本不应直接安装,它是供其他脚本使用的外部库。如果你需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/390248/738664/EntryList.js

  1. // EntryList library
  2. // Common functions for modifying/hiding/etc. entries in page, based on
  3. // entry features or presence in one or more lists.
  4. // For instance: hide all YouTube videos that have been watched and highlight
  5. // the ones that have been started but not finished, highlight Netflix movies
  6. // based on IMDb lists, etc.
  7. //
  8. // https://greasyfork.org/scripts/390248-entrylist
  9. // Copyright (C) 2019, Guido Villa
  10. // Original idea and some of the code is taken from IMDb 'My Movies' enhancer:
  11. // Copyright (C) 2008-2018, Ricardo Mendonça Ferreira (ric@mpcnet.com.br)
  12. // Released under the GPL license - http://www.gnu.org/copyleft/gpl.html
  13. //
  14. // For instructions, see https://greasyfork.org/help/installing-user-scripts
  15. //
  16. // Use "@require https://greasyfork.org/scripts/390248-entrylist/code/EntryList.js"
  17. // to use this library in a script.
  18. //
  19. // --------------------------------------------------------------------
  20. //
  21. // ==UserScript==
  22. // @namespace https://greasyfork.org/users/373199-guido-villa
  23. // @exclude *
  24. //
  25. // ==UserLibrary==
  26. // @name EntryList
  27. // @description Common functions for working on lists of entries
  28. // @version 1.7
  29. // @author guidovilla
  30. // @date 06.10.2019
  31. // @copyright 2019, Guido Villa (https://greasyfork.org/users/373199-guido-villa)
  32. // @license GPL-3.0-or-later
  33. // @homepageURL https://greasyfork.org/scripts/390248-entrylist
  34. // @supportURL https://gitlab.com/gv-browser/userscripts/issues
  35. // @contributionURL https://tinyurl.com/gv-donate-0c
  36. // ==/UserScript==
  37. //
  38. // ==/UserLibrary==
  39. //
  40. // --------------------------------------------------------------------
  41. //
  42. // To-do (priority: [H]igh, [M]edium, [L]ow):
  43. // - [H] Extend library to work on all the scripts
  44. // - [M] Make private members actually private and not only undocumented
  45. // (only after understanding which ones really can be private)
  46. // - [M] main context as default context
  47. // - [M] do we need that the library is not cached? if so, how?
  48. // - [M] changes to a list aren't reflected in page till reload. Change?
  49. // - [M] Better handle case without lists (e.g. optimizations)
  50. // - [M] Add description of flow in usage documentation
  51. // - [M] Add indication of URL to use to @require library itself
  52. // - [M] List regeneration function doesn't handle case where lists are missing
  53. //
  54. // Changelog:
  55. // ----------
  56. // 2019.10.06 [1.7] Add possibility of source contexts
  57. // Add getPageType and processPage callbacks
  58. // Some refactoring
  59. // 2019.10.06 [1.6] Changed storage names for future needs (multiple contexts)
  60. // (requires manually adjusting previous storage)
  61. // 2019.10.03 [1.5] Automatically handle case with only one list
  62. // Better handling of list of lists
  63. // Add possibility to permanently skip an entry
  64. // 2019.10.02 [1.4] More generic: getUser and getIdFromEntry are now optional
  65. // Add newContext utility function
  66. // 2019.09.30 [1.3] Correct @namespace and other headers (for public use)
  67. // 2019.09.27 [1.2] Refactoring and name changing: TitleList -> EntryList
  68. // 2019.09.27 [1.1] Code cleanup (string literals, reorder functions)
  69. // Check for validity of the context object
  70. // Add usage documentation
  71. // 2019.09.21 [1.0] First version
  72. // 2019.09.18 [0.1] First test version, private use only
  73. //
  74.  
  75. /* jshint esversion: 6, supernew: true, laxbreak: true */
  76. /* exported EL, Library_Version_ENTRYLIST */
  77.  
  78. const Library_Version_ENTRYLIST = '1.7';
  79.  
  80. /* How to use the library
  81.  
  82. This library instantitates an EL object with a startup method.
  83.  
  84. Call, in order:
  85. 0. EL.newContext(name) to initialize each source and target context
  86. 1. EL.init(ctx), passing a "context" object that is specific to the
  87. website you need to "enhance"
  88. -> not needed if you don't have external sources, just call EL.startup(ctx)
  89. 2. EL.addSource(ctx) for each external source, with its specific context
  90. 3. EL.startup(ctx), ctx us not needed if EL.init(ctx) was called.
  91.  
  92. Other functions:
  93. - addToggleEventOnClick(button, howToFindEntry[, toggleList[, toggleType]]):
  94. mainly used in ctx.modifyEntry(), adds an event listener that implements
  95. a toggle function:
  96. - button: the DOM object to attach the event listener to
  97. - howToFindEntry: how to go from evt.target to the entry object. It can be:
  98. - a number: # of node.parentNode to hop to get from evt.target to to entry
  99. - a CSS selector: used with evt.target.closest to get to entry
  100. - toggleList: the list where the entry is toggled when the button is pressed
  101. (can be omitted if a default list is to be used)
  102. - toggleType: the processing type that is toggled by the press of the button
  103. (can be omitted if only one processing type is used)
  104. It cannot be a false value (0, null, false, undefined, etc.)
  105. - markInvalid(entry):
  106. marks entry as invalid to skips it in subsequent passes
  107. This function returns false so it can be used in isValidEntry() in this way:
  108. return condition || EL.markInvalid(entry)
  109. This leaves the return value unchanged and marks the entry only if invalid
  110.  
  111.  
  112. NOTE:
  113. to use this library you must @grant GM_getValue, GM_setValue, GM_listValues
  114.  
  115.  
  116. Mandatory callback functions and variables in main context:
  117.  
  118. - name: identifier of the site (set with newContext())
  119.  
  120. - getPageEntries():
  121. return (usually with querySelectorAll) an array of entries to be treated
  122. - processItem(entry, tt, processingType):
  123. process the entry based on the processing type or other features of the entry
  124.  
  125.  
  126. Conditionally mandatory callback functions in main context:
  127.  
  128. - getUser(): retrieve and return the username used on the website
  129. mandatory if data are to be stored on a per-user basis
  130. - getIdFromEntry(entry): return a tt: { id, name } object from the entry
  131. mandatory if you want to save entries to lists
  132. NOTE: if id is not found, entry is skipped but it is not marked as invalid
  133. for subsequent passes (unless you use TL.markInvalid(), see above)
  134. - unProcessItem(entry, tt, processingType):
  135. like processItem, but it should reverse the action
  136. mandatory for entries that have a toggle action added with
  137. EL.addToggleEventOnClick()
  138.  
  139.  
  140. Optional callback functions and variables in main context:
  141.  
  142. - interval: interval (in ms) to re-scan links in the DOM
  143. won't re-scan if < MIN_INTERVAL
  144. dafault: DEFAULT_INTERVAL
  145.  
  146. - isEntryPage():
  147. returns false if page must not be scanned for entries
  148. Default is always true => all pages contain entries
  149. - getPageType():
  150. returns some non false value (true, number, object) if page is significant to
  151. the script for some reason (e.g. it is the page where lists are reloaded),
  152. false otherwise. The result is stored in ctx.pageType.
  153. Default is always false => no special page
  154. - processPage(pageType, isEntryPage):
  155. optionally does operations on page based on pageType (and if isEntryPage)
  156. - isValidEntry(entry):
  157. return false if entry must be skipped
  158. NOTE: if entry is skipped, it is not however marked as invalid for subsequent
  159. passes (unless you use TL.markInvalid(), see above)
  160. Default is always true => all entries returned by getPageEntries() are valid
  161. - modifyEntry(entry):
  162. optionally modify entry when scanned for the first time (e.g. add a button)
  163. see also EL.addToggleEventOnClick() above
  164. - determineType(lists, tt, entry):
  165. return the processing type for an entry, given the lists it appears in, or a
  166. false value (0, null, false, undefined, etc.) if no processing is required
  167. "lists" is an object with a true property for each list the entry appears in.
  168. The decision can also be taken using name, id and properties of the entry.
  169. If there is a single processing type, the function might as well return true/false
  170. Default: returns true if entry is in at least one list (especially useful in
  171. cases with only one list, so there is no need to tell different lists apart)
  172.  
  173.  
  174. Callback functions and variables in contexts for external sources:
  175.  
  176. - name: identifier of the site (set with newContext())
  177.  
  178. - getUser(): see above
  179. - getSourceUserFromTargetUser(targetContextName, targetUser):
  180. returns the user name on the source site corresponding to the one on target
  181. site. This is needed to look for the saved lists.
  182. Default is looking for the last saved user (single-user scenario).
  183. - getPageType(): see above
  184. - processPage(pageType, isEntryPage): see above
  185.  
  186.  
  187. */
  188.  
  189.  
  190. var EL = new (function() {
  191. 'use strict';
  192. const SEP = '|';
  193. const STORAGE_SEP = '-';
  194. const FAKE_USER = '_';
  195. const DEFAULT_TYPE = '_DEF_';
  196. const MIN_INTERVAL = 100;
  197. const DEFAULT_INTERVAL = 1000;
  198.  
  199. var self = this;
  200.  
  201. var initialized = false;
  202. var failedInit = false;
  203. var mainContext; // target context object
  204. var isEntryPage; // boolean
  205. var allContexts; // array (cointains mainContext, too)
  206.  
  207.  
  208. /* PRIVATE members */
  209.  
  210. // Check if "object" has "property" of "type"
  211. // used to test if object "implements" a specific interface
  212. function checkProperty(object, property, type, optional = false) {
  213.  
  214. if (typeof object[property] !== type && (!optional || typeof object[property] !== 'undefined')) {
  215. console.error((optional ? 'Optionally, c' : 'C') + 'ontext must have a "' + property + '" property of type "' + type + '"');
  216. return false;
  217. }
  218. else return true;
  219. }
  220.  
  221.  
  222. // check if target context has the correct variables and functions
  223. function isValidTargetContext(ctx) {
  224. var valid = true;
  225.  
  226. valid &= checkProperty(ctx, 'name', 'string');
  227. valid &= checkProperty(ctx, 'getPageEntries', 'function');
  228. valid &= checkProperty(ctx, 'processItem', 'function');
  229. valid &= checkProperty(ctx, 'interval', 'number', true);
  230. valid &= checkProperty(ctx, 'isEntryPage', 'function', true);
  231. valid &= checkProperty(ctx, 'getPageType', 'function', true);
  232. valid &= checkProperty(ctx, 'isValidEntry', 'function', true);
  233. valid &= checkProperty(ctx, 'modifyEntry', 'function', true);
  234. valid &= checkProperty(ctx, 'determineType', 'function', true);
  235. valid &= checkProperty(ctx, 'getUser', 'function', true);
  236. valid &= checkProperty(ctx, 'getIdFromEntry', 'function', true);
  237. valid &= checkProperty(ctx, 'unProcessItem', 'function', true);
  238.  
  239. return !!valid;
  240. }
  241.  
  242.  
  243. // check if source context has the correct variables and functions
  244. function isValidSourceContext(ctx) {
  245. var valid = true;
  246.  
  247. valid &= checkProperty(ctx, 'name', 'string');
  248. valid &= checkProperty(ctx, 'getUser', 'function', true);
  249. valid &= checkProperty(ctx, 'getSourceUserFromTargetUser', 'function', true);
  250. valid &= checkProperty(ctx, 'getPageType', 'function', true);
  251.  
  252. return !!valid;
  253. }
  254.  
  255.  
  256. // standardized names for storage variables
  257. var storName = {
  258. 'listIdent': function(ctx) { return STORAGE_SEP + ctx.name + STORAGE_SEP + ctx.user; },
  259. 'listPrefix': function(ctx) { return 'List' + this.listIdent(ctx) + STORAGE_SEP; },
  260.  
  261. 'lastUser': function(ctx) { return ctx.name + STORAGE_SEP + 'lastUser'; },
  262. 'listOfLists': function(ctx) { return 'Lists' + this.listIdent(ctx); },
  263. 'listName': function(ctx, listName) { return this.listPrefix(ctx) + listName; },
  264. };
  265.  
  266.  
  267. // Return name of user currently logged on <ctx> site
  268. // Return last saved value and log error if no user is found
  269. this.getLoggedUser = function(ctx) {
  270. if (!ctx.getUser) return (ctx.user = FAKE_USER);
  271.  
  272. var user = ctx.getUser();
  273. if (!user) {
  274. console.error(ctx.name + ": user not logged in (or couldn't get user info) on URL " + document.URL);
  275. user = GM_getValue(storName.lastUser(ctx));
  276. console.error('Using last user: ' + user);
  277. }
  278. GM_setValue(storName.lastUser(ctx), user);
  279. ctx.user = user;
  280. return user;
  281. };
  282.  
  283.  
  284. // Return name of user to read for this source <ctx>, corresponding to the
  285. // user on the target context
  286. // if no mapping function is defined, take the last saved user, regardless
  287. // of target user
  288. this.getRemoteUser = function(ctx) {
  289. if (ctx.getSourceUserFromTargetUser) {
  290. ctx.user = ctx.getSourceUserFromTargetUser(mainContext.name, mainContext.user);
  291. if (!user) {
  292. console.error(ctx.name + ": cannot find user corresponding to '" + mainContext.user + "' on " + mainContext.name);
  293. }
  294. } else {
  295. ctx.user = GM_getValue(storName.lastUser(ctx));
  296. }
  297. return user;
  298. };
  299.  
  300.  
  301. // Regenerate and save the list of lists stored object, even if empty
  302. // returns the new list
  303. function regenerateListOfLists(ctx) {
  304. var allVariables = GM_listValues();
  305.  
  306. var listNames = allVariables.reduce(function(listNames, variable) {
  307. if (variable.startsWith(storName.listPrefix(ctx))) {
  308. listNames.push(variable.substring(storName.listPrefix(ctx).length));
  309. }
  310. return listNames;
  311. }, []);
  312.  
  313. var userData = JSON.stringify(listNames);
  314. GM_setValue(storName.listOfLists(ctx), userData);
  315. return listNames;
  316. }
  317.  
  318.  
  319. // Load a single saved lists
  320. function loadSavedList(listName) {
  321. var list;
  322. var userData = GM_getValue(listName);
  323. if (userData) {
  324. try {
  325. list = JSON.parse(userData);
  326. } catch(err) {
  327. alert("Error loading saved list named '" + listName + "'!\n" + err.message);
  328. }
  329. }
  330. return list;
  331. }
  332.  
  333.  
  334. // Load the list of lists, regenerating it if necessary
  335. // always returns an array, possibly empty
  336. function loadListOfLists(ctx) {
  337. var listNames = loadSavedList(storName.listOfLists(ctx));
  338.  
  339. if (!Array.isArray(listNames)) listNames = regenerateListOfLists(ctx);
  340. return listNames;
  341. }
  342.  
  343.  
  344. // Load lists for the current user
  345. this.loadSavedLists = function(ctx) {
  346. var listNames = loadListOfLists(ctx);
  347. var lists = {};
  348. var list;
  349. var mustRegenerateListOfLists = false;
  350.  
  351. listNames.forEach(function(listName) {
  352. list = loadSavedList(storName.listName(ctx, listName));
  353. if (list) lists[listName] = list;
  354. else mustRegenerateListOfLists = true;
  355. });
  356. if (mustRegenerateListOfLists) regenerateListOfLists(ctx);
  357. return lists;
  358. };
  359.  
  360.  
  361. // Save single list for the current user
  362. this.saveList = function(ctx, list, name) {
  363. var userData;
  364. var listNames = loadListOfLists(ctx);
  365.  
  366. if (listNames.indexOf(name) == -1) {
  367. listNames.push(name);
  368. userData = JSON.stringify(listNames);
  369. GM_setValue(storName.listOfLists(ctx), userData);
  370. }
  371.  
  372. userData = JSON.stringify(list);
  373. GM_setValue(storName.listName(ctx, name), userData);
  374. };
  375.  
  376.  
  377. // Receives an entry tt and finds all lists where tt.id appears
  378. this.inLists = function(tt) {
  379. var lists = {};
  380.  
  381. allContexts.forEach(function(ctx) {
  382. for (var list in ctx.allLists) {
  383. if (ctx.allLists[list][tt.id]) lists[ctx.name + SEP + list] = true;
  384. }
  385. });
  386.  
  387. return lists;
  388. };
  389.  
  390.  
  391. // Wrap ctx.getIdFromEntry and add error logging
  392. function _wrap_getIdFromEntry(ctx, entry) {
  393. var tt = ctx.getIdFromEntry(entry);
  394. if (!tt) console.error('Could not determine id :-( - for entry', entry);
  395. return tt;
  396. }
  397.  
  398.  
  399. // Process a single entry
  400. function processOneEntry(entry, ctx = mainContext) {
  401. var tt, lists, processingType;
  402.  
  403. // if entry has already been previously processed, skip it
  404. if (entry.ELProcessed || entry.ELInvalid) return;
  405.  
  406. // see if entry is valid
  407. if (ctx.isValidEntry && !ctx.isValidEntry(entry)) return;
  408.  
  409. if (ctx.getIdFromEntry) {
  410. tt = _wrap_getIdFromEntry(ctx, entry);
  411. if (!tt) return;
  412. }
  413.  
  414. if (ctx.modifyEntry) ctx.modifyEntry(entry);
  415. lists = ( tt ? self.inLists(tt) : {} );
  416.  
  417. processingType = (ctx.determineType
  418. ? ctx.determineType(lists, tt, entry)
  419. : Object.keys(lists).length > 0);
  420.  
  421. if (processingType) {
  422. ctx.processItem(entry, tt, processingType);
  423. entry.ELProcessingType = processingType;
  424. }
  425.  
  426. entry.ELProcessed = true; // set to "true" after processing (so we skip it on next pass)
  427. }
  428.  
  429.  
  430. // Process all entries in current page
  431. this.processAllEntries = function(ctx = mainContext) {
  432. var entries = ctx.getPageEntries();
  433. if (!entries) return;
  434.  
  435. for (var i = 0; i < entries.length; i++) {
  436. processOneEntry(entries[i], ctx);
  437. }
  438. };
  439.  
  440.  
  441. // handle the toggle event
  442. this.handleToggleButton = function(evt) {
  443. evt.stopPropagation();
  444. evt.preventDefault();
  445. var data = evt.target.dataset;
  446. var toggleList = (typeof data.toggleList === 'undefined' ? DEFAULT_TYPE : data.toggleList);
  447. var toggleType = (typeof data.toggleType === 'undefined' ? DEFAULT_TYPE : data.toggleType);
  448.  
  449. // get corresponding entry
  450. var entry = evt.target;
  451. if (Number.isInteger(Number(data.howToFindEntry))) {
  452. for (var i = 0; i < Number(data.howToFindEntry); i++) entry = entry.parentNode;
  453. } else {
  454. entry = entry.closest(data.howToFindEntry);
  455. }
  456.  
  457. self.toggleEntry(entry, toggleList, toggleType);
  458. };
  459.  
  460.  
  461. // add/remove entry from a list
  462. this.toggleEntry = function(entry, toggleList, toggleType) {
  463. var ctx = mainContext;
  464.  
  465. var tt = _wrap_getIdFromEntry(ctx, entry);
  466. if (!tt) return;
  467.  
  468. // check if item is in list
  469. var list = ctx.allLists[toggleList];
  470. if (!list) list = ctx.allLists[toggleList] = {};
  471. if (list[tt.id]) {
  472. delete list[tt.id];
  473. ctx.unProcessItem(entry, tt, toggleType);
  474. entry.ELProcessingType = '-' + toggleType;
  475. } else {
  476. list[tt.id] = tt.name;
  477. ctx.processItem(entry, tt, toggleType);
  478. entry.ELProcessingType = toggleType;
  479. }
  480. self.saveList(ctx, list, toggleList);
  481. };
  482.  
  483.  
  484.  
  485. /* PUBLIC members */
  486.  
  487. // utility function to create a new context, initialized with <name>
  488. this.newContext = function(name) {
  489. return { 'name': name };
  490. };
  491.  
  492.  
  493. // init function
  494. this.init = function(ctx) {
  495. initialized = false;
  496. failedInit = true;
  497. mainContext = null;
  498. isEntryPage = false;
  499. allContexts = [];
  500.  
  501. // check that passed context is good
  502. if (!isValidTargetContext(ctx)) {
  503. console.log('Invalid target context, aborting');
  504. return;
  505. }
  506.  
  507. isEntryPage = ( !ctx.isEntryPage || ctx.isEntryPage() );
  508. ctx.pageType = ( ctx.getPageType && ctx.getPageType() );
  509.  
  510. if (isEntryPage || ctx.pageType) {
  511. // find current logged in user, or quit script
  512. if (!self.getLoggedUser(ctx)) {
  513. console.log(ctx.name + ': no user is defined, aborting');
  514. return;
  515. }
  516. if (ctx.pageType && ctx.processPage) ctx.processPage(ctx.pageType, isEntryPage);
  517. }
  518.  
  519. mainContext = ctx;
  520. initialized = true;
  521. failedInit = false;
  522. };
  523.  
  524.  
  525. // startup function
  526. this.startup = function(ctx) {
  527. if (!initialized) {
  528. if (failedInit) return;
  529. self.init(ctx);
  530.  
  531. } else if (ctx) console.warn('Startup called with context parameter after init, ignoring ctx');
  532.  
  533. if (!isEntryPage) return;
  534.  
  535. // Load list data for this user from local storage
  536. ctx.allLists = self.loadSavedLists(ctx);
  537. allContexts.push(ctx);
  538.  
  539. // start the entry processing function
  540. self.processAllEntries();
  541. if (typeof ctx.interval === 'undefined' || ctx.interval >= MIN_INTERVAL) {
  542. // TODO we might consider using MutationObserver in the future, instead
  543. ctx.timer = setInterval(self.processAllEntries, ctx.interval || DEFAULT_INTERVAL);
  544. }
  545. };
  546.  
  547.  
  548. // add a source context
  549. this.addSource = function(ctx) {
  550. if (!initialized) {
  551. console.log('Main context is not initialized, aborting addSource');
  552. return;
  553. }
  554.  
  555. // check that passed context is good
  556. if (!isValidSourceContext(ctx)) {
  557. console.log('Invalid source context, aborting');
  558. return;
  559. }
  560.  
  561. ctx.pageType = ( ctx.getPageType && ctx.getPageType() );
  562.  
  563. if (ctx.pageType) {
  564. // find current logged in user, or quit script
  565. if (!self.getLoggedUser(ctx)) {
  566. console.log(ctx.name + ': no user is defined, aborting');
  567. return;
  568. }
  569. if (ctx.processPage) ctx.processPage(ctx.pageType, isEntryPage);
  570. }
  571.  
  572. if (!isEntryPage) return;
  573.  
  574. // find user corresponding to current logged in user, or quit script
  575. // TODO if (entryPage && pageType), remote user overwrites logged user
  576. if (!self.getRemoteUser(ctx)) {
  577. console.log(ctx.name + ': no remote user is defined, aborting');
  578. return;
  579. }
  580.  
  581. // Load list data for this user from local storage
  582. ctx.allLists = self.loadSavedLists(ctx);
  583. allContexts.push(ctx);
  584. };
  585.  
  586.  
  587. this.addToggleEventOnClick = function(button, howToFindEntry, toggleList = null, toggleType = null) {
  588. button.dataset.howToFindEntry = howToFindEntry;
  589. if (toggleList !== null) button.dataset.toggleList = toggleList;
  590. if (toggleType !== null) button.dataset.toggleType = toggleType;
  591. button.addEventListener('click', self.handleToggleButton, false);
  592. };
  593.  
  594.  
  595. this.markInvalid = function(entry) {
  596. entry.ELInvalid = true;
  597. return false;
  598. };
  599.  
  600.  
  601. })();