[] and id=
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import itertools
3 import requests
4 import datetime
5 import time
6 import re
7
8 from twitter.util import printNicely
9 from functools import wraps
10 from pyfiglet import figlet_format
11 from dateutil import parser
12 from .c_image import *
13 from .colors import *
14 from .config import *
15 from .db import *
16 from .py3patch import *
17
18
19 db = RainbowDB()
20 g = {}
21
22
23 def 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
34 def start_cycle():
35 """
36 Notify from rainbow
37 """
38 g['cyc'] = init_cycle()
39 g['cache'] = {}
40
41
42 def 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
54 def 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
66 def 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
79 def cycle_color(s):
80 """
81 Cycle the colors_shuffle
82 """
83 return next(g['cyc'])(s)
84
85
86 def 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
96 def 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
114 def check_config():
115 """
116 Check if config is changed
117 """
118 changed = False
119 data = get_all_config()
120 for key in c:
121 if key in data:
122 if data[key] != c[key]:
123 changed = True
124 if changed:
125 reload_config()
126
127
128 def validate_theme(theme):
129 """
130 Validate a theme exists or not
131 """
132 # Theme changed check
133 files = os.listdir(os.path.dirname(__file__) + '/colorset')
134 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
135 return theme in themes
136
137
138 def reload_theme(current_config):
139 """
140 Check current theme and update if necessary
141 """
142 exists = db.theme_query()
143 themes = [t.theme_name for t in exists]
144 if current_config != themes[0]:
145 config = os.path.dirname(
146 __file__) + '/colorset/' + current_config + '.json'
147 # Load new config
148 data = load_config(config)
149 if data:
150 for d in data:
151 c[d] = data[d]
152 # Restart color cycle and update db/config
153 start_cycle()
154 db.theme_update(current_config)
155 set_config('THEME', current_config)
156
157
158 def color_func(func_name):
159 """
160 Call color function base on name
161 """
162 if str(func_name).isdigit():
163 return term_color(int(func_name))
164 return globals()[func_name]
165
166
167 def draw(t, keyword=None, check_semaphore=False, fil=[], ig=[]):
168 """
169 Draw the rainbow
170 """
171
172 check_config()
173 reload_theme(c['THEME'])
174 # Retrieve tweet
175 tid = t['id']
176 text = t['text']
177 screen_name = t['user']['screen_name']
178 name = t['user']['name']
179 created_at = t['created_at']
180 favorited = t['favorited']
181 date = parser.parse(created_at)
182 date = date - datetime.timedelta(seconds=time.timezone)
183 clock_format = '%Y/%m/%d %H:%M:%S'
184 try:
185 clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT']
186 except:
187 pass
188 clock = date.strftime(clock_format)
189
190 # Pull extended retweet text
191 try:
192 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
193 t['retweeted_status']['text']
194 except:
195 pass
196
197 # Unescape HTML character
198 text = unescape(text)
199
200 # Get expanded url
201 try:
202 expanded_url = []
203 url = []
204 urls = t['entities']['urls']
205 for u in urls:
206 expanded_url.append(u['expanded_url'])
207 url.append(u['url'])
208 except:
209 expanded_url = None
210 url = None
211
212 # Get media
213 try:
214 media_url = []
215 media = t['entities']['media']
216 for m in media:
217 media_url.append(m['media_url'])
218 except:
219 media_url = None
220
221 # Filter and ignore
222 screen_name = '@' + screen_name
223 if fil and screen_name not in fil:
224 return
225 if ig and screen_name in ig:
226 return
227
228 # Get rainbow id
229 res = db.tweet_to_rainbow_query(tid)
230 if not res:
231 db.tweet_store(tid)
232 res = db.tweet_to_rainbow_query(tid)
233 rid = res[0].rainbow_id
234
235 # Format info
236 name = cycle_color(name)
237 nick = color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
238 clock = clock
239 id = str(rid)
240 fav = ''
241 if favorited:
242 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
243
244 tweet = text.split()
245 # Replace url
246 if expanded_url:
247 for index in range(len(expanded_url)):
248 tweet = lmap(
249 lambda x: expanded_url[index] if x == url[index] else x,
250 tweet)
251 # Highlight RT
252 tweet = lmap(
253 lambda x: color_func(
254 c['TWEET']['rt'])(x) if x == 'RT' else x,
255 tweet)
256 # Highlight screen_name
257 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
258 # Highlight link
259 tweet = lmap(
260 lambda x: color_func(
261 c['TWEET']['link'])(x) if x[
262 0:4] == 'http' else x,
263 tweet)
264
265 # Highlight keyword
266 tweet = ' '.join(tweet)
267 if keyword:
268 roj = re.search(keyword, tweet, re.IGNORECASE)
269 if roj:
270 occur = roj.group()
271 ary = tweet.split(occur)
272 delimiter = color_func(c['TWEET']['keyword'])(occur)
273 tweet = delimiter.join(ary)
274
275 # Load config formater
276 try:
277 formater = c['FORMAT']['TWEET']['DISPLAY']
278 formater = name.join(formater.split("#name"))
279 formater = nick.join(formater.split("#nick"))
280 formater = fav.join(formater.split("#fav"))
281 formater = tweet.join(formater.split("#tweet"))
282 # Change clock word
283 word = [w for w in formater.split() if '#clock' in w][0]
284 delimiter = color_func(
285 c['TWEET']['clock'])(
286 clock.join(
287 word.split('#clock')))
288 formater = delimiter.join(formater.split(word))
289 # Change id word
290 word = [w for w in formater.split() if '#id' in w][0]
291 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
292 formater = delimiter.join(formater.split(word))
293 except:
294 printNicely(red('Wrong format in config.'))
295 return
296
297 # Check the semaphore lock
298 if check_semaphore:
299 while db.semaphore_query():
300 time.sleep(0.5)
301
302 # Draw
303 printNicely(formater)
304
305 # Display Image
306 if c['IMAGE_ON_TERM'] and media_url:
307 for mu in media_url:
308 try:
309 response = requests.get(mu)
310 image_to_display(BytesIO(response.content))
311 except Exception:
312 printNicely(red('Sorry, image link is broken'))
313
314
315 def print_message(m):
316 """
317 Print direct message
318 """
319 sender_screen_name = '@' + m['sender_screen_name']
320 sender_name = m['sender']['name']
321 text = unescape(m['text'])
322 recipient_screen_name = '@' + m['recipient_screen_name']
323 recipient_name = m['recipient']['name']
324 mid = m['id']
325 date = parser.parse(m['created_at'])
326 date = date - datetime.timedelta(seconds=time.timezone)
327 clock_format = '%Y/%m/%d %H:%M:%S'
328 try:
329 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
330 except:
331 pass
332 clock = date.strftime(clock_format)
333
334 # Get rainbow id
335 res = db.message_to_rainbow_query(mid)
336 if not res:
337 db.message_store(mid)
338 res = db.message_to_rainbow_query(mid)
339 rid = res[0].rainbow_id
340
341 # Draw
342 sender_name = cycle_color(sender_name)
343 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
344 recipient_name = cycle_color(recipient_name)
345 recipient_nick = color_func(
346 c['MESSAGE']['recipient'])(recipient_screen_name)
347 to = color_func(c['MESSAGE']['to'])('>>>')
348 clock = clock
349 id = str(rid)
350
351 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
352
353 # Load config formater
354 try:
355 formater = c['FORMAT']['MESSAGE']['DISPLAY']
356 formater = sender_name.join(formater.split("#sender_name"))
357 formater = sender_nick.join(formater.split("#sender_nick"))
358 formater = to.join(formater.split("#to"))
359 formater = recipient_name.join(formater.split("#recipient_name"))
360 formater = recipient_nick.join(formater.split("#recipient_nick"))
361 formater = text.join(formater.split("#message"))
362 # Change clock word
363 word = [w for w in formater.split() if '#clock' in w][0]
364 delimiter = color_func(
365 c['MESSAGE']['clock'])(
366 clock.join(
367 word.split('#clock')))
368 formater = delimiter.join(formater.split(word))
369 # Change id word
370 word = [w for w in formater.split() if '#id' in w][0]
371 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
372 formater = delimiter.join(formater.split(word))
373 except:
374 printNicely(red('Wrong format in config.'))
375 return
376
377 # Draw
378 printNicely(formater)
379
380
381 def show_profile(u):
382 """
383 Show a profile
384 """
385 # Retrieve info
386 name = u['name']
387 screen_name = u['screen_name']
388 description = u['description']
389 profile_image_url = u['profile_image_url']
390 location = u['location']
391 url = u['url']
392 created_at = u['created_at']
393 statuses_count = u['statuses_count']
394 friends_count = u['friends_count']
395 followers_count = u['followers_count']
396
397 # Create content
398 statuses_count = color_func(
399 c['PROFILE']['statuses_count'])(
400 str(statuses_count) +
401 ' tweets')
402 friends_count = color_func(
403 c['PROFILE']['friends_count'])(
404 str(friends_count) +
405 ' following')
406 followers_count = color_func(
407 c['PROFILE']['followers_count'])(
408 str(followers_count) +
409 ' followers')
410 count = statuses_count + ' ' + friends_count + ' ' + followers_count
411 user = cycle_color(
412 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
413 profile_image_raw_url = 'Profile photo: ' + \
414 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
415 description = ''.join(
416 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
417 description = color_func(c['PROFILE']['description'])(description)
418 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
419 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
420 date = parser.parse(created_at)
421 date = date - datetime.timedelta(seconds=time.timezone)
422 clock = date.strftime('%Y/%m/%d %H:%M:%S')
423 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
424
425 # Format
426 line1 = u"{u:>{uw}}".format(
427 u=user,
428 uw=len(user) + 2,
429 )
430 line2 = u"{p:>{pw}}".format(
431 p=profile_image_raw_url,
432 pw=len(profile_image_raw_url) + 4,
433 )
434 line3 = u"{d:>{dw}}".format(
435 d=description,
436 dw=len(description) + 4,
437 )
438 line4 = u"{l:>{lw}}".format(
439 l=location,
440 lw=len(location) + 4,
441 )
442 line5 = u"{u:>{uw}}".format(
443 u=url,
444 uw=len(url) + 4,
445 )
446 line6 = u"{c:>{cw}}".format(
447 c=clock,
448 cw=len(clock) + 4,
449 )
450
451 # Display
452 printNicely('')
453 printNicely(line1)
454 if c['IMAGE_ON_TERM']:
455 try:
456 response = requests.get(profile_image_url)
457 image_to_display(BytesIO(response.content), 2, 20)
458 except:
459 pass
460 else:
461 printNicely(line2)
462 for line in [line3, line4, line5, line6]:
463 printNicely(line)
464 printNicely('')
465
466
467 def print_trends(trends):
468 """
469 Display topics
470 """
471 for topic in trends[:c['TREND_MAX']]:
472 name = topic['name']
473 url = topic['url']
474 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
475 printNicely(line)
476 printNicely('')
477
478
479 def print_list(group):
480 """
481 Display a list
482 """
483 for g in group:
484 # Format
485 name = g['full_name']
486 name = color_func(c['GROUP']['name'])(name + ' : ')
487 member = str(g['member_count'])
488 member = color_func(c['GROUP']['member'])(member + ' member')
489 subscriber = str(g['subscriber_count'])
490 subscriber = color_func(
491 c['GROUP']['subscriber'])(
492 subscriber +
493 ' subscriber')
494 description = g['description'].strip()
495 description = color_func(c['GROUP']['description'])(description)
496 mode = g['mode']
497 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
498 created_at = g['created_at']
499 date = parser.parse(created_at)
500 date = date - datetime.timedelta(seconds=time.timezone)
501 clock = date.strftime('%Y/%m/%d %H:%M:%S')
502 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
503
504 # Create lines
505 line1 = ' ' * 2 + name + member + ' ' + subscriber
506 line2 = ' ' * 4 + description
507 line3 = ' ' * 4 + mode
508 line4 = ' ' * 4 + clock
509
510 # Display
511 printNicely('')
512 printNicely(line1)
513 printNicely(line2)
514 printNicely(line3)
515 printNicely(line4)
516
517 printNicely('')
518
519
520 # Start the color cycle
521 start_cycle()