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