Merge branch 'master' of github.com:DTVD/rainbowstream
[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',
56702c8f 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).')
53 parser.add_argument(
2a6238f5
O
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.')
c426a344 70 parser.add_argument(
69b6ab70
JH
71 '-24',
72 '--color-24bit',
73 action='store_true',
74 help='Display images using 24bit color codes.')
75 parser.add_argument(
c426a344 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
d4b36355
O
245 # Check type of ONLY_LIST and IGNORE_LIST
246 if not isinstance(c['ONLY_LIST'], list):
247 printNicely(red('ONLY_LIST is not a valid list value.'))
248 c['ONLY_LIST'] = []
249 if not isinstance(c['IGNORE_LIST'], list):
250 printNicely(red('IGNORE_LIST is not a valid list value.'))
251 c['IGNORE_LIST'] = []
e3927852
O
252 # Mute dict
253 c['IGNORE_LIST'] += build_mute_dict()
f405a7d0 254
ceec8593 255
4592d231 256def trend():
257 """
258 Trend
259 """
260 t = Twitter(auth=authen())
48a25fe8 261 # Get country and town
4592d231 262 try:
263 country = g['stuff'].split()[0]
264 except:
265 country = ''
48a25fe8 266 try:
267 town = g['stuff'].split()[1]
268 except:
269 town = ''
48a25fe8 270 avail = t.trends.available()
271 # World wide
272 if not country:
273 trends = t.trends.place(_id=1)[0]['trends']
274 print_trends(trends)
275 else:
276 for location in avail:
277 # Search for country and Town
278 if town:
279 if location['countryCode'] == country \
280 and location['placeType']['name'] == 'Town' \
281 and location['name'] == town:
282 trends = t.trends.place(_id=location['woeid'])[0]['trends']
283 print_trends(trends)
284 # Search for country only
285 else:
286 if location['countryCode'] == country \
287 and location['placeType']['name'] == 'Country':
288 trends = t.trends.place(_id=location['woeid'])[0]['trends']
289 print_trends(trends)
4592d231 290
291
7b674cef 292def home():
293 """
294 Home
295 """
296 t = Twitter(auth=authen())
632c6fa5 297 num = c['HOME_TWEET_NUM']
7b674cef 298 if g['stuff'].isdigit():
305ce127 299 num = int(g['stuff'])
94a5f62e 300 for tweet in reversed(t.statuses.home_timeline(count=num)):
fe9bb33b 301 draw(t=tweet)
94a5f62e 302 printNicely('')
7b674cef 303
304
99cd1fba
O
305def notification():
306 """
307 Show notifications
308 """
d7d9c67c 309 if c['events']:
310 for e in c['events']:
99cd1fba
O
311 print_event(e)
312 printNicely('')
313 else:
314 printNicely(magenta('Nothing at this time.'))
315
316
fd87ddac
O
317def mentions():
318 """
319 Mentions timeline
320 """
321 t = Twitter(auth=authen())
322 num = c['HOME_TWEET_NUM']
323 if g['stuff'].isdigit():
324 num = int(g['stuff'])
325 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
326 draw(t=tweet)
327 printNicely('')
328
329
330def whois():
331 """
332 Show profile of a specific user
333 """
334 t = Twitter(auth=authen())
04610460
O
335 try:
336 screen_name = g['stuff'].split()[0]
337 except:
338 printNicely(red('Sorry I can\'t understand.'))
339 return
fd87ddac
O
340 if screen_name.startswith('@'):
341 try:
342 user = t.users.show(
343 screen_name=screen_name[1:],
344 include_entities=False)
345 show_profile(user)
346 except:
7a8a52fc
O
347 debug_option()
348 printNicely(red('No user.'))
fd87ddac
O
349 else:
350 printNicely(red('A name should begin with a \'@\''))
351
352
7b674cef 353def view():
354 """
355 Friend view
356 """
357 t = Twitter(auth=authen())
04610460
O
358 try:
359 user = g['stuff'].split()[0]
360 except:
361 printNicely(red('Sorry I can\'t understand.'))
362 return
b8fbcb70 363 if user[0] == '@':
364 try:
94a5f62e 365 num = int(g['stuff'].split()[1])
b8fbcb70 366 except:
632c6fa5 367 num = c['HOME_TWEET_NUM']
9ee4a3cc
O
368 for tweet in reversed(
369 t.statuses.user_timeline(count=num, screen_name=user[1:])):
fe9bb33b 370 draw(t=tweet)
94a5f62e 371 printNicely('')
b8fbcb70 372 else:
c91f75f2 373 printNicely(red('A name should begin with a \'@\''))
7b674cef 374
375
fd87ddac 376def search():
2d0ad040 377 """
fd87ddac 378 Search
2d0ad040
J
379 """
380 t = Twitter(auth=authen())
954b3101 381 # Setup query
382 query = g['stuff'].strip()
04610460
O
383 if not query:
384 printNicely(red('Sorry I can\'t understand.'))
385 return
954b3101 386 type = c['SEARCH_TYPE']
387 if type not in ['mixed', 'recent', 'popular']:
388 type = 'mixed'
389 max_record = c['SEARCH_MAX_RECORD']
390 count = min(max_record, 100)
391 # Perform search
392 rel = t.search.tweets(
393 q=query,
394 type=type,
395 count=count
396 )['statuses']
397 # Return results
fd87ddac
O
398 if rel:
399 printNicely('Newest tweets:')
954b3101 400 for i in reversed(xrange(count)):
401 draw(t=rel[i], keyword=query)
fd87ddac
O
402 printNicely('')
403 else:
404 printNicely(magenta('I\'m afraid there is no result'))
2d0ad040
J
405
406
f405a7d0 407def tweet():
54277114 408 """
7b674cef 409 Tweet
54277114
O
410 """
411 t = Twitter(auth=authen())
f405a7d0 412 t.statuses.update(status=g['stuff'])
f405a7d0 413
b2b933a9 414
1ba4abfd
O
415def retweet():
416 """
417 ReTweet
418 """
419 t = Twitter(auth=authen())
420 try:
421 id = int(g['stuff'].split()[0])
1ba4abfd 422 except:
b8c1f42a
O
423 printNicely(red('Sorry I can\'t understand.'))
424 return
99b52f5f 425 tid = c['tweet_dict'][id]
b8c1f42a 426 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
1ba4abfd
O
427
428
80b70d60
O
429def quote():
430 """
431 Quote a tweet
432 """
b7c9c570 433 # Get tweet
80b70d60
O
434 t = Twitter(auth=authen())
435 try:
436 id = int(g['stuff'].split()[0])
437 except:
438 printNicely(red('Sorry I can\'t understand.'))
439 return
99b52f5f 440 tid = c['tweet_dict'][id]
80b70d60 441 tweet = t.statuses.show(id=tid)
b7c9c570 442 # Get formater
443 formater = format_quote(tweet)
444 if not formater:
7c437a0f 445 return
7c437a0f 446 # Get comment
be4dba0e 447 prefix = light_magenta('Compose your ', rl=True) + \
448 light_green('#comment: ', rl=True)
7c437a0f
O
449 comment = raw_input(prefix)
450 if comment:
451 quote = comment.join(formater.split('#comment'))
b7c9c570 452 t.statuses.update(status=quote)
80b70d60
O
453 else:
454 printNicely(light_magenta('No text added.'))
455
456
1f24a05a 457def allretweet():
458 """
459 List all retweet
460 """
461 t = Twitter(auth=authen())
462 # Get rainbow id
463 try:
464 id = int(g['stuff'].split()[0])
465 except:
466 printNicely(red('Sorry I can\'t understand.'))
467 return
99b52f5f 468 tid = c['tweet_dict'][id]
1f24a05a 469 # Get display num if exist
470 try:
471 num = int(g['stuff'].split()[1])
472 except:
632c6fa5 473 num = c['RETWEETS_SHOW_NUM']
1f24a05a 474 # Get result and display
d8e901a4 475 rt_ary = t.statuses.retweets(id=tid, count=num)
1f24a05a 476 if not rt_ary:
477 printNicely(magenta('This tweet has no retweet.'))
478 return
479 for tweet in reversed(rt_ary):
fe9bb33b 480 draw(t=tweet)
1f24a05a 481 printNicely('')
482
483
fd87ddac 484def conversation():
7e4ccbf3 485 """
fd87ddac 486 Conversation view
7e4ccbf3 487 """
488 t = Twitter(auth=authen())
489 try:
490 id = int(g['stuff'].split()[0])
7e4ccbf3 491 except:
b8c1f42a
O
492 printNicely(red('Sorry I can\'t understand.'))
493 return
99b52f5f 494 tid = c['tweet_dict'][id]
fd87ddac
O
495 tweet = t.statuses.show(id=tid)
496 limit = c['CONVERSATION_MAX']
497 thread_ref = []
498 thread_ref.append(tweet)
499 prev_tid = tweet['in_reply_to_status_id']
500 while prev_tid and limit:
501 limit -= 1
502 tweet = t.statuses.show(id=prev_tid)
503 prev_tid = tweet['in_reply_to_status_id']
504 thread_ref.append(tweet)
505
506 for tweet in reversed(thread_ref):
507 draw(t=tweet)
b8c1f42a 508 printNicely('')
7e4ccbf3 509
510
7b674cef 511def reply():
829cc2d8 512 """
7b674cef 513 Reply
829cc2d8
O
514 """
515 t = Twitter(auth=authen())
7b674cef 516 try:
517 id = int(g['stuff'].split()[0])
7b674cef 518 except:
c91f75f2 519 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a 520 return
99b52f5f 521 tid = c['tweet_dict'][id]
b8c1f42a
O
522 user = t.statuses.show(id=tid)['user']['screen_name']
523 status = ' '.join(g['stuff'].split()[1:])
7c437a0f 524 status = '@' + user + ' ' + str2u(status)
b8c1f42a 525 t.statuses.update(status=status, in_reply_to_status_id=tid)
7b674cef 526
527
ba6c09d1
O
528def reply_all():
529 """
530 Reply to all
531 """
532 t = Twitter(auth=authen())
533 try:
534 id = int(g['stuff'].split()[0])
535 except:
536 printNicely(red('Sorry I can\'t understand.'))
537 return
538 tid = c['tweet_dict'][id]
539 original_tweet = t.statuses.show(id=tid)
540 text = original_tweet['text']
247c4e80 541 nick_ary = [original_tweet['user']['screen_name']]
a99609e6 542 for user in list(original_tweet['entities']['user_mentions']):
97def8fc
JT
543 if user['screen_name'] not in nick_ary \
544 and user['screen_name'] != g['original_name']:
247c4e80 545 nick_ary.append(user['screen_name'])
ba6c09d1 546 status = ' '.join(g['stuff'].split()[1:])
247c4e80 547 status = ' '.join(['@' + nick for nick in nick_ary]) + ' ' + str2u(status)
ba6c09d1
O
548 t.statuses.update(status=status, in_reply_to_status_id=tid)
549
550
fd87ddac 551def favorite():
7b674cef 552 """
fd87ddac 553 Favorite
7b674cef 554 """
555 t = Twitter(auth=authen())
556 try:
99b52f5f 557 id = int(g['stuff'].split()[0])
7b674cef 558 except:
305ce127 559 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a 560 return
99b52f5f 561 tid = c['tweet_dict'][id]
fd87ddac
O
562 t.favorites.create(_id=tid, include_entities=False)
563 printNicely(green('Favorited.'))
564 draw(t.statuses.show(id=tid))
565 printNicely('')
829cc2d8
O
566
567
7e4ccbf3 568def unfavorite():
569 """
570 Unfavorite
571 """
572 t = Twitter(auth=authen())
573 try:
574 id = int(g['stuff'].split()[0])
7e4ccbf3 575 except:
b8c1f42a
O
576 printNicely(red('Sorry I can\'t understand.'))
577 return
99b52f5f 578 tid = c['tweet_dict'][id]
b8c1f42a
O
579 t.favorites.destroy(_id=tid)
580 printNicely(green('Okay it\'s unfavorited.'))
fe9bb33b 581 draw(t.statuses.show(id=tid))
b8c1f42a 582 printNicely('')
7e4ccbf3 583
584
413857b5
O
585def share():
586 """
587 Copy url of a tweet to clipboard
588 """
589 t = Twitter(auth=authen())
590 try:
591 id = int(g['stuff'].split()[0])
66fe9f75 592 tid = c['tweet_dict'][id]
413857b5 593 except:
66fe9f75 594 printNicely(red('Tweet id is not valid.'))
413857b5 595 return
413857b5
O
596 tweet = t.statuses.show(id=tid)
597 url = 'https://twitter.com/' + \
598 tweet['user']['screen_name'] + '/status/' + str(tid)
eb9b6273 599 import platform
600 if platform.system().lower() == 'darwin':
601 os.system("echo '%s' | pbcopy" % url)
602 printNicely(green('Copied tweet\'s url to clipboard.'))
603 else:
604 printNicely('Direct link: ' + yellow(url))
413857b5
O
605
606
fd87ddac 607def delete():
305ce127 608 """
fd87ddac 609 Delete
305ce127 610 """
611 t = Twitter(auth=authen())
fd87ddac
O
612 try:
613 id = int(g['stuff'].split()[0])
614 except:
615 printNicely(red('Sorry I can\'t understand.'))
616 return
617 tid = c['tweet_dict'][id]
618 t.statuses.destroy(id=tid)
619 printNicely(green('Okay it\'s gone.'))
305ce127 620
621
f5677fb1 622def show():
843647ad 623 """
f5677fb1 624 Show image
843647ad
O
625 """
626 t = Twitter(auth=authen())
f5677fb1
O
627 try:
628 target = g['stuff'].split()[0]
629 if target != 'image':
630 return
631 id = int(g['stuff'].split()[1])
99b52f5f 632 tid = c['tweet_dict'][id]
f5677fb1
O
633 tweet = t.statuses.show(id=tid)
634 media = tweet['entities']['media']
635 for m in media:
636 res = requests.get(m['media_url'])
b3164e62 637 img = Image.open(BytesIO(res.content))
f5677fb1
O
638 img.show()
639 except:
7a8a52fc 640 debug_option()
f5677fb1 641 printNicely(red('Sorry I can\'t show this image.'))
843647ad
O
642
643
80bb2040 644def urlopen():
80b70d60
O
645 """
646 Open url
647 """
648 t = Twitter(auth=authen())
649 try:
650 if not g['stuff'].isdigit():
651 return
8101275e 652 tid = c['tweet_dict'][int(g['stuff'])]
80b70d60 653 tweet = t.statuses.show(id=tid)
571ea706
O
654 link_prefix = ('http://', 'https://')
655 link_ary = [u for u in tweet['text'].split()
656 if u.startswith(link_prefix)]
80b70d60
O
657 if not link_ary:
658 printNicely(light_magenta('No url here @.@!'))
659 return
660 for link in link_ary:
661 webbrowser.open(link)
662 except:
7a8a52fc 663 debug_option()
80b70d60
O
664 printNicely(red('Sorry I can\'t open url in this tweet.'))
665
666
305ce127 667def inbox():
668 """
67c663f8 669 Inbox threads
305ce127 670 """
671 t = Twitter(auth=authen())
632c6fa5 672 num = c['MESSAGES_DISPLAY']
305ce127 673 if g['stuff'].isdigit():
674 num = g['stuff']
67c663f8 675 # Get inbox messages
305ce127 676 cur_page = 1
67c663f8 677 inbox = []
305ce127 678 while num > 20:
67c663f8 679 inbox = inbox + t.direct_messages(
305ce127 680 count=20,
681 page=cur_page,
682 include_entities=False,
683 skip_status=False
48a25fe8 684 )
305ce127 685 num -= 20
686 cur_page += 1
67c663f8 687 inbox = inbox + t.direct_messages(
305ce127 688 count=num,
689 page=cur_page,
690 include_entities=False,
691 skip_status=False
48a25fe8 692 )
67c663f8 693 # Get sent messages
632c6fa5 694 num = c['MESSAGES_DISPLAY']
305ce127 695 if g['stuff'].isdigit():
67c663f8 696 num = g['stuff']
305ce127 697 cur_page = 1
67c663f8 698 sent = []
305ce127 699 while num > 20:
67c663f8 700 sent = sent + t.direct_messages.sent(
305ce127 701 count=20,
702 page=cur_page,
703 include_entities=False,
704 skip_status=False
48a25fe8 705 )
305ce127 706 num -= 20
707 cur_page += 1
67c663f8 708 sent = sent + t.direct_messages.sent(
305ce127 709 count=num,
710 page=cur_page,
711 include_entities=False,
712 skip_status=False
48a25fe8 713 )
67c663f8
O
714
715 d = {}
716 uniq_inbox = list(set(
03c0d30b 717 [(m['sender_screen_name'], m['sender']['name']) for m in inbox]
67c663f8 718 ))
03c0d30b 719 uniq_sent = list(set(
720 [(m['recipient_screen_name'], m['recipient']['name']) for m in sent]
67c663f8
O
721 ))
722 for partner in uniq_inbox:
723 inbox_ary = [m for m in inbox if m['sender_screen_name'] == partner[0]]
03c0d30b 724 sent_ary = [
725 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
726 d[partner] = inbox_ary + sent_ary
727 for partner in uniq_sent:
728 if partner not in d:
03c0d30b 729 d[partner] = [
730 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
731 g['message_threads'] = print_threads(d)
732
733
734def thread():
735 """
736 View a thread of message
737 """
738 try:
739 thread_id = int(g['stuff'])
03c0d30b 740 print_thread(
741 g['message_threads'][thread_id],
742 g['original_name'],
743 g['full_name'])
744 except Exception:
7a8a52fc 745 debug_option()
67c663f8 746 printNicely(red('No such thread.'))
e2b81717 747
305ce127 748
fd87ddac
O
749def message():
750 """
751 Send a direct message
752 """
753 t = Twitter(auth=authen())
03c0d30b 754 try:
755 user = g['stuff'].split()[0]
756 if user[0].startswith('@'):
757 content = ' '.join(g['stuff'].split()[1:])
758 t.direct_messages.new(
759 screen_name=user[1:],
760 text=content
761 )
762 printNicely(green('Message sent.'))
763 else:
764 printNicely(red('A name should begin with a \'@\''))
765 except:
7a8a52fc 766 debug_option()
03c0d30b 767 printNicely(red('Sorry I can\'t understand.'))
fd87ddac
O
768
769
305ce127 770def trash():
771 """
772 Remove message
773 """
774 t = Twitter(auth=authen())
775 try:
99b52f5f 776 id = int(g['stuff'].split()[0])
305ce127 777 except:
778 printNicely(red('Sorry I can\'t understand.'))
99b52f5f 779 mid = c['message_dict'][id]
b8c1f42a
O
780 t.direct_messages.destroy(id=mid)
781 printNicely(green('Message deleted.'))
305ce127 782
783
fd87ddac 784def ls():
e2b81717 785 """
fd87ddac 786 List friends for followers
e2b81717
O
787 """
788 t = Twitter(auth=authen())
fd87ddac
O
789 # Get name
790 try:
791 name = g['stuff'].split()[1]
792 if name.startswith('@'):
793 name = name[1:]
794 else:
795 printNicely(red('A name should begin with a \'@\''))
796 raise Exception('Invalid name')
797 except:
798 name = g['original_name']
799 # Get list followers or friends
800 try:
801 target = g['stuff'].split()[0]
802 except:
803 printNicely(red('Omg some syntax is wrong.'))
04610460 804 return
fd87ddac
O
805 # Init cursor
806 d = {'fl': 'followers', 'fr': 'friends'}
807 next_cursor = -1
808 rel = {}
809 # Cursor loop
810 while next_cursor != 0:
811 list = getattr(t, d[target]).list(
812 screen_name=name,
813 cursor=next_cursor,
814 skip_status=True,
815 include_entities=False,
816 )
817 for u in list['users']:
818 rel[u['name']] = '@' + u['screen_name']
819 next_cursor = list['next_cursor']
820 # Print out result
821 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
822 for name in rel:
823 user = ' ' + cycle_color(name)
824 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
825 printNicely(user)
e2b81717
O
826
827
f5677fb1 828def follow():
843647ad 829 """
f5677fb1 830 Follow a user
843647ad
O
831 """
832 t = Twitter(auth=authen())
f5677fb1 833 screen_name = g['stuff'].split()[0]
b8c1f42a
O
834 if screen_name.startswith('@'):
835 t.friendships.create(screen_name=screen_name[1:], follow=True)
836 printNicely(green('You are following ' + screen_name + ' now!'))
f5677fb1 837 else:
b8c1f42a 838 printNicely(red('A name should begin with a \'@\''))
f5677fb1
O
839
840
841def unfollow():
842 """
843 Unfollow a user
844 """
845 t = Twitter(auth=authen())
846 screen_name = g['stuff'].split()[0]
b8c1f42a
O
847 if screen_name.startswith('@'):
848 t.friendships.destroy(
849 screen_name=screen_name[1:],
850 include_entities=False)
851 printNicely(green('Unfollow ' + screen_name + ' success!'))
f5677fb1 852 else:
b8c1f42a 853 printNicely(red('A name should begin with a \'@\''))
843647ad
O
854
855
5b2c4faf 856def mute():
857 """
858 Mute a user
859 """
860 t = Twitter(auth=authen())
861 try:
862 screen_name = g['stuff'].split()[0]
863 except:
864 printNicely(red('A name should be specified. '))
865 return
866 if screen_name.startswith('@'):
e3927852
O
867 try:
868 rel = t.mutes.users.create(screen_name=screen_name[1:])
869 if isinstance(rel, dict):
870 printNicely(green(screen_name + ' is muted.'))
612d6863 871 c['IGNORE_LIST'] += [unc(screen_name)]
e3927852
O
872 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
873 else:
874 printNicely(red(rel))
875 except:
7a8a52fc 876 debug_option()
e3927852 877 printNicely(red('Something is wrong, can not mute now :('))
5b2c4faf 878 else:
879 printNicely(red('A name should begin with a \'@\''))
880
881
882def unmute():
883 """
884 Unmute a user
885 """
886 t = Twitter(auth=authen())
887 try:
888 screen_name = g['stuff'].split()[0]
889 except:
890 printNicely(red('A name should be specified. '))
891 return
892 if screen_name.startswith('@'):
e3927852
O
893 try:
894 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
895 if isinstance(rel, dict):
896 printNicely(green(screen_name + ' is unmuted.'))
897 c['IGNORE_LIST'].remove(screen_name)
898 else:
899 printNicely(red(rel))
900 except:
901 printNicely(red('Maybe you are not muting this person ?'))
5b2c4faf 902 else:
903 printNicely(red('A name should begin with a \'@\''))
904
905
906def muting():
907 """
908 List muting user
909 """
e3927852
O
910 # Get dict of muting users
911 md = build_mute_dict(dict_data=True)
912 printNicely('All: ' + str(len(md)) + ' people.')
913 for name in md:
914 user = ' ' + cycle_color(md[name])
915 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
5b2c4faf 916 printNicely(user)
e3927852
O
917 # Update from Twitter
918 c['IGNORE_LIST'] = [n for n in md]
5b2c4faf 919
920
305ce127 921def block():
922 """
923 Block a user
924 """
925 t = Twitter(auth=authen())
926 screen_name = g['stuff'].split()[0]
b8c1f42a
O
927 if screen_name.startswith('@'):
928 t.blocks.create(
5b2c4faf 929 screen_name=screen_name[1:],
930 include_entities=False,
931 skip_status=True)
b8c1f42a 932 printNicely(green('You blocked ' + screen_name + '.'))
305ce127 933 else:
b8c1f42a 934 printNicely(red('A name should begin with a \'@\''))
305ce127 935
936
937def unblock():
938 """
939 Unblock a user
940 """
941 t = Twitter(auth=authen())
942 screen_name = g['stuff'].split()[0]
b8c1f42a
O
943 if screen_name.startswith('@'):
944 t.blocks.destroy(
945 screen_name=screen_name[1:],
946 include_entities=False,
947 skip_status=True)
948 printNicely(green('Unblock ' + screen_name + ' success!'))
305ce127 949 else:
b8c1f42a 950 printNicely(red('A name should begin with a \'@\''))
305ce127 951
952
953def report():
954 """
955 Report a user as a spam account
956 """
957 t = Twitter(auth=authen())
958 screen_name = g['stuff'].split()[0]
b8c1f42a
O
959 if screen_name.startswith('@'):
960 t.users.report_spam(
961 screen_name=screen_name[1:])
962 printNicely(green('You reported ' + screen_name + '.'))
305ce127 963 else:
964 printNicely(red('Sorry I can\'t understand.'))
965
966
8b8566d1
O
967def get_slug():
968 """
ee4c94b1 969 Get slug
8b8566d1 970 """
a8c5fce4 971 # Get list name
be4dba0e 972 list_name = raw_input(
973 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl=True))
8b8566d1
O
974 # Get list name and owner
975 try:
976 owner, slug = list_name.split('/')
977 if slug.startswith('@'):
978 slug = slug[1:]
979 return owner, slug
980 except:
a8c5fce4
O
981 printNicely(
982 light_magenta('List name should follow "@owner/list_name" format.'))
8b8566d1
O
983 raise Exception('Wrong list name')
984
56702c8f 985
434c2160 986def check_slug(list_name):
987 """
988 Check slug
989 """
990 # Get list name and owner
991 try:
992 owner, slug = list_name.split('/')
993 if slug.startswith('@'):
994 slug = slug[1:]
995 return owner, slug
996 except:
997 printNicely(
998 light_magenta('List name should follow "@owner/list_name" format.'))
999 raise Exception('Wrong list name')
8b8566d1 1000
56702c8f 1001
2d341029
O
1002def show_lists(t):
1003 """
422dd385 1004 List list
2d341029
O
1005 """
1006 rel = t.lists.list(screen_name=g['original_name'])
1007 if rel:
1008 print_list(rel)
1009 else:
1010 printNicely(light_magenta('You belong to no lists :)'))
1011
1012
1013def list_home(t):
1014 """
1015 List home
1016 """
8b8566d1 1017 owner, slug = get_slug()
2d341029 1018 res = t.lists.statuses(
422dd385
O
1019 slug=slug,
1020 owner_screen_name=owner,
1021 count=c['LIST_MAX'],
2d341029 1022 include_entities=False)
7304256c 1023 for tweet in reversed(res):
2d341029
O
1024 draw(t=tweet)
1025 printNicely('')
1026
1027
1028def list_members(t):
1029 """
1030 List members
1031 """
8b8566d1 1032 owner, slug = get_slug()
422dd385 1033 # Get members
2d341029
O
1034 rel = {}
1035 next_cursor = -1
422dd385 1036 while next_cursor != 0:
2d341029 1037 m = t.lists.members(
422dd385
O
1038 slug=slug,
1039 owner_screen_name=owner,
1040 cursor=next_cursor,
2d341029
O
1041 include_entities=False)
1042 for u in m['users']:
1043 rel[u['name']] = '@' + u['screen_name']
1044 next_cursor = m['next_cursor']
1045 printNicely('All: ' + str(len(rel)) + ' members.')
1046 for name in rel:
1047 user = ' ' + cycle_color(name)
422dd385 1048 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
1049 printNicely(user)
1050
1051
1052def list_subscribers(t):
1053 """
1054 List subscribers
1055 """
8b8566d1 1056 owner, slug = get_slug()
422dd385 1057 # Get subscribers
2d341029
O
1058 rel = {}
1059 next_cursor = -1
422dd385 1060 while next_cursor != 0:
2d341029 1061 m = t.lists.subscribers(
422dd385
O
1062 slug=slug,
1063 owner_screen_name=owner,
1064 cursor=next_cursor,
2d341029
O
1065 include_entities=False)
1066 for u in m['users']:
1067 rel[u['name']] = '@' + u['screen_name']
1068 next_cursor = m['next_cursor']
1069 printNicely('All: ' + str(len(rel)) + ' subscribers.')
1070 for name in rel:
1071 user = ' ' + cycle_color(name)
422dd385 1072 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
1073 printNicely(user)
1074
1075
422dd385
O
1076def list_add(t):
1077 """
1078 Add specific user to a list
1079 """
8b8566d1 1080 owner, slug = get_slug()
422dd385 1081 # Add
be4dba0e 1082 user_name = raw_input(
1083 light_magenta(
1084 'Give me name of the newbie: ',
1085 rl=True))
422dd385
O
1086 if user_name.startswith('@'):
1087 user_name = user_name[1:]
1088 try:
1089 t.lists.members.create(
1090 slug=slug,
1091 owner_screen_name=owner,
1092 screen_name=user_name)
d6cc4c67 1093 printNicely(green('Added.'))
422dd385 1094 except:
7a8a52fc 1095 debug_option()
422dd385
O
1096 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1097
1098
2d341029
O
1099def list_remove(t):
1100 """
1101 Remove specific user from a list
1102 """
8b8566d1 1103 owner, slug = get_slug()
2d341029 1104 # Remove
be4dba0e 1105 user_name = raw_input(
1106 light_magenta(
1107 'Give me name of the unlucky one: ',
1108 rl=True))
422dd385
O
1109 if user_name.startswith('@'):
1110 user_name = user_name[1:]
2d341029
O
1111 try:
1112 t.lists.members.destroy(
422dd385
O
1113 slug=slug,
1114 owner_screen_name=owner,
1115 screen_name=user_name)
d6cc4c67 1116 printNicely(green('Gone.'))
422dd385 1117 except:
7a8a52fc 1118 debug_option()
422dd385
O
1119 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1120
1121
1122def list_subscribe(t):
1123 """
1124 Subscribe to a list
1125 """
8b8566d1 1126 owner, slug = get_slug()
422dd385
O
1127 # Subscribe
1128 try:
1129 t.lists.subscribers.create(
1130 slug=slug,
1131 owner_screen_name=owner)
d6cc4c67 1132 printNicely(green('Done.'))
422dd385 1133 except:
7a8a52fc 1134 debug_option()
422dd385
O
1135 printNicely(
1136 light_magenta('I\'m sorry you can not subscribe to this list.'))
1137
1138
1139def list_unsubscribe(t):
1140 """
1141 Unsubscribe a list
1142 """
8b8566d1 1143 owner, slug = get_slug()
422dd385
O
1144 # Subscribe
1145 try:
1146 t.lists.subscribers.destroy(
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 unsubscribe to this list.'))
1154
1155
1156def list_own(t):
1157 """
1158 List own
1159 """
1160 rel = []
1161 next_cursor = -1
1162 while next_cursor != 0:
1163 res = t.lists.ownerships(
1164 screen_name=g['original_name'],
1165 cursor=next_cursor)
1166 rel += res['lists']
1167 next_cursor = res['next_cursor']
1168 if rel:
1169 print_list(rel)
1170 else:
1171 printNicely(light_magenta('You own no lists :)'))
1172
1173
1174def list_new(t):
1175 """
1176 Create a new list
1177 """
be4dba0e 1178 name = raw_input(light_magenta('New list\'s name: ', rl=True))
1179 mode = raw_input(
1180 light_magenta(
1181 'New list\'s mode (public/private): ',
1182 rl=True))
1183 description = raw_input(
1184 light_magenta(
1185 'New list\'s description: ',
1186 rl=True))
422dd385
O
1187 try:
1188 t.lists.create(
1189 name=name,
1190 mode=mode,
1191 description=description)
d6cc4c67 1192 printNicely(green(name + ' list is created.'))
422dd385 1193 except:
7a8a52fc 1194 debug_option()
422dd385
O
1195 printNicely(red('Oops something is wrong with Twitter :('))
1196
1197
1198def list_update(t):
1199 """
1200 Update a list
1201 """
be4dba0e 1202 slug = raw_input(
1203 light_magenta(
1204 'Your list that you want to update: ',
1205 rl=True))
1206 name = raw_input(
1207 light_magenta(
1208 'Update name (leave blank to unchange): ',
1209 rl=True))
1210 mode = raw_input(light_magenta('Update mode (public/private): ', rl=True))
1211 description = raw_input(light_magenta('Update description: ', rl=True))
422dd385
O
1212 try:
1213 if name:
1214 t.lists.update(
1215 slug='-'.join(slug.split()),
1216 owner_screen_name=g['original_name'],
1217 name=name,
1218 mode=mode,
1219 description=description)
1220 else:
1221 t.lists.update(
1222 slug=slug,
1223 owner_screen_name=g['original_name'],
1224 mode=mode,
1225 description=description)
d6cc4c67 1226 printNicely(green(slug + ' list is updated.'))
3c85d8fc 1227 except:
7a8a52fc 1228 debug_option()
422dd385
O
1229 printNicely(red('Oops something is wrong with Twitter :('))
1230
1231
1232def list_delete(t):
1233 """
1234 Delete a list
1235 """
be4dba0e 1236 slug = raw_input(
1237 light_magenta(
1238 'Your list that you want to delete: ',
1239 rl=True))
422dd385
O
1240 try:
1241 t.lists.destroy(
1242 slug='-'.join(slug.split()),
1243 owner_screen_name=g['original_name'])
d6cc4c67 1244 printNicely(green(slug + ' list is deleted.'))
2d341029 1245 except:
7a8a52fc 1246 debug_option()
422dd385 1247 printNicely(red('Oops something is wrong with Twitter :('))
2d341029
O
1248
1249
e3927852 1250def twitterlist():
2d341029
O
1251 """
1252 Twitter's list
1253 """
1254 t = Twitter(auth=authen())
1255 # List all lists or base on action
1256 try:
1257 g['list_action'] = g['stuff'].split()[0]
1258 except:
1259 show_lists(t)
1260 return
422dd385 1261 # Sub-function
2d341029
O
1262 action_ary = {
1263 'home': list_home,
1264 'all_mem': list_members,
1265 'all_sub': list_subscribers,
422dd385 1266 'add': list_add,
2d341029 1267 'rm': list_remove,
422dd385
O
1268 'sub': list_subscribe,
1269 'unsub': list_unsubscribe,
1270 'own': list_own,
1271 'new': list_new,
1272 'update': list_update,
1273 'del': list_delete,
2d341029
O
1274 }
1275 try:
1276 return action_ary[g['list_action']](t)
3c85d8fc 1277 except:
8b8566d1 1278 printNicely(red('Please try again.'))
2d341029
O
1279
1280
fd87ddac
O
1281def switch():
1282 """
1283 Switch stream
1284 """
1285 try:
1286 target = g['stuff'].split()[0]
1287 # Filter and ignore
1288 args = parse_arguments()
1289 try:
1290 if g['stuff'].split()[-1] == '-f':
1291 guide = 'To ignore an option, just hit Enter key.'
1292 printNicely(light_magenta(guide))
1293 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
1294 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1295 args.filter = filter(None, only.split(','))
1296 args.ignore = filter(None, ignore.split(','))
fd87ddac
O
1297 except:
1298 printNicely(red('Sorry, wrong format.'))
1299 return
56702c8f 1300 # Kill old thread
1301 g['stream_stop'] = True
69b6ab70 1302 try:
56702c8f 1303 stuff = g['stuff'].split()[1]
1304 except:
1305 stuff = None
1306 # Spawn new thread
1307 spawn_dict = {
1308 'public': spawn_public_stream,
1309 'list': spawn_list_stream,
1310 'mine': spawn_personal_stream,
1311 }
1312 spawn_dict.get(target)(args, stuff)
050a294e 1313 except:
ee4c94b1 1314 debug_option()
fd87ddac
O
1315 printNicely(red('Sorry I can\'t understand.'))
1316
1317
813a5d80 1318def cal():
1319 """
1320 Unix's command `cal`
1321 """
1322 # Format
1323 rel = os.popen('cal').read().split('\n')
1324 month = rel.pop(0)
813a5d80 1325 date = rel.pop(0)
2a0cabee 1326 show_calendar(month, date, rel)
813a5d80 1327
1328
fd87ddac
O
1329def theme():
1330 """
1331 List and change theme
1332 """
1333 if not g['stuff']:
1334 # List themes
1335 for theme in g['themes']:
1336 line = light_magenta(theme)
1337 if c['THEME'] == theme:
1338 line = ' ' * 2 + light_yellow('* ') + line
1339 else:
1340 line = ' ' * 4 + line
1341 printNicely(line)
1342 else:
1343 # Change theme
1344 try:
1345 # Load new theme
1346 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1347 # Redefine decorated_name
1348 g['decorated_name'] = lambda x: color_func(
1349 c['DECORATED_NAME'])(
1350 '[' + x + ']: ')
1351 printNicely(green('Theme changed.'))
1352 except:
1353 printNicely(red('No such theme exists.'))
1354
1355
29fd0be6
O
1356def config():
1357 """
1358 Browse and change config
1359 """
1360 all_config = get_all_config()
1361 g['stuff'] = g['stuff'].strip()
1362 # List all config
1363 if not g['stuff']:
1364 for k in all_config:
a8c5fce4 1365 line = ' ' * 2 + \
d6cc4c67 1366 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1367 printNicely(line)
1368 guide = 'Detailed explanation can be found at ' + \
a8c5fce4
O
1369 color_func(c['TWEET']['link'])(
1370 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
29fd0be6
O
1371 printNicely(guide)
1372 # Print specific config
1373 elif len(g['stuff'].split()) == 1:
1374 if g['stuff'] in all_config:
1375 k = g['stuff']
a8c5fce4 1376 line = ' ' * 2 + \
d6cc4c67 1377 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1378 printNicely(line)
1379 else:
fe9bb33b 1380 printNicely(red('No such config key.'))
29fd0be6
O
1381 # Print specific config's default value
1382 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1383 key = g['stuff'].split()[0]
fe9bb33b 1384 try:
1385 value = get_default_config(key)
d6cc4c67 1386 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
fe9bb33b 1387 printNicely(line)
050a294e
O
1388 except:
1389 debug_option()
1390 printNicely(red('Just can not get the default.'))
fe9bb33b 1391 # Delete specific config key in config file
1392 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1393 key = g['stuff'].split()[0]
1394 try:
1395 delete_config(key)
d6cc4c67 1396 printNicely(green('Config key is dropped.'))
050a294e
O
1397 except:
1398 debug_option()
1399 printNicely(red('Just can not drop the key.'))
29fd0be6 1400 # Set specific config
a8c5fce4 1401 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
29fd0be6
O
1402 key = g['stuff'].split()[0]
1403 value = g['stuff'].split()[-1]
ceec8593 1404 if key == 'THEME' and not validate_theme(value):
1405 printNicely(red('Invalid theme\'s value.'))
1406 return
3c01ba57 1407 try:
a8c5fce4 1408 set_config(key, value)
050a294e 1409 # Keys that needs to be apply immediately
ceec8593 1410 if key == 'THEME':
baec5f50 1411 c['THEME'] = reload_theme(value, c['THEME'])
ceec8593 1412 g['decorated_name'] = lambda x: color_func(
a8e71259 1413 c['DECORATED_NAME'])('[' + x + ']: ')
050a294e 1414 elif key == 'PREFIX':
063f6bb1 1415 g['PREFIX'] = u2str(emojize(format_prefix(
1416 listname=g['listname'],
1417 keyword=g['keyword']
1418 )))
a8e71259 1419 reload_config()
d6cc4c67 1420 printNicely(green('Updated successfully.'))
050a294e
O
1421 except:
1422 debug_option()
1423 printNicely(red('Just can not set the key.'))
29fd0be6
O
1424 else:
1425 printNicely(light_magenta('Sorry I can\'s understand.'))
1426
1427
2d341029 1428def help_discover():
f405a7d0 1429 """
2d341029 1430 Discover the world
f405a7d0 1431 """
7e4ccbf3 1432 s = ' ' * 2
1f24a05a 1433 # Discover the world
2d341029 1434 usage = '\n'
8bc30efd 1435 usage += s + grey(u'\u266A' + ' Discover the world \n')
c075e6dc
O
1436 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1437 'You can try ' + light_green('trend US') + ' or ' + \
1438 light_green('trend JP Tokyo') + '.\n'
1439 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1440 light_green('home 7') + ' will show 7 tweets.\n'
99cd1fba
O
1441 usage += s * 2 + \
1442 light_green('notification') + ' will show your recent notification.\n'
c075e6dc
O
1443 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1444 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1445 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
8bc30efd 1446 magenta('@mdo') + '.\n'
c075e6dc 1447 usage += s * 2 + light_green('view @mdo') + \
8bc30efd 1448 ' will show ' + magenta('@mdo') + '\'s home.\n'
03e08f86
O
1449 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1450 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1451 'Search can be performed with or without hashtag.\n'
2d341029
O
1452 printNicely(usage)
1453
8bc30efd 1454
2d341029
O
1455def help_tweets():
1456 """
1457 Tweets
1458 """
1459 s = ' ' * 2
1f24a05a 1460 # Tweet
2d341029 1461 usage = '\n'
8bc30efd 1462 usage += s + grey(u'\u266A' + ' Tweets \n')
c075e6dc
O
1463 usage += s * 2 + light_green('t oops ') + \
1464 'will tweet "' + light_yellow('oops') + '" immediately.\n'
7e4ccbf3 1465 usage += s * 2 + \
c075e6dc
O
1466 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1467 light_yellow('[id=12]') + '.\n'
1f24a05a 1468 usage += s * 2 + \
80b70d60
O
1469 light_green('quote 12 ') + ' will quote the tweet with ' + \
1470 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1471 'the quote will be canceled.\n'
1472 usage += s * 2 + \
c075e6dc
O
1473 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1474 light_yellow('[id=12]') + '.\n'
fd87ddac
O
1475 usage += s * 2 + light_green('conversation 12') + ' will show the chain of ' + \
1476 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
c075e6dc 1477 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
ba6c09d1
O
1478 light_yellow('oops') + '" to the owner of the tweet with ' + \
1479 light_yellow('[id=12]') + '.\n'
1480 usage += s * 2 + light_green('repall 12 oops') + ' will reply "' + \
1481 light_yellow('oops') + '" to all people in the tweet with ' + \
c075e6dc 1482 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1483 usage += s * 2 + \
c075e6dc
O
1484 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1485 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1486 usage += s * 2 + \
c075e6dc
O
1487 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1488 light_yellow('[id=12]') + '.\n'
8bc30efd 1489 usage += s * 2 + \
66fe9f75 1490 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1491 light_yellow('[id=12]') + '.\n'
413857b5 1492 usage += s * 2 + \
c075e6dc
O
1493 light_green('del 12 ') + ' will delete tweet with ' + \
1494 light_yellow('[id=12]') + '.\n'
1495 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1496 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
80b70d60
O
1497 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1498 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
2d341029 1499 printNicely(usage)
8bc30efd 1500
2d341029
O
1501
1502def help_messages():
1503 """
1504 Messages
1505 """
1506 s = ' ' * 2
5b2c4faf 1507 # Direct message
2d341029 1508 usage = '\n'
8bc30efd 1509 usage += s + grey(u'\u266A' + ' Direct messages \n')
c075e6dc
O
1510 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1511 light_green('inbox 7') + ' will show newest 7 messages.\n'
03c0d30b 1512 usage += s * 2 + light_green('thread 2') + ' will show full thread with ' + \
1513 light_yellow('[thread_id=2]') + '.\n'
c075e6dc 1514 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
8bc30efd 1515 magenta('@dtvd88') + '.\n'
c075e6dc
O
1516 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1517 light_yellow('[message_id=5]') + '.\n'
2d341029 1518 printNicely(usage)
8bc30efd 1519
2d341029
O
1520
1521def help_friends_and_followers():
1522 """
1523 Friends and Followers
1524 """
1525 s = ' ' * 2
8bc30efd 1526 # Follower and following
2d341029 1527 usage = '\n'
cdccb0d6 1528 usage += s + grey(u'\u266A' + ' Friends and followers \n')
8bc30efd 1529 usage += s * 2 + \
c075e6dc 1530 light_green('ls fl') + \
8bc30efd 1531 ' will list all followers (people who are following you).\n'
1532 usage += s * 2 + \
c075e6dc 1533 light_green('ls fr') + \
8bc30efd 1534 ' will list all friends (people who you are following).\n'
c075e6dc 1535 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
305ce127 1536 magenta('@dtvd88') + '.\n'
c075e6dc 1537 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
305ce127 1538 magenta('@dtvd88') + '.\n'
c075e6dc 1539 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
5b2c4faf 1540 magenta('@dtvd88') + '.\n'
c075e6dc 1541 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
5b2c4faf 1542 magenta('@dtvd88') + '.\n'
c075e6dc
O
1543 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1544 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
305ce127 1545 magenta('@dtvd88') + '.\n'
c075e6dc 1546 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
305ce127 1547 magenta('@dtvd88') + '.\n'
c075e6dc 1548 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
305ce127 1549 magenta('@dtvd88') + ' as a spam account.\n'
2d341029
O
1550 printNicely(usage)
1551
1552
1553def help_list():
1554 """
1555 Lists
1556 """
1557 s = ' ' * 2
1558 # Twitter list
1559 usage = '\n'
1560 usage += s + grey(u'\u266A' + ' Twitter list\n')
1561 usage += s * 2 + light_green('list') + \
1562 ' will show all lists you are belong to.\n'
1563 usage += s * 2 + light_green('list home') + \
bef33491 1564 ' will show timeline of list. You will be asked for list\'s name.\n'
a65bd34c 1565 usage += s * 2 + light_green('list all_mem') + \
2d341029 1566 ' will show list\'s all members.\n'
a65bd34c 1567 usage += s * 2 + light_green('list all_sub') + \
2d341029 1568 ' will show list\'s all subscribers.\n'
422dd385
O
1569 usage += s * 2 + light_green('list add') + \
1570 ' will add specific person to a list owned by you.' + \
1571 ' You will be asked for list\'s name and person\'s name.\n'
2d341029
O
1572 usage += s * 2 + light_green('list rm') + \
1573 ' will remove specific person from a list owned by you.' + \
1574 ' You will be asked for list\'s name and person\'s name.\n'
422dd385
O
1575 usage += s * 2 + light_green('list sub') + \
1576 ' will subscribe you to a specific list.\n'
1577 usage += s * 2 + light_green('list unsub') + \
1578 ' will unsubscribe you from a specific list.\n'
1579 usage += s * 2 + light_green('list own') + \
1580 ' will show all list owned by you.\n'
1581 usage += s * 2 + light_green('list new') + \
1582 ' will create a new list.\n'
1583 usage += s * 2 + light_green('list update') + \
1584 ' will update a list owned by you.\n'
1585 usage += s * 2 + light_green('list del') + \
1586 ' will delete a list owned by you.\n'
2d341029 1587 printNicely(usage)
8bc30efd 1588
2d341029
O
1589
1590def help_stream():
1591 """
1592 Stream switch
1593 """
1594 s = ' ' * 2
8bc30efd 1595 # Switch
2d341029 1596 usage = '\n'
8bc30efd 1597 usage += s + grey(u'\u266A' + ' Switching streams \n')
c075e6dc 1598 usage += s * 2 + light_green('switch public #AKB') + \
48a25fe8 1599 ' will switch to public stream and follow "' + \
c075e6dc
O
1600 light_yellow('AKB') + '" keyword.\n'
1601 usage += s * 2 + light_green('switch mine') + \
48a25fe8 1602 ' will switch to your personal stream.\n'
c075e6dc 1603 usage += s * 2 + light_green('switch mine -f ') + \
48a25fe8 1604 ' will prompt to enter the filter.\n'
c075e6dc 1605 usage += s * 3 + light_yellow('Only nicks') + \
48a25fe8 1606 ' filter will decide nicks will be INCLUDE ONLY.\n'
c075e6dc 1607 usage += s * 3 + light_yellow('Ignore nicks') + \
48a25fe8 1608 ' filter will decide nicks will be EXCLUDE.\n'
ee4c94b1
O
1609 usage += s * 2 + light_green('switch list') + \
1610 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
2d341029
O
1611 printNicely(usage)
1612
1613
1614def help():
1615 """
1616 Help
1617 """
1618 s = ' ' * 2
1619 h, w = os.popen('stty size', 'r').read().split()
2d341029
O
1620 # Start
1621 usage = '\n'
1622 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1623 usage += s + '-' * (int(w) - 4) + '\n'
1624 usage += s + 'You are ' + \
1625 light_yellow('already') + ' on your personal stream.\n'
1626 usage += s + 'Any update from Twitter will show up ' + \
1627 light_yellow('immediately') + '.\n'
37d1047f 1628 usage += s + 'In addition, following commands are available right now:\n'
2d341029
O
1629 # Twitter help section
1630 usage += '\n'
1631 usage += s + grey(u'\u266A' + ' Twitter help\n')
1632 usage += s * 2 + light_green('h discover') + \
1633 ' will show help for discover commands.\n'
1634 usage += s * 2 + light_green('h tweets') + \
1635 ' will show help for tweets commands.\n'
1636 usage += s * 2 + light_green('h messages') + \
1637 ' will show help for messages commands.\n'
1638 usage += s * 2 + light_green('h friends_and_followers') + \
1639 ' will show help for friends and followers commands.\n'
1640 usage += s * 2 + light_green('h list') + \
1641 ' will show help for list commands.\n'
1642 usage += s * 2 + light_green('h stream') + \
1643 ' will show help for stream commands.\n'
1f24a05a 1644 # Smart shell
1645 usage += '\n'
1646 usage += s + grey(u'\u266A' + ' Smart shell\n')
c075e6dc 1647 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1f24a05a 1648 'will be evaluate by Python interpreter.\n'
c075e6dc 1649 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1f24a05a 1650 ' for current month.\n'
29fd0be6 1651 # Config
1f24a05a 1652 usage += '\n'
29fd0be6
O
1653 usage += s + grey(u'\u266A' + ' Config \n')
1654 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
c075e6dc 1655 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
632c6fa5 1656 ' theme immediately.\n'
29fd0be6
O
1657 usage += s * 2 + light_green('config') + ' will list all config.\n'
1658 usage += s * 3 + \
1659 light_green('config ASCII_ART') + ' will output current value of ' +\
a8c5fce4 1660 light_yellow('ASCII_ART') + ' config key.\n'
29fd0be6 1661 usage += s * 3 + \
fe9bb33b 1662 light_green('config TREND_MAX default') + ' will output default value of ' + \
1663 light_yellow('TREND_MAX') + ' config key.\n'
1664 usage += s * 3 + \
1665 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1666 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
29fd0be6 1667 usage += s * 3 + \
fe9bb33b 1668 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1669 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1670 light_yellow('True') + '.\n'
29fd0be6
O
1671 # Screening
1672 usage += '\n'
1673 usage += s + grey(u'\u266A' + ' Screening \n')
c075e6dc 1674 usage += s * 2 + light_green('h') + ' will show this help again.\n'
d6cc4c67
O
1675 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1676 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
c075e6dc 1677 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
806f42df 1678 usage += s * 2 + light_green('v') + ' will show version info.\n'
c075e6dc 1679 usage += s * 2 + light_green('q') + ' will quit.\n'
8bc30efd 1680 # End
1681 usage += '\n'
7e4ccbf3 1682 usage += s + '-' * (int(w) - 4) + '\n'
8bc30efd 1683 usage += s + 'Have fun and hang tight! \n'
2d341029
O
1684 # Show help
1685 d = {
422dd385
O
1686 'discover': help_discover,
1687 'tweets': help_tweets,
1688 'messages': help_messages,
1689 'friends_and_followers': help_friends_and_followers,
1690 'list': help_list,
1691 'stream': help_stream,
2d341029
O
1692 }
1693 if g['stuff']:
baec5f50 1694 d.get(
1695 g['stuff'].strip(),
1696 lambda: printNicely(red('No such command.'))
3d48702f 1697 )()
2d341029
O
1698 else:
1699 printNicely(usage)
f405a7d0
O
1700
1701
d6cc4c67
O
1702def pause():
1703 """
1704 Pause stream display
1705 """
4dc385b5 1706 g['pause'] = True
d6cc4c67
O
1707 printNicely(green('Stream is paused'))
1708
1709
1710def replay():
1711 """
1712 Replay stream
1713 """
4dc385b5 1714 g['pause'] = False
d6cc4c67
O
1715 printNicely(green('Stream is running back now'))
1716
1717
843647ad 1718def clear():
f405a7d0 1719 """
7b674cef 1720 Clear screen
f405a7d0 1721 """
843647ad 1722 os.system('clear')
f405a7d0
O
1723
1724
843647ad 1725def quit():
b8dda704
O
1726 """
1727 Exit all
1728 """
4c025026 1729 try:
1730 save_history()
4c025026 1731 printNicely(green('See you next time :)'))
1732 except:
1733 pass
843647ad 1734 sys.exit()
b8dda704
O
1735
1736
321a893a
O
1737def changelog_notify():
1738 # For v1.2.8. Hardcoded here but will improve later
1739 notice = light_yellow('Hey! RS just ')
1740 notice += light_green('doubled ')
1741 notice += light_yellow('pixels for higher image resolution. Upgrade and try')
1742 notice += light_green(' -iot ')
1743 notice += light_yellow('and you will like it for sure :)')
1744 printNicely(notice)
1745
1746
94a5f62e 1747def reset():
f405a7d0 1748 """
94a5f62e 1749 Reset prefix of line
f405a7d0 1750 """
c91f75f2 1751 if g['reset']:
a8e71259 1752 if c.get('USER_JSON_ERROR'):
1753 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1754 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1755 printNicely('')
321a893a
O
1756 if not g['using_latest']:
1757 changelog_notify()
e3885f55 1758 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
c91f75f2 1759 g['reset'] = False
d0a726d6 1760 try:
779b0640 1761 printNicely(str(eval(g['cmd'])))
2a0cabee 1762 except Exception:
d0a726d6 1763 pass
54277114
O
1764
1765
f1c1dfea
O
1766# Command set
1767cmdset = [
1768 'switch',
1769 'trend',
1770 'home',
99cd1fba 1771 'notification',
f1c1dfea
O
1772 'view',
1773 'mentions',
1774 't',
1775 'rt',
1776 'quote',
1777 'allrt',
fd87ddac 1778 'conversation',
f1c1dfea
O
1779 'fav',
1780 'rep',
ba6c09d1 1781 'repall',
f1c1dfea
O
1782 'del',
1783 'ufav',
413857b5 1784 'share',
f1c1dfea
O
1785 's',
1786 'mes',
1787 'show',
1788 'open',
1789 'ls',
1790 'inbox',
67c663f8 1791 'thread',
f1c1dfea
O
1792 'trash',
1793 'whois',
1794 'fl',
1795 'ufl',
1796 'mute',
1797 'unmute',
1798 'muting',
1799 'block',
1800 'unblock',
1801 'report',
1802 'list',
1803 'cal',
1804 'config',
1805 'theme',
1806 'h',
1807 'p',
1808 'r',
1809 'c',
806f42df 1810 'v',
bf766c7b 1811 'q',
f1c1dfea
O
1812]
1813
1814# Handle function set
1815funcset = [
1816 switch,
1817 trend,
1818 home,
99cd1fba 1819 notification,
f1c1dfea
O
1820 view,
1821 mentions,
1822 tweet,
1823 retweet,
1824 quote,
1825 allretweet,
fd87ddac 1826 conversation,
f1c1dfea
O
1827 favorite,
1828 reply,
ba6c09d1 1829 reply_all,
f1c1dfea
O
1830 delete,
1831 unfavorite,
413857b5 1832 share,
f1c1dfea
O
1833 search,
1834 message,
1835 show,
1836 urlopen,
1837 ls,
1838 inbox,
67c663f8 1839 thread,
f1c1dfea
O
1840 trash,
1841 whois,
1842 follow,
1843 unfollow,
1844 mute,
1845 unmute,
1846 muting,
1847 block,
1848 unblock,
1849 report,
1850 twitterlist,
1851 cal,
1852 config,
1853 theme,
1854 help,
1855 pause,
1856 replay,
1857 clear,
bf766c7b 1858 upgrade_center,
806f42df 1859 quit,
f1c1dfea
O
1860]
1861
1862
94a5f62e 1863def process(cmd):
54277114 1864 """
94a5f62e 1865 Process switch
54277114 1866 """
f1c1dfea 1867 return dict(zip(cmdset, funcset)).get(cmd, reset)
94a5f62e 1868
1869
1870def listen():
42fde775 1871 """
1872 Listen to user's input
1873 """
d51b4107
O
1874 d = dict(zip(
1875 cmdset,
1876 [
ee4c94b1 1877 ['public', 'mine', 'list'], # switch
4592d231 1878 [], # trend
7e4ccbf3 1879 [], # home
99cd1fba 1880 [], # notification
7e4ccbf3 1881 ['@'], # view
305ce127 1882 [], # mentions
7e4ccbf3 1883 [], # tweet
1884 [], # retweet
80b70d60 1885 [], # quote
1f24a05a 1886 [], # allretweet
fd87ddac 1887 [], # conversation
f5677fb1 1888 [], # favorite
7e4ccbf3 1889 [], # reply
ba6c09d1 1890 [], # reply_all
7e4ccbf3 1891 [], # delete
f5677fb1 1892 [], # unfavorite
413857b5 1893 [], # url
7e4ccbf3 1894 ['#'], # search
305ce127 1895 ['@'], # message
f5677fb1 1896 ['image'], # show image
80b70d60 1897 [''], # open url
305ce127 1898 ['fl', 'fr'], # list
1899 [], # inbox
03c0d30b 1900 [i for i in g['message_threads']], # sent
305ce127 1901 [], # trash
e2b81717 1902 ['@'], # whois
affcb149
O
1903 ['@'], # follow
1904 ['@'], # unfollow
5b2c4faf 1905 ['@'], # mute
1906 ['@'], # unmute
1907 ['@'], # muting
305ce127 1908 ['@'], # block
1909 ['@'], # unblock
1910 ['@'], # report
422dd385
O
1911 [
1912 'home',
1913 'all_mem',
1914 'all_sub',
1915 'add',
1916 'rm',
1917 'sub',
1918 'unsub',
1919 'own',
1920 'new',
1921 'update',
1922 'del'
1923 ], # list
813a5d80 1924 [], # cal
a8c5fce4 1925 [key for key in dict(get_all_config())], # config
ceec8593 1926 g['themes'], # theme
422dd385
O
1927 [
1928 'discover',
1929 'tweets',
1930 'messages',
1931 'friends_and_followers',
1932 'list',
1933 'stream'
1934 ], # help
d6cc4c67
O
1935 [], # pause
1936 [], # reconnect
7e4ccbf3 1937 [], # clear
7cfb8af4 1938 [], # version
806f42df 1939 [], # quit
d51b4107 1940 ]
7e4ccbf3 1941 ))
d51b4107 1942 init_interactive_shell(d)
f5677fb1 1943 read_history()
819569e8 1944 reset()
b2b933a9 1945 while True:
b8c1f42a 1946 try:
39b8e6b3
O
1947 # raw_input
1948 if g['prefix']:
aa452ee9 1949 # Only use PREFIX as a string with raw_input
c285decf 1950 line = raw_input(g['decorated_name'](g['PREFIX']))
39b8e6b3
O
1951 else:
1952 line = raw_input()
1953 # Save cmd to compare with readline buffer
1954 g['cmd'] = line.strip()
1955 # Get short cmd to pass to handle function
1956 try:
1957 cmd = line.split()[0]
1958 except:
1959 cmd = ''
9683e61d 1960 # Lock the semaphore
99b52f5f 1961 c['lock'] = True
9683e61d 1962 # Save cmd to global variable and call process
b8c1f42a 1963 g['stuff'] = ' '.join(line.split()[1:])
fc460124
BJ
1964 # Check tweet length
1965 if check_tweet_length():
1966 # Process the command
1967 process(cmd)()
1968 # Not re-display
1969 if cmd in ['switch', 't', 'rt', 'rep']:
1970 g['prefix'] = False
1971 else:
1972 g['prefix'] = True
9683e61d 1973 # Release the semaphore lock
99b52f5f 1974 c['lock'] = False
39b8e6b3
O
1975 except EOFError:
1976 printNicely('')
eadd85a8 1977 except Exception:
7a8a52fc 1978 debug_option()
b8c1f42a 1979 printNicely(red('OMG something is wrong with Twitter right now.'))
ee444288 1980
54277114 1981
fc460124
BJ
1982def check_tweet_length():
1983 """
1984 Check tweet length (should be <= 140 chars)
1985 """
1986 length = len(g['stuff'])
1987 if length <= 140:
1988 return True
1989
1990 printNicely(red("Message is too long: %s chars" % length))
1991 return False
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]
56702c8f 2246 if target == 'mine' :
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()