support quote format
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
e9f5200b
VNM
1import random
2import itertools
7500d90b
VNM
3import requests
4import datetime
5import time
59262e95 6import re
7500d90b 7
2da50cc4 8from twitter.util import printNicely
e9f5200b
VNM
9from functools import wraps
10from pyfiglet import figlet_format
7500d90b 11from dateutil import parser
2da50cc4 12from .c_image import *
7500d90b
VNM
13from .colors import *
14from .config import *
c3bab4ef 15from .py3patch import *
16
99b52f5f
O
17# Draw global variables
18dg = {}
1fdd6a5c 19
422dd385 20
e9f5200b
VNM
21def init_cycle():
22 """
23 Init the cycle
24 """
25 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
26 if not str(i).isdigit()
27 else term_color(int(i))
422dd385 28 for i in c['CYCLE_COLOR']]
5f22104f 29 return itertools.cycle(colors_shuffle)
1fdd6a5c 30
e9f5200b 31
59262e95 32def start_cycle():
2359c276
VNM
33 """
34 Notify from rainbow
35 """
99b52f5f
O
36 dg['cyc'] = init_cycle()
37 dg['cache'] = {}
2359c276
VNM
38
39
e9f5200b
VNM
40def order_rainbow(s):
41 """
42 Print a string with ordered color with each character
43 """
5f22104f 44 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
45 if not str(i).isdigit()
46 else term_color(int(i))
422dd385 47 for i in c['CYCLE_COLOR']]
5f22104f 48 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
c3bab4ef 49 return ''.join(colored)
e9f5200b
VNM
50
51
52def random_rainbow(s):
53 """
54 Print a string with random color with each character
55 """
5f22104f 56 colors_shuffle = [globals()[i.encode('utf8')]
fa6e062d
O
57 if not str(i).isdigit()
58 else term_color(int(i))
422dd385 59 for i in c['CYCLE_COLOR']]
5f22104f 60 colored = [random.choice(colors_shuffle)(i) for i in s]
c3bab4ef 61 return ''.join(colored)
e9f5200b
VNM
62
63
64def Memoize(func):
65 """
66 Memoize decorator
67 """
e9f5200b
VNM
68 @wraps(func)
69 def wrapper(*args):
99b52f5f
O
70 if args not in dg['cache']:
71 dg['cache'][args] = func(*args)
72 return dg['cache'][args]
e9f5200b
VNM
73 return wrapper
74
75
76@Memoize
77def cycle_color(s):
78 """
79 Cycle the colors_shuffle
80 """
99b52f5f 81 return next(dg['cyc'])(s)
e9f5200b
VNM
82
83
84def ascii_art(text):
85 """
86 Draw the Ascii Art
87 """
88 fi = figlet_format(text, font='doom')
89 print('\n'.join(
99b52f5f 90 [next(dg['cyc'])(i) for i in fi.split('\n')]
e9f5200b
VNM
91 ))
92
93
92685d21 94def check_config():
ceec8593 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
108def 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
92685d21 116
117
99b52f5f 118def reload_theme(value, prev):
4cf86720
VNM
119 """
120 Check current theme and update if necessary
121 """
99b52f5f 122 if value != prev:
1f2f6159 123 config = os.path.dirname(
99b52f5f 124 __file__) + '/colorset/' + value + '.json'
4cf86720
VNM
125 # Load new config
126 data = load_config(config)
a5301bc0
VNM
127 if data:
128 for d in data:
129 c[d] = data[d]
99b52f5f 130 # Restart color cycle and update config
ceec8593 131 start_cycle()
99b52f5f
O
132 set_config('THEME', value)
133 return value
134 return prev
7500d90b 135
fe08f905
VNM
136
137def color_func(func_name):
138 """
139 Call color function base on name
140 """
fa6e062d
O
141 if str(func_name).isdigit():
142 return term_color(int(func_name))
c3bab4ef 143 return globals()[func_name]
fe08f905
VNM
144
145
fe9bb33b 146def draw(t, keyword=None, check_semaphore=False, fil=[], ig=[]):
7500d90b
VNM
147 """
148 Draw the rainbow
149 """
150
99b52f5f 151 # Check the semaphore pause and lock (stream process only)
c37c04a9 152 if check_semaphore:
99b52f5f 153 if c['pause']:
c37c04a9 154 return
99b52f5f 155 while c['lock']:
c37c04a9
O
156 time.sleep(0.5)
157
99b52f5f 158 # Check config
92685d21 159 check_config()
c37c04a9 160
7500d90b
VNM
161 # Retrieve tweet
162 tid = t['id']
606def7e 163 text = t['text']
7500d90b
VNM
164 screen_name = t['user']['screen_name']
165 name = t['user']['name']
166 created_at = t['created_at']
167 favorited = t['favorited']
318cdd67
O
168 retweet_count = t['retweet_count']
169 favorite_count = t['favorite_count']
7500d90b
VNM
170 date = parser.parse(created_at)
171 date = date - datetime.timedelta(seconds=time.timezone)
8c7ae594
O
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)
7500d90b 178
606def7e
BR
179 # Pull extended retweet text
180 try:
18df6e7f
O
181 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
182 t['retweeted_status']['text']
606def7e
BR
183 except:
184 pass
185
18df6e7f 186 # Unescape HTML character
606def7e
BR
187 text = unescape(text)
188
7500d90b
VNM
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
e3927852
O
212 fil = list(set((fil or []) + c['ONLY_LIST']))
213 ig = list(set((ig or []) + c['IGNORE_LIST']))
7500d90b
VNM
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
99b52f5f
O
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)
7500d90b
VNM
225
226 # Format info
8c7ae594 227 name = cycle_color(name)
d6cc4c67 228 nick = color_func(c['TWEET']['nick'])(screen_name)
0d9977c7
O
229 clock = clock
230 id = str(rid)
8c7ae594 231 fav = ''
7500d90b 232 if favorited:
8c7ae594
O
233 fav = color_func(c['TWEET']['favorited'])(u'\u2605')
234
7500d90b
VNM
235 tweet = text.split()
236 # Replace url
237 if expanded_url:
13e6b275 238 for index in xrange(len(expanded_url)):
c3bab4ef 239 tweet = lmap(
8141aca6 240 lambda x: expanded_url[index]
241 if x == url[index]
242 else x,
7500d90b
VNM
243 tweet)
244 # Highlight RT
c3bab4ef 245 tweet = lmap(
8141aca6 246 lambda x: color_func(c['TWEET']['rt'])(x)
247 if x == 'RT'
248 else x,
c075e6dc 249 tweet)
7500d90b 250 # Highlight screen_name
c3bab4ef 251 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
7500d90b 252 # Highlight link
c3bab4ef 253 tweet = lmap(
8141aca6 254 lambda x: color_func(c['TWEET']['link'])(x)
255 if x[0:4] == 'http'
256 else x,
c075e6dc 257 tweet)
4c025026 258 # Highlight hashtag
259 tweet = lmap(
8141aca6 260 lambda x: color_func(c['TWEET']['hashtag'])(x)
261 if x.startswith('#')
262 else x,
4c025026 263 tweet)
59262e95 264 # Highlight keyword
7500d90b 265 tweet = ' '.join(tweet)
59262e95 266 if keyword:
a8c5fce4 267 roj = re.search(keyword, tweet, re.IGNORECASE)
59262e95
O
268 if roj:
269 occur = roj.group()
270 ary = tweet.split(occur)
b13c6a0d 271 delimiter = color_func(c['TWEET']['keyword'])(occur)
272 tweet = delimiter.join(ary)
7500d90b 273
8c7ae594 274 # Load config formater
318cdd67 275 formater = ''
8c7ae594
O
276 try:
277 formater = c['FORMAT']['TWEET']['DISPLAY']
7c437a0f
O
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'))
0d9977c7
O
282 # Change clock word
283 word = [w for w in formater.split() if '#clock' in w][0]
8141aca6 284 delimiter = color_func(c['TWEET']['clock'])(
285 clock.join(word.split('#clock')))
0d9977c7
O
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))
318cdd67
O
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))
8c7ae594 301 except:
318cdd67 302 pass
7500d90b 303
8c7ae594
O
304 # Draw
305 printNicely(formater)
7500d90b
VNM
306
307 # Display Image
fe9bb33b 308 if c['IMAGE_ON_TERM'] and media_url:
7500d90b 309 for mu in media_url:
17bc529d 310 try:
311 response = requests.get(mu)
77f1d210 312 image_to_display(BytesIO(response.content))
313 except Exception:
17bc529d 314 printNicely(red('Sorry, image link is broken'))
7500d90b
VNM
315
316
c37c04a9 317def print_message(m, check_semaphore=False):
7500d90b
VNM
318 """
319 Print direct message
320 """
c37c04a9 321
99b52f5f 322 # Check the semaphore pause and lock (stream process only)
c37c04a9 323 if check_semaphore:
99b52f5f 324 if c['pause']:
c37c04a9 325 return
99b52f5f 326 while c['lock']:
c37c04a9
O
327 time.sleep(0.5)
328
329 # Retrieve message
7500d90b
VNM
330 sender_screen_name = '@' + m['sender_screen_name']
331 sender_name = m['sender']['name']
b2cde062 332 text = unescape(m['text'])
7500d90b
VNM
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)
8c7ae594
O
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)
7500d90b
VNM
344
345 # Get rainbow id
99b52f5f
O
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)
7500d90b 351
6fa09c14 352 # Draw
8c7ae594
O
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)
0d9977c7
O
356 recipient_nick = color_func(
357 c['MESSAGE']['recipient'])(recipient_screen_name)
8c7ae594 358 to = color_func(c['MESSAGE']['to'])('>>>')
0d9977c7
O
359 clock = clock
360 id = str(rid)
8c7ae594 361
c3bab4ef 362 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
7500d90b 363
8c7ae594
O
364 # Load config formater
365 try:
366 formater = c['FORMAT']['MESSAGE']['DISPLAY']
0d9977c7
O
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]
8141aca6 375 delimiter = color_func(c['MESSAGE']['clock'])(
376 clock.join(word.split('#clock')))
0d9977c7
O
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))
8c7ae594
O
382 except:
383 printNicely(red('Wrong format in config.'))
384 return
385
386 # Draw
387 printNicely(formater)
7500d90b
VNM
388
389
fe9bb33b 390def show_profile(u):
7500d90b
VNM
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']
6fa09c14 405
7500d90b 406 # Create content
c075e6dc
O
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')
7500d90b 419 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
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)
7500d90b 424 description = ''.join(
c3bab4ef 425 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
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 '')
7500d90b
VNM
429 date = parser.parse(created_at)
430 date = date - datetime.timedelta(seconds=time.timezone)
431 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 432 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 433
7500d90b
VNM
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 )
6fa09c14 459
7500d90b
VNM
460 # Display
461 printNicely('')
462 printNicely(line1)
fe9bb33b 463 if c['IMAGE_ON_TERM']:
17bc529d 464 try:
465 response = requests.get(profile_image_url)
c37c04a9 466 image_to_display(BytesIO(response.content))
17bc529d 467 except:
468 pass
7500d90b
VNM
469 else:
470 printNicely(line2)
471 for line in [line3, line4, line5, line6]:
472 printNicely(line)
473 printNicely('')
474
475
476def print_trends(trends):
477 """
478 Display topics
479 """
632c6fa5 480 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
481 name = topic['name']
482 url = topic['url']
8394e34b 483 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
484 printNicely(line)
485 printNicely('')
2d341029
O
486
487
488def print_list(group):
489 """
490 Display a list
491 """
99b52f5f 492 for grp in group:
2d341029 493 # Format
99b52f5f 494 name = grp['full_name']
2d341029 495 name = color_func(c['GROUP']['name'])(name + ' : ')
99b52f5f 496 member = str(grp['member_count'])
422dd385 497 member = color_func(c['GROUP']['member'])(member + ' member')
99b52f5f 498 subscriber = str(grp['subscriber_count'])
422dd385
O
499 subscriber = color_func(
500 c['GROUP']['subscriber'])(
501 subscriber +
502 ' subscriber')
99b52f5f 503 description = grp['description'].strip()
2d341029 504 description = color_func(c['GROUP']['description'])(description)
99b52f5f 505 mode = grp['mode']
422dd385 506 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
99b52f5f 507 created_at = grp['created_at']
2d341029
O
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
2d341029 513 # Create lines
422dd385
O
514 line1 = ' ' * 2 + name + member + ' ' + subscriber
515 line2 = ' ' * 4 + description
516 line3 = ' ' * 4 + mode
517 line4 = ' ' * 4 + clock
2d341029
O
518
519 # Display
520 printNicely('')
521 printNicely(line1)
522 printNicely(line2)
523 printNicely(line3)
524 printNicely(line4)
525
526 printNicely('')
59262e95
O
527
528
8141aca6 529def 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
59262e95 549# Start the color cycle
b2cde062 550start_cycle()