forked from vielikiy/tweetfilter.github.com
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tweetfilter-dbg.user.js
5698 lines (5473 loc) · 338 KB
/
tweetfilter-dbg.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Tweetfilter
// @version 2.1.3
// @namespace Chilla42o
// @description Tweetfilter is a highly customizable timeline filter and feature extension for twitter.com
// @homepageURL http://tweetfilter.org
// @updateURL https://userscripts.org/scripts/source/49905.meta.js
// @supportURL http://github.com/Tweetfilter/tweetfilter.github.com/issues
// @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LKM9ZBZ77KSYN
// @icon http://tweetfilter.org/icon32.png
// @icon64 http://tweetfilter.org/icon64.png
// @domain twitter.com
// @include http://twitter.com/
// @include https://twitter.com/
// @include http://twitter.com/#*
// @include https://twitter.com/#*
// @match http://twitter.com/
// @match https://twitter.com/
// @match http://twitter.com/#*
// @match https://twitter.com/#*
// @include /^https?://twitter\.com/(\?.*)?(#.*)?$/
// @noframes 1
// ==/UserScript==
// Copyright (c) 2009-2011 Chilla42o <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
var TweetfilterScript = function() {
function Tweetfilter() {
//gradient start colors for highlighting tweets, change to your taste
this.color_reply = '#FFFAB4'; // tweets mentioning current user
this.color_excluded = '#E5F4AC'; // tweets matching excluded filters
this.color_me = '#FFFAB4'; // tweets written by current user
this._heartbeat = 420/2; //amount of ms between poll ticks which perform various filter actions. don't set below 50
this.version = '2.1.3'; //current visible script version
this.beta = false;
// internal route, page and stream declarations
var pagemap = { //pagename => route.name
'Home': ['index', 'home', 'yourActivity', 'activity', 'mentions', 'replies', 'retweets', 'retweetsByOthers', 'retweetsOfMine', 'listInHome', 'savedSearch'],
'SearchHome': ['searchHome', 'searchAdvanced'],
'Search': ['searchRealtime', 'formSearchResults', 'searchLinks', 'formSearchLinks', 'placeTweetSearch', 'searchResults'],
'WhoToFollow': ['userSearch', 'userSearchForm', 'whoToFollow', 'whoToFollowSearch', 'whoToFollowSearchForm', 'whoToFollowInterests', 'whoToFollowInterestsCategory', 'whoToFollowSuggestions', 'whoToFollowImport', 'whoToFollowImportMatches'],
'Messages': ['messages', 'inbox', 'sent'],
'Profile': ['createDm', 'userActivity', 'favorites', 'friends', 'lists', 'profile', 'userFavorites', 'userLists', 'memberships', 'subscriptions', 'followerRequests'],
'Followers': ['followers', 'followersYouFollow', 'userFollowers'],
'Following': ['following', 'followingTweets', 'userFollowing', 'youBothFollow', 'userFollowingTweets'],
'SimilarTo': ['similarTo'],
'List': ['userList', 'listMembers', 'listSubscribers', 'userListFull']
};
var streammap = { //streamItemType => stream namespace
"tweet": ["Home", "Mentions", "RetweetsByOthers", "RetweetsByYou", "YourTweetsRetweeted", "Search", "List", "User", "Favorites", "FollowingTweets"],
"user": ["ListMembers", "ListFollowers", "Followers", "SocialContextStream", "Friends", "UserRecommendationsStream", "SuggestionCategoryMembersStream"],
"activity": ["ActivityOfMeStream","ActivityByNetworkStream","ActivityByUserStream"]
//only the itemtypes of interest
};
this._routemap = { //route.name => stream namespace (from stream._cacheKey)
"index": "Home",
"home": "Home",
"mentions": "Mentions",
"activity": "ActivityByNetworkStream",
"userActivity": "ActivityByUserStream",
"yourActivity": "ActivityOfMeStream",
"retweetsByOthers": "RetweetsByOthers",
"retweets": "RetweetsByYou",
"retweetsOfMine": "YourTweetsRetweeted",
"savedSearch": "Search",
"listInHome": "List",
"userList": "List",
"listMembers": "ListMembers",
"listSubscribers": "ListFollowers",
"subscriptions": "Subscriptions",
"memberships": "Memberships",
"profile": "User",
"userLists": "OwnLists",
"userFavorites": "Favorites",
"userFollowing": "Friends",
"youBothFollow": "SocialContextStream",
"userFollowingTweets": "FollowingTweets",
"userFollowers": "Followers",
"similarTo": "UserSimilaritiesStream",
"messages": "MessageStream",
"whoToFollow": "UserRecommendationsStream",
"whoToFollowInterests": "SuggestionCategoriesStream",
"whoToFollowInterestsCategory": "SuggestionCategoryMembersStream",
"whoToFollowImport": "ContactImportServices",
"whoToFollowSuggestions": "UserRecommendationsStream",
"searchResults": "Search",
"searchRealtime": "Search",
"searchLinks": "Search"
};
this._streammap = {}; //stream namespace => stream itemtype
this._pagemap = {}; //route name => page name
var i, imax;
for (var pagename in pagemap) {
for (i=0,imax=pagemap[pagename].length;i<imax;i++) {
this._pagemap[pagemap[pagename][i]] = pagename;
}
}
for (var itemtype in streammap) {
for (i=0,imax=streammap[itemtype].length;i<imax;i++) {
this._streammap[streammap[itemtype][i]] = itemtype;
}
}
this._initretries = 21; // ~ 10s
this._route = '';
this._page = '';
this._stream = {
key:'',
namespace: '',
params: {}
};
this._isprotected = false; //is current stream protected
this._isloading = false;
this._loggedin = false;
this._pageswitched = false;
this.cp = false; //current page
this.sm = false; //stream manager
this.cs = false; //current stream
this.stream = {
title: (function() {
switch(this._stream.namespace) {
case 'Home':return 'Home timeline';break;
case 'Mentions':return 'Mentions';break;
case 'RetweetsByYou':return 'Retweets by you';break; //filter.retweets = false;
case 'RetweetsByOthers':return 'Retweets by others';break; //filter.retweets = false;
case 'YourTweetsRetweeted':return 'Your Tweets, retweeted';break;
case 'ActivityByUserStream':return this.stream.whose()+' Activity';break;
case 'ActivityByNetworkStream':return 'Your friends\' Activity';break;
case 'ActivityOfMeStream':return 'Your Activity';break;
case 'Search':
switch (this._stream.params.mode) {
case 'relevance':return 'Search <em>top Tweets</em>';break;
case 'tweets':return 'Search <em>all Tweets</em>';break;
case 'links':return 'Search <em>Tweets with links</em>';break;
}
break;
case 'List':return this.stream.whose()+'List <b>'+this._stream.params.listSlug+'</b>';break;
case 'OwnLists':return this.stream.whose()+'Lists';break;
case 'MessageStream':return 'Messages';break;
case 'User':return this.stream.whose()+'Tweets';break;
case 'Favorites':return this.stream.whose()+'Favorites';break;
case 'Following':return 'Following';break;
case 'Friends':return this.stream.whose()+'Friends';break;
case 'FollowingTweets':return this.stream.whose()+'Timeline';break;
case 'Followers':return this.stream.whose()+'Followers';break;
case 'SocialContextStream':return 'Your and '+this.stream.whose()+'Friends';break; //you both follow
case 'ListMembers':return 'Members of list <b>'+this._stream.params.listSlug+'</b>';break;
case 'ListFollowers':return 'Followers of list <b>'+this._stream.params.listSlug+'</b>';break;
case 'UserRecommendationsStream':return 'Who to follow: Suggestions';break;
case 'SuggestionCategoryMembersStream':
case 'SuggestionCategoriesStream':
return 'Who to follow: Interests';
break;
case 'ContactImportServices':return 'Who to follow: Import contacts';break;
}
return 'unknkown: '+this._stream.namespace;
}).bind(this),
isusers: (function() {
return this._stream.itemtype === 'user';
}).bind(this),
istweets: (function() {
return this._stream.itemtype === 'tweet';
}).bind(this),
isactivity: (function() {
return this._stream.itemtype === 'activity';
}).bind(this),
islinks: (function() {
return this._stream.params.mode && this._stream.params.mode === 'links';
}).bind(this),
isretweets: (function() { //is current stream showing only retweets
return this._stream.namespace.indexOf('RetweetsBy') === 0;
}).bind(this),
ismentions: (function() {
return this._stream.namespace === 'Mentions';
}).bind(this),
ismytweets: (function() {
return this._stream.namespace === 'YourTweetsRetweeted' || (this._stream.namespace === 'User' && this._stream.params.screenName.toLowerCase() === this.user.name);
}).bind(this),
isfiltered: (function() {
return this.stream.isready() && this.cs.hasOwnProperty('filter');
}).bind(this),
whose: (function() {
return !this._stream.params.hasOwnProperty('screenName') ||
this._stream.params.screenName.toLowerCase() === this.user.name ?
'Your ' : '@'+this._stream.params.screenName+"'s ";
}).bind(this),
isprotected: (function() {
return this._stream.params.hasOwnProperty('canViewUser') && this._stream.params.canViewUser === false;
}).bind(this),
status:false,
isready: (function() {
return (this._stream.key === 'unknown') || (!this._isloading && this.cs && this._stream.key === this.cs._cacheKey);
}).bind(this),
setloading: (function() {
if (this.stream.status !== 'loading') {
this.stream.status = 'loading';
}
}).bind(this),
isloading: (function() {
return this.stream.status === 'loading';
}).bind(this),
identify: (function(streamid) {
if (streamid.indexOf('{') === -1) {
return streamid === this._stream.namespace;
} else {
var streamns = streamid.substr(0, streamid.indexOf('{'));
if (streamns === this._stream.namespace) {
var streamparams = JSON.parse(streamid.substr(streamid.indexOf('{')));
for (var p in streamparams) {
if (!this._stream.params.hasOwnProperty(p) || this._stream.params[p] !== streamparams[p]) {
return false;
}
}
return true;
}
return false;
}
}).bind(this),
itemclass: (function() {
return this._stream.streamItemClass || 'stream-item';
}).bind(this),
streamid: (function() {
var streamparams = {};
for (var p in this._stream.params) {
if (~['listSlug','screenName','query'].indexOf(p)) {
streamparams[p] = this._stream.params[p];
}
}
for (p in streamparams) {
return this._stream.namespace+JSON.stringify(streamparams);
}
return this._stream.namespace;
}).bind(this)
};
this.switches = {
'filter-minimized': {
initial: false,
activate: {
'setoption': []
},
css: {
common: [],
active: [],
inactive: [],
disabled: []
}
}
};
this.options = { /* default option settings */
/* widget options */
'filter-minimized': false, /* widget minimized state */
/* global options */
'hide-topbar': false, /* auto-hide top bar */
'hide-tweetbox': false, /* main tweet box */
'hide-question': true, /* hide "What's happening" */
'alert-message': true, /* message alert when new direct messages received */
'alert-sound-message': true,/* play sound when new direct messages received */
'alert-mention': true,/* message alert when new mentions arrived */
'alert-sound-mention': true,/* play sound when new direct messages received */
/* options changing the dashboard */
'compact-activities': true, /* compact activities */
'hide-wtf': false, /* hide who to follow */
'hide-following': false, /* hide following dashboard component */
'hide-followers': false, /* hide followers dashboard component */
'hide-trends': false, /* hide trends */
'hide-ad': true, /* hide advertising */
'hide-invite': true, /* hide invite friends */
'minify-menu': false, /* show only essential dashboard menu options */
'fixed-dashboard': false, /* fixed dashboard */
/* options changing the stream */
'filter-disabled': false, /* disable filter */
'filter-inverted': false, /* invert filter */
'skip-me': true, /* filter should skip my posts */
'skip-mentionsme': true, /* filter should skip tweets mentioning me */
'filter-replies': false, /* filter all replies */
'filter-links': false, /* filter all tweets with links */
'filter-retweets': false, /* filter all retweets */
'filter-media': false, /* filter all media */
'filter-classicrts': false, /* treat classic rts like new style rts */
'hide-promoted-tweets': false, /* always hide promoted tweets */
'hide-promoted-content': false, /* hide promoted content in the dashboard */
'show-navigation': true, /* show draggable top/bottom link menu */
'show-via': true, /* show tweet source */
'show-usertime': true, /* show user's local time near tweet time */
'show-timestamp': true, /* show user's local time near tweet time */
'show-tab': true, /* show "filtered"-tab */
'show-br': true, /* show line breaks in tweets */
'add-selection': false, /* show add to filter menu after simple text selection in tweets */
'expand-new': true, /* expand new tweets */
'hide-last': false, /* expand last tweet on dashboard */
'expand-last': true, /* expand last tweet on dashboard */
'expand-links': false, /* show expanded links */
'expand-activity': false, /* expand activitiy dashboard component */
'hide-activity': false, /* hide the activity dashboard component */
'expand-link-targets': false, /* change links pointing to expanded url instead of shortened*/
'enable-tweeplus': true, /* expand tweeplus shortened tweets in detail view */
'small-links': false, /* show small links */
'highlight-me': false, /* highlight what I wrote */
'highlight-mentionsme':true, /* highlight replies to me */
'highlight-excluded':true, /* highlight tweets matching exclusions */
'search-realtime': true, /* default searches to "all" tweets */
'show-classictabs': true, /* show @mentions and retweets-tabs, hide mentions and retweets in activities */
//'show-unfollowers': true, /* show in dashboard who unfollowed you lately */
'hide-follow': true, /* hide all follow action from activity pages */
'hide-list': true, /* hide all list action from activity pages */
'show-friends':true, /* show who follows you and who you follow */
'show-retweeted':false, /* show retweet info in Tweets */
'copy-expanded': true, /* copy expanded (visible) links */
'enable-richtext': false, /* enable rich text editor */
'scroll-lock': false, /* lock scrolling position when loading new tweets */
'clear-stream-cache': true, /* reset stream cache after page switch - for speed issues */
'tweets-fill-page': false /* load tweets until page is full */
};
if (!this.beta) {
delete this.options['expand-link-targets'];
delete this.options['enable-richtext'];
}
this.disabledoptions = []; //currently disabled options. for check in getoption()
//identify dashboard components, some changed by options
this.components = {
similarto: {
path: 'div.user-rec-inner.user-rec-inner-similarities'
},
wtf: {
path: 'div.user-rec-inner > ul.recommended-followers.user-rec-component',
option: 'hide-wtf'
},
trends: {
path: 'div.trends-inner', //what to search for to identify the component
option: 'hide-trends' //which option depends on the component, will be activated when it's found
},
latest: {
path: 'div.tweet-activity',
option: ['compact-activities', 'hide-last', 'expand-last']
},
invite: {
path: 'div.invite-friends-component'
},
following: {
path: 'div.following-activity-full'
},
youbothfollow: {
path: 'div.social-context > div.you-both-follow'
},
activities: {
path: 'div.your-activity.following-activity'
},
ad: {
path: 'div.definition p.promo',
option: 'hide-ad'
},
menu: {
path: 'div.footer.inline-list',
option: ['minify-menu']
},
stats: {
path: 'ul.user-stats',
option: 'compact-activities'
},
listmembers: {
path: 'div.newest-list-members'
},
morelists: {
path: 'div.more-lists'
}
};
this.queries = []; /* parsed queries (objects) */
this.exclusive = []; /* exclusive filtered queries (ids) */
this.friends = {
expires:0, //refresh after expires
loading: false,
loadedpacket:0, //currently loaded packets (a 100.000)
fetchedpackets:0, //how many packets were fetched from api
uids: {}, //fetched user ids
fids: {} //currently fetching userids
};
this.exfriends = {
};
this.status = {
messagesinceid: -1, //id of last mention, is 0 if no mentions found
messageslastchecked: -1, //when were messages last checked (across multiple instances)
mentionsinceid: -1, //id of last direct message, is 0 if no messages found
mentionslastchecked: -1, //when were mentions last checked (across multiple instances)
selectedtweet: '', //id of tweet containing currently selected text for feature "add selection to filter"
foundcomponents: [], //which components were found in findcomponents()
initialized: false //is widget created and settings loaded: influences setoption and poll behaviour
};
this.timeids = { //timeout and/or interval ids for special functions
};
this.tweeplus = {
unique: (function(arr) {
var uarr = [];
for (var a=0,al=arr.length,av;a<al && (av=arr[a]);a++) {
if (!~uarr.indexOf(av)) uarr.push(av);
}
return uarr;
}).bind(this),
remove: (function(arr,rarr) {
for (var r=0,rl=rarr.length,rv,p;r<rl && (rv=rarr[r]);r++) {
while ((p = -~arr.indexOf(rv))) {
arr.splice(p-1,1);
}
}
return arr;
}).bind(this),
encodetext: function(text) {
return encodeURIComponent(text).replace(/(['\(\)\*\.~]|%20)/g, function($1,$2) {
return {"'":'%27','(':'%28',')':'%29','*':'%2A','.':'%2e','~':'%7e','%20':'+'}[$2];
});
},
encode: (function(text, replytourl) {
text = $.trim(text);
var username = replytourl ? (replytourl.match(/\/(\w+)\/status\//i) || [,''])[1] : '',
cutoff = 115 - (username? username.length + 2 : 0), // initial cut-off point
summary,
mentions = this.tweeplus.mentions(text),
previousLength = mentions.length + 1;
while(mentions.length < previousLength) {
summary = text.slice(0, cutoff - (mentions.length? mentions.join(' ').length + 1 : 0));
previousLength = mentions.length;
mentions = this.tweeplus.remove(mentions, this.tweeplus.mentions(summary));
}
return summary + '[\u2026] ' + 'http://tweeplus.com/'+(replytourl ? '?in_reply_to=' + encodeURIComponent(replytourl) : '')+
'#'+this.tweeplus.encodetext(text) + (mentions? ' ' + mentions.join(' ') : '');
}).bind(this),
mentions: (function(text) {
return this.tweeplus.unique(text.match(/@\w{1,20}/g) || []);
}).bind(this)
};
this.polling = {
tick: 0, //count of ticks executed, mainly for debug
timeoutid: -1, //id returned by settimeout for next poll, to avoid multiple timeout calls, -1=can repoll
suspend: false, //immediately and permanently stop polling
stop: true, //stop poll after run of _poll()
busy: false, //is poll currently busy (already processing)
working: false,
events: { //possible events executed during poll. order matters!
refreshlayoutcss: false, //refresh inline stylesheets
parseitems: false, //parse through cached tweets (outside the dom)
parsestream: false, //parse through displayed tweets (in the dom)
findcomponents: false, //try to find dashboard components
addclass: false, //add class to <body> - used for layout options, spares css recreation
removeclass: false, //remove class from <body>
refreshoptions: false, //set enabled/disabled options
refreshfriends: false, //check if friend status is up to date
loadfriends: false, //staggered load friends from browser storage
fetchfriends: false, //staggered fetch friends from api
refreshindex: false, //rebuild the filter index
refreshfiltercss: false, //refresh inline stylesheets
refreshfriendscss: false, //refresh inline stylesheets
refreshfilterlist: false, //refresh the list of filters and exclusions on the widget
setstreamtitle: false, //refresh stream title on the widget and the stream
refreshactivities: false, //refresh compact activities display
lockscroll: false, //lock scroll position after loading new tweets
checknewmessages: false, //check for new messages
checknewmentions: false, //check for new mentions
parselinks: false, //pick up links and expand or collapse them
removeselection: false //remove text selection
},
running: {}, //events currently running during the tick. populated from "queued" before tick is executed
queued: {} //queued action events, in no specific order. added through method "poll()"
};
this.user = {}; //current user info
this.nextid = 1; /* next unique id for query. always incremented */
this.queries = []; /* parsed queries */
this.stopchars = " \n(){}[].,;-_#'+*~´`?\\/&%$§\"!^°"; //possible chars delimiting a phrase, for exact search. spares expensive regex match
this.basex = this._basemap('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'); //base62 map for large number compression
this.base10 = this._basemap('0123456789');
if (!this.checkrequirements()) { //browser must meet minimum requirements
this.showmessage('Tweetfilter can\'t work correctly on this browser. <br />It would probably work fine on latest <a href="http://www.mozilla.com/firefox">Firefox</a>, '+
'<a href="http://www.google.com/chrome">Chrome</a> or <a href="http://www.opera.com">Opera</a>.', {resident:true});
return;
} else {
this.initialize();
}
}
Tweetfilter.prototype.istwttrloaded = function() {
var has = 'hasOwnProperty', get = 'getElementById';
if (window.jQuery && window.twttr) {
if (!twttr.loggedIn) {
return false;
}
if(document[get]('top-stuff') && document[get]('page-outer') &&
twttr[has]('router') && twttr[has]('$doc') && twttr[has]('$elements') && twttr.$elements[has]('page') &&
twttr[has]('app') && twttr[has]('currentUser')) {
return true;
}
}
return false;
};
Tweetfilter.prototype.initialize = function() {
var f=_F('initialize');
_D(f,'trying to initialize');
if (!this.istwttrloaded() || !this.bindevents()) {
_D(f,'W:link objects failed, retrying another', this._initretries, 'times');
if (!twttr.loggedIn) return false;
if (this._initretries-- > 0) {
setTimeout(this.initialize.bind(this), 210);
return false;
}
_D(f,'W:initialize failed too many times.');
if (typeof twttr !== 'undefined') {
this.showmessage('Tweetfilter failed to initialize. You may try to refresh the page.', {resident:true});
}
return false;
}
_D(f,'I:successfully initialized.');
return true;
};
Tweetfilter.prototype.trigger = function(type, data) {
var f=_F('trigger');
data = data || {};
_D(f,'trigger event', type, 'with data', data);
this._eventprovider.trigger(type, data);
};
Tweetfilter.prototype.bind = function(type, handler) {
var f=_F('bind');
_D(f,'binding event', type);
this._eventprovider.bind(type, handler);
};
Tweetfilter.prototype.waitforstream = function() {
var f=_F('waitforstream');
try {
_D(f,'waiting for page', this._page, 'with stream', JSON.stringify(this._stream));
if (twttr.app.currentPage && twttr.app.currentPage()._instance) {
this.cs = this.sm = this.cp = null;
var cp = twttr.app.currentPage();
this.cp = cp._instance;
if (cp._name !== this._page) { //these must match, expected page and current page, else we have not switched
_D(f,'W:current page', this.cp._name, 'is not expected', this._page);
throw 'pagenotswitched';
}
if (this.cp.streamManager && this.cp.streamManager.getCurrent) {
_D(f,'current page found. switched:', this._pageswitched);
if (!this._pageswitched) { //trigger pageswitched only after the streamManager for page is loaded
this._pageswitched = true;
if (!twttr.$elements.page.data()._tfbound) {
_D(f, 'I:delegating page events.');
twttr.$elements.page.delegate('li.stream-tab-searches a[href!=#]', 'mousedown click', (function(e) {return this.savedsearchclick(e);}).bind(this))
.data('_tfbound', 1);
}
this.trigger('pageswitched', {page: this._page});
}
this.sm = this.cp.streamManager;
if (!this.sm._tfbound) {
_D(f,'binding stream manager events');
this.sm.bind('newItemsCountChanged switchingToStream', this.twttreventhandler.bind(this));
this.sm._tfbound = true;
}
if ((this.cs = this.sm.getCurrent())) {
if (this._stream.key !== this.cs._cacheKey) { //has stream switched
this._isprotected = this.cs.params.hasOwnProperty('canViewUser') ? !this.cs.params.canViewUser : false;
if ((this.cs.items && this.cs.items.length && $("div.stream-item", this.sm.$streamContainer).length) || (this._isprotected || this.cs.$find('.no-members,.stream-end').length)) {
//check if it's the expected stream
var namespace = decodeURIComponent(this.cs._cacheKey);
if (namespace.indexOf('{')>-1) namespace = namespace.substr(0,namespace.indexOf('{'));
_D(f,'found stream namespace', namespace, 'in', this.cs._cacheKey);
if (namespace !== this._stream.namespace) {
_D(f, 'W:stream namespace ', namespace, 'does not match expected',this._stream.namespace);
throw 'streamnamespacenotswitched';
}
_D(f, 'checking stream params ', JSON.stringify(this.cs.params), '<<>>', JSON.stringify(this._stream.params));
for (var p in this._stream.params) {
if (this.cs.params.hasOwnProperty(p)) {
if ((typeof this.cs.params[p] === 'string' && this.cs.params[p].toLowerCase() !== this._stream.params[p].toLowerCase()) ||
(typeof this.cs.params[p] !== 'string' && this.cs.params[p] != this._stream.params[p])) {
_D(f, 'W:stream param ', p, 'does not match:', this.cs.params[p], '!=', this._stream.params[p]);
throw 'streamparamsnotswitched';
}
}
}
//special fix for mode parameter which is not set in route parameters but is set in cachekey for the stream (decider switches first mode to default "Top")
if (this.cs.params.mode && !this._stream.params.mode) {
this._stream.params.mode = this.cs.params.mode;
}
if (!this.cs._tfbound) { //in uncached streams, the property will be deleted after page switch
this.cs.bind('didTweet doneLoadingMore streamEnd reloadCurrentStream', this.twttreventhandler.bind(this));
this.cs._tfbound = true;
}
this.clearstreamcache();
this._stream.key = this.cs._cacheKey;
this._stream.itemtype = this.cs.streamItemType;
this._isloading = false;
this.trigger('streamswitched');
_D(f,'I:stream successfully switched', this._stream);
return true;
} else {
_D(f,'W:items are not loaded yet');
//<debug>
_D(f, 'items in cache:', this.cs.items.length, ', items in stream:', $("div.stream-item", this.sm.$streamContainer).length);
//</debug>
throw 'itemsnotloaded';
}
} else {
throw 'streamkeynotswitched';
}
//stream was not switched, should'nt get here
_D(f,'W:is NOT switched');
} else {
_D(f,'W:stream component is not loaded');
throw 'streamnotloaded';
}
} else {
_D(f,'W:stream manager component is not loaded');
//required component
throw 'streammanagernotloaded';
}
} else {
_D(f,'W:page component is not loaded');
//current page is not loaded or not the one we expected. this._page is set earlier in routeFollowed and must match current's page name at this point
throw 'pagenotloaded';
}
} catch(e) {
if (!this._isloading) {
this.trigger('loading');
this._isloading = true;
}
if (!this.timeids.waitforstream || this.timeids.waitforstream === -1) {
_D(f,'repolling waitforstream due to exception:', e);
this.timeids.waitforstream = window.setTimeout((function() {
this.timeids.waitforstream = -1;
this.waitforstream();
}).bind(this), this._heartbeat*2);
}else {
_D(f,'W:NOT repolling waitforstream, already queued!', e);
}
return false;
}
};
Tweetfilter.prototype.clearstreamcache = function() {
var f=_F('clearstreamcache');
if (this.getoption('clear-stream-cache')) {
if (this._stream.key && this.sm && this.sm.streams && this.sm.streams[this._stream.key]) {
_D(f,'clearing cache of previous stream:', decodeURIComponent(this._stream.key));
delete this.sm.streams[this._stream.key];
}
}
};
Tweetfilter.prototype.twttreventhandler = function(e,a,b) {
var f=_F('twttreventhandler');
_D(f,'I:triggered event:', e.type, ' with params: ', a,',', b);
switch(e.type) {
//this event is triggered in twttr.router, when a new location has been set (hash changed). we are only interested in pages we know (this.routemap)
case 'routeFollowed': //a = route
_D(f,'W:------------routeFollowed-------------------------');
if (!this._routemap[a.name]) { //get stream for route
_D(f,'W:unknown route:', a.name);
this.clearstreamcache();
this._route = this._stream.key = this._stream.namespace = this._stream.itemtype = 'unknown';
this._stream.params = {};
this.trigger('routeunknown', {route: a});
return;
}
this._stream.namespace = this._routemap[a.name];
if (!this._stream.namespace) {
this.trigger('streamunknown');
return;
}
_D(f,'expected stream namespace:', this._stream.namespace);
this._stream.params = {};
var _route = '', streamparam, hasargs = false;
for (var p in a.args) {
streamparam = p.replace(/_([a-z])/, function(m,c) {return c.toUpperCase();});
this._stream.params[streamparam] = a.args[p];
hasargs = true;
}
_route = hasargs ? a.name+JSON.stringify(this._stream.params) : a.name;
_D(f, 'routeFollowed:', _route);
if (_route !== this._route) { //check if route changed. since this is the routefollowed event and not "routed", this should always be true
this._route = _route;
this.trigger('routeswitched', {route: _route});
} else {
_D(f,'W:route NOT changed');
return;
}
if (this._pagemap[a.name]) { //check if the page for this route is known
this._pageswitched = false; //used to trigger pageswitched only once
this._page = this._pagemap[a.name];
if (this.timeids.waitforstream && this.timeids.waitforstream > -1) {
window.clearTimeout([this.timeids.waitforstream, this.timeids.waitforstream=-1][0]);
}
this.waitforstream();
} else { // unknown route for page
this._page = false;
this.trigger('pageunknown', {route:a});
}
break;
case 'reloadCurrentStream':
_D(f,'W:------------reloadCurrentStream-------------------------');
case 'switchingToStream': //for stream changes that don't change the route, like switch from "All" to "Top" in saved search.
//we are only concerned about changing "mode" param while namespace remains the same, we assume the stream namespace itself is correctly switched in routefollowed
_D(f,'W:------------switchingToStream-------------------------');
_D(f, 'about to switch to stream:', decodeURIComponent(a._cacheKey), this._stream.namespace, this._stream.params, a.params);
if (a.params.mode) { //only if mode is set
var streamkey = decodeURIComponent(a._cacheKey);
var namespace = streamkey.substr(0, streamkey.indexOf('{'));
var params = JSON.parse(streamkey.substr(streamkey.indexOf('{')));
_D(f, 'parsed stream key, namespace:', namespace, ', params:', params);
if (namespace === this._stream.namespace) {
var route = {
name: twttr.router.getCurrentRoute().name,
args: params
};
_D(f, 'W:found a stream switch with same route and different mode:', a.params.mode,'!=',this._stream.params.mode, ' - faking new route:', route);
//fake a routefollowed event
this.twttreventhandler({type:'routeFollowed'}, route);
} else {
_D(f, 'W:namespaces do not match:', namespace, '!=', this._stream.namespace);
}
}
break;
case 'didTweet':
this.trigger('newitemsloaded', {count: 1});
break;
case 'newItemsCountChanged': //a = count of new items
this.trigger('newitemsloaded', {count: a});
break;
case 'doneLoadingMore':
this.trigger('moreitemsloaded');
break;
}
};
Tweetfilter.prototype.bindevents = function() {
var f=_F('linkobjects');
try {
_D(f,'trying to link objects');
if (!this._eventprovider) this._eventprovider = $('<div>');
if (!twttr.app._tfbound) {
_D(f,'binding app events');
twttr.app.bind('switchToPage', this.twttreventhandler.bind(this));
twttr.app._tfbound = true;
}
if (!twttr.router._tfbound) {
_D(f,'binding router events');
twttr.router.bind('routeFollowed', this.twttreventhandler.bind(this));
twttr.router._tfbound = true;
}
this.fastbrowser = $.browser.webkit || ($.browser.mozilla && parseFloat($.browser.version.substr(0,3)) > 1.9); //disable stream cache per default for all except webkit and firefox 4+
this.options['clear-stream-cache'] = !this.fastbrowser;
this.refreshuser();
$('head').append( //create style containers
'<style id="tf-layout" type="text/css"></style>', //contains main widget layout
'<style id="tf-pane" type="text/css"></style>', //dynamic pane size
'<style id="tf-friends" type="text/css"></style>', //display friend status, updated separately
'<style id="tf-filter" type="text/css"></style>' //hide and show single tweets according to filters
);
$('div#top-stuff').attr({
'data-over':0, //is mouse over top bar
'data-focused':0 //is search field focused
}).hover(function() {
var topbar = $(this);
topbar.attr('data-over', '1');
}, function() {
var topbar = $(this);
topbar.attr('data-over', '0');
}).delegate('#search-query', 'focus', function() {
$('div#top-stuff').attr('data-focused', '1');
}).delegate('#search-query', 'blur', function() {
$('div#top-stuff').attr('data-focused', '0');
}).find('a[href^="/#!/"]').each(function() { //fix a bug when clicking black bar menu while in some picture view changes url format (tf would disappear)
var link = $(this);
link.attr('href', location.protocol+'//twitter.com'+link.attr('href'));
});
this._spritesurl = $('#new-tweet span').css('background-image');
this._activityspritesurl = this._spritesurl.split('/img/')[0]+'/img/sprite-activity-icons.png)';
$('.twitter-anywhere-tweet-box-editor').live('focus blur', this.tweetboxfocus.bind(this));
this.components.latest.callback =(function(component) {
this.createactivities(component);
}).bind(this);
this.components.stats.callback = (function(component) {
this.createactivities(component);
}).bind(this);
$('#search-form').unbind('submit').bind('submit', (function(e) {
var f=_F('searchsubmit');
var field = $('#search-query');
_D(f, 'submitting search:', field.val());
if (field.val()) {
var route = twttr.router[(this.getoption('search-realtime') ? 'searchRealtimePath' : 'searchResultsPath')]({query: field.val()});
_D(f, 'new route:', route);
twttr.router.routeTo(route);
} else {
field.focus();
}
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}).bind(this));
//don't show hidden topbar when hovering a message notification
$('#message-drawer').bind('mouseenter', function(e) {
e.stopPropagation();
e.preventDefault();
return false;
});
window.scrollTo(0,0); //scroll to the top
$(document).bind('ajaxSuccess', (function(event, request, settings) {
this.twttrajaxevent(event, request, settings);
}).bind(this)); //watch for ajax requests
this.bind("resizepane", (function() {
var f=_F('resizepane');
_D(f, 'resizing pane');
var cp = twttr.app.currentPage();
var $detailsPane = cp.$find("div.details-pane:has(.inner-pane.active)"),
$pageOuter = $("#page-outer"),
pagetoppadding = parseInt($pageOuter.css("padding-top"), 10),
widgetheight = $('div#tf').outerHeight() * +!this.getoption('filter-minimized');
if ($detailsPane.length > 0) {
var contentHeight = twttr.$win.height() - pagetoppadding;
var paneheight = contentHeight - $detailsPane[0].offsetTop - 8;
var componentsheight = paneheight - $detailsPane.find(".inner-pane.active .pane-toolbar").outerHeight() - widgetheight * +!this.getoption('filter-minimized') - 20;
paneheight -= widgetheight + 10;
this.setcss('pane',
'div.details-pane { height: '+paneheight+'px !important; }'+
'div.details-pane .pane-components { height: '+componentsheight+'px !important; }');
}
}).bind(this));
twttr.$win.bind('resize', (function() {
this.trigger('resizepane');
}).bind(this));
twttr.util.lazyBind(window, 'resize', (function() {
this.trigger('resizepane');
}).bind(this));
if (!$.browser.mozilla && !$.browser.webkit) {
this.disabledoptions.push('enable-richtext');
}
this.setdeciderfeatures();
this.createwidget();
this.loadsettings();
this.bind('routeswitched', this.routeswitched.bind(this));
this.bind('streamswitched', this.streamswitched.bind(this));
this.bind('newitemsloaded', this.newitemsloaded.bind(this));
this.bind('moreitemsloaded', this.moreitemsloaded.bind(this));
this.bind('pageswitched', this.pageswitched.bind(this));
this.bind('pageunknown routeunknown streamunknown', this.unknownlocation.bind(this));
this.twttreventhandler({type:'routeFollowed'}, twttr.router.getCurrentRoute()); //fire up first time
return true;
} catch(e) {
_D(f,'W:',e);
return false;
}
};
Tweetfilter.prototype.pageswitched = function() {
this.poll(['refreshactivities', 'refreshfilterlist']);
};
Tweetfilter.prototype.moreitemsloaded = function() {
this.stream.newitemsloaded = false;
this.poll('parseitems');
};
Tweetfilter.prototype.newitemsloaded = function() {
this.stream.newitemsloaded = true;
this.poll('parseitems');
};
Tweetfilter.prototype.streamswitched = function() {
var f=_F('streamswitched');
_D(f,'stream switched to', decodeURIComponent(this._stream.key), this._stream);
if (!this.cs.$node.data('_tfbound')) {
this.cs.$node.delegate('div.stream-item', 'click', (function() {return this.tweetclick();}).bind(this))
.delegate('a.tf', 'mousedown click', (function(e) {return this.tweetactionsclick(e);}).bind(this))
.delegate('span.tf-via > a', 'mousedown click', (function(e) {return this.tweetclickvia(e);}).bind(this))
.delegate('a.reply-action', 'mousedown', (function(e) {this.tweetclickreply(e);}).bind(this))
.delegate('div.tweet-text', 'mousedown', (function(e) {return this.tweettextmousedown(e);}).bind(this))
.delegate('div.tweet-text', 'mouseup click', (function(e) {return this.tweettextmouseup(e);}).bind(this))
.delegate('span.tf-rtc', 'click', (function(e) {return this.tweetclickretweeted(e);}).bind(this))
.delegate('ul.tf-menu', 'mouseleave', (function(e) {this.filtermenuleave(e);}).bind(this))
.delegate('a.twitter-timeline-link', 'click', (function(e) {return this.tweetclicklink(e);}).bind(this))
.delegate('a.twitter-hashtag', 'mousedown click', (function(e) {return this.tweetclickhashtag(e);}).bind(this))
.data('_tfbound',1);
}
$('#stream-items-id').addClass('tf-'+this._stream.itemtype+'-stream');
if (this.getoption('scroll-lock')) {
_D(f,'resetting scroll lock');
this.status.scrollheight = 0;
this.status.scrolltop = 0;
this.status.scrollsinceid = false;
this.stream.newitemsloaded = false;
}
this.widget.toggleClass('userstream', this.stream.isusers());
this.widget.toggleClass('tweetstream', this.stream.istweets());
this.widget.toggleClass('activitystream', this.stream.isactivity());
this.widget.toggleClass('hidden', !(this.stream.isusers() || this.stream.istweets() || this.stream.isactivity()));
this.polling.suspend = false;
this.polling.busy = false;
if (this._route === 'messages') {
this.poll('checknewmessages');
}
var streamid = this.stream.streamid();
for (var q=0,len=this.queries.length,query;q<len && (query=this.queries[q]);q++) {
query.active = !query.stream || (query.stream === streamid);
}
if (!this.cs.resolvedurls) {
this.cs.resolvedurls = {};
}
this.poll(['parseitems', 'parselinks', 'refreshfiltercss', 'refreshlayoutcss',
'refreshfriendscss', 'refreshfilterlist', 'setstreamtitle', 'refreshoptions']);
this.poll('findcomponents', 3);
if (!this.status.initialized) {
this.poll(['loadfriends']); //first time load friends
this.status.initialized = true;
window.setTimeout(this._poll.bind(this),0);
}
};
//handler for routeswitched event. happens just after the location changed, page and stream may still be loading
Tweetfilter.prototype.routeswitched = function() {
var f=_F('routeswitched');
_D(f,'route switched to', this._route);
this.setcss('filter', '.main-content div.stream-items > div.stream-item { visibility:hidden; }'); //remove flicker after switch
this.setcss('friends', '');
$('#tf-stream-title').html(_("Please wait\u2026"));
$('[id^="tf-count-"]', this.widget).html('--'); //set counters idle
$('.tf-queries > li', this.widget).toggleClass('notfound', true);
//close message notification boxes when switching to the stream
if (this._route === 'messages') {
$('#message-drawer span.tf.newmessages a.x').trigger('click');
} else if (this._route === 'mentions') {
$('#message-drawer span.tf.newmentions a.x').trigger('click');
}
};
Tweetfilter.prototype.unknownlocation = function() {
var f=_F('unknownlocation');
_D(f,'W:location is unknown:', this._route);
this.resetfiltercss();
this.widget.toggleClass('hidden', true);
};
Tweetfilter.prototype.checkrequirements = function() {
try { //need HTML5 local storage, native JSON, ECMA5 tilde operator and JS 1.8.5 bind
return !!window.localStorage && !!JSON && ~~[] === 0 && Function.prototype.bind && Array.prototype.indexOf;
} catch(e) {
return false;
}
};
Tweetfilter.prototype.refreshoptions = function() {
var exclusivemode = this.exclusive.length > 0;
var filterdisabled = this.options['filter-disabled'];
this.enableoption(['filter-retweets'], !filterdisabled && (this.stream.istweets() || this.stream.isactivity) && !this.stream.isretweets());
this.enableoption(['filter-links'], !filterdisabled && this.stream.istweets() && !this.stream.islinks());
this.enableoption(['filter-inverted'], !filterdisabled && this.stream.istweets() && !exclusivemode);
this.enableoption(['filter-replies'], !filterdisabled && this.stream.istweets());
this.enableoption(['filter-media'], !filterdisabled && this.stream.istweets());
this.enableoption(['skip-mentionsme'], !filterdisabled && !exclusivemode && this.stream.istweets() && !(this.stream.ismentions() && this.options['skip-mentionsme']));
this.enableoption(['show-friends'], !this.friends.loading && (this.stream.istweets() || this.stream.isusers()) && !this.stream.ismytweets());
this.enableoption(['skip-me'], !filterdisabled && !exclusivemode && this.stream.istweets() && !this.stream.ismytweets());
this.enableoption(['hide-last'], this._page === 'Home');
this.enableoption(['expand-last'], this._page === 'Home' && !this.options['hide-last']);
this.enableoption(['hide-tweetbox'], this._page === 'Home' && (this.stream.istweets() || this.stream.isactivity()));
this.enableoption(['hide-question'], this._page === 'Home' && (this.stream.istweets() || this.stream.isactivity()) && !this.options['hide-tweetbox']);
this.enableoption(['copy-expanded'], this.options['expand-links']);
this.enableoption(['add-selection'], !filterdisabled && (this.stream.istweets() || this.stream.isactivity()) );
this.enableoption(['highlight-me'], this.stream.istweets() && !this.stream.ismytweets());
this.enableoption(['highlight-mentionsme'], (this.stream.istweets() || this.stream.isactivity()) && !this.stream.ismentions());
this.enableoption(['highlight-excluded'], !filterdisabled && this.stream.istweets());
this.enableoption(['show-br'], this.stream.istweets());