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