final version
[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
O
124 set_config('PREFIX', screen_name)
125 g['original_name'] = screen_name[1:]
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)
422dd385
O
464 link_ary = [
465 u for u in tweet['text'].split() if u.startswith('http://')]
80b70d60
O
466 if not link_ary:
467 printNicely(light_magenta('No url here @.@!'))
468 return
469 for link in link_ary:
470 webbrowser.open(link)
471 except:
472 printNicely(red('Sorry I can\'t open url in this tweet.'))
473
474
305ce127 475def inbox():
476 """
67c663f8 477 Inbox threads
305ce127 478 """
479 t = Twitter(auth=authen())
632c6fa5 480 num = c['MESSAGES_DISPLAY']
305ce127 481 if g['stuff'].isdigit():
482 num = g['stuff']
67c663f8 483 # Get inbox messages
305ce127 484 cur_page = 1
67c663f8 485 inbox = []
305ce127 486 while num > 20:
67c663f8 487 inbox = inbox + t.direct_messages(
305ce127 488 count=20,
489 page=cur_page,
490 include_entities=False,
491 skip_status=False
48a25fe8 492 )
305ce127 493 num -= 20
494 cur_page += 1
67c663f8 495 inbox = inbox + t.direct_messages(
305ce127 496 count=num,
497 page=cur_page,
498 include_entities=False,
499 skip_status=False
48a25fe8 500 )
67c663f8 501 # Get sent messages
632c6fa5 502 num = c['MESSAGES_DISPLAY']
305ce127 503 if g['stuff'].isdigit():
67c663f8 504 num = g['stuff']
305ce127 505 cur_page = 1
67c663f8 506 sent = []
305ce127 507 while num > 20:
67c663f8 508 sent = sent + t.direct_messages.sent(
305ce127 509 count=20,
510 page=cur_page,
511 include_entities=False,
512 skip_status=False
48a25fe8 513 )
305ce127 514 num -= 20
515 cur_page += 1
67c663f8 516 sent = sent + t.direct_messages.sent(
305ce127 517 count=num,
518 page=cur_page,
519 include_entities=False,
520 skip_status=False
48a25fe8 521 )
67c663f8
O
522
523 d = {}
524 uniq_inbox = list(set(
03c0d30b 525 [(m['sender_screen_name'], m['sender']['name']) for m in inbox]
67c663f8 526 ))
03c0d30b 527 uniq_sent = list(set(
528 [(m['recipient_screen_name'], m['recipient']['name']) for m in sent]
67c663f8
O
529 ))
530 for partner in uniq_inbox:
531 inbox_ary = [m for m in inbox if m['sender_screen_name'] == partner[0]]
03c0d30b 532 sent_ary = [
533 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
534 d[partner] = inbox_ary + sent_ary
535 for partner in uniq_sent:
536 if partner not in d:
03c0d30b 537 d[partner] = [
538 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
539 g['message_threads'] = print_threads(d)
540
541
542def thread():
543 """
544 View a thread of message
545 """
546 try:
547 thread_id = int(g['stuff'])
03c0d30b 548 print_thread(
549 g['message_threads'][thread_id],
550 g['original_name'],
551 g['full_name'])
552 except Exception:
67c663f8 553 printNicely(red('No such thread.'))
e2b81717 554
305ce127 555
fd87ddac
O
556def message():
557 """
558 Send a direct message
559 """
560 t = Twitter(auth=authen())
03c0d30b 561 try:
562 user = g['stuff'].split()[0]
563 if user[0].startswith('@'):
564 content = ' '.join(g['stuff'].split()[1:])
565 t.direct_messages.new(
566 screen_name=user[1:],
567 text=content
568 )
569 printNicely(green('Message sent.'))
570 else:
571 printNicely(red('A name should begin with a \'@\''))
572 except:
573 printNicely(red('Sorry I can\'t understand.'))
fd87ddac
O
574
575
305ce127 576def trash():
577 """
578 Remove message
579 """
580 t = Twitter(auth=authen())
581 try:
99b52f5f 582 id = int(g['stuff'].split()[0])
305ce127 583 except:
584 printNicely(red('Sorry I can\'t understand.'))
99b52f5f 585 mid = c['message_dict'][id]
b8c1f42a
O
586 t.direct_messages.destroy(id=mid)
587 printNicely(green('Message deleted.'))
305ce127 588
589
fd87ddac 590def ls():
e2b81717 591 """
fd87ddac 592 List friends for followers
e2b81717
O
593 """
594 t = Twitter(auth=authen())
fd87ddac
O
595 # Get name
596 try:
597 name = g['stuff'].split()[1]
598 if name.startswith('@'):
599 name = name[1:]
600 else:
601 printNicely(red('A name should begin with a \'@\''))
602 raise Exception('Invalid name')
603 except:
604 name = g['original_name']
605 # Get list followers or friends
606 try:
607 target = g['stuff'].split()[0]
608 except:
609 printNicely(red('Omg some syntax is wrong.'))
610 # Init cursor
611 d = {'fl': 'followers', 'fr': 'friends'}
612 next_cursor = -1
613 rel = {}
614 # Cursor loop
615 while next_cursor != 0:
616 list = getattr(t, d[target]).list(
617 screen_name=name,
618 cursor=next_cursor,
619 skip_status=True,
620 include_entities=False,
621 )
622 for u in list['users']:
623 rel[u['name']] = '@' + u['screen_name']
624 next_cursor = list['next_cursor']
625 # Print out result
626 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
627 for name in rel:
628 user = ' ' + cycle_color(name)
629 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
630 printNicely(user)
e2b81717
O
631
632
f5677fb1 633def follow():
843647ad 634 """
f5677fb1 635 Follow a user
843647ad
O
636 """
637 t = Twitter(auth=authen())
f5677fb1 638 screen_name = g['stuff'].split()[0]
b8c1f42a
O
639 if screen_name.startswith('@'):
640 t.friendships.create(screen_name=screen_name[1:], follow=True)
641 printNicely(green('You are following ' + screen_name + ' now!'))
f5677fb1 642 else:
b8c1f42a 643 printNicely(red('A name should begin with a \'@\''))
f5677fb1
O
644
645
646def unfollow():
647 """
648 Unfollow a user
649 """
650 t = Twitter(auth=authen())
651 screen_name = g['stuff'].split()[0]
b8c1f42a
O
652 if screen_name.startswith('@'):
653 t.friendships.destroy(
654 screen_name=screen_name[1:],
655 include_entities=False)
656 printNicely(green('Unfollow ' + screen_name + ' success!'))
f5677fb1 657 else:
b8c1f42a 658 printNicely(red('A name should begin with a \'@\''))
843647ad
O
659
660
5b2c4faf 661def mute():
662 """
663 Mute a user
664 """
665 t = Twitter(auth=authen())
666 try:
667 screen_name = g['stuff'].split()[0]
668 except:
669 printNicely(red('A name should be specified. '))
670 return
671 if screen_name.startswith('@'):
e3927852
O
672 try:
673 rel = t.mutes.users.create(screen_name=screen_name[1:])
674 if isinstance(rel, dict):
675 printNicely(green(screen_name + ' is muted.'))
612d6863 676 c['IGNORE_LIST'] += [unc(screen_name)]
e3927852
O
677 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
678 else:
679 printNicely(red(rel))
680 except:
681 printNicely(red('Something is wrong, can not mute now :('))
5b2c4faf 682 else:
683 printNicely(red('A name should begin with a \'@\''))
684
685
686def unmute():
687 """
688 Unmute a user
689 """
690 t = Twitter(auth=authen())
691 try:
692 screen_name = g['stuff'].split()[0]
693 except:
694 printNicely(red('A name should be specified. '))
695 return
696 if screen_name.startswith('@'):
e3927852
O
697 try:
698 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
699 if isinstance(rel, dict):
700 printNicely(green(screen_name + ' is unmuted.'))
701 c['IGNORE_LIST'].remove(screen_name)
702 else:
703 printNicely(red(rel))
704 except:
705 printNicely(red('Maybe you are not muting this person ?'))
5b2c4faf 706 else:
707 printNicely(red('A name should begin with a \'@\''))
708
709
710def muting():
711 """
712 List muting user
713 """
e3927852
O
714 # Get dict of muting users
715 md = build_mute_dict(dict_data=True)
716 printNicely('All: ' + str(len(md)) + ' people.')
717 for name in md:
718 user = ' ' + cycle_color(md[name])
719 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
5b2c4faf 720 printNicely(user)
e3927852
O
721 # Update from Twitter
722 c['IGNORE_LIST'] = [n for n in md]
5b2c4faf 723
724
305ce127 725def block():
726 """
727 Block a user
728 """
729 t = Twitter(auth=authen())
730 screen_name = g['stuff'].split()[0]
b8c1f42a
O
731 if screen_name.startswith('@'):
732 t.blocks.create(
5b2c4faf 733 screen_name=screen_name[1:],
734 include_entities=False,
735 skip_status=True)
b8c1f42a 736 printNicely(green('You blocked ' + screen_name + '.'))
305ce127 737 else:
b8c1f42a 738 printNicely(red('A name should begin with a \'@\''))
305ce127 739
740
741def unblock():
742 """
743 Unblock a user
744 """
745 t = Twitter(auth=authen())
746 screen_name = g['stuff'].split()[0]
b8c1f42a
O
747 if screen_name.startswith('@'):
748 t.blocks.destroy(
749 screen_name=screen_name[1:],
750 include_entities=False,
751 skip_status=True)
752 printNicely(green('Unblock ' + screen_name + ' success!'))
305ce127 753 else:
b8c1f42a 754 printNicely(red('A name should begin with a \'@\''))
305ce127 755
756
757def report():
758 """
759 Report a user as a spam account
760 """
761 t = Twitter(auth=authen())
762 screen_name = g['stuff'].split()[0]
b8c1f42a
O
763 if screen_name.startswith('@'):
764 t.users.report_spam(
765 screen_name=screen_name[1:])
766 printNicely(green('You reported ' + screen_name + '.'))
305ce127 767 else:
768 printNicely(red('Sorry I can\'t understand.'))
769
770
8b8566d1
O
771def get_slug():
772 """
773 Get Slug Decorator
774 """
a8c5fce4 775 # Get list name
8b8566d1
O
776 list_name = raw_input(light_magenta('Give me the list\'s name: '))
777 # Get list name and owner
778 try:
779 owner, slug = list_name.split('/')
780 if slug.startswith('@'):
781 slug = slug[1:]
782 return owner, slug
783 except:
a8c5fce4
O
784 printNicely(
785 light_magenta('List name should follow "@owner/list_name" format.'))
8b8566d1
O
786 raise Exception('Wrong list name')
787
788
2d341029
O
789def show_lists(t):
790 """
422dd385 791 List list
2d341029
O
792 """
793 rel = t.lists.list(screen_name=g['original_name'])
794 if rel:
795 print_list(rel)
796 else:
797 printNicely(light_magenta('You belong to no lists :)'))
798
799
800def list_home(t):
801 """
802 List home
803 """
8b8566d1 804 owner, slug = get_slug()
2d341029 805 res = t.lists.statuses(
422dd385
O
806 slug=slug,
807 owner_screen_name=owner,
808 count=c['LIST_MAX'],
2d341029
O
809 include_entities=False)
810 for tweet in res:
811 draw(t=tweet)
812 printNicely('')
813
814
815def list_members(t):
816 """
817 List members
818 """
8b8566d1 819 owner, slug = get_slug()
422dd385 820 # Get members
2d341029
O
821 rel = {}
822 next_cursor = -1
422dd385 823 while next_cursor != 0:
2d341029 824 m = t.lists.members(
422dd385
O
825 slug=slug,
826 owner_screen_name=owner,
827 cursor=next_cursor,
2d341029
O
828 include_entities=False)
829 for u in m['users']:
830 rel[u['name']] = '@' + u['screen_name']
831 next_cursor = m['next_cursor']
832 printNicely('All: ' + str(len(rel)) + ' members.')
833 for name in rel:
834 user = ' ' + cycle_color(name)
422dd385 835 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
836 printNicely(user)
837
838
839def list_subscribers(t):
840 """
841 List subscribers
842 """
8b8566d1 843 owner, slug = get_slug()
422dd385 844 # Get subscribers
2d341029
O
845 rel = {}
846 next_cursor = -1
422dd385 847 while next_cursor != 0:
2d341029 848 m = t.lists.subscribers(
422dd385
O
849 slug=slug,
850 owner_screen_name=owner,
851 cursor=next_cursor,
2d341029
O
852 include_entities=False)
853 for u in m['users']:
854 rel[u['name']] = '@' + u['screen_name']
855 next_cursor = m['next_cursor']
856 printNicely('All: ' + str(len(rel)) + ' subscribers.')
857 for name in rel:
858 user = ' ' + cycle_color(name)
422dd385 859 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
860 printNicely(user)
861
862
422dd385
O
863def list_add(t):
864 """
865 Add specific user to a list
866 """
8b8566d1 867 owner, slug = get_slug()
422dd385
O
868 # Add
869 user_name = raw_input(light_magenta('Give me name of the newbie: '))
870 if user_name.startswith('@'):
871 user_name = user_name[1:]
872 try:
873 t.lists.members.create(
874 slug=slug,
875 owner_screen_name=owner,
876 screen_name=user_name)
d6cc4c67 877 printNicely(green('Added.'))
422dd385
O
878 except:
879 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
880
881
2d341029
O
882def list_remove(t):
883 """
884 Remove specific user from a list
885 """
8b8566d1 886 owner, slug = get_slug()
2d341029 887 # Remove
422dd385
O
888 user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
889 if user_name.startswith('@'):
890 user_name = user_name[1:]
2d341029
O
891 try:
892 t.lists.members.destroy(
422dd385
O
893 slug=slug,
894 owner_screen_name=owner,
895 screen_name=user_name)
d6cc4c67 896 printNicely(green('Gone.'))
422dd385
O
897 except:
898 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
899
900
901def list_subscribe(t):
902 """
903 Subscribe to a list
904 """
8b8566d1 905 owner, slug = get_slug()
422dd385
O
906 # Subscribe
907 try:
908 t.lists.subscribers.create(
909 slug=slug,
910 owner_screen_name=owner)
d6cc4c67 911 printNicely(green('Done.'))
422dd385
O
912 except:
913 printNicely(
914 light_magenta('I\'m sorry you can not subscribe to this list.'))
915
916
917def list_unsubscribe(t):
918 """
919 Unsubscribe a list
920 """
8b8566d1 921 owner, slug = get_slug()
422dd385
O
922 # Subscribe
923 try:
924 t.lists.subscribers.destroy(
925 slug=slug,
926 owner_screen_name=owner)
d6cc4c67 927 printNicely(green('Done.'))
422dd385
O
928 except:
929 printNicely(
930 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
931
932
933def list_own(t):
934 """
935 List own
936 """
937 rel = []
938 next_cursor = -1
939 while next_cursor != 0:
940 res = t.lists.ownerships(
941 screen_name=g['original_name'],
942 cursor=next_cursor)
943 rel += res['lists']
944 next_cursor = res['next_cursor']
945 if rel:
946 print_list(rel)
947 else:
948 printNicely(light_magenta('You own no lists :)'))
949
950
951def list_new(t):
952 """
953 Create a new list
954 """
955 name = raw_input(light_magenta('New list\'s name: '))
956 mode = raw_input(light_magenta('New list\'s mode (public/private): '))
957 description = raw_input(light_magenta('New list\'s description: '))
958 try:
959 t.lists.create(
960 name=name,
961 mode=mode,
962 description=description)
d6cc4c67 963 printNicely(green(name + ' list is created.'))
422dd385
O
964 except:
965 printNicely(red('Oops something is wrong with Twitter :('))
966
967
968def list_update(t):
969 """
970 Update a list
971 """
972 slug = raw_input(light_magenta('Your list that you want to update: '))
973 name = raw_input(light_magenta('Update name (leave blank to unchange): '))
974 mode = raw_input(light_magenta('Update mode (public/private): '))
975 description = raw_input(light_magenta('Update description: '))
976 try:
977 if name:
978 t.lists.update(
979 slug='-'.join(slug.split()),
980 owner_screen_name=g['original_name'],
981 name=name,
982 mode=mode,
983 description=description)
984 else:
985 t.lists.update(
986 slug=slug,
987 owner_screen_name=g['original_name'],
988 mode=mode,
989 description=description)
d6cc4c67 990 printNicely(green(slug + ' list is updated.'))
3c85d8fc 991 except:
422dd385
O
992 printNicely(red('Oops something is wrong with Twitter :('))
993
994
995def list_delete(t):
996 """
997 Delete a list
998 """
8b3456f9 999 slug = raw_input(light_magenta('Your list that you want to delete: '))
422dd385
O
1000 try:
1001 t.lists.destroy(
1002 slug='-'.join(slug.split()),
1003 owner_screen_name=g['original_name'])
d6cc4c67 1004 printNicely(green(slug + ' list is deleted.'))
2d341029 1005 except:
422dd385 1006 printNicely(red('Oops something is wrong with Twitter :('))
2d341029
O
1007
1008
e3927852 1009def twitterlist():
2d341029
O
1010 """
1011 Twitter's list
1012 """
1013 t = Twitter(auth=authen())
1014 # List all lists or base on action
1015 try:
1016 g['list_action'] = g['stuff'].split()[0]
1017 except:
1018 show_lists(t)
1019 return
422dd385 1020 # Sub-function
2d341029
O
1021 action_ary = {
1022 'home': list_home,
1023 'all_mem': list_members,
1024 'all_sub': list_subscribers,
422dd385 1025 'add': list_add,
2d341029 1026 'rm': list_remove,
422dd385
O
1027 'sub': list_subscribe,
1028 'unsub': list_unsubscribe,
1029 'own': list_own,
1030 'new': list_new,
1031 'update': list_update,
1032 'del': list_delete,
2d341029
O
1033 }
1034 try:
1035 return action_ary[g['list_action']](t)
3c85d8fc 1036 except:
8b8566d1 1037 printNicely(red('Please try again.'))
2d341029
O
1038
1039
fd87ddac
O
1040def switch():
1041 """
1042 Switch stream
1043 """
1044 try:
1045 target = g['stuff'].split()[0]
1046 # Filter and ignore
1047 args = parse_arguments()
1048 try:
1049 if g['stuff'].split()[-1] == '-f':
1050 guide = 'To ignore an option, just hit Enter key.'
1051 printNicely(light_magenta(guide))
1052 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
1053 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1054 args.filter = filter(None, only.split(','))
1055 args.ignore = filter(None, ignore.split(','))
1056 elif g['stuff'].split()[-1] == '-d':
1057 args.filter = c['ONLY_LIST']
1058 args.ignore = c['IGNORE_LIST']
1059 except:
1060 printNicely(red('Sorry, wrong format.'))
1061 return
1062 # Public stream
1063 if target == 'public':
1064 keyword = g['stuff'].split()[1]
1065 if keyword[0] == '#':
1066 keyword = keyword[1:]
1067 # Kill old thread
1068 g['stream_stop'] = True
1069 args.track_keywords = keyword
1070 # Start new thread
1071 th = threading.Thread(
1072 target=stream,
1073 args=(
1074 c['PUBLIC_DOMAIN'],
1075 args))
1076 th.daemon = True
1077 th.start()
1078 # Personal stream
1079 elif target == 'mine':
1080 # Kill old thread
1081 g['stream_stop'] = True
1082 # Start new thread
1083 th = threading.Thread(
1084 target=stream,
1085 args=(
1086 c['USER_DOMAIN'],
1087 args,
1088 g['original_name']))
1089 th.daemon = True
1090 th.start()
1091 printNicely('')
1092 if args.filter:
1093 printNicely(cyan('Only: ' + str(args.filter)))
1094 if args.ignore:
1095 printNicely(red('Ignore: ' + str(args.ignore)))
1096 printNicely('')
1097 except:
1098 printNicely(red('Sorry I can\'t understand.'))
1099
1100
813a5d80 1101def cal():
1102 """
1103 Unix's command `cal`
1104 """
1105 # Format
1106 rel = os.popen('cal').read().split('\n')
1107 month = rel.pop(0)
813a5d80 1108 date = rel.pop(0)
2a0cabee 1109 show_calendar(month, date, rel)
813a5d80 1110
1111
fd87ddac
O
1112def theme():
1113 """
1114 List and change theme
1115 """
1116 if not g['stuff']:
1117 # List themes
1118 for theme in g['themes']:
1119 line = light_magenta(theme)
1120 if c['THEME'] == theme:
1121 line = ' ' * 2 + light_yellow('* ') + line
1122 else:
1123 line = ' ' * 4 + line
1124 printNicely(line)
1125 else:
1126 # Change theme
1127 try:
1128 # Load new theme
1129 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1130 # Redefine decorated_name
1131 g['decorated_name'] = lambda x: color_func(
1132 c['DECORATED_NAME'])(
1133 '[' + x + ']: ')
1134 printNicely(green('Theme changed.'))
1135 except:
1136 printNicely(red('No such theme exists.'))
1137
1138
29fd0be6
O
1139def config():
1140 """
1141 Browse and change config
1142 """
1143 all_config = get_all_config()
1144 g['stuff'] = g['stuff'].strip()
1145 # List all config
1146 if not g['stuff']:
1147 for k in all_config:
a8c5fce4 1148 line = ' ' * 2 + \
d6cc4c67 1149 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1150 printNicely(line)
1151 guide = 'Detailed explanation can be found at ' + \
a8c5fce4
O
1152 color_func(c['TWEET']['link'])(
1153 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
29fd0be6
O
1154 printNicely(guide)
1155 # Print specific config
1156 elif len(g['stuff'].split()) == 1:
1157 if g['stuff'] in all_config:
1158 k = g['stuff']
a8c5fce4 1159 line = ' ' * 2 + \
d6cc4c67 1160 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1161 printNicely(line)
1162 else:
fe9bb33b 1163 printNicely(red('No such config key.'))
29fd0be6
O
1164 # Print specific config's default value
1165 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1166 key = g['stuff'].split()[0]
fe9bb33b 1167 try:
1168 value = get_default_config(key)
d6cc4c67 1169 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
fe9bb33b 1170 printNicely(line)
a8e71259 1171 except Exception as e:
1172 printNicely(red(e))
fe9bb33b 1173 # Delete specific config key in config file
1174 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1175 key = g['stuff'].split()[0]
1176 try:
1177 delete_config(key)
d6cc4c67 1178 printNicely(green('Config key is dropped.'))
a8e71259 1179 except Exception as e:
1180 printNicely(red(e))
29fd0be6 1181 # Set specific config
a8c5fce4 1182 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
29fd0be6
O
1183 key = g['stuff'].split()[0]
1184 value = g['stuff'].split()[-1]
ceec8593 1185 if key == 'THEME' and not validate_theme(value):
1186 printNicely(red('Invalid theme\'s value.'))
1187 return
3c01ba57 1188 try:
a8c5fce4 1189 set_config(key, value)
ceec8593 1190 # Apply theme immediately
1191 if key == 'THEME':
baec5f50 1192 c['THEME'] = reload_theme(value, c['THEME'])
ceec8593 1193 g['decorated_name'] = lambda x: color_func(
a8e71259 1194 c['DECORATED_NAME'])('[' + x + ']: ')
1195 reload_config()
d6cc4c67 1196 printNicely(green('Updated successfully.'))
a8e71259 1197 except Exception as e:
1198 printNicely(red(e))
29fd0be6
O
1199 else:
1200 printNicely(light_magenta('Sorry I can\'s understand.'))
1201
1202
2d341029 1203def help_discover():
f405a7d0 1204 """
2d341029 1205 Discover the world
f405a7d0 1206 """
7e4ccbf3 1207 s = ' ' * 2
1f24a05a 1208 # Discover the world
2d341029 1209 usage = '\n'
8bc30efd 1210 usage += s + grey(u'\u266A' + ' Discover the world \n')
c075e6dc
O
1211 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1212 'You can try ' + light_green('trend US') + ' or ' + \
1213 light_green('trend JP Tokyo') + '.\n'
1214 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1215 light_green('home 7') + ' will show 7 tweets.\n'
1216 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1217 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1218 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
8bc30efd 1219 magenta('@mdo') + '.\n'
c075e6dc 1220 usage += s * 2 + light_green('view @mdo') + \
8bc30efd 1221 ' will show ' + magenta('@mdo') + '\'s home.\n'
03e08f86
O
1222 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1223 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1224 'Search can be performed with or without hashtag.\n'
2d341029
O
1225 printNicely(usage)
1226
8bc30efd 1227
2d341029
O
1228def help_tweets():
1229 """
1230 Tweets
1231 """
1232 s = ' ' * 2
1f24a05a 1233 # Tweet
2d341029 1234 usage = '\n'
8bc30efd 1235 usage += s + grey(u'\u266A' + ' Tweets \n')
c075e6dc
O
1236 usage += s * 2 + light_green('t oops ') + \
1237 'will tweet "' + light_yellow('oops') + '" immediately.\n'
7e4ccbf3 1238 usage += s * 2 + \
c075e6dc
O
1239 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1240 light_yellow('[id=12]') + '.\n'
1f24a05a 1241 usage += s * 2 + \
80b70d60
O
1242 light_green('quote 12 ') + ' will quote the tweet with ' + \
1243 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1244 'the quote will be canceled.\n'
1245 usage += s * 2 + \
c075e6dc
O
1246 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1247 light_yellow('[id=12]') + '.\n'
fd87ddac
O
1248 usage += s * 2 + light_green('conversation 12') + ' will show the chain of ' + \
1249 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
c075e6dc
O
1250 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1251 light_yellow('oops') + '" to tweet with ' + \
1252 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1253 usage += s * 2 + \
c075e6dc
O
1254 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1255 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1256 usage += s * 2 + \
c075e6dc
O
1257 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1258 light_yellow('[id=12]') + '.\n'
8bc30efd 1259 usage += s * 2 + \
c075e6dc
O
1260 light_green('del 12 ') + ' will delete tweet with ' + \
1261 light_yellow('[id=12]') + '.\n'
1262 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1263 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
80b70d60
O
1264 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1265 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
2d341029 1266 printNicely(usage)
8bc30efd 1267
2d341029
O
1268
1269def help_messages():
1270 """
1271 Messages
1272 """
1273 s = ' ' * 2
5b2c4faf 1274 # Direct message
2d341029 1275 usage = '\n'
8bc30efd 1276 usage += s + grey(u'\u266A' + ' Direct messages \n')
c075e6dc
O
1277 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1278 light_green('inbox 7') + ' will show newest 7 messages.\n'
03c0d30b 1279 usage += s * 2 + light_green('thread 2') + ' will show full thread with ' + \
1280 light_yellow('[thread_id=2]') + '.\n'
c075e6dc 1281 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
8bc30efd 1282 magenta('@dtvd88') + '.\n'
c075e6dc
O
1283 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1284 light_yellow('[message_id=5]') + '.\n'
2d341029 1285 printNicely(usage)
8bc30efd 1286
2d341029
O
1287
1288def help_friends_and_followers():
1289 """
1290 Friends and Followers
1291 """
1292 s = ' ' * 2
8bc30efd 1293 # Follower and following
2d341029 1294 usage = '\n'
cdccb0d6 1295 usage += s + grey(u'\u266A' + ' Friends and followers \n')
8bc30efd 1296 usage += s * 2 + \
c075e6dc 1297 light_green('ls fl') + \
8bc30efd 1298 ' will list all followers (people who are following you).\n'
1299 usage += s * 2 + \
c075e6dc 1300 light_green('ls fr') + \
8bc30efd 1301 ' will list all friends (people who you are following).\n'
c075e6dc 1302 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
305ce127 1303 magenta('@dtvd88') + '.\n'
c075e6dc 1304 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
305ce127 1305 magenta('@dtvd88') + '.\n'
c075e6dc 1306 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
5b2c4faf 1307 magenta('@dtvd88') + '.\n'
c075e6dc 1308 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
5b2c4faf 1309 magenta('@dtvd88') + '.\n'
c075e6dc
O
1310 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1311 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
305ce127 1312 magenta('@dtvd88') + '.\n'
c075e6dc 1313 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
305ce127 1314 magenta('@dtvd88') + '.\n'
c075e6dc 1315 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
305ce127 1316 magenta('@dtvd88') + ' as a spam account.\n'
2d341029
O
1317 printNicely(usage)
1318
1319
1320def help_list():
1321 """
1322 Lists
1323 """
1324 s = ' ' * 2
1325 # Twitter list
1326 usage = '\n'
1327 usage += s + grey(u'\u266A' + ' Twitter list\n')
1328 usage += s * 2 + light_green('list') + \
1329 ' will show all lists you are belong to.\n'
1330 usage += s * 2 + light_green('list home') + \
bef33491 1331 ' will show timeline of list. You will be asked for list\'s name.\n'
a65bd34c 1332 usage += s * 2 + light_green('list all_mem') + \
2d341029 1333 ' will show list\'s all members.\n'
a65bd34c 1334 usage += s * 2 + light_green('list all_sub') + \
2d341029 1335 ' will show list\'s all subscribers.\n'
422dd385
O
1336 usage += s * 2 + light_green('list add') + \
1337 ' will add specific person to a list owned by you.' + \
1338 ' You will be asked for list\'s name and person\'s name.\n'
2d341029
O
1339 usage += s * 2 + light_green('list rm') + \
1340 ' will remove specific person from a list owned by you.' + \
1341 ' You will be asked for list\'s name and person\'s name.\n'
422dd385
O
1342 usage += s * 2 + light_green('list sub') + \
1343 ' will subscribe you to a specific list.\n'
1344 usage += s * 2 + light_green('list unsub') + \
1345 ' will unsubscribe you from a specific list.\n'
1346 usage += s * 2 + light_green('list own') + \
1347 ' will show all list owned by you.\n'
1348 usage += s * 2 + light_green('list new') + \
1349 ' will create a new list.\n'
1350 usage += s * 2 + light_green('list update') + \
1351 ' will update a list owned by you.\n'
1352 usage += s * 2 + light_green('list del') + \
1353 ' will delete a list owned by you.\n'
2d341029 1354 printNicely(usage)
8bc30efd 1355
2d341029
O
1356
1357def help_stream():
1358 """
1359 Stream switch
1360 """
1361 s = ' ' * 2
8bc30efd 1362 # Switch
2d341029 1363 usage = '\n'
8bc30efd 1364 usage += s + grey(u'\u266A' + ' Switching streams \n')
c075e6dc 1365 usage += s * 2 + light_green('switch public #AKB') + \
48a25fe8 1366 ' will switch to public stream and follow "' + \
c075e6dc
O
1367 light_yellow('AKB') + '" keyword.\n'
1368 usage += s * 2 + light_green('switch mine') + \
48a25fe8 1369 ' will switch to your personal stream.\n'
c075e6dc 1370 usage += s * 2 + light_green('switch mine -f ') + \
48a25fe8 1371 ' will prompt to enter the filter.\n'
c075e6dc 1372 usage += s * 3 + light_yellow('Only nicks') + \
48a25fe8 1373 ' filter will decide nicks will be INCLUDE ONLY.\n'
c075e6dc 1374 usage += s * 3 + light_yellow('Ignore nicks') + \
48a25fe8 1375 ' filter will decide nicks will be EXCLUDE.\n'
c075e6dc 1376 usage += s * 2 + light_green('switch mine -d') + \
48a25fe8 1377 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
2d341029
O
1378 printNicely(usage)
1379
1380
1381def help():
1382 """
1383 Help
1384 """
1385 s = ' ' * 2
1386 h, w = os.popen('stty size', 'r').read().split()
2d341029
O
1387 # Start
1388 usage = '\n'
1389 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1390 usage += s + '-' * (int(w) - 4) + '\n'
1391 usage += s + 'You are ' + \
1392 light_yellow('already') + ' on your personal stream.\n'
1393 usage += s + 'Any update from Twitter will show up ' + \
1394 light_yellow('immediately') + '.\n'
37d1047f 1395 usage += s + 'In addition, following commands are available right now:\n'
2d341029
O
1396 # Twitter help section
1397 usage += '\n'
1398 usage += s + grey(u'\u266A' + ' Twitter help\n')
1399 usage += s * 2 + light_green('h discover') + \
1400 ' will show help for discover commands.\n'
1401 usage += s * 2 + light_green('h tweets') + \
1402 ' will show help for tweets commands.\n'
1403 usage += s * 2 + light_green('h messages') + \
1404 ' will show help for messages commands.\n'
1405 usage += s * 2 + light_green('h friends_and_followers') + \
1406 ' will show help for friends and followers commands.\n'
1407 usage += s * 2 + light_green('h list') + \
1408 ' will show help for list commands.\n'
1409 usage += s * 2 + light_green('h stream') + \
1410 ' will show help for stream commands.\n'
1f24a05a 1411 # Smart shell
1412 usage += '\n'
1413 usage += s + grey(u'\u266A' + ' Smart shell\n')
c075e6dc 1414 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1f24a05a 1415 'will be evaluate by Python interpreter.\n'
c075e6dc 1416 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1f24a05a 1417 ' for current month.\n'
29fd0be6 1418 # Config
1f24a05a 1419 usage += '\n'
29fd0be6
O
1420 usage += s + grey(u'\u266A' + ' Config \n')
1421 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
c075e6dc 1422 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
632c6fa5 1423 ' theme immediately.\n'
29fd0be6
O
1424 usage += s * 2 + light_green('config') + ' will list all config.\n'
1425 usage += s * 3 + \
1426 light_green('config ASCII_ART') + ' will output current value of ' +\
a8c5fce4 1427 light_yellow('ASCII_ART') + ' config key.\n'
29fd0be6 1428 usage += s * 3 + \
fe9bb33b 1429 light_green('config TREND_MAX default') + ' will output default value of ' + \
1430 light_yellow('TREND_MAX') + ' config key.\n'
1431 usage += s * 3 + \
1432 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1433 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
29fd0be6 1434 usage += s * 3 + \
fe9bb33b 1435 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1436 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1437 light_yellow('True') + '.\n'
29fd0be6
O
1438 # Screening
1439 usage += '\n'
1440 usage += s + grey(u'\u266A' + ' Screening \n')
c075e6dc 1441 usage += s * 2 + light_green('h') + ' will show this help again.\n'
d6cc4c67
O
1442 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1443 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
c075e6dc
O
1444 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1445 usage += s * 2 + light_green('q') + ' will quit.\n'
8bc30efd 1446 # End
1447 usage += '\n'
7e4ccbf3 1448 usage += s + '-' * (int(w) - 4) + '\n'
8bc30efd 1449 usage += s + 'Have fun and hang tight! \n'
2d341029
O
1450 # Show help
1451 d = {
422dd385
O
1452 'discover': help_discover,
1453 'tweets': help_tweets,
1454 'messages': help_messages,
1455 'friends_and_followers': help_friends_and_followers,
1456 'list': help_list,
1457 'stream': help_stream,
2d341029
O
1458 }
1459 if g['stuff']:
baec5f50 1460 d.get(
1461 g['stuff'].strip(),
1462 lambda: printNicely(red('No such command.'))
3d48702f 1463 )()
2d341029
O
1464 else:
1465 printNicely(usage)
f405a7d0
O
1466
1467
d6cc4c67
O
1468def pause():
1469 """
1470 Pause stream display
1471 """
4dc385b5 1472 g['pause'] = True
d6cc4c67
O
1473 printNicely(green('Stream is paused'))
1474
1475
1476def replay():
1477 """
1478 Replay stream
1479 """
4dc385b5 1480 g['pause'] = False
d6cc4c67
O
1481 printNicely(green('Stream is running back now'))
1482
1483
843647ad 1484def clear():
f405a7d0 1485 """
7b674cef 1486 Clear screen
f405a7d0 1487 """
843647ad 1488 os.system('clear')
f405a7d0
O
1489
1490
843647ad 1491def quit():
b8dda704
O
1492 """
1493 Exit all
1494 """
4c025026 1495 try:
1496 save_history()
4c025026 1497 printNicely(green('See you next time :)'))
1498 except:
1499 pass
843647ad 1500 sys.exit()
b8dda704
O
1501
1502
94a5f62e 1503def reset():
f405a7d0 1504 """
94a5f62e 1505 Reset prefix of line
f405a7d0 1506 """
c91f75f2 1507 if g['reset']:
a8e71259 1508 if c.get('USER_JSON_ERROR'):
1509 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1510 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1511 printNicely('')
e3885f55 1512 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
c91f75f2 1513 g['reset'] = False
d0a726d6 1514 try:
779b0640 1515 printNicely(str(eval(g['cmd'])))
2a0cabee 1516 except Exception:
d0a726d6 1517 pass
54277114
O
1518
1519
f1c1dfea
O
1520# Command set
1521cmdset = [
1522 'switch',
1523 'trend',
1524 'home',
1525 'view',
1526 'mentions',
1527 't',
1528 'rt',
1529 'quote',
1530 'allrt',
fd87ddac 1531 'conversation',
f1c1dfea
O
1532 'fav',
1533 'rep',
1534 'del',
1535 'ufav',
1536 's',
1537 'mes',
1538 'show',
1539 'open',
1540 'ls',
1541 'inbox',
67c663f8 1542 'thread',
f1c1dfea
O
1543 'trash',
1544 'whois',
1545 'fl',
1546 'ufl',
1547 'mute',
1548 'unmute',
1549 'muting',
1550 'block',
1551 'unblock',
1552 'report',
1553 'list',
1554 'cal',
1555 'config',
1556 'theme',
1557 'h',
1558 'p',
1559 'r',
1560 'c',
1561 'q'
1562]
1563
1564# Handle function set
1565funcset = [
1566 switch,
1567 trend,
1568 home,
1569 view,
1570 mentions,
1571 tweet,
1572 retweet,
1573 quote,
1574 allretweet,
fd87ddac 1575 conversation,
f1c1dfea
O
1576 favorite,
1577 reply,
1578 delete,
1579 unfavorite,
1580 search,
1581 message,
1582 show,
1583 urlopen,
1584 ls,
1585 inbox,
67c663f8 1586 thread,
f1c1dfea
O
1587 trash,
1588 whois,
1589 follow,
1590 unfollow,
1591 mute,
1592 unmute,
1593 muting,
1594 block,
1595 unblock,
1596 report,
1597 twitterlist,
1598 cal,
1599 config,
1600 theme,
1601 help,
1602 pause,
1603 replay,
1604 clear,
1605 quit
1606]
1607
1608
94a5f62e 1609def process(cmd):
54277114 1610 """
94a5f62e 1611 Process switch
54277114 1612 """
f1c1dfea 1613 return dict(zip(cmdset, funcset)).get(cmd, reset)
94a5f62e 1614
1615
1616def listen():
42fde775 1617 """
1618 Listen to user's input
1619 """
d51b4107
O
1620 d = dict(zip(
1621 cmdset,
1622 [
affcb149 1623 ['public', 'mine'], # switch
4592d231 1624 [], # trend
7e4ccbf3 1625 [], # home
1626 ['@'], # view
305ce127 1627 [], # mentions
7e4ccbf3 1628 [], # tweet
1629 [], # retweet
80b70d60 1630 [], # quote
1f24a05a 1631 [], # allretweet
fd87ddac 1632 [], # conversation
f5677fb1 1633 [], # favorite
7e4ccbf3 1634 [], # reply
1635 [], # delete
f5677fb1 1636 [], # unfavorite
7e4ccbf3 1637 ['#'], # search
305ce127 1638 ['@'], # message
f5677fb1 1639 ['image'], # show image
80b70d60 1640 [''], # open url
305ce127 1641 ['fl', 'fr'], # list
1642 [], # inbox
03c0d30b 1643 [i for i in g['message_threads']], # sent
305ce127 1644 [], # trash
e2b81717 1645 ['@'], # whois
affcb149
O
1646 ['@'], # follow
1647 ['@'], # unfollow
5b2c4faf 1648 ['@'], # mute
1649 ['@'], # unmute
1650 ['@'], # muting
305ce127 1651 ['@'], # block
1652 ['@'], # unblock
1653 ['@'], # report
422dd385
O
1654 [
1655 'home',
1656 'all_mem',
1657 'all_sub',
1658 'add',
1659 'rm',
1660 'sub',
1661 'unsub',
1662 'own',
1663 'new',
1664 'update',
1665 'del'
1666 ], # list
813a5d80 1667 [], # cal
a8c5fce4 1668 [key for key in dict(get_all_config())], # config
ceec8593 1669 g['themes'], # theme
422dd385
O
1670 [
1671 'discover',
1672 'tweets',
1673 'messages',
1674 'friends_and_followers',
1675 'list',
1676 'stream'
1677 ], # help
d6cc4c67
O
1678 [], # pause
1679 [], # reconnect
7e4ccbf3 1680 [], # clear
1681 [], # quit
d51b4107 1682 ]
7e4ccbf3 1683 ))
d51b4107 1684 init_interactive_shell(d)
f5677fb1 1685 read_history()
819569e8 1686 reset()
b2b933a9 1687 while True:
b8c1f42a 1688 try:
39b8e6b3
O
1689 # raw_input
1690 if g['prefix']:
1691 line = raw_input(g['decorated_name'](c['PREFIX']))
1692 else:
1693 line = raw_input()
1694 # Save cmd to compare with readline buffer
1695 g['cmd'] = line.strip()
1696 # Get short cmd to pass to handle function
1697 try:
1698 cmd = line.split()[0]
1699 except:
1700 cmd = ''
9683e61d 1701 # Lock the semaphore
99b52f5f 1702 c['lock'] = True
9683e61d 1703 # Save cmd to global variable and call process
b8c1f42a 1704 g['stuff'] = ' '.join(line.split()[1:])
9683e61d 1705 # Process the command
b8c1f42a 1706 process(cmd)()
9683e61d 1707 # Not re-display
99b52f5f 1708 if cmd in ['switch', 't', 'rt', 'rep']:
9683e61d
O
1709 g['prefix'] = False
1710 else:
1711 g['prefix'] = True
1712 # Release the semaphore lock
99b52f5f 1713 c['lock'] = False
39b8e6b3
O
1714 except EOFError:
1715 printNicely('')
eadd85a8 1716 except Exception:
b8c1f42a 1717 printNicely(red('OMG something is wrong with Twitter right now.'))
54277114
O
1718
1719
42fde775 1720def stream(domain, args, name='Rainbow Stream'):
54277114 1721 """
f405a7d0 1722 Track the stream
54277114 1723 """
54277114 1724 # The Logo
42fde775 1725 art_dict = {
632c6fa5
O
1726 c['USER_DOMAIN']: name,
1727 c['PUBLIC_DOMAIN']: args.track_keywords,
1f2f6159 1728 c['SITE_DOMAIN']: name,
42fde775 1729 }
687567eb 1730 if c['ASCII_ART']:
c075e6dc 1731 ascii_art(art_dict[domain])
91476ec3
O
1732 # These arguments are optional:
1733 stream_args = dict(
e3927852 1734 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
cb45dc23 1735 block=True,
1736 heartbeat_timeout=c['HEARTBEAT_TIMEOUT'] * 60)
91476ec3
O
1737 # Track keyword
1738 query_args = dict()
1739 if args.track_keywords:
1740 query_args['track'] = args.track_keywords
91476ec3 1741 # Get stream
2a6238f5 1742 stream = TwitterStream(
22be990e 1743 auth=authen(),
42fde775 1744 domain=domain,
2a6238f5 1745 **stream_args)
2a0cabee
O
1746 try:
1747 if domain == c['USER_DOMAIN']:
1748 tweet_iter = stream.user(**query_args)
1749 elif domain == c['SITE_DOMAIN']:
1750 tweet_iter = stream.site(**query_args)
42fde775 1751 else:
2a0cabee
O
1752 if args.track_keywords:
1753 tweet_iter = stream.statuses.filter(**query_args)
1754 else:
1755 tweet_iter = stream.statuses.sample()
92983945
BS
1756 # Block new stream until other one exits
1757 StreamLock.acquire()
1758 g['stream_stop'] = False
72c02928
VNM
1759 for tweet in tweet_iter:
1760 if tweet is None:
a1222228 1761 printNicely("-- None --")
72c02928 1762 elif tweet is Timeout:
335e7803
O
1763 if(g['stream_stop']):
1764 StreamLock.release()
1765 break
72c02928
VNM
1766 elif tweet is HeartbeatTimeout:
1767 printNicely("-- Heartbeat Timeout --")
cb45dc23 1768 guide = light_magenta("You can use ") + \
1769 light_green("switch") + \
1770 light_magenta(" command to return to your stream.\n")
1771 guide += light_magenta("Type ") + \
1772 light_green("h stream") + \
1773 light_magenta(" for more details.")
1774 printNicely(guide)
1775 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1776 sys.stdout.flush()
8715dda0
O
1777 StreamLock.release()
1778 break
72c02928
VNM
1779 elif tweet is Hangup:
1780 printNicely("-- Hangup --")
1781 elif tweet.get('text'):
4dc385b5
O
1782 # Check the semaphore pause and lock (stream process only)
1783 if g['pause']:
1784 continue
1785 while c['lock']:
1786 time.sleep(0.5)
1787 # Draw the tweet
72c02928
VNM
1788 draw(
1789 t=tweet,
72c02928 1790 keyword=args.track_keywords,
8b3456f9 1791 humanize=False,
72c02928
VNM
1792 fil=args.filter,
1793 ig=args.ignore,
1794 )
4824b181
O
1795 # Current readline buffer
1796 current_buffer = readline.get_line_buffer().strip()
335e7803 1797 # There is an unexpected behaviour in MacOSX readline + Python 2:
3d48702f
O
1798 # after completely delete a word after typing it,
1799 # somehow readline buffer still contains
1800 # the 1st character of that word
f1c1dfea 1801 if current_buffer and g['cmd'] != current_buffer:
3d48702f 1802 sys.stdout.write(
7c437a0f 1803 g['decorated_name'](c['PREFIX']) + str2u(current_buffer))
4824b181 1804 sys.stdout.flush()
335e7803
O
1805 elif not c['HIDE_PROMPT']:
1806 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1807 sys.stdout.flush()
14db58c7 1808 elif tweet.get('direct_message'):
4dc385b5
O
1809 # Check the semaphore pause and lock (stream process only)
1810 if g['pause']:
1811 continue
1812 while c['lock']:
1813 time.sleep(0.5)
1814 print_message(tweet['direct_message'])
2a0cabee
O
1815 except TwitterHTTPError:
1816 printNicely('')
c075e6dc 1817 printNicely(
2a0cabee 1818 magenta("We have maximum connection problem with twitter'stream API right now :("))
54277114
O
1819
1820
1821def fly():
1822 """
1823 Main function
1824 """
531f5682 1825 # Initial
42fde775 1826 args = parse_arguments()
2a0cabee 1827 try:
fe9bb33b 1828 init(args)
2a0cabee
O
1829 except TwitterHTTPError:
1830 printNicely('')
1831 printNicely(
e3927852 1832 magenta("We have connection problem with twitter'stream API right now :("))
4c025026 1833 printNicely(magenta("Let's try again later."))
2a0cabee 1834 save_history()
2a0cabee 1835 sys.exit()
92983945 1836 # Spawn stream thread
baec5f50 1837 th = threading.Thread(
1838 target=stream,
1839 args=(
1840 c['USER_DOMAIN'],
1841 args,
1842 g['original_name']))
92983945
BS
1843 th.daemon = True
1844 th.start()
42fde775 1845 # Start listen process
819569e8 1846 time.sleep(0.5)
c91f75f2 1847 g['reset'] = True
1dd312f5 1848 g['prefix'] = True
0f6e4daf 1849 listen()