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