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