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