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