add notification command
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
e9f5200b 1import random
bcb5518e 2import textwrap
e9f5200b 3import itertools
7500d90b 4import requests
8b3456f9 5import locale
6import arrow
59262e95 7import re
67c663f8 8import os
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
99cd1fba 148def draw(t, keyword=None, humanize=True, noti=False, fil=[], ig=[]):
7500d90b
VNM
149 """
150 Draw the rainbow
151 """
99b52f5f 152 # Check config
92685d21 153 check_config()
c37c04a9 154
7500d90b
VNM
155 # Retrieve tweet
156 tid = t['id']
606def7e 157 text = t['text']
7500d90b
VNM
158 screen_name = t['user']['screen_name']
159 name = t['user']['name']
160 created_at = t['created_at']
161 favorited = t['favorited']
318cdd67
O
162 retweet_count = t['retweet_count']
163 favorite_count = t['favorite_count']
7500d90b 164 date = parser.parse(created_at)
8b3456f9 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)
7500d90b 175
606def7e
BR
176 # Pull extended retweet text
177 try:
18df6e7f
O
178 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
179 t['retweeted_status']['text']
606def7e
BR
180 except:
181 pass
182
18df6e7f 183 # Unescape HTML character
606def7e
BR
184 text = unescape(text)
185
7500d90b
VNM
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
37cf396a 208 mytweet = screen_name == c['original_name']
7500d90b 209 screen_name = '@' + screen_name
e3927852
O
210 fil = list(set((fil or []) + c['ONLY_LIST']))
211 ig = list(set((ig or []) + c['IGNORE_LIST']))
7500d90b
VNM
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
99b52f5f
O
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)
7500d90b
VNM
223
224 # Format info
8c7ae594 225 name = cycle_color(name)
571ea706
O
226 if mytweet:
227 nick = color_func(c['TWEET']['mynick'])(screen_name)
228 else:
229 nick = color_func(c['TWEET']['nick'])(screen_name)
0d9977c7
O
230 clock = clock
231 id = str(rid)
8c7ae594 232 fav = ''
7500d90b 233 if favorited:
8c7ae594
O
234 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
235
7500d90b
VNM
236 tweet = text.split()
237 # Replace url
238 if expanded_url:
13e6b275 239 for index in xrange(len(expanded_url)):
c3bab4ef 240 tweet = lmap(
8141aca6 241 lambda x: expanded_url[index]
242 if x == url[index]
243 else x,
7500d90b
VNM
244 tweet)
245 # Highlight RT
c3bab4ef 246 tweet = lmap(
8141aca6 247 lambda x: color_func(c['TWEET']['rt'])(x)
248 if x == 'RT'
249 else x,
c075e6dc 250 tweet)
7500d90b 251 # Highlight screen_name
c3bab4ef 252 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 253 # Highlight link
c3bab4ef 254 tweet = lmap(
8141aca6 255 lambda x: color_func(c['TWEET']['link'])(x)
37cf396a 256 if x.startswith('http')
8141aca6 257 else x,
c075e6dc 258 tweet)
4c025026 259 # Highlight hashtag
260 tweet = lmap(
8141aca6 261 lambda x: color_func(c['TWEET']['hashtag'])(x)
262 if x.startswith('#')
263 else x,
4c025026 264 tweet)
37cf396a
O
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 ]
59262e95 274 # Highlight keyword
7500d90b 275 tweet = ' '.join(tweet)
59262e95 276 if keyword:
a8c5fce4 277 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
278 if roj:
279 occur = roj.group()
280 ary = tweet.split(occur)
b13c6a0d 281 delimiter = color_func(c['TWEET']['keyword'])(occur)
282 tweet = delimiter.join(ary)
7500d90b 283
8c7ae594 284 # Load config formater
318cdd67 285 formater = ''
8c7ae594
O
286 try:
287 formater = c['FORMAT']['TWEET']['DISPLAY']
7c437a0f
O
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'))
0d9977c7 292 # Change clock word
03c0d30b 293 word = [wo for wo in formater.split() if '#clock' in wo][0]
8141aca6 294 delimiter = color_func(c['TWEET']['clock'])(
295 clock.join(word.split('#clock')))
0d9977c7
O
296 formater = delimiter.join(formater.split(word))
297 # Change id word
03c0d30b 298 word = [wo for wo in formater.split() if '#id' in wo][0]
0d9977c7
O
299 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
300 formater = delimiter.join(formater.split(word))
318cdd67 301 # Change retweet count word
03c0d30b 302 word = [wo for wo in formater.split() if '#rt_count' in wo][0]
318cdd67
O
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
03c0d30b 307 word = [wo for wo in formater.split() if '#fa_count' in wo][0]
318cdd67
O
308 delimiter = color_func(c['TWEET']['favorite_count'])(
309 str(favorite_count).join(word.split('#fa_count')))
310 formater = delimiter.join(formater.split(word))
8c7ae594 311 except:
318cdd67 312 pass
7500d90b 313
99cd1fba
O
314 # Add spaces in begining of line if this is inside a notification
315 if noti:
316 formater = '\n '.join(formater.split('\n'))
317
8c7ae594
O
318 # Draw
319 printNicely(formater)
7500d90b
VNM
320
321 # Display Image
fe9bb33b 322 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 323 for mu in media_url:
17bc529d 324 try:
325 response = requests.get(mu)
77f1d210 326 image_to_display(BytesIO(response.content))
327 except Exception:
17bc529d 328 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
329
330
67c663f8
O
331def 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)
03c0d30b 344 thread_id = color_func(c['MESSAGE']['id'])('thread_id:' + str(id))
345 line = ' ' * 2 + name + ' ' + screen_name + \
67c663f8
O
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
354def 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]
03c0d30b 360 messages.sort(key=lambda x: parser.parse(x['created_at']))
361 # Use legacy display on non-ascii text message
bcb5518e 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:
03c0d30b 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)
67c663f8
O
377 me_screen_name = color_func(c['MESSAGE']['me'])('@' + me_nick)
378 me_name = cycle_color(me_name)
03c0d30b 379 left = ' ' * margin + partner_name + ' ' + partner_nick
67c663f8
O
380 right = me_name + ' ' + me_screen_name + ' ' * margin
381 h, w = os.popen('stty size', 'r').read().split()
382 w = int(w)
03c0d30b 383 line = '{}{}{}'.format(
384 left, ' ' * (w - left_size - right_size - 2 * margin), right)
67c663f8
O
385 printNicely('')
386 printNicely(line)
387 printNicely('')
67c663f8
O
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
396def 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)
03c0d30b 402 frame_width = w // 3 - dg['frame_margin']
37cf396a 403 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
03c0d30b 404 step = frame_width - 2 * dg['frame_margin']
bcb5518e 405 slicing = textwrap.wrap(m['text'], step)
03c0d30b 406 spaces = w - frame_width - dg['frame_margin']
67c663f8 407 dotline = ' ' * spaces + '-' * frame_width
03c0d30b 408 dotline = color_func(c['MESSAGE']['me_frame'])(dotline)
223d2e05 409 # Draw the frame
67c663f8
O
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 + '|'
03c0d30b 418 screen_line = color_func(c['MESSAGE']['me_frame'])(screen_line)
67c663f8
O
419 printNicely(screen_line)
420 printNicely(dotline)
03c0d30b 421 # Format clock
223d2e05
O
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)
03c0d30b 430 # Format id
223d2e05
O
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'])
03c0d30b 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
223d2e05 457 printNicely(line)
67c663f8
O
458
459
460def 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)
03c0d30b 466 frame_width = w // 3 - dg['frame_margin']
37cf396a 467 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
03c0d30b 468 step = frame_width - 2 * dg['frame_margin']
bcb5518e 469 slicing = textwrap.wrap(m['text'], step)
03c0d30b 470 spaces = dg['frame_margin']
67c663f8 471 dotline = ' ' * spaces + '-' * frame_width
03c0d30b 472 dotline = color_func(c['MESSAGE']['partner_frame'])(dotline)
223d2e05 473 # Draw the frame
67c663f8
O
474 printNicely(dotline)
475 for line in slicing:
476 fill = step - len(line)
477 screen_line = ' ' + line + ' ' * fill + ' |'
478 if slicing[-1] == line:
03c0d30b 479 screen_line = ' ' * (spaces - 1) + '< ' + screen_line
67c663f8
O
480 else:
481 screen_line = ' ' * spaces + '|' + screen_line
03c0d30b 482 screen_line = color_func(c['MESSAGE']['partner_frame'])(screen_line)
67c663f8
O
483 printNicely(screen_line)
484 printNicely(dotline)
03c0d30b 485 # Format clock
223d2e05
O
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)
03c0d30b 494 # Format id
223d2e05
O
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'])
03c0d30b 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
223d2e05 521 printNicely(line)
67c663f8
O
522
523
4dc385b5 524def print_message(m):
7500d90b
VNM
525 """
526 Print direct message
527 """
c37c04a9 528 # Retrieve message
7500d90b
VNM
529 sender_screen_name = '@' + m['sender_screen_name']
530 sender_name = m['sender']['name']
b2cde062 531 text = unescape(m['text'])
7500d90b
VNM
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'])
8b3456f9 536 date = arrow.get(date).to('local').datetime
8c7ae594
O
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)
7500d90b
VNM
543
544 # Get rainbow id
99b52f5f
O
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)
7500d90b 550
6fa09c14 551 # Draw
8c7ae594
O
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)
0d9977c7
O
555 recipient_nick = color_func(
556 c['MESSAGE']['recipient'])(recipient_screen_name)
8c7ae594 557 to = color_func(c['MESSAGE']['to'])('>>>')
0d9977c7
O
558 clock = clock
559 id = str(rid)
8c7ae594 560
c3bab4ef 561 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b 562
8c7ae594
O
563 # Load config formater
564 try:
565 formater = c['FORMAT']['MESSAGE']['DISPLAY']
0d9977c7
O
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
03c0d30b 573 word = [wo for wo in formater.split() if '#clock' in wo][0]
8141aca6 574 delimiter = color_func(c['MESSAGE']['clock'])(
575 clock.join(word.split('#clock')))
0d9977c7
O
576 formater = delimiter.join(formater.split(word))
577 # Change id word
03c0d30b 578 word = [wo for wo in formater.split() if '#id' in wo][0]
0d9977c7
O
579 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
580 formater = delimiter.join(formater.split(word))
8c7ae594
O
581 except:
582 printNicely(red('Wrong format in config.'))
583 return
584
585 # Draw
586 printNicely(formater)
7500d90b
VNM
587
588
99cd1fba
O
589def 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
617def 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
646def 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
672def 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
700def 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
729def 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
758def 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
787def 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
fe9bb33b 803def show_profile(u):
7500d90b
VNM
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']
6fa09c14 818
7500d90b 819 # Create content
c075e6dc
O
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')
7500d90b 832 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
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)
7500d90b 837 description = ''.join(
c3bab4ef 838 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
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 '')
7500d90b 842 date = parser.parse(created_at)
8b3456f9 843 lang, encode = locale.getdefaultlocale()
844 clock = arrow.get(date).to('local').humanize(locale=lang)
632c6fa5 845 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 846
7500d90b
VNM
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 )
6fa09c14 872
7500d90b
VNM
873 # Display
874 printNicely('')
875 printNicely(line1)
fe9bb33b 876 if c['IMAGE_ON_TERM']:
17bc529d 877 try:
878 response = requests.get(profile_image_url)
c37c04a9 879 image_to_display(BytesIO(response.content))
17bc529d 880 except:
881 pass
7500d90b
VNM
882 else:
883 printNicely(line2)
884 for line in [line3, line4, line5, line6]:
885 printNicely(line)
886 printNicely('')
887
888
889def print_trends(trends):
890 """
891 Display topics
892 """
632c6fa5 893 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
894 name = topic['name']
895 url = topic['url']
8394e34b 896 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
897 printNicely(line)
898 printNicely('')
2d341029
O
899
900
99cd1fba 901def print_list(group, noti=False):
2d341029
O
902 """
903 Display a list
904 """
99b52f5f 905 for grp in group:
2d341029 906 # Format
99b52f5f 907 name = grp['full_name']
2d341029 908 name = color_func(c['GROUP']['name'])(name + ' : ')
99b52f5f 909 member = str(grp['member_count'])
422dd385 910 member = color_func(c['GROUP']['member'])(member + ' member')
99b52f5f 911 subscriber = str(grp['subscriber_count'])
422dd385
O
912 subscriber = color_func(
913 c['GROUP']['subscriber'])(
914 subscriber +
915 ' subscriber')
99b52f5f 916 description = grp['description'].strip()
2d341029 917 description = color_func(c['GROUP']['description'])(description)
99b52f5f 918 mode = grp['mode']
422dd385 919 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
99b52f5f 920 created_at = grp['created_at']
2d341029 921 date = parser.parse(created_at)
8b3456f9 922 lang, encode = locale.getdefaultlocale()
923 clock = arrow.get(date).to('local').humanize(locale=lang)
2d341029
O
924 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
925
99cd1fba
O
926 prefix = ' ' * 2
927 # Add spaces in begining of line if this is inside a notification
928 if noti:
929 prefix = ' ' * 2 + prefix
2d341029 930 # Create lines
99cd1fba
O
931 line1 = prefix + name + member + ' ' + subscriber
932 line2 = prefix + ' ' * 2 + description
933 line3 = prefix + ' ' * 2 + mode
934 line4 = prefix + ' ' * 2 + clock
2d341029
O
935
936 # Display
937 printNicely('')
938 printNicely(line1)
939 printNicely(line2)
940 printNicely(line3)
941 printNicely(line4)
942
943 printNicely('')
59262e95
O
944
945
8141aca6 946def 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
b7c9c570 966def 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
4dc385b5
O
990 notice = formater.split()
991 notice = lmap(
b7c9c570 992 lambda x: light_green(x)
993 if x == '#comment'
994 else x,
4dc385b5
O
995 notice)
996 notice = lmap(
b7c9c570 997 lambda x: color_func(c['TWEET']['rt'])(x)
998 if x == 'RT'
999 else x,
4dc385b5
O
1000 notice)
1001 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
1002 notice = lmap(
b7c9c570 1003 lambda x: color_func(c['TWEET']['link'])(x)
1004 if x[0:4] == 'http'
1005 else x,
4dc385b5
O
1006 notice)
1007 notice = lmap(
b7c9c570 1008 lambda x: color_func(c['TWEET']['hashtag'])(x)
1009 if x.startswith('#')
1010 else x,
4dc385b5
O
1011 notice)
1012 notice = ' '.join(notice)
b7c9c570 1013 # Notice
4dc385b5 1014 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
b7c9c570 1015 printNicely(notice)
1016 return formater
1017
1018
59262e95 1019# Start the color cycle
b2cde062 1020start_cycle()