5dd078807b32946e40db1d561b123c51e693d4ef
[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 fil = list(set((fil or []) + c['ONLY_LIST']))
211 ig = list(set((ig or []) + c['IGNORE_LIST']))
212 if fil and screen_name not in fil:
213 return
214 if ig and screen_name in ig:
215 return
216
217 # Get rainbow id
218 if tid not in c['tweet_dict']:
219 c['tweet_dict'].append(tid)
220 rid = len(c['tweet_dict']) - 1
221 else:
222 rid = c['tweet_dict'].index(tid)
223
224 # Format info
225 name = cycle_color(name)
226 nick = color_func(c['TWEET']['nick'])(screen_name)
227 clock = clock
228 id = str(rid)
229 fav = ''
230 if favorited:
231 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
232
233 tweet = text.split()
234 # Replace url
235 if expanded_url:
236 for index in range(len(expanded_url)):
237 tweet = lmap(
238 lambda x: expanded_url[index]
239 if x == url[index]
240 else x,
241 tweet)
242 # Highlight RT
243 tweet = lmap(
244 lambda x: color_func(c['TWEET']['rt'])(x)
245 if x == 'RT'
246 else x,
247 tweet)
248 # Highlight screen_name
249 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
250 # Highlight link
251 tweet = lmap(
252 lambda x: color_func(c['TWEET']['link'])(x)
253 if x[0:4] == 'http'
254 else x,
255 tweet)
256 # Highlight hashtag
257 tweet = lmap(
258 lambda x: color_func(c['TWEET']['hashtag'])(x)
259 if x.startswith('#')
260 else x,
261 tweet)
262 # Highlight keyword
263 tweet = ' '.join(tweet)
264 if keyword:
265 roj = re.search(keyword, tweet, re.IGNORECASE)
266 if roj:
267 occur = roj.group()
268 ary = tweet.split(occur)
269 delimiter = color_func(c['TWEET']['keyword'])(occur)
270 tweet = delimiter.join(ary)
271
272 # Load config formater
273 try:
274 formater = c['FORMAT']['TWEET']['DISPLAY']
275 formater = name.join(formater.split("#name"))
276 formater = nick.join(formater.split("#nick"))
277 formater = fav.join(formater.split("#fav"))
278 formater = tweet.join(formater.split("#tweet"))
279 # Change clock word
280 word = [w for w in formater.split() if '#clock' in w][0]
281 delimiter = color_func(c['TWEET']['clock'])(
282 clock.join(word.split('#clock')))
283 formater = delimiter.join(formater.split(word))
284 # Change id word
285 word = [w for w in formater.split() if '#id' in w][0]
286 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
287 formater = delimiter.join(formater.split(word))
288 except:
289 printNicely(red('Wrong format in config.'))
290 return
291
292 # Draw
293 printNicely(formater)
294
295 # Display Image
296 if c['IMAGE_ON_TERM'] and media_url:
297 for mu in media_url:
298 try:
299 response = requests.get(mu)
300 image_to_display(BytesIO(response.content))
301 except Exception:
302 printNicely(red('Sorry, image link is broken'))
303
304
305 def print_message(m, check_semaphore=False):
306 """
307 Print direct message
308 """
309
310 # Check the semaphore pause and lock (stream process only)
311 if check_semaphore:
312 if c['pause']:
313 return
314 while c['lock']:
315 time.sleep(0.5)
316
317 # Retrieve message
318 sender_screen_name = '@' + m['sender_screen_name']
319 sender_name = m['sender']['name']
320 text = unescape(m['text'])
321 recipient_screen_name = '@' + m['recipient_screen_name']
322 recipient_name = m['recipient']['name']
323 mid = m['id']
324 date = parser.parse(m['created_at'])
325 date = date - datetime.timedelta(seconds=time.timezone)
326 clock_format = '%Y/%m/%d %H:%M:%S'
327 try:
328 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
329 except:
330 pass
331 clock = date.strftime(clock_format)
332
333 # Get rainbow id
334 if mid not in c['message_dict']:
335 c['message_dict'].append(mid)
336 rid = len(c['message_dict']) - 1
337 else:
338 rid = c['message_dict'].index(mid)
339
340 # Draw
341 sender_name = cycle_color(sender_name)
342 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
343 recipient_name = cycle_color(recipient_name)
344 recipient_nick = color_func(
345 c['MESSAGE']['recipient'])(recipient_screen_name)
346 to = color_func(c['MESSAGE']['to'])('>>>')
347 clock = clock
348 id = str(rid)
349
350 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
351
352 # Load config formater
353 try:
354 formater = c['FORMAT']['MESSAGE']['DISPLAY']
355 formater = sender_name.join(formater.split("#sender_name"))
356 formater = sender_nick.join(formater.split("#sender_nick"))
357 formater = to.join(formater.split("#to"))
358 formater = recipient_name.join(formater.split("#recipient_name"))
359 formater = recipient_nick.join(formater.split("#recipient_nick"))
360 formater = text.join(formater.split("#message"))
361 # Change clock word
362 word = [w for w in formater.split() if '#clock' in w][0]
363 delimiter = color_func(c['MESSAGE']['clock'])(
364 clock.join(word.split('#clock')))
365 formater = delimiter.join(formater.split(word))
366 # Change id word
367 word = [w for w in formater.split() if '#id' in w][0]
368 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
369 formater = delimiter.join(formater.split(word))
370 except:
371 printNicely(red('Wrong format in config.'))
372 return
373
374 # Draw
375 printNicely(formater)
376
377
378 def show_profile(u):
379 """
380 Show a profile
381 """
382 # Retrieve info
383 name = u['name']
384 screen_name = u['screen_name']
385 description = u['description']
386 profile_image_url = u['profile_image_url']
387 location = u['location']
388 url = u['url']
389 created_at = u['created_at']
390 statuses_count = u['statuses_count']
391 friends_count = u['friends_count']
392 followers_count = u['followers_count']
393
394 # Create content
395 statuses_count = color_func(
396 c['PROFILE']['statuses_count'])(
397 str(statuses_count) +
398 ' tweets')
399 friends_count = color_func(
400 c['PROFILE']['friends_count'])(
401 str(friends_count) +
402 ' following')
403 followers_count = color_func(
404 c['PROFILE']['followers_count'])(
405 str(followers_count) +
406 ' followers')
407 count = statuses_count + ' ' + friends_count + ' ' + followers_count
408 user = cycle_color(
409 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
410 profile_image_raw_url = 'Profile photo: ' + \
411 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
412 description = ''.join(
413 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
414 description = color_func(c['PROFILE']['description'])(description)
415 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
416 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
417 date = parser.parse(created_at)
418 date = date - datetime.timedelta(seconds=time.timezone)
419 clock = date.strftime('%Y/%m/%d %H:%M:%S')
420 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
421
422 # Format
423 line1 = u"{u:>{uw}}".format(
424 u=user,
425 uw=len(user) + 2,
426 )
427 line2 = u"{p:>{pw}}".format(
428 p=profile_image_raw_url,
429 pw=len(profile_image_raw_url) + 4,
430 )
431 line3 = u"{d:>{dw}}".format(
432 d=description,
433 dw=len(description) + 4,
434 )
435 line4 = u"{l:>{lw}}".format(
436 l=location,
437 lw=len(location) + 4,
438 )
439 line5 = u"{u:>{uw}}".format(
440 u=url,
441 uw=len(url) + 4,
442 )
443 line6 = u"{c:>{cw}}".format(
444 c=clock,
445 cw=len(clock) + 4,
446 )
447
448 # Display
449 printNicely('')
450 printNicely(line1)
451 if c['IMAGE_ON_TERM']:
452 try:
453 response = requests.get(profile_image_url)
454 image_to_display(BytesIO(response.content))
455 except:
456 pass
457 else:
458 printNicely(line2)
459 for line in [line3, line4, line5, line6]:
460 printNicely(line)
461 printNicely('')
462
463
464 def print_trends(trends):
465 """
466 Display topics
467 """
468 for topic in trends[:c['TREND_MAX']]:
469 name = topic['name']
470 url = topic['url']
471 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
472 printNicely(line)
473 printNicely('')
474
475
476 def print_list(group):
477 """
478 Display a list
479 """
480 for grp in group:
481 # Format
482 name = grp['full_name']
483 name = color_func(c['GROUP']['name'])(name + ' : ')
484 member = str(grp['member_count'])
485 member = color_func(c['GROUP']['member'])(member + ' member')
486 subscriber = str(grp['subscriber_count'])
487 subscriber = color_func(
488 c['GROUP']['subscriber'])(
489 subscriber +
490 ' subscriber')
491 description = grp['description'].strip()
492 description = color_func(c['GROUP']['description'])(description)
493 mode = grp['mode']
494 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
495 created_at = grp['created_at']
496 date = parser.parse(created_at)
497 date = date - datetime.timedelta(seconds=time.timezone)
498 clock = date.strftime('%Y/%m/%d %H:%M:%S')
499 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
500
501 # Create lines
502 line1 = ' ' * 2 + name + member + ' ' + subscriber
503 line2 = ' ' * 4 + description
504 line3 = ' ' * 4 + mode
505 line4 = ' ' * 4 + clock
506
507 # Display
508 printNicely('')
509 printNicely(line1)
510 printNicely(line2)
511 printNicely(line3)
512 printNicely(line4)
513
514 printNicely('')
515
516
517 def show_calendar(month, date, rel):
518 """
519 Show the calendar in rainbow mode
520 """
521 month = random_rainbow(month)
522 date = ' '.join([cycle_color(i) for i in date.split(' ')])
523 today = str(int(os.popen('date +\'%d\'').read().strip()))
524 # Display
525 printNicely(month)
526 printNicely(date)
527 for line in rel:
528 ary = line.split(' ')
529 ary = lmap(
530 lambda x: color_func(c['CAL']['today'])(x)
531 if x == today
532 else color_func(c['CAL']['days'])(x),
533 ary)
534 printNicely(' '.join(ary))
535
536
537 # Start the color cycle
538 start_cycle()