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