def call_c():
+ """
+ Call the C program for converting RGB to Ansi colors
+ """
library = expanduser('~/.image.so')
sauce = join(dirname(__file__), 'image.c')
if not exists(library) or getmtime(sauce) > getmtime(library):
def pixel_print(ansicolor):
+ """
+ Print a pixel with given Ansi color
+ """
sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
def image_to_display(path, start=None, length=None):
+ """
+ Display an image
+ """
rows, columns = os.popen('stty size', 'r').read().split()
if not start:
start = c['IMAGE_SHIFT']
pixel_print(rgb2short(r, g, b))
sys.stdout.write('\n')
+
+"""
+For direct using purpose
+"""
if __name__ == '__main__':
image_to_display(sys.argv[1])
-
def basic_color(code):
"""
16 colors supported
return inner
+"""
+16 basic colors
+"""
default = basic_color('39')
black = basic_color('30')
red = basic_color('31')
light_cyan = basic_color('96')
white = basic_color('97')
+"""
+16 basic colors on background
+"""
on_default = basic_color('49')
on_black = basic_color('40')
on_red = basic_color('41')
import os.path
from collections import OrderedDict
-# Regular expression for comments
+# Regular expression for comments in config file
comment_re = re.compile(
'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
+# Config dictionary
+c = {}
+
def fixup(adict, k, v):
"""
print('It seems that ~/.rainbow_config.json has wrong format :(')
-# Config dictionary
-c = {}
+def init_config():
+ """
+ Init configuration
+ """
+ # Load the initial config
+ config = os.path.dirname(
+ __file__) + '/colorset/config'
+ try:
+ data = load_config(config)
+ for d in data:
+ c[d] = data[d]
+ except:
+ pass
+ # Load user's config
+ rainbow_config = os.environ.get(
+ 'HOME',
+ os.environ.get(
+ 'USERPROFILE',
+ '')) + os.sep + '.rainbow_config.json'
+ try:
+ data = load_config(rainbow_config)
+ for d in data:
+ c[d] = data[d]
+ except:
+ print('It seems that ~/.rainbow_config.json has wrong format :(')
+ # Load default theme
+ theme_file = os.path.dirname(
+ __file__) + '/colorset/' + c['THEME'] + '.json'
+ try:
+ data = load_config(theme_file)
+ for d in data:
+ c[d] = data[d]
+ except:
+ pass
+
-# Load the initial config
-config = os.path.dirname(
- __file__) + '/colorset/config'
-try:
- data = load_config(config)
- for d in data:
- c[d] = data[d]
-except:
- pass
-
-# Load user's config
-rainbow_config = os.environ.get(
- 'HOME',
- os.environ.get(
- 'USERPROFILE',
- '')) + os.sep + '.rainbow_config.json'
-try:
- data = load_config(rainbow_config)
- for d in data:
- c[d] = data[d]
-except:
- print('It seems that ~/.rainbow_config.json has wrong format :(')
-
-# Load default theme
-theme_file = os.path.dirname(
- __file__) + '/colorset/' + c['THEME'] + '.json'
-try:
- data = load_config(theme_file)
- for d in data:
- c[d] = data[d]
-except:
- pass
+# Init config
+init_config()
\ No newline at end of file
engine = None
def __init__(self):
+ """
+ Init DB
+ """
if not os.path.isfile('rainbow.db'):
init_db()
self.engine = create_engine('sqlite:///rainbow.db', echo=False)
+
def tweet_store(self, tweet_id):
"""
Store tweet id
session.add(t)
session.commit()
+
def rainbow_to_tweet_query(self, rid):
"""
Query base of rainbow id
res = session.query(Tweet).filter_by(rainbow_id=rid).all()
return res
+
def tweet_to_rainbow_query(self, tid):
"""
Query base of tweet id
res = session.query(Tweet).filter_by(tweet_id=tid).all()
return res
+
def message_store(self, message_id):
"""
Store message id
session.add(m)
session.commit()
+
def rainbow_to_message_query(self, rid):
"""
Query base of rainbow id
res = session.query(Message).filter_by(rainbow_id=rid).all()
return res
+
def message_to_rainbow_query(self, mid):
"""
Query base of message id
res = session.query(Message).filter_by(message_id=mid).all()
return res
+
def theme_store(self, theme_name):
"""
Store theme
session.add(th)
session.commit()
+
def theme_update(self, theme_name):
"""
Update theme
r.theme_name = theme_name
session.commit()
+
def theme_query(self):
"""
Query theme
res = session.query(Theme).all()
return res
+
def semaphore_store(self, flag):
"""
Store semaphore flag
session.add(th)
session.commit()
+
def semaphore_update(self, flag):
"""
Update semaphore flag
r.flag = flag
session.commit()
+
def semaphore_query(self):
"""
Query semaphore
def _create_dicts():
+ """
+ Create dictionary
+ """
short2rgb_dict = dict(CLUT)
rgb2short_dict = {}
for k, v in short2rgb_dict.items():
def short2rgb(short):
+ """
+ Short to RGB
+ """
return SHORT2RGB_DICT[short]
def pixel_print(ansicolor):
+ """
+ Print a pixel with given Ansi color
+ """
sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
def hex_to_rgb(value):
+ """
+ Hex to RGB
+ """
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv / 3], 16) for i in range(0, lv, lv / 3))
def rgb_to_hex(rgb):
+ """
+ RGB to Hex
+ """
return '%02x%02x%02x' % rgb
def rgb2short(r, g, b):
+ """
+ RGB to short
+ """
dist = lambda s, d: (s[0] - d[0]) ** 2 + \
(s[1] - d[1]) ** 2 + (s[2] - d[2]) ** 2
ary = [hex_to_rgb(hex) for hex in RGB2SHORT_DICT]
def image_to_display(path, start=None, length=None):
+ """
+ Display an image
+ """
rows, columns = os.popen('stty size', 'r').read().split()
if not start:
start = IMAGE_SHIFT
pixel_print(rgb2short(r, g, b))
sys.stdout.write('\n')
+
+"""
+For direct using purpose
+"""
if __name__ == '__main__':
image_to_display(sys.argv[1])
import time
import requests
import webbrowser
-import json
from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
from twitter.api import *
from .c_image import *
from .py3patch import *
-
+# Global values
g = {}
+
+# Database
db = RainbowDB()
+
+# Commands
cmdset = [
'switch',
'trend',
CONSUMER_SECRET)
-def get_decorated_name():
+def init():
"""
Init function
"""
name = '@' + t.account.verify_credentials()['screen_name']
g['original_name'] = name[1:]
g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
-
# Theme init
files = os.listdir(os.path.dirname(__file__) + '/colorset')
themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
g['themes'] = themes
db.theme_store(c['THEME'])
-
# Semaphore init
db.semaphore_store(False)
"""
try:
target = g['stuff'].split()[0]
-
# Filter and ignore
args = parse_arguments()
try:
except:
printNicely(red('Sorry, wrong format.'))
return
-
# Public stream
if target == 'public':
keyword = g['stuff'].split()[1]
args))
p.start()
g['stream_pid'] = p.pid
-
# Personal stream
elif target == 'mine':
# Kill old process
town = g['stuff'].split()[1]
except:
town = ''
-
avail = t.trends.available()
# World wide
if not country:
"""
s = ' ' * 2
h, w = os.popen('stty size', 'r').read().split()
-
# Start
usage = '\n'
usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
usage += s + 'Any update from Twitter will show up ' + \
light_yellow('immediately') + '.\n'
usage += s + 'In addtion, following commands are available right now:\n'
-
# Twitter help section
usage += '\n'
usage += s + grey(u'\u266A' + ' Twitter help\n')
' will show help for list commands.\n'
usage += s * 2 + light_green('h stream') + \
' will show help for stream commands.\n'
-
# Smart shell
usage += '\n'
usage += s + grey(u'\u266A' + ' Smart shell\n')
'will be evaluate by Python interpreter.\n'
usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
' for current month.\n'
-
# Config
usage += '\n'
usage += s + grey(u'\u266A' + ' Config \n')
light_green('config ASCII_ART = False') + ' will set value of ' + \
light_yellow('ASCII_ART') + ' config key to ' + \
light_yellow('False') + '.\n'
-
# Screening
usage += '\n'
usage += s + grey(u'\u266A' + ' Screening \n')
usage += s * 2 + light_green('h') + ' will show this help again.\n'
usage += s * 2 + light_green('c') + ' will clear the screen.\n'
usage += s * 2 + light_green('q') + ' will quit.\n'
-
# End
usage += '\n'
usage += s + '-' * (int(w) - 4) + '\n'
usage += s + 'Have fun and hang tight! \n'
-
# Show help
d = {
'discover': help_discover,
"""
Track the stream
"""
-
# The Logo
art_dict = {
c['USER_DOMAIN']: name,
}
if c['ASCII_ART']:
ascii_art(art_dict[domain])
-
# These arguments are optional:
stream_args = dict(
timeout=args.timeout,
block=not args.no_block,
heartbeat_timeout=args.heartbeat_timeout)
-
# Track keyword
query_args = dict()
if args.track_keywords:
query_args['track'] = args.track_keywords
-
# Get stream
stream = TwitterStream(
auth=authen(),
domain=domain,
**stream_args)
-
try:
if domain == c['USER_DOMAIN']:
tweet_iter = stream.user(**query_args)
tweet_iter = stream.statuses.filter(**query_args)
else:
tweet_iter = stream.statuses.sample()
-
- # Iterate over the stream.
for tweet in tweet_iter:
if tweet is None:
printNicely("-- None --")
"""
Main function
"""
- # Spawn stream process
+ # Initial
args = parse_arguments()
try:
- get_decorated_name()
-
+ init()
except TwitterHTTPError:
printNicely('')
printNicely(
save_history()
os.system('rm -rf rainbow.db')
sys.exit()
-
+ # Spawn stream process
p = Process(
target=stream,
args=(
args,
g['original_name']))
p.start()
-
# Start listen process
time.sleep(0.5)
g['reset'] = True
import os, sys
# Bumped version
-version = '0.4.1'
+version = '0.4.2'
# Require
install_requires = [
"twitter",
"Pillow",
]
+
# Python 3 doesn't hava pysqlite
if sys.version[0] == "2":
install_requires += ["pysqlite"]