Commit | Line | Data |
---|---|---|
e9f5200b VNM |
1 | import random |
2 | import itertools | |
7500d90b VNM |
3 | import requests |
4 | import datetime | |
5 | import time | |
59262e95 | 6 | import re |
7500d90b | 7 | |
2da50cc4 | 8 | from twitter.util import printNicely |
e9f5200b VNM |
9 | from functools import wraps |
10 | from pyfiglet import figlet_format | |
7500d90b | 11 | from dateutil import parser |
2da50cc4 | 12 | from .c_image import * |
7500d90b VNM |
13 | from .colors import * |
14 | from .config import * | |
15 | from .db import * | |
c3bab4ef | 16 | from .py3patch import * |
17 | ||
7500d90b VNM |
18 | |
19 | db = RainbowDB() | |
1fdd6a5c VNM |
20 | g = {} |
21 | ||
422dd385 | 22 | |
e9f5200b VNM |
23 | def init_cycle(): |
24 | """ | |
25 | Init the cycle | |
26 | """ | |
27 | colors_shuffle = [globals()[i.encode('utf8')] | |
fa6e062d O |
28 | if not str(i).isdigit() |
29 | else term_color(int(i)) | |
422dd385 | 30 | for i in c['CYCLE_COLOR']] |
5f22104f | 31 | return itertools.cycle(colors_shuffle) |
1fdd6a5c | 32 | |
e9f5200b | 33 | |
59262e95 | 34 | def start_cycle(): |
2359c276 VNM |
35 | """ |
36 | Notify from rainbow | |
37 | """ | |
5f22104f | 38 | g['cyc'] = init_cycle() |
e43ebfa6 | 39 | g['cache'] = {} |
2359c276 VNM |
40 | |
41 | ||
e9f5200b VNM |
42 | def order_rainbow(s): |
43 | """ | |
44 | Print a string with ordered color with each character | |
45 | """ | |
5f22104f | 46 | colors_shuffle = [globals()[i.encode('utf8')] |
fa6e062d O |
47 | if not str(i).isdigit() |
48 | else term_color(int(i)) | |
422dd385 | 49 | for i in c['CYCLE_COLOR']] |
5f22104f | 50 | colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))] |
c3bab4ef | 51 | return ''.join(colored) |
e9f5200b VNM |
52 | |
53 | ||
54 | def random_rainbow(s): | |
55 | """ | |
56 | Print a string with random color with each character | |
57 | """ | |
5f22104f | 58 | colors_shuffle = [globals()[i.encode('utf8')] |
fa6e062d O |
59 | if not str(i).isdigit() |
60 | else term_color(int(i)) | |
422dd385 | 61 | for i in c['CYCLE_COLOR']] |
5f22104f | 62 | colored = [random.choice(colors_shuffle)(i) for i in s] |
c3bab4ef | 63 | return ''.join(colored) |
e9f5200b VNM |
64 | |
65 | ||
66 | def Memoize(func): | |
67 | """ | |
68 | Memoize decorator | |
69 | """ | |
e9f5200b VNM |
70 | @wraps(func) |
71 | def wrapper(*args): | |
e43ebfa6 | 72 | if args not in g['cache']: |
73 | g['cache'][args] = func(*args) | |
74 | return g['cache'][args] | |
e9f5200b VNM |
75 | return wrapper |
76 | ||
77 | ||
78 | @Memoize | |
79 | def cycle_color(s): | |
80 | """ | |
81 | Cycle the colors_shuffle | |
82 | """ | |
1fdd6a5c | 83 | return next(g['cyc'])(s) |
e9f5200b VNM |
84 | |
85 | ||
86 | def ascii_art(text): | |
87 | """ | |
88 | Draw the Ascii Art | |
89 | """ | |
90 | fi = figlet_format(text, font='doom') | |
91 | print('\n'.join( | |
1fdd6a5c | 92 | [next(g['cyc'])(i) for i in fi.split('\n')] |
e9f5200b VNM |
93 | )) |
94 | ||
95 | ||
2a0cabee O |
96 | def show_calendar(month, date, rel): |
97 | """ | |
98 | Show the calendar in rainbow mode | |
99 | """ | |
100 | month = random_rainbow(month) | |
101 | date = ' '.join([cycle_color(i) for i in date.split(' ')]) | |
102 | today = str(int(os.popen('date +\'%d\'').read().strip())) | |
103 | # Display | |
104 | printNicely(month) | |
105 | printNicely(date) | |
106 | for line in rel: | |
107 | ary = line.split(' ') | |
c3bab4ef | 108 | ary = lmap(lambda x: color_func(c['CAL']['today'])(x) |
422dd385 O |
109 | if x == today |
110 | else color_func(c['CAL']['days'])(x), ary) | |
2a0cabee O |
111 | printNicely(' '.join(ary)) |
112 | ||
113 | ||
92685d21 | 114 | def check_config(): |
ceec8593 | 115 | """ |
116 | Check if config is changed | |
117 | """ | |
118 | changed = False | |
119 | data = get_all_config() | |
120 | for key in c: | |
121 | if key in data: | |
122 | if data[key] != c[key]: | |
123 | changed = True | |
124 | if changed: | |
125 | reload_config() | |
126 | ||
127 | ||
128 | def validate_theme(theme): | |
129 | """ | |
130 | Validate a theme exists or not | |
131 | """ | |
132 | # Theme changed check | |
133 | files = os.listdir(os.path.dirname(__file__) + '/colorset') | |
134 | themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json'] | |
135 | return theme in themes | |
92685d21 | 136 | |
137 | ||
ceec8593 | 138 | def reload_theme(current_config): |
4cf86720 VNM |
139 | """ |
140 | Check current theme and update if necessary | |
141 | """ | |
142 | exists = db.theme_query() | |
143 | themes = [t.theme_name for t in exists] | |
ceec8593 | 144 | if current_config != themes[0]: |
1f2f6159 | 145 | config = os.path.dirname( |
ceec8593 | 146 | __file__) + '/colorset/' + current_config + '.json' |
4cf86720 VNM |
147 | # Load new config |
148 | data = load_config(config) | |
a5301bc0 VNM |
149 | if data: |
150 | for d in data: | |
151 | c[d] = data[d] | |
ceec8593 | 152 | # Restart color cycle and update db/config |
153 | start_cycle() | |
154 | db.theme_update(current_config) | |
155 | set_config('THEME', current_config) | |
7500d90b | 156 | |
fe08f905 VNM |
157 | |
158 | def color_func(func_name): | |
159 | """ | |
160 | Call color function base on name | |
161 | """ | |
fa6e062d O |
162 | if str(func_name).isdigit(): |
163 | return term_color(int(func_name)) | |
c3bab4ef | 164 | return globals()[func_name] |
fe08f905 VNM |
165 | |
166 | ||
fe9bb33b | 167 | def draw(t, keyword=None, check_semaphore=False, fil=[], ig=[]): |
7500d90b VNM |
168 | """ |
169 | Draw the rainbow | |
170 | """ | |
171 | ||
92685d21 | 172 | check_config() |
ceec8593 | 173 | reload_theme(c['THEME']) |
7500d90b VNM |
174 | # Retrieve tweet |
175 | tid = t['id'] | |
606def7e | 176 | text = t['text'] |
7500d90b VNM |
177 | screen_name = t['user']['screen_name'] |
178 | name = t['user']['name'] | |
179 | created_at = t['created_at'] | |
180 | favorited = t['favorited'] | |
181 | date = parser.parse(created_at) | |
182 | date = date - datetime.timedelta(seconds=time.timezone) | |
8c7ae594 O |
183 | clock_format = '%Y/%m/%d %H:%M:%S' |
184 | try: | |
185 | clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT'] | |
186 | except: | |
187 | pass | |
188 | clock = date.strftime(clock_format) | |
7500d90b | 189 | |
606def7e BR |
190 | # Pull extended retweet text |
191 | try: | |
18df6e7f O |
192 | text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\ |
193 | t['retweeted_status']['text'] | |
606def7e BR |
194 | except: |
195 | pass | |
196 | ||
18df6e7f | 197 | # Unescape HTML character |
606def7e BR |
198 | text = unescape(text) |
199 | ||
7500d90b VNM |
200 | # Get expanded url |
201 | try: | |
202 | expanded_url = [] | |
203 | url = [] | |
204 | urls = t['entities']['urls'] | |
205 | for u in urls: | |
206 | expanded_url.append(u['expanded_url']) | |
207 | url.append(u['url']) | |
208 | except: | |
209 | expanded_url = None | |
210 | url = None | |
211 | ||
212 | # Get media | |
213 | try: | |
214 | media_url = [] | |
215 | media = t['entities']['media'] | |
216 | for m in media: | |
217 | media_url.append(m['media_url']) | |
218 | except: | |
219 | media_url = None | |
220 | ||
221 | # Filter and ignore | |
222 | screen_name = '@' + screen_name | |
223 | if fil and screen_name not in fil: | |
224 | return | |
225 | if ig and screen_name in ig: | |
226 | return | |
227 | ||
228 | # Get rainbow id | |
229 | res = db.tweet_to_rainbow_query(tid) | |
230 | if not res: | |
231 | db.tweet_store(tid) | |
232 | res = db.tweet_to_rainbow_query(tid) | |
233 | rid = res[0].rainbow_id | |
234 | ||
235 | # Format info | |
8c7ae594 | 236 | name = cycle_color(name) |
d6cc4c67 | 237 | nick = color_func(c['TWEET']['nick'])(screen_name) |
0d9977c7 O |
238 | clock = clock |
239 | id = str(rid) | |
8c7ae594 | 240 | fav = '' |
7500d90b | 241 | if favorited: |
8c7ae594 O |
242 | fav = color_func(c['TWEET']['favorited'])(u'\u2605') |
243 | ||
7500d90b VNM |
244 | tweet = text.split() |
245 | # Replace url | |
246 | if expanded_url: | |
247 | for index in range(len(expanded_url)): | |
c3bab4ef | 248 | tweet = lmap( |
7500d90b VNM |
249 | lambda x: expanded_url[index] if x == url[index] else x, |
250 | tweet) | |
251 | # Highlight RT | |
c3bab4ef | 252 | tweet = lmap( |
c075e6dc O |
253 | lambda x: color_func( |
254 | c['TWEET']['rt'])(x) if x == 'RT' else x, | |
255 | tweet) | |
7500d90b | 256 | # Highlight screen_name |
c3bab4ef | 257 | tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet) |
7500d90b | 258 | # Highlight link |
c3bab4ef | 259 | tweet = lmap( |
c075e6dc O |
260 | lambda x: color_func( |
261 | c['TWEET']['link'])(x) if x[ | |
262 | 0:4] == 'http' else x, | |
263 | tweet) | |
59262e95 O |
264 | |
265 | # Highlight keyword | |
7500d90b | 266 | tweet = ' '.join(tweet) |
59262e95 | 267 | if keyword: |
a8c5fce4 | 268 | roj = re.search(keyword, tweet, re.IGNORECASE) |
59262e95 O |
269 | if roj: |
270 | occur = roj.group() | |
271 | ary = tweet.split(occur) | |
b13c6a0d | 272 | delimiter = color_func(c['TWEET']['keyword'])(occur) |
273 | tweet = delimiter.join(ary) | |
7500d90b | 274 | |
8c7ae594 O |
275 | # Load config formater |
276 | try: | |
277 | formater = c['FORMAT']['TWEET']['DISPLAY'] | |
0d9977c7 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")) | |
282 | # Change clock word | |
283 | word = [w for w in formater.split() if '#clock' in w][0] | |
284 | delimiter = color_func( | |
285 | c['TWEET']['clock'])( | |
286 | clock.join( | |
287 | word.split('#clock'))) | |
288 | formater = delimiter.join(formater.split(word)) | |
289 | # Change id word | |
290 | word = [w for w in formater.split() if '#id' in w][0] | |
291 | delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id'))) | |
292 | formater = delimiter.join(formater.split(word)) | |
8c7ae594 O |
293 | except: |
294 | printNicely(red('Wrong format in config.')) | |
295 | return | |
7500d90b | 296 | |
d6cc4c67 | 297 | # Check the semaphore lock (stream process only) |
9683e61d | 298 | if check_semaphore: |
d6cc4c67 O |
299 | if db.semaphore_query_pause(): |
300 | return | |
301 | while db.semaphore_query_flag(): | |
9683e61d O |
302 | time.sleep(0.5) |
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 | ||
317 | def print_message(m): | |
318 | """ | |
319 | Print direct message | |
320 | """ | |
321 | sender_screen_name = '@' + m['sender_screen_name'] | |
322 | sender_name = m['sender']['name'] | |
b2cde062 | 323 | text = unescape(m['text']) |
7500d90b VNM |
324 | recipient_screen_name = '@' + m['recipient_screen_name'] |
325 | recipient_name = m['recipient']['name'] | |
326 | mid = m['id'] | |
327 | date = parser.parse(m['created_at']) | |
328 | date = date - datetime.timedelta(seconds=time.timezone) | |
8c7ae594 O |
329 | clock_format = '%Y/%m/%d %H:%M:%S' |
330 | try: | |
331 | clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT'] | |
332 | except: | |
333 | pass | |
334 | clock = date.strftime(clock_format) | |
7500d90b VNM |
335 | |
336 | # Get rainbow id | |
337 | res = db.message_to_rainbow_query(mid) | |
338 | if not res: | |
339 | db.message_store(mid) | |
340 | res = db.message_to_rainbow_query(mid) | |
341 | rid = res[0].rainbow_id | |
342 | ||
6fa09c14 | 343 | # Draw |
8c7ae594 O |
344 | sender_name = cycle_color(sender_name) |
345 | sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name) | |
346 | recipient_name = cycle_color(recipient_name) | |
0d9977c7 O |
347 | recipient_nick = color_func( |
348 | c['MESSAGE']['recipient'])(recipient_screen_name) | |
8c7ae594 | 349 | to = color_func(c['MESSAGE']['to'])('>>>') |
0d9977c7 O |
350 | clock = clock |
351 | id = str(rid) | |
8c7ae594 | 352 | |
c3bab4ef | 353 | text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text)) |
7500d90b | 354 | |
8c7ae594 O |
355 | # Load config formater |
356 | try: | |
357 | formater = c['FORMAT']['MESSAGE']['DISPLAY'] | |
0d9977c7 O |
358 | formater = sender_name.join(formater.split("#sender_name")) |
359 | formater = sender_nick.join(formater.split("#sender_nick")) | |
360 | formater = to.join(formater.split("#to")) | |
361 | formater = recipient_name.join(formater.split("#recipient_name")) | |
362 | formater = recipient_nick.join(formater.split("#recipient_nick")) | |
363 | formater = text.join(formater.split("#message")) | |
364 | # Change clock word | |
365 | word = [w for w in formater.split() if '#clock' in w][0] | |
366 | delimiter = color_func( | |
367 | c['MESSAGE']['clock'])( | |
368 | clock.join( | |
369 | word.split('#clock'))) | |
370 | formater = delimiter.join(formater.split(word)) | |
371 | # Change id word | |
372 | word = [w for w in formater.split() if '#id' in w][0] | |
373 | delimiter = color_func(c['MESSAGE']['id'])(id.join(word.split('#id'))) | |
374 | formater = delimiter.join(formater.split(word)) | |
8c7ae594 O |
375 | except: |
376 | printNicely(red('Wrong format in config.')) | |
377 | return | |
378 | ||
379 | # Draw | |
380 | printNicely(formater) | |
7500d90b VNM |
381 | |
382 | ||
fe9bb33b | 383 | def show_profile(u): |
7500d90b VNM |
384 | """ |
385 | Show a profile | |
386 | """ | |
387 | # Retrieve info | |
388 | name = u['name'] | |
389 | screen_name = u['screen_name'] | |
390 | description = u['description'] | |
391 | profile_image_url = u['profile_image_url'] | |
392 | location = u['location'] | |
393 | url = u['url'] | |
394 | created_at = u['created_at'] | |
395 | statuses_count = u['statuses_count'] | |
396 | friends_count = u['friends_count'] | |
397 | followers_count = u['followers_count'] | |
6fa09c14 | 398 | |
7500d90b | 399 | # Create content |
c075e6dc O |
400 | statuses_count = color_func( |
401 | c['PROFILE']['statuses_count'])( | |
402 | str(statuses_count) + | |
403 | ' tweets') | |
404 | friends_count = color_func( | |
405 | c['PROFILE']['friends_count'])( | |
406 | str(friends_count) + | |
407 | ' following') | |
408 | followers_count = color_func( | |
409 | c['PROFILE']['followers_count'])( | |
410 | str(followers_count) + | |
411 | ' followers') | |
7500d90b | 412 | count = statuses_count + ' ' + friends_count + ' ' + followers_count |
c075e6dc O |
413 | user = cycle_color( |
414 | name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count | |
415 | profile_image_raw_url = 'Profile photo: ' + \ | |
416 | color_func(c['PROFILE']['profile_image_url'])(profile_image_url) | |
7500d90b | 417 | description = ''.join( |
c3bab4ef | 418 | lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description)) |
632c6fa5 O |
419 | description = color_func(c['PROFILE']['description'])(description) |
420 | location = 'Location : ' + color_func(c['PROFILE']['location'])(location) | |
421 | url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '') | |
7500d90b VNM |
422 | date = parser.parse(created_at) |
423 | date = date - datetime.timedelta(seconds=time.timezone) | |
424 | clock = date.strftime('%Y/%m/%d %H:%M:%S') | |
632c6fa5 | 425 | clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock) |
6fa09c14 | 426 | |
7500d90b VNM |
427 | # Format |
428 | line1 = u"{u:>{uw}}".format( | |
429 | u=user, | |
430 | uw=len(user) + 2, | |
431 | ) | |
432 | line2 = u"{p:>{pw}}".format( | |
433 | p=profile_image_raw_url, | |
434 | pw=len(profile_image_raw_url) + 4, | |
435 | ) | |
436 | line3 = u"{d:>{dw}}".format( | |
437 | d=description, | |
438 | dw=len(description) + 4, | |
439 | ) | |
440 | line4 = u"{l:>{lw}}".format( | |
441 | l=location, | |
442 | lw=len(location) + 4, | |
443 | ) | |
444 | line5 = u"{u:>{uw}}".format( | |
445 | u=url, | |
446 | uw=len(url) + 4, | |
447 | ) | |
448 | line6 = u"{c:>{cw}}".format( | |
449 | c=clock, | |
450 | cw=len(clock) + 4, | |
451 | ) | |
6fa09c14 | 452 | |
7500d90b VNM |
453 | # Display |
454 | printNicely('') | |
455 | printNicely(line1) | |
fe9bb33b | 456 | if c['IMAGE_ON_TERM']: |
17bc529d | 457 | try: |
458 | response = requests.get(profile_image_url) | |
77f1d210 | 459 | image_to_display(BytesIO(response.content), 2, 20) |
17bc529d | 460 | except: |
461 | pass | |
7500d90b VNM |
462 | else: |
463 | printNicely(line2) | |
464 | for line in [line3, line4, line5, line6]: | |
465 | printNicely(line) | |
466 | printNicely('') | |
467 | ||
468 | ||
469 | def print_trends(trends): | |
470 | """ | |
471 | Display topics | |
472 | """ | |
632c6fa5 | 473 | for topic in trends[:c['TREND_MAX']]: |
7500d90b VNM |
474 | name = topic['name'] |
475 | url = topic['url'] | |
8394e34b | 476 | line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url) |
7500d90b VNM |
477 | printNicely(line) |
478 | printNicely('') | |
2d341029 O |
479 | |
480 | ||
481 | def print_list(group): | |
482 | """ | |
483 | Display a list | |
484 | """ | |
485 | for g in group: | |
486 | # Format | |
422dd385 | 487 | name = g['full_name'] |
2d341029 O |
488 | name = color_func(c['GROUP']['name'])(name + ' : ') |
489 | member = str(g['member_count']) | |
422dd385 | 490 | member = color_func(c['GROUP']['member'])(member + ' member') |
2d341029 | 491 | subscriber = str(g['subscriber_count']) |
422dd385 O |
492 | subscriber = color_func( |
493 | c['GROUP']['subscriber'])( | |
494 | subscriber + | |
495 | ' subscriber') | |
2d341029 O |
496 | description = g['description'].strip() |
497 | description = color_func(c['GROUP']['description'])(description) | |
498 | mode = g['mode'] | |
422dd385 | 499 | mode = color_func(c['GROUP']['mode'])('Type: ' + mode) |
2d341029 O |
500 | created_at = g['created_at'] |
501 | date = parser.parse(created_at) | |
502 | date = date - datetime.timedelta(seconds=time.timezone) | |
503 | clock = date.strftime('%Y/%m/%d %H:%M:%S') | |
504 | clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock) | |
505 | ||
2d341029 | 506 | # Create lines |
422dd385 O |
507 | line1 = ' ' * 2 + name + member + ' ' + subscriber |
508 | line2 = ' ' * 4 + description | |
509 | line3 = ' ' * 4 + mode | |
510 | line4 = ' ' * 4 + clock | |
2d341029 O |
511 | |
512 | # Display | |
513 | printNicely('') | |
514 | printNicely(line1) | |
515 | printNicely(line2) | |
516 | printNicely(line3) | |
517 | printNicely(line4) | |
518 | ||
519 | printNicely('') | |
59262e95 O |
520 | |
521 | ||
522 | # Start the color cycle | |
b2cde062 | 523 | start_cycle() |