Update index.rst
[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
92685d21 114def check_config():
115 """
116 Check if config is changed
117 """
118 changed = False
119 data = get_all_config()
fe9bb33b 120 for key in c:
121 if key in data:
122 if data[key] != c[key]:
123 changed = True
92685d21 124 if changed:
125 reload_config()
126
127
4cf86720
VNM
128def 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]
1f2f6159
O
134 if c['THEME'] != themes[0]:
135 c['THEME'] = themes[0]
136 config = os.path.dirname(
137 __file__) + '/colorset/' + c['THEME'] + '.json'
4cf86720
VNM
138 # Load new config
139 data = load_config(config)
a5301bc0
VNM
140 if data:
141 for d in data:
142 c[d] = data[d]
9c7342ca 143 # Re-init color cycle
1fdd6a5c 144 g['cyc'] = init_cycle()
7500d90b 145
fe08f905
VNM
146
147def color_func(func_name):
148 """
149 Call color function base on name
150 """
fa6e062d
O
151 if str(func_name).isdigit():
152 return term_color(int(func_name))
c3bab4ef 153 return globals()[func_name]
fe08f905
VNM
154
155
fe9bb33b 156def draw(t, keyword=None, check_semaphore=False, fil=[], ig=[]):
7500d90b
VNM
157 """
158 Draw the rainbow
159 """
160
4cf86720 161 check_theme()
92685d21 162 check_config()
7500d90b
VNM
163 # Retrieve tweet
164 tid = t['id']
606def7e 165 text = t['text']
7500d90b
VNM
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
606def7e
BR
174 # Pull extended retweet text
175 try:
18df6e7f
O
176 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
177 t['retweeted_status']['text']
606def7e
BR
178 except:
179 pass
180
18df6e7f 181 # Unescape HTML character
606def7e
BR
182 text = unescape(text)
183
7500d90b
VNM
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
c075e6dc
O
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) + '] ')
7500d90b 224 if favorited:
1a0ac1b8 225 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
7500d90b
VNM
226 tweet = text.split()
227 # Replace url
228 if expanded_url:
229 for index in range(len(expanded_url)):
c3bab4ef 230 tweet = lmap(
7500d90b
VNM
231 lambda x: expanded_url[index] if x == url[index] else x,
232 tweet)
233 # Highlight RT
c3bab4ef 234 tweet = lmap(
c075e6dc
O
235 lambda x: color_func(
236 c['TWEET']['rt'])(x) if x == 'RT' else x,
237 tweet)
7500d90b 238 # Highlight screen_name
c3bab4ef 239 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 240 # Highlight link
c3bab4ef 241 tweet = lmap(
c075e6dc
O
242 lambda x: color_func(
243 c['TWEET']['link'])(x) if x[
244 0:4] == 'http' else x,
245 tweet)
59262e95
O
246
247 # Highlight keyword
7500d90b 248 tweet = ' '.join(tweet)
59262e95 249 if keyword:
a8c5fce4 250 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
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)
7500d90b
VNM
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
9683e61d
O
268 # Check the semaphore lock
269 if check_semaphore:
270 while db.semaphore_query():
271 time.sleep(0.5)
272
273 # Output
7500d90b
VNM
274 printNicely('')
275 printNicely(line1)
276 printNicely(line2)
277 printNicely(line3)
278
279 # Display Image
fe9bb33b 280 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 281 for mu in media_url:
17bc529d 282 try:
283 response = requests.get(mu)
77f1d210 284 image_to_display(BytesIO(response.content))
285 except Exception:
17bc529d 286 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
287
288
289def print_message(m):
290 """
291 Print direct message
292 """
293 sender_screen_name = '@' + m['sender_screen_name']
294 sender_name = m['sender']['name']
b2cde062 295 text = unescape(m['text'])
7500d90b
VNM
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
6fa09c14 310 # Draw
c075e6dc
O
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 + ' ')
632c6fa5 316 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
c075e6dc
O
317 meta = color_func(
318 c['MESSAGE']['clock'])(
319 '[' + clock + ']') + color_func(
320 c['MESSAGE']['id'])(
321 ' [message_id=' + str(rid) + '] ')
c3bab4ef 322 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b
VNM
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
fe9bb33b 341def show_profile(u):
7500d90b
VNM
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']
6fa09c14 356
7500d90b 357 # Create content
c075e6dc
O
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')
7500d90b 370 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
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)
7500d90b 375 description = ''.join(
c3bab4ef 376 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
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 '')
7500d90b
VNM
380 date = parser.parse(created_at)
381 date = date - datetime.timedelta(seconds=time.timezone)
382 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 383 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 384
7500d90b
VNM
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 )
6fa09c14 410
7500d90b
VNM
411 # Display
412 printNicely('')
413 printNicely(line1)
fe9bb33b 414 if c['IMAGE_ON_TERM']:
17bc529d 415 try:
416 response = requests.get(profile_image_url)
77f1d210 417 image_to_display(BytesIO(response.content), 2, 20)
17bc529d 418 except:
419 pass
7500d90b
VNM
420 else:
421 printNicely(line2)
422 for line in [line3, line4, line5, line6]:
423 printNicely(line)
424 printNicely('')
425
426
427def print_trends(trends):
428 """
429 Display topics
430 """
632c6fa5 431 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
432 name = topic['name']
433 url = topic['url']
8394e34b 434 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
435 printNicely(line)
436 printNicely('')
2d341029
O
437
438
439def print_list(group):
440 """
441 Display a list
442 """
443 for g in group:
444 # Format
422dd385 445 name = g['full_name']
2d341029
O
446 name = color_func(c['GROUP']['name'])(name + ' : ')
447 member = str(g['member_count'])
422dd385 448 member = color_func(c['GROUP']['member'])(member + ' member')
2d341029 449 subscriber = str(g['subscriber_count'])
422dd385
O
450 subscriber = color_func(
451 c['GROUP']['subscriber'])(
452 subscriber +
453 ' subscriber')
2d341029
O
454 description = g['description'].strip()
455 description = color_func(c['GROUP']['description'])(description)
456 mode = g['mode']
422dd385 457 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
2d341029
O
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
2d341029 464 # Create lines
422dd385
O
465 line1 = ' ' * 2 + name + member + ' ' + subscriber
466 line2 = ' ' * 4 + description
467 line3 = ' ' * 4 + mode
468 line4 = ' ' * 4 + clock
2d341029
O
469
470 # Display
471 printNicely('')
472 printNicely(line1)
473 printNicely(line2)
474 printNicely(line3)
475 printNicely(line4)
476
477 printNicely('')
59262e95
O
478
479
480# Start the color cycle
b2cde062 481start_cycle()