def image_to_display(path,start=None,length=None):
rows, columns = os.popen('stty size', 'r').read().split()
if not start:
- start = IMAGE_SHIFT
+ start = c['IMAGE_SHIFT']
if not length:
length = int(columns) - 2 * start
i = Image.open(path)
height = int(float(h) * (float(width) / float(w)))
height //= 2
i = i.resize((width, height), Image.ANTIALIAS)
- height = min(height, IMAGE_MAX_HEIGHT)
+ height = min(height, c['IMAGE_MAX_HEIGHT'])
for y in xrange(height):
print ' ' * start,
import itertools
from functools import wraps
from pyfiglet import figlet_format
+from .config import *
def basic_color(code):
on_light_cyan = basic_color('106')
on_white = basic_color('107')
-colors_shuffle = [
- grey,
- light_red,
- light_green,
- light_yellow,
- light_blue,
- light_magenta,
- light_cyan]
+colors_shuffle = [locals()[i.encode('utf8')] if not i.startswith('RGB_') else RGB(int(i[4:])) for i in c['CYCLE_COLOR']]
+
background_shuffle = [
on_grey,
on_light_red,
* light_magenta
* light_cyan
* white
-
+ and 256 colors from RGB_0 to RGB_255
+ Color code can be reference at
+ http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
*/
+
+ "CYCLE_COLOR" :["light_red","light_green","light_yellow","light_blue","light_magenta","light_cyan"],
"TWEET" : {
"nick" : "grey",
"clock" : "grey",
--- /dev/null
+{
+ /* Color config
+ There are 16 basic colors supported :
+ * default
+ * black
+ * red
+ * green
+ * yellow
+ * blue
+ * magenta
+ * cyan
+ * grey
+ * light_red
+ * light_green
+ * light_yellow
+ * light_blue
+ * light_magenta
+ * light_cyan
+ * white
+ and 256 colors from RGB_0 to RGB_255
+ Color code can be reference at
+ http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
+ */
+
+ "CYCLE_COLOR" :["RGB_198","RGB_57","RGB_166","RGB_50","RGB_179","RGB_74","RGB_112"],
+ "TWEET" : {
+ "nick" : "RGB_198",
+ "clock" : "RGB_57",
+ "id" : "RGB_166",
+ "favourite" : "RGB_50",
+ "rt" : "RGB_179",
+ "link" : "RGB_74",
+ "keyword" : "on_light_green"
+ },
+
+ "MESSAGE" : {
+ "sender" : "RGB_198",
+ "recipient" : "RGB_112",
+ "to" : "RGB_50",
+ "clock" : "RGB_57",
+ "id" : "RGB_166"
+ },
+
+ "PROFILE" : {
+ "statuses_count" : "RGB_112",
+ "friends_count" : "RGB_198",
+ "followers_count" : "RGB_57",
+ "nick" : "RGB_198",
+ "profile_image_url" : "RGB_74",
+ "description" : "RGB_166",
+ "location" : "RGB_112",
+ "url" : "RGB_74",
+ "clock" : "RGB_57"
+ },
+
+ "TREND" : {
+ "url": "RGB_74"
+ }
+}
\ No newline at end of file
import re
import os
import os.path
-from twitter.util import printNicely
# Regular expression for comments
comment_re = re.compile(
while match:
content = content[:match.start()] + content[match.end():]
match = comment_re.search(content)
- data = json.loads(content)
- for d in data:
- globals()[d] = data[d]
+ return json.loads(content)
except:
pass
-# Load colorset
+# Load default colorset
+c = {}
default_config = 'rainbowstream/colorset/default.json'
+data = load_config(default_config)
+for d in data:
+ c[d] = data[d]
+# Load user's colorset
rainbow_config = os.environ.get('HOME', os.environ.get('USERPROFILE','')) + os.sep + '.rainbow_config.json'
-load_config(default_config)
-load_config(rainbow_config)
+data = load_config(rainbow_config)
+for d in data:
+ c[d] = data[d]
"""
Call color function base on name
"""
+ print globals()['TWEET']
pure = func_name.encode('utf8')
if pure.startswith('RGB_') and pure[4:].isdigit():
return RGB(int(pure[4:]))
rid = res[0].rainbow_id
# Format info
- user = cycle_color(name) + color_func(TWEET['nick'])(' ' + screen_name + ' ')
- meta = color_func(TWEET['clock'])('[' + clock + '] ') + color_func(TWEET['id'])('[id=' + str(rid) + '] ')
+ user = cycle_color(name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
+ meta = color_func(c['TWEET']['clock'])('[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
if favorited:
- meta = meta + color_func(TWEET['favorite'])(u'\u2605')
+ meta = meta + color_func(c['TWEET']['favorite'])(u'\u2605')
tweet = text.split()
# Replace url
if expanded_url:
lambda x: expanded_url[index] if x == url[index] else x,
tweet)
# Highlight RT
- tweet = map(lambda x: color_func(TWEET['rt'])(x) if x == 'RT' else x, tweet)
+ tweet = map(lambda x: color_func(c['TWEET']['rt'])(x) if x == 'RT' else x, tweet)
# Highlight screen_name
tweet = map(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
# Highlight link
- tweet = map(lambda x: color_func(TWEET['link'])(x) if x[0:4] == 'http' else x, tweet)
+ tweet = map(lambda x: color_func(c['TWEET']['link'])(x) if x[0:4] == 'http' else x, tweet)
# Highlight search keyword
if keyword:
tweet = map(
- lambda x: color_func(TWEET['keyword'])(x) if
+ lambda x: color_func(c['TWEET']['keyword'])(x) if
''.join(c for c in x if c.isalnum()).lower() == keyword.lower()
else x,
tweet
rid = res[0].rainbow_id
# Draw
- sender = cycle_color(sender_name) + color_func(MESSAGE['sender'])(' ' + sender_screen_name + ' ')
- recipient = cycle_color(recipient_name) + color_func(MESSAGE['recipient'])(' ' + recipient_screen_name + ' ')
- user = sender + color_func(MESSAGE['to'])(' >>> ') + recipient
- meta = color_func(MESSAGE['clock'])('[' + clock + ']') + color_func(MESSAGE['id'])(' [message_id=' + str(rid) + '] ')
+ sender = cycle_color(sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
+ recipient = cycle_color(recipient_name) + color_func(c['MESSAGE']['recipient'])(' ' + recipient_screen_name + ' ')
+ user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
+ meta = color_func(c['MESSAGE']['clock'])('[' + clock + ']') + color_func(c['MESSAGE']['id'])(' [message_id=' + str(rid) + '] ')
text = ''.join(map(lambda x: x + ' ' if x == '\n' else x, text))
line1 = u"{u:>{uw}}:".format(
followers_count = u['followers_count']
# Create content
- statuses_count = color_func(PROFILE['statuses_count'])(str(statuses_count) + ' tweets')
- friends_count = color_func(PROFILE['friends_count'])(str(friends_count) + ' following')
- followers_count = color_func(PROFILE['followers_count'])(str(followers_count) + ' followers')
+ statuses_count = color_func(c['PROFILE']['statuses_count'])(str(statuses_count) + ' tweets')
+ friends_count = color_func(c['PROFILE']['friends_count'])(str(friends_count) + ' following')
+ followers_count = color_func(c['PROFILE']['followers_count'])(str(followers_count) + ' followers')
count = statuses_count + ' ' + friends_count + ' ' + followers_count
- user = cycle_color(name) + color_func(PROFILE['nick'])(' @' + screen_name + ' : ') + count
- profile_image_raw_url = 'Profile photo: ' + color_func(PROFILE['profile_image_url'])(profile_image_url)
+ user = cycle_color(name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
+ profile_image_raw_url = 'Profile photo: ' + color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
description = ''.join(
map(lambda x: x + ' ' * 4 if x == '\n' else x, description))
- description = color_func(PROFILE['description'])(description)
- location = 'Location : ' + color_func(PROFILE['location'])(location)
- url = 'URL : ' + (color_func(PROFILE['url'])(url) if url else '')
+ description = color_func(c['PROFILE']['description'])(description)
+ location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
+ url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
date = parser.parse(created_at)
date = date - datetime.timedelta(seconds=time.timezone)
clock = date.strftime('%Y/%m/%d %H:%M:%S')
- clock = 'Join at ' + color_func(PROFILE['clock'])(clock)
+ clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
# Format
line1 = u"{u:>{uw}}".format(
"""
Display topics
"""
- for topic in trends[:TREND_MAX]:
+ for topic in trends[:c['TREND_MAX']]:
name = topic['name']
url = topic['url']
- line = cycle_color(name) + ': ' + TREND['url'](url)
+ line = cycle_color(name) + ': ' + color_func(TREND['url'])(url)
printNicely(line)
printNicely('')
"""
Read history file
"""
- if os.path.isfile(HISTORY_FILENAME):
- readline.read_history_file(HISTORY_FILENAME)
+ if os.path.isfile(c['HISTORY_FILENAME']):
+ readline.read_history_file(c['HISTORY_FILENAME'])
def save_history():
"""
Save history to file
"""
- readline.write_history_file(HISTORY_FILENAME)
+ readline.write_history_file(c['HISTORY_FILENAME'])
def init_interactive_shell(d):
Colorful user's timeline stream
"""
from multiprocessing import Process
-from dateutil import parser
import os
import os.path
import signal
import argparse
import time
-import datetime
import requests
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
'unblock',
'report',
'cal',
+ 'theme',
'h',
'c',
'q'
g['original_name'] = name[1:]
g['decorated_name'] = grey('[') + grey(name) + grey(']: ')
+ files = os.listdir('rainbowstream/colorset')
+ themes = [f.split('.')[0] for f in files if f.split('.')[-1]=='json']
+ g['themes'] = themes
+
def switch():
"""
args.filter = filter(None, only.split(','))
args.ignore = filter(None, ignore.split(','))
elif g['stuff'].split()[-1] == '-d':
- args.filter = ONLY_LIST
- args.ignore = IGNORE_LIST
+ args.filter = c['ONLY_LIST']
+ args.ignore = c['IGNORE_LIST']
except:
printNicely(red('Sorry, wrong format.'))
return
p = Process(
target=stream,
args=(
- PUBLIC_DOMAIN,
+ c['PUBLIC_DOMAIN'],
args))
p.start()
g['stream_pid'] = p.pid
p = Process(
target=stream,
args=(
- USER_DOMAIN,
+ c['USER_DOMAIN'],
args,
g['original_name']))
p.start()
Home
"""
t = Twitter(auth=authen())
- num = HOME_TWEET_NUM
+ num = c['HOME_TWEET_NUM']
if g['stuff'].isdigit():
num = int(g['stuff'])
for tweet in reversed(t.statuses.home_timeline(count=num)):
try:
num = int(g['stuff'].split()[1])
except:
- num = HOME_TWEET_NUM
+ num = c['HOME_TWEET_NUM']
for tweet in reversed(t.statuses.user_timeline(count=num, screen_name=user[1:])):
draw(t=tweet, iot=g['iot'])
printNicely('')
Mentions timeline
"""
t = Twitter(auth=authen())
- num = HOME_TWEET_NUM
+ num = c['HOME_TWEET_NUM']
if g['stuff'].isdigit():
num = int(g['stuff'])
for tweet in reversed(t.statuses.mentions_timeline(count=num)):
try:
num = int(g['stuff'].split()[1])
except:
- num = RETWEETS_SHOW_NUM
+ num = c['RETWEETS_SHOW_NUM']
# Get result and display
rt_ary = t.statuses.retweets(id=tid, count=num)
if not rt_ary:
rel = t.search.tweets(q=g['stuff'])['statuses']
if rel:
printNicely('Newest tweets:')
- for i in reversed(xrange(SEARCH_MAX_RECORD)):
+ for i in reversed(xrange(c['SEARCH_MAX_RECORD'])):
draw(t=rel[i],
iot=g['iot'],
keyword=g['stuff'].strip()[1:])
Inbox direct messages
"""
t = Twitter(auth=authen())
- num = MESSAGES_DISPLAY
+ num = c['MESSAGES_DISPLAY']
rel = []
if g['stuff'].isdigit():
num = g['stuff']
Sent direct messages
"""
t = Twitter(auth=authen())
- num = MESSAGES_DISPLAY
+ num = c['MESSAGES_DISPLAY']
rel = []
if g['stuff'].isdigit():
num = int(g['stuff'])
"""
t = Twitter(auth=authen())
# Init cursor
- d = {'fl': 'followers', 'fr': 'friends'}
next_cursor = -1
rel = {}
# Cursor loop
printNicely(' '.join(ary))
+def theme():
+ """
+ List and change theme
+ """
+ if not g['stuff']:
+ # List themes
+ for theme in g['themes']:
+ line = ' '*2 + magenta('* ' + theme)
+ printNicely(line)
+ else:
+ # Change theme
+ try :
+ new_config = 'rainbowstream/colorset/' + g['stuff'] + '.json'
+ new_config = load_config(new_config)
+ for nc in new_config:
+ c[nc] = new_config[nc]
+ printNicely(green('Theme changed.'))
+ except :
+ printNicely(red('Sorry, config file is broken!'))
+
+
def help():
"""
Help
' filter will decide nicks will be EXCLUDE.\n'
usage += s * 2 + green('switch mine -d') + \
' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
- usage += s * 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
# Smart shell
usage += '\n'
# Screening
usage += '\n'
usage += s + grey(u'\u266A' + ' Screening \n')
+ usage += s * 2 + green('theme') + ' will list available theme.' + \
+ green('theme monokai') + ' will apply '+ yellow('monokai') + \
+ ' theme immediately.\n'
usage += s * 2 + green('h') + ' will show this help again.\n'
usage += s * 2 + green('c') + ' will clear the screen.\n'
usage += s * 2 + green('q') + ' will quit.\n'
unblock,
report,
cal,
+ theme,
help,
clear,
quit
['@'], # unblock
['@'], # report
[], # cal
+ g['themes'], # theme
[], # help
[], # clear
[], # quit
# The Logo
art_dict = {
- USER_DOMAIN: name,
- PUBLIC_DOMAIN: args.track_keywords,
- SITE_DOMAIN: 'Site Stream',
+ c['USER_DOMAIN']: name,
+ c['PUBLIC_DOMAIN']: args.track_keywords,
+ c['SITE_DOMAIN']: 'Site Stream',
}
ascii_art(art_dict[domain])
domain=domain,
**stream_args)
- if domain == USER_DOMAIN:
+ if domain == c['USER_DOMAIN']:
tweet_iter = stream.user(**query_args)
- elif domain == SITE_DOMAIN:
+ elif domain == c['SITE_DOMAIN']:
tweet_iter = stream.site(**query_args)
else:
if args.track_keywords:
# Spawn stream process
args = parse_arguments()
get_decorated_name()
- p = Process(target=stream, args=(USER_DOMAIN, args, g['original_name']))
+ p = Process(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
p.start()
# Start listen process
from setuptools import setup, find_packages
-version = '0.1.1'
+version = '0.1.2'
install_requires = [
"SQLAlchemy",