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