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