Fanfiction.net Unwanted Result Filter

Make up for how limited Fanfiction.net's result filtering is

当前为 2015-12-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Fanfiction.net Unwanted Result Filter
  3. // @namespace http://www.ficfan.org/
  4. // @description Make up for how limited Fanfiction.net's result filtering is
  5. // compared to sites like Twisting the Hellmouth.
  6. // @copyright 2014-2015, Stephan Sokolow (http://www.ssokolow.com/)
  7. // @license MIT; http://www.opensource.org/licenses/mit-license.php
  8. // @version 0.1.4
  9. //
  10. // @require http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js
  11. // @require https://openuserjs.org/src/libs/sizzle/GM_config.js
  12. //
  13. // @grant GM_registerMenuCommand
  14. // @grant GM_getValue
  15. // @grant GM_setValue
  16. // @grant GM_log
  17. // @noframes
  18. //
  19. // @compatible firefox Tested regularly under Greasemonkey.
  20. // @compatible chrome Tested occasionally under Tampermonkey.
  21. //
  22. // @match *://www.fanfiction.net/*
  23. // ==/UserScript==
  24. (function($) {
  25.  
  26. /* NOTE TO USERS OF VERSION 0.0.1:
  27. * Sorry for erasing any modifications you made to the filter settings.
  28. *
  29. * I didn't put much thought into version 0.0.1 and, as a result, it was
  30. * impossible to release an update without erasing modifications.
  31. *
  32. * I'm now storing settings via GM_setValue, so it should never happen again
  33. * and there's a proper configuration GUI available at
  34. * Greasemonkey > User Script Commands... > Configure Result Filter...
  35. */
  36.  
  37. // ----==== Configuration ====----
  38.  
  39. var IGNORED_OPACITY = 0.3;
  40.  
  41. var fieldDefs = {
  42. 'filter_slash': {
  43. 'section': ['Slash Filter',
  44. 'Hide stories with slash based on warnings in story descriptions'],
  45. 'label': 'Enabled',
  46. 'labelPos': 'right',
  47. 'type': 'checkbox',
  48. 'default': true,
  49. },
  50. 'hide_slash': {
  51. 'label': 'No Placeholder',
  52. 'labelPos': 'right',
  53. 'type': 'checkbox',
  54. 'default': false,
  55. },
  56. 'slash_pat': {
  57. 'label': 'Slash is...',
  58. 'title': 'A regular expression which matches slash in descriptions',
  59. 'type': 'text',
  60. 'size': 255,
  61. 'default': ".*(slash|yaoi)([.,!: ]|$)"
  62. },
  63. 'not_slash_pat': {
  64. 'label': '...but not...',
  65. 'title': 'A regular expression which matches "not slash" and so on',
  66. 'type': 'text',
  67. 'size': 255,
  68. 'default': ".*(fem|not?[ ]+)(slash|yaoi)([.,!: ]|$)"
  69. },
  70. 'filter_cats': {
  71. 'section': ['Unwanted Category Filter',
  72. 'Hide unwanted fandoms in author pages and "All Crossovers" searches'],
  73. 'label': 'Enabled',
  74. 'labelPos': 'right',
  75. 'type': 'checkbox',
  76. 'default': true,
  77. },
  78. 'hide_cats': {
  79. 'label': 'No Placeholder',
  80. 'labelPos': 'right',
  81. 'type': 'checkbox',
  82. 'default': false,
  83. },
  84. 'unwanted_cats': {
  85. 'label': 'Unwanted categories (One per line, blank lines and lines ' +
  86. 'beginning with # will be ignored):',
  87. 'type': 'textarea',
  88. 'size': 100,
  89. 'default': [
  90. "# --== Never wanted ==-- ",
  91. "Invader Zim",
  92. "Supernatural",
  93. "Twilight",
  94. "",
  95. "# --== Not right now ==-- ",
  96. "Harry Potter & Avengers",
  97. "Naruto",
  98. ].join("\n"),
  99. },
  100. 'unwanted_cats_escape': {
  101. 'label': 'Lines are literal strings (uncheck for regular expressions)',
  102. 'labelPos': 'right',
  103. 'title': 'NOTE: Leading/trailing whitespace is always ignored and ' +
  104. 'newlines always have OR behaviour.',
  105. 'type': 'checkbox',
  106. 'default': true,
  107. },
  108. 'unwanted_cats_commute': {
  109. 'label': 'Automatically generate "B & A" lines from "A & B" lines',
  110. 'labelPos': 'right',
  111. 'title': "WARNING: This will break regexes with & inside () or []",
  112. 'type': 'checkbox',
  113. 'default': true,
  114. }
  115. // TODO: Ideas for future filters:
  116. // - Genre (allowing more than one whitelist/blacklist entry)
  117. // TODO: Ideas for filters requiring an in-page UI:
  118. // - sort orders not already offered (eg. faves/follows on authors faves)
  119. // - min/max words as a freeform range entry
  120. // - already read (ideally, support hooking in an external API w/i caching)
  121. // - filter sets which can be toggled
  122. };
  123.  
  124. var frame = $('<div>').appendTo('body')[0];
  125. var config_params = {
  126. 'id': 'ffnet_result_filter',
  127. 'title': 'Fanfiction.net Unwanted Result Filter',
  128. 'fields': fieldDefs,
  129. 'css': ('#ffnet_result_filter ' + [
  130. // Match Fanfiction.net styling more closely
  131. ".section_header { background-color: #339 !important; }",
  132. ".section_desc { background-color: #f6f7ee !important; border: none; " +
  133. " padding: 1px; }",
  134. ".config_header { font-size: 16pt; }",
  135. ".field_label { font-size: 13px; font-weight: normal; }",
  136. // Layout adjustments for using a non-iframe container
  137. "#ffnet_result_filter_wrapper { flex: 1 1 auto; display: flex; " +
  138. " flex-direction: column; }\n" +
  139. ".force_display_flex { display: flex !important; }",
  140. "label { display: inline; }",
  141. ".section_header_holder { padding: 15px; margin-bottom: 2em; }",
  142. ".modal-footer { margin-top: -2em; }",
  143. ".saveclose_buttons.btn { margin: 0 0 0 5px !important; }",
  144. ".reset_holder { padding-right: 12px; }",
  145. "input[type=checkbox] { margin: 2px 4px 2px; }",
  146. // Form layout fixes
  147. "input[type=text], textarea " +
  148. " { width: calc(100% - 1.1em); resize: vertical; }\n" +
  149. "#ffnet_result_filter_filter_slash_var, " +
  150. "#ffnet_result_filter_filter_cats_var, " +
  151. "#ffnet_result_filter_hide_slash_var, " +
  152. "#ffnet_result_filter_hide_cats_var " +
  153. " { display: inline-block; margin-right: 1em !important; } " +
  154. "#ffnet_result_filter_field_unwanted_cats { min-height: 10em; }"
  155. ].join('\n#ffnet_result_filter ')),
  156. 'events': {
  157. 'open': function(doc) {
  158. // Reconcile GM_config and Bootstrap CSS
  159. $(this.frame).css({
  160. 'z-index': 1050,
  161. 'top': '50px',
  162. 'height': 'calc(99% - 100px)',
  163. 'flex-direction': 'column',
  164. 'border-color': '#d4d4d4',
  165. }).addClass('modal fade in force_display_flex');
  166. var header = $('.config_header').addClass('modal-header');
  167. $('<div>', {id: 'ffnrfilter_contentbox'})
  168. .insertAfter(header)
  169. .css('flex', '1')
  170. .append($('.section_header_holder').detach());
  171. $('#ffnet_result_filter_buttons_holder').addClass('modal-footer');
  172. $('button', this.frame).addClass('btn');
  173. $('.reset_holder').addClass('btn pull-left');
  174. $("<div>", {'id': 'gm_modal_back'}).click(function() {
  175. GM_config.close();
  176. }).addClass('modal-backdrop fade in').appendTo('body');
  177. },
  178. 'close': function() {
  179. $(this.frame).removeClass('force_display_flex');
  180. $('#gm_modal_back').remove();
  181. }
  182. },
  183. 'frame': frame,
  184. };
  185.  
  186. // ----==== Functions ====----
  187.  
  188. /// Escape string for literal meaning inside a regular expression
  189. /// Source: http://stackoverflow.com/a/3561711/435253
  190. var re_escape = function(s) {
  191. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  192. };
  193.  
  194. /// Use with Array.filter() to remove comments and blank lines
  195. var rows_filter = function(elem, idx, arr) {
  196. elem = elem.trim()
  197. if (elem.charAt(0) == '#' || !elem) {
  198. return false;
  199. }
  200. return true;
  201. };
  202.  
  203. /// Parse an array from a newline-delimited string containing # comments
  204. var parse_lines = function(s) {
  205. return s.split("\n").map(function(e, i, a) {
  206. return e.trim();
  207. }).filter(rows_filter);
  208. };
  209.  
  210. /// Parse a usable list of category patterns from a raw string
  211. var parse_cats_list = function(s, escape, commute) {
  212. // Parse the config
  213. var cats_raw = parse_lines(s);
  214. if (escape) { cats_raw = cats_raw.map(re_escape) }
  215. if (commute) {
  216. var cats_out = [];
  217. for (var i = 0, len = cats_raw.length; i < len; i++) {
  218. var line = cats_raw[i];
  219. cats_out.push(line);
  220. var parts = line.split(' & ');
  221. if (parts.length > 1) {
  222. cats_out.push(parts[1] + ' & ' + parts[0]);
  223. }
  224. }
  225. }
  226. return cats_out;
  227. }
  228.  
  229. /// Hide a story entry in a way it can be recovered
  230. var hide_entry = function(node) {
  231. $(node).addClass('filtered').hide();
  232. };
  233.  
  234. /// Hide a story entry and add a clickable placeholder
  235. var add_placeholder = function(node, reason) {
  236. var $story = $(node);
  237. var $placeholder = $story.clone();
  238.  
  239. $placeholder.html("Click to Show (" + reason + ")").css({
  240. minHeight: 0,
  241. maxHeight: '1em',
  242. color: 'lightgray',
  243. textAlign: 'center',
  244. cursor: 'pointer',
  245. }).click($story, function(e) {
  246. $(this).slideUp();
  247. e.data.css('min-height', 0).slideDown();
  248. }).addClass('filter_placeholder').insertBefore($story);
  249. hide_entry($story);
  250. };
  251.  
  252. /// Code which must be re-run to reapply filters after changing the config
  253. var initialize_filters_and_apply = function() {
  254. // Parse the config
  255. var bad_cats = parse_cats_list(
  256. GM_config.get('unwanted_cats'),
  257. GM_config.get('unwanted_cats_escape'),
  258. GM_config.get('unwanted_cats_commute')
  259. );
  260.  
  261. // Generate RegExp objects from the parsed config
  262. var slash_re = new RegExp(GM_config.get('slash_pat'), 'i');
  263. var not_slash_re = new RegExp(GM_config.get('not_slash_pat'), 'i');
  264. var cats_re = new RegExp("- (.*(" + bad_cats.join('|') + ').*) - Rated:.*');
  265. var cat_link_re = new RegExp(bad_cats.join('|'));
  266.  
  267. // Clean up after any previous run
  268. $(".filter_placeholder").remove();
  269. $(".filtered").show();
  270.  
  271. var results = $(".z-list");
  272. for (var i = 0, reslen = results.length; i < reslen; i++) {
  273. var story = results[i];
  274. var meta_row = $('.xgray', story).text();
  275. var description = $('.z-padtop', story).contents()[0].data;
  276.  
  277. // TODO: Redesign to collapse runs of hidden entries
  278. var reason = null;
  279. if (GM_config.get('filter_slash') && slash_re.test(description)
  280. && !not_slash_re.test(description)) {
  281. if (GM_config.get('hide_slash')) {
  282. hide_entry(story);
  283. } else {
  284. add_placeholder(story, "Slash");
  285. }
  286. } else if (GM_config.get('filter_cats')) {
  287. var matches = meta_row.match(cats_re);
  288. if (matches && matches.length > 0) {
  289. if (GM_config.get('hide_cats')) {
  290. hide_entry(story);
  291. } else {
  292. add_placeholder(story, matches[1]);
  293. }
  294. }
  295. }
  296. }
  297.  
  298. $('#list_output a').each(function() {
  299. $this = $(this);
  300. if (cat_link_re.test($this.text())) {
  301. $this.css('opacity', IGNORED_OPACITY);
  302. }
  303. });
  304. };
  305.  
  306. // ----==== Begin Main Program ====----
  307.  
  308. // Stuff which either must or need only be called once
  309. GM_config.init(config_params);
  310. GM_config.onSave = initialize_filters_and_apply;
  311. GM_registerMenuCommand("Configure Result Filter...",
  312. function() { GM_config.open(); }, 'C');
  313.  
  314. // Clear out ad box which misaligns "Hidden" message if it's first result
  315. $($('#content_wrapper_inner ins.adsbygoogle').parent()[0]).remove();
  316.  
  317. initialize_filters_and_apply();
  318.  
  319. }).call(this, jQuery);