Fanfiction.net Unwanted Result Filter

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

目前為 2015-11-29 提交的版本,檢視 最新版本

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