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