delete unused lib
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
e9f5200b
VNM
1import random
2import itertools
7500d90b 3import requests
7500d90b 4import time
8b3456f9 5import locale
6import arrow
59262e95 7import re
7500d90b 8
2da50cc4 9from twitter.util import printNicely
e9f5200b
VNM
10from functools import wraps
11from pyfiglet import figlet_format
7500d90b 12from dateutil import parser
2da50cc4 13from .c_image import *
7500d90b
VNM
14from .colors import *
15from .config import *
c3bab4ef 16from .py3patch import *
17
99b52f5f
O
18# Draw global variables
19dg = {}
1fdd6a5c 20
422dd385 21
e9f5200b
VNM
22def init_cycle():
23 """
24 Init the cycle
25 """
26 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
27 if not str(i).isdigit()
28 else term_color(int(i))
422dd385 29 for i in c['CYCLE_COLOR']]
5f22104f 30 return itertools.cycle(colors_shuffle)
1fdd6a5c 31
e9f5200b 32
59262e95 33def start_cycle():
2359c276
VNM
34 """
35 Notify from rainbow
36 """
99b52f5f
O
37 dg['cyc'] = init_cycle()
38 dg['cache'] = {}
2359c276
VNM
39
40
e9f5200b
VNM
41def order_rainbow(s):
42 """
43 Print a string with ordered color with each character
44 """
5f22104f 45 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
46 if not str(i).isdigit()
47 else term_color(int(i))
422dd385 48 for i in c['CYCLE_COLOR']]
5f22104f 49 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
c3bab4ef 50 return ''.join(colored)
e9f5200b
VNM
51
52
53def random_rainbow(s):
54 """
55 Print a string with random color with each character
56 """
5f22104f 57 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
58 if not str(i).isdigit()
59 else term_color(int(i))
422dd385 60 for i in c['CYCLE_COLOR']]
5f22104f 61 colored = [random.choice(colors_shuffle)(i) for i in s]
c3bab4ef 62 return ''.join(colored)
e9f5200b
VNM
63
64
65def Memoize(func):
66 """
67 Memoize decorator
68 """
e9f5200b
VNM
69 @wraps(func)
70 def wrapper(*args):
99b52f5f
O
71 if args not in dg['cache']:
72 dg['cache'][args] = func(*args)
73 return dg['cache'][args]
e9f5200b
VNM
74 return wrapper
75
76
77@Memoize
78def cycle_color(s):
79 """
80 Cycle the colors_shuffle
81 """
99b52f5f 82 return next(dg['cyc'])(s)
e9f5200b
VNM
83
84
85def ascii_art(text):
86 """
87 Draw the Ascii Art
88 """
89 fi = figlet_format(text, font='doom')
90 print('\n'.join(
99b52f5f 91 [next(dg['cyc'])(i) for i in fi.split('\n')]
e9f5200b
VNM
92 ))
93
94
92685d21 95def check_config():
ceec8593 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
92685d21 117
118
99b52f5f 119def reload_theme(value, prev):
4cf86720
VNM
120 """
121 Check current theme and update if necessary
122 """
99b52f5f 123 if value != prev:
1f2f6159 124 config = os.path.dirname(
99b52f5f 125 __file__) + '/colorset/' + value + '.json'
4cf86720
VNM
126 # Load new config
127 data = load_config(config)
a5301bc0
VNM
128 if data:
129 for d in data:
130 c[d] = data[d]
99b52f5f 131 # Restart color cycle and update config
ceec8593 132 start_cycle()
99b52f5f
O
133 set_config('THEME', value)
134 return value
135 return prev
7500d90b 136
fe08f905
VNM
137
138def color_func(func_name):
139 """
140 Call color function base on name
141 """
fa6e062d
O
142 if str(func_name).isdigit():
143 return term_color(int(func_name))
c3bab4ef 144 return globals()[func_name]
fe08f905
VNM
145
146
8b3456f9 147def draw(t, keyword=None, humanize=True, check_semaphore=False, fil=[], ig=[]):
7500d90b
VNM
148 """
149 Draw the rainbow
150 """
151
99b52f5f 152 # Check the semaphore pause and lock (stream process only)
c37c04a9 153 if check_semaphore:
99b52f5f 154 if c['pause']:
c37c04a9 155 return
99b52f5f 156 while c['lock']:
c37c04a9
O
157 time.sleep(0.5)
158
99b52f5f 159 # Check config
92685d21 160 check_config()
c37c04a9 161
7500d90b
VNM
162 # Retrieve tweet
163 tid = t['id']
606def7e 164 text = t['text']
7500d90b
VNM
165 screen_name = t['user']['screen_name']
166 name = t['user']['name']
167 created_at = t['created_at']
168 favorited = t['favorited']
318cdd67
O
169 retweet_count = t['retweet_count']
170 favorite_count = t['favorite_count']
7500d90b 171 date = parser.parse(created_at)
8b3456f9 172 date = arrow.get(date).to('local')
173 if humanize:
174 lang, encode = locale.getdefaultlocale()
175 clock = arrow.get(date).to('local').humanize(locale=lang)
176 else:
177 try:
178 clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT']
179 except:
180 clock_format = '%Y/%m/%d %H:%M:%S'
181 clock = date.datetime.strftime(clock_format)
7500d90b 182
606def7e
BR
183 # Pull extended retweet text
184 try:
18df6e7f
O
185 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
186 t['retweeted_status']['text']
606def7e
BR
187 except:
188 pass
189
18df6e7f 190 # Unescape HTML character
606def7e
BR
191 text = unescape(text)
192
7500d90b
VNM
193 # Get expanded url
194 try:
195 expanded_url = []
196 url = []
197 urls = t['entities']['urls']
198 for u in urls:
199 expanded_url.append(u['expanded_url'])
200 url.append(u['url'])
201 except:
202 expanded_url = None
203 url = None
204
205 # Get media
206 try:
207 media_url = []
208 media = t['entities']['media']
209 for m in media:
210 media_url.append(m['media_url'])
211 except:
212 media_url = None
213
214 # Filter and ignore
215 screen_name = '@' + screen_name
e3927852
O
216 fil = list(set((fil or []) + c['ONLY_LIST']))
217 ig = list(set((ig or []) + c['IGNORE_LIST']))
7500d90b
VNM
218 if fil and screen_name not in fil:
219 return
220 if ig and screen_name in ig:
221 return
222
223 # Get rainbow id
99b52f5f
O
224 if tid not in c['tweet_dict']:
225 c['tweet_dict'].append(tid)
226 rid = len(c['tweet_dict']) - 1
227 else:
228 rid = c['tweet_dict'].index(tid)
7500d90b
VNM
229
230 # Format info
8c7ae594 231 name = cycle_color(name)
d6cc4c67 232 nick = color_func(c['TWEET']['nick'])(screen_name)
0d9977c7
O
233 clock = clock
234 id = str(rid)
8c7ae594 235 fav = ''
7500d90b 236 if favorited:
8c7ae594
O
237 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
238
7500d90b
VNM
239 tweet = text.split()
240 # Replace url
241 if expanded_url:
13e6b275 242 for index in xrange(len(expanded_url)):
c3bab4ef 243 tweet = lmap(
8141aca6 244 lambda x: expanded_url[index]
245 if x == url[index]
246 else x,
7500d90b
VNM
247 tweet)
248 # Highlight RT
c3bab4ef 249 tweet = lmap(
8141aca6 250 lambda x: color_func(c['TWEET']['rt'])(x)
251 if x == 'RT'
252 else x,
c075e6dc 253 tweet)
7500d90b 254 # Highlight screen_name
c3bab4ef 255 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 256 # Highlight link
c3bab4ef 257 tweet = lmap(
8141aca6 258 lambda x: color_func(c['TWEET']['link'])(x)
259 if x[0:4] == 'http'
260 else x,
c075e6dc 261 tweet)
4c025026 262 # Highlight hashtag
263 tweet = lmap(
8141aca6 264 lambda x: color_func(c['TWEET']['hashtag'])(x)
265 if x.startswith('#')
266 else x,
4c025026 267 tweet)
59262e95 268 # Highlight keyword
7500d90b 269 tweet = ' '.join(tweet)
59262e95 270 if keyword:
a8c5fce4 271 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
272 if roj:
273 occur = roj.group()
274 ary = tweet.split(occur)
b13c6a0d 275 delimiter = color_func(c['TWEET']['keyword'])(occur)
276 tweet = delimiter.join(ary)
7500d90b 277
8c7ae594 278 # Load config formater
318cdd67 279 formater = ''
8c7ae594
O
280 try:
281 formater = c['FORMAT']['TWEET']['DISPLAY']
7c437a0f
O
282 formater = name.join(formater.split('#name'))
283 formater = nick.join(formater.split('#nick'))
284 formater = fav.join(formater.split('#fav'))
285 formater = tweet.join(formater.split('#tweet'))
0d9977c7
O
286 # Change clock word
287 word = [w for w in formater.split() if '#clock' in w][0]
8141aca6 288 delimiter = color_func(c['TWEET']['clock'])(
289 clock.join(word.split('#clock')))
0d9977c7
O
290 formater = delimiter.join(formater.split(word))
291 # Change id word
292 word = [w for w in formater.split() if '#id' in w][0]
293 delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id')))
294 formater = delimiter.join(formater.split(word))
318cdd67
O
295 # Change retweet count word
296 word = [w for w in formater.split() if '#rt_count' in w][0]
297 delimiter = color_func(c['TWEET']['retweet_count'])(
298 str(retweet_count).join(word.split('#rt_count')))
299 formater = delimiter.join(formater.split(word))
300 # Change favorites count word
301 word = [w for w in formater.split() if '#fa_count' in w][0]
302 delimiter = color_func(c['TWEET']['favorite_count'])(
303 str(favorite_count).join(word.split('#fa_count')))
304 formater = delimiter.join(formater.split(word))
8c7ae594 305 except:
318cdd67 306 pass
7500d90b 307
8c7ae594
O
308 # Draw
309 printNicely(formater)
7500d90b
VNM
310
311 # Display Image
fe9bb33b 312 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 313 for mu in media_url:
17bc529d 314 try:
315 response = requests.get(mu)
77f1d210 316 image_to_display(BytesIO(response.content))
317 except Exception:
17bc529d 318 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
319
320
c37c04a9 321def print_message(m, check_semaphore=False):
7500d90b
VNM
322 """
323 Print direct message
324 """
c37c04a9 325
99b52f5f 326 # Check the semaphore pause and lock (stream process only)
c37c04a9 327 if check_semaphore:
99b52f5f 328 if c['pause']:
c37c04a9 329 return
99b52f5f 330 while c['lock']:
c37c04a9
O
331 time.sleep(0.5)
332
333 # Retrieve message
7500d90b
VNM
334 sender_screen_name = '@' + m['sender_screen_name']
335 sender_name = m['sender']['name']
b2cde062 336 text = unescape(m['text'])
7500d90b
VNM
337 recipient_screen_name = '@' + m['recipient_screen_name']
338 recipient_name = m['recipient']['name']
339 mid = m['id']
340 date = parser.parse(m['created_at'])
8b3456f9 341 date = arrow.get(date).to('local').datetime
8c7ae594
O
342 clock_format = '%Y/%m/%d %H:%M:%S'
343 try:
344 clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT']
345 except:
346 pass
347 clock = date.strftime(clock_format)
7500d90b
VNM
348
349 # Get rainbow id
99b52f5f
O
350 if mid not in c['message_dict']:
351 c['message_dict'].append(mid)
352 rid = len(c['message_dict']) - 1
353 else:
354 rid = c['message_dict'].index(mid)
7500d90b 355
6fa09c14 356 # Draw
8c7ae594
O
357 sender_name = cycle_color(sender_name)
358 sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name)
359 recipient_name = cycle_color(recipient_name)
0d9977c7
O
360 recipient_nick = color_func(
361 c['MESSAGE']['recipient'])(recipient_screen_name)
8c7ae594 362 to = color_func(c['MESSAGE']['to'])('>>>')
0d9977c7
O
363 clock = clock
364 id = str(rid)
8c7ae594 365
c3bab4ef 366 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b 367
8c7ae594
O
368 # Load config formater
369 try:
370 formater = c['FORMAT']['MESSAGE']['DISPLAY']
0d9977c7
O
371 formater = sender_name.join(formater.split("#sender_name"))
372 formater = sender_nick.join(formater.split("#sender_nick"))
373 formater = to.join(formater.split("#to"))
374 formater = recipient_name.join(formater.split("#recipient_name"))
375 formater = recipient_nick.join(formater.split("#recipient_nick"))
376 formater = text.join(formater.split("#message"))
377 # Change clock word
378 word = [w for w in formater.split() if '#clock' in w][0]
8141aca6 379 delimiter = color_func(c['MESSAGE']['clock'])(
380 clock.join(word.split('#clock')))
0d9977c7
O
381 formater = delimiter.join(formater.split(word))
382 # Change id word
383 word = [w for w in formater.split() if '#id' in w][0]
384 delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id')))
385 formater = delimiter.join(formater.split(word))
8c7ae594
O
386 except:
387 printNicely(red('Wrong format in config.'))
388 return
389
390 # Draw
391 printNicely(formater)
7500d90b
VNM
392
393
fe9bb33b 394def show_profile(u):
7500d90b
VNM
395 """
396 Show a profile
397 """
398 # Retrieve info
399 name = u['name']
400 screen_name = u['screen_name']
401 description = u['description']
402 profile_image_url = u['profile_image_url']
403 location = u['location']
404 url = u['url']
405 created_at = u['created_at']
406 statuses_count = u['statuses_count']
407 friends_count = u['friends_count']
408 followers_count = u['followers_count']
6fa09c14 409
7500d90b 410 # Create content
c075e6dc
O
411 statuses_count = color_func(
412 c['PROFILE']['statuses_count'])(
413 str(statuses_count) +
414 ' tweets')
415 friends_count = color_func(
416 c['PROFILE']['friends_count'])(
417 str(friends_count) +
418 ' following')
419 followers_count = color_func(
420 c['PROFILE']['followers_count'])(
421 str(followers_count) +
422 ' followers')
7500d90b 423 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
424 user = cycle_color(
425 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
426 profile_image_raw_url = 'Profile photo: ' + \
427 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b 428 description = ''.join(
c3bab4ef 429 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
430 description = color_func(c['PROFILE']['description'])(description)
431 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
432 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b 433 date = parser.parse(created_at)
8b3456f9 434 lang, encode = locale.getdefaultlocale()
435 clock = arrow.get(date).to('local').humanize(locale=lang)
632c6fa5 436 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 437
7500d90b
VNM
438 # Format
439 line1 = u"{u:>{uw}}".format(
440 u=user,
441 uw=len(user) + 2,
442 )
443 line2 = u"{p:>{pw}}".format(
444 p=profile_image_raw_url,
445 pw=len(profile_image_raw_url) + 4,
446 )
447 line3 = u"{d:>{dw}}".format(
448 d=description,
449 dw=len(description) + 4,
450 )
451 line4 = u"{l:>{lw}}".format(
452 l=location,
453 lw=len(location) + 4,
454 )
455 line5 = u"{u:>{uw}}".format(
456 u=url,
457 uw=len(url) + 4,
458 )
459 line6 = u"{c:>{cw}}".format(
460 c=clock,
461 cw=len(clock) + 4,
462 )
6fa09c14 463
7500d90b
VNM
464 # Display
465 printNicely('')
466 printNicely(line1)
fe9bb33b 467 if c['IMAGE_ON_TERM']:
17bc529d 468 try:
469 response = requests.get(profile_image_url)
c37c04a9 470 image_to_display(BytesIO(response.content))
17bc529d 471 except:
472 pass
7500d90b
VNM
473 else:
474 printNicely(line2)
475 for line in [line3, line4, line5, line6]:
476 printNicely(line)
477 printNicely('')
478
479
480def print_trends(trends):
481 """
482 Display topics
483 """
632c6fa5 484 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
485 name = topic['name']
486 url = topic['url']
8394e34b 487 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
488 printNicely(line)
489 printNicely('')
2d341029
O
490
491
492def print_list(group):
493 """
494 Display a list
495 """
99b52f5f 496 for grp in group:
2d341029 497 # Format
99b52f5f 498 name = grp['full_name']
2d341029 499 name = color_func(c['GROUP']['name'])(name + ' : ')
99b52f5f 500 member = str(grp['member_count'])
422dd385 501 member = color_func(c['GROUP']['member'])(member + ' member')
99b52f5f 502 subscriber = str(grp['subscriber_count'])
422dd385
O
503 subscriber = color_func(
504 c['GROUP']['subscriber'])(
505 subscriber +
506 ' subscriber')
99b52f5f 507 description = grp['description'].strip()
2d341029 508 description = color_func(c['GROUP']['description'])(description)
99b52f5f 509 mode = grp['mode']
422dd385 510 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
99b52f5f 511 created_at = grp['created_at']
2d341029 512 date = parser.parse(created_at)
8b3456f9 513 lang, encode = locale.getdefaultlocale()
514 clock = arrow.get(date).to('local').humanize(locale=lang)
2d341029
O
515 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
516
2d341029 517 # Create lines
422dd385
O
518 line1 = ' ' * 2 + name + member + ' ' + subscriber
519 line2 = ' ' * 4 + description
520 line3 = ' ' * 4 + mode
521 line4 = ' ' * 4 + clock
2d341029
O
522
523 # Display
524 printNicely('')
525 printNicely(line1)
526 printNicely(line2)
527 printNicely(line3)
528 printNicely(line4)
529
530 printNicely('')
59262e95
O
531
532
8141aca6 533def show_calendar(month, date, rel):
534 """
535 Show the calendar in rainbow mode
536 """
537 month = random_rainbow(month)
538 date = ' '.join([cycle_color(i) for i in date.split(' ')])
539 today = str(int(os.popen('date +\'%d\'').read().strip()))
540 # Display
541 printNicely(month)
542 printNicely(date)
543 for line in rel:
544 ary = line.split(' ')
545 ary = lmap(
546 lambda x: color_func(c['CAL']['today'])(x)
547 if x == today
548 else color_func(c['CAL']['days'])(x),
549 ary)
550 printNicely(' '.join(ary))
551
552
b7c9c570 553def format_quote(tweet):
554 """
555 Quoting format
556 """
557 # Retrieve info
558 screen_name = '@' + tweet['user']['screen_name']
559 text = tweet['text']
560 # Validate quote format
561 if '#owner' not in c['QUOTE_FORMAT']:
562 printNicely(light_magenta('Quote should contains #owner'))
563 return False
564 if '#comment' not in c['QUOTE_FORMAT']:
565 printNicely(light_magenta('Quote format should have #comment'))
566 return False
567 # Build formater
568 formater = ''
569 try:
570 formater = c['QUOTE_FORMAT']
571 formater = screen_name.join(formater.split('#owner'))
572 formater = text.join(formater.split('#tweet'))
573 formater = u2str(formater)
574 except:
575 pass
576 # Highlight like a tweet
577 formater = formater.split()
578 formater = lmap(
579 lambda x: light_green(x)
580 if x == '#comment'
581 else x,
582 formater)
583 formater = lmap(
584 lambda x: color_func(c['TWEET']['rt'])(x)
585 if x == 'RT'
586 else x,
587 formater)
588 formater = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, formater)
589 formater = lmap(
590 lambda x: color_func(c['TWEET']['link'])(x)
591 if x[0:4] == 'http'
592 else x,
593 formater)
594 formater = lmap(
595 lambda x: color_func(c['TWEET']['hashtag'])(x)
596 if x.startswith('#')
597 else x,
598 formater)
599 formater = ' '.join(formater)
600 # Notice
601 notice = light_magenta('Quoting: "') + formater + light_magenta('"')
602 printNicely(notice)
603 return formater
604
605
59262e95 606# Start the color cycle
b2cde062 607start_cycle()