notify config changed in draw
[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():
115 """
116 Check if config is changed
117 """
118 changed = False
119 data = get_all_config()
120 for key in data:
121 if data[key] != c[key]:
122 changed = True
123 if changed:
124 reload_config()
125
126
4cf86720
VNM
127def check_theme():
128 """
129 Check current theme and update if necessary
130 """
131 exists = db.theme_query()
132 themes = [t.theme_name for t in exists]
1f2f6159
O
133 if c['THEME'] != themes[0]:
134 c['THEME'] = themes[0]
135 config = os.path.dirname(
136 __file__) + '/colorset/' + c['THEME'] + '.json'
4cf86720
VNM
137 # Load new config
138 data = load_config(config)
a5301bc0
VNM
139 if data:
140 for d in data:
141 c[d] = data[d]
9c7342ca 142 # Re-init color cycle
1fdd6a5c 143 g['cyc'] = init_cycle()
7500d90b 144
fe08f905
VNM
145
146def color_func(func_name):
147 """
148 Call color function base on name
149 """
fa6e062d
O
150 if str(func_name).isdigit():
151 return term_color(int(func_name))
c3bab4ef 152 return globals()[func_name]
fe08f905
VNM
153
154
9683e61d 155def draw(t, iot=False, keyword=None, check_semaphore=False, fil=[], ig=[]):
7500d90b
VNM
156 """
157 Draw the rainbow
158 """
159
4cf86720 160 check_theme()
92685d21 161 check_config()
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']
169 date = parser.parse(created_at)
170 date = date - datetime.timedelta(seconds=time.timezone)
171 clock = date.strftime('%Y/%m/%d %H:%M:%S')
172
606def7e
BR
173 # Pull extended retweet text
174 try:
18df6e7f
O
175 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
176 t['retweeted_status']['text']
606def7e
BR
177 except:
178 pass
179
18df6e7f 180 # Unescape HTML character
606def7e
BR
181 text = unescape(text)
182
7500d90b
VNM
183 # Get expanded url
184 try:
185 expanded_url = []
186 url = []
187 urls = t['entities']['urls']
188 for u in urls:
189 expanded_url.append(u['expanded_url'])
190 url.append(u['url'])
191 except:
192 expanded_url = None
193 url = None
194
195 # Get media
196 try:
197 media_url = []
198 media = t['entities']['media']
199 for m in media:
200 media_url.append(m['media_url'])
201 except:
202 media_url = None
203
204 # Filter and ignore
205 screen_name = '@' + screen_name
206 if fil and screen_name not in fil:
207 return
208 if ig and screen_name in ig:
209 return
210
211 # Get rainbow id
212 res = db.tweet_to_rainbow_query(tid)
213 if not res:
214 db.tweet_store(tid)
215 res = db.tweet_to_rainbow_query(tid)
216 rid = res[0].rainbow_id
217
218 # Format info
c075e6dc
O
219 user = cycle_color(
220 name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
221 meta = color_func(c['TWEET']['clock'])(
222 '[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
7500d90b 223 if favorited:
1a0ac1b8 224 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
7500d90b
VNM
225 tweet = text.split()
226 # Replace url
227 if expanded_url:
228 for index in range(len(expanded_url)):
c3bab4ef 229 tweet = lmap(
7500d90b
VNM
230 lambda x: expanded_url[index] if x == url[index] else x,
231 tweet)
232 # Highlight RT
c3bab4ef 233 tweet = lmap(
c075e6dc
O
234 lambda x: color_func(
235 c['TWEET']['rt'])(x) if x == 'RT' else x,
236 tweet)
7500d90b 237 # Highlight screen_name
c3bab4ef 238 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 239 # Highlight link
c3bab4ef 240 tweet = lmap(
c075e6dc
O
241 lambda x: color_func(
242 c['TWEET']['link'])(x) if x[
243 0:4] == 'http' else x,
244 tweet)
59262e95
O
245
246 # Highlight keyword
7500d90b 247 tweet = ' '.join(tweet)
59262e95 248 if keyword:
a8c5fce4 249 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
250 if roj:
251 occur = roj.group()
252 ary = tweet.split(occur)
253 delimeter = color_func(c['TWEET']['keyword'])(occur)
254 tweet = delimeter.join(ary)
7500d90b
VNM
255
256 # Draw rainbow
257 line1 = u"{u:>{uw}}:".format(
258 u=user,
259 uw=len(user) + 2,
260 )
261 line2 = u"{c:>{cw}}".format(
262 c=meta,
263 cw=len(meta) + 2,
264 )
265 line3 = ' ' + tweet
266
9683e61d
O
267 # Check the semaphore lock
268 if check_semaphore:
269 while db.semaphore_query():
270 time.sleep(0.5)
271
272 # Output
7500d90b
VNM
273 printNicely('')
274 printNicely(line1)
275 printNicely(line2)
276 printNicely(line3)
277
278 # Display Image
279 if iot and media_url:
280 for mu in media_url:
17bc529d 281 try:
282 response = requests.get(mu)
77f1d210 283 image_to_display(BytesIO(response.content))
284 except Exception:
17bc529d 285 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
286
287
288def print_message(m):
289 """
290 Print direct message
291 """
292 sender_screen_name = '@' + m['sender_screen_name']
293 sender_name = m['sender']['name']
b2cde062 294 text = unescape(m['text'])
7500d90b
VNM
295 recipient_screen_name = '@' + m['recipient_screen_name']
296 recipient_name = m['recipient']['name']
297 mid = m['id']
298 date = parser.parse(m['created_at'])
299 date = date - datetime.timedelta(seconds=time.timezone)
300 clock = date.strftime('%Y/%m/%d %H:%M:%S')
301
302 # Get rainbow id
303 res = db.message_to_rainbow_query(mid)
304 if not res:
305 db.message_store(mid)
306 res = db.message_to_rainbow_query(mid)
307 rid = res[0].rainbow_id
308
6fa09c14 309 # Draw
c075e6dc
O
310 sender = cycle_color(
311 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
312 recipient = cycle_color(recipient_name) + color_func(
313 c['MESSAGE']['recipient'])(
314 ' ' + recipient_screen_name + ' ')
632c6fa5 315 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
c075e6dc
O
316 meta = color_func(
317 c['MESSAGE']['clock'])(
318 '[' + clock + ']') + color_func(
319 c['MESSAGE']['id'])(
320 ' [message_id=' + str(rid) + '] ')
c3bab4ef 321 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b
VNM
322
323 line1 = u"{u:>{uw}}:".format(
324 u=user,
325 uw=len(user) + 2,
326 )
327 line2 = u"{c:>{cw}}".format(
328 c=meta,
329 cw=len(meta) + 2,
330 )
331
332 line3 = ' ' + text
333
334 printNicely('')
335 printNicely(line1)
336 printNicely(line2)
337 printNicely(line3)
338
339
340def show_profile(u, iot=False):
341 """
342 Show a profile
343 """
344 # Retrieve info
345 name = u['name']
346 screen_name = u['screen_name']
347 description = u['description']
348 profile_image_url = u['profile_image_url']
349 location = u['location']
350 url = u['url']
351 created_at = u['created_at']
352 statuses_count = u['statuses_count']
353 friends_count = u['friends_count']
354 followers_count = u['followers_count']
6fa09c14 355
7500d90b 356 # Create content
c075e6dc
O
357 statuses_count = color_func(
358 c['PROFILE']['statuses_count'])(
359 str(statuses_count) +
360 ' tweets')
361 friends_count = color_func(
362 c['PROFILE']['friends_count'])(
363 str(friends_count) +
364 ' following')
365 followers_count = color_func(
366 c['PROFILE']['followers_count'])(
367 str(followers_count) +
368 ' followers')
7500d90b 369 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
370 user = cycle_color(
371 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
372 profile_image_raw_url = 'Profile photo: ' + \
373 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b 374 description = ''.join(
c3bab4ef 375 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
376 description = color_func(c['PROFILE']['description'])(description)
377 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
378 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b
VNM
379 date = parser.parse(created_at)
380 date = date - datetime.timedelta(seconds=time.timezone)
381 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 382 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 383
7500d90b
VNM
384 # Format
385 line1 = u"{u:>{uw}}".format(
386 u=user,
387 uw=len(user) + 2,
388 )
389 line2 = u"{p:>{pw}}".format(
390 p=profile_image_raw_url,
391 pw=len(profile_image_raw_url) + 4,
392 )
393 line3 = u"{d:>{dw}}".format(
394 d=description,
395 dw=len(description) + 4,
396 )
397 line4 = u"{l:>{lw}}".format(
398 l=location,
399 lw=len(location) + 4,
400 )
401 line5 = u"{u:>{uw}}".format(
402 u=url,
403 uw=len(url) + 4,
404 )
405 line6 = u"{c:>{cw}}".format(
406 c=clock,
407 cw=len(clock) + 4,
408 )
6fa09c14 409
7500d90b
VNM
410 # Display
411 printNicely('')
412 printNicely(line1)
413 if iot:
17bc529d 414 try:
415 response = requests.get(profile_image_url)
77f1d210 416 image_to_display(BytesIO(response.content), 2, 20)
17bc529d 417 except:
418 pass
7500d90b
VNM
419 else:
420 printNicely(line2)
421 for line in [line3, line4, line5, line6]:
422 printNicely(line)
423 printNicely('')
424
425
426def print_trends(trends):
427 """
428 Display topics
429 """
632c6fa5 430 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
431 name = topic['name']
432 url = topic['url']
8394e34b 433 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
434 printNicely(line)
435 printNicely('')
2d341029
O
436
437
438def print_list(group):
439 """
440 Display a list
441 """
442 for g in group:
443 # Format
422dd385 444 name = g['full_name']
2d341029
O
445 name = color_func(c['GROUP']['name'])(name + ' : ')
446 member = str(g['member_count'])
422dd385 447 member = color_func(c['GROUP']['member'])(member + ' member')
2d341029 448 subscriber = str(g['subscriber_count'])
422dd385
O
449 subscriber = color_func(
450 c['GROUP']['subscriber'])(
451 subscriber +
452 ' subscriber')
2d341029
O
453 description = g['description'].strip()
454 description = color_func(c['GROUP']['description'])(description)
455 mode = g['mode']
422dd385 456 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
2d341029
O
457 created_at = g['created_at']
458 date = parser.parse(created_at)
459 date = date - datetime.timedelta(seconds=time.timezone)
460 clock = date.strftime('%Y/%m/%d %H:%M:%S')
461 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
462
2d341029 463 # Create lines
422dd385
O
464 line1 = ' ' * 2 + name + member + ' ' + subscriber
465 line2 = ' ' * 4 + description
466 line3 = ' ' * 4 + mode
467 line4 = ' ' * 4 + clock
2d341029
O
468
469 # Display
470 printNicely('')
471 printNicely(line1)
472 printNicely(line2)
473 printNicely(line3)
474 printNicely(line4)
475
476 printNicely('')
59262e95
O
477
478
479# Start the color cycle
b2cde062 480start_cycle()