Merge pull request #47 from hexagon5un/master
[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
4dc385b5 148def draw(t, keyword=None, humanize=True, 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)
d6cc4c67 226 nick = color_func(c['TWEET']['nick'])(screen_name)
0d9977c7
O
227 clock = clock
228 id = str(rid)
8c7ae594 229 fav = ''
7500d90b 230 if favorited:
8c7ae594
O
231 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
232
7500d90b
VNM
233 tweet = text.split()
234 # Replace url
235 if expanded_url:
13e6b275 236 for index in xrange(len(expanded_url)):
c3bab4ef 237 tweet = lmap(
8141aca6 238 lambda x: expanded_url[index]
239 if x == url[index]
240 else x,
7500d90b
VNM
241 tweet)
242 # Highlight RT
c3bab4ef 243 tweet = lmap(
8141aca6 244 lambda x: color_func(c['TWEET']['rt'])(x)
245 if x == 'RT'
246 else x,
c075e6dc 247 tweet)
7500d90b 248 # Highlight screen_name
c3bab4ef 249 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 250 # Highlight link
c3bab4ef 251 tweet = lmap(
8141aca6 252 lambda x: color_func(c['TWEET']['link'])(x)
37cf396a 253 if x.startswith('http')
8141aca6 254 else x,
c075e6dc 255 tweet)
4c025026 256 # Highlight hashtag
257 tweet = lmap(
8141aca6 258 lambda x: color_func(c['TWEET']['hashtag'])(x)
259 if x.startswith('#')
260 else x,
4c025026 261 tweet)
37cf396a
O
262 # Highlight my tweet
263 if mytweet:
264 tweet = [color_func(c['TWEET']['mytweet'])(x)
265 for x in tweet
266 if not any([
267 x == 'RT',
268 x.startswith('http'),
269 x.startswith('#')])
270 ]
59262e95 271 # Highlight keyword
7500d90b 272 tweet = ' '.join(tweet)
59262e95 273 if keyword:
a8c5fce4 274 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
275 if roj:
276 occur = roj.group()
277 ary = tweet.split(occur)
b13c6a0d 278 delimiter = color_func(c['TWEET']['keyword'])(occur)
279 tweet = delimiter.join(ary)
7500d90b 280
8c7ae594 281 # Load config formater
318cdd67 282 formater = ''
8c7ae594
O
283 try:
284 formater = c['FORMAT']['TWEET']['DISPLAY']
7c437a0f
O
285 formater = name.join(formater.split('#name'))
286 formater = nick.join(formater.split('#nick'))
287 formater = fav.join(formater.split('#fav'))
288 formater = tweet.join(formater.split('#tweet'))
0d9977c7 289 # Change clock word
03c0d30b 290 word = [wo for wo in formater.split() if '#clock' in wo][0]
8141aca6 291 delimiter = color_func(c['TWEET']['clock'])(
292 clock.join(word.split('#clock')))
0d9977c7
O
293 formater = delimiter.join(formater.split(word))
294 # Change id word
03c0d30b 295 word = [wo for wo in formater.split() if '#id' in wo][0]
0d9977c7
O
296 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
297 formater = delimiter.join(formater.split(word))
318cdd67 298 # Change retweet count word
03c0d30b 299 word = [wo for wo in formater.split() if '#rt_count' in wo][0]
318cdd67
O
300 delimiter = color_func(c['TWEET']['retweet_count'])(
301 str(retweet_count).join(word.split('#rt_count')))
302 formater = delimiter.join(formater.split(word))
303 # Change favorites count word
03c0d30b 304 word = [wo for wo in formater.split() if '#fa_count' in wo][0]
318cdd67
O
305 delimiter = color_func(c['TWEET']['favorite_count'])(
306 str(favorite_count).join(word.split('#fa_count')))
307 formater = delimiter.join(formater.split(word))
8c7ae594 308 except:
318cdd67 309 pass
7500d90b 310
8c7ae594
O
311 # Draw
312 printNicely(formater)
7500d90b
VNM
313
314 # Display Image
fe9bb33b 315 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 316 for mu in media_url:
17bc529d 317 try:
318 response = requests.get(mu)
77f1d210 319 image_to_display(BytesIO(response.content))
320 except Exception:
17bc529d 321 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
322
323
67c663f8
O
324def print_threads(d):
325 """
326 Print threads of messages
327 """
328 id = 1
329 rel = {}
330 for partner in d:
331 messages = d[partner]
332 count = len(messages)
333 screen_name = '@' + partner[0]
334 name = partner[1]
335 screen_name = color_func(c['MESSAGE']['partner'])(screen_name)
336 name = cycle_color(name)
03c0d30b 337 thread_id = color_func(c['MESSAGE']['id'])('thread_id:' + str(id))
338 line = ' ' * 2 + name + ' ' + screen_name + \
67c663f8
O
339 ' (' + str(count) + ' message) ' + thread_id
340 printNicely(line)
341 rel[id] = partner
342 id += 1
343 dg['thread'] = d
344 return rel
345
346
347def print_thread(partner, me_nick, me_name):
348 """
349 Print a thread of messages
350 """
351 # Sort messages by time
352 messages = dg['thread'][partner]
03c0d30b 353 messages.sort(key=lambda x: parser.parse(x['created_at']))
354 # Use legacy display on non-ascii text message
bcb5518e 355 ms = [m['text'] for m in messages]
356 ums = [m for m in ms if not all(ord(c) < 128 for c in m)]
357 if ums:
03c0d30b 358 for m in messages:
359 print_message(m)
360 printNicely('')
361 return
362 # Print the first line
363 dg['frame_margin'] = margin = 2
364 partner_nick = partner[0]
365 partner_name = partner[1]
366 left_size = len(partner_nick) + len(partner_name) + 2
367 right_size = len(me_nick) + len(me_name) + 2
368 partner_nick = color_func(c['MESSAGE']['partner'])('@' + partner_nick)
369 partner_name = cycle_color(partner_name)
67c663f8
O
370 me_screen_name = color_func(c['MESSAGE']['me'])('@' + me_nick)
371 me_name = cycle_color(me_name)
03c0d30b 372 left = ' ' * margin + partner_name + ' ' + partner_nick
67c663f8
O
373 right = me_name + ' ' + me_screen_name + ' ' * margin
374 h, w = os.popen('stty size', 'r').read().split()
375 w = int(w)
03c0d30b 376 line = '{}{}{}'.format(
377 left, ' ' * (w - left_size - right_size - 2 * margin), right)
67c663f8
O
378 printNicely('')
379 printNicely(line)
380 printNicely('')
67c663f8
O
381 # Print messages
382 for m in messages:
383 if m['sender_screen_name'] == me_nick:
384 print_right_message(m)
385 elif m['recipient_screen_name'] == me_nick:
386 print_left_message(m)
387
388
389def print_right_message(m):
390 """
391 Print a message on the right of screen
392 """
393 h, w = os.popen('stty size', 'r').read().split()
394 w = int(w)
03c0d30b 395 frame_width = w // 3 - dg['frame_margin']
37cf396a 396 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
03c0d30b 397 step = frame_width - 2 * dg['frame_margin']
bcb5518e 398 slicing = textwrap.wrap(m['text'], step)
03c0d30b 399 spaces = w - frame_width - dg['frame_margin']
67c663f8 400 dotline = ' ' * spaces + '-' * frame_width
03c0d30b 401 dotline = color_func(c['MESSAGE']['me_frame'])(dotline)
223d2e05 402 # Draw the frame
67c663f8
O
403 printNicely(dotline)
404 for line in slicing:
405 fill = step - len(line)
406 screen_line = ' ' * spaces + '| ' + line + ' ' * fill + ' '
407 if slicing[-1] == line:
408 screen_line = screen_line + ' >'
409 else:
410 screen_line = screen_line + '|'
03c0d30b 411 screen_line = color_func(c['MESSAGE']['me_frame'])(screen_line)
67c663f8
O
412 printNicely(screen_line)
413 printNicely(dotline)
03c0d30b 414 # Format clock
223d2e05
O
415 date = parser.parse(m['created_at'])
416 date = arrow.get(date).to('local').datetime
417 clock_format = '%Y/%m/%d %H:%M:%S'
418 try:
419 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
420 except:
421 pass
422 clock = date.strftime(clock_format)
03c0d30b 423 # Format id
223d2e05
O
424 if m['id'] not in c['message_dict']:
425 c['message_dict'].append(m['id'])
426 rid = len(c['message_dict']) - 1
427 else:
428 rid = c['message_dict'].index(m['id'])
03c0d30b 429 id = str(rid)
430 # Print meta
431 formater = ''
432 try:
433 virtual_meta = formater = c['THREAD_META_RIGHT']
434 virtual_meta = clock.join(virtual_meta.split('#clock'))
435 virtual_meta = id.join(virtual_meta.split('#id'))
436 # Change clock word
437 word = [wo for wo in formater.split() if '#clock' in wo][0]
438 delimiter = color_func(c['MESSAGE']['clock'])(
439 clock.join(word.split('#clock')))
440 formater = delimiter.join(formater.split(word))
441 # Change id word
442 word = [wo for wo in formater.split() if '#id' in wo][0]
443 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
444 formater = delimiter.join(formater.split(word))
445 except Exception:
446 printNicely(red('Wrong format in config.'))
447 return
448 meta = formater
449 line = ' ' * (w - len(virtual_meta) - dg['frame_margin']) + meta
223d2e05 450 printNicely(line)
67c663f8
O
451
452
453def print_left_message(m):
454 """
455 Print a message on the left of screen
456 """
457 h, w = os.popen('stty size', 'r').read().split()
458 w = int(w)
03c0d30b 459 frame_width = w // 3 - dg['frame_margin']
37cf396a 460 frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
03c0d30b 461 step = frame_width - 2 * dg['frame_margin']
bcb5518e 462 slicing = textwrap.wrap(m['text'], step)
03c0d30b 463 spaces = dg['frame_margin']
67c663f8 464 dotline = ' ' * spaces + '-' * frame_width
03c0d30b 465 dotline = color_func(c['MESSAGE']['partner_frame'])(dotline)
223d2e05 466 # Draw the frame
67c663f8
O
467 printNicely(dotline)
468 for line in slicing:
469 fill = step - len(line)
470 screen_line = ' ' + line + ' ' * fill + ' |'
471 if slicing[-1] == line:
03c0d30b 472 screen_line = ' ' * (spaces - 1) + '< ' + screen_line
67c663f8
O
473 else:
474 screen_line = ' ' * spaces + '|' + screen_line
03c0d30b 475 screen_line = color_func(c['MESSAGE']['partner_frame'])(screen_line)
67c663f8
O
476 printNicely(screen_line)
477 printNicely(dotline)
03c0d30b 478 # Format clock
223d2e05
O
479 date = parser.parse(m['created_at'])
480 date = arrow.get(date).to('local').datetime
481 clock_format = '%Y/%m/%d %H:%M:%S'
482 try:
483 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
484 except:
485 pass
486 clock = date.strftime(clock_format)
03c0d30b 487 # Format id
223d2e05
O
488 if m['id'] not in c['message_dict']:
489 c['message_dict'].append(m['id'])
490 rid = len(c['message_dict']) - 1
491 else:
492 rid = c['message_dict'].index(m['id'])
03c0d30b 493 id = str(rid)
494 # Print meta
495 formater = ''
496 try:
497 virtual_meta = formater = c['THREAD_META_LEFT']
498 virtual_meta = clock.join(virtual_meta.split('#clock'))
499 virtual_meta = id.join(virtual_meta.split('#id'))
500 # Change clock word
501 word = [wo for wo in formater.split() if '#clock' in wo][0]
502 delimiter = color_func(c['MESSAGE']['clock'])(
503 clock.join(word.split('#clock')))
504 formater = delimiter.join(formater.split(word))
505 # Change id word
506 word = [wo for wo in formater.split() if '#id' in wo][0]
507 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
508 formater = delimiter.join(formater.split(word))
509 except Exception:
510 printNicely(red('Wrong format in config.'))
511 return
512 meta = formater
513 line = ' ' * dg['frame_margin'] + meta
223d2e05 514 printNicely(line)
67c663f8
O
515
516
4dc385b5 517def print_message(m):
7500d90b
VNM
518 """
519 Print direct message
520 """
c37c04a9 521 # Retrieve message
7500d90b
VNM
522 sender_screen_name = '@' + m['sender_screen_name']
523 sender_name = m['sender']['name']
b2cde062 524 text = unescape(m['text'])
7500d90b
VNM
525 recipient_screen_name = '@' + m['recipient_screen_name']
526 recipient_name = m['recipient']['name']
527 mid = m['id']
528 date = parser.parse(m['created_at'])
8b3456f9 529 date = arrow.get(date).to('local').datetime
8c7ae594
O
530 clock_format = '%Y/%m/%d %H:%M:%S'
531 try:
532 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
533 except:
534 pass
535 clock = date.strftime(clock_format)
7500d90b
VNM
536
537 # Get rainbow id
99b52f5f
O
538 if mid not in c['message_dict']:
539 c['message_dict'].append(mid)
540 rid = len(c['message_dict']) - 1
541 else:
542 rid = c['message_dict'].index(mid)
7500d90b 543
6fa09c14 544 # Draw
8c7ae594
O
545 sender_name = cycle_color(sender_name)
546 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
547 recipient_name = cycle_color(recipient_name)
0d9977c7
O
548 recipient_nick = color_func(
549 c['MESSAGE']['recipient'])(recipient_screen_name)
8c7ae594 550 to = color_func(c['MESSAGE']['to'])('>>>')
0d9977c7
O
551 clock = clock
552 id = str(rid)
8c7ae594 553
c3bab4ef 554 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b 555
8c7ae594
O
556 # Load config formater
557 try:
558 formater = c['FORMAT']['MESSAGE']['DISPLAY']
0d9977c7
O
559 formater = sender_name.join(formater.split("#sender_name"))
560 formater = sender_nick.join(formater.split("#sender_nick"))
561 formater = to.join(formater.split("#to"))
562 formater = recipient_name.join(formater.split("#recipient_name"))
563 formater = recipient_nick.join(formater.split("#recipient_nick"))
564 formater = text.join(formater.split("#message"))
565 # Change clock word
03c0d30b 566 word = [wo for wo in formater.split() if '#clock' in wo][0]
8141aca6 567 delimiter = color_func(c['MESSAGE']['clock'])(
568 clock.join(word.split('#clock')))
0d9977c7
O
569 formater = delimiter.join(formater.split(word))
570 # Change id word
03c0d30b 571 word = [wo for wo in formater.split() if '#id' in wo][0]
0d9977c7
O
572 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
573 formater = delimiter.join(formater.split(word))
8c7ae594
O
574 except:
575 printNicely(red('Wrong format in config.'))
576 return
577
578 # Draw
579 printNicely(formater)
7500d90b
VNM
580
581
fe9bb33b 582def show_profile(u):
7500d90b
VNM
583 """
584 Show a profile
585 """
586 # Retrieve info
587 name = u['name']
588 screen_name = u['screen_name']
589 description = u['description']
590 profile_image_url = u['profile_image_url']
591 location = u['location']
592 url = u['url']
593 created_at = u['created_at']
594 statuses_count = u['statuses_count']
595 friends_count = u['friends_count']
596 followers_count = u['followers_count']
6fa09c14 597
7500d90b 598 # Create content
c075e6dc
O
599 statuses_count = color_func(
600 c['PROFILE']['statuses_count'])(
601 str(statuses_count) +
602 ' tweets')
603 friends_count = color_func(
604 c['PROFILE']['friends_count'])(
605 str(friends_count) +
606 ' following')
607 followers_count = color_func(
608 c['PROFILE']['followers_count'])(
609 str(followers_count) +
610 ' followers')
7500d90b 611 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
612 user = cycle_color(
613 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
614 profile_image_raw_url = 'Profile photo: ' + \
615 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b 616 description = ''.join(
c3bab4ef 617 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
618 description = color_func(c['PROFILE']['description'])(description)
619 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
620 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b 621 date = parser.parse(created_at)
8b3456f9 622 lang, encode = locale.getdefaultlocale()
623 clock = arrow.get(date).to('local').humanize(locale=lang)
632c6fa5 624 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 625
7500d90b
VNM
626 # Format
627 line1 = u"{u:>{uw}}".format(
628 u=user,
629 uw=len(user) + 2,
630 )
631 line2 = u"{p:>{pw}}".format(
632 p=profile_image_raw_url,
633 pw=len(profile_image_raw_url) + 4,
634 )
635 line3 = u"{d:>{dw}}".format(
636 d=description,
637 dw=len(description) + 4,
638 )
639 line4 = u"{l:>{lw}}".format(
640 l=location,
641 lw=len(location) + 4,
642 )
643 line5 = u"{u:>{uw}}".format(
644 u=url,
645 uw=len(url) + 4,
646 )
647 line6 = u"{c:>{cw}}".format(
648 c=clock,
649 cw=len(clock) + 4,
650 )
6fa09c14 651
7500d90b
VNM
652 # Display
653 printNicely('')
654 printNicely(line1)
fe9bb33b 655 if c['IMAGE_ON_TERM']:
17bc529d 656 try:
657 response = requests.get(profile_image_url)
c37c04a9 658 image_to_display(BytesIO(response.content))
17bc529d 659 except:
660 pass
7500d90b
VNM
661 else:
662 printNicely(line2)
663 for line in [line3, line4, line5, line6]:
664 printNicely(line)
665 printNicely('')
666
667
668def print_trends(trends):
669 """
670 Display topics
671 """
632c6fa5 672 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
673 name = topic['name']
674 url = topic['url']
8394e34b 675 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
676 printNicely(line)
677 printNicely('')
2d341029
O
678
679
680def print_list(group):
681 """
682 Display a list
683 """
99b52f5f 684 for grp in group:
2d341029 685 # Format
99b52f5f 686 name = grp['full_name']
2d341029 687 name = color_func(c['GROUP']['name'])(name + ' : ')
99b52f5f 688 member = str(grp['member_count'])
422dd385 689 member = color_func(c['GROUP']['member'])(member + ' member')
99b52f5f 690 subscriber = str(grp['subscriber_count'])
422dd385
O
691 subscriber = color_func(
692 c['GROUP']['subscriber'])(
693 subscriber +
694 ' subscriber')
99b52f5f 695 description = grp['description'].strip()
2d341029 696 description = color_func(c['GROUP']['description'])(description)
99b52f5f 697 mode = grp['mode']
422dd385 698 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
99b52f5f 699 created_at = grp['created_at']
2d341029 700 date = parser.parse(created_at)
8b3456f9 701 lang, encode = locale.getdefaultlocale()
702 clock = arrow.get(date).to('local').humanize(locale=lang)
2d341029
O
703 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
704
2d341029 705 # Create lines
422dd385
O
706 line1 = ' ' * 2 + name + member + ' ' + subscriber
707 line2 = ' ' * 4 + description
708 line3 = ' ' * 4 + mode
709 line4 = ' ' * 4 + clock
2d341029
O
710
711 # Display
712 printNicely('')
713 printNicely(line1)
714 printNicely(line2)
715 printNicely(line3)
716 printNicely(line4)
717
718 printNicely('')
59262e95
O
719
720
8141aca6 721def show_calendar(month, date, rel):
722 """
723 Show the calendar in rainbow mode
724 """
725 month = random_rainbow(month)
726 date = ' '.join([cycle_color(i) for i in date.split(' ')])
727 today = str(int(os.popen('date +\'%d\'').read().strip()))
728 # Display
729 printNicely(month)
730 printNicely(date)
731 for line in rel:
732 ary = line.split(' ')
733 ary = lmap(
734 lambda x: color_func(c['CAL']['today'])(x)
735 if x == today
736 else color_func(c['CAL']['days'])(x),
737 ary)
738 printNicely(' '.join(ary))
739
740
b7c9c570 741def format_quote(tweet):
742 """
743 Quoting format
744 """
745 # Retrieve info
746 screen_name = '@' + tweet['user']['screen_name']
747 text = tweet['text']
748 # Validate quote format
749 if '#owner' not in c['QUOTE_FORMAT']:
750 printNicely(light_magenta('Quote should contains #owner'))
751 return False
752 if '#comment' not in c['QUOTE_FORMAT']:
753 printNicely(light_magenta('Quote format should have #comment'))
754 return False
755 # Build formater
756 formater = ''
757 try:
758 formater = c['QUOTE_FORMAT']
759 formater = screen_name.join(formater.split('#owner'))
760 formater = text.join(formater.split('#tweet'))
761 formater = u2str(formater)
762 except:
763 pass
764 # Highlight like a tweet
4dc385b5
O
765 notice = formater.split()
766 notice = lmap(
b7c9c570 767 lambda x: light_green(x)
768 if x == '#comment'
769 else x,
4dc385b5
O
770 notice)
771 notice = lmap(
b7c9c570 772 lambda x: color_func(c['TWEET']['rt'])(x)
773 if x == 'RT'
774 else x,
4dc385b5
O
775 notice)
776 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
777 notice = lmap(
b7c9c570 778 lambda x: color_func(c['TWEET']['link'])(x)
779 if x[0:4] == 'http'
780 else x,
4dc385b5
O
781 notice)
782 notice = lmap(
b7c9c570 783 lambda x: color_func(c['TWEET']['hashtag'])(x)
784 if x.startswith('#')
785 else x,
4dc385b5
O
786 notice)
787 notice = ' '.join(notice)
b7c9c570 788 # Notice
4dc385b5 789 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
b7c9c570 790 printNicely(notice)
791 return formater
792
793
59262e95 794# Start the color cycle
b2cde062 795start_cycle()