config fix
[rainbowstream.git] / rainbowstream / rainbow.py
CommitLineData
91476ec3
O
1"""
2Colorful user's timeline stream
3"""
b2b933a9 4import os
5import os.path
6import sys
7import signal
8import argparse
9import time
92983945 10import threading
991c30af 11import requests
80b70d60 12import webbrowser
91476ec3 13
91476ec3 14from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
54277114 15from twitter.api import *
91476ec3 16from twitter.oauth import OAuth, read_token_file
8c840a83 17from twitter.oauth_dance import oauth_dance
91476ec3 18from twitter.util import printNicely
91476ec3 19
7500d90b 20from .draw import *
2a6238f5
O
21from .colors import *
22from .config import *
777c52d4 23from .consumer import *
94a5f62e 24from .interactive import *
991c30af 25from .c_image import *
c3bab4ef 26from .py3patch import *
27
531f5682 28# Global values
f405a7d0 29g = {}
531f5682 30
92983945 31# Lock for streams
92983945
BS
32StreamLock = threading.Lock()
33
531f5682 34# Commands
94a5f62e 35cmdset = [
42fde775 36 'switch',
4592d231 37 'trend',
94a5f62e 38 'home',
39 'view',
305ce127 40 'mentions',
94a5f62e 41 't',
42 'rt',
80b70d60 43 'quote',
1f24a05a 44 'allrt',
7e4ccbf3 45 'fav',
94a5f62e 46 'rep',
47 'del',
7e4ccbf3 48 'ufav',
94a5f62e 49 's',
305ce127 50 'mes',
f5677fb1 51 'show',
80b70d60 52 'open',
0f6e4daf 53 'ls',
305ce127 54 'inbox',
55 'sent',
56 'trash',
e2b81717 57 'whois',
94a5f62e 58 'fl',
f5677fb1 59 'ufl',
5b2c4faf 60 'mute',
61 'unmute',
62 'muting',
305ce127 63 'block',
64 'unblock',
65 'report',
2d341029 66 'list',
813a5d80 67 'cal',
29fd0be6 68 'config',
632c6fa5 69 'theme',
94a5f62e 70 'h',
d6cc4c67
O
71 'p',
72 'r',
94a5f62e 73 'c',
74 'q'
75]
22be990e 76
c075e6dc 77
91476ec3
O
78def parse_arguments():
79 """
80 Parse the arguments
81 """
91476ec3 82 parser = argparse.ArgumentParser(description=__doc__ or "")
2a6238f5
O
83 parser.add_argument(
84 '-to',
85 '--timeout',
86 help='Timeout for the stream (seconds).')
87 parser.add_argument(
88 '-ht',
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
91 default=90)
92 parser.add_argument(
93 '-nb',
94 '--no-block',
95 action='store_true',
96 help='Set stream to non-blocking.')
97 parser.add_argument(
98 '-tt',
99 '--track-keywords',
100 help='Search the stream for specific text.')
d51b4107
O
101 parser.add_argument(
102 '-fil',
103 '--filter',
104 help='Filter specific screen_name.')
105 parser.add_argument(
106 '-ig',
107 '--ignore',
108 help='Ignore specific screen_name.')
88af38d8 109 parser.add_argument(
c1fa7c94
O
110 '-iot',
111 '--image-on-term',
112 action='store_true',
113 help='Display all image on terminal.')
91476ec3
O
114 return parser.parse_args()
115
116
54277114
O
117def authen():
118 """
7b674cef 119 Authenticate with Twitter OAuth
54277114 120 """
8c840a83 121 # When using rainbow stream you must authorize.
2a6238f5
O
122 twitter_credential = os.environ.get(
123 'HOME',
124 os.environ.get(
125 'USERPROFILE',
126 '')) + os.sep + '.rainbow_oauth'
8c840a83
O
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)
54277114 133 return OAuth(
2a6238f5
O
134 oauth_token,
135 oauth_token_secret,
136 CONSUMER_KEY,
137 CONSUMER_SECRET)
91476ec3 138
54277114 139
fe9bb33b 140def init(args):
54277114 141 """
9683e61d 142 Init function
54277114 143 """
64156ac4
O
144 # Handle Ctrl C
145 ctrl_c_handler = lambda signum, frame: quit()
146 signal.signal(signal.SIGINT, ctrl_c_handler)
9683e61d 147 # Get name
54277114 148 t = Twitter(auth=authen())
c5ff542b 149 name = '@' + t.account.verify_credentials()['screen_name']
ceec8593 150 if not get_config('PREFIX'):
151 set_config('PREFIX', name)
42fde775 152 g['original_name'] = name[1:]
ceec8593 153 g['decorated_name'] = lambda x: color_func(
a8e71259 154 c['DECORATED_NAME'])('[' + x + ']: ')
9683e61d 155 # Theme init
422dd385 156 files = os.listdir(os.path.dirname(__file__) + '/colorset')
c075e6dc 157 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
632c6fa5 158 g['themes'] = themes
4824b181 159 # Startup cmd
4824b181 160 g['previous_cmd'] = ''
9683e61d 161 # Semaphore init
99b52f5f
O
162 c['lock'] = False
163 c['pause'] = False
164 # Init tweet dict and message dict
165 c['tweet_dict'] = []
166 c['message_dict'] = []
fe9bb33b 167 # Image on term
168 c['IMAGE_ON_TERM'] = args.image_on_term
a8e71259 169 set_config('IMAGE_ON_TERM',str(c['IMAGE_ON_TERM']))
f405a7d0 170
ceec8593 171
42fde775 172def switch():
173 """
174 Switch stream
175 """
176 try:
177 target = g['stuff'].split()[0]
d51b4107
O
178 # Filter and ignore
179 args = parse_arguments()
7e4ccbf3 180 try:
d51b4107 181 if g['stuff'].split()[-1] == '-f':
14db58c7 182 guide = 'To ignore an option, just hit Enter key.'
183 printNicely(light_magenta(guide))
184 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
185 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
7e4ccbf3 186 args.filter = filter(None, only.split(','))
187 args.ignore = filter(None, ignore.split(','))
d51b4107 188 elif g['stuff'].split()[-1] == '-d':
632c6fa5
O
189 args.filter = c['ONLY_LIST']
190 args.ignore = c['IGNORE_LIST']
d51b4107
O
191 except:
192 printNicely(red('Sorry, wrong format.'))
193 return
42fde775 194 # Public stream
195 if target == 'public':
196 keyword = g['stuff'].split()[1]
197 if keyword[0] == '#':
198 keyword = keyword[1:]
92983945
BS
199 # Kill old thread
200 g['stream_stop'] = True
42fde775 201 args.track_keywords = keyword
92983945 202 # Start new thread
baec5f50 203 th = threading.Thread(
204 target=stream,
205 args=(
206 c['PUBLIC_DOMAIN'],
207 args))
92983945
BS
208 th.daemon = True
209 th.start()
42fde775 210 # Personal stream
211 elif target == 'mine':
92983945
BS
212 # Kill old thread
213 g['stream_stop'] = True
214 # Start new thread
baec5f50 215 th = threading.Thread(
216 target=stream,
217 args=(
218 c['USER_DOMAIN'],
219 args,
220 g['original_name']))
92983945
BS
221 th.daemon = True
222 th.start()
d51b4107 223 printNicely('')
d51b4107
O
224 if args.filter:
225 printNicely(cyan('Only: ' + str(args.filter)))
226 if args.ignore:
227 printNicely(red('Ignore: ' + str(args.ignore)))
228 printNicely('')
49514d7e 229 except:
42fde775 230 printNicely(red('Sorry I can\'t understand.'))
42fde775 231
232
4592d231 233def trend():
234 """
235 Trend
236 """
237 t = Twitter(auth=authen())
48a25fe8 238 # Get country and town
4592d231 239 try:
240 country = g['stuff'].split()[0]
241 except:
242 country = ''
48a25fe8 243 try:
244 town = g['stuff'].split()[1]
245 except:
246 town = ''
48a25fe8 247 avail = t.trends.available()
248 # World wide
249 if not country:
250 trends = t.trends.place(_id=1)[0]['trends']
251 print_trends(trends)
252 else:
253 for location in avail:
254 # Search for country and Town
255 if town:
256 if location['countryCode'] == country \
257 and location['placeType']['name'] == 'Town' \
258 and location['name'] == town:
259 trends = t.trends.place(_id=location['woeid'])[0]['trends']
260 print_trends(trends)
261 # Search for country only
262 else:
263 if location['countryCode'] == country \
264 and location['placeType']['name'] == 'Country':
265 trends = t.trends.place(_id=location['woeid'])[0]['trends']
266 print_trends(trends)
4592d231 267
268
7b674cef 269def home():
270 """
271 Home
272 """
273 t = Twitter(auth=authen())
632c6fa5 274 num = c['HOME_TWEET_NUM']
7b674cef 275 if g['stuff'].isdigit():
305ce127 276 num = int(g['stuff'])
94a5f62e 277 for tweet in reversed(t.statuses.home_timeline(count=num)):
fe9bb33b 278 draw(t=tweet)
94a5f62e 279 printNicely('')
7b674cef 280
281
282def view():
283 """
284 Friend view
285 """
286 t = Twitter(auth=authen())
287 user = g['stuff'].split()[0]
b8fbcb70 288 if user[0] == '@':
289 try:
94a5f62e 290 num = int(g['stuff'].split()[1])
b8fbcb70 291 except:
632c6fa5 292 num = c['HOME_TWEET_NUM']
94a5f62e 293 for tweet in reversed(t.statuses.user_timeline(count=num, screen_name=user[1:])):
fe9bb33b 294 draw(t=tweet)
94a5f62e 295 printNicely('')
b8fbcb70 296 else:
c91f75f2 297 printNicely(red('A name should begin with a \'@\''))
7b674cef 298
299
305ce127 300def mentions():
301 """
302 Mentions timeline
303 """
304 t = Twitter(auth=authen())
632c6fa5 305 num = c['HOME_TWEET_NUM']
305ce127 306 if g['stuff'].isdigit():
307 num = int(g['stuff'])
308 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
fe9bb33b 309 draw(t=tweet)
305ce127 310 printNicely('')
311
312
f405a7d0 313def tweet():
54277114 314 """
7b674cef 315 Tweet
54277114
O
316 """
317 t = Twitter(auth=authen())
f405a7d0 318 t.statuses.update(status=g['stuff'])
f405a7d0 319
b2b933a9 320
1ba4abfd
O
321def retweet():
322 """
323 ReTweet
324 """
325 t = Twitter(auth=authen())
326 try:
327 id = int(g['stuff'].split()[0])
1ba4abfd 328 except:
b8c1f42a
O
329 printNicely(red('Sorry I can\'t understand.'))
330 return
99b52f5f 331 tid = c['tweet_dict'][id]
b8c1f42a 332 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
1ba4abfd
O
333
334
80b70d60
O
335def quote():
336 """
337 Quote a tweet
338 """
339 t = Twitter(auth=authen())
340 try:
341 id = int(g['stuff'].split()[0])
342 except:
343 printNicely(red('Sorry I can\'t understand.'))
344 return
99b52f5f 345 tid = c['tweet_dict'][id]
80b70d60
O
346 tweet = t.statuses.show(id=tid)
347 screen_name = tweet['user']['screen_name']
348 text = tweet['text']
349 quote = '\"@' + screen_name + ': ' + text + '\"'
350 quote = quote.encode('utf8')
595fdb16
O
351 notice = light_magenta('Compose mode ')
352 notice += light_yellow('(Enter nothing will cancel the quote)')
353 notice += light_magenta(':')
354 printNicely(notice)
80b70d60
O
355 extra = raw_input(quote)
356 if extra:
422dd385 357 t.statuses.update(status=quote + extra)
80b70d60
O
358 else:
359 printNicely(light_magenta('No text added.'))
360
361
1f24a05a 362def allretweet():
363 """
364 List all retweet
365 """
366 t = Twitter(auth=authen())
367 # Get rainbow id
368 try:
369 id = int(g['stuff'].split()[0])
370 except:
371 printNicely(red('Sorry I can\'t understand.'))
372 return
99b52f5f 373 tid = c['tweet_dict'][id]
1f24a05a 374 # Get display num if exist
375 try:
376 num = int(g['stuff'].split()[1])
377 except:
632c6fa5 378 num = c['RETWEETS_SHOW_NUM']
1f24a05a 379 # Get result and display
d8e901a4 380 rt_ary = t.statuses.retweets(id=tid, count=num)
1f24a05a 381 if not rt_ary:
382 printNicely(magenta('This tweet has no retweet.'))
383 return
384 for tweet in reversed(rt_ary):
fe9bb33b 385 draw(t=tweet)
1f24a05a 386 printNicely('')
387
388
7e4ccbf3 389def favorite():
390 """
391 Favorite
392 """
393 t = Twitter(auth=authen())
394 try:
395 id = int(g['stuff'].split()[0])
7e4ccbf3 396 except:
b8c1f42a
O
397 printNicely(red('Sorry I can\'t understand.'))
398 return
99b52f5f 399 tid = c['tweet_dict'][id]
b8c1f42a
O
400 t.favorites.create(_id=tid, include_entities=False)
401 printNicely(green('Favorited.'))
fe9bb33b 402 draw(t.statuses.show(id=tid))
b8c1f42a 403 printNicely('')
7e4ccbf3 404
405
7b674cef 406def reply():
829cc2d8 407 """
7b674cef 408 Reply
829cc2d8
O
409 """
410 t = Twitter(auth=authen())
7b674cef 411 try:
412 id = int(g['stuff'].split()[0])
7b674cef 413 except:
c91f75f2 414 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a 415 return
99b52f5f 416 tid = c['tweet_dict'][id]
b8c1f42a
O
417 user = t.statuses.show(id=tid)['user']['screen_name']
418 status = ' '.join(g['stuff'].split()[1:])
419 status = '@' + user + ' ' + status.decode('utf-8')
420 t.statuses.update(status=status, in_reply_to_status_id=tid)
7b674cef 421
422
423def delete():
424 """
425 Delete
426 """
427 t = Twitter(auth=authen())
428 try:
99b52f5f 429 id = int(g['stuff'].split()[0])
7b674cef 430 except:
305ce127 431 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a 432 return
99b52f5f 433 tid = c['tweet_dict'][id]
b8c1f42a
O
434 t.statuses.destroy(id=tid)
435 printNicely(green('Okay it\'s gone.'))
829cc2d8
O
436
437
7e4ccbf3 438def unfavorite():
439 """
440 Unfavorite
441 """
442 t = Twitter(auth=authen())
443 try:
444 id = int(g['stuff'].split()[0])
7e4ccbf3 445 except:
b8c1f42a
O
446 printNicely(red('Sorry I can\'t understand.'))
447 return
99b52f5f 448 tid = c['tweet_dict'][id]
b8c1f42a
O
449 t.favorites.destroy(_id=tid)
450 printNicely(green('Okay it\'s unfavorited.'))
fe9bb33b 451 draw(t.statuses.show(id=tid))
b8c1f42a 452 printNicely('')
7e4ccbf3 453
454
f405a7d0
O
455def search():
456 """
7b674cef 457 Search
f405a7d0
O
458 """
459 t = Twitter(auth=authen())
59262e95
O
460 g['stuff'] = g['stuff'].strip()
461 rel = t.search.tweets(q=g['stuff'])['statuses']
462 if rel:
463 printNicely('Newest tweets:')
464 for i in reversed(xrange(c['SEARCH_MAX_RECORD'])):
465 draw(t=rel[i],
59262e95
O
466 keyword=g['stuff'])
467 printNicely('')
b8c1f42a 468 else:
59262e95 469 printNicely(magenta('I\'m afraid there is no result'))
b2b933a9 470
f405a7d0 471
305ce127 472def message():
473 """
474 Send a direct message
475 """
476 t = Twitter(auth=authen())
477 user = g['stuff'].split()[0]
b8c1f42a 478 if user[0].startswith('@'):
305ce127 479 try:
480 content = g['stuff'].split()[1]
305ce127 481 except:
482 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a
O
483 t.direct_messages.new(
484 screen_name=user[1:],
485 text=content
486 )
487 printNicely(green('Message sent.'))
305ce127 488 else:
489 printNicely(red('A name should begin with a \'@\''))
490
491
f5677fb1 492def show():
843647ad 493 """
f5677fb1 494 Show image
843647ad
O
495 """
496 t = Twitter(auth=authen())
f5677fb1
O
497 try:
498 target = g['stuff'].split()[0]
499 if target != 'image':
500 return
501 id = int(g['stuff'].split()[1])
99b52f5f 502 tid = c['tweet_dict'][id]
f5677fb1
O
503 tweet = t.statuses.show(id=tid)
504 media = tweet['entities']['media']
505 for m in media:
506 res = requests.get(m['media_url'])
b3164e62 507 img = Image.open(BytesIO(res.content))
f5677fb1
O
508 img.show()
509 except:
510 printNicely(red('Sorry I can\'t show this image.'))
843647ad
O
511
512
80bb2040 513def urlopen():
80b70d60
O
514 """
515 Open url
516 """
517 t = Twitter(auth=authen())
518 try:
519 if not g['stuff'].isdigit():
520 return
8101275e 521 tid = c['tweet_dict'][int(g['stuff'])]
80b70d60 522 tweet = t.statuses.show(id=tid)
422dd385
O
523 link_ary = [
524 u for u in tweet['text'].split() if u.startswith('http://')]
80b70d60
O
525 if not link_ary:
526 printNicely(light_magenta('No url here @.@!'))
527 return
528 for link in link_ary:
529 webbrowser.open(link)
530 except:
531 printNicely(red('Sorry I can\'t open url in this tweet.'))
532
533
2d341029 534def ls():
0f6e4daf 535 """
536 List friends for followers
537 """
538 t = Twitter(auth=authen())
e2b81717
O
539 # Get name
540 try:
541 name = g['stuff'].split()[1]
b8c1f42a 542 if name.startswith('@'):
e2b81717
O
543 name = name[1:]
544 else:
545 printNicely(red('A name should begin with a \'@\''))
546 raise Exception('Invalid name')
547 except:
548 name = g['original_name']
549 # Get list followers or friends
0f6e4daf 550 try:
551 target = g['stuff'].split()[0]
0f6e4daf 552 except:
553 printNicely(red('Omg some syntax is wrong.'))
b8c1f42a
O
554 # Init cursor
555 d = {'fl': 'followers', 'fr': 'friends'}
556 next_cursor = -1
557 rel = {}
558 # Cursor loop
559 while next_cursor != 0:
560 list = getattr(t, d[target]).list(
561 screen_name=name,
562 cursor=next_cursor,
563 skip_status=True,
564 include_entities=False,
565 )
566 for u in list['users']:
567 rel[u['name']] = '@' + u['screen_name']
568 next_cursor = list['next_cursor']
569 # Print out result
2d341029 570 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
b8c1f42a 571 for name in rel:
2d341029 572 user = ' ' + cycle_color(name)
422dd385 573 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
b8c1f42a 574 printNicely(user)
0f6e4daf 575
576
305ce127 577def inbox():
578 """
579 Inbox direct messages
580 """
581 t = Twitter(auth=authen())
632c6fa5 582 num = c['MESSAGES_DISPLAY']
305ce127 583 rel = []
584 if g['stuff'].isdigit():
585 num = g['stuff']
586 cur_page = 1
587 # Max message per page is 20 so we have to loop
588 while num > 20:
589 rel = rel + t.direct_messages(
590 count=20,
591 page=cur_page,
592 include_entities=False,
593 skip_status=False
48a25fe8 594 )
305ce127 595 num -= 20
596 cur_page += 1
597 rel = rel + t.direct_messages(
598 count=num,
599 page=cur_page,
600 include_entities=False,
601 skip_status=False
48a25fe8 602 )
e2b81717 603 # Display
305ce127 604 printNicely('Inbox: newest ' + str(len(rel)) + ' messages.')
605 for m in reversed(rel):
606 print_message(m)
607 printNicely('')
608
e2b81717 609
305ce127 610def sent():
611 """
612 Sent direct messages
613 """
614 t = Twitter(auth=authen())
632c6fa5 615 num = c['MESSAGES_DISPLAY']
305ce127 616 rel = []
617 if g['stuff'].isdigit():
618 num = int(g['stuff'])
619 cur_page = 1
620 # Max message per page is 20 so we have to loop
621 while num > 20:
622 rel = rel + t.direct_messages.sent(
623 count=20,
624 page=cur_page,
625 include_entities=False,
626 skip_status=False
48a25fe8 627 )
305ce127 628 num -= 20
629 cur_page += 1
630 rel = rel + t.direct_messages.sent(
631 count=num,
632 page=cur_page,
633 include_entities=False,
634 skip_status=False
48a25fe8 635 )
e2b81717 636 # Display
305ce127 637 printNicely('Sent: newest ' + str(len(rel)) + ' messages.')
638 for m in reversed(rel):
639 print_message(m)
640 printNicely('')
e2b81717 641
305ce127 642
643def trash():
644 """
645 Remove message
646 """
647 t = Twitter(auth=authen())
648 try:
99b52f5f 649 id = int(g['stuff'].split()[0])
305ce127 650 except:
651 printNicely(red('Sorry I can\'t understand.'))
99b52f5f 652 mid = c['message_dict'][id]
b8c1f42a
O
653 t.direct_messages.destroy(id=mid)
654 printNicely(green('Message deleted.'))
305ce127 655
656
e2b81717
O
657def whois():
658 """
659 Show profile of a specific user
660 """
661 t = Twitter(auth=authen())
662 screen_name = g['stuff'].split()[0]
b8c1f42a 663 if screen_name.startswith('@'):
e2b81717
O
664 try:
665 user = t.users.show(
666 screen_name=screen_name[1:],
667 include_entities=False)
fe9bb33b 668 show_profile(user)
e2b81717
O
669 except:
670 printNicely(red('Omg no user.'))
671 else:
b8c1f42a 672 printNicely(red('A name should begin with a \'@\''))
e2b81717
O
673
674
f5677fb1 675def follow():
843647ad 676 """
f5677fb1 677 Follow a user
843647ad
O
678 """
679 t = Twitter(auth=authen())
f5677fb1 680 screen_name = g['stuff'].split()[0]
b8c1f42a
O
681 if screen_name.startswith('@'):
682 t.friendships.create(screen_name=screen_name[1:], follow=True)
683 printNicely(green('You are following ' + screen_name + ' now!'))
f5677fb1 684 else:
b8c1f42a 685 printNicely(red('A name should begin with a \'@\''))
f5677fb1
O
686
687
688def unfollow():
689 """
690 Unfollow a user
691 """
692 t = Twitter(auth=authen())
693 screen_name = g['stuff'].split()[0]
b8c1f42a
O
694 if screen_name.startswith('@'):
695 t.friendships.destroy(
696 screen_name=screen_name[1:],
697 include_entities=False)
698 printNicely(green('Unfollow ' + screen_name + ' success!'))
f5677fb1 699 else:
b8c1f42a 700 printNicely(red('A name should begin with a \'@\''))
843647ad
O
701
702
5b2c4faf 703def mute():
704 """
705 Mute a user
706 """
707 t = Twitter(auth=authen())
708 try:
709 screen_name = g['stuff'].split()[0]
710 except:
711 printNicely(red('A name should be specified. '))
712 return
713 if screen_name.startswith('@'):
714 rel = t.mutes.users.create(screen_name=screen_name[1:])
715 if isinstance(rel, dict):
716 printNicely(green(screen_name + ' is muted.'))
717 else:
718 printNicely(red(rel))
719 else:
720 printNicely(red('A name should begin with a \'@\''))
721
722
723def unmute():
724 """
725 Unmute a user
726 """
727 t = Twitter(auth=authen())
728 try:
729 screen_name = g['stuff'].split()[0]
730 except:
731 printNicely(red('A name should be specified. '))
732 return
733 if screen_name.startswith('@'):
734 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
735 if isinstance(rel, dict):
736 printNicely(green(screen_name + ' is unmuted.'))
737 else:
738 printNicely(red(rel))
739 else:
740 printNicely(red('A name should begin with a \'@\''))
741
742
743def muting():
744 """
745 List muting user
746 """
747 t = Twitter(auth=authen())
748 # Init cursor
5b2c4faf 749 next_cursor = -1
750 rel = {}
751 # Cursor loop
752 while next_cursor != 0:
753 list = t.mutes.users.list(
754 screen_name=g['original_name'],
755 cursor=next_cursor,
756 skip_status=True,
757 include_entities=False,
758 )
759 for u in list['users']:
760 rel[u['name']] = '@' + u['screen_name']
761 next_cursor = list['next_cursor']
762 # Print out result
763 printNicely('All: ' + str(len(rel)) + ' people.')
764 for name in rel:
2d341029 765 user = ' ' + cycle_color(name)
422dd385 766 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
5b2c4faf 767 printNicely(user)
768
769
305ce127 770def block():
771 """
772 Block a user
773 """
774 t = Twitter(auth=authen())
775 screen_name = g['stuff'].split()[0]
b8c1f42a
O
776 if screen_name.startswith('@'):
777 t.blocks.create(
5b2c4faf 778 screen_name=screen_name[1:],
779 include_entities=False,
780 skip_status=True)
b8c1f42a 781 printNicely(green('You blocked ' + screen_name + '.'))
305ce127 782 else:
b8c1f42a 783 printNicely(red('A name should begin with a \'@\''))
305ce127 784
785
786def unblock():
787 """
788 Unblock a user
789 """
790 t = Twitter(auth=authen())
791 screen_name = g['stuff'].split()[0]
b8c1f42a
O
792 if screen_name.startswith('@'):
793 t.blocks.destroy(
794 screen_name=screen_name[1:],
795 include_entities=False,
796 skip_status=True)
797 printNicely(green('Unblock ' + screen_name + ' success!'))
305ce127 798 else:
b8c1f42a 799 printNicely(red('A name should begin with a \'@\''))
305ce127 800
801
802def report():
803 """
804 Report a user as a spam account
805 """
806 t = Twitter(auth=authen())
807 screen_name = g['stuff'].split()[0]
b8c1f42a
O
808 if screen_name.startswith('@'):
809 t.users.report_spam(
810 screen_name=screen_name[1:])
811 printNicely(green('You reported ' + screen_name + '.'))
305ce127 812 else:
813 printNicely(red('Sorry I can\'t understand.'))
814
815
8b8566d1
O
816def get_slug():
817 """
818 Get Slug Decorator
819 """
a8c5fce4 820 # Get list name
8b8566d1
O
821 list_name = raw_input(light_magenta('Give me the list\'s name: '))
822 # Get list name and owner
823 try:
824 owner, slug = list_name.split('/')
825 if slug.startswith('@'):
826 slug = slug[1:]
827 return owner, slug
828 except:
a8c5fce4
O
829 printNicely(
830 light_magenta('List name should follow "@owner/list_name" format.'))
8b8566d1
O
831 raise Exception('Wrong list name')
832
833
2d341029
O
834def show_lists(t):
835 """
422dd385 836 List list
2d341029
O
837 """
838 rel = t.lists.list(screen_name=g['original_name'])
839 if rel:
840 print_list(rel)
841 else:
842 printNicely(light_magenta('You belong to no lists :)'))
843
844
845def list_home(t):
846 """
847 List home
848 """
8b8566d1 849 owner, slug = get_slug()
2d341029 850 res = t.lists.statuses(
422dd385
O
851 slug=slug,
852 owner_screen_name=owner,
853 count=c['LIST_MAX'],
2d341029
O
854 include_entities=False)
855 for tweet in res:
856 draw(t=tweet)
857 printNicely('')
858
859
860def list_members(t):
861 """
862 List members
863 """
8b8566d1 864 owner, slug = get_slug()
422dd385 865 # Get members
2d341029
O
866 rel = {}
867 next_cursor = -1
422dd385 868 while next_cursor != 0:
2d341029 869 m = t.lists.members(
422dd385
O
870 slug=slug,
871 owner_screen_name=owner,
872 cursor=next_cursor,
2d341029
O
873 include_entities=False)
874 for u in m['users']:
875 rel[u['name']] = '@' + u['screen_name']
876 next_cursor = m['next_cursor']
877 printNicely('All: ' + str(len(rel)) + ' members.')
878 for name in rel:
879 user = ' ' + cycle_color(name)
422dd385 880 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
881 printNicely(user)
882
883
884def list_subscribers(t):
885 """
886 List subscribers
887 """
8b8566d1 888 owner, slug = get_slug()
422dd385 889 # Get subscribers
2d341029
O
890 rel = {}
891 next_cursor = -1
422dd385 892 while next_cursor != 0:
2d341029 893 m = t.lists.subscribers(
422dd385
O
894 slug=slug,
895 owner_screen_name=owner,
896 cursor=next_cursor,
2d341029
O
897 include_entities=False)
898 for u in m['users']:
899 rel[u['name']] = '@' + u['screen_name']
900 next_cursor = m['next_cursor']
901 printNicely('All: ' + str(len(rel)) + ' subscribers.')
902 for name in rel:
903 user = ' ' + cycle_color(name)
422dd385 904 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
905 printNicely(user)
906
907
422dd385
O
908def list_add(t):
909 """
910 Add specific user to a list
911 """
8b8566d1 912 owner, slug = get_slug()
422dd385
O
913 # Add
914 user_name = raw_input(light_magenta('Give me name of the newbie: '))
915 if user_name.startswith('@'):
916 user_name = user_name[1:]
917 try:
918 t.lists.members.create(
919 slug=slug,
920 owner_screen_name=owner,
921 screen_name=user_name)
d6cc4c67 922 printNicely(green('Added.'))
422dd385
O
923 except:
924 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
925
926
2d341029
O
927def list_remove(t):
928 """
929 Remove specific user from a list
930 """
8b8566d1 931 owner, slug = get_slug()
2d341029 932 # Remove
422dd385
O
933 user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
934 if user_name.startswith('@'):
935 user_name = user_name[1:]
2d341029
O
936 try:
937 t.lists.members.destroy(
422dd385
O
938 slug=slug,
939 owner_screen_name=owner,
940 screen_name=user_name)
d6cc4c67 941 printNicely(green('Gone.'))
422dd385
O
942 except:
943 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
944
945
946def list_subscribe(t):
947 """
948 Subscribe to a list
949 """
8b8566d1 950 owner, slug = get_slug()
422dd385
O
951 # Subscribe
952 try:
953 t.lists.subscribers.create(
954 slug=slug,
955 owner_screen_name=owner)
d6cc4c67 956 printNicely(green('Done.'))
422dd385
O
957 except:
958 printNicely(
959 light_magenta('I\'m sorry you can not subscribe to this list.'))
960
961
962def list_unsubscribe(t):
963 """
964 Unsubscribe a list
965 """
8b8566d1 966 owner, slug = get_slug()
422dd385
O
967 # Subscribe
968 try:
969 t.lists.subscribers.destroy(
970 slug=slug,
971 owner_screen_name=owner)
d6cc4c67 972 printNicely(green('Done.'))
422dd385
O
973 except:
974 printNicely(
975 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
976
977
978def list_own(t):
979 """
980 List own
981 """
982 rel = []
983 next_cursor = -1
984 while next_cursor != 0:
985 res = t.lists.ownerships(
986 screen_name=g['original_name'],
987 cursor=next_cursor)
988 rel += res['lists']
989 next_cursor = res['next_cursor']
990 if rel:
991 print_list(rel)
992 else:
993 printNicely(light_magenta('You own no lists :)'))
994
995
996def list_new(t):
997 """
998 Create a new list
999 """
1000 name = raw_input(light_magenta('New list\'s name: '))
1001 mode = raw_input(light_magenta('New list\'s mode (public/private): '))
1002 description = raw_input(light_magenta('New list\'s description: '))
1003 try:
1004 t.lists.create(
1005 name=name,
1006 mode=mode,
1007 description=description)
d6cc4c67 1008 printNicely(green(name + ' list is created.'))
422dd385
O
1009 except:
1010 printNicely(red('Oops something is wrong with Twitter :('))
1011
1012
1013def list_update(t):
1014 """
1015 Update a list
1016 """
1017 slug = raw_input(light_magenta('Your list that you want to update: '))
1018 name = raw_input(light_magenta('Update name (leave blank to unchange): '))
1019 mode = raw_input(light_magenta('Update mode (public/private): '))
1020 description = raw_input(light_magenta('Update description: '))
1021 try:
1022 if name:
1023 t.lists.update(
1024 slug='-'.join(slug.split()),
1025 owner_screen_name=g['original_name'],
1026 name=name,
1027 mode=mode,
1028 description=description)
1029 else:
1030 t.lists.update(
1031 slug=slug,
1032 owner_screen_name=g['original_name'],
1033 mode=mode,
1034 description=description)
d6cc4c67 1035 printNicely(green(slug + ' list is updated.'))
3c85d8fc 1036 except:
422dd385
O
1037 printNicely(red('Oops something is wrong with Twitter :('))
1038
1039
1040def list_delete(t):
1041 """
1042 Delete a list
1043 """
1044 slug = raw_input(light_magenta('Your list that you want to update: '))
1045 try:
1046 t.lists.destroy(
1047 slug='-'.join(slug.split()),
1048 owner_screen_name=g['original_name'])
d6cc4c67 1049 printNicely(green(slug + ' list is deleted.'))
2d341029 1050 except:
422dd385 1051 printNicely(red('Oops something is wrong with Twitter :('))
2d341029
O
1052
1053
1054def list():
1055 """
1056 Twitter's list
1057 """
1058 t = Twitter(auth=authen())
1059 # List all lists or base on action
1060 try:
1061 g['list_action'] = g['stuff'].split()[0]
1062 except:
1063 show_lists(t)
1064 return
422dd385 1065 # Sub-function
2d341029
O
1066 action_ary = {
1067 'home': list_home,
1068 'all_mem': list_members,
1069 'all_sub': list_subscribers,
422dd385 1070 'add': list_add,
2d341029 1071 'rm': list_remove,
422dd385
O
1072 'sub': list_subscribe,
1073 'unsub': list_unsubscribe,
1074 'own': list_own,
1075 'new': list_new,
1076 'update': list_update,
1077 'del': list_delete,
2d341029
O
1078 }
1079 try:
1080 return action_ary[g['list_action']](t)
3c85d8fc 1081 except:
8b8566d1 1082 printNicely(red('Please try again.'))
2d341029
O
1083
1084
813a5d80 1085def cal():
1086 """
1087 Unix's command `cal`
1088 """
1089 # Format
1090 rel = os.popen('cal').read().split('\n')
1091 month = rel.pop(0)
813a5d80 1092 date = rel.pop(0)
2a0cabee 1093 show_calendar(month, date, rel)
813a5d80 1094
1095
29fd0be6
O
1096def config():
1097 """
1098 Browse and change config
1099 """
1100 all_config = get_all_config()
1101 g['stuff'] = g['stuff'].strip()
1102 # List all config
1103 if not g['stuff']:
1104 for k in all_config:
a8c5fce4 1105 line = ' ' * 2 + \
d6cc4c67 1106 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1107 printNicely(line)
1108 guide = 'Detailed explanation can be found at ' + \
a8c5fce4
O
1109 color_func(c['TWEET']['link'])(
1110 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
29fd0be6
O
1111 printNicely(guide)
1112 # Print specific config
1113 elif len(g['stuff'].split()) == 1:
1114 if g['stuff'] in all_config:
1115 k = g['stuff']
a8c5fce4 1116 line = ' ' * 2 + \
d6cc4c67 1117 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1118 printNicely(line)
1119 else:
fe9bb33b 1120 printNicely(red('No such config key.'))
29fd0be6
O
1121 # Print specific config's default value
1122 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1123 key = g['stuff'].split()[0]
fe9bb33b 1124 try:
1125 value = get_default_config(key)
d6cc4c67 1126 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
fe9bb33b 1127 printNicely(line)
a8e71259 1128 except Exception as e:
1129 printNicely(red(e))
fe9bb33b 1130 # Delete specific config key in config file
1131 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1132 key = g['stuff'].split()[0]
1133 try:
1134 delete_config(key)
d6cc4c67 1135 printNicely(green('Config key is dropped.'))
a8e71259 1136 except Exception as e:
1137 printNicely(red(e))
29fd0be6 1138 # Set specific config
a8c5fce4 1139 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
29fd0be6
O
1140 key = g['stuff'].split()[0]
1141 value = g['stuff'].split()[-1]
ceec8593 1142 if key == 'THEME' and not validate_theme(value):
1143 printNicely(red('Invalid theme\'s value.'))
1144 return
3c01ba57 1145 try:
a8c5fce4 1146 set_config(key, value)
ceec8593 1147 # Apply theme immediately
1148 if key == 'THEME':
baec5f50 1149 c['THEME'] = reload_theme(value, c['THEME'])
ceec8593 1150 g['decorated_name'] = lambda x: color_func(
a8e71259 1151 c['DECORATED_NAME'])('[' + x + ']: ')
1152 reload_config()
d6cc4c67 1153 printNicely(green('Updated successfully.'))
a8e71259 1154 except Exception as e:
1155 printNicely(red(e))
29fd0be6
O
1156 else:
1157 printNicely(light_magenta('Sorry I can\'s understand.'))
1158
1159
632c6fa5
O
1160def theme():
1161 """
1162 List and change theme
1163 """
1164 if not g['stuff']:
1165 # List themes
1166 for theme in g['themes']:
1f2f6159
O
1167 line = light_magenta(theme)
1168 if c['THEME'] == theme:
422dd385 1169 line = ' ' * 2 + light_yellow('* ') + line
ddb1e615 1170 else:
422dd385 1171 line = ' ' * 4 + line
632c6fa5
O
1172 printNicely(line)
1173 else:
1174 # Change theme
c075e6dc 1175 try:
ceec8593 1176 # Load new theme
baec5f50 1177 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
ceec8593 1178 # Redefine decorated_name
1179 g['decorated_name'] = lambda x: color_func(
c075e6dc 1180 c['DECORATED_NAME'])(
ceec8593 1181 '[' + x + ']: ')
632c6fa5 1182 printNicely(green('Theme changed.'))
8101275e 1183 except:
1f2f6159 1184 printNicely(red('No such theme exists.'))
632c6fa5
O
1185
1186
2d341029 1187def help_discover():
f405a7d0 1188 """
2d341029 1189 Discover the world
f405a7d0 1190 """
7e4ccbf3 1191 s = ' ' * 2
1f24a05a 1192 # Discover the world
2d341029 1193 usage = '\n'
8bc30efd 1194 usage += s + grey(u'\u266A' + ' Discover the world \n')
c075e6dc
O
1195 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1196 'You can try ' + light_green('trend US') + ' or ' + \
1197 light_green('trend JP Tokyo') + '.\n'
1198 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1199 light_green('home 7') + ' will show 7 tweets.\n'
1200 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1201 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1202 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
8bc30efd 1203 magenta('@mdo') + '.\n'
c075e6dc 1204 usage += s * 2 + light_green('view @mdo') + \
8bc30efd 1205 ' will show ' + magenta('@mdo') + '\'s home.\n'
03e08f86
O
1206 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1207 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1208 'Search can be performed with or without hashtag.\n'
2d341029
O
1209 printNicely(usage)
1210
8bc30efd 1211
2d341029
O
1212def help_tweets():
1213 """
1214 Tweets
1215 """
1216 s = ' ' * 2
1f24a05a 1217 # Tweet
2d341029 1218 usage = '\n'
8bc30efd 1219 usage += s + grey(u'\u266A' + ' Tweets \n')
c075e6dc
O
1220 usage += s * 2 + light_green('t oops ') + \
1221 'will tweet "' + light_yellow('oops') + '" immediately.\n'
7e4ccbf3 1222 usage += s * 2 + \
c075e6dc
O
1223 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1224 light_yellow('[id=12]') + '.\n'
1f24a05a 1225 usage += s * 2 + \
80b70d60
O
1226 light_green('quote 12 ') + ' will quote the tweet with ' + \
1227 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1228 'the quote will be canceled.\n'
1229 usage += s * 2 + \
c075e6dc
O
1230 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1231 light_yellow('[id=12]') + '.\n'
1232 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1233 light_yellow('oops') + '" to tweet with ' + \
1234 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1235 usage += s * 2 + \
c075e6dc
O
1236 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1237 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1238 usage += s * 2 + \
c075e6dc
O
1239 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1240 light_yellow('[id=12]') + '.\n'
8bc30efd 1241 usage += s * 2 + \
c075e6dc
O
1242 light_green('del 12 ') + ' will delete tweet with ' + \
1243 light_yellow('[id=12]') + '.\n'
1244 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1245 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
80b70d60
O
1246 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1247 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
2d341029 1248 printNicely(usage)
8bc30efd 1249
2d341029
O
1250
1251def help_messages():
1252 """
1253 Messages
1254 """
1255 s = ' ' * 2
5b2c4faf 1256 # Direct message
2d341029 1257 usage = '\n'
8bc30efd 1258 usage += s + grey(u'\u266A' + ' Direct messages \n')
c075e6dc
O
1259 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1260 light_green('inbox 7') + ' will show newest 7 messages.\n'
1261 usage += s * 2 + light_green('sent') + ' will show sent messages. ' + \
1262 light_green('sent 7') + ' will show newest 7 messages.\n'
1263 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
8bc30efd 1264 magenta('@dtvd88') + '.\n'
c075e6dc
O
1265 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1266 light_yellow('[message_id=5]') + '.\n'
2d341029 1267 printNicely(usage)
8bc30efd 1268
2d341029
O
1269
1270def help_friends_and_followers():
1271 """
1272 Friends and Followers
1273 """
1274 s = ' ' * 2
8bc30efd 1275 # Follower and following
2d341029 1276 usage = '\n'
cdccb0d6 1277 usage += s + grey(u'\u266A' + ' Friends and followers \n')
8bc30efd 1278 usage += s * 2 + \
c075e6dc 1279 light_green('ls fl') + \
8bc30efd 1280 ' will list all followers (people who are following you).\n'
1281 usage += s * 2 + \
c075e6dc 1282 light_green('ls fr') + \
8bc30efd 1283 ' will list all friends (people who you are following).\n'
c075e6dc 1284 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
305ce127 1285 magenta('@dtvd88') + '.\n'
c075e6dc 1286 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
305ce127 1287 magenta('@dtvd88') + '.\n'
c075e6dc 1288 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
5b2c4faf 1289 magenta('@dtvd88') + '.\n'
c075e6dc 1290 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
5b2c4faf 1291 magenta('@dtvd88') + '.\n'
c075e6dc
O
1292 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1293 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
305ce127 1294 magenta('@dtvd88') + '.\n'
c075e6dc 1295 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
305ce127 1296 magenta('@dtvd88') + '.\n'
c075e6dc 1297 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
305ce127 1298 magenta('@dtvd88') + ' as a spam account.\n'
2d341029
O
1299 printNicely(usage)
1300
1301
1302def help_list():
1303 """
1304 Lists
1305 """
1306 s = ' ' * 2
1307 # Twitter list
1308 usage = '\n'
1309 usage += s + grey(u'\u266A' + ' Twitter list\n')
1310 usage += s * 2 + light_green('list') + \
1311 ' will show all lists you are belong to.\n'
1312 usage += s * 2 + light_green('list home') + \
bef33491 1313 ' will show timeline of list. You will be asked for list\'s name.\n'
a65bd34c 1314 usage += s * 2 + light_green('list all_mem') + \
2d341029 1315 ' will show list\'s all members.\n'
a65bd34c 1316 usage += s * 2 + light_green('list all_sub') + \
2d341029 1317 ' will show list\'s all subscribers.\n'
422dd385
O
1318 usage += s * 2 + light_green('list add') + \
1319 ' will add specific person to a list owned by you.' + \
1320 ' You will be asked for list\'s name and person\'s name.\n'
2d341029
O
1321 usage += s * 2 + light_green('list rm') + \
1322 ' will remove specific person from a list owned by you.' + \
1323 ' You will be asked for list\'s name and person\'s name.\n'
422dd385
O
1324 usage += s * 2 + light_green('list sub') + \
1325 ' will subscribe you to a specific list.\n'
1326 usage += s * 2 + light_green('list unsub') + \
1327 ' will unsubscribe you from a specific list.\n'
1328 usage += s * 2 + light_green('list own') + \
1329 ' will show all list owned by you.\n'
1330 usage += s * 2 + light_green('list new') + \
1331 ' will create a new list.\n'
1332 usage += s * 2 + light_green('list update') + \
1333 ' will update a list owned by you.\n'
1334 usage += s * 2 + light_green('list del') + \
1335 ' will delete a list owned by you.\n'
2d341029 1336 printNicely(usage)
8bc30efd 1337
2d341029
O
1338
1339def help_stream():
1340 """
1341 Stream switch
1342 """
1343 s = ' ' * 2
8bc30efd 1344 # Switch
2d341029 1345 usage = '\n'
8bc30efd 1346 usage += s + grey(u'\u266A' + ' Switching streams \n')
c075e6dc 1347 usage += s * 2 + light_green('switch public #AKB') + \
48a25fe8 1348 ' will switch to public stream and follow "' + \
c075e6dc
O
1349 light_yellow('AKB') + '" keyword.\n'
1350 usage += s * 2 + light_green('switch mine') + \
48a25fe8 1351 ' will switch to your personal stream.\n'
c075e6dc 1352 usage += s * 2 + light_green('switch mine -f ') + \
48a25fe8 1353 ' will prompt to enter the filter.\n'
c075e6dc 1354 usage += s * 3 + light_yellow('Only nicks') + \
48a25fe8 1355 ' filter will decide nicks will be INCLUDE ONLY.\n'
c075e6dc 1356 usage += s * 3 + light_yellow('Ignore nicks') + \
48a25fe8 1357 ' filter will decide nicks will be EXCLUDE.\n'
c075e6dc 1358 usage += s * 2 + light_green('switch mine -d') + \
48a25fe8 1359 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
2d341029
O
1360 printNicely(usage)
1361
1362
1363def help():
1364 """
1365 Help
1366 """
1367 s = ' ' * 2
1368 h, w = os.popen('stty size', 'r').read().split()
2d341029
O
1369 # Start
1370 usage = '\n'
1371 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1372 usage += s + '-' * (int(w) - 4) + '\n'
1373 usage += s + 'You are ' + \
1374 light_yellow('already') + ' on your personal stream.\n'
1375 usage += s + 'Any update from Twitter will show up ' + \
1376 light_yellow('immediately') + '.\n'
1377 usage += s + 'In addtion, following commands are available right now:\n'
2d341029
O
1378 # Twitter help section
1379 usage += '\n'
1380 usage += s + grey(u'\u266A' + ' Twitter help\n')
1381 usage += s * 2 + light_green('h discover') + \
1382 ' will show help for discover commands.\n'
1383 usage += s * 2 + light_green('h tweets') + \
1384 ' will show help for tweets commands.\n'
1385 usage += s * 2 + light_green('h messages') + \
1386 ' will show help for messages commands.\n'
1387 usage += s * 2 + light_green('h friends_and_followers') + \
1388 ' will show help for friends and followers commands.\n'
1389 usage += s * 2 + light_green('h list') + \
1390 ' will show help for list commands.\n'
1391 usage += s * 2 + light_green('h stream') + \
1392 ' will show help for stream commands.\n'
1f24a05a 1393 # Smart shell
1394 usage += '\n'
1395 usage += s + grey(u'\u266A' + ' Smart shell\n')
c075e6dc 1396 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1f24a05a 1397 'will be evaluate by Python interpreter.\n'
c075e6dc 1398 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1f24a05a 1399 ' for current month.\n'
29fd0be6 1400 # Config
1f24a05a 1401 usage += '\n'
29fd0be6
O
1402 usage += s + grey(u'\u266A' + ' Config \n')
1403 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
c075e6dc 1404 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
632c6fa5 1405 ' theme immediately.\n'
29fd0be6
O
1406 usage += s * 2 + light_green('config') + ' will list all config.\n'
1407 usage += s * 3 + \
1408 light_green('config ASCII_ART') + ' will output current value of ' +\
a8c5fce4 1409 light_yellow('ASCII_ART') + ' config key.\n'
29fd0be6 1410 usage += s * 3 + \
fe9bb33b 1411 light_green('config TREND_MAX default') + ' will output default value of ' + \
1412 light_yellow('TREND_MAX') + ' config key.\n'
1413 usage += s * 3 + \
1414 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1415 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
29fd0be6 1416 usage += s * 3 + \
fe9bb33b 1417 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1418 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1419 light_yellow('True') + '.\n'
29fd0be6
O
1420 # Screening
1421 usage += '\n'
1422 usage += s + grey(u'\u266A' + ' Screening \n')
c075e6dc 1423 usage += s * 2 + light_green('h') + ' will show this help again.\n'
d6cc4c67
O
1424 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1425 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
c075e6dc
O
1426 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1427 usage += s * 2 + light_green('q') + ' will quit.\n'
8bc30efd 1428 # End
1429 usage += '\n'
7e4ccbf3 1430 usage += s + '-' * (int(w) - 4) + '\n'
8bc30efd 1431 usage += s + 'Have fun and hang tight! \n'
2d341029
O
1432 # Show help
1433 d = {
422dd385
O
1434 'discover': help_discover,
1435 'tweets': help_tweets,
1436 'messages': help_messages,
1437 'friends_and_followers': help_friends_and_followers,
1438 'list': help_list,
1439 'stream': help_stream,
2d341029
O
1440 }
1441 if g['stuff']:
baec5f50 1442 d.get(
1443 g['stuff'].strip(),
1444 lambda: printNicely(red('No such command.'))
3d48702f 1445 )()
2d341029
O
1446 else:
1447 printNicely(usage)
f405a7d0
O
1448
1449
d6cc4c67
O
1450def pause():
1451 """
1452 Pause stream display
1453 """
99b52f5f 1454 c['pause'] = True
d6cc4c67
O
1455 printNicely(green('Stream is paused'))
1456
1457
1458def replay():
1459 """
1460 Replay stream
1461 """
99b52f5f 1462 c['pause'] = False
d6cc4c67
O
1463 printNicely(green('Stream is running back now'))
1464
1465
843647ad 1466def clear():
f405a7d0 1467 """
7b674cef 1468 Clear screen
f405a7d0 1469 """
843647ad 1470 os.system('clear')
f405a7d0
O
1471
1472
843647ad 1473def quit():
b8dda704
O
1474 """
1475 Exit all
1476 """
4c025026 1477 try:
1478 save_history()
4c025026 1479 printNicely(green('See you next time :)'))
1480 except:
1481 pass
843647ad 1482 sys.exit()
b8dda704
O
1483
1484
94a5f62e 1485def reset():
f405a7d0 1486 """
94a5f62e 1487 Reset prefix of line
f405a7d0 1488 """
c91f75f2 1489 if g['reset']:
a8e71259 1490 if c.get('USER_JSON_ERROR'):
1491 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1492 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1493 printNicely('')
e3885f55 1494 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
c91f75f2 1495 g['reset'] = False
d0a726d6 1496 try:
2a0cabee
O
1497 printNicely(str(eval(g['cmd'])))
1498 except Exception:
d0a726d6 1499 pass
54277114
O
1500
1501
94a5f62e 1502def process(cmd):
54277114 1503 """
94a5f62e 1504 Process switch
54277114 1505 """
94a5f62e 1506 return dict(zip(
1507 cmdset,
b2b933a9 1508 [
42fde775 1509 switch,
4592d231 1510 trend,
b2b933a9 1511 home,
1512 view,
305ce127 1513 mentions,
b2b933a9 1514 tweet,
1515 retweet,
80b70d60 1516 quote,
1f24a05a 1517 allretweet,
7e4ccbf3 1518 favorite,
b2b933a9 1519 reply,
1520 delete,
7e4ccbf3 1521 unfavorite,
b2b933a9 1522 search,
305ce127 1523 message,
f5677fb1 1524 show,
80bb2040 1525 urlopen,
2d341029 1526 ls,
305ce127 1527 inbox,
1528 sent,
1529 trash,
e2b81717 1530 whois,
f5677fb1
O
1531 follow,
1532 unfollow,
5b2c4faf 1533 mute,
1534 unmute,
1535 muting,
305ce127 1536 block,
1537 unblock,
1538 report,
2d341029 1539 list,
813a5d80 1540 cal,
29fd0be6 1541 config,
632c6fa5 1542 theme,
b2b933a9 1543 help,
d6cc4c67
O
1544 pause,
1545 replay,
b2b933a9 1546 clear,
1547 quit
1548 ]
94a5f62e 1549 )).get(cmd, reset)
1550
1551
1552def listen():
42fde775 1553 """
1554 Listen to user's input
1555 """
d51b4107
O
1556 d = dict(zip(
1557 cmdset,
1558 [
affcb149 1559 ['public', 'mine'], # switch
4592d231 1560 [], # trend
7e4ccbf3 1561 [], # home
1562 ['@'], # view
305ce127 1563 [], # mentions
7e4ccbf3 1564 [], # tweet
1565 [], # retweet
80b70d60 1566 [], # quote
1f24a05a 1567 [], # allretweet
f5677fb1 1568 [], # favorite
7e4ccbf3 1569 [], # reply
1570 [], # delete
f5677fb1 1571 [], # unfavorite
7e4ccbf3 1572 ['#'], # search
305ce127 1573 ['@'], # message
f5677fb1 1574 ['image'], # show image
80b70d60 1575 [''], # open url
305ce127 1576 ['fl', 'fr'], # list
1577 [], # inbox
1578 [], # sent
1579 [], # trash
e2b81717 1580 ['@'], # whois
affcb149
O
1581 ['@'], # follow
1582 ['@'], # unfollow
5b2c4faf 1583 ['@'], # mute
1584 ['@'], # unmute
1585 ['@'], # muting
305ce127 1586 ['@'], # block
1587 ['@'], # unblock
1588 ['@'], # report
422dd385
O
1589 [
1590 'home',
1591 'all_mem',
1592 'all_sub',
1593 'add',
1594 'rm',
1595 'sub',
1596 'unsub',
1597 'own',
1598 'new',
1599 'update',
1600 'del'
1601 ], # list
813a5d80 1602 [], # cal
a8c5fce4 1603 [key for key in dict(get_all_config())], # config
ceec8593 1604 g['themes'], # theme
422dd385
O
1605 [
1606 'discover',
1607 'tweets',
1608 'messages',
1609 'friends_and_followers',
1610 'list',
1611 'stream'
1612 ], # help
d6cc4c67
O
1613 [], # pause
1614 [], # reconnect
7e4ccbf3 1615 [], # clear
1616 [], # quit
d51b4107 1617 ]
7e4ccbf3 1618 ))
d51b4107 1619 init_interactive_shell(d)
f5677fb1 1620 read_history()
819569e8 1621 reset()
b2b933a9 1622 while True:
99b52f5f 1623 # raw_input
1dd312f5 1624 if g['prefix']:
ceec8593 1625 line = raw_input(g['decorated_name'](c['PREFIX']))
1dd312f5
O
1626 else:
1627 line = raw_input()
4824b181
O
1628 # Save previous cmd in order to compare with readline buffer
1629 g['previous_cmd'] = line.strip()
843647ad
O
1630 try:
1631 cmd = line.split()[0]
1632 except:
1633 cmd = ''
d0a726d6 1634 g['cmd'] = cmd
b8c1f42a 1635 try:
9683e61d 1636 # Lock the semaphore
99b52f5f 1637 c['lock'] = True
9683e61d 1638 # Save cmd to global variable and call process
b8c1f42a 1639 g['stuff'] = ' '.join(line.split()[1:])
9683e61d 1640 # Process the command
b8c1f42a 1641 process(cmd)()
9683e61d 1642 # Not re-display
99b52f5f 1643 if cmd in ['switch', 't', 'rt', 'rep']:
9683e61d
O
1644 g['prefix'] = False
1645 else:
1646 g['prefix'] = True
1647 # Release the semaphore lock
99b52f5f 1648 c['lock'] = False
eadd85a8 1649 except Exception:
b8c1f42a 1650 printNicely(red('OMG something is wrong with Twitter right now.'))
54277114
O
1651
1652
42fde775 1653def stream(domain, args, name='Rainbow Stream'):
54277114 1654 """
f405a7d0 1655 Track the stream
54277114 1656 """
54277114 1657 # The Logo
42fde775 1658 art_dict = {
632c6fa5
O
1659 c['USER_DOMAIN']: name,
1660 c['PUBLIC_DOMAIN']: args.track_keywords,
1f2f6159 1661 c['SITE_DOMAIN']: name,
42fde775 1662 }
687567eb 1663 if c['ASCII_ART']:
c075e6dc 1664 ascii_art(art_dict[domain])
91476ec3
O
1665 # These arguments are optional:
1666 stream_args = dict(
335e7803 1667 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
a1222228 1668 block=not args.no_block,
91476ec3 1669 heartbeat_timeout=args.heartbeat_timeout)
91476ec3
O
1670 # Track keyword
1671 query_args = dict()
1672 if args.track_keywords:
1673 query_args['track'] = args.track_keywords
91476ec3 1674 # Get stream
2a6238f5 1675 stream = TwitterStream(
22be990e 1676 auth=authen(),
42fde775 1677 domain=domain,
2a6238f5 1678 **stream_args)
2a0cabee
O
1679 try:
1680 if domain == c['USER_DOMAIN']:
1681 tweet_iter = stream.user(**query_args)
1682 elif domain == c['SITE_DOMAIN']:
1683 tweet_iter = stream.site(**query_args)
42fde775 1684 else:
2a0cabee
O
1685 if args.track_keywords:
1686 tweet_iter = stream.statuses.filter(**query_args)
1687 else:
1688 tweet_iter = stream.statuses.sample()
92983945
BS
1689 # Block new stream until other one exits
1690 StreamLock.acquire()
1691 g['stream_stop'] = False
72c02928
VNM
1692 for tweet in tweet_iter:
1693 if tweet is None:
a1222228 1694 printNicely("-- None --")
72c02928 1695 elif tweet is Timeout:
335e7803
O
1696 if(g['stream_stop']):
1697 StreamLock.release()
1698 break
72c02928
VNM
1699 elif tweet is HeartbeatTimeout:
1700 printNicely("-- Heartbeat Timeout --")
1701 elif tweet is Hangup:
1702 printNicely("-- Hangup --")
1703 elif tweet.get('text'):
1704 draw(
1705 t=tweet,
72c02928 1706 keyword=args.track_keywords,
9683e61d 1707 check_semaphore=True,
72c02928
VNM
1708 fil=args.filter,
1709 ig=args.ignore,
1710 )
4824b181
O
1711 # Current readline buffer
1712 current_buffer = readline.get_line_buffer().strip()
335e7803 1713 # There is an unexpected behaviour in MacOSX readline + Python 2:
3d48702f
O
1714 # after completely delete a word after typing it,
1715 # somehow readline buffer still contains
1716 # the 1st character of that word
335e7803 1717 if current_buffer and g['previous_cmd'] != current_buffer:
3d48702f
O
1718 sys.stdout.write(
1719 g['decorated_name'](c['PREFIX']) + current_buffer)
4824b181 1720 sys.stdout.flush()
335e7803
O
1721 elif not c['HIDE_PROMPT']:
1722 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1723 sys.stdout.flush()
14db58c7 1724 elif tweet.get('direct_message'):
8141aca6 1725 print_message(tweet['direct_message'], check_semaphore=True)
2a0cabee
O
1726 except TwitterHTTPError:
1727 printNicely('')
c075e6dc 1728 printNicely(
2a0cabee 1729 magenta("We have maximum connection problem with twitter'stream API right now :("))
54277114
O
1730
1731
1732def fly():
1733 """
1734 Main function
1735 """
531f5682 1736 # Initial
42fde775 1737 args = parse_arguments()
2a0cabee 1738 try:
fe9bb33b 1739 init(args)
2a0cabee
O
1740 except TwitterHTTPError:
1741 printNicely('')
1742 printNicely(
4c025026 1743 magenta("We have maximum connection problem with twitter'stream API right now :("))
1744 printNicely(magenta("Let's try again later."))
2a0cabee 1745 save_history()
2a0cabee 1746 sys.exit()
92983945 1747 # Spawn stream thread
baec5f50 1748 th = threading.Thread(
1749 target=stream,
1750 args=(
1751 c['USER_DOMAIN'],
1752 args,
1753 g['original_name']))
92983945
BS
1754 th.daemon = True
1755 th.start()
42fde775 1756 # Start listen process
819569e8 1757 time.sleep(0.5)
c91f75f2 1758 g['reset'] = True
1dd312f5 1759 g['prefix'] = True
0f6e4daf 1760 listen()