add notification command
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import textwrap
3 import itertools
4 import requests
5 import locale
6 import arrow
7 import re
8 import os
9
10 from twitter.util import printNicely
11 from functools import wraps
12 from pyfiglet import figlet_format
13 from dateutil import parser
14 from .c_image import *
15 from .colors import *
16 from .config import *
17 from .py3patch import *
18
19 # Draw global variables
20 dg = {}
21
22
23 def init_cycle():
24 """
25 Init the cycle
26 """
27 colors_shuffle = [globals()[i.encode('utf8')]
28 if not str(i).isdigit()
29 else term_color(int(i))
30 for i in c['CYCLE_COLOR']]
31 return itertools.cycle(colors_shuffle)
32
33
34 def start_cycle():
35 """
36 Notify from rainbow
37 """
38 dg['cyc'] = init_cycle()
39 dg['cache'] = {}
40
41
42 def order_rainbow(s):
43 """
44 Print a string with ordered color with each character
45 """
46 colors_shuffle = [globals()[i.encode('utf8')]
47 if not str(i).isdigit()
48 else term_color(int(i))
49 for i in c['CYCLE_COLOR']]
50 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
51 return ''.join(colored)
52
53
54 def random_rainbow(s):
55 """
56 Print a string with random color with each character
57 """
58 colors_shuffle = [globals()[i.encode('utf8')]
59 if not str(i).isdigit()
60 else term_color(int(i))
61 for i in c['CYCLE_COLOR']]
62 colored = [random.choice(colors_shuffle)(i) for i in s]
63 return ''.join(colored)
64
65
66 def Memoize(func):
67 """
68 Memoize decorator
69 """
70 @wraps(func)
71 def wrapper(*args):
72 if args not in dg['cache']:
73 dg['cache'][args] = func(*args)
74 return dg['cache'][args]
75 return wrapper
76
77
78 @Memoize
79 def cycle_color(s):
80 """
81 Cycle the colors_shuffle
82 """
83 return next(dg['cyc'])(s)
84
85
86 def ascii_art(text):
87 """
88 Draw the Ascii Art
89 """
90 fi = figlet_format(text, font='doom')
91 print('\n'.join(
92 [next(dg['cyc'])(i) for i in fi.split('\n')]
93 ))
94
95
96 def check_config():
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
110 def 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
118
119
120 def reload_theme(value, prev):
121 """
122 Check current theme and update if necessary
123 """
124 if value != prev:
125 config = os.path.dirname(
126 __file__) + '/colorset/' + value + '.json'
127 # Load new config
128 data = load_config(config)
129 if data:
130 for d in data:
131 c[d] = data[d]
132 # Restart color cycle and update config
133 start_cycle()
134 set_config('THEME', value)
135 return value
136 return prev
137
138
139 def color_func(func_name):
140 """
141 Call color function base on name
142 """
143 if str(func_name).isdigit():
144 return term_color(int(func_name))
145 return globals()[func_name]
146
147
148 def draw(t, keyword=None, humanize=True, noti=False, fil=[], ig=[]):
149 """
150 Draw the rainbow
151 """
152 # Check config
153 check_config()
154
155 # Retrieve tweet
156 tid = t['id']
157 text = t['text']
158 screen_name = t['user']['screen_name']
159 name = t['user']['name']
160 created_at = t['created_at']
161 favorited = t['favorited']
162 retweet_count = t['retweet_count']
163 favorite_count = t['favorite_count']
164 date = parser.parse(created_at)
165 date = arrow.get(date).to('local')
166 if humanize:
167 lang, encode = locale.getdefaultlocale()
168 clock = arrow.get(date).to('local').humanize(locale=lang)
169 else:
170 try:
171 clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT']
172 except:
173 clock_format = '%Y/%m/%d %H:%M:%S'
174 clock = date.datetime.strftime(clock_format)
175
176 # Pull extended retweet text
177 try:
178 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
179 t['retweeted_status']['text']
180 except:
181 pass
182
183 # Unescape HTML character
184 text = unescape(text)
185
186 # Get expanded url
187 try:
188 expanded_url = []
189 url = []
190 urls = t['entities']['urls']
191 for u in urls:
192 expanded_url.append(u['expanded_url'])
193 url.append(u['url'])
194 except:
195 expanded_url = None
196 url = None
197
198 # Get media
199 try:
200 media_url = []
201 media = t['entities']['media']
202 for m in media:
203 media_url.append(m['media_url'])
204 except:
205 media_url = None
206
207 # Filter and ignore
208 mytweet = screen_name == c['original_name']
209 screen_name = '@' + screen_name
210 fil = list(set((fil or []) + c['ONLY_LIST']))
211 ig = list(set((ig or []) + c['IGNORE_LIST']))
212 if fil and screen_name not in fil:
213 return
214 if ig and screen_name in ig:
215 return
216
217 # Get rainbow id
218 if tid not in c['tweet_dict']:
219 c['tweet_dict'].append(tid)
220 rid = len(c['tweet_dict']) - 1
221 else:
222 rid = c['tweet_dict'].index(tid)
223
224 # Format info
225 name = cycle_color(name)
226 if mytweet:
227 nick = color_func(c['TWEET']['mynick'])(screen_name)
228 else:
229 nick = color_func(c['TWEET']['nick'])(screen_name)
230 clock = clock
231 id = str(rid)
232 fav = ''
233 if favorited:
234 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
235
236 tweet = text.split()
237 # Replace url
238 if expanded_url:
239 for index in xrange(len(expanded_url)):
240 tweet = lmap(
241 lambda x: expanded_url[index]
242 if x == url[index]
243 else x,
244 tweet)
245 # Highlight RT
246 tweet = lmap(
247 lambda x: color_func(c['TWEET']['rt'])(x)
248 if x == 'RT'
249 else x,
250 tweet)
251 # Highlight screen_name
252 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
253 # Highlight link
254 tweet = lmap(
255 lambda x: color_func(c['TWEET']['link'])(x)
256 if x.startswith('http')
257 else x,
258 tweet)
259 # Highlight hashtag
260 tweet = lmap(
261 lambda x: color_func(c['TWEET']['hashtag'])(x)
262 if x.startswith('#')
263 else x,
264 tweet)
265 # Highlight my tweet
266 if mytweet:
267 tweet = [color_func(c['TWEET']['mytweet'])(x)
268 for x in tweet
269 if not any([
270 x == 'RT',
271 x.startswith('http'),
272 x.startswith('#')])
273 ]
274 # Highlight keyword
275 tweet = ' '.join(tweet)
276 if keyword:
277 roj = re.search(keyword, tweet, re.IGNORECASE)
278 if roj:
279 occur = roj.group()
280 ary = tweet.split(occur)
281 delimiter = color_func(c['TWEET']['keyword'])(occur)
282 tweet = delimiter.join(ary)
283
284 # Load config formater
285 formater = ''
286 try:
287 formater = c['FORMAT']['TWEET']['DISPLAY']
288 formater = name.join(formater.split('#name'))
289 formater = nick.join(formater.split('#nick'))
290 formater = fav.join(formater.split('#fav'))
291 formater = tweet.join(formater.split('#tweet'))
292 # Change clock word
293 word = [wo for wo in formater.split() if '#clock' in wo][0]
294 delimiter = color_func(c['TWEET']['clock'])(
295 clock.join(word.split('#clock')))
296 formater = delimiter.join(formater.split(word))
297 # Change id word
298 word = [wo for wo in formater.split() if '#id' in wo][0]
299 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
300 formater = delimiter.join(formater.split(word))
301 # Change retweet count word
302 word = [wo for wo in formater.split() if '#rt_count' in wo][0]
303 delimiter = color_func(c['TWEET']['retweet_count'])(
304 str(retweet_count).join(word.split('#rt_count')))
305 formater = delimiter.join(formater.split(word))
306 # Change favorites count word
307 word = [wo for wo in formater.split() if '#fa_count' in wo][0]
308 delimiter = color_func(c['TWEET']['favorite_count'])(
309 str(favorite_count).join(word.split('#fa_count')))
310 formater = delimiter.join(formater.split(word))
311 except:
312 pass
313
314 # Add spaces in begining of line if this is inside a notification
315 if noti:
316 formater = '\n '.join(formater.split('\n'))
317
318 # Draw
319 printNicely(formater)
320
321 # Display Image
322 if c['IMAGE_ON_TERM'] and media_url:
323 for mu in media_url:
324 try:
325 response = requests.get(mu)
326 image_to_display(BytesIO(response.content))
327 except Exception:
328 printNicely(red('Sorry, image link is broken'))
329
330
331 def print_threads(d):
332 """
333 Print threads of messages
334 """
335 id = 1
336 rel = {}
337 for partner in d:
338 messages = d[partner]
339 count = len(messages)
340 screen_name = '@' + partner[0]
341 name = partner[1]
342 screen_name = color_func(c['MESSAGE']['partner'])(screen_name)
343 name = cycle_color(name)
344 thread_id = color_func(c['MESSAGE']['id'])('thread_id:' + str(id))
345 line = ' ' * 2 + name + ' ' + screen_name + \
346 ' (' + str(count) + ' message) ' + thread_id
347 printNicely(line)
348 rel[id] = partner
349 id += 1
350 dg['thread'] = d
351 return rel
352
353
354 def print_thread(partner, me_nick, me_name):
355 """
356 Print a thread of messages
357 """
358 # Sort messages by time
359 messages = dg['thread'][partner]
360 messages.sort(key=lambda x: parser.parse(x['created_at']))
361 # Use legacy display on non-ascii text message
362 ms = [m['text'] for m in messages]
363 ums = [m for m in ms if not all(ord(c) < 128 for c in m)]
364 if ums:
365 for m in messages:
366 print_message(m)
367 printNicely('')
368 return
369 # Print the first line
370 dg['frame_margin'] = margin = 2
371 partner_nick = partner[0]
372 partner_name = partner[1]
373 left_size = len(partner_nick) + len(partner_name) + 2
374 right_size = len(me_nick) + len(me_name) + 2
375 partner_nick = color_func(c['MESSAGE']['partner'])('@' + partner_nick)
376 partner_name = cycle_color(partner_name)
377 me_screen_name = color_func(c['MESSAGE']['me'])('@' + me_nick)
378 me_name = cycle_color(me_name)
379 left = ' ' * margin + partner_name + ' ' + partner_nick
380 right = me_name + ' ' + me_screen_name + ' ' * margin
381 h, w = os.popen('stty size', 'r').read().split()
382 w = int(w)
383 line = '{}{}{}'.format(
384 left, ' ' * (w - left_size - right_size - 2 * margin), right)
385 printNicely('')
386 printNicely(line)
387 printNicely('')
388 # Print messages
389 for m in messages:
390 if m['sender_screen_name'] == me_nick:
391 print_right_message(m)
392 elif m['recipient_screen_name'] == me_nick:
393 print_left_message(m)
394
395
396 def print_right_message(m):
397 """
398 Print a message on the right of screen
399 """
400 h, w = os.popen('stty size', 'r').read().split()
401 w = int(w)
402 frame_width = w // 3 - dg['frame_margin']
403 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
404 step = frame_width - 2 * dg['frame_margin']
405 slicing = textwrap.wrap(m['text'], step)
406 spaces = w - frame_width - dg['frame_margin']
407 dotline = ' ' * spaces + '-' * frame_width
408 dotline = color_func(c['MESSAGE']['me_frame'])(dotline)
409 # Draw the frame
410 printNicely(dotline)
411 for line in slicing:
412 fill = step - len(line)
413 screen_line = ' ' * spaces + '| ' + line + ' ' * fill + ' '
414 if slicing[-1] == line:
415 screen_line = screen_line + ' >'
416 else:
417 screen_line = screen_line + '|'
418 screen_line = color_func(c['MESSAGE']['me_frame'])(screen_line)
419 printNicely(screen_line)
420 printNicely(dotline)
421 # Format clock
422 date = parser.parse(m['created_at'])
423 date = arrow.get(date).to('local').datetime
424 clock_format = '%Y/%m/%d %H:%M:%S'
425 try:
426 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
427 except:
428 pass
429 clock = date.strftime(clock_format)
430 # Format id
431 if m['id'] not in c['message_dict']:
432 c['message_dict'].append(m['id'])
433 rid = len(c['message_dict']) - 1
434 else:
435 rid = c['message_dict'].index(m['id'])
436 id = str(rid)
437 # Print meta
438 formater = ''
439 try:
440 virtual_meta = formater = c['THREAD_META_RIGHT']
441 virtual_meta = clock.join(virtual_meta.split('#clock'))
442 virtual_meta = id.join(virtual_meta.split('#id'))
443 # Change clock word
444 word = [wo for wo in formater.split() if '#clock' in wo][0]
445 delimiter = color_func(c['MESSAGE']['clock'])(
446 clock.join(word.split('#clock')))
447 formater = delimiter.join(formater.split(word))
448 # Change id word
449 word = [wo for wo in formater.split() if '#id' in wo][0]
450 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
451 formater = delimiter.join(formater.split(word))
452 except Exception:
453 printNicely(red('Wrong format in config.'))
454 return
455 meta = formater
456 line = ' ' * (w - len(virtual_meta) - dg['frame_margin']) + meta
457 printNicely(line)
458
459
460 def print_left_message(m):
461 """
462 Print a message on the left of screen
463 """
464 h, w = os.popen('stty size', 'r').read().split()
465 w = int(w)
466 frame_width = w // 3 - dg['frame_margin']
467 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
468 step = frame_width - 2 * dg['frame_margin']
469 slicing = textwrap.wrap(m['text'], step)
470 spaces = dg['frame_margin']
471 dotline = ' ' * spaces + '-' * frame_width
472 dotline = color_func(c['MESSAGE']['partner_frame'])(dotline)
473 # Draw the frame
474 printNicely(dotline)
475 for line in slicing:
476 fill = step - len(line)
477 screen_line = ' ' + line + ' ' * fill + ' |'
478 if slicing[-1] == line:
479 screen_line = ' ' * (spaces - 1) + '< ' + screen_line
480 else:
481 screen_line = ' ' * spaces + '|' + screen_line
482 screen_line = color_func(c['MESSAGE']['partner_frame'])(screen_line)
483 printNicely(screen_line)
484 printNicely(dotline)
485 # Format clock
486 date = parser.parse(m['created_at'])
487 date = arrow.get(date).to('local').datetime
488 clock_format = '%Y/%m/%d %H:%M:%S'
489 try:
490 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
491 except:
492 pass
493 clock = date.strftime(clock_format)
494 # Format id
495 if m['id'] not in c['message_dict']:
496 c['message_dict'].append(m['id'])
497 rid = len(c['message_dict']) - 1
498 else:
499 rid = c['message_dict'].index(m['id'])
500 id = str(rid)
501 # Print meta
502 formater = ''
503 try:
504 virtual_meta = formater = c['THREAD_META_LEFT']
505 virtual_meta = clock.join(virtual_meta.split('#clock'))
506 virtual_meta = id.join(virtual_meta.split('#id'))
507 # Change clock word
508 word = [wo for wo in formater.split() if '#clock' in wo][0]
509 delimiter = color_func(c['MESSAGE']['clock'])(
510 clock.join(word.split('#clock')))
511 formater = delimiter.join(formater.split(word))
512 # Change id word
513 word = [wo for wo in formater.split() if '#id' in wo][0]
514 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
515 formater = delimiter.join(formater.split(word))
516 except Exception:
517 printNicely(red('Wrong format in config.'))
518 return
519 meta = formater
520 line = ' ' * dg['frame_margin'] + meta
521 printNicely(line)
522
523
524 def print_message(m):
525 """
526 Print direct message
527 """
528 # Retrieve message
529 sender_screen_name = '@' + m['sender_screen_name']
530 sender_name = m['sender']['name']
531 text = unescape(m['text'])
532 recipient_screen_name = '@' + m['recipient_screen_name']
533 recipient_name = m['recipient']['name']
534 mid = m['id']
535 date = parser.parse(m['created_at'])
536 date = arrow.get(date).to('local').datetime
537 clock_format = '%Y/%m/%d %H:%M:%S'
538 try:
539 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
540 except:
541 pass
542 clock = date.strftime(clock_format)
543
544 # Get rainbow id
545 if mid not in c['message_dict']:
546 c['message_dict'].append(mid)
547 rid = len(c['message_dict']) - 1
548 else:
549 rid = c['message_dict'].index(mid)
550
551 # Draw
552 sender_name = cycle_color(sender_name)
553 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
554 recipient_name = cycle_color(recipient_name)
555 recipient_nick = color_func(
556 c['MESSAGE']['recipient'])(recipient_screen_name)
557 to = color_func(c['MESSAGE']['to'])('>>>')
558 clock = clock
559 id = str(rid)
560
561 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
562
563 # Load config formater
564 try:
565 formater = c['FORMAT']['MESSAGE']['DISPLAY']
566 formater = sender_name.join(formater.split("#sender_name"))
567 formater = sender_nick.join(formater.split("#sender_nick"))
568 formater = to.join(formater.split("#to"))
569 formater = recipient_name.join(formater.split("#recipient_name"))
570 formater = recipient_nick.join(formater.split("#recipient_nick"))
571 formater = text.join(formater.split("#message"))
572 # Change clock word
573 word = [wo for wo in formater.split() if '#clock' in wo][0]
574 delimiter = color_func(c['MESSAGE']['clock'])(
575 clock.join(word.split('#clock')))
576 formater = delimiter.join(formater.split(word))
577 # Change id word
578 word = [wo for wo in formater.split() if '#id' in wo][0]
579 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
580 formater = delimiter.join(formater.split(word))
581 except:
582 printNicely(red('Wrong format in config.'))
583 return
584
585 # Draw
586 printNicely(formater)
587
588
589 def notify_favorite(e):
590 """
591 Notify a favorite event
592 """
593 # Retrieve info
594 target = e['target']
595 if target['screen_name'] != c['original_name']:
596 return
597 source = e['source']
598 target_object = e['target_object']
599 created_at = e['created_at']
600 # Format
601 source_user = cycle_color(source['name']) + \
602 color_func(c['NOTIFICATION']['source_nick'])(
603 ' @' + source['screen_name'])
604 notify = color_func(c['NOTIFICATION']['notify'])(' favorited your tweet ')
605 date = parser.parse(created_at)
606 date = arrow.get(date).to('local')
607 lang, encode = locale.getdefaultlocale()
608 clock = arrow.get(date).to('local').humanize(locale=lang)
609 clock = color_func(c['NOTIFICATION']['clock'])(clock)
610 meta = ' ' * 2 + source_user + notify + clock
611 # Output
612 printNicely('')
613 printNicely(meta)
614 draw(t=target_object, noti=True)
615
616
617 def notify_unfavorite(e):
618 """
619 Notify a unfavorite event
620 """
621 # Retrieve info
622 target = e['target']
623 if target['screen_name'] != c['original_name']:
624 return
625 source = e['source']
626 target_object = e['target_object']
627 created_at = e['created_at']
628 # Format
629 source_user = cycle_color(source['name']) + \
630 color_func(c['NOTIFICATION']['source_nick'])(
631 ' @' + source['screen_name'])
632 notify = color_func(c['NOTIFICATION']['notify'])(
633 ' unfavorited your tweet ')
634 date = parser.parse(created_at)
635 date = arrow.get(date).to('local')
636 lang, encode = locale.getdefaultlocale()
637 clock = arrow.get(date).to('local').humanize(locale=lang)
638 clock = color_func(c['NOTIFICATION']['clock'])(clock)
639 meta = ' ' * 2 + source_user + notify + clock
640 # Output
641 printNicely('')
642 printNicely(meta)
643 draw(t=target_object, noti=True)
644
645
646 def notify_follow(e):
647 """
648 Notify a follow event
649 """
650 # Retrieve info
651 target = e['target']
652 if target['screen_name'] != c['original_name']:
653 return
654 source = e['source']
655 created_at = e['created_at']
656 # Format
657 source_user = cycle_color(source['name']) + \
658 color_func(c['NOTIFICATION']['source_nick'])(
659 ' @' + source['screen_name'])
660 notify = color_func(c['NOTIFICATION']['notify'])(' followed you ')
661 date = parser.parse(created_at)
662 date = arrow.get(date).to('local')
663 lang, encode = locale.getdefaultlocale()
664 clock = arrow.get(date).to('local').humanize(locale=lang)
665 clock = color_func(c['NOTIFICATION']['clock'])(clock)
666 meta = ' ' * 2 + source_user + notify + clock
667 # Output
668 printNicely('')
669 printNicely(meta)
670
671
672 def notify_list_member_added(e):
673 """
674 Notify a list_member_added event
675 """
676 # Retrieve info
677 target = e['target']
678 if target['screen_name'] != c['original_name']:
679 return
680 source = e['source']
681 target_object = [e['target_object']] # list of Twitter list
682 created_at = e['created_at']
683 # Format
684 source_user = cycle_color(source['name']) + \
685 color_func(c['NOTIFICATION']['source_nick'])(
686 ' @' + source['screen_name'])
687 notify = color_func(c['NOTIFICATION']['notify'])(' added you to a list ')
688 date = parser.parse(created_at)
689 date = arrow.get(date).to('local')
690 lang, encode = locale.getdefaultlocale()
691 clock = arrow.get(date).to('local').humanize(locale=lang)
692 clock = color_func(c['NOTIFICATION']['clock'])(clock)
693 meta = ' ' * 2 + source_user + notify + clock
694 # Output
695 printNicely('')
696 printNicely(meta)
697 print_list(target_object, noti=True)
698
699
700 def notify_list_member_removed(e):
701 """
702 Notify a list_member_removed event
703 """
704 # Retrieve info
705 target = e['target']
706 if target['screen_name'] != c['original_name']:
707 return
708 source = e['source']
709 target_object = [e['target_object']] # list of Twitter list
710 created_at = e['created_at']
711 # Format
712 source_user = cycle_color(source['name']) + \
713 color_func(c['NOTIFICATION']['source_nick'])(
714 ' @' + source['screen_name'])
715 notify = color_func(c['NOTIFICATION']['notify'])(
716 ' removed you from a list ')
717 date = parser.parse(created_at)
718 date = arrow.get(date).to('local')
719 lang, encode = locale.getdefaultlocale()
720 clock = arrow.get(date).to('local').humanize(locale=lang)
721 clock = color_func(c['NOTIFICATION']['clock'])(clock)
722 meta = ' ' * 2 + source_user + notify + clock
723 # Output
724 printNicely('')
725 printNicely(meta)
726 print_list(target_object, noti=True)
727
728
729 def notify_list_user_subscribed(e):
730 """
731 Notify a list_user_subscribed event
732 """
733 # Retrieve info
734 target = e['target']
735 if target['screen_name'] != c['original_name']:
736 return
737 source = e['source']
738 target_object = [e['target_object']] # list of Twitter list
739 created_at = e['created_at']
740 # Format
741 source_user = cycle_color(source['name']) + \
742 color_func(c['NOTIFICATION']['source_nick'])(
743 ' @' + source['screen_name'])
744 notify = color_func(c['NOTIFICATION']['notify'])(
745 ' subscribed to your list ')
746 date = parser.parse(created_at)
747 date = arrow.get(date).to('local')
748 lang, encode = locale.getdefaultlocale()
749 clock = arrow.get(date).to('local').humanize(locale=lang)
750 clock = color_func(c['NOTIFICATION']['clock'])(clock)
751 meta = ' ' * 2 + source_user + notify + clock
752 # Output
753 printNicely('')
754 printNicely(meta)
755 print_list(target_object, noti=True)
756
757
758 def notify_list_user_unsubscribed(e):
759 """
760 Notify a list_user_unsubscribed event
761 """
762 # Retrieve info
763 target = e['target']
764 if target['screen_name'] != c['original_name']:
765 return
766 source = e['source']
767 target_object = [e['target_object']] # list of Twitter list
768 created_at = e['created_at']
769 # Format
770 source_user = cycle_color(source['name']) + \
771 color_func(c['NOTIFICATION']['source_nick'])(
772 ' @' + source['screen_name'])
773 notify = color_func(c['NOTIFICATION']['notify'])(
774 ' unsubscribed from your list ')
775 date = parser.parse(created_at)
776 date = arrow.get(date).to('local')
777 lang, encode = locale.getdefaultlocale()
778 clock = arrow.get(date).to('local').humanize(locale=lang)
779 clock = color_func(c['NOTIFICATION']['clock'])(clock)
780 meta = ' ' * 2 + source_user + notify + clock
781 # Output
782 printNicely('')
783 printNicely(meta)
784 print_list(target_object, noti=True)
785
786
787 def print_event(e):
788 """
789 Notify an event
790 """
791 event_dict = {
792 'favorite': notify_favorite,
793 'unfavorite': notify_unfavorite,
794 'follow': notify_follow,
795 'list_member_added': notify_list_member_added,
796 'list_member_removed': notify_list_member_removed,
797 'list_user_subscribed': notify_list_user_subscribed,
798 'list_user_unsubscribed': notify_list_user_unsubscribed,
799 }
800 event_dict[e['event']](e)
801
802
803 def show_profile(u):
804 """
805 Show a profile
806 """
807 # Retrieve info
808 name = u['name']
809 screen_name = u['screen_name']
810 description = u['description']
811 profile_image_url = u['profile_image_url']
812 location = u['location']
813 url = u['url']
814 created_at = u['created_at']
815 statuses_count = u['statuses_count']
816 friends_count = u['friends_count']
817 followers_count = u['followers_count']
818
819 # Create content
820 statuses_count = color_func(
821 c['PROFILE']['statuses_count'])(
822 str(statuses_count) +
823 ' tweets')
824 friends_count = color_func(
825 c['PROFILE']['friends_count'])(
826 str(friends_count) +
827 ' following')
828 followers_count = color_func(
829 c['PROFILE']['followers_count'])(
830 str(followers_count) +
831 ' followers')
832 count = statuses_count + ' ' + friends_count + ' ' + followers_count
833 user = cycle_color(
834 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
835 profile_image_raw_url = 'Profile photo: ' + \
836 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
837 description = ''.join(
838 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
839 description = color_func(c['PROFILE']['description'])(description)
840 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
841 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
842 date = parser.parse(created_at)
843 lang, encode = locale.getdefaultlocale()
844 clock = arrow.get(date).to('local').humanize(locale=lang)
845 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
846
847 # Format
848 line1 = u"{u:>{uw}}".format(
849 u=user,
850 uw=len(user) + 2,
851 )
852 line2 = u"{p:>{pw}}".format(
853 p=profile_image_raw_url,
854 pw=len(profile_image_raw_url) + 4,
855 )
856 line3 = u"{d:>{dw}}".format(
857 d=description,
858 dw=len(description) + 4,
859 )
860 line4 = u"{l:>{lw}}".format(
861 l=location,
862 lw=len(location) + 4,
863 )
864 line5 = u"{u:>{uw}}".format(
865 u=url,
866 uw=len(url) + 4,
867 )
868 line6 = u"{c:>{cw}}".format(
869 c=clock,
870 cw=len(clock) + 4,
871 )
872
873 # Display
874 printNicely('')
875 printNicely(line1)
876 if c['IMAGE_ON_TERM']:
877 try:
878 response = requests.get(profile_image_url)
879 image_to_display(BytesIO(response.content))
880 except:
881 pass
882 else:
883 printNicely(line2)
884 for line in [line3, line4, line5, line6]:
885 printNicely(line)
886 printNicely('')
887
888
889 def print_trends(trends):
890 """
891 Display topics
892 """
893 for topic in trends[:c['TREND_MAX']]:
894 name = topic['name']
895 url = topic['url']
896 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
897 printNicely(line)
898 printNicely('')
899
900
901 def print_list(group, noti=False):
902 """
903 Display a list
904 """
905 for grp in group:
906 # Format
907 name = grp['full_name']
908 name = color_func(c['GROUP']['name'])(name + ' : ')
909 member = str(grp['member_count'])
910 member = color_func(c['GROUP']['member'])(member + ' member')
911 subscriber = str(grp['subscriber_count'])
912 subscriber = color_func(
913 c['GROUP']['subscriber'])(
914 subscriber +
915 ' subscriber')
916 description = grp['description'].strip()
917 description = color_func(c['GROUP']['description'])(description)
918 mode = grp['mode']
919 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
920 created_at = grp['created_at']
921 date = parser.parse(created_at)
922 lang, encode = locale.getdefaultlocale()
923 clock = arrow.get(date).to('local').humanize(locale=lang)
924 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
925
926 prefix = ' ' * 2
927 # Add spaces in begining of line if this is inside a notification
928 if noti:
929 prefix = ' ' * 2 + prefix
930 # Create lines
931 line1 = prefix + name + member + ' ' + subscriber
932 line2 = prefix + ' ' * 2 + description
933 line3 = prefix + ' ' * 2 + mode
934 line4 = prefix + ' ' * 2 + clock
935
936 # Display
937 printNicely('')
938 printNicely(line1)
939 printNicely(line2)
940 printNicely(line3)
941 printNicely(line4)
942
943 printNicely('')
944
945
946 def show_calendar(month, date, rel):
947 """
948 Show the calendar in rainbow mode
949 """
950 month = random_rainbow(month)
951 date = ' '.join([cycle_color(i) for i in date.split(' ')])
952 today = str(int(os.popen('date +\'%d\'').read().strip()))
953 # Display
954 printNicely(month)
955 printNicely(date)
956 for line in rel:
957 ary = line.split(' ')
958 ary = lmap(
959 lambda x: color_func(c['CAL']['today'])(x)
960 if x == today
961 else color_func(c['CAL']['days'])(x),
962 ary)
963 printNicely(' '.join(ary))
964
965
966 def format_quote(tweet):
967 """
968 Quoting format
969 """
970 # Retrieve info
971 screen_name = '@' + tweet['user']['screen_name']
972 text = tweet['text']
973 # Validate quote format
974 if '#owner' not in c['QUOTE_FORMAT']:
975 printNicely(light_magenta('Quote should contains #owner'))
976 return False
977 if '#comment' not in c['QUOTE_FORMAT']:
978 printNicely(light_magenta('Quote format should have #comment'))
979 return False
980 # Build formater
981 formater = ''
982 try:
983 formater = c['QUOTE_FORMAT']
984 formater = screen_name.join(formater.split('#owner'))
985 formater = text.join(formater.split('#tweet'))
986 formater = u2str(formater)
987 except:
988 pass
989 # Highlight like a tweet
990 notice = formater.split()
991 notice = lmap(
992 lambda x: light_green(x)
993 if x == '#comment'
994 else x,
995 notice)
996 notice = lmap(
997 lambda x: color_func(c['TWEET']['rt'])(x)
998 if x == 'RT'
999 else x,
1000 notice)
1001 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
1002 notice = lmap(
1003 lambda x: color_func(c['TWEET']['link'])(x)
1004 if x[0:4] == 'http'
1005 else x,
1006 notice)
1007 notice = lmap(
1008 lambda x: color_func(c['TWEET']['hashtag'])(x)
1009 if x.startswith('#')
1010 else x,
1011 notice)
1012 notice = ' '.join(notice)
1013 # Notice
1014 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
1015 printNicely(notice)
1016 return formater
1017
1018
1019 # Start the color cycle
1020 start_cycle()