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