quote and pause bug fix
[rainbowstream.git] / rainbowstream / draw.py
... / ...
CommitLineData
1import random
2import itertools
3import requests
4import time
5import locale
6import arrow
7import re
8
9from twitter.util import printNicely
10from functools import wraps
11from pyfiglet import figlet_format
12from dateutil import parser
13from .c_image import *
14from .colors import *
15from .config import *
16from .py3patch import *
17
18# Draw global variables
19dg = {}
20
21
22def init_cycle():
23 """
24 Init the cycle
25 """
26 colors_shuffle = [globals()[i.encode('utf8')]
27 if not str(i).isdigit()
28 else term_color(int(i))
29 for i in c['CYCLE_COLOR']]
30 return itertools.cycle(colors_shuffle)
31
32
33def start_cycle():
34 """
35 Notify from rainbow
36 """
37 dg['cyc'] = init_cycle()
38 dg['cache'] = {}
39
40
41def order_rainbow(s):
42 """
43 Print a string with ordered color with each character
44 """
45 colors_shuffle = [globals()[i.encode('utf8')]
46 if not str(i).isdigit()
47 else term_color(int(i))
48 for i in c['CYCLE_COLOR']]
49 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
50 return ''.join(colored)
51
52
53def random_rainbow(s):
54 """
55 Print a string with random color with each character
56 """
57 colors_shuffle = [globals()[i.encode('utf8')]
58 if not str(i).isdigit()
59 else term_color(int(i))
60 for i in c['CYCLE_COLOR']]
61 colored = [random.choice(colors_shuffle)(i) for i in s]
62 return ''.join(colored)
63
64
65def Memoize(func):
66 """
67 Memoize decorator
68 """
69 @wraps(func)
70 def wrapper(*args):
71 if args not in dg['cache']:
72 dg['cache'][args] = func(*args)
73 return dg['cache'][args]
74 return wrapper
75
76
77@Memoize
78def cycle_color(s):
79 """
80 Cycle the colors_shuffle
81 """
82 return next(dg['cyc'])(s)
83
84
85def ascii_art(text):
86 """
87 Draw the Ascii Art
88 """
89 fi = figlet_format(text, font='doom')
90 print('\n'.join(
91 [next(dg['cyc'])(i) for i in fi.split('\n')]
92 ))
93
94
95def check_config():
96 """
97 Check if config is changed
98 """
99 changed = False
100 data = get_all_config()
101 for key in c:
102 if key in data:
103 if data[key] != c[key]:
104 changed = True
105 if changed:
106 reload_config()
107
108
109def validate_theme(theme):
110 """
111 Validate a theme exists or not
112 """
113 # Theme changed check
114 files = os.listdir(os.path.dirname(__file__) + '/colorset')
115 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
116 return theme in themes
117
118
119def reload_theme(value, prev):
120 """
121 Check current theme and update if necessary
122 """
123 if value != prev:
124 config = os.path.dirname(
125 __file__) + '/colorset/' + value + '.json'
126 # Load new config
127 data = load_config(config)
128 if data:
129 for d in data:
130 c[d] = data[d]
131 # Restart color cycle and update config
132 start_cycle()
133 set_config('THEME', value)
134 return value
135 return prev
136
137
138def color_func(func_name):
139 """
140 Call color function base on name
141 """
142 if str(func_name).isdigit():
143 return term_color(int(func_name))
144 return globals()[func_name]
145
146
147def draw(t, keyword=None, humanize=True, fil=[], ig=[]):
148 """
149 Draw the rainbow
150 """
151 # Check config
152 check_config()
153
154 # Retrieve tweet
155 tid = t['id']
156 text = t['text']
157 screen_name = t['user']['screen_name']
158 name = t['user']['name']
159 created_at = t['created_at']
160 favorited = t['favorited']
161 retweet_count = t['retweet_count']
162 favorite_count = t['favorite_count']
163 date = parser.parse(created_at)
164 date = arrow.get(date).to('local')
165 if humanize:
166 lang, encode = locale.getdefaultlocale()
167 clock = arrow.get(date).to('local').humanize(locale=lang)
168 else:
169 try:
170 clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT']
171 except:
172 clock_format = '%Y/%m/%d %H:%M:%S'
173 clock = date.datetime.strftime(clock_format)
174
175 # Pull extended retweet text
176 try:
177 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
178 t['retweeted_status']['text']
179 except:
180 pass
181
182 # Unescape HTML character
183 text = unescape(text)
184
185 # Get expanded url
186 try:
187 expanded_url = []
188 url = []
189 urls = t['entities']['urls']
190 for u in urls:
191 expanded_url.append(u['expanded_url'])
192 url.append(u['url'])
193 except:
194 expanded_url = None
195 url = None
196
197 # Get media
198 try:
199 media_url = []
200 media = t['entities']['media']
201 for m in media:
202 media_url.append(m['media_url'])
203 except:
204 media_url = None
205
206 # Filter and ignore
207 screen_name = '@' + screen_name
208 fil = list(set((fil or []) + c['ONLY_LIST']))
209 ig = list(set((ig or []) + c['IGNORE_LIST']))
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 xrange(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 formater = ''
272 try:
273 formater = c['FORMAT']['TWEET']['DISPLAY']
274 formater = name.join(formater.split('#name'))
275 formater = nick.join(formater.split('#nick'))
276 formater = fav.join(formater.split('#fav'))
277 formater = tweet.join(formater.split('#tweet'))
278 # Change clock word
279 word = [w for w in formater.split() if '#clock' in w][0]
280 delimiter = color_func(c['TWEET']['clock'])(
281 clock.join(word.split('#clock')))
282 formater = delimiter.join(formater.split(word))
283 # Change id word
284 word = [w for w in formater.split() if '#id' in w][0]
285 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
286 formater = delimiter.join(formater.split(word))
287 # Change retweet count word
288 word = [w for w in formater.split() if '#rt_count' in w][0]
289 delimiter = color_func(c['TWEET']['retweet_count'])(
290 str(retweet_count).join(word.split('#rt_count')))
291 formater = delimiter.join(formater.split(word))
292 # Change favorites count word
293 word = [w for w in formater.split() if '#fa_count' in w][0]
294 delimiter = color_func(c['TWEET']['favorite_count'])(
295 str(favorite_count).join(word.split('#fa_count')))
296 formater = delimiter.join(formater.split(word))
297 except:
298 pass
299
300 # Draw
301 printNicely(formater)
302
303 # Display Image
304 if c['IMAGE_ON_TERM'] and media_url:
305 for mu in media_url:
306 try:
307 response = requests.get(mu)
308 image_to_display(BytesIO(response.content))
309 except Exception:
310 printNicely(red('Sorry, image link is broken'))
311
312
313def print_message(m):
314 """
315 Print direct message
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 = arrow.get(date).to('local').datetime
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
378def 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 lang, encode = locale.getdefaultlocale()
419 clock = arrow.get(date).to('local').humanize(locale=lang)
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
464def 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
476def 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 lang, encode = locale.getdefaultlocale()
498 clock = arrow.get(date).to('local').humanize(locale=lang)
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
517def 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
537def format_quote(tweet):
538 """
539 Quoting format
540 """
541 # Retrieve info
542 screen_name = '@' + tweet['user']['screen_name']
543 text = tweet['text']
544 # Validate quote format
545 if '#owner' not in c['QUOTE_FORMAT']:
546 printNicely(light_magenta('Quote should contains #owner'))
547 return False
548 if '#comment' not in c['QUOTE_FORMAT']:
549 printNicely(light_magenta('Quote format should have #comment'))
550 return False
551 # Build formater
552 formater = ''
553 try:
554 formater = c['QUOTE_FORMAT']
555 formater = screen_name.join(formater.split('#owner'))
556 formater = text.join(formater.split('#tweet'))
557 formater = u2str(formater)
558 except:
559 pass
560 # Highlight like a tweet
561 notice = formater.split()
562 notice = lmap(
563 lambda x: light_green(x)
564 if x == '#comment'
565 else x,
566 notice)
567 notice = lmap(
568 lambda x: color_func(c['TWEET']['rt'])(x)
569 if x == 'RT'
570 else x,
571 notice)
572 notice = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, notice)
573 notice = lmap(
574 lambda x: color_func(c['TWEET']['link'])(x)
575 if x[0:4] == 'http'
576 else x,
577 notice)
578 notice = lmap(
579 lambda x: color_func(c['TWEET']['hashtag'])(x)
580 if x.startswith('#')
581 else x,
582 notice)
583 notice = ' '.join(notice)
584 # Notice
585 notice = light_magenta('Quoting: "') + notice + light_magenta('"')
586 printNicely(notice)
587 return formater
588
589
590# Start the color cycle
591start_cycle()