notify config changed in draw
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import itertools
3 import requests
4 import datetime
5 import time
6 import re
7
8 from twitter.util import printNicely
9 from functools import wraps
10 from pyfiglet import figlet_format
11 from dateutil import parser
12 from .c_image import *
13 from .colors import *
14 from .config import *
15 from .db import *
16 from .py3patch import *
17
18
19 db = RainbowDB()
20 g = {}
21
22
23 def init_cycle():
24 """
25 Init the cycle
26 """
27 colors_shuffle = [globals()[i.encode('utf8')]
28 if not str(i).isdigit()
29 else term_color(int(i))
30 for i in c['CYCLE_COLOR']]
31 return itertools.cycle(colors_shuffle)
32
33
34 def start_cycle():
35 """
36 Notify from rainbow
37 """
38 g['cyc'] = init_cycle()
39 g['cache'] = {}
40
41
42 def order_rainbow(s):
43 """
44 Print a string with ordered color with each character
45 """
46 colors_shuffle = [globals()[i.encode('utf8')]
47 if not str(i).isdigit()
48 else term_color(int(i))
49 for i in c['CYCLE_COLOR']]
50 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
51 return ''.join(colored)
52
53
54 def random_rainbow(s):
55 """
56 Print a string with random color with each character
57 """
58 colors_shuffle = [globals()[i.encode('utf8')]
59 if not str(i).isdigit()
60 else term_color(int(i))
61 for i in c['CYCLE_COLOR']]
62 colored = [random.choice(colors_shuffle)(i) for i in s]
63 return ''.join(colored)
64
65
66 def Memoize(func):
67 """
68 Memoize decorator
69 """
70 @wraps(func)
71 def wrapper(*args):
72 if args not in g['cache']:
73 g['cache'][args] = func(*args)
74 return g['cache'][args]
75 return wrapper
76
77
78 @Memoize
79 def cycle_color(s):
80 """
81 Cycle the colors_shuffle
82 """
83 return next(g['cyc'])(s)
84
85
86 def ascii_art(text):
87 """
88 Draw the Ascii Art
89 """
90 fi = figlet_format(text, font='doom')
91 print('\n'.join(
92 [next(g['cyc'])(i) for i in fi.split('\n')]
93 ))
94
95
96 def 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(' ')
108 ary = lmap(lambda x: color_func(c['CAL']['today'])(x)
109 if x == today
110 else color_func(c['CAL']['days'])(x), ary)
111 printNicely(' '.join(ary))
112
113
114 def 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
127 def 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]
133 if c['THEME'] != themes[0]:
134 c['THEME'] = themes[0]
135 config = os.path.dirname(
136 __file__) + '/colorset/' + c['THEME'] + '.json'
137 # Load new config
138 data = load_config(config)
139 if data:
140 for d in data:
141 c[d] = data[d]
142 # Re-init color cycle
143 g['cyc'] = init_cycle()
144
145
146 def color_func(func_name):
147 """
148 Call color function base on name
149 """
150 if str(func_name).isdigit():
151 return term_color(int(func_name))
152 return globals()[func_name]
153
154
155 def draw(t, iot=False, keyword=None, check_semaphore=False, fil=[], ig=[]):
156 """
157 Draw the rainbow
158 """
159
160 check_theme()
161 check_config()
162 # Retrieve tweet
163 tid = t['id']
164 text = t['text']
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
173 # Pull extended retweet text
174 try:
175 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
176 t['retweeted_status']['text']
177 except:
178 pass
179
180 # Unescape HTML character
181 text = unescape(text)
182
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
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) + '] ')
223 if favorited:
224 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
225 tweet = text.split()
226 # Replace url
227 if expanded_url:
228 for index in range(len(expanded_url)):
229 tweet = lmap(
230 lambda x: expanded_url[index] if x == url[index] else x,
231 tweet)
232 # Highlight RT
233 tweet = lmap(
234 lambda x: color_func(
235 c['TWEET']['rt'])(x) if x == 'RT' else x,
236 tweet)
237 # Highlight screen_name
238 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
239 # Highlight link
240 tweet = lmap(
241 lambda x: color_func(
242 c['TWEET']['link'])(x) if x[
243 0:4] == 'http' else x,
244 tweet)
245
246 # Highlight keyword
247 tweet = ' '.join(tweet)
248 if keyword:
249 roj = re.search(keyword, tweet, re.IGNORECASE)
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)
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
267 # Check the semaphore lock
268 if check_semaphore:
269 while db.semaphore_query():
270 time.sleep(0.5)
271
272 # Output
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:
281 try:
282 response = requests.get(mu)
283 image_to_display(BytesIO(response.content))
284 except Exception:
285 printNicely(red('Sorry, image link is broken'))
286
287
288 def print_message(m):
289 """
290 Print direct message
291 """
292 sender_screen_name = '@' + m['sender_screen_name']
293 sender_name = m['sender']['name']
294 text = unescape(m['text'])
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
309 # Draw
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 + ' ')
315 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
316 meta = color_func(
317 c['MESSAGE']['clock'])(
318 '[' + clock + ']') + color_func(
319 c['MESSAGE']['id'])(
320 ' [message_id=' + str(rid) + '] ')
321 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
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
340 def 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']
355
356 # Create content
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')
369 count = statuses_count + ' ' + friends_count + ' ' + followers_count
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)
374 description = ''.join(
375 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
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 '')
379 date = parser.parse(created_at)
380 date = date - datetime.timedelta(seconds=time.timezone)
381 clock = date.strftime('%Y/%m/%d %H:%M:%S')
382 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
383
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 )
409
410 # Display
411 printNicely('')
412 printNicely(line1)
413 if iot:
414 try:
415 response = requests.get(profile_image_url)
416 image_to_display(BytesIO(response.content), 2, 20)
417 except:
418 pass
419 else:
420 printNicely(line2)
421 for line in [line3, line4, line5, line6]:
422 printNicely(line)
423 printNicely('')
424
425
426 def print_trends(trends):
427 """
428 Display topics
429 """
430 for topic in trends[:c['TREND_MAX']]:
431 name = topic['name']
432 url = topic['url']
433 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
434 printNicely(line)
435 printNicely('')
436
437
438 def print_list(group):
439 """
440 Display a list
441 """
442 for g in group:
443 # Format
444 name = g['full_name']
445 name = color_func(c['GROUP']['name'])(name + ' : ')
446 member = str(g['member_count'])
447 member = color_func(c['GROUP']['member'])(member + ' member')
448 subscriber = str(g['subscriber_count'])
449 subscriber = color_func(
450 c['GROUP']['subscriber'])(
451 subscriber +
452 ' subscriber')
453 description = g['description'].strip()
454 description = color_func(c['GROUP']['description'])(description)
455 mode = g['mode']
456 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
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
463 # Create lines
464 line1 = ' ' * 2 + name + member + ' ' + subscriber
465 line2 = ' ' * 4 + description
466 line3 = ' ' * 4 + mode
467 line4 = ' ' * 4 + clock
468
469 # Display
470 printNicely('')
471 printNicely(line1)
472 printNicely(line2)
473 printNicely(line3)
474 printNicely(line4)
475
476 printNicely('')
477
478
479 # Start the color cycle
480 start_cycle()