Advertisement
Guest User

Untitled

a guest
Apr 5th, 2016
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.43 KB | None | 0 0
  1. // ==UserScript==
  2. // @name Robin Enhancement Script
  3. // @namespace https://www.reddit.com/
  4. // @version 3.1.0
  5. // @description Highlight mentions, make link clickable, use channels & automatically remove spam
  6. // @author Bag
  7. // @author netnerd01
  8. // @match https://www.reddit.com/robin*
  9. // @grant none
  10. // @grant GM_setValue
  11. // @grant GM_getValue
  12. // ==/UserScript==
  13. (function() {
  14.  
  15. // Grab users username + play nice with RES
  16. var robin_user = $("#header-bottom-right .user a").first().text();
  17. var ignored_users = {};
  18.  
  19. // for spam counter - very important i know :P
  20. var blocked_spam_el = null;
  21. var blocked_spam = 0;
  22. var user_last_message = '';
  23. //
  24. var _robin_grow_detected = false;
  25.  
  26. /**
  27. * Pull tabber out in to semi-stand alone module
  28. * Big thanks to netnerd01 for his pre-work on this
  29. *
  30. * Basic usage - tabbedChannels.init( dom_node_to_add_tabs_to );
  31. * and hook up tabbedChannels.proccessLine(lower_case_text, jquery_of_line_container); to each line detected by the system
  32. */
  33. var tabbedChannels = new function(){
  34. var _self = this;
  35.  
  36. // Default options
  37. this.channels = ["~","*",".","%","$","#",";","^","<3",":gov","#rpg","@"];
  38. this.mode = 'single';
  39.  
  40. // internals
  41. this.unread_counts = {};
  42. this.$el = null;
  43. this.$opt = null;
  44. this.defaultRoomClasses = '';
  45. this.channelMatchingCache = [];
  46.  
  47. //channels user is in currently
  48. this.currentRooms = 0;
  49.  
  50. // When channel is clicked, toggle it on or off
  51. this.toggle_channel = function(e){
  52. var channel = $(e.target).data("filter");
  53. if(channel===null)return; // no a channel
  54.  
  55. if(!$("#robinChatWindow").hasClass("robin-filter-" + channel)){
  56. _self.enable_channel(channel);
  57. $(e.target).addClass("selected");
  58. // clear unread counter
  59. $(e.target).find("span")[0].innerHTML = '0';
  60. _self.unread_counts[channel] = 0;
  61.  
  62. // set key indicatior (blanking others)
  63. _self.$el.find(".robin-filters").children("span").each(function(){$(this).find("span")[1].innerHTML = '◇';});
  64. $(e.target).find("span")[1].innerHTML = '◆';
  65. }else{
  66. $(e.target).removeClass("selected");
  67. _self.disable_channel(channel);
  68.  
  69. // set key indicators
  70. _self.$el.find(".robin-filters").children("span").each(function(){$(this).find("span")[1].innerHTML = '◇';});
  71. _self.$el.find("span[data-filter=" + _self.channels.indexOf($("#robinChatWindow").attr("data-channel-key")) + "]").find("span")[1].innerHTML = '◆';
  72. }
  73.  
  74. // scroll everything correctly
  75. _scroll_to_bottom();
  76. };
  77.  
  78. // Enable a channel
  79. this.enable_channel = function(channel_id){
  80.  
  81. // if using room type "single", deslect other rooms on change
  82. if(this.mode == "single"){
  83. this.disable_all_channels();
  84. }
  85.  
  86. $("#robinChatWindow").addClass("robin-filter robin-filter-" + channel_id);
  87. $("#robinChatWindow").attr("data-channel-key", this.channels[channel_id]);
  88. this.currentRooms++;
  89. // unselect show all
  90. _self.$el.find("span.all").removeClass("selected");
  91. };
  92.  
  93. // disable a channel
  94. this.disable_channel = function(channel_id){
  95. $("#robinChatWindow").removeClass("robin-filter-" + channel_id);
  96. // update key
  97. $("#robinChatWindow").attr("data-channel-key", $(".robin-filters span.selected").first().data("filter-name"));
  98. if(!$(".robin-filters span.selected").first().data("filter-name")) $("#robinChatWindow").attr("data-channel-key", "");
  99. this.currentRooms--;
  100.  
  101. // no rooms selcted, run "show all"
  102. if(this.currentRooms == 0) this.disable_all_channels();
  103. };
  104.  
  105. // turn all channels off
  106. this.disable_all_channels = function(e){
  107. $("#robinChatWindow").attr("class", _self.defaultRoomClasses);
  108. _self.$el.find(".robin-filters > span").removeClass("selected");
  109. this.currentRooms = 0;
  110.  
  111. // reset key indicators
  112. _self.$el.find(".robin-filters").children("span").each(function(){$(this).find("span")[1].innerHTML = '◇';});
  113.  
  114. _self.$el.find("span.all").addClass("selected");
  115. _scroll_to_bottom();
  116. };
  117.  
  118. // render tabs
  119. this.drawTabs = function(){
  120. html = '';
  121. for(var i in this.channels){
  122. if(typeof this.channels[i] === 'undefined') continue;
  123. html += '<span data-filter="' + i + '" data-filter-name="'+ this.channels[i] +'">' + this.channels[i] + ' (<span>0</span>) <span style="float:right;padding-right:4px;font-size:25px;height:0px;top:-11px;position:relative;">◇</span></span> ';
  124.  
  125.  
  126. }
  127. this.$el.find(".robin-filters").html(html);
  128. };
  129.  
  130. // Add new channel
  131. this.addChannel = function(new_channel){
  132. if(this.channels.indexOf(new_channel) === -1){
  133. this.channels.push(new_channel);
  134. this.unread_counts[this.channels.length-1] = 0;
  135. this.updateChannelMatchCache();
  136. this.saveChannelList();
  137. this.drawTabs();
  138.  
  139. // refresh everything after redraw
  140. this.disable_all_channels();
  141. }
  142. };
  143.  
  144. // remove existing channel
  145. this.removeChannel = function(channel){
  146. if(confirm("are you sure you wish to remove the " + channel + " channel?")){
  147. var idx = this.channels.indexOf(channel);
  148. delete this.channels[idx];
  149. this.updateChannelMatchCache();
  150. this.saveChannelList();
  151. this.drawTabs();
  152.  
  153. // refresh everything after redraw
  154. this.disable_all_channels();
  155. }
  156. };
  157.  
  158.  
  159. // save channel list
  160. this.saveChannelList = function(){
  161. // clean array before save
  162. var channels = this.channels.filter(function (item) { return item != undefined });
  163. GM_setValue("robin-enhance-channels", channels);
  164. };
  165.  
  166. // Change chat mode
  167. this.changeChannelMode = function(e){
  168. _self.mode = $(this).data("type");
  169.  
  170. // swicth bolding
  171. $(this).parent().find("span").css("font-weight","normal");
  172. $(this).css("font-weight","bold");
  173. _self.disable_all_channels();
  174.  
  175. // Update mode setting
  176. GM_setValue("robin-enhance-mode", _self.mode);
  177. };
  178.  
  179. this.updateChannelMatchCache = function(){
  180. var order = this.channels.slice(0);
  181. order.sort(function(a, b){
  182. return b.length - a.length; // ASC -> a - b; DESC -> b - a
  183. });
  184. for(var i in order){
  185. order[i] = this.channels.indexOf(order[i]);
  186. }
  187. // sorted array of channel name indexs
  188.  
  189. this.channelMatchingCache = order;
  190. };
  191.  
  192. // Procces each chat line to create text
  193. this.proccessLine = function(text, $element){
  194. var i, idx, channel;
  195. for(i=0; i< this.channelMatchingCache.length; i++){
  196. idx = this.channelMatchingCache[i];
  197. channel = this.channels[idx];
  198.  
  199. if(typeof channel === 'undefined') continue;
  200.  
  201. if(text.indexOf(channel) === 0){
  202. $element.addClass("robin-filter-" + idx +" in-channel");
  203. this.unread_counts[idx]++;
  204. return;
  205. }
  206. }
  207. };
  208.  
  209. // If in one channel, auto add channel keys
  210. this.submit_helper = function(){
  211. if($("#robinChatWindow").hasClass("robin-filter")){
  212. // auto add channel key
  213. var channel_key = $("#robinChatWindow").attr("data-channel-key");
  214.  
  215. if($(".text-counter-input").val().indexOf("/me") === 0){
  216. $(".text-counter-input").val("/me " + channel_key + " " + $(".text-counter-input").val().substr(3));
  217. }else if($(".text-counter-input").val().indexOf("/") !== 0){
  218. // if its not a "/" command, add channel
  219. $(".text-counter-input").val(channel_key + " " + $(".text-counter-input").val());
  220. }
  221. }
  222. };
  223.  
  224. // Update everuything
  225. this.tick = function(){
  226. _self.$el.find(".robin-filters").children("span").each(function(){
  227. if($(this).hasClass("selected")) return;
  228. $(this).find("span")[0].innerHTML = _self.unread_counts[$(this).data("filter")];
  229. });
  230. };
  231.  
  232. // Init tab zone
  233. this.init = function($el){
  234. // Load channels
  235. if(GM_getValue("robin-enhance-channels")){
  236. this.channels = GM_getValue("robin-enhance-channels");
  237. }
  238. if(GM_getValue("robin-enhance-mode")){
  239. this.mode = GM_getValue("robin-enhance-mode");
  240. }
  241.  
  242. // init counters
  243. for(var i in this.channels){
  244. this.unread_counts[i] = 0;
  245. }
  246.  
  247. // update channel cache
  248. this.updateChannelMatchCache();
  249.  
  250. // set up el
  251. this.$el = $el;
  252.  
  253. // Create inital markup
  254. this.$el.html("<span class='all selected'>Everything</span><span><div class='robin-filters'></div></span><span class='more'>[Options]</span>");
  255. this.$opt = $("<div class='robin-channel-add' style='display:none'><input name='add-channel'><button>Add channel</button> <span class='channel-mode'>Channel Mode: <span title='View one channel at a time' data-type='single'>Single</span> | <span title='View many channels at once' data-type='multi'>Multi</span></span></div>").insertAfter(this.$el);
  256.  
  257. // Attach events
  258. this.$el.find(".robin-filters").click(this.toggle_channel);
  259. this.$el.find("span.all").click(this.disable_all_channels);
  260. this.$el.find("span.more").click(function(){ $(".robin-channel-add").slideToggle(); });
  261. this.$el.find(".robin-filters").bind("contextmenu", function(e){
  262. e.preventDefault();
  263. e.stopPropagation();
  264. var chan_id = $(e.target).data("filter");
  265. if(chan_id===null)return; // no a channel
  266. _self.removeChannel(_self.channels[chan_id]);
  267. });
  268. // Form events
  269. this.$opt.find(".channel-mode span").click(this.changeChannelMode);
  270. this.$opt.find("button").click(function(){
  271. var new_chan = _self.$opt.find("input[name='add-channel']").val();
  272. if(new_chan != '') _self.addChannel(new_chan);
  273. _self.$opt.find("input[name='add-channel']").val('');
  274. });
  275.  
  276.  
  277. $("#robinSendMessage").submit(this.submit_helper);
  278.  
  279. // store default room class
  280. this.defaultRoomClasses = $("#robinChatWindow").attr("class");
  281.  
  282. // redraw tabs
  283. this.drawTabs();
  284.  
  285. // start ticker
  286. setInterval(this.tick, 1000);
  287. }
  288. };
  289.  
  290. /**
  291. * Check if a message is "spam"
  292. */
  293. var is_spam = function(line){
  294. return (
  295. // Hide auto vote messages
  296. (/^voted to (grow|stay|abandon)/.test(line)) ||
  297. // random unicode?
  298. (/[\u0080-\uFFFF]/.test(line)) ||
  299. // hide any auto voter messages
  300. (/\[.*autovoter.*\]/.test(line)) ||
  301. // Common bots
  302. (/^(\[binbot\]|\[robin-grow\])/.test(line)) ||
  303. // repeating chars in line (more than 5). e.g. aaaaaaa !!!!!!!!
  304. (/(.)\1{5,}/.test(line)) ||
  305. // Some common messages
  306. (/(voting will end in approximately|\[i spam the most used phrase\]|\[message from creator\]|\[.*bot.*\])/.test(line)) ||
  307. // no spaces = spam if its longer than 25 chars (dont filter links)
  308. (line.indexOf(" ") === -1 && line.length > 25 && line.indexOf("http") === -1) ||
  309. // repeating same word
  310. /(\b\S+\b)\s+\b\1\b/i.test(line)
  311. );
  312. };
  313.  
  314. /**
  315. * Check if a message is from an ignored user
  316. *
  317. */
  318. var is_ignored = function($usr, $ele){
  319. // no user name, go looking for when said it
  320. if($usr.length === 0){
  321. while($usr.length === 0){
  322. $ele = $ele.prev();
  323. $usr = $ele.find(".robin--username");
  324. }
  325. }
  326. // are they ignored?
  327. return (ignored_users[$usr.text()]);
  328. };
  329.  
  330. /**
  331. * Make links clickable
  332. *
  333. */
  334. var auto_link = function($msg){
  335. var text = $msg.html(); // read as html so stuff stays escaped
  336. // normal links
  337. text = text.replace(/\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim, '<a target="blank" href="$&">$&</a>');
  338. // reddit subreddit links
  339. text = text.replace(/ \/r\/(\w+)/gim, ' <a target="blank" href="https://reddit.com/r/$1">/r/$1</a>');
  340. // update text
  341. $msg.html(text);
  342. };
  343.  
  344. /**
  345. * Mute a user
  346. */
  347. var _mute_user = function(usr){
  348. // Add to ignore list
  349. ignored_users[usr] = true;
  350. _render_muted_list();
  351. };
  352.  
  353. /**
  354. * un-mute a user
  355. */
  356. var _unmute_user = function(usr){
  357. // Add to ignore list
  358. delete ignored_users[usr];
  359. _render_muted_list();
  360. };
  361.  
  362. // Render list of ignored users
  363. var _render_muted_list = function(){
  364. var html = "<strong>Ignored users</strong><br>";
  365. for(var u in ignored_users){
  366. html += "<div data-usr='"+ u + "'>" + u + " - [unmute]</div>";
  367. }
  368. $("#muted_users").html(html);
  369. };
  370.  
  371. // Scroll chat back to bottom
  372. var _scroll_to_bottom = function(){
  373. $("#robinChatWindow").scrollTop($("#robinChatMessageList").height());
  374. };
  375.  
  376. var update_spam_count = function(){
  377. blocked_spam++;
  378. blocked_spam_el.innerHTML = blocked_spam;
  379. };
  380.  
  381. var fill_name = function(e){
  382. e.preventDefault();
  383. e.stopPropagation();
  384.  
  385. // if text area blank, prefill name. if not, stick it on the end
  386. if($(".text-counter-input").val() === ''){
  387. $(".text-counter-input").val($(this).text() + ' ').focus();
  388. }else{
  389. $(".text-counter-input").val($(".text-counter-input").val() + ' ' + $(this).text()).focus();
  390. }
  391. };
  392.  
  393. /**
  394. * Parse a link and apply changes
  395. */
  396. var parse_line = function($ele){
  397. var $msg = $ele.find(".robin-message--message");
  398. var $usr = $ele.find(".robin--username");
  399. var line = $msg.text().toLowerCase();
  400. // dont parse system messages
  401. if($ele.hasClass("robin--user-class--system")){
  402. if(line.indexOf("ratelimit | you are doing that too much") !== -1){
  403. $(".text-counter-input").val(user_last_message);
  404. }
  405. return;
  406. }
  407.  
  408. // If user is ignored or message looks like "Spam". hide it
  409. if (is_ignored($usr, $ele) || is_spam(line)) {
  410. $ele.addClass("spam-hidden");
  411. update_spam_count();
  412. }
  413.  
  414. // Highlight mentions
  415. if(line.indexOf(robin_user) !== -1){
  416. $ele.addClass("user-mention");
  417. }
  418.  
  419. // Make links clickable
  420. if(!_robin_grow_detected && line.indexOf("http") !== -1){
  421. auto_link($msg);
  422. }
  423.  
  424. // Add mute button to users
  425. if(!$ele.hasClass("robin--user-class--system") && $usr.text() != robin_user){
  426. $("<span style='font-size:.8em;cursor:pointer'> [mute] </span>").insertBefore($usr).click(function(){
  427. _mute_user($usr.text());
  428. });
  429. }
  430.  
  431. // Track channels
  432. tabbedChannels.proccessLine(line, $ele);
  433.  
  434. // bind click to use (override other click events if we can)
  435. $usr.bindFirst("click", fill_name);
  436. };
  437.  
  438.  
  439. // Detect changes, are parse the new message
  440. $("#robinChatWindow").on('DOMNodeInserted', function(e) {
  441. if ($(e.target).is('div.robin-message')) {
  442. // Apply changes to line
  443. parse_line($(e.target));
  444. }
  445. });
  446.  
  447. // When everything is ready
  448. $(document).ready(function(){
  449.  
  450. // Set default spam filter type
  451. $("#robinChatWindow").addClass("hide-spam");
  452.  
  453. // Add checkbox to toggle "hide" behaviors
  454. $("#robinDesktopNotifier").append("<label><input type='checkbox' checked='checked'>Hide spam completely (<span id='spamcount'>0</span> removed)</label>").click(function(){
  455. if($(this).find("input").is(':checked')){
  456. $("#robinChatWindow").removeClass("mute-spam").addClass("hide-spam");
  457. }else{
  458. $("#robinChatWindow").removeClass("hide-spam").addClass("mute-spam");
  459. }
  460. // correct scroll after spam filter change
  461. _scroll_to_bottom();
  462. });
  463.  
  464. blocked_spam_el = $("#spamcount")[0];
  465.  
  466. // Add Muted list & hook up unmute logic
  467. $('<div id="muted_users" class="robin-chat--sidebar-widget robin-chat--notification-widget"><strong>Ignored users</strong></div>').insertAfter($("#robinDesktopNotifier"));
  468. $('#muted_users').click(function(e){
  469. var user = $(e.target).data("usr");
  470. if(user) _unmute_user(user);
  471. });
  472.  
  473. // Init tabbed channels
  474. tabbedChannels.init($('<div id="filter_tabs"></div>').insertAfter("#robinChatWindow"));
  475.  
  476. // store i copy of last message, in case somthing goes wrong (rate limit)
  477. $("#robinSendMessage").submit(function(){
  478. user_last_message = $(".text-counter-input").val();
  479. });
  480.  
  481. });
  482.  
  483. // fix by netnerd01
  484. var stylesheet = document.createElement('style');
  485. document.head.appendChild(stylesheet);
  486. stylesheet = stylesheet.sheet;
  487.  
  488. // filter for channel
  489. stylesheet.insertRule("#robinChatWindow.robin-filter div.robin-message { display:none; }", 0);
  490. stylesheet.insertRule("#robinChatWindow.robin-filter div.robin-message.robin--user-class--system { display:block; }", 0);
  491. for(var c=0;c<35;c++){
  492. stylesheet.insertRule("#robinChatWindow.robin-filter.robin-filter-"+c+" div.robin-message.robin-filter-"+c+" { display:block; }", 0);
  493. }
  494.  
  495. // Styles for filter tabs
  496. stylesheet.insertRule("#filter_tabs {width:100%; display: table; table-layout: fixed; background:#d7d7d2; border-bottom:1px solid #efefed;}",0);
  497. stylesheet.insertRule("#filter_tabs > span {width:90%; display: table-cell;}",0);
  498. stylesheet.insertRule("#filter_tabs > span.all, #filter_tabs > span.more {width:60px; text-align:center; vertical-align:middle; cursor:pointer;}",0);
  499. stylesheet.insertRule("#filter_tabs > span.all.selected, #filter_tabs > span.all.selected:hover {background: #fff;}", 0);
  500. stylesheet.insertRule("#filter_tabs .robin-filters { display: table; width:100%;table-layout: fixed; '}", 0);
  501. stylesheet.insertRule("#filter_tabs .robin-filters > span { padding: 5px 2px;text-align: center; display: table-cell; cursor: pointer;width:2%; vertical-align: middle; font-size: 1.1em;}", 0);
  502. stylesheet.insertRule("#filter_tabs .robin-filters > span.selected, #filter_tabs .robin-filters > span:hover { background: #fff;}", 0);
  503. stylesheet.insertRule("#filter_tabs .robin-filters > span > span {pointer-events: none;}", 0);
  504.  
  505. stylesheet.insertRule(".robin-channel-add {padding:5px; display:none;}", 0);
  506. stylesheet.insertRule(".robin-channel-add input {padding: 2.5px; }", 0);
  507. stylesheet.insertRule(".robin-channel-add .channel-mode {float:right; font-size:1.2em;padding:5px;}", 0);
  508. stylesheet.insertRule(".robin-channel-add .channel-mode span {cursor:pointer}", 0);
  509. //mentions should show even in filter view
  510. stylesheet.insertRule("#robinChat #robinChatWindow div.robin-message.user-mention { display:block; font-weight:bold; }", 0);
  511.  
  512. // Add initial styles for "spam" messages
  513. stylesheet.insertRule("#robinChat #robinChatWindow.hide-spam div.robin-message.spam-hidden { display:none; }", 0);
  514. stylesheet.insertRule("#robinChat #robinChatWindow.mute-spam div.robin-message.spam-hidden { opacity:0.3; font-size:1.2em; }", 0);
  515.  
  516. // muted user box
  517. stylesheet.insertRule("#muted_users { font-size:1.2em; }", 0);
  518. stylesheet.insertRule("#muted_users div { padding: 2px 0; }", 0);
  519. stylesheet.insertRule("#muted_users strong { font-weight:bold; }", 0);
  520.  
  521. // FIX RES nightmode (ish) [ by Kei ]
  522. stylesheet.insertRule(".res-nightmode #robinChatWindow div.robin-message { color: #ccc; }", 0);
  523. stylesheet.insertRule(".res-nightmode .robin-chat--sidebar-widget { background: #222; color: #ccc;}", 0);
  524. stylesheet.insertRule(".res-nightmode .robin-room-participant { background: #222; color: #999;}", 0);
  525. stylesheet.insertRule(".res-nightmode #filter_tabs {background: rgb(51, 51, 51);}", 0);
  526. stylesheet.insertRule(".res-nightmode #filter_tabs .robin-filters > span.selected,.res-nightmode #filter_tabs .robin-filters > span:hover,.res-nightmode #filter_tabs > span.all.selected,.res-nightmode #filter_tabs > span.all:hover {background: rgb(34, 34, 34)}", 0);
  527. stylesheet.insertRule(".res-nightmode .robin-chat--input { background: #222 }", 0);
  528. stylesheet.insertRule(".res-nightmode .robin--presence-class--away .robin--username {color: #999;}", 0);
  529. stylesheet.insertRule(".res-nightmode .robin--presence-class--present .robin--username {color: #ccc;}", 0);
  530. stylesheet.insertRule(".res-nightmode #robinChat .robin--user-class--self .robin--username { color: #999; }", 0);
  531. stylesheet.insertRule(".res-nightmode .robin-chat--vote { background: #777; color: #ccc;}", 0);
  532. stylesheet.insertRule(".res-nightmode .robin-chat--buttons button.robin-chat--vote.robin--active { background: #ccc; color:#999; }", 0);
  533.  
  534. $(document).ready(function(){
  535. setTimeout(function(){
  536. // Play nice with robin grow (makes room for tab bar we insert)
  537. if($(".usercount.robin-chat--vote").length !== 0){
  538. _robin_grow_detected = true;
  539. stylesheet.insertRule("#robinChat.robin-chat .robin-chat--body { height: calc(100vh - 150px); }", 0);
  540. }
  541. },500);
  542. });
  543.  
  544. // Allow me to sneek functions in front of other libaries - used when working with robin grow >.< sorry guys
  545. //http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t
  546. $.fn.bindFirst = function(name, fn) {
  547. // bind as you normally would
  548. // don't want to miss out on any jQuery magic
  549. this.on(name, fn);
  550.  
  551. // Thanks to a comment by @Martin, adding support for
  552. // namespaced events too.
  553. this.each(function() {
  554. var handlers = $._data(this, 'events')[name.split('.')[0]];
  555. // take out the handler we just inserted from the end
  556. var handler = handlers.pop();
  557. // move it at the beginning
  558. handlers.splice(0, 0, handler);
  559. });
  560. };
  561.  
  562. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement