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