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