| 1 | import random |
| 2 | import itertools |
| 3 | import requests |
| 4 | import datetime |
| 5 | import time |
| 6 | import re |
| 7 | |
| 8 | from twitter.util import printNicely |
| 9 | from functools import wraps |
| 10 | from pyfiglet import figlet_format |
| 11 | from dateutil import parser |
| 12 | from .c_image import * |
| 13 | from .colors import * |
| 14 | from .config import * |
| 15 | from .db import * |
| 16 | from .py3patch import * |
| 17 | |
| 18 | |
| 19 | db = RainbowDB() |
| 20 | g = {} |
| 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 | g['cyc'] = init_cycle() |
| 39 | g['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 g['cache']: |
| 73 | g['cache'][args] = func(*args) |
| 74 | return g['cache'][args] |
| 75 | return wrapper |
| 76 | |
| 77 | |
| 78 | @Memoize |
| 79 | def cycle_color(s): |
| 80 | """ |
| 81 | Cycle the colors_shuffle |
| 82 | """ |
| 83 | return next(g['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(g['cyc'])(i) for i in fi.split('\n')] |
| 93 | )) |
| 94 | |
| 95 | |
| 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(' ') |
| 108 | ary = lmap(lambda x: color_func(c['CAL']['today'])(x) |
| 109 | if x == today |
| 110 | else color_func(c['CAL']['days'])(x), ary) |
| 111 | printNicely(' '.join(ary)) |
| 112 | |
| 113 | |
| 114 | def check_config(): |
| 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 |
| 136 | |
| 137 | |
| 138 | def reload_theme(current_config): |
| 139 | """ |
| 140 | Check current theme and update if necessary |
| 141 | """ |
| 142 | exists = db.theme_query() |
| 143 | themes = [t.theme_name for t in exists] |
| 144 | if current_config != themes[0]: |
| 145 | config = os.path.dirname( |
| 146 | __file__) + '/colorset/' + current_config + '.json' |
| 147 | # Load new config |
| 148 | data = load_config(config) |
| 149 | if data: |
| 150 | for d in data: |
| 151 | c[d] = data[d] |
| 152 | # Restart color cycle and update db/config |
| 153 | start_cycle() |
| 154 | db.theme_update(current_config) |
| 155 | set_config('THEME', current_config) |
| 156 | |
| 157 | |
| 158 | def color_func(func_name): |
| 159 | """ |
| 160 | Call color function base on name |
| 161 | """ |
| 162 | if str(func_name).isdigit(): |
| 163 | return term_color(int(func_name)) |
| 164 | return globals()[func_name] |
| 165 | |
| 166 | |
| 167 | def draw(t, keyword=None, check_semaphore=False, fil=[], ig=[]): |
| 168 | """ |
| 169 | Draw the rainbow |
| 170 | """ |
| 171 | |
| 172 | # Check the semaphore lock (stream process only) |
| 173 | if check_semaphore: |
| 174 | if db.semaphore_query_pause(): |
| 175 | return |
| 176 | while db.semaphore_query_lock(): |
| 177 | time.sleep(0.5) |
| 178 | |
| 179 | # Check config and theme |
| 180 | check_config() |
| 181 | reload_theme(c['THEME']) |
| 182 | |
| 183 | # Retrieve tweet |
| 184 | tid = t['id'] |
| 185 | text = t['text'] |
| 186 | screen_name = t['user']['screen_name'] |
| 187 | name = t['user']['name'] |
| 188 | created_at = t['created_at'] |
| 189 | favorited = t['favorited'] |
| 190 | date = parser.parse(created_at) |
| 191 | date = date - datetime.timedelta(seconds=time.timezone) |
| 192 | clock_format = '%Y/%m/%d %H:%M:%S' |
| 193 | try: |
| 194 | clock_format = c['FORMAT']['TWEET']['CLOCK_FORMAT'] |
| 195 | except: |
| 196 | pass |
| 197 | clock = date.strftime(clock_format) |
| 198 | |
| 199 | # Pull extended retweet text |
| 200 | try: |
| 201 | text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\ |
| 202 | t['retweeted_status']['text'] |
| 203 | except: |
| 204 | pass |
| 205 | |
| 206 | # Unescape HTML character |
| 207 | text = unescape(text) |
| 208 | |
| 209 | # Get expanded url |
| 210 | try: |
| 211 | expanded_url = [] |
| 212 | url = [] |
| 213 | urls = t['entities']['urls'] |
| 214 | for u in urls: |
| 215 | expanded_url.append(u['expanded_url']) |
| 216 | url.append(u['url']) |
| 217 | except: |
| 218 | expanded_url = None |
| 219 | url = None |
| 220 | |
| 221 | # Get media |
| 222 | try: |
| 223 | media_url = [] |
| 224 | media = t['entities']['media'] |
| 225 | for m in media: |
| 226 | media_url.append(m['media_url']) |
| 227 | except: |
| 228 | media_url = None |
| 229 | |
| 230 | # Filter and ignore |
| 231 | screen_name = '@' + screen_name |
| 232 | if fil and screen_name not in fil: |
| 233 | return |
| 234 | if ig and screen_name in ig: |
| 235 | return |
| 236 | |
| 237 | # Get rainbow id |
| 238 | res = db.tweet_to_rainbow_query(tid) |
| 239 | if not res: |
| 240 | db.tweet_store(tid) |
| 241 | res = db.tweet_to_rainbow_query(tid) |
| 242 | rid = res[0].rainbow_id |
| 243 | |
| 244 | # Format info |
| 245 | name = cycle_color(name) |
| 246 | nick = color_func(c['TWEET']['nick'])(screen_name) |
| 247 | clock = clock |
| 248 | id = str(rid) |
| 249 | fav = '' |
| 250 | if favorited: |
| 251 | fav = color_func(c['TWEET']['favorited'])(u'\u2605') |
| 252 | |
| 253 | tweet = text.split() |
| 254 | # Replace url |
| 255 | if expanded_url: |
| 256 | for index in range(len(expanded_url)): |
| 257 | tweet = lmap( |
| 258 | lambda x: expanded_url[index] if x == url[index] else x, |
| 259 | tweet) |
| 260 | # Highlight RT |
| 261 | tweet = lmap( |
| 262 | lambda x: color_func( |
| 263 | c['TWEET']['rt'])(x) if x == 'RT' else x, |
| 264 | tweet) |
| 265 | # Highlight screen_name |
| 266 | tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet) |
| 267 | # Highlight link |
| 268 | tweet = lmap( |
| 269 | lambda x: color_func( |
| 270 | c['TWEET']['link'])(x) if x[ |
| 271 | 0:4] == 'http' else x, |
| 272 | tweet) |
| 273 | |
| 274 | # Highlight keyword |
| 275 | tweet = ' '.join(tweet) |
| 276 | if keyword: |
| 277 | roj = re.search(keyword, tweet, re.IGNORECASE) |
| 278 | if roj: |
| 279 | occur = roj.group() |
| 280 | ary = tweet.split(occur) |
| 281 | delimiter = color_func(c['TWEET']['keyword'])(occur) |
| 282 | tweet = delimiter.join(ary) |
| 283 | |
| 284 | # Load config formater |
| 285 | try: |
| 286 | formater = c['FORMAT']['TWEET']['DISPLAY'] |
| 287 | formater = name.join(formater.split("#name")) |
| 288 | formater = nick.join(formater.split("#nick")) |
| 289 | formater = fav.join(formater.split("#fav")) |
| 290 | formater = tweet.join(formater.split("#tweet")) |
| 291 | # Change clock word |
| 292 | word = [w for w in formater.split() if '#clock' in w][0] |
| 293 | delimiter = color_func( |
| 294 | c['TWEET']['clock'])( |
| 295 | clock.join( |
| 296 | word.split('#clock'))) |
| 297 | formater = delimiter.join(formater.split(word)) |
| 298 | # Change id word |
| 299 | word = [w for w in formater.split() if '#id' in w][0] |
| 300 | delimiter = color_func(c['TWEET']['id'])(id.join(word.split('#id'))) |
| 301 | formater = delimiter.join(formater.split(word)) |
| 302 | except: |
| 303 | printNicely(red('Wrong format in config.')) |
| 304 | return |
| 305 | |
| 306 | # Draw |
| 307 | printNicely(formater) |
| 308 | |
| 309 | # Display Image |
| 310 | if c['IMAGE_ON_TERM'] and media_url: |
| 311 | for mu in media_url: |
| 312 | try: |
| 313 | response = requests.get(mu) |
| 314 | image_to_display(BytesIO(response.content)) |
| 315 | except Exception: |
| 316 | printNicely(red('Sorry, image link is broken')) |
| 317 | |
| 318 | |
| 319 | def print_message(m, check_semaphore=False): |
| 320 | """ |
| 321 | Print direct message |
| 322 | """ |
| 323 | |
| 324 | # Check the semaphore lock (stream process only) |
| 325 | if check_semaphore: |
| 326 | if db.semaphore_query_pause(): |
| 327 | return |
| 328 | while db.semaphore_query_lock(): |
| 329 | time.sleep(0.5) |
| 330 | |
| 331 | # Retrieve message |
| 332 | sender_screen_name = '@' + m['sender_screen_name'] |
| 333 | sender_name = m['sender']['name'] |
| 334 | text = unescape(m['text']) |
| 335 | recipient_screen_name = '@' + m['recipient_screen_name'] |
| 336 | recipient_name = m['recipient']['name'] |
| 337 | mid = m['id'] |
| 338 | date = parser.parse(m['created_at']) |
| 339 | date = date - datetime.timedelta(seconds=time.timezone) |
| 340 | clock_format = '%Y/%m/%d %H:%M:%S' |
| 341 | try: |
| 342 | clock_format = c['FORMAT']['MESSAGE']['CLOCK_FORMAT'] |
| 343 | except: |
| 344 | pass |
| 345 | clock = date.strftime(clock_format) |
| 346 | |
| 347 | # Get rainbow id |
| 348 | res = db.message_to_rainbow_query(mid) |
| 349 | if not res: |
| 350 | db.message_store(mid) |
| 351 | res = db.message_to_rainbow_query(mid) |
| 352 | rid = res[0].rainbow_id |
| 353 | |
| 354 | # Draw |
| 355 | sender_name = cycle_color(sender_name) |
| 356 | sender_nick = color_func(c['MESSAGE']['sender'])(sender_screen_name) |
| 357 | recipient_name = cycle_color(recipient_name) |
| 358 | recipient_nick = color_func( |
| 359 | c['MESSAGE']['recipient'])(recipient_screen_name) |
| 360 | to = color_func(c['MESSAGE']['to'])('>>>') |
| 361 | clock = clock |
| 362 | id = str(rid) |
| 363 | |
| 364 | text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text)) |
| 365 | |
| 366 | # Load config formater |
| 367 | try: |
| 368 | formater = c['FORMAT']['MESSAGE']['DISPLAY'] |
| 369 | formater = sender_name.join(formater.split("#sender_name")) |
| 370 | formater = sender_nick.join(formater.split("#sender_nick")) |
| 371 | formater = to.join(formater.split("#to")) |
| 372 | formater = recipient_name.join(formater.split("#recipient_name")) |
| 373 | formater = recipient_nick.join(formater.split("#recipient_nick")) |
| 374 | formater = text.join(formater.split("#message")) |
| 375 | # Change clock word |
| 376 | word = [w for w in formater.split() if '#clock' in w][0] |
| 377 | delimiter = color_func( |
| 378 | c['MESSAGE']['clock'])( |
| 379 | clock.join( |
| 380 | word.split('#clock'))) |
| 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)) |
| 386 | except: |
| 387 | printNicely(red('Wrong format in config.')) |
| 388 | return |
| 389 | |
| 390 | # Draw |
| 391 | printNicely(formater) |
| 392 | |
| 393 | |
| 394 | def show_profile(u): |
| 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'] |
| 409 | |
| 410 | # Create content |
| 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') |
| 423 | count = statuses_count + ' ' + friends_count + ' ' + followers_count |
| 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) |
| 428 | description = ''.join( |
| 429 | lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description)) |
| 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 '') |
| 433 | date = parser.parse(created_at) |
| 434 | date = date - datetime.timedelta(seconds=time.timezone) |
| 435 | clock = date.strftime('%Y/%m/%d %H:%M:%S') |
| 436 | clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock) |
| 437 | |
| 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 | ) |
| 463 | |
| 464 | # Display |
| 465 | printNicely('') |
| 466 | printNicely(line1) |
| 467 | if c['IMAGE_ON_TERM']: |
| 468 | try: |
| 469 | response = requests.get(profile_image_url) |
| 470 | image_to_display(BytesIO(response.content)) |
| 471 | except: |
| 472 | pass |
| 473 | else: |
| 474 | printNicely(line2) |
| 475 | for line in [line3, line4, line5, line6]: |
| 476 | printNicely(line) |
| 477 | printNicely('') |
| 478 | |
| 479 | |
| 480 | def print_trends(trends): |
| 481 | """ |
| 482 | Display topics |
| 483 | """ |
| 484 | for topic in trends[:c['TREND_MAX']]: |
| 485 | name = topic['name'] |
| 486 | url = topic['url'] |
| 487 | line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url) |
| 488 | printNicely(line) |
| 489 | printNicely('') |
| 490 | |
| 491 | |
| 492 | def print_list(group): |
| 493 | """ |
| 494 | Display a list |
| 495 | """ |
| 496 | for g in group: |
| 497 | # Format |
| 498 | name = g['full_name'] |
| 499 | name = color_func(c['GROUP']['name'])(name + ' : ') |
| 500 | member = str(g['member_count']) |
| 501 | member = color_func(c['GROUP']['member'])(member + ' member') |
| 502 | subscriber = str(g['subscriber_count']) |
| 503 | subscriber = color_func( |
| 504 | c['GROUP']['subscriber'])( |
| 505 | subscriber + |
| 506 | ' subscriber') |
| 507 | description = g['description'].strip() |
| 508 | description = color_func(c['GROUP']['description'])(description) |
| 509 | mode = g['mode'] |
| 510 | mode = color_func(c['GROUP']['mode'])('Type: ' + mode) |
| 511 | created_at = g['created_at'] |
| 512 | date = parser.parse(created_at) |
| 513 | date = date - datetime.timedelta(seconds=time.timezone) |
| 514 | clock = date.strftime('%Y/%m/%d %H:%M:%S') |
| 515 | clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock) |
| 516 | |
| 517 | # Create lines |
| 518 | line1 = ' ' * 2 + name + member + ' ' + subscriber |
| 519 | line2 = ' ' * 4 + description |
| 520 | line3 = ' ' * 4 + mode |
| 521 | line4 = ' ' * 4 + clock |
| 522 | |
| 523 | # Display |
| 524 | printNicely('') |
| 525 | printNicely(line1) |
| 526 | printNicely(line2) |
| 527 | printNicely(line3) |
| 528 | printNicely(line4) |
| 529 | |
| 530 | printNicely('') |
| 531 | |
| 532 | |
| 533 | # Start the color cycle |
| 534 | start_cycle() |