add info and colored
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import itertools
3 import requests
4 import locale
5 import arrow
6 import re
7 import os
8
9 from twitter.util import printNicely
10 from functools import wraps
11 from pyfiglet import figlet_format
12 from dateutil import parser
13 from .c_image import *
14 from .colors import *
15 from .config import *
16 from .py3patch import *
17
18 # Draw global variables
19 dg = {}
20
21
22 def init_cycle():
23 """
24 Init the cycle
25 """
26 colors_shuffle = [globals()[i.encode('utf8')]
27 if not str(i).isdigit()
28 else term_color(int(i))
29 for i in c['CYCLE_COLOR']]
30 return itertools.cycle(colors_shuffle)
31
32
33 def start_cycle():
34 """
35 Notify from rainbow
36 """
37 dg['cyc'] = init_cycle()
38 dg['cache'] = {}
39
40
41 def order_rainbow(s):
42 """
43 Print a string with ordered color with each character
44 """
45 colors_shuffle = [globals()[i.encode('utf8')]
46 if not str(i).isdigit()
47 else term_color(int(i))
48 for i in c['CYCLE_COLOR']]
49 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
50 return ''.join(colored)
51
52
53 def random_rainbow(s):
54 """
55 Print a string with random color with each character
56 """
57 colors_shuffle = [globals()[i.encode('utf8')]
58 if not str(i).isdigit()
59 else term_color(int(i))
60 for i in c['CYCLE_COLOR']]
61 colored = [random.choice(colors_shuffle)(i) for i in s]
62 return ''.join(colored)
63
64
65 def Memoize(func):
66 """
67 Memoize decorator
68 """
69 @wraps(func)
70 def wrapper(*args):
71 if args not in dg['cache']:
72 dg['cache'][args] = func(*args)
73 return dg['cache'][args]
74 return wrapper
75
76
77 @Memoize
78 def cycle_color(s):
79 """
80 Cycle the colors_shuffle
81 """
82 return next(dg['cyc'])(s)
83
84
85 def ascii_art(text):
86 """
87 Draw the Ascii Art
88 """
89 fi = figlet_format(text, font='doom')
90 print('\n'.join(
91 [next(dg['cyc'])(i) for i in fi.split('\n')]
92 ))
93
94
95 def check_config():
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
109 def 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
117
118
119 def reload_theme(value, prev):
120 """
121 Check current theme and update if necessary
122 """
123 if value != prev:
124 config = os.path.dirname(
125 __file__) + '/colorset/' + value + '.json'
126 # Load new config
127 data = load_config(config)
128 if data:
129 for d in data:
130 c[d] = data[d]
131 # Restart color cycle and update config
132 start_cycle()
133 set_config('THEME', value)
134 return value
135 return prev
136
137
138 def color_func(func_name):
139 """
140 Call color function base on name
141 """
142 if str(func_name).isdigit():
143 return term_color(int(func_name))
144 return globals()[func_name]
145
146
147 def draw(t, keyword=None, humanize=True, fil=[], ig=[]):
148 """
149 Draw the rainbow
150 """
151 # Check config
152 check_config()
153
154 # Retrieve tweet
155 tid = t['id']
156 text = t['text']
157 screen_name = t['user']['screen_name']
158 name = t['user']['name']
159 created_at = t['created_at']
160 favorited = t['favorited']
161 retweet_count = t['retweet_count']
162 favorite_count = t['favorite_count']
163 date = parser.parse(created_at)
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)
174
175 # Pull extended retweet text
176 try:
177 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
178 t['retweeted_status']['text']
179 except:
180 pass
181
182 # Unescape HTML character
183 text = unescape(text)
184
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
208 fil = list(set((fil or []) + c['ONLY_LIST']))
209 ig = list(set((ig or []) + c['IGNORE_LIST']))
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
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)
221
222 # Format info
223 name = cycle_color(name)
224 nick = color_func(c['TWEET']['nick'])(screen_name)
225 clock = clock
226 id = str(rid)
227 fav = ''
228 if favorited:
229 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
230
231 tweet = text.split()
232 # Replace url
233 if expanded_url:
234 for index in xrange(len(expanded_url)):
235 tweet = lmap(
236 lambda x: expanded_url[index]
237 if x == url[index]
238 else x,
239 tweet)
240 # Highlight RT
241 tweet = lmap(
242 lambda x: color_func(c['TWEET']['rt'])(x)
243 if x == 'RT'
244 else x,
245 tweet)
246 # Highlight screen_name
247 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
248 # Highlight link
249 tweet = lmap(
250 lambda x: color_func(c['TWEET']['link'])(x)
251 if x[0:4] == 'http'
252 else x,
253 tweet)
254 # Highlight hashtag
255 tweet = lmap(
256 lambda x: color_func(c['TWEET']['hashtag'])(x)
257 if x.startswith('#')
258 else x,
259 tweet)
260 # Highlight keyword
261 tweet = ' '.join(tweet)
262 if keyword:
263 roj = re.search(keyword, tweet, re.IGNORECASE)
264 if roj:
265 occur = roj.group()
266 ary = tweet.split(occur)
267 delimiter = color_func(c['TWEET']['keyword'])(occur)
268 tweet = delimiter.join(ary)
269
270 # Load config formater
271 formater = ''
272 try:
273 formater = c['FORMAT']['TWEET']['DISPLAY']
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'))
278 # Change clock word
279 word = [w for w in formater.split() if '#clock' in w][0]
280 delimiter = color_func(c['TWEET']['clock'])(
281 clock.join(word.split('#clock')))
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))
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))
297 except:
298 pass
299
300 # Draw
301 printNicely(formater)
302
303 # Display Image
304 if c['IMAGE_ON_TERM'] and media_url:
305 for mu in media_url:
306 try:
307 response = requests.get(mu)
308 image_to_display(BytesIO(response.content))
309 except Exception:
310 printNicely(red('Sorry, image link is broken'))
311
312
313 def print_threads(d):
314 """
315 Print threads of messages
316 """
317 id = 1
318 rel = {}
319 for partner in d:
320 messages = d[partner]
321 count = len(messages)
322 screen_name = '@' + partner[0]
323 name = partner[1]
324 screen_name = color_func(c['MESSAGE']['partner'])(screen_name)
325 name = cycle_color(name)
326 thread_id = color_func(c['MESSAGE']['id'])('thread id:'+str(id))
327 line = ' '*2 + name + ' ' + screen_name + \
328 ' (' + str(count) + ' message) ' + thread_id
329 printNicely(line)
330 rel[id] = partner
331 id += 1
332 dg['thread'] = d
333 return rel
334
335
336 def print_thread(partner, me_nick, me_name):
337 """
338 Print a thread of messages
339 """
340 # Sort messages by time
341 messages = dg['thread'][partner]
342 messages.sort(key = lambda x:parser.parse(x['created_at']))
343 # Print the 1st line
344 dg['message_thread_margin'] = margin = 2
345 left_size = len(partner[0])+len(partner[1]) + margin
346 right_size = len(me_nick) + len(me_name) + margin
347 partner_screen_name = color_func(c['MESSAGE']['partner'])('@' + partner[0])
348 partner_name = cycle_color(partner[1])
349 me_screen_name = color_func(c['MESSAGE']['me'])('@' + me_nick)
350 me_name = cycle_color(me_name)
351 left = ' ' * margin + partner_name + ' ' + partner_screen_name
352 right = me_name + ' ' + me_screen_name + ' ' * margin
353 h, w = os.popen('stty size', 'r').read().split()
354 w = int(w)
355 line = '{}{}{}'.format(left, ' '*(w - left_size - right_size - 2 * margin), right)
356 printNicely('')
357 printNicely(line)
358 printNicely('')
359 # Print messages
360 for m in messages:
361 if m['sender_screen_name'] == me_nick:
362 print_right_message(m)
363 elif m['recipient_screen_name'] == me_nick:
364 print_left_message(m)
365
366
367 def print_right_message(m):
368 """
369 Print a message on the right of screen
370 """
371 h, w = os.popen('stty size', 'r').read().split()
372 w = int(w)
373 frame_width = w //3 - dg['message_thread_margin']
374 step = frame_width - 2 * dg['message_thread_margin']
375 slicing = [m['text'][i:i+step] for i in range(0, len(m['text']), step)]
376 spaces = w - frame_width - dg['message_thread_margin']
377 dotline = ' ' * spaces + '-' * frame_width
378 dotline = color_func(c['MESSAGE']['me_bg'])(dotline)
379 # Draw the frame
380 printNicely(dotline)
381 for line in slicing:
382 fill = step - len(line)
383 screen_line = ' ' * spaces + '| ' + line + ' ' * fill + ' '
384 if slicing[-1] == line:
385 screen_line = screen_line + ' >'
386 else:
387 screen_line = screen_line + '|'
388 screen_line = color_func(c['MESSAGE']['me_bg'])(screen_line)
389 printNicely(screen_line)
390 printNicely(dotline)
391 # Print clock
392 date = parser.parse(m['created_at'])
393 date = arrow.get(date).to('local').datetime
394 clock_format = '%Y/%m/%d %H:%M:%S'
395 try:
396 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
397 except:
398 pass
399 clock = date.strftime(clock_format)
400 # Get rainbow id
401 if m['id'] not in c['message_dict']:
402 c['message_dict'].append(m['id'])
403 rid = len(c['message_dict']) - 1
404 else:
405 rid = c['message_dict'].index(m['id'])
406 rid = str(rid)
407 # Create line and print
408 meta = color_func(c['MESSAGE']['clock'])(clock) + \
409 color_func(c['MESSAGE']['id'])(' ('+rid+')')
410 line = ' ' * (w - len(clock + rid) - 3 - dg['message_thread_margin']) + \
411 meta
412 printNicely(line)
413
414
415 def print_left_message(m):
416 """
417 Print a message on the left of screen
418 """
419 h, w = os.popen('stty size', 'r').read().split()
420 w = int(w)
421 frame_width = w //3 - dg['message_thread_margin']
422 step = frame_width - 2 * dg['message_thread_margin']
423 slicing = [m['text'][i:i+step] for i in range(0, len(m['text']), step)]
424 spaces = dg['message_thread_margin']
425 dotline = ' ' * spaces + '-' * frame_width
426 dotline = color_func(c['MESSAGE']['partner_bg'])(dotline)
427 # Draw the frame
428 printNicely(dotline)
429 for line in slicing:
430 fill = step - len(line)
431 screen_line = ' ' + line + ' ' * fill + ' |'
432 if slicing[-1] == line:
433 screen_line = ' ' * (spaces-1) + '< ' + screen_line
434 else:
435 screen_line = ' ' * spaces + '|' + screen_line
436 screen_line = color_func(c['MESSAGE']['partner_bg'])(screen_line)
437 printNicely(screen_line)
438 printNicely(dotline)
439 # Print clock
440 date = parser.parse(m['created_at'])
441 date = arrow.get(date).to('local').datetime
442 clock_format = '%Y/%m/%d %H:%M:%S'
443 try:
444 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
445 except:
446 pass
447 clock = date.strftime(clock_format)
448 # Get rainbow id
449 if m['id'] not in c['message_dict']:
450 c['message_dict'].append(m['id'])
451 rid = len(c['message_dict']) - 1
452 else:
453 rid = c['message_dict'].index(m['id'])
454 rid = str(rid)
455 # Create line and print
456 meta = color_func(c['MESSAGE']['clock'])(clock) + \
457 color_func(c['MESSAGE']['id'])(' ('+rid+')')
458 line = ' ' * dg['message_thread_margin'] + \
459 meta
460 printNicely(line)
461
462
463 def print_message(m):
464 """
465 Print direct message
466 """
467 # Retrieve message
468 sender_screen_name = '@' + m['sender_screen_name']
469 sender_name = m['sender']['name']
470 text = unescape(m['text'])
471 recipient_screen_name = '@' + m['recipient_screen_name']
472 recipient_name = m['recipient']['name']
473 mid = m['id']
474 date = parser.parse(m['created_at'])
475 date = arrow.get(date).to('local').datetime
476 clock_format = '%Y/%m/%d %H:%M:%S'
477 try:
478 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
479 except:
480 pass
481 clock = date.strftime(clock_format)
482
483 # Get rainbow id
484 if mid not in c['message_dict']:
485 c['message_dict'].append(mid)
486 rid = len(c['message_dict']) - 1
487 else:
488 rid = c['message_dict'].index(mid)
489
490 # Draw
491 sender_name = cycle_color(sender_name)
492 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
493 recipient_name = cycle_color(recipient_name)
494 recipient_nick = color_func(
495 c['MESSAGE']['recipient'])(recipient_screen_name)
496 to = color_func(c['MESSAGE']['to'])('>>>')
497 clock = clock
498 id = str(rid)
499
500 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
501
502 # Load config formater
503 try:
504 formater = c['FORMAT']['MESSAGE']['DISPLAY']
505 formater = sender_name.join(formater.split("#sender_name"))
506 formater = sender_nick.join(formater.split("#sender_nick"))
507 formater = to.join(formater.split("#to"))
508 formater = recipient_name.join(formater.split("#recipient_name"))
509 formater = recipient_nick.join(formater.split("#recipient_nick"))
510 formater = text.join(formater.split("#message"))
511 # Change clock word
512 word = [w for w in formater.split() if '#clock' in w][0]
513 delimiter = color_func(c['MESSAGE']['clock'])(
514 clock.join(word.split('#clock')))
515 formater = delimiter.join(formater.split(word))
516 # Change id word
517 word = [w for w in formater.split() if '#id' in w][0]
518 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
519 formater = delimiter.join(formater.split(word))
520 except:
521 printNicely(red('Wrong format in config.'))
522 return
523
524 # Draw
525 printNicely(formater)
526
527
528 def show_profile(u):
529 """
530 Show a profile
531 """
532 # Retrieve info
533 name = u['name']
534 screen_name = u['screen_name']
535 description = u['description']
536 profile_image_url = u['profile_image_url']
537 location = u['location']
538 url = u['url']
539 created_at = u['created_at']
540 statuses_count = u['statuses_count']
541 friends_count = u['friends_count']
542 followers_count = u['followers_count']
543
544 # Create content
545 statuses_count = color_func(
546 c['PROFILE']['statuses_count'])(
547 str(statuses_count) +
548 ' tweets')
549 friends_count = color_func(
550 c['PROFILE']['friends_count'])(
551 str(friends_count) +
552 ' following')
553 followers_count = color_func(
554 c['PROFILE']['followers_count'])(
555 str(followers_count) +
556 ' followers')
557 count = statuses_count + ' ' + friends_count + ' ' + followers_count
558 user = cycle_color(
559 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
560 profile_image_raw_url = 'Profile photo: ' + \
561 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
562 description = ''.join(
563 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
564 description = color_func(c['PROFILE']['description'])(description)
565 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
566 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
567 date = parser.parse(created_at)
568 lang, encode = locale.getdefaultlocale()
569 clock = arrow.get(date).to('local').humanize(locale=lang)
570 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
571
572 # Format
573 line1 = u"{u:>{uw}}".format(
574 u=user,
575 uw=len(user) + 2,
576 )
577 line2 = u"{p:>{pw}}".format(
578 p=profile_image_raw_url,
579 pw=len(profile_image_raw_url) + 4,
580 )
581 line3 = u"{d:>{dw}}".format(
582 d=description,
583 dw=len(description) + 4,
584 )
585 line4 = u"{l:>{lw}}".format(
586 l=location,
587 lw=len(location) + 4,
588 )
589 line5 = u"{u:>{uw}}".format(
590 u=url,
591 uw=len(url) + 4,
592 )
593 line6 = u"{c:>{cw}}".format(
594 c=clock,
595 cw=len(clock) + 4,
596 )
597
598 # Display
599 printNicely('')
600 printNicely(line1)
601 if c['IMAGE_ON_TERM']:
602 try:
603 response = requests.get(profile_image_url)
604 image_to_display(BytesIO(response.content))
605 except:
606 pass
607 else:
608 printNicely(line2)
609 for line in [line3, line4, line5, line6]:
610 printNicely(line)
611 printNicely('')
612
613
614 def print_trends(trends):
615 """
616 Display topics
617 """
618 for topic in trends[:c['TREND_MAX']]:
619 name = topic['name']
620 url = topic['url']
621 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
622 printNicely(line)
623 printNicely('')
624
625
626 def print_list(group):
627 """
628 Display a list
629 """
630 for grp in group:
631 # Format
632 name = grp['full_name']
633 name = color_func(c['GROUP']['name'])(name + ' : ')
634 member = str(grp['member_count'])
635 member = color_func(c['GROUP']['member'])(member + ' member')
636 subscriber = str(grp['subscriber_count'])
637 subscriber = color_func(
638 c['GROUP']['subscriber'])(
639 subscriber +
640 ' subscriber')
641 description = grp['description'].strip()
642 description = color_func(c['GROUP']['description'])(description)
643 mode = grp['mode']
644 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
645 created_at = grp['created_at']
646 date = parser.parse(created_at)
647 lang, encode = locale.getdefaultlocale()
648 clock = arrow.get(date).to('local').humanize(locale=lang)
649 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
650
651 # Create lines
652 line1 = ' ' * 2 + name + member + ' ' + subscriber
653 line2 = ' ' * 4 + description
654 line3 = ' ' * 4 + mode
655 line4 = ' ' * 4 + clock
656
657 # Display
658 printNicely('')
659 printNicely(line1)
660 printNicely(line2)
661 printNicely(line3)
662 printNicely(line4)
663
664 printNicely('')
665
666
667 def show_calendar(month, date, rel):
668 """
669 Show the calendar in rainbow mode
670 """
671 month = random_rainbow(month)
672 date = ' '.join([cycle_color(i) for i in date.split(' ')])
673 today = str(int(os.popen('date +\'%d\'').read().strip()))
674 # Display
675 printNicely(month)
676 printNicely(date)
677 for line in rel:
678 ary = line.split(' ')
679 ary = lmap(
680 lambda x: color_func(c['CAL']['today'])(x)
681 if x == today
682 else color_func(c['CAL']['days'])(x),
683 ary)
684 printNicely(' '.join(ary))
685
686
687 def format_quote(tweet):
688 """
689 Quoting format
690 """
691 # Retrieve info
692 screen_name = '@' + tweet['user']['screen_name']
693 text = tweet['text']
694 # Validate quote format
695 if '#owner' not in c['QUOTE_FORMAT']:
696 printNicely(light_magenta('Quote should contains #owner'))
697 return False
698 if '#comment' not in c['QUOTE_FORMAT']:
699 printNicely(light_magenta('Quote format should have #comment'))
700 return False
701 # Build formater
702 formater = ''
703 try:
704 formater = c['QUOTE_FORMAT']
705 formater = screen_name.join(formater.split('#owner'))
706 formater = text.join(formater.split('#tweet'))
707 formater = u2str(formater)
708 except:
709 pass
710 # Highlight like a tweet
711 notice = formater.split()
712 notice = lmap(
713 lambda x: light_green(x)
714 if x == '#comment'
715 else x,
716 notice)
717 notice = lmap(
718 lambda x: color_func(c['TWEET']['rt'])(x)
719 if x == 'RT'
720 else x,
721 notice)
722 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
723 notice = lmap(
724 lambda x: color_func(c['TWEET']['link'])(x)
725 if x[0:4] == 'http'
726 else x,
727 notice)
728 notice = lmap(
729 lambda x: color_func(c['TWEET']['hashtag'])(x)
730 if x.startswith('#')
731 else x,
732 notice)
733 notice = ' '.join(notice)
734 # Notice
735 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
736 printNicely(notice)
737 return formater
738
739
740 # Start the color cycle
741 start_cycle()