updated succesfully
[rainbowstream.git] / rainbowstream / draw.py
... / ...
CommitLineData
1import random
2import itertools
3import requests
4import datetime
5import time
6import re
7
8from twitter.util import printNicely
9from functools import wraps
10from pyfiglet import figlet_format
11from dateutil import parser
12from .c_image import *
13from .colors import *
14from .config import *
15from .db import *
16from .py3patch import *
17
18
19db = RainbowDB()
20g = {}
21
22
23def 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
34def start_cycle():
35 """
36 Notify from rainbow
37 """
38 g['cyc'] = init_cycle()
39 g['cache'] = {}
40
41
42def 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
54def 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
66def 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
79def cycle_color(s):
80 """
81 Cycle the colors_shuffle
82 """
83 return next(g['cyc'])(s)
84
85
86def 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
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(' ')
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
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]
120 if c['THEME'] != themes[0]:
121 c['THEME'] = themes[0]
122 config = os.path.dirname(
123 __file__) + '/colorset/' + c['THEME'] + '.json'
124 # Load new config
125 data = load_config(config)
126 if data:
127 for d in data:
128 c[d] = data[d]
129 # Re-init color cycle
130 g['cyc'] = init_cycle()
131
132
133def color_func(func_name):
134 """
135 Call color function base on name
136 """
137 if str(func_name).isdigit():
138 return term_color(int(func_name))
139 return globals()[func_name]
140
141
142def draw(t, iot=False, keyword=None, check_semaphore=False, fil=[], ig=[]):
143 """
144 Draw the rainbow
145 """
146
147 check_theme()
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
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) + '] ')
199 if favorited:
200 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
201 tweet = text.split()
202 # Replace url
203 if expanded_url:
204 for index in range(len(expanded_url)):
205 tweet = lmap(
206 lambda x: expanded_url[index] if x == url[index] else x,
207 tweet)
208 # Highlight RT
209 tweet = lmap(
210 lambda x: color_func(
211 c['TWEET']['rt'])(x) if x == 'RT' else x,
212 tweet)
213 # Highlight screen_name
214 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
215 # Highlight link
216 tweet = lmap(
217 lambda x: color_func(
218 c['TWEET']['link'])(x) if x[
219 0:4] == 'http' else x,
220 tweet)
221
222 # Highlight keyword
223 tweet = ' '.join(tweet)
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)
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
243 # Check the semaphore lock
244 if check_semaphore:
245 while db.semaphore_query():
246 time.sleep(0.5)
247
248 # Output
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:
257 try:
258 response = requests.get(mu)
259 image_to_display(BytesIO(response.content))
260 except Exception:
261 printNicely(red('Sorry, image link is broken'))
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
285 # Draw
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 + ' ')
291 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
292 meta = color_func(
293 c['MESSAGE']['clock'])(
294 '[' + clock + ']') + color_func(
295 c['MESSAGE']['id'])(
296 ' [message_id=' + str(rid) + '] ')
297 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
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']
331
332 # Create content
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')
345 count = statuses_count + ' ' + friends_count + ' ' + followers_count
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)
350 description = ''.join(
351 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
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 '')
355 date = parser.parse(created_at)
356 date = date - datetime.timedelta(seconds=time.timezone)
357 clock = date.strftime('%Y/%m/%d %H:%M:%S')
358 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
359
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 )
385
386 # Display
387 printNicely('')
388 printNicely(line1)
389 if iot:
390 try:
391 response = requests.get(profile_image_url)
392 image_to_display(BytesIO(response.content), 2, 20)
393 except:
394 pass
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 """
406 for topic in trends[:c['TREND_MAX']]:
407 name = topic['name']
408 url = topic['url']
409 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
410 printNicely(line)
411 printNicely('')
412
413
414def print_list(group):
415 """
416 Display a list
417 """
418 for g in group:
419 # Format
420 name = g['full_name']
421 name = color_func(c['GROUP']['name'])(name + ' : ')
422 member = str(g['member_count'])
423 member = color_func(c['GROUP']['member'])(member + ' member')
424 subscriber = str(g['subscriber_count'])
425 subscriber = color_func(
426 c['GROUP']['subscriber'])(
427 subscriber +
428 ' subscriber')
429 description = g['description'].strip()
430 description = color_func(c['GROUP']['description'])(description)
431 mode = g['mode']
432 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
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
439 # Create lines
440 line1 = ' ' * 2 + name + member + ' ' + subscriber
441 line2 = ' ' * 4 + description
442 line3 = ' ' * 4 + mode
443 line4 = ' ' * 4 + clock
444
445 # Display
446 printNicely('')
447 printNicely(line1)
448 printNicely(line2)
449 printNicely(line3)
450 printNicely(line4)
451
452 printNicely('')
453
454
455# Start the color cycle
456start_cycle()