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