fe060fb3de0af1a5e411ff50f166877644b7ae41
[rainbowstream.git] / rainbowstream / rainbow.py
1 """
2 Colorful user's timeline stream
3 """
4 from multiprocessing import Process
5
6 import os
7 import os.path
8 import sys
9 import signal
10 import argparse
11 import time
12 import requests
13
14 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
15 from twitter.api import *
16 from twitter.oauth import OAuth, read_token_file
17 from twitter.oauth_dance import oauth_dance
18 from twitter.util import printNicely
19 from StringIO import StringIO
20
21 from .draw import *
22 from .colors import *
23 from .config import *
24 from .consumer import *
25 from .interactive import *
26 from .db import *
27 from .c_image import *
28
29 g = {}
30 db = RainbowDB()
31 cmdset = [
32 'switch',
33 'trend',
34 'home',
35 'view',
36 'mentions',
37 't',
38 'rt',
39 'allrt',
40 'fav',
41 'rep',
42 'del',
43 'ufav',
44 's',
45 'mes',
46 'show',
47 'ls',
48 'inbox',
49 'sent',
50 'trash',
51 'whois',
52 'fl',
53 'ufl',
54 'mute',
55 'unmute',
56 'muting',
57 'block',
58 'unblock',
59 'report',
60 'cal',
61 'theme',
62 'h',
63 'c',
64 'q'
65 ]
66
67
68 def parse_arguments():
69 """
70 Parse the arguments
71 """
72 parser = argparse.ArgumentParser(description=__doc__ or "")
73 parser.add_argument(
74 '-to',
75 '--timeout',
76 help='Timeout for the stream (seconds).')
77 parser.add_argument(
78 '-ht',
79 '--heartbeat-timeout',
80 help='Set heartbeat timeout.',
81 default=90)
82 parser.add_argument(
83 '-nb',
84 '--no-block',
85 action='store_true',
86 help='Set stream to non-blocking.')
87 parser.add_argument(
88 '-tt',
89 '--track-keywords',
90 help='Search the stream for specific text.')
91 parser.add_argument(
92 '-fil',
93 '--filter',
94 help='Filter specific screen_name.')
95 parser.add_argument(
96 '-ig',
97 '--ignore',
98 help='Ignore specific screen_name.')
99 parser.add_argument(
100 '-iot',
101 '--image-on-term',
102 action='store_true',
103 help='Display all image on terminal.')
104 return parser.parse_args()
105
106
107 def authen():
108 """
109 Authenticate with Twitter OAuth
110 """
111 # When using rainbow stream you must authorize.
112 twitter_credential = os.environ.get(
113 'HOME',
114 os.environ.get(
115 'USERPROFILE',
116 '')) + os.sep + '.rainbow_oauth'
117 if not os.path.exists(twitter_credential):
118 oauth_dance("Rainbow Stream",
119 CONSUMER_KEY,
120 CONSUMER_SECRET,
121 twitter_credential)
122 oauth_token, oauth_token_secret = read_token_file(twitter_credential)
123 return OAuth(
124 oauth_token,
125 oauth_token_secret,
126 CONSUMER_KEY,
127 CONSUMER_SECRET)
128
129
130 def get_decorated_name():
131 """
132 Beginning of every line
133 """
134 t = Twitter(auth=authen())
135 name = '@' + t.account.verify_credentials()['screen_name']
136 g['original_name'] = name[1:]
137 g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
138 g['ascii_art'] = True
139
140 files = os.listdir(os.path.dirname(__file__)+'/colorset')
141 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
142 themes += ['custom']
143 g['themes'] = themes
144 db.theme_store(c['theme'])
145
146
147 def switch():
148 """
149 Switch stream
150 """
151 try:
152 target = g['stuff'].split()[0]
153
154 # Filter and ignore
155 args = parse_arguments()
156 try:
157 if g['stuff'].split()[-1] == '-f':
158 only = raw_input('Only nicks: ')
159 ignore = raw_input('Ignore nicks: ')
160 args.filter = filter(None, only.split(','))
161 args.ignore = filter(None, ignore.split(','))
162 elif g['stuff'].split()[-1] == '-d':
163 args.filter = c['ONLY_LIST']
164 args.ignore = c['IGNORE_LIST']
165 except:
166 printNicely(red('Sorry, wrong format.'))
167 return
168
169 # Public stream
170 if target == 'public':
171 keyword = g['stuff'].split()[1]
172 if keyword[0] == '#':
173 keyword = keyword[1:]
174 # Kill old process
175 os.kill(g['stream_pid'], signal.SIGKILL)
176 args.track_keywords = keyword
177 # Start new process
178 p = Process(
179 target=stream,
180 args=(
181 c['PUBLIC_DOMAIN'],
182 args))
183 p.start()
184 g['stream_pid'] = p.pid
185
186 # Personal stream
187 elif target == 'mine':
188 # Kill old process
189 os.kill(g['stream_pid'], signal.SIGKILL)
190 # Start new process
191 p = Process(
192 target=stream,
193 args=(
194 c['USER_DOMAIN'],
195 args,
196 g['original_name']))
197 p.start()
198 g['stream_pid'] = p.pid
199 printNicely('')
200 if args.filter:
201 printNicely(cyan('Only: ' + str(args.filter)))
202 if args.ignore:
203 printNicely(red('Ignore: ' + str(args.ignore)))
204 printNicely('')
205 g['ascii_art'] = True
206 except:
207 printNicely(red('Sorry I can\'t understand.'))
208
209
210 def trend():
211 """
212 Trend
213 """
214 t = Twitter(auth=authen())
215 # Get country and town
216 try:
217 country = g['stuff'].split()[0]
218 except:
219 country = ''
220 try:
221 town = g['stuff'].split()[1]
222 except:
223 town = ''
224
225 avail = t.trends.available()
226 # World wide
227 if not country:
228 trends = t.trends.place(_id=1)[0]['trends']
229 print_trends(trends)
230 else:
231 for location in avail:
232 # Search for country and Town
233 if town:
234 if location['countryCode'] == country \
235 and location['placeType']['name'] == 'Town' \
236 and location['name'] == town:
237 trends = t.trends.place(_id=location['woeid'])[0]['trends']
238 print_trends(trends)
239 # Search for country only
240 else:
241 if location['countryCode'] == country \
242 and location['placeType']['name'] == 'Country':
243 trends = t.trends.place(_id=location['woeid'])[0]['trends']
244 print_trends(trends)
245
246
247 def home():
248 """
249 Home
250 """
251 t = Twitter(auth=authen())
252 num = c['HOME_TWEET_NUM']
253 if g['stuff'].isdigit():
254 num = int(g['stuff'])
255 for tweet in reversed(t.statuses.home_timeline(count=num)):
256 draw(t=tweet, iot=g['iot'])
257 printNicely('')
258
259
260 def view():
261 """
262 Friend view
263 """
264 t = Twitter(auth=authen())
265 user = g['stuff'].split()[0]
266 if user[0] == '@':
267 try:
268 num = int(g['stuff'].split()[1])
269 except:
270 num = c['HOME_TWEET_NUM']
271 for tweet in reversed(t.statuses.user_timeline(count=num, screen_name=user[1:])):
272 draw(t=tweet, iot=g['iot'])
273 printNicely('')
274 else:
275 printNicely(red('A name should begin with a \'@\''))
276
277
278 def mentions():
279 """
280 Mentions timeline
281 """
282 t = Twitter(auth=authen())
283 num = c['HOME_TWEET_NUM']
284 if g['stuff'].isdigit():
285 num = int(g['stuff'])
286 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
287 draw(t=tweet, iot=g['iot'])
288 printNicely('')
289
290
291 def tweet():
292 """
293 Tweet
294 """
295 t = Twitter(auth=authen())
296 t.statuses.update(status=g['stuff'])
297
298
299 def retweet():
300 """
301 ReTweet
302 """
303 t = Twitter(auth=authen())
304 try:
305 id = int(g['stuff'].split()[0])
306 except:
307 printNicely(red('Sorry I can\'t understand.'))
308 return
309 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
310 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
311
312
313 def allretweet():
314 """
315 List all retweet
316 """
317 t = Twitter(auth=authen())
318 # Get rainbow id
319 try:
320 id = int(g['stuff'].split()[0])
321 except:
322 printNicely(red('Sorry I can\'t understand.'))
323 return
324 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
325 # Get display num if exist
326 try:
327 num = int(g['stuff'].split()[1])
328 except:
329 num = c['RETWEETS_SHOW_NUM']
330 # Get result and display
331 rt_ary = t.statuses.retweets(id=tid, count=num)
332 if not rt_ary:
333 printNicely(magenta('This tweet has no retweet.'))
334 return
335 for tweet in reversed(rt_ary):
336 draw(t=tweet, iot=g['iot'])
337 printNicely('')
338
339
340 def favorite():
341 """
342 Favorite
343 """
344 t = Twitter(auth=authen())
345 try:
346 id = int(g['stuff'].split()[0])
347 except:
348 printNicely(red('Sorry I can\'t understand.'))
349 return
350 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
351 t.favorites.create(_id=tid, include_entities=False)
352 printNicely(green('Favorited.'))
353 draw(t.statuses.show(id=tid), iot=g['iot'])
354 printNicely('')
355
356
357 def reply():
358 """
359 Reply
360 """
361 t = Twitter(auth=authen())
362 try:
363 id = int(g['stuff'].split()[0])
364 except:
365 printNicely(red('Sorry I can\'t understand.'))
366 return
367 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
368 user = t.statuses.show(id=tid)['user']['screen_name']
369 status = ' '.join(g['stuff'].split()[1:])
370 status = '@' + user + ' ' + status.decode('utf-8')
371 t.statuses.update(status=status, in_reply_to_status_id=tid)
372
373
374 def delete():
375 """
376 Delete
377 """
378 t = Twitter(auth=authen())
379 try:
380 rid = int(g['stuff'].split()[0])
381 except:
382 printNicely(red('Sorry I can\'t understand.'))
383 return
384 tid = db.rainbow_to_tweet_query(rid)[0].tweet_id
385 t.statuses.destroy(id=tid)
386 printNicely(green('Okay it\'s gone.'))
387
388
389 def unfavorite():
390 """
391 Unfavorite
392 """
393 t = Twitter(auth=authen())
394 try:
395 id = int(g['stuff'].split()[0])
396 except:
397 printNicely(red('Sorry I can\'t understand.'))
398 return
399 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
400 t.favorites.destroy(_id=tid)
401 printNicely(green('Okay it\'s unfavorited.'))
402 draw(t.statuses.show(id=tid), iot=g['iot'])
403 printNicely('')
404
405
406 def search():
407 """
408 Search
409 """
410 t = Twitter(auth=authen())
411 if g['stuff'].startswith('#'):
412 rel = t.search.tweets(q=g['stuff'])['statuses']
413 if rel:
414 printNicely('Newest tweets:')
415 for i in reversed(xrange(c['SEARCH_MAX_RECORD'])):
416 draw(t=rel[i],
417 iot=g['iot'],
418 keyword=g['stuff'].strip()[1:])
419 printNicely('')
420 else:
421 printNicely(magenta('I\'m afraid there is no result'))
422 else:
423 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
424
425
426 def message():
427 """
428 Send a direct message
429 """
430 t = Twitter(auth=authen())
431 user = g['stuff'].split()[0]
432 if user[0].startswith('@'):
433 try:
434 content = g['stuff'].split()[1]
435 except:
436 printNicely(red('Sorry I can\'t understand.'))
437 t.direct_messages.new(
438 screen_name=user[1:],
439 text=content
440 )
441 printNicely(green('Message sent.'))
442 else:
443 printNicely(red('A name should begin with a \'@\''))
444
445
446 def show():
447 """
448 Show image
449 """
450 t = Twitter(auth=authen())
451 try:
452 target = g['stuff'].split()[0]
453 if target != 'image':
454 return
455 id = int(g['stuff'].split()[1])
456 tid = db.rainbow_to_tweet_query(id)[0].tweet_id
457 tweet = t.statuses.show(id=tid)
458 media = tweet['entities']['media']
459 for m in media:
460 res = requests.get(m['media_url'])
461 img = Image.open(StringIO(res.content))
462 img.show()
463 except:
464 printNicely(red('Sorry I can\'t show this image.'))
465
466
467 def list():
468 """
469 List friends for followers
470 """
471 t = Twitter(auth=authen())
472 # Get name
473 try:
474 name = g['stuff'].split()[1]
475 if name.startswith('@'):
476 name = name[1:]
477 else:
478 printNicely(red('A name should begin with a \'@\''))
479 raise Exception('Invalid name')
480 except:
481 name = g['original_name']
482 # Get list followers or friends
483 try:
484 target = g['stuff'].split()[0]
485 except:
486 printNicely(red('Omg some syntax is wrong.'))
487 # Init cursor
488 d = {'fl': 'followers', 'fr': 'friends'}
489 next_cursor = -1
490 rel = {}
491 # Cursor loop
492 while next_cursor != 0:
493 list = getattr(t, d[target]).list(
494 screen_name=name,
495 cursor=next_cursor,
496 skip_status=True,
497 include_entities=False,
498 )
499 for u in list['users']:
500 rel[u['name']] = '@' + u['screen_name']
501 next_cursor = list['next_cursor']
502 # Print out result
503 printNicely('All: ' + str(len(rel)) + ' people.')
504 for name in rel:
505 user = ' ' + cycle_color(name) + grey(' ' + rel[name] + ' ')
506 printNicely(user)
507
508
509 def inbox():
510 """
511 Inbox direct messages
512 """
513 t = Twitter(auth=authen())
514 num = c['MESSAGES_DISPLAY']
515 rel = []
516 if g['stuff'].isdigit():
517 num = g['stuff']
518 cur_page = 1
519 # Max message per page is 20 so we have to loop
520 while num > 20:
521 rel = rel + t.direct_messages(
522 count=20,
523 page=cur_page,
524 include_entities=False,
525 skip_status=False
526 )
527 num -= 20
528 cur_page += 1
529 rel = rel + t.direct_messages(
530 count=num,
531 page=cur_page,
532 include_entities=False,
533 skip_status=False
534 )
535 # Display
536 printNicely('Inbox: newest ' + str(len(rel)) + ' messages.')
537 for m in reversed(rel):
538 print_message(m)
539 printNicely('')
540
541
542 def sent():
543 """
544 Sent direct messages
545 """
546 t = Twitter(auth=authen())
547 num = c['MESSAGES_DISPLAY']
548 rel = []
549 if g['stuff'].isdigit():
550 num = int(g['stuff'])
551 cur_page = 1
552 # Max message per page is 20 so we have to loop
553 while num > 20:
554 rel = rel + t.direct_messages.sent(
555 count=20,
556 page=cur_page,
557 include_entities=False,
558 skip_status=False
559 )
560 num -= 20
561 cur_page += 1
562 rel = rel + t.direct_messages.sent(
563 count=num,
564 page=cur_page,
565 include_entities=False,
566 skip_status=False
567 )
568 # Display
569 printNicely('Sent: newest ' + str(len(rel)) + ' messages.')
570 for m in reversed(rel):
571 print_message(m)
572 printNicely('')
573
574
575 def trash():
576 """
577 Remove message
578 """
579 t = Twitter(auth=authen())
580 try:
581 rid = int(g['stuff'].split()[0])
582 except:
583 printNicely(red('Sorry I can\'t understand.'))
584 mid = db.rainbow_to_message_query(rid)[0].message_id
585 t.direct_messages.destroy(id=mid)
586 printNicely(green('Message deleted.'))
587
588
589 def whois():
590 """
591 Show profile of a specific user
592 """
593 t = Twitter(auth=authen())
594 screen_name = g['stuff'].split()[0]
595 if screen_name.startswith('@'):
596 try:
597 user = t.users.show(
598 screen_name=screen_name[1:],
599 include_entities=False)
600 show_profile(user, g['iot'])
601 except:
602 printNicely(red('Omg no user.'))
603 else:
604 printNicely(red('A name should begin with a \'@\''))
605
606
607 def follow():
608 """
609 Follow a user
610 """
611 t = Twitter(auth=authen())
612 screen_name = g['stuff'].split()[0]
613 if screen_name.startswith('@'):
614 t.friendships.create(screen_name=screen_name[1:], follow=True)
615 printNicely(green('You are following ' + screen_name + ' now!'))
616 else:
617 printNicely(red('A name should begin with a \'@\''))
618
619
620 def unfollow():
621 """
622 Unfollow a user
623 """
624 t = Twitter(auth=authen())
625 screen_name = g['stuff'].split()[0]
626 if screen_name.startswith('@'):
627 t.friendships.destroy(
628 screen_name=screen_name[1:],
629 include_entities=False)
630 printNicely(green('Unfollow ' + screen_name + ' success!'))
631 else:
632 printNicely(red('A name should begin with a \'@\''))
633
634
635 def mute():
636 """
637 Mute a user
638 """
639 t = Twitter(auth=authen())
640 try:
641 screen_name = g['stuff'].split()[0]
642 except:
643 printNicely(red('A name should be specified. '))
644 return
645 if screen_name.startswith('@'):
646 rel = t.mutes.users.create(screen_name=screen_name[1:])
647 if isinstance(rel, dict):
648 printNicely(green(screen_name + ' is muted.'))
649 else:
650 printNicely(red(rel))
651 else:
652 printNicely(red('A name should begin with a \'@\''))
653
654
655 def unmute():
656 """
657 Unmute a user
658 """
659 t = Twitter(auth=authen())
660 try:
661 screen_name = g['stuff'].split()[0]
662 except:
663 printNicely(red('A name should be specified. '))
664 return
665 if screen_name.startswith('@'):
666 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
667 if isinstance(rel, dict):
668 printNicely(green(screen_name + ' is unmuted.'))
669 else:
670 printNicely(red(rel))
671 else:
672 printNicely(red('A name should begin with a \'@\''))
673
674
675 def muting():
676 """
677 List muting user
678 """
679 t = Twitter(auth=authen())
680 # Init cursor
681 next_cursor = -1
682 rel = {}
683 # Cursor loop
684 while next_cursor != 0:
685 list = t.mutes.users.list(
686 screen_name=g['original_name'],
687 cursor=next_cursor,
688 skip_status=True,
689 include_entities=False,
690 )
691 for u in list['users']:
692 rel[u['name']] = '@' + u['screen_name']
693 next_cursor = list['next_cursor']
694 # Print out result
695 printNicely('All: ' + str(len(rel)) + ' people.')
696 for name in rel:
697 user = ' ' + cycle_color(name) + grey(' ' + rel[name] + ' ')
698 printNicely(user)
699
700
701 def block():
702 """
703 Block a user
704 """
705 t = Twitter(auth=authen())
706 screen_name = g['stuff'].split()[0]
707 if screen_name.startswith('@'):
708 t.blocks.create(
709 screen_name=screen_name[1:],
710 include_entities=False,
711 skip_status=True)
712 printNicely(green('You blocked ' + screen_name + '.'))
713 else:
714 printNicely(red('A name should begin with a \'@\''))
715
716
717 def unblock():
718 """
719 Unblock a user
720 """
721 t = Twitter(auth=authen())
722 screen_name = g['stuff'].split()[0]
723 if screen_name.startswith('@'):
724 t.blocks.destroy(
725 screen_name=screen_name[1:],
726 include_entities=False,
727 skip_status=True)
728 printNicely(green('Unblock ' + screen_name + ' success!'))
729 else:
730 printNicely(red('A name should begin with a \'@\''))
731
732
733 def report():
734 """
735 Report a user as a spam account
736 """
737 t = Twitter(auth=authen())
738 screen_name = g['stuff'].split()[0]
739 if screen_name.startswith('@'):
740 t.users.report_spam(
741 screen_name=screen_name[1:])
742 printNicely(green('You reported ' + screen_name + '.'))
743 else:
744 printNicely(red('Sorry I can\'t understand.'))
745
746
747 def cal():
748 """
749 Unix's command `cal`
750 """
751 # Format
752 rel = os.popen('cal').read().split('\n')
753 month = rel.pop(0)
754 date = rel.pop(0)
755 show_calendar(month, date, rel)
756
757
758 def theme():
759 """
760 List and change theme
761 """
762 if not g['stuff']:
763 # List themes
764 for theme in g['themes']:
765 line = ''
766 # Detect custom config
767 if theme == 'custom':
768 line += light_magenta('custom')
769 custom_path = os.environ.get(
770 'HOME',
771 os.environ.get('USERPROFILE',
772 '')) + os.sep + '.rainbow_config.json'
773 if not os.path.exists(custom_path):
774 line += light_magenta(' (create your own config file at ~/.rainbow_config.json)')
775 else:
776 line += light_magenta(' (loaded)')
777 else:
778 line += light_magenta(theme)
779 if c['theme'] == theme :
780 line = ' '*2 + light_yellow('* ') + line
781 else:
782 line = ' '*4 + line
783 printNicely(line)
784 else:
785 # Change theme
786 try:
787 # Load new config
788 if g['stuff'] != 'custom':
789 new_config = os.path.dirname(__file__) + '/colorset/' + g['stuff'] + '.json'
790 else:
791 new_config = os.environ.get(
792 'HOME',os.environ.get(
793 'USERPROFILE',
794 '')) + os.sep + '.rainbow_config.json'
795 new_config = load_config(new_config)
796 if new_config:
797 for nc in new_config:
798 c[nc] = new_config[nc]
799 # Update db and reset colors
800 db.theme_update(g['stuff'])
801 c['theme'] = g['stuff']
802 notify_cycle()
803 g['decorated_name'] = color_func(
804 c['DECORATED_NAME'])(
805 '[@' + g['original_name'] + ']: ')
806 printNicely(green('Theme changed.'))
807 except:
808 if g['stuff'] == 'custom':
809 printNicely(red('~/.rainbow_config.json is not exists!'))
810 else:
811 printNicely(red('No such theme exists.'))
812
813
814 def help():
815 """
816 Help
817 """
818 s = ' ' * 2
819 h, w = os.popen('stty size', 'r').read().split()
820
821 # Start
822 usage = '\n'
823 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
824 usage += s + '-' * (int(w) - 4) + '\n'
825 usage += s + 'You are ' + \
826 light_yellow('already') + ' on your personal stream.\n'
827 usage += s + 'Any update from Twitter will show up ' + \
828 light_yellow('immediately') + '.\n'
829 usage += s + 'In addtion, following commands are available right now:\n'
830
831 # Discover the world
832 usage += '\n'
833 usage += s + grey(u'\u266A' + ' Discover the world \n')
834 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
835 'You can try ' + light_green('trend US') + ' or ' + \
836 light_green('trend JP Tokyo') + '.\n'
837 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
838 light_green('home 7') + ' will show 7 tweets.\n'
839 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
840 light_green('mentions 7') + ' will show 7 mention tweets.\n'
841 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
842 magenta('@mdo') + '.\n'
843 usage += s * 2 + light_green('view @mdo') + \
844 ' will show ' + magenta('@mdo') + '\'s home.\n'
845 usage += s * 2 + light_green('s #AKB48') + ' will search for "' + \
846 light_yellow('AKB48') + '" and return 5 newest tweet.\n'
847
848 # Tweet
849 usage += '\n'
850 usage += s + grey(u'\u266A' + ' Tweets \n')
851 usage += s * 2 + light_green('t oops ') + \
852 'will tweet "' + light_yellow('oops') + '" immediately.\n'
853 usage += s * 2 + \
854 light_green('rt 12 ') + ' will retweet to tweet with ' + \
855 light_yellow('[id=12]') + '.\n'
856 usage += s * 2 + \
857 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
858 light_yellow('[id=12]') + '.\n'
859 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
860 light_yellow('oops') + '" to tweet with ' + \
861 light_yellow('[id=12]') + '.\n'
862 usage += s * 2 + \
863 light_green('fav 12 ') + ' will favorite the tweet with ' + \
864 light_yellow('[id=12]') + '.\n'
865 usage += s * 2 + \
866 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
867 light_yellow('[id=12]') + '.\n'
868 usage += s * 2 + \
869 light_green('del 12 ') + ' will delete tweet with ' + \
870 light_yellow('[id=12]') + '.\n'
871 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
872 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
873
874 # Direct message
875 usage += '\n'
876 usage += s + grey(u'\u266A' + ' Direct messages \n')
877 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
878 light_green('inbox 7') + ' will show newest 7 messages.\n'
879 usage += s * 2 + light_green('sent') + ' will show sent messages. ' + \
880 light_green('sent 7') + ' will show newest 7 messages.\n'
881 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
882 magenta('@dtvd88') + '.\n'
883 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
884 light_yellow('[message_id=5]') + '.\n'
885
886 # Follower and following
887 usage += '\n'
888 usage += s + grey(u'\u266A' + ' Fiends and followers \n')
889 usage += s * 2 + \
890 light_green('ls fl') + \
891 ' will list all followers (people who are following you).\n'
892 usage += s * 2 + \
893 light_green('ls fr') + \
894 ' will list all friends (people who you are following).\n'
895 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
896 magenta('@dtvd88') + '.\n'
897 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
898 magenta('@dtvd88') + '.\n'
899 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
900 magenta('@dtvd88') + '.\n'
901 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
902 magenta('@dtvd88') + '.\n'
903 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
904 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
905 magenta('@dtvd88') + '.\n'
906 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
907 magenta('@dtvd88') + '.\n'
908 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
909 magenta('@dtvd88') + ' as a spam account.\n'
910
911 # Switch
912 usage += '\n'
913 usage += s + grey(u'\u266A' + ' Switching streams \n')
914 usage += s * 2 + light_green('switch public #AKB') + \
915 ' will switch to public stream and follow "' + \
916 light_yellow('AKB') + '" keyword.\n'
917 usage += s * 2 + light_green('switch mine') + \
918 ' will switch to your personal stream.\n'
919 usage += s * 2 + light_green('switch mine -f ') + \
920 ' will prompt to enter the filter.\n'
921 usage += s * 3 + light_yellow('Only nicks') + \
922 ' filter will decide nicks will be INCLUDE ONLY.\n'
923 usage += s * 3 + light_yellow('Ignore nicks') + \
924 ' filter will decide nicks will be EXCLUDE.\n'
925 usage += s * 2 + light_green('switch mine -d') + \
926 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
927
928 # Smart shell
929 usage += '\n'
930 usage += s + grey(u'\u266A' + ' Smart shell\n')
931 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
932 'will be evaluate by Python interpreter.\n'
933 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
934 ' for current month.\n'
935
936 # Screening
937 usage += '\n'
938 usage += s + grey(u'\u266A' + ' Screening \n')
939 usage += s * 2 + light_green('theme') + ' will list available theme.' + \
940 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
941 ' theme immediately.\n'
942 usage += s * 2 + light_green('h') + ' will show this help again.\n'
943 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
944 usage += s * 2 + light_green('q') + ' will quit.\n'
945
946 # End
947 usage += '\n'
948 usage += s + '-' * (int(w) - 4) + '\n'
949 usage += s + 'Have fun and hang tight! \n'
950 printNicely(usage)
951
952
953 def clear():
954 """
955 Clear screen
956 """
957 os.system('clear')
958
959
960 def quit():
961 """
962 Exit all
963 """
964 save_history()
965 os.system('rm -rf rainbow.db')
966 os.kill(g['stream_pid'], signal.SIGKILL)
967 sys.exit()
968
969
970 def reset():
971 """
972 Reset prefix of line
973 """
974 if g['reset']:
975 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
976 g['reset'] = False
977 try:
978 printNicely(str(eval(g['cmd'])))
979 except Exception:
980 pass
981
982
983 def process(cmd):
984 """
985 Process switch
986 """
987 return dict(zip(
988 cmdset,
989 [
990 switch,
991 trend,
992 home,
993 view,
994 mentions,
995 tweet,
996 retweet,
997 allretweet,
998 favorite,
999 reply,
1000 delete,
1001 unfavorite,
1002 search,
1003 message,
1004 show,
1005 list,
1006 inbox,
1007 sent,
1008 trash,
1009 whois,
1010 follow,
1011 unfollow,
1012 mute,
1013 unmute,
1014 muting,
1015 block,
1016 unblock,
1017 report,
1018 cal,
1019 theme,
1020 help,
1021 clear,
1022 quit
1023 ]
1024 )).get(cmd, reset)
1025
1026
1027 def listen():
1028 """
1029 Listen to user's input
1030 """
1031 d = dict(zip(
1032 cmdset,
1033 [
1034 ['public', 'mine'], # switch
1035 [], # trend
1036 [], # home
1037 ['@'], # view
1038 [], # mentions
1039 [], # tweet
1040 [], # retweet
1041 [], # allretweet
1042 [], # favorite
1043 [], # reply
1044 [], # delete
1045 [], # unfavorite
1046 ['#'], # search
1047 ['@'], # message
1048 ['image'], # show image
1049 ['fl', 'fr'], # list
1050 [], # inbox
1051 [], # sent
1052 [], # trash
1053 ['@'], # whois
1054 ['@'], # follow
1055 ['@'], # unfollow
1056 ['@'], # mute
1057 ['@'], # unmute
1058 ['@'], # muting
1059 ['@'], # block
1060 ['@'], # unblock
1061 ['@'], # report
1062 [], # cal
1063 g['themes'], # theme
1064 [], # help
1065 [], # clear
1066 [], # quit
1067 ]
1068 ))
1069 init_interactive_shell(d)
1070 read_history()
1071 reset()
1072 while True:
1073 if g['prefix']:
1074 line = raw_input(g['decorated_name'])
1075 else:
1076 line = raw_input()
1077 try:
1078 cmd = line.split()[0]
1079 except:
1080 cmd = ''
1081 g['cmd'] = cmd
1082 # Save cmd to global variable and call process
1083 try:
1084 g['stuff'] = ' '.join(line.split()[1:])
1085 process(cmd)()
1086 except Exception:
1087 printNicely(red('OMG something is wrong with Twitter right now.'))
1088 # Not redisplay prefix
1089 if cmd in ['switch', 't', 'rt', 'rep']:
1090 g['prefix'] = False
1091 else:
1092 g['prefix'] = True
1093
1094
1095 def stream(domain, args, name='Rainbow Stream'):
1096 """
1097 Track the stream
1098 """
1099
1100 # The Logo
1101 art_dict = {
1102 c['USER_DOMAIN']: name,
1103 c['PUBLIC_DOMAIN']: args.track_keywords,
1104 c['SITE_DOMAIN']: 'Site Stream',
1105 }
1106 if g['ascii_art']:
1107 ascii_art(art_dict[domain])
1108
1109 # These arguments are optional:
1110 stream_args = dict(
1111 timeout=args.timeout,
1112 block=not args.no_block,
1113 heartbeat_timeout=args.heartbeat_timeout)
1114
1115 # Track keyword
1116 query_args = dict()
1117 if args.track_keywords:
1118 query_args['track'] = args.track_keywords
1119
1120 # Get stream
1121 stream = TwitterStream(
1122 auth=authen(),
1123 domain=domain,
1124 **stream_args)
1125
1126 try:
1127 if domain == c['USER_DOMAIN']:
1128 tweet_iter = stream.user(**query_args)
1129 elif domain == c['SITE_DOMAIN']:
1130 tweet_iter = stream.site(**query_args)
1131 else:
1132 if args.track_keywords:
1133 tweet_iter = stream.statuses.filter(**query_args)
1134 else:
1135 tweet_iter = stream.statuses.sample()
1136
1137 # Iterate over the stream.
1138 for tweet in tweet_iter:
1139 if tweet is None:
1140 printNicely("-- None --")
1141 elif tweet is Timeout:
1142 printNicely("-- Timeout --")
1143 elif tweet is HeartbeatTimeout:
1144 printNicely("-- Heartbeat Timeout --")
1145 elif tweet is Hangup:
1146 printNicely("-- Hangup --")
1147 elif tweet.get('text'):
1148 draw(
1149 t=tweet,
1150 iot=args.image_on_term,
1151 keyword=args.track_keywords,
1152 fil=args.filter,
1153 ig=args.ignore,
1154 )
1155 except TwitterHTTPError:
1156 printNicely('')
1157 printNicely(
1158 magenta("We have maximum connection problem with twitter'stream API right now :("))
1159
1160
1161 def fly():
1162 """
1163 Main function
1164 """
1165 # Spawn stream process
1166 args = parse_arguments()
1167 try:
1168 get_decorated_name()
1169
1170 except TwitterHTTPError:
1171 printNicely('')
1172 printNicely(
1173 magenta("I'm afraid we have maximum connection problem with twitter right now :("))
1174 printNicely(magenta("Let's try again later."))
1175 save_history()
1176 os.system('rm -rf rainbow.db')
1177 sys.exit()
1178
1179 p = Process(
1180 target=stream,
1181 args=(
1182 c['USER_DOMAIN'],
1183 args,
1184 g['original_name']))
1185 p.start()
1186
1187 # Start listen process
1188 time.sleep(0.5)
1189 g['reset'] = True
1190 g['prefix'] = True
1191 g['stream_pid'] = p.pid
1192 g['iot'] = args.image_on_term
1193 listen()