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