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