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