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