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