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