dd7fffcc950db8f85b8c4135572a6b7039c54ef6
[rainbowstream.git] / rainbowstream / rainbow.py
1 import os
2 import os.path
3 import sys
4 import signal
5 import argparse
6 import time
7 import threading
8 import requests
9 import webbrowser
10 import traceback
11 import pkg_resources
12
13 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
14 from twitter.api import *
15 from twitter.oauth import OAuth, read_token_file
16 from twitter.oauth_dance import oauth_dance
17 from twitter.util import printNicely
18
19 from .draw import *
20 from .colors import *
21 from .config import *
22 from .consumer import *
23 from .interactive import *
24 from .c_image import *
25 from .py3patch import *
26 from .emoji import *
27
28 # Global values
29 g = {}
30
31 # Lock for streams
32 StreamLock = threading.Lock()
33
34
35 def parse_arguments():
36 """
37 Parse the arguments
38 """
39 parser = argparse.ArgumentParser(description=__doc__ or "")
40 parser.add_argument(
41 '-to',
42 '--timeout',
43 help='Timeout for the stream (seconds).')
44 parser.add_argument(
45 '-tt',
46 '--track-keywords',
47 help='Search the stream for specific text.')
48 parser.add_argument(
49 '-fil',
50 '--filter',
51 help='Filter specific screen_name.')
52 parser.add_argument(
53 '-ig',
54 '--ignore',
55 help='Ignore specific screen_name.')
56 parser.add_argument(
57 '-iot',
58 '--image-on-term',
59 action='store_true',
60 help='Display all image on terminal.')
61 return parser.parse_args()
62
63
64 def authen():
65 """
66 Authenticate with Twitter OAuth
67 """
68 # When using rainbow stream you must authorize.
69 twitter_credential = os.environ.get(
70 'HOME',
71 os.environ.get(
72 'USERPROFILE',
73 '')) + os.sep + '.rainbow_oauth'
74 if not os.path.exists(twitter_credential):
75 oauth_dance("Rainbow Stream",
76 CONSUMER_KEY,
77 CONSUMER_SECRET,
78 twitter_credential)
79 oauth_token, oauth_token_secret = read_token_file(twitter_credential)
80 return OAuth(
81 oauth_token,
82 oauth_token_secret,
83 CONSUMER_KEY,
84 CONSUMER_SECRET)
85
86
87 def build_mute_dict(dict_data=False):
88 """
89 Build muting list
90 """
91 t = Twitter(auth=authen())
92 # Init cursor
93 next_cursor = -1
94 screen_name_list = []
95 name_list = []
96 # Cursor loop
97 while next_cursor != 0:
98 list = t.mutes.users.list(
99 screen_name=g['original_name'],
100 cursor=next_cursor,
101 skip_status=True,
102 include_entities=False,
103 )
104 screen_name_list += ['@' + u['screen_name'] for u in list['users']]
105 name_list += [u['name'] for u in list['users']]
106 next_cursor = list['next_cursor']
107 # Return dict or list
108 if dict_data:
109 return dict(zip(screen_name_list, name_list))
110 else:
111 return screen_name_list
112
113
114 def debug_option():
115 """
116 Save traceback when run in debug mode
117 """
118 if g['debug']:
119 g['traceback'].append(traceback.format_exc())
120
121
122 def upgrade_center():
123 """
124 Check latest and notify to upgrade
125 """
126 try:
127 current = pkg_resources.get_distribution("rainbowstream").version
128 url = 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
129 readme = requests.get(url).content
130 latest = readme.split("version = \'")[1].split("\'")[0]
131 if current != latest:
132 notice = light_magenta('RainbowStream latest version is ')
133 notice += light_green(latest)
134 notice += light_magenta(' while your current version is ')
135 notice += light_yellow(current) + '\n'
136 notice += light_magenta('You should upgrade with ')
137 notice += light_green('pip install -U rainbowstream')
138 printNicely(notice)
139 except:
140 pass
141
142
143 def init(args):
144 """
145 Init function
146 """
147 # Handle Ctrl C
148 ctrl_c_handler = lambda signum, frame: quit()
149 signal.signal(signal.SIGINT, ctrl_c_handler)
150 # Upgrade notify
151 upgrade_center()
152 # Get name
153 t = Twitter(auth=authen())
154 credential = t.account.verify_credentials()
155 screen_name = '@' + credential['screen_name']
156 name = credential['name']
157 if not get_config('PREFIX'):
158 set_config('PREFIX', screen_name)
159 c['PREFIX'] = emojize(c['PREFIX'])
160 g['PREFIX'] = u2str(c['PREFIX'])
161 c['original_name'] = g['original_name'] = screen_name[1:]
162 g['full_name'] = name
163 g['decorated_name'] = lambda x: color_func(
164 c['DECORATED_NAME'])('[' + x + ']: ')
165 # Theme init
166 files = os.listdir(os.path.dirname(__file__) + '/colorset')
167 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
168 g['themes'] = themes
169 g['pause'] = False
170 g['message_threads'] = {}
171 # Startup cmd
172 g['cmd'] = ''
173 # Debug option default = True
174 g['debug'] = True
175 g['traceback'] = []
176 # Events
177 c['events'] = []
178 # Semaphore init
179 c['lock'] = False
180 # Init tweet dict and message dict
181 c['tweet_dict'] = []
182 c['message_dict'] = []
183 # Image on term
184 c['IMAGE_ON_TERM'] = args.image_on_term
185 set_config('IMAGE_ON_TERM', str(c['IMAGE_ON_TERM']))
186 # Mute dict
187 c['IGNORE_LIST'] += build_mute_dict()
188
189
190 def trend():
191 """
192 Trend
193 """
194 t = Twitter(auth=authen())
195 # Get country and town
196 try:
197 country = g['stuff'].split()[0]
198 except:
199 country = ''
200 try:
201 town = g['stuff'].split()[1]
202 except:
203 town = ''
204 avail = t.trends.available()
205 # World wide
206 if not country:
207 trends = t.trends.place(_id=1)[0]['trends']
208 print_trends(trends)
209 else:
210 for location in avail:
211 # Search for country and Town
212 if town:
213 if location['countryCode'] == country \
214 and location['placeType']['name'] == 'Town' \
215 and location['name'] == town:
216 trends = t.trends.place(_id=location['woeid'])[0]['trends']
217 print_trends(trends)
218 # Search for country only
219 else:
220 if location['countryCode'] == country \
221 and location['placeType']['name'] == 'Country':
222 trends = t.trends.place(_id=location['woeid'])[0]['trends']
223 print_trends(trends)
224
225
226 def home():
227 """
228 Home
229 """
230 t = Twitter(auth=authen())
231 num = c['HOME_TWEET_NUM']
232 if g['stuff'].isdigit():
233 num = int(g['stuff'])
234 for tweet in reversed(t.statuses.home_timeline(count=num)):
235 draw(t=tweet)
236 printNicely('')
237
238
239 def notification():
240 """
241 Show notifications
242 """
243 if c['events']:
244 for e in c['events']:
245 print_event(e)
246 printNicely('')
247 else:
248 printNicely(magenta('Nothing at this time.'))
249
250
251 def mentions():
252 """
253 Mentions timeline
254 """
255 t = Twitter(auth=authen())
256 num = c['HOME_TWEET_NUM']
257 if g['stuff'].isdigit():
258 num = int(g['stuff'])
259 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
260 draw(t=tweet)
261 printNicely('')
262
263
264 def whois():
265 """
266 Show profile of a specific user
267 """
268 t = Twitter(auth=authen())
269 screen_name = g['stuff'].split()[0]
270 if screen_name.startswith('@'):
271 try:
272 user = t.users.show(
273 screen_name=screen_name[1:],
274 include_entities=False)
275 show_profile(user)
276 except:
277 debug_option()
278 printNicely(red('No user.'))
279 else:
280 printNicely(red('A name should begin with a \'@\''))
281
282
283 def view():
284 """
285 Friend view
286 """
287 t = Twitter(auth=authen())
288 user = g['stuff'].split()[0]
289 if user[0] == '@':
290 try:
291 num = int(g['stuff'].split()[1])
292 except:
293 num = c['HOME_TWEET_NUM']
294 for tweet in reversed(t.statuses.user_timeline(count=num, screen_name=user[1:])):
295 draw(t=tweet)
296 printNicely('')
297 else:
298 printNicely(red('A name should begin with a \'@\''))
299
300
301 def search():
302 """
303 Search
304 """
305 t = Twitter(auth=authen())
306 # Setup query
307 query = g['stuff'].strip()
308 type = c['SEARCH_TYPE']
309 if type not in ['mixed', 'recent', 'popular']:
310 type = 'mixed'
311 max_record = c['SEARCH_MAX_RECORD']
312 count = min(max_record, 100)
313 # Perform search
314 rel = t.search.tweets(
315 q=query,
316 type=type,
317 count=count
318 )['statuses']
319 # Return results
320 if rel:
321 printNicely('Newest tweets:')
322 for i in reversed(xrange(count)):
323 draw(t=rel[i], keyword=query)
324 printNicely('')
325 else:
326 printNicely(magenta('I\'m afraid there is no result'))
327
328
329 def tweet():
330 """
331 Tweet
332 """
333 t = Twitter(auth=authen())
334 t.statuses.update(status=g['stuff'])
335
336
337 def retweet():
338 """
339 ReTweet
340 """
341 t = Twitter(auth=authen())
342 try:
343 id = int(g['stuff'].split()[0])
344 except:
345 printNicely(red('Sorry I can\'t understand.'))
346 return
347 tid = c['tweet_dict'][id]
348 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
349
350
351 def quote():
352 """
353 Quote a tweet
354 """
355 # Get tweet
356 t = Twitter(auth=authen())
357 try:
358 id = int(g['stuff'].split()[0])
359 except:
360 printNicely(red('Sorry I can\'t understand.'))
361 return
362 tid = c['tweet_dict'][id]
363 tweet = t.statuses.show(id=tid)
364 # Get formater
365 formater = format_quote(tweet)
366 if not formater:
367 return
368 # Get comment
369 prefix = light_magenta('Compose your ') + light_green('#comment: ')
370 comment = raw_input(prefix)
371 if comment:
372 quote = comment.join(formater.split('#comment'))
373 t.statuses.update(status=quote)
374 else:
375 printNicely(light_magenta('No text added.'))
376
377
378 def allretweet():
379 """
380 List all retweet
381 """
382 t = Twitter(auth=authen())
383 # Get rainbow id
384 try:
385 id = int(g['stuff'].split()[0])
386 except:
387 printNicely(red('Sorry I can\'t understand.'))
388 return
389 tid = c['tweet_dict'][id]
390 # Get display num if exist
391 try:
392 num = int(g['stuff'].split()[1])
393 except:
394 num = c['RETWEETS_SHOW_NUM']
395 # Get result and display
396 rt_ary = t.statuses.retweets(id=tid, count=num)
397 if not rt_ary:
398 printNicely(magenta('This tweet has no retweet.'))
399 return
400 for tweet in reversed(rt_ary):
401 draw(t=tweet)
402 printNicely('')
403
404
405 def conversation():
406 """
407 Conversation view
408 """
409 t = Twitter(auth=authen())
410 try:
411 id = int(g['stuff'].split()[0])
412 except:
413 printNicely(red('Sorry I can\'t understand.'))
414 return
415 tid = c['tweet_dict'][id]
416 tweet = t.statuses.show(id=tid)
417 limit = c['CONVERSATION_MAX']
418 thread_ref = []
419 thread_ref.append(tweet)
420 prev_tid = tweet['in_reply_to_status_id']
421 while prev_tid and limit:
422 limit -= 1
423 tweet = t.statuses.show(id=prev_tid)
424 prev_tid = tweet['in_reply_to_status_id']
425 thread_ref.append(tweet)
426
427 for tweet in reversed(thread_ref):
428 draw(t=tweet)
429 printNicely('')
430
431
432 def reply():
433 """
434 Reply
435 """
436 t = Twitter(auth=authen())
437 try:
438 id = int(g['stuff'].split()[0])
439 except:
440 printNicely(red('Sorry I can\'t understand.'))
441 return
442 tid = c['tweet_dict'][id]
443 user = t.statuses.show(id=tid)['user']['screen_name']
444 status = ' '.join(g['stuff'].split()[1:])
445 status = '@' + user + ' ' + str2u(status)
446 t.statuses.update(status=status, in_reply_to_status_id=tid)
447
448
449 def favorite():
450 """
451 Favorite
452 """
453 t = Twitter(auth=authen())
454 try:
455 id = int(g['stuff'].split()[0])
456 except:
457 printNicely(red('Sorry I can\'t understand.'))
458 return
459 tid = c['tweet_dict'][id]
460 t.favorites.create(_id=tid, include_entities=False)
461 printNicely(green('Favorited.'))
462 draw(t.statuses.show(id=tid))
463 printNicely('')
464
465
466 def unfavorite():
467 """
468 Unfavorite
469 """
470 t = Twitter(auth=authen())
471 try:
472 id = int(g['stuff'].split()[0])
473 except:
474 printNicely(red('Sorry I can\'t understand.'))
475 return
476 tid = c['tweet_dict'][id]
477 t.favorites.destroy(_id=tid)
478 printNicely(green('Okay it\'s unfavorited.'))
479 draw(t.statuses.show(id=tid))
480 printNicely('')
481
482
483 def delete():
484 """
485 Delete
486 """
487 t = Twitter(auth=authen())
488 try:
489 id = int(g['stuff'].split()[0])
490 except:
491 printNicely(red('Sorry I can\'t understand.'))
492 return
493 tid = c['tweet_dict'][id]
494 t.statuses.destroy(id=tid)
495 printNicely(green('Okay it\'s gone.'))
496
497
498 def show():
499 """
500 Show image
501 """
502 t = Twitter(auth=authen())
503 try:
504 target = g['stuff'].split()[0]
505 if target != 'image':
506 return
507 id = int(g['stuff'].split()[1])
508 tid = c['tweet_dict'][id]
509 tweet = t.statuses.show(id=tid)
510 media = tweet['entities']['media']
511 for m in media:
512 res = requests.get(m['media_url'])
513 img = Image.open(BytesIO(res.content))
514 img.show()
515 except:
516 debug_option()
517 printNicely(red('Sorry I can\'t show this image.'))
518
519
520 def urlopen():
521 """
522 Open url
523 """
524 t = Twitter(auth=authen())
525 try:
526 if not g['stuff'].isdigit():
527 return
528 tid = c['tweet_dict'][int(g['stuff'])]
529 tweet = t.statuses.show(id=tid)
530 link_prefix = ('http://', 'https://')
531 link_ary = [u for u in tweet['text'].split()
532 if u.startswith(link_prefix)]
533 if not link_ary:
534 printNicely(light_magenta('No url here @.@!'))
535 return
536 for link in link_ary:
537 webbrowser.open(link)
538 except:
539 debug_option()
540 printNicely(red('Sorry I can\'t open url in this tweet.'))
541
542
543 def inbox():
544 """
545 Inbox threads
546 """
547 t = Twitter(auth=authen())
548 num = c['MESSAGES_DISPLAY']
549 if g['stuff'].isdigit():
550 num = g['stuff']
551 # Get inbox messages
552 cur_page = 1
553 inbox = []
554 while num > 20:
555 inbox = inbox + t.direct_messages(
556 count=20,
557 page=cur_page,
558 include_entities=False,
559 skip_status=False
560 )
561 num -= 20
562 cur_page += 1
563 inbox = inbox + t.direct_messages(
564 count=num,
565 page=cur_page,
566 include_entities=False,
567 skip_status=False
568 )
569 # Get sent messages
570 num = c['MESSAGES_DISPLAY']
571 if g['stuff'].isdigit():
572 num = g['stuff']
573 cur_page = 1
574 sent = []
575 while num > 20:
576 sent = sent + t.direct_messages.sent(
577 count=20,
578 page=cur_page,
579 include_entities=False,
580 skip_status=False
581 )
582 num -= 20
583 cur_page += 1
584 sent = sent + t.direct_messages.sent(
585 count=num,
586 page=cur_page,
587 include_entities=False,
588 skip_status=False
589 )
590
591 d = {}
592 uniq_inbox = list(set(
593 [(m['sender_screen_name'], m['sender']['name']) for m in inbox]
594 ))
595 uniq_sent = list(set(
596 [(m['recipient_screen_name'], m['recipient']['name']) for m in sent]
597 ))
598 for partner in uniq_inbox:
599 inbox_ary = [m for m in inbox if m['sender_screen_name'] == partner[0]]
600 sent_ary = [
601 m for m in sent if m['recipient_screen_name'] == partner[0]]
602 d[partner] = inbox_ary + sent_ary
603 for partner in uniq_sent:
604 if partner not in d:
605 d[partner] = [
606 m for m in sent if m['recipient_screen_name'] == partner[0]]
607 g['message_threads'] = print_threads(d)
608
609
610 def thread():
611 """
612 View a thread of message
613 """
614 try:
615 thread_id = int(g['stuff'])
616 print_thread(
617 g['message_threads'][thread_id],
618 g['original_name'],
619 g['full_name'])
620 except Exception:
621 debug_option()
622 printNicely(red('No such thread.'))
623
624
625 def message():
626 """
627 Send a direct message
628 """
629 t = Twitter(auth=authen())
630 try:
631 user = g['stuff'].split()[0]
632 if user[0].startswith('@'):
633 content = ' '.join(g['stuff'].split()[1:])
634 t.direct_messages.new(
635 screen_name=user[1:],
636 text=content
637 )
638 printNicely(green('Message sent.'))
639 else:
640 printNicely(red('A name should begin with a \'@\''))
641 except:
642 debug_option()
643 printNicely(red('Sorry I can\'t understand.'))
644
645
646 def trash():
647 """
648 Remove message
649 """
650 t = Twitter(auth=authen())
651 try:
652 id = int(g['stuff'].split()[0])
653 except:
654 printNicely(red('Sorry I can\'t understand.'))
655 mid = c['message_dict'][id]
656 t.direct_messages.destroy(id=mid)
657 printNicely(green('Message deleted.'))
658
659
660 def ls():
661 """
662 List friends for followers
663 """
664 t = Twitter(auth=authen())
665 # Get name
666 try:
667 name = g['stuff'].split()[1]
668 if name.startswith('@'):
669 name = name[1:]
670 else:
671 printNicely(red('A name should begin with a \'@\''))
672 raise Exception('Invalid name')
673 except:
674 name = g['original_name']
675 # Get list followers or friends
676 try:
677 target = g['stuff'].split()[0]
678 except:
679 printNicely(red('Omg some syntax is wrong.'))
680 # Init cursor
681 d = {'fl': 'followers', 'fr': 'friends'}
682 next_cursor = -1
683 rel = {}
684 # Cursor loop
685 while next_cursor != 0:
686 list = getattr(t, d[target]).list(
687 screen_name=name,
688 cursor=next_cursor,
689 skip_status=True,
690 include_entities=False,
691 )
692 for u in list['users']:
693 rel[u['name']] = '@' + u['screen_name']
694 next_cursor = list['next_cursor']
695 # Print out result
696 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
697 for name in rel:
698 user = ' ' + cycle_color(name)
699 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
700 printNicely(user)
701
702
703 def follow():
704 """
705 Follow a user
706 """
707 t = Twitter(auth=authen())
708 screen_name = g['stuff'].split()[0]
709 if screen_name.startswith('@'):
710 t.friendships.create(screen_name=screen_name[1:], follow=True)
711 printNicely(green('You are following ' + screen_name + ' now!'))
712 else:
713 printNicely(red('A name should begin with a \'@\''))
714
715
716 def unfollow():
717 """
718 Unfollow a user
719 """
720 t = Twitter(auth=authen())
721 screen_name = g['stuff'].split()[0]
722 if screen_name.startswith('@'):
723 t.friendships.destroy(
724 screen_name=screen_name[1:],
725 include_entities=False)
726 printNicely(green('Unfollow ' + screen_name + ' success!'))
727 else:
728 printNicely(red('A name should begin with a \'@\''))
729
730
731 def mute():
732 """
733 Mute a user
734 """
735 t = Twitter(auth=authen())
736 try:
737 screen_name = g['stuff'].split()[0]
738 except:
739 printNicely(red('A name should be specified. '))
740 return
741 if screen_name.startswith('@'):
742 try:
743 rel = t.mutes.users.create(screen_name=screen_name[1:])
744 if isinstance(rel, dict):
745 printNicely(green(screen_name + ' is muted.'))
746 c['IGNORE_LIST'] += [unc(screen_name)]
747 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
748 else:
749 printNicely(red(rel))
750 except:
751 debug_option()
752 printNicely(red('Something is wrong, can not mute now :('))
753 else:
754 printNicely(red('A name should begin with a \'@\''))
755
756
757 def unmute():
758 """
759 Unmute a user
760 """
761 t = Twitter(auth=authen())
762 try:
763 screen_name = g['stuff'].split()[0]
764 except:
765 printNicely(red('A name should be specified. '))
766 return
767 if screen_name.startswith('@'):
768 try:
769 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
770 if isinstance(rel, dict):
771 printNicely(green(screen_name + ' is unmuted.'))
772 c['IGNORE_LIST'].remove(screen_name)
773 else:
774 printNicely(red(rel))
775 except:
776 printNicely(red('Maybe you are not muting this person ?'))
777 else:
778 printNicely(red('A name should begin with a \'@\''))
779
780
781 def muting():
782 """
783 List muting user
784 """
785 # Get dict of muting users
786 md = build_mute_dict(dict_data=True)
787 printNicely('All: ' + str(len(md)) + ' people.')
788 for name in md:
789 user = ' ' + cycle_color(md[name])
790 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
791 printNicely(user)
792 # Update from Twitter
793 c['IGNORE_LIST'] = [n for n in md]
794
795
796 def block():
797 """
798 Block a user
799 """
800 t = Twitter(auth=authen())
801 screen_name = g['stuff'].split()[0]
802 if screen_name.startswith('@'):
803 t.blocks.create(
804 screen_name=screen_name[1:],
805 include_entities=False,
806 skip_status=True)
807 printNicely(green('You blocked ' + screen_name + '.'))
808 else:
809 printNicely(red('A name should begin with a \'@\''))
810
811
812 def unblock():
813 """
814 Unblock a user
815 """
816 t = Twitter(auth=authen())
817 screen_name = g['stuff'].split()[0]
818 if screen_name.startswith('@'):
819 t.blocks.destroy(
820 screen_name=screen_name[1:],
821 include_entities=False,
822 skip_status=True)
823 printNicely(green('Unblock ' + screen_name + ' success!'))
824 else:
825 printNicely(red('A name should begin with a \'@\''))
826
827
828 def report():
829 """
830 Report a user as a spam account
831 """
832 t = Twitter(auth=authen())
833 screen_name = g['stuff'].split()[0]
834 if screen_name.startswith('@'):
835 t.users.report_spam(
836 screen_name=screen_name[1:])
837 printNicely(green('You reported ' + screen_name + '.'))
838 else:
839 printNicely(red('Sorry I can\'t understand.'))
840
841
842 def get_slug():
843 """
844 Get Slug Decorator
845 """
846 # Get list name
847 list_name = raw_input(light_magenta('Give me the list\'s name: '))
848 # Get list name and owner
849 try:
850 owner, slug = list_name.split('/')
851 if slug.startswith('@'):
852 slug = slug[1:]
853 return owner, slug
854 except:
855 printNicely(
856 light_magenta('List name should follow "@owner/list_name" format.'))
857 raise Exception('Wrong list name')
858
859
860 def show_lists(t):
861 """
862 List list
863 """
864 rel = t.lists.list(screen_name=g['original_name'])
865 if rel:
866 print_list(rel)
867 else:
868 printNicely(light_magenta('You belong to no lists :)'))
869
870
871 def list_home(t):
872 """
873 List home
874 """
875 owner, slug = get_slug()
876 res = t.lists.statuses(
877 slug=slug,
878 owner_screen_name=owner,
879 count=c['LIST_MAX'],
880 include_entities=False)
881 for tweet in res:
882 draw(t=tweet)
883 printNicely('')
884
885
886 def list_members(t):
887 """
888 List members
889 """
890 owner, slug = get_slug()
891 # Get members
892 rel = {}
893 next_cursor = -1
894 while next_cursor != 0:
895 m = t.lists.members(
896 slug=slug,
897 owner_screen_name=owner,
898 cursor=next_cursor,
899 include_entities=False)
900 for u in m['users']:
901 rel[u['name']] = '@' + u['screen_name']
902 next_cursor = m['next_cursor']
903 printNicely('All: ' + str(len(rel)) + ' members.')
904 for name in rel:
905 user = ' ' + cycle_color(name)
906 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
907 printNicely(user)
908
909
910 def list_subscribers(t):
911 """
912 List subscribers
913 """
914 owner, slug = get_slug()
915 # Get subscribers
916 rel = {}
917 next_cursor = -1
918 while next_cursor != 0:
919 m = t.lists.subscribers(
920 slug=slug,
921 owner_screen_name=owner,
922 cursor=next_cursor,
923 include_entities=False)
924 for u in m['users']:
925 rel[u['name']] = '@' + u['screen_name']
926 next_cursor = m['next_cursor']
927 printNicely('All: ' + str(len(rel)) + ' subscribers.')
928 for name in rel:
929 user = ' ' + cycle_color(name)
930 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
931 printNicely(user)
932
933
934 def list_add(t):
935 """
936 Add specific user to a list
937 """
938 owner, slug = get_slug()
939 # Add
940 user_name = raw_input(light_magenta('Give me name of the newbie: '))
941 if user_name.startswith('@'):
942 user_name = user_name[1:]
943 try:
944 t.lists.members.create(
945 slug=slug,
946 owner_screen_name=owner,
947 screen_name=user_name)
948 printNicely(green('Added.'))
949 except:
950 debug_option()
951 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
952
953
954 def list_remove(t):
955 """
956 Remove specific user from a list
957 """
958 owner, slug = get_slug()
959 # Remove
960 user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
961 if user_name.startswith('@'):
962 user_name = user_name[1:]
963 try:
964 t.lists.members.destroy(
965 slug=slug,
966 owner_screen_name=owner,
967 screen_name=user_name)
968 printNicely(green('Gone.'))
969 except:
970 debug_option()
971 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
972
973
974 def list_subscribe(t):
975 """
976 Subscribe to a list
977 """
978 owner, slug = get_slug()
979 # Subscribe
980 try:
981 t.lists.subscribers.create(
982 slug=slug,
983 owner_screen_name=owner)
984 printNicely(green('Done.'))
985 except:
986 debug_option()
987 printNicely(
988 light_magenta('I\'m sorry you can not subscribe to this list.'))
989
990
991 def list_unsubscribe(t):
992 """
993 Unsubscribe a list
994 """
995 owner, slug = get_slug()
996 # Subscribe
997 try:
998 t.lists.subscribers.destroy(
999 slug=slug,
1000 owner_screen_name=owner)
1001 printNicely(green('Done.'))
1002 except:
1003 debug_option()
1004 printNicely(
1005 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1006
1007
1008 def list_own(t):
1009 """
1010 List own
1011 """
1012 rel = []
1013 next_cursor = -1
1014 while next_cursor != 0:
1015 res = t.lists.ownerships(
1016 screen_name=g['original_name'],
1017 cursor=next_cursor)
1018 rel += res['lists']
1019 next_cursor = res['next_cursor']
1020 if rel:
1021 print_list(rel)
1022 else:
1023 printNicely(light_magenta('You own no lists :)'))
1024
1025
1026 def list_new(t):
1027 """
1028 Create a new list
1029 """
1030 name = raw_input(light_magenta('New list\'s name: '))
1031 mode = raw_input(light_magenta('New list\'s mode (public/private): '))
1032 description = raw_input(light_magenta('New list\'s description: '))
1033 try:
1034 t.lists.create(
1035 name=name,
1036 mode=mode,
1037 description=description)
1038 printNicely(green(name + ' list is created.'))
1039 except:
1040 debug_option()
1041 printNicely(red('Oops something is wrong with Twitter :('))
1042
1043
1044 def list_update(t):
1045 """
1046 Update a list
1047 """
1048 slug = raw_input(light_magenta('Your list that you want to update: '))
1049 name = raw_input(light_magenta('Update name (leave blank to unchange): '))
1050 mode = raw_input(light_magenta('Update mode (public/private): '))
1051 description = raw_input(light_magenta('Update description: '))
1052 try:
1053 if name:
1054 t.lists.update(
1055 slug='-'.join(slug.split()),
1056 owner_screen_name=g['original_name'],
1057 name=name,
1058 mode=mode,
1059 description=description)
1060 else:
1061 t.lists.update(
1062 slug=slug,
1063 owner_screen_name=g['original_name'],
1064 mode=mode,
1065 description=description)
1066 printNicely(green(slug + ' list is updated.'))
1067 except:
1068 debug_option()
1069 printNicely(red('Oops something is wrong with Twitter :('))
1070
1071
1072 def list_delete(t):
1073 """
1074 Delete a list
1075 """
1076 slug = raw_input(light_magenta('Your list that you want to delete: '))
1077 try:
1078 t.lists.destroy(
1079 slug='-'.join(slug.split()),
1080 owner_screen_name=g['original_name'])
1081 printNicely(green(slug + ' list is deleted.'))
1082 except:
1083 debug_option()
1084 printNicely(red('Oops something is wrong with Twitter :('))
1085
1086
1087 def twitterlist():
1088 """
1089 Twitter's list
1090 """
1091 t = Twitter(auth=authen())
1092 # List all lists or base on action
1093 try:
1094 g['list_action'] = g['stuff'].split()[0]
1095 except:
1096 show_lists(t)
1097 return
1098 # Sub-function
1099 action_ary = {
1100 'home': list_home,
1101 'all_mem': list_members,
1102 'all_sub': list_subscribers,
1103 'add': list_add,
1104 'rm': list_remove,
1105 'sub': list_subscribe,
1106 'unsub': list_unsubscribe,
1107 'own': list_own,
1108 'new': list_new,
1109 'update': list_update,
1110 'del': list_delete,
1111 }
1112 try:
1113 return action_ary[g['list_action']](t)
1114 except:
1115 printNicely(red('Please try again.'))
1116
1117
1118 def switch():
1119 """
1120 Switch stream
1121 """
1122 try:
1123 target = g['stuff'].split()[0]
1124 # Filter and ignore
1125 args = parse_arguments()
1126 try:
1127 if g['stuff'].split()[-1] == '-f':
1128 guide = 'To ignore an option, just hit Enter key.'
1129 printNicely(light_magenta(guide))
1130 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
1131 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1132 args.filter = filter(None, only.split(','))
1133 args.ignore = filter(None, ignore.split(','))
1134 elif g['stuff'].split()[-1] == '-d':
1135 args.filter = c['ONLY_LIST']
1136 args.ignore = c['IGNORE_LIST']
1137 except:
1138 printNicely(red('Sorry, wrong format.'))
1139 return
1140 # Public stream
1141 if target == 'public':
1142 keyword = g['stuff'].split()[1]
1143 if keyword[0] == '#':
1144 keyword = keyword[1:]
1145 # Kill old thread
1146 g['stream_stop'] = True
1147 args.track_keywords = keyword
1148 # Start new thread
1149 th = threading.Thread(
1150 target=stream,
1151 args=(
1152 c['PUBLIC_DOMAIN'],
1153 args))
1154 th.daemon = True
1155 th.start()
1156 # Personal stream
1157 elif target == 'mine':
1158 # Kill old thread
1159 g['stream_stop'] = True
1160 # Start new thread
1161 th = threading.Thread(
1162 target=stream,
1163 args=(
1164 c['USER_DOMAIN'],
1165 args,
1166 g['original_name']))
1167 th.daemon = True
1168 th.start()
1169 printNicely('')
1170 if args.filter:
1171 printNicely(cyan('Only: ' + str(args.filter)))
1172 if args.ignore:
1173 printNicely(red('Ignore: ' + str(args.ignore)))
1174 printNicely('')
1175 except:
1176 printNicely(red('Sorry I can\'t understand.'))
1177
1178
1179 def cal():
1180 """
1181 Unix's command `cal`
1182 """
1183 # Format
1184 rel = os.popen('cal').read().split('\n')
1185 month = rel.pop(0)
1186 date = rel.pop(0)
1187 show_calendar(month, date, rel)
1188
1189
1190 def theme():
1191 """
1192 List and change theme
1193 """
1194 if not g['stuff']:
1195 # List themes
1196 for theme in g['themes']:
1197 line = light_magenta(theme)
1198 if c['THEME'] == theme:
1199 line = ' ' * 2 + light_yellow('* ') + line
1200 else:
1201 line = ' ' * 4 + line
1202 printNicely(line)
1203 else:
1204 # Change theme
1205 try:
1206 # Load new theme
1207 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1208 # Redefine decorated_name
1209 g['decorated_name'] = lambda x: color_func(
1210 c['DECORATED_NAME'])(
1211 '[' + x + ']: ')
1212 printNicely(green('Theme changed.'))
1213 except:
1214 printNicely(red('No such theme exists.'))
1215
1216
1217 def config():
1218 """
1219 Browse and change config
1220 """
1221 all_config = get_all_config()
1222 g['stuff'] = g['stuff'].strip()
1223 # List all config
1224 if not g['stuff']:
1225 for k in all_config:
1226 line = ' ' * 2 + \
1227 green(k) + ': ' + light_yellow(str(all_config[k]))
1228 printNicely(line)
1229 guide = 'Detailed explanation can be found at ' + \
1230 color_func(c['TWEET']['link'])(
1231 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1232 printNicely(guide)
1233 # Print specific config
1234 elif len(g['stuff'].split()) == 1:
1235 if g['stuff'] in all_config:
1236 k = g['stuff']
1237 line = ' ' * 2 + \
1238 green(k) + ': ' + light_yellow(str(all_config[k]))
1239 printNicely(line)
1240 else:
1241 printNicely(red('No such config key.'))
1242 # Print specific config's default value
1243 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1244 key = g['stuff'].split()[0]
1245 try:
1246 value = get_default_config(key)
1247 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
1248 printNicely(line)
1249 except Exception as e:
1250 printNicely(red(e))
1251 # Delete specific config key in config file
1252 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1253 key = g['stuff'].split()[0]
1254 try:
1255 delete_config(key)
1256 printNicely(green('Config key is dropped.'))
1257 except Exception as e:
1258 printNicely(red(e))
1259 # Set specific config
1260 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
1261 key = g['stuff'].split()[0]
1262 value = g['stuff'].split()[-1]
1263 if key == 'THEME' and not validate_theme(value):
1264 printNicely(red('Invalid theme\'s value.'))
1265 return
1266 try:
1267 set_config(key, value)
1268 # Apply theme immediately
1269 if key == 'THEME':
1270 c['THEME'] = reload_theme(value, c['THEME'])
1271 g['decorated_name'] = lambda x: color_func(
1272 c['DECORATED_NAME'])('[' + x + ']: ')
1273 reload_config()
1274 printNicely(green('Updated successfully.'))
1275 except Exception as e:
1276 printNicely(red(e))
1277 else:
1278 printNicely(light_magenta('Sorry I can\'s understand.'))
1279
1280
1281 def help_discover():
1282 """
1283 Discover the world
1284 """
1285 s = ' ' * 2
1286 # Discover the world
1287 usage = '\n'
1288 usage += s + grey(u'\u266A' + ' Discover the world \n')
1289 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1290 'You can try ' + light_green('trend US') + ' or ' + \
1291 light_green('trend JP Tokyo') + '.\n'
1292 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1293 light_green('home 7') + ' will show 7 tweets.\n'
1294 usage += s * 2 + \
1295 light_green('notification') + ' will show your recent notification.\n'
1296 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1297 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1298 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
1299 magenta('@mdo') + '.\n'
1300 usage += s * 2 + light_green('view @mdo') + \
1301 ' will show ' + magenta('@mdo') + '\'s home.\n'
1302 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1303 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1304 'Search can be performed with or without hashtag.\n'
1305 printNicely(usage)
1306
1307
1308 def help_tweets():
1309 """
1310 Tweets
1311 """
1312 s = ' ' * 2
1313 # Tweet
1314 usage = '\n'
1315 usage += s + grey(u'\u266A' + ' Tweets \n')
1316 usage += s * 2 + light_green('t oops ') + \
1317 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1318 usage += s * 2 + \
1319 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1320 light_yellow('[id=12]') + '.\n'
1321 usage += s * 2 + \
1322 light_green('quote 12 ') + ' will quote the tweet with ' + \
1323 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1324 'the quote will be canceled.\n'
1325 usage += s * 2 + \
1326 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1327 light_yellow('[id=12]') + '.\n'
1328 usage += s * 2 + light_green('conversation 12') + ' will show the chain of ' + \
1329 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1330 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1331 light_yellow('oops') + '" to tweet with ' + \
1332 light_yellow('[id=12]') + '.\n'
1333 usage += s * 2 + \
1334 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1335 light_yellow('[id=12]') + '.\n'
1336 usage += s * 2 + \
1337 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1338 light_yellow('[id=12]') + '.\n'
1339 usage += s * 2 + \
1340 light_green('del 12 ') + ' will delete tweet with ' + \
1341 light_yellow('[id=12]') + '.\n'
1342 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1343 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1344 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1345 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1346 printNicely(usage)
1347
1348
1349 def help_messages():
1350 """
1351 Messages
1352 """
1353 s = ' ' * 2
1354 # Direct message
1355 usage = '\n'
1356 usage += s + grey(u'\u266A' + ' Direct messages \n')
1357 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1358 light_green('inbox 7') + ' will show newest 7 messages.\n'
1359 usage += s * 2 + light_green('thread 2') + ' will show full thread with ' + \
1360 light_yellow('[thread_id=2]') + '.\n'
1361 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1362 magenta('@dtvd88') + '.\n'
1363 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1364 light_yellow('[message_id=5]') + '.\n'
1365 printNicely(usage)
1366
1367
1368 def help_friends_and_followers():
1369 """
1370 Friends and Followers
1371 """
1372 s = ' ' * 2
1373 # Follower and following
1374 usage = '\n'
1375 usage += s + grey(u'\u266A' + ' Friends and followers \n')
1376 usage += s * 2 + \
1377 light_green('ls fl') + \
1378 ' will list all followers (people who are following you).\n'
1379 usage += s * 2 + \
1380 light_green('ls fr') + \
1381 ' will list all friends (people who you are following).\n'
1382 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
1383 magenta('@dtvd88') + '.\n'
1384 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1385 magenta('@dtvd88') + '.\n'
1386 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
1387 magenta('@dtvd88') + '.\n'
1388 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1389 magenta('@dtvd88') + '.\n'
1390 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1391 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
1392 magenta('@dtvd88') + '.\n'
1393 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1394 magenta('@dtvd88') + '.\n'
1395 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
1396 magenta('@dtvd88') + ' as a spam account.\n'
1397 printNicely(usage)
1398
1399
1400 def help_list():
1401 """
1402 Lists
1403 """
1404 s = ' ' * 2
1405 # Twitter list
1406 usage = '\n'
1407 usage += s + grey(u'\u266A' + ' Twitter list\n')
1408 usage += s * 2 + light_green('list') + \
1409 ' will show all lists you are belong to.\n'
1410 usage += s * 2 + light_green('list home') + \
1411 ' will show timeline of list. You will be asked for list\'s name.\n'
1412 usage += s * 2 + light_green('list all_mem') + \
1413 ' will show list\'s all members.\n'
1414 usage += s * 2 + light_green('list all_sub') + \
1415 ' will show list\'s all subscribers.\n'
1416 usage += s * 2 + light_green('list add') + \
1417 ' will add specific person to a list owned by you.' + \
1418 ' You will be asked for list\'s name and person\'s name.\n'
1419 usage += s * 2 + light_green('list rm') + \
1420 ' will remove specific person from a list owned by you.' + \
1421 ' You will be asked for list\'s name and person\'s name.\n'
1422 usage += s * 2 + light_green('list sub') + \
1423 ' will subscribe you to a specific list.\n'
1424 usage += s * 2 + light_green('list unsub') + \
1425 ' will unsubscribe you from a specific list.\n'
1426 usage += s * 2 + light_green('list own') + \
1427 ' will show all list owned by you.\n'
1428 usage += s * 2 + light_green('list new') + \
1429 ' will create a new list.\n'
1430 usage += s * 2 + light_green('list update') + \
1431 ' will update a list owned by you.\n'
1432 usage += s * 2 + light_green('list del') + \
1433 ' will delete a list owned by you.\n'
1434 printNicely(usage)
1435
1436
1437 def help_stream():
1438 """
1439 Stream switch
1440 """
1441 s = ' ' * 2
1442 # Switch
1443 usage = '\n'
1444 usage += s + grey(u'\u266A' + ' Switching streams \n')
1445 usage += s * 2 + light_green('switch public #AKB') + \
1446 ' will switch to public stream and follow "' + \
1447 light_yellow('AKB') + '" keyword.\n'
1448 usage += s * 2 + light_green('switch mine') + \
1449 ' will switch to your personal stream.\n'
1450 usage += s * 2 + light_green('switch mine -f ') + \
1451 ' will prompt to enter the filter.\n'
1452 usage += s * 3 + light_yellow('Only nicks') + \
1453 ' filter will decide nicks will be INCLUDE ONLY.\n'
1454 usage += s * 3 + light_yellow('Ignore nicks') + \
1455 ' filter will decide nicks will be EXCLUDE.\n'
1456 usage += s * 2 + light_green('switch mine -d') + \
1457 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1458 printNicely(usage)
1459
1460
1461 def help():
1462 """
1463 Help
1464 """
1465 s = ' ' * 2
1466 h, w = os.popen('stty size', 'r').read().split()
1467 # Start
1468 usage = '\n'
1469 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1470 usage += s + '-' * (int(w) - 4) + '\n'
1471 usage += s + 'You are ' + \
1472 light_yellow('already') + ' on your personal stream.\n'
1473 usage += s + 'Any update from Twitter will show up ' + \
1474 light_yellow('immediately') + '.\n'
1475 usage += s + 'In addition, following commands are available right now:\n'
1476 # Twitter help section
1477 usage += '\n'
1478 usage += s + grey(u'\u266A' + ' Twitter help\n')
1479 usage += s * 2 + light_green('h discover') + \
1480 ' will show help for discover commands.\n'
1481 usage += s * 2 + light_green('h tweets') + \
1482 ' will show help for tweets commands.\n'
1483 usage += s * 2 + light_green('h messages') + \
1484 ' will show help for messages commands.\n'
1485 usage += s * 2 + light_green('h friends_and_followers') + \
1486 ' will show help for friends and followers commands.\n'
1487 usage += s * 2 + light_green('h list') + \
1488 ' will show help for list commands.\n'
1489 usage += s * 2 + light_green('h stream') + \
1490 ' will show help for stream commands.\n'
1491 # Smart shell
1492 usage += '\n'
1493 usage += s + grey(u'\u266A' + ' Smart shell\n')
1494 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1495 'will be evaluate by Python interpreter.\n'
1496 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1497 ' for current month.\n'
1498 # Config
1499 usage += '\n'
1500 usage += s + grey(u'\u266A' + ' Config \n')
1501 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
1502 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1503 ' theme immediately.\n'
1504 usage += s * 2 + light_green('config') + ' will list all config.\n'
1505 usage += s * 3 + \
1506 light_green('config ASCII_ART') + ' will output current value of ' +\
1507 light_yellow('ASCII_ART') + ' config key.\n'
1508 usage += s * 3 + \
1509 light_green('config TREND_MAX default') + ' will output default value of ' + \
1510 light_yellow('TREND_MAX') + ' config key.\n'
1511 usage += s * 3 + \
1512 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1513 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1514 usage += s * 3 + \
1515 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1516 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1517 light_yellow('True') + '.\n'
1518 # Screening
1519 usage += '\n'
1520 usage += s + grey(u'\u266A' + ' Screening \n')
1521 usage += s * 2 + light_green('h') + ' will show this help again.\n'
1522 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1523 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
1524 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1525 usage += s * 2 + light_green('q') + ' will quit.\n'
1526 # End
1527 usage += '\n'
1528 usage += s + '-' * (int(w) - 4) + '\n'
1529 usage += s + 'Have fun and hang tight! \n'
1530 # Show help
1531 d = {
1532 'discover': help_discover,
1533 'tweets': help_tweets,
1534 'messages': help_messages,
1535 'friends_and_followers': help_friends_and_followers,
1536 'list': help_list,
1537 'stream': help_stream,
1538 }
1539 if g['stuff']:
1540 d.get(
1541 g['stuff'].strip(),
1542 lambda: printNicely(red('No such command.'))
1543 )()
1544 else:
1545 printNicely(usage)
1546
1547
1548 def pause():
1549 """
1550 Pause stream display
1551 """
1552 g['pause'] = True
1553 printNicely(green('Stream is paused'))
1554
1555
1556 def replay():
1557 """
1558 Replay stream
1559 """
1560 g['pause'] = False
1561 printNicely(green('Stream is running back now'))
1562
1563
1564 def clear():
1565 """
1566 Clear screen
1567 """
1568 os.system('clear')
1569
1570
1571 def quit():
1572 """
1573 Exit all
1574 """
1575 try:
1576 save_history()
1577 printNicely(green('See you next time :)'))
1578 except:
1579 pass
1580 sys.exit()
1581
1582
1583 def reset():
1584 """
1585 Reset prefix of line
1586 """
1587 if g['reset']:
1588 if c.get('USER_JSON_ERROR'):
1589 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1590 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1591 printNicely('')
1592 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1593 g['reset'] = False
1594 try:
1595 printNicely(str(eval(g['cmd'])))
1596 except Exception:
1597 pass
1598
1599
1600 # Command set
1601 cmdset = [
1602 'switch',
1603 'trend',
1604 'home',
1605 'notification',
1606 'view',
1607 'mentions',
1608 't',
1609 'rt',
1610 'quote',
1611 'allrt',
1612 'conversation',
1613 'fav',
1614 'rep',
1615 'del',
1616 'ufav',
1617 's',
1618 'mes',
1619 'show',
1620 'open',
1621 'ls',
1622 'inbox',
1623 'thread',
1624 'trash',
1625 'whois',
1626 'fl',
1627 'ufl',
1628 'mute',
1629 'unmute',
1630 'muting',
1631 'block',
1632 'unblock',
1633 'report',
1634 'list',
1635 'cal',
1636 'config',
1637 'theme',
1638 'h',
1639 'p',
1640 'r',
1641 'c',
1642 'q'
1643 ]
1644
1645 # Handle function set
1646 funcset = [
1647 switch,
1648 trend,
1649 home,
1650 notification,
1651 view,
1652 mentions,
1653 tweet,
1654 retweet,
1655 quote,
1656 allretweet,
1657 conversation,
1658 favorite,
1659 reply,
1660 delete,
1661 unfavorite,
1662 search,
1663 message,
1664 show,
1665 urlopen,
1666 ls,
1667 inbox,
1668 thread,
1669 trash,
1670 whois,
1671 follow,
1672 unfollow,
1673 mute,
1674 unmute,
1675 muting,
1676 block,
1677 unblock,
1678 report,
1679 twitterlist,
1680 cal,
1681 config,
1682 theme,
1683 help,
1684 pause,
1685 replay,
1686 clear,
1687 quit
1688 ]
1689
1690
1691 def process(cmd):
1692 """
1693 Process switch
1694 """
1695 return dict(zip(cmdset, funcset)).get(cmd, reset)
1696
1697
1698 def listen():
1699 """
1700 Listen to user's input
1701 """
1702 d = dict(zip(
1703 cmdset,
1704 [
1705 ['public', 'mine'], # switch
1706 [], # trend
1707 [], # home
1708 [], # notification
1709 ['@'], # view
1710 [], # mentions
1711 [], # tweet
1712 [], # retweet
1713 [], # quote
1714 [], # allretweet
1715 [], # conversation
1716 [], # favorite
1717 [], # reply
1718 [], # delete
1719 [], # unfavorite
1720 ['#'], # search
1721 ['@'], # message
1722 ['image'], # show image
1723 [''], # open url
1724 ['fl', 'fr'], # list
1725 [], # inbox
1726 [i for i in g['message_threads']], # sent
1727 [], # trash
1728 ['@'], # whois
1729 ['@'], # follow
1730 ['@'], # unfollow
1731 ['@'], # mute
1732 ['@'], # unmute
1733 ['@'], # muting
1734 ['@'], # block
1735 ['@'], # unblock
1736 ['@'], # report
1737 [
1738 'home',
1739 'all_mem',
1740 'all_sub',
1741 'add',
1742 'rm',
1743 'sub',
1744 'unsub',
1745 'own',
1746 'new',
1747 'update',
1748 'del'
1749 ], # list
1750 [], # cal
1751 [key for key in dict(get_all_config())], # config
1752 g['themes'], # theme
1753 [
1754 'discover',
1755 'tweets',
1756 'messages',
1757 'friends_and_followers',
1758 'list',
1759 'stream'
1760 ], # help
1761 [], # pause
1762 [], # reconnect
1763 [], # clear
1764 [], # quit
1765 ]
1766 ))
1767 init_interactive_shell(d)
1768 read_history()
1769 reset()
1770 while True:
1771 try:
1772 # raw_input
1773 if g['prefix']:
1774 # Only use PREFIX as a string with raw_input
1775 line = raw_input(g['decorated_name'](g['PREFIX']))
1776 else:
1777 line = raw_input()
1778 # Save cmd to compare with readline buffer
1779 g['cmd'] = line.strip()
1780 # Get short cmd to pass to handle function
1781 try:
1782 cmd = line.split()[0]
1783 except:
1784 cmd = ''
1785 # Lock the semaphore
1786 c['lock'] = True
1787 # Save cmd to global variable and call process
1788 g['stuff'] = ' '.join(line.split()[1:])
1789 # Process the command
1790 process(cmd)()
1791 # Not re-display
1792 if cmd in ['switch', 't', 'rt', 'rep']:
1793 g['prefix'] = False
1794 else:
1795 g['prefix'] = True
1796 # Release the semaphore lock
1797 c['lock'] = False
1798 except EOFError:
1799 printNicely('')
1800 except Exception:
1801 debug_option()
1802 printNicely(red('OMG something is wrong with Twitter right now.'))
1803
1804
1805 def stream(domain, args, name='Rainbow Stream'):
1806 """
1807 Track the stream
1808 """
1809 # The Logo
1810 art_dict = {
1811 c['USER_DOMAIN']: name,
1812 c['PUBLIC_DOMAIN']: args.track_keywords,
1813 c['SITE_DOMAIN']: name,
1814 }
1815 if c['ASCII_ART']:
1816 ascii_art(art_dict[domain])
1817 # These arguments are optional:
1818 stream_args = dict(
1819 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
1820 block=True,
1821 heartbeat_timeout=c['HEARTBEAT_TIMEOUT'] * 60)
1822 # Track keyword
1823 query_args = dict()
1824 if args.track_keywords:
1825 query_args['track'] = args.track_keywords
1826 # Get stream
1827 stream = TwitterStream(
1828 auth=authen(),
1829 domain=domain,
1830 **stream_args)
1831 try:
1832 if domain == c['USER_DOMAIN']:
1833 tweet_iter = stream.user(**query_args)
1834 elif domain == c['SITE_DOMAIN']:
1835 tweet_iter = stream.site(**query_args)
1836 else:
1837 if args.track_keywords:
1838 tweet_iter = stream.statuses.filter(**query_args)
1839 else:
1840 tweet_iter = stream.statuses.sample()
1841 # Block new stream until other one exits
1842 StreamLock.acquire()
1843 g['stream_stop'] = False
1844 for tweet in tweet_iter:
1845 if tweet is None:
1846 printNicely("-- None --")
1847 elif tweet is Timeout:
1848 if(g['stream_stop']):
1849 StreamLock.release()
1850 break
1851 elif tweet is HeartbeatTimeout:
1852 printNicely("-- Heartbeat Timeout --")
1853 guide = light_magenta("You can use ") + \
1854 light_green("switch") + \
1855 light_magenta(" command to return to your stream.\n")
1856 guide += light_magenta("Type ") + \
1857 light_green("h stream") + \
1858 light_magenta(" for more details.")
1859 printNicely(guide)
1860 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1861 sys.stdout.flush()
1862 StreamLock.release()
1863 break
1864 elif tweet is Hangup:
1865 printNicely("-- Hangup --")
1866 elif tweet.get('text'):
1867 # Check the semaphore pause and lock (stream process only)
1868 if g['pause']:
1869 continue
1870 while c['lock']:
1871 time.sleep(0.5)
1872 # Draw the tweet
1873 draw(
1874 t=tweet,
1875 keyword=args.track_keywords,
1876 humanize=False,
1877 fil=args.filter,
1878 ig=args.ignore,
1879 )
1880 # Current readline buffer
1881 current_buffer = readline.get_line_buffer().strip()
1882 # There is an unexpected behaviour in MacOSX readline + Python 2:
1883 # after completely delete a word after typing it,
1884 # somehow readline buffer still contains
1885 # the 1st character of that word
1886 if current_buffer and g['cmd'] != current_buffer:
1887 sys.stdout.write(
1888 g['decorated_name'](c['PREFIX']) + str2u(current_buffer))
1889 sys.stdout.flush()
1890 elif not c['HIDE_PROMPT']:
1891 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1892 sys.stdout.flush()
1893 elif tweet.get('direct_message'):
1894 # Check the semaphore pause and lock (stream process only)
1895 if g['pause']:
1896 continue
1897 while c['lock']:
1898 time.sleep(0.5)
1899 print_message(tweet['direct_message'])
1900 elif tweet.get('event'):
1901 c['events'].append(tweet)
1902 print_event(tweet)
1903 except TwitterHTTPError:
1904 printNicely('')
1905 printNicely(
1906 magenta("We have maximum connection problem with twitter'stream API right now :("))
1907
1908
1909 def fly():
1910 """
1911 Main function
1912 """
1913 # Initial
1914 args = parse_arguments()
1915 try:
1916 init(args)
1917 except TwitterHTTPError:
1918 printNicely('')
1919 printNicely(
1920 magenta("We have connection problem with twitter'stream API right now :("))
1921 printNicely(magenta("Let's try again later."))
1922 save_history()
1923 sys.exit()
1924 # Spawn stream thread
1925 th = threading.Thread(
1926 target=stream,
1927 args=(
1928 c['USER_DOMAIN'],
1929 args,
1930 g['original_name']))
1931 th.daemon = True
1932 th.start()
1933 # Start listen process
1934 time.sleep(0.5)
1935 g['reset'] = True
1936 g['prefix'] = True
1937 listen()