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