Merge pull request #20 from bnrubin/master
[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
b2cde062
BR
23def unescape(s):
24 p = HTMLParser()
25 return p.unescape(s)
26
27
e9f5200b
VNM
28def init_cycle():
29 """
30 Init the cycle
31 """
32 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
33 if not str(i).isdigit()
34 else term_color(int(i))
422dd385 35 for i in c['CYCLE_COLOR']]
5f22104f 36 return itertools.cycle(colors_shuffle)
1fdd6a5c 37
e9f5200b 38
59262e95 39def start_cycle():
2359c276
VNM
40 """
41 Notify from rainbow
42 """
5f22104f 43 g['cyc'] = init_cycle()
e43ebfa6 44 g['cache'] = {}
2359c276
VNM
45
46
e9f5200b
VNM
47def order_rainbow(s):
48 """
49 Print a string with ordered color with each character
50 """
5f22104f 51 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
52 if not str(i).isdigit()
53 else term_color(int(i))
422dd385 54 for i in c['CYCLE_COLOR']]
5f22104f 55 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
c3bab4ef 56 return ''.join(colored)
e9f5200b
VNM
57
58
59def random_rainbow(s):
60 """
61 Print a string with random color with each character
62 """
5f22104f 63 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
64 if not str(i).isdigit()
65 else term_color(int(i))
422dd385 66 for i in c['CYCLE_COLOR']]
5f22104f 67 colored = [random.choice(colors_shuffle)(i) for i in s]
c3bab4ef 68 return ''.join(colored)
e9f5200b
VNM
69
70
71def Memoize(func):
72 """
73 Memoize decorator
74 """
e9f5200b
VNM
75 @wraps(func)
76 def wrapper(*args):
e43ebfa6 77 if args not in g['cache']:
78 g['cache'][args] = func(*args)
79 return g['cache'][args]
e9f5200b
VNM
80 return wrapper
81
82
83@Memoize
84def cycle_color(s):
85 """
86 Cycle the colors_shuffle
87 """
1fdd6a5c 88 return next(g['cyc'])(s)
e9f5200b
VNM
89
90
91def ascii_art(text):
92 """
93 Draw the Ascii Art
94 """
95 fi = figlet_format(text, font='doom')
96 print('\n'.join(
1fdd6a5c 97 [next(g['cyc'])(i) for i in fi.split('\n')]
e9f5200b
VNM
98 ))
99
100
2a0cabee
O
101def show_calendar(month, date, rel):
102 """
103 Show the calendar in rainbow mode
104 """
105 month = random_rainbow(month)
106 date = ' '.join([cycle_color(i) for i in date.split(' ')])
107 today = str(int(os.popen('date +\'%d\'').read().strip()))
108 # Display
109 printNicely(month)
110 printNicely(date)
111 for line in rel:
112 ary = line.split(' ')
c3bab4ef 113 ary = lmap(lambda x: color_func(c['CAL']['today'])(x)
422dd385
O
114 if x == today
115 else color_func(c['CAL']['days'])(x), ary)
2a0cabee
O
116 printNicely(' '.join(ary))
117
118
4cf86720
VNM
119def check_theme():
120 """
121 Check current theme and update if necessary
122 """
123 exists = db.theme_query()
124 themes = [t.theme_name for t in exists]
1f2f6159
O
125 if c['THEME'] != themes[0]:
126 c['THEME'] = themes[0]
127 config = os.path.dirname(
128 __file__) + '/colorset/' + c['THEME'] + '.json'
4cf86720
VNM
129 # Load new config
130 data = load_config(config)
a5301bc0
VNM
131 if data:
132 for d in data:
133 c[d] = data[d]
9c7342ca 134 # Re-init color cycle
1fdd6a5c 135 g['cyc'] = init_cycle()
7500d90b 136
fe08f905
VNM
137
138def color_func(func_name):
139 """
140 Call color function base on name
141 """
fa6e062d
O
142 if str(func_name).isdigit():
143 return term_color(int(func_name))
c3bab4ef 144 return globals()[func_name]
fe08f905
VNM
145
146
9683e61d 147def draw(t, iot=False, keyword=None, check_semaphore=False, fil=[], ig=[]):
7500d90b
VNM
148 """
149 Draw the rainbow
150 """
151
4cf86720 152 check_theme()
7500d90b
VNM
153 # Retrieve tweet
154 tid = t['id']
606def7e 155 text = t['text']
7500d90b
VNM
156 screen_name = t['user']['screen_name']
157 name = t['user']['name']
158 created_at = t['created_at']
159 favorited = t['favorited']
160 date = parser.parse(created_at)
161 date = date - datetime.timedelta(seconds=time.timezone)
162 clock = date.strftime('%Y/%m/%d %H:%M:%S')
163
606def7e
BR
164 # Pull extended retweet text
165 try:
166 text = 'RT @{0}: {1}'.format(t['retweeted_status']['user']['screen_name'],
167 t['retweeted_status']['text'])
168 except:
169 pass
170
171 text = unescape(text)
172
7500d90b
VNM
173 # Get expanded url
174 try:
175 expanded_url = []
176 url = []
177 urls = t['entities']['urls']
178 for u in urls:
179 expanded_url.append(u['expanded_url'])
180 url.append(u['url'])
181 except:
182 expanded_url = None
183 url = None
184
185 # Get media
186 try:
187 media_url = []
188 media = t['entities']['media']
189 for m in media:
190 media_url.append(m['media_url'])
191 except:
192 media_url = None
193
194 # Filter and ignore
195 screen_name = '@' + screen_name
196 if fil and screen_name not in fil:
197 return
198 if ig and screen_name in ig:
199 return
200
201 # Get rainbow id
202 res = db.tweet_to_rainbow_query(tid)
203 if not res:
204 db.tweet_store(tid)
205 res = db.tweet_to_rainbow_query(tid)
206 rid = res[0].rainbow_id
207
208 # Format info
c075e6dc
O
209 user = cycle_color(
210 name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
211 meta = color_func(c['TWEET']['clock'])(
212 '[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
7500d90b 213 if favorited:
1a0ac1b8 214 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
7500d90b
VNM
215 tweet = text.split()
216 # Replace url
217 if expanded_url:
218 for index in range(len(expanded_url)):
c3bab4ef 219 tweet = lmap(
7500d90b
VNM
220 lambda x: expanded_url[index] if x == url[index] else x,
221 tweet)
222 # Highlight RT
c3bab4ef 223 tweet = lmap(
c075e6dc
O
224 lambda x: color_func(
225 c['TWEET']['rt'])(x) if x == 'RT' else x,
226 tweet)
7500d90b 227 # Highlight screen_name
c3bab4ef 228 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 229 # Highlight link
c3bab4ef 230 tweet = lmap(
c075e6dc
O
231 lambda x: color_func(
232 c['TWEET']['link'])(x) if x[
233 0:4] == 'http' else x,
234 tweet)
59262e95
O
235
236 # Highlight keyword
7500d90b 237 tweet = ' '.join(tweet)
59262e95
O
238 if keyword:
239 roj = re.search(keyword,tweet,re.IGNORECASE)
240 if roj:
241 occur = roj.group()
242 ary = tweet.split(occur)
243 delimeter = color_func(c['TWEET']['keyword'])(occur)
244 tweet = delimeter.join(ary)
7500d90b
VNM
245
246 # Draw rainbow
247 line1 = u"{u:>{uw}}:".format(
248 u=user,
249 uw=len(user) + 2,
250 )
251 line2 = u"{c:>{cw}}".format(
252 c=meta,
253 cw=len(meta) + 2,
254 )
255 line3 = ' ' + tweet
256
9683e61d
O
257 # Check the semaphore lock
258 if check_semaphore:
259 while db.semaphore_query():
260 time.sleep(0.5)
261
262 # Output
7500d90b
VNM
263 printNicely('')
264 printNicely(line1)
265 printNicely(line2)
266 printNicely(line3)
267
268 # Display Image
269 if iot and media_url:
270 for mu in media_url:
17bc529d 271 try:
272 response = requests.get(mu)
77f1d210 273 image_to_display(BytesIO(response.content))
274 except Exception:
17bc529d 275 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
276
277
278def print_message(m):
279 """
280 Print direct message
281 """
282 sender_screen_name = '@' + m['sender_screen_name']
283 sender_name = m['sender']['name']
b2cde062 284 text = unescape(m['text'])
7500d90b
VNM
285 recipient_screen_name = '@' + m['recipient_screen_name']
286 recipient_name = m['recipient']['name']
287 mid = m['id']
288 date = parser.parse(m['created_at'])
289 date = date - datetime.timedelta(seconds=time.timezone)
290 clock = date.strftime('%Y/%m/%d %H:%M:%S')
291
292 # Get rainbow id
293 res = db.message_to_rainbow_query(mid)
294 if not res:
295 db.message_store(mid)
296 res = db.message_to_rainbow_query(mid)
297 rid = res[0].rainbow_id
298
6fa09c14 299 # Draw
c075e6dc
O
300 sender = cycle_color(
301 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
302 recipient = cycle_color(recipient_name) + color_func(
303 c['MESSAGE']['recipient'])(
304 ' ' + recipient_screen_name + ' ')
632c6fa5 305 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
c075e6dc
O
306 meta = color_func(
307 c['MESSAGE']['clock'])(
308 '[' + clock + ']') + color_func(
309 c['MESSAGE']['id'])(
310 ' [message_id=' + str(rid) + '] ')
c3bab4ef 311 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b
VNM
312
313 line1 = u"{u:>{uw}}:".format(
314 u=user,
315 uw=len(user) + 2,
316 )
317 line2 = u"{c:>{cw}}".format(
318 c=meta,
319 cw=len(meta) + 2,
320 )
321
322 line3 = ' ' + text
323
324 printNicely('')
325 printNicely(line1)
326 printNicely(line2)
327 printNicely(line3)
328
329
330def show_profile(u, iot=False):
331 """
332 Show a profile
333 """
334 # Retrieve info
335 name = u['name']
336 screen_name = u['screen_name']
337 description = u['description']
338 profile_image_url = u['profile_image_url']
339 location = u['location']
340 url = u['url']
341 created_at = u['created_at']
342 statuses_count = u['statuses_count']
343 friends_count = u['friends_count']
344 followers_count = u['followers_count']
6fa09c14 345
7500d90b 346 # Create content
c075e6dc
O
347 statuses_count = color_func(
348 c['PROFILE']['statuses_count'])(
349 str(statuses_count) +
350 ' tweets')
351 friends_count = color_func(
352 c['PROFILE']['friends_count'])(
353 str(friends_count) +
354 ' following')
355 followers_count = color_func(
356 c['PROFILE']['followers_count'])(
357 str(followers_count) +
358 ' followers')
7500d90b 359 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
360 user = cycle_color(
361 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
362 profile_image_raw_url = 'Profile photo: ' + \
363 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b 364 description = ''.join(
c3bab4ef 365 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
366 description = color_func(c['PROFILE']['description'])(description)
367 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
368 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b
VNM
369 date = parser.parse(created_at)
370 date = date - datetime.timedelta(seconds=time.timezone)
371 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 372 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 373
7500d90b
VNM
374 # Format
375 line1 = u"{u:>{uw}}".format(
376 u=user,
377 uw=len(user) + 2,
378 )
379 line2 = u"{p:>{pw}}".format(
380 p=profile_image_raw_url,
381 pw=len(profile_image_raw_url) + 4,
382 )
383 line3 = u"{d:>{dw}}".format(
384 d=description,
385 dw=len(description) + 4,
386 )
387 line4 = u"{l:>{lw}}".format(
388 l=location,
389 lw=len(location) + 4,
390 )
391 line5 = u"{u:>{uw}}".format(
392 u=url,
393 uw=len(url) + 4,
394 )
395 line6 = u"{c:>{cw}}".format(
396 c=clock,
397 cw=len(clock) + 4,
398 )
6fa09c14 399
7500d90b
VNM
400 # Display
401 printNicely('')
402 printNicely(line1)
403 if iot:
17bc529d 404 try:
405 response = requests.get(profile_image_url)
77f1d210 406 image_to_display(BytesIO(response.content), 2, 20)
17bc529d 407 except:
408 pass
7500d90b
VNM
409 else:
410 printNicely(line2)
411 for line in [line3, line4, line5, line6]:
412 printNicely(line)
413 printNicely('')
414
415
416def print_trends(trends):
417 """
418 Display topics
419 """
632c6fa5 420 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
421 name = topic['name']
422 url = topic['url']
8394e34b 423 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
424 printNicely(line)
425 printNicely('')
2d341029
O
426
427
428def print_list(group):
429 """
430 Display a list
431 """
432 for g in group:
433 # Format
422dd385 434 name = g['full_name']
2d341029
O
435 name = color_func(c['GROUP']['name'])(name + ' : ')
436 member = str(g['member_count'])
422dd385 437 member = color_func(c['GROUP']['member'])(member + ' member')
2d341029 438 subscriber = str(g['subscriber_count'])
422dd385
O
439 subscriber = color_func(
440 c['GROUP']['subscriber'])(
441 subscriber +
442 ' subscriber')
2d341029
O
443 description = g['description'].strip()
444 description = color_func(c['GROUP']['description'])(description)
445 mode = g['mode']
422dd385 446 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
2d341029
O
447 created_at = g['created_at']
448 date = parser.parse(created_at)
449 date = date - datetime.timedelta(seconds=time.timezone)
450 clock = date.strftime('%Y/%m/%d %H:%M:%S')
451 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
452
2d341029 453 # Create lines
422dd385
O
454 line1 = ' ' * 2 + name + member + ' ' + subscriber
455 line2 = ' ' * 4 + description
456 line3 = ' ' * 4 + mode
457 line4 = ' ' * 4 + clock
2d341029
O
458
459 # Display
460 printNicely('')
461 printNicely(line1)
462 printNicely(line2)
463 printNicely(line3)
464 printNicely(line4)
465
466 printNicely('')
59262e95
O
467
468
469# Start the color cycle
b2cde062 470start_cycle()