quote and pause bug fix
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
e9f5200b
VNM
1import random
2import itertools
7500d90b 3import requests
7500d90b 4import time
8b3456f9 5import locale
6import arrow
59262e95 7import re
7500d90b 8
2da50cc4 9from twitter.util import printNicely
e9f5200b
VNM
10from functools import wraps
11from pyfiglet import figlet_format
7500d90b 12from dateutil import parser
2da50cc4 13from .c_image import *
7500d90b
VNM
14from .colors import *
15from .config import *
c3bab4ef 16from .py3patch import *
17
99b52f5f
O
18# Draw global variables
19dg = {}
1fdd6a5c 20
422dd385 21
e9f5200b
VNM
22def init_cycle():
23 """
24 Init the cycle
25 """
26 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
27 if not str(i).isdigit()
28 else term_color(int(i))
422dd385 29 for i in c['CYCLE_COLOR']]
5f22104f 30 return itertools.cycle(colors_shuffle)
1fdd6a5c 31
e9f5200b 32
59262e95 33def start_cycle():
2359c276
VNM
34 """
35 Notify from rainbow
36 """
99b52f5f
O
37 dg['cyc'] = init_cycle()
38 dg['cache'] = {}
2359c276
VNM
39
40
e9f5200b
VNM
41def order_rainbow(s):
42 """
43 Print a string with ordered color with each character
44 """
5f22104f 45 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
46 if not str(i).isdigit()
47 else term_color(int(i))
422dd385 48 for i in c['CYCLE_COLOR']]
5f22104f 49 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
c3bab4ef 50 return ''.join(colored)
e9f5200b
VNM
51
52
53def random_rainbow(s):
54 """
55 Print a string with random color with each character
56 """
5f22104f 57 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
58 if not str(i).isdigit()
59 else term_color(int(i))
422dd385 60 for i in c['CYCLE_COLOR']]
5f22104f 61 colored = [random.choice(colors_shuffle)(i) for i in s]
c3bab4ef 62 return ''.join(colored)
e9f5200b
VNM
63
64
65def Memoize(func):
66 """
67 Memoize decorator
68 """
e9f5200b
VNM
69 @wraps(func)
70 def wrapper(*args):
99b52f5f
O
71 if args not in dg['cache']:
72 dg['cache'][args] = func(*args)
73 return dg['cache'][args]
e9f5200b
VNM
74 return wrapper
75
76
77@Memoize
78def cycle_color(s):
79 """
80 Cycle the colors_shuffle
81 """
99b52f5f 82 return next(dg['cyc'])(s)
e9f5200b
VNM
83
84
85def ascii_art(text):
86 """
87 Draw the Ascii Art
88 """
89 fi = figlet_format(text, font='doom')
90 print('\n'.join(
99b52f5f 91 [next(dg['cyc'])(i) for i in fi.split('\n')]
e9f5200b
VNM
92 ))
93
94
92685d21 95def check_config():
ceec8593 96 """
97 Check if config is changed
98 """
99 changed = False
100 data = get_all_config()
101 for key in c:
102 if key in data:
103 if data[key] != c[key]:
104 changed = True
105 if changed:
106 reload_config()
107
108
109def validate_theme(theme):
110 """
111 Validate a theme exists or not
112 """
113 # Theme changed check
114 files = os.listdir(os.path.dirname(__file__) + '/colorset')
115 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
116 return theme in themes
92685d21 117
118
99b52f5f 119def reload_theme(value, prev):
4cf86720
VNM
120 """
121 Check current theme and update if necessary
122 """
99b52f5f 123 if value != prev:
1f2f6159 124 config = os.path.dirname(
99b52f5f 125 __file__) + '/colorset/' + value + '.json'
4cf86720
VNM
126 # Load new config
127 data = load_config(config)
a5301bc0
VNM
128 if data:
129 for d in data:
130 c[d] = data[d]
99b52f5f 131 # Restart color cycle and update config
ceec8593 132 start_cycle()
99b52f5f
O
133 set_config('THEME', value)
134 return value
135 return prev
7500d90b 136
fe08f905
VNM
137
138def color_func(func_name):
139 """
140 Call color function base on name
141 """
fa6e062d
O
142 if str(func_name).isdigit():
143 return term_color(int(func_name))
c3bab4ef 144 return globals()[func_name]
fe08f905
VNM
145
146
4dc385b5 147def draw(t, keyword=None, humanize=True, fil=[], ig=[]):
7500d90b
VNM
148 """
149 Draw the rainbow
150 """
99b52f5f 151 # Check config
92685d21 152 check_config()
c37c04a9 153
7500d90b
VNM
154 # Retrieve tweet
155 tid = t['id']
606def7e 156 text = t['text']
7500d90b
VNM
157 screen_name = t['user']['screen_name']
158 name = t['user']['name']
159 created_at = t['created_at']
160 favorited = t['favorited']
318cdd67
O
161 retweet_count = t['retweet_count']
162 favorite_count = t['favorite_count']
7500d90b 163 date = parser.parse(created_at)
8b3456f9 164 date = arrow.get(date).to('local')
165 if humanize:
166 lang, encode = locale.getdefaultlocale()
167 clock = arrow.get(date).to('local').humanize(locale=lang)
168 else:
169 try:
170 clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT']
171 except:
172 clock_format = '%Y/%m/%d %H:%M:%S'
173 clock = date.datetime.strftime(clock_format)
7500d90b 174
606def7e
BR
175 # Pull extended retweet text
176 try:
18df6e7f
O
177 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
178 t['retweeted_status']['text']
606def7e
BR
179 except:
180 pass
181
18df6e7f 182 # Unescape HTML character
606def7e
BR
183 text = unescape(text)
184
7500d90b
VNM
185 # Get expanded url
186 try:
187 expanded_url = []
188 url = []
189 urls = t['entities']['urls']
190 for u in urls:
191 expanded_url.append(u['expanded_url'])
192 url.append(u['url'])
193 except:
194 expanded_url = None
195 url = None
196
197 # Get media
198 try:
199 media_url = []
200 media = t['entities']['media']
201 for m in media:
202 media_url.append(m['media_url'])
203 except:
204 media_url = None
205
206 # Filter and ignore
207 screen_name = '@' + screen_name
e3927852
O
208 fil = list(set((fil or []) + c['ONLY_LIST']))
209 ig = list(set((ig or []) + c['IGNORE_LIST']))
7500d90b
VNM
210 if fil and screen_name not in fil:
211 return
212 if ig and screen_name in ig:
213 return
214
215 # Get rainbow id
99b52f5f
O
216 if tid not in c['tweet_dict']:
217 c['tweet_dict'].append(tid)
218 rid = len(c['tweet_dict']) - 1
219 else:
220 rid = c['tweet_dict'].index(tid)
7500d90b
VNM
221
222 # Format info
8c7ae594 223 name = cycle_color(name)
d6cc4c67 224 nick = color_func(c['TWEET']['nick'])(screen_name)
0d9977c7
O
225 clock = clock
226 id = str(rid)
8c7ae594 227 fav = ''
7500d90b 228 if favorited:
8c7ae594
O
229 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
230
7500d90b
VNM
231 tweet = text.split()
232 # Replace url
233 if expanded_url:
13e6b275 234 for index in xrange(len(expanded_url)):
c3bab4ef 235 tweet = lmap(
8141aca6 236 lambda x: expanded_url[index]
237 if x == url[index]
238 else x,
7500d90b
VNM
239 tweet)
240 # Highlight RT
c3bab4ef 241 tweet = lmap(
8141aca6 242 lambda x: color_func(c['TWEET']['rt'])(x)
243 if x == 'RT'
244 else x,
c075e6dc 245 tweet)
7500d90b 246 # Highlight screen_name
c3bab4ef 247 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 248 # Highlight link
c3bab4ef 249 tweet = lmap(
8141aca6 250 lambda x: color_func(c['TWEET']['link'])(x)
251 if x[0:4] == 'http'
252 else x,
c075e6dc 253 tweet)
4c025026 254 # Highlight hashtag
255 tweet = lmap(
8141aca6 256 lambda x: color_func(c['TWEET']['hashtag'])(x)
257 if x.startswith('#')
258 else x,
4c025026 259 tweet)
59262e95 260 # Highlight keyword
7500d90b 261 tweet = ' '.join(tweet)
59262e95 262 if keyword:
a8c5fce4 263 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
264 if roj:
265 occur = roj.group()
266 ary = tweet.split(occur)
b13c6a0d 267 delimiter = color_func(c['TWEET']['keyword'])(occur)
268 tweet = delimiter.join(ary)
7500d90b 269
8c7ae594 270 # Load config formater
318cdd67 271 formater = ''
8c7ae594
O
272 try:
273 formater = c['FORMAT']['TWEET']['DISPLAY']
7c437a0f
O
274 formater = name.join(formater.split('#name'))
275 formater = nick.join(formater.split('#nick'))
276 formater = fav.join(formater.split('#fav'))
277 formater = tweet.join(formater.split('#tweet'))
0d9977c7
O
278 # Change clock word
279 word = [w for w in formater.split() if '#clock' in w][0]
8141aca6 280 delimiter = color_func(c['TWEET']['clock'])(
281 clock.join(word.split('#clock')))
0d9977c7
O
282 formater = delimiter.join(formater.split(word))
283 # Change id word
284 word = [w for w in formater.split() if '#id' in w][0]
285 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
286 formater = delimiter.join(formater.split(word))
318cdd67
O
287 # Change retweet count word
288 word = [w for w in formater.split() if '#rt_count' in w][0]
289 delimiter = color_func(c['TWEET']['retweet_count'])(
290 str(retweet_count).join(word.split('#rt_count')))
291 formater = delimiter.join(formater.split(word))
292 # Change favorites count word
293 word = [w for w in formater.split() if '#fa_count' in w][0]
294 delimiter = color_func(c['TWEET']['favorite_count'])(
295 str(favorite_count).join(word.split('#fa_count')))
296 formater = delimiter.join(formater.split(word))
8c7ae594 297 except:
318cdd67 298 pass
7500d90b 299
8c7ae594
O
300 # Draw
301 printNicely(formater)
7500d90b
VNM
302
303 # Display Image
fe9bb33b 304 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 305 for mu in media_url:
17bc529d 306 try:
307 response = requests.get(mu)
77f1d210 308 image_to_display(BytesIO(response.content))
309 except Exception:
17bc529d 310 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
311
312
4dc385b5 313def print_message(m):
7500d90b
VNM
314 """
315 Print direct message
316 """
c37c04a9 317 # Retrieve message
7500d90b
VNM
318 sender_screen_name = '@' + m['sender_screen_name']
319 sender_name = m['sender']['name']
b2cde062 320 text = unescape(m['text'])
7500d90b
VNM
321 recipient_screen_name = '@' + m['recipient_screen_name']
322 recipient_name = m['recipient']['name']
323 mid = m['id']
324 date = parser.parse(m['created_at'])
8b3456f9 325 date = arrow.get(date).to('local').datetime
8c7ae594
O
326 clock_format = '%Y/%m/%d %H:%M:%S'
327 try:
328 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
329 except:
330 pass
331 clock = date.strftime(clock_format)
7500d90b
VNM
332
333 # Get rainbow id
99b52f5f
O
334 if mid not in c['message_dict']:
335 c['message_dict'].append(mid)
336 rid = len(c['message_dict']) - 1
337 else:
338 rid = c['message_dict'].index(mid)
7500d90b 339
6fa09c14 340 # Draw
8c7ae594
O
341 sender_name = cycle_color(sender_name)
342 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
343 recipient_name = cycle_color(recipient_name)
0d9977c7
O
344 recipient_nick = color_func(
345 c['MESSAGE']['recipient'])(recipient_screen_name)
8c7ae594 346 to = color_func(c['MESSAGE']['to'])('>>>')
0d9977c7
O
347 clock = clock
348 id = str(rid)
8c7ae594 349
c3bab4ef 350 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b 351
8c7ae594
O
352 # Load config formater
353 try:
354 formater = c['FORMAT']['MESSAGE']['DISPLAY']
0d9977c7
O
355 formater = sender_name.join(formater.split("#sender_name"))
356 formater = sender_nick.join(formater.split("#sender_nick"))
357 formater = to.join(formater.split("#to"))
358 formater = recipient_name.join(formater.split("#recipient_name"))
359 formater = recipient_nick.join(formater.split("#recipient_nick"))
360 formater = text.join(formater.split("#message"))
361 # Change clock word
362 word = [w for w in formater.split() if '#clock' in w][0]
8141aca6 363 delimiter = color_func(c['MESSAGE']['clock'])(
364 clock.join(word.split('#clock')))
0d9977c7
O
365 formater = delimiter.join(formater.split(word))
366 # Change id word
367 word = [w for w in formater.split() if '#id' in w][0]
368 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
369 formater = delimiter.join(formater.split(word))
8c7ae594
O
370 except:
371 printNicely(red('Wrong format in config.'))
372 return
373
374 # Draw
375 printNicely(formater)
7500d90b
VNM
376
377
fe9bb33b 378def show_profile(u):
7500d90b
VNM
379 """
380 Show a profile
381 """
382 # Retrieve info
383 name = u['name']
384 screen_name = u['screen_name']
385 description = u['description']
386 profile_image_url = u['profile_image_url']
387 location = u['location']
388 url = u['url']
389 created_at = u['created_at']
390 statuses_count = u['statuses_count']
391 friends_count = u['friends_count']
392 followers_count = u['followers_count']
6fa09c14 393
7500d90b 394 # Create content
c075e6dc
O
395 statuses_count = color_func(
396 c['PROFILE']['statuses_count'])(
397 str(statuses_count) +
398 ' tweets')
399 friends_count = color_func(
400 c['PROFILE']['friends_count'])(
401 str(friends_count) +
402 ' following')
403 followers_count = color_func(
404 c['PROFILE']['followers_count'])(
405 str(followers_count) +
406 ' followers')
7500d90b 407 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
408 user = cycle_color(
409 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
410 profile_image_raw_url = 'Profile photo: ' + \
411 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b 412 description = ''.join(
c3bab4ef 413 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
414 description = color_func(c['PROFILE']['description'])(description)
415 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
416 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b 417 date = parser.parse(created_at)
8b3456f9 418 lang, encode = locale.getdefaultlocale()
419 clock = arrow.get(date).to('local').humanize(locale=lang)
632c6fa5 420 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 421
7500d90b
VNM
422 # Format
423 line1 = u"{u:>{uw}}".format(
424 u=user,
425 uw=len(user) + 2,
426 )
427 line2 = u"{p:>{pw}}".format(
428 p=profile_image_raw_url,
429 pw=len(profile_image_raw_url) + 4,
430 )
431 line3 = u"{d:>{dw}}".format(
432 d=description,
433 dw=len(description) + 4,
434 )
435 line4 = u"{l:>{lw}}".format(
436 l=location,
437 lw=len(location) + 4,
438 )
439 line5 = u"{u:>{uw}}".format(
440 u=url,
441 uw=len(url) + 4,
442 )
443 line6 = u"{c:>{cw}}".format(
444 c=clock,
445 cw=len(clock) + 4,
446 )
6fa09c14 447
7500d90b
VNM
448 # Display
449 printNicely('')
450 printNicely(line1)
fe9bb33b 451 if c['IMAGE_ON_TERM']:
17bc529d 452 try:
453 response = requests.get(profile_image_url)
c37c04a9 454 image_to_display(BytesIO(response.content))
17bc529d 455 except:
456 pass
7500d90b
VNM
457 else:
458 printNicely(line2)
459 for line in [line3, line4, line5, line6]:
460 printNicely(line)
461 printNicely('')
462
463
464def print_trends(trends):
465 """
466 Display topics
467 """
632c6fa5 468 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
469 name = topic['name']
470 url = topic['url']
8394e34b 471 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
472 printNicely(line)
473 printNicely('')
2d341029
O
474
475
476def print_list(group):
477 """
478 Display a list
479 """
99b52f5f 480 for grp in group:
2d341029 481 # Format
99b52f5f 482 name = grp['full_name']
2d341029 483 name = color_func(c['GROUP']['name'])(name + ' : ')
99b52f5f 484 member = str(grp['member_count'])
422dd385 485 member = color_func(c['GROUP']['member'])(member + ' member')
99b52f5f 486 subscriber = str(grp['subscriber_count'])
422dd385
O
487 subscriber = color_func(
488 c['GROUP']['subscriber'])(
489 subscriber +
490 ' subscriber')
99b52f5f 491 description = grp['description'].strip()
2d341029 492 description = color_func(c['GROUP']['description'])(description)
99b52f5f 493 mode = grp['mode']
422dd385 494 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
99b52f5f 495 created_at = grp['created_at']
2d341029 496 date = parser.parse(created_at)
8b3456f9 497 lang, encode = locale.getdefaultlocale()
498 clock = arrow.get(date).to('local').humanize(locale=lang)
2d341029
O
499 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
500
2d341029 501 # Create lines
422dd385
O
502 line1 = ' ' * 2 + name + member + ' ' + subscriber
503 line2 = ' ' * 4 + description
504 line3 = ' ' * 4 + mode
505 line4 = ' ' * 4 + clock
2d341029
O
506
507 # Display
508 printNicely('')
509 printNicely(line1)
510 printNicely(line2)
511 printNicely(line3)
512 printNicely(line4)
513
514 printNicely('')
59262e95
O
515
516
8141aca6 517def show_calendar(month, date, rel):
518 """
519 Show the calendar in rainbow mode
520 """
521 month = random_rainbow(month)
522 date = ' '.join([cycle_color(i) for i in date.split(' ')])
523 today = str(int(os.popen('date +\'%d\'').read().strip()))
524 # Display
525 printNicely(month)
526 printNicely(date)
527 for line in rel:
528 ary = line.split(' ')
529 ary = lmap(
530 lambda x: color_func(c['CAL']['today'])(x)
531 if x == today
532 else color_func(c['CAL']['days'])(x),
533 ary)
534 printNicely(' '.join(ary))
535
536
b7c9c570 537def format_quote(tweet):
538 """
539 Quoting format
540 """
541 # Retrieve info
542 screen_name = '@' + tweet['user']['screen_name']
543 text = tweet['text']
544 # Validate quote format
545 if '#owner' not in c['QUOTE_FORMAT']:
546 printNicely(light_magenta('Quote should contains #owner'))
547 return False
548 if '#comment' not in c['QUOTE_FORMAT']:
549 printNicely(light_magenta('Quote format should have #comment'))
550 return False
551 # Build formater
552 formater = ''
553 try:
554 formater = c['QUOTE_FORMAT']
555 formater = screen_name.join(formater.split('#owner'))
556 formater = text.join(formater.split('#tweet'))
557 formater = u2str(formater)
558 except:
559 pass
560 # Highlight like a tweet
4dc385b5
O
561 notice = formater.split()
562 notice = lmap(
b7c9c570 563 lambda x: light_green(x)
564 if x == '#comment'
565 else x,
4dc385b5
O
566 notice)
567 notice = lmap(
b7c9c570 568 lambda x: color_func(c['TWEET']['rt'])(x)
569 if x == 'RT'
570 else x,
4dc385b5
O
571 notice)
572 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
573 notice = lmap(
b7c9c570 574 lambda x: color_func(c['TWEET']['link'])(x)
575 if x[0:4] == 'http'
576 else x,
4dc385b5
O
577 notice)
578 notice = lmap(
b7c9c570 579 lambda x: color_func(c['TWEET']['hashtag'])(x)
580 if x.startswith('#')
581 else x,
4dc385b5
O
582 notice)
583 notice = ' '.join(notice)
b7c9c570 584 # Notice
4dc385b5 585 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
b7c9c570 586 printNicely(notice)
587 return formater
588
589
59262e95 590# Start the color cycle
b2cde062 591start_cycle()