re-init cycle color
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
7500d90b
VNM
1"""
2Draw
3"""
4import requests
5import datetime
6import time
7
2da50cc4 8from twitter.util import printNicely
7500d90b
VNM
9from StringIO import StringIO
10from dateutil import parser
2da50cc4 11from .c_image import *
7500d90b
VNM
12from .colors import *
13from .config import *
14from .db import *
15
16db = RainbowDB()
4cf86720
VNM
17
18def check_theme():
19 """
20 Check current theme and update if necessary
21 """
22 exists = db.theme_query()
23 themes = [t.theme_name for t in exists]
ddb1e615
VNM
24 if c['theme'] != themes[0]:
25 c['theme'] = themes[0]
4cf86720 26 # Determine path
ddb1e615 27 if c['theme'] == 'custom':
4cf86720
VNM
28 config = os.environ.get(
29 'HOME',
30 os.environ.get(
31 'USERPROFILE',
32 '')) + os.sep + '.rainbow_config.json'
33 else:
ddb1e615 34 config = 'rainbowstream/colorset/'+c['theme']+'.json'
4cf86720
VNM
35 # Load new config
36 data = load_config(config)
a5301bc0
VNM
37 if data:
38 for d in data:
39 c[d] = data[d]
7500d90b 40
fe08f905
VNM
41
42def color_func(func_name):
43 """
44 Call color function base on name
45 """
46 pure = func_name.encode('utf8')
92be926e 47 if pure.startswith('RGB_') and pure[4:].isdigit():
93384849 48 return RGB(int(pure[4:]))
1face019 49 return globals()[pure]
fe08f905
VNM
50
51
7500d90b
VNM
52def draw(t, iot=False, keyword=None, fil=[], ig=[]):
53 """
54 Draw the rainbow
55 """
56
4cf86720 57 check_theme()
7500d90b
VNM
58 # Retrieve tweet
59 tid = t['id']
60 text = t['text']
61 screen_name = t['user']['screen_name']
62 name = t['user']['name']
63 created_at = t['created_at']
64 favorited = t['favorited']
65 date = parser.parse(created_at)
66 date = date - datetime.timedelta(seconds=time.timezone)
67 clock = date.strftime('%Y/%m/%d %H:%M:%S')
68
69 # Get expanded url
70 try:
71 expanded_url = []
72 url = []
73 urls = t['entities']['urls']
74 for u in urls:
75 expanded_url.append(u['expanded_url'])
76 url.append(u['url'])
77 except:
78 expanded_url = None
79 url = None
80
81 # Get media
82 try:
83 media_url = []
84 media = t['entities']['media']
85 for m in media:
86 media_url.append(m['media_url'])
87 except:
88 media_url = None
89
90 # Filter and ignore
91 screen_name = '@' + screen_name
92 if fil and screen_name not in fil:
93 return
94 if ig and screen_name in ig:
95 return
96
97 # Get rainbow id
98 res = db.tweet_to_rainbow_query(tid)
99 if not res:
100 db.tweet_store(tid)
101 res = db.tweet_to_rainbow_query(tid)
102 rid = res[0].rainbow_id
103
104 # Format info
c075e6dc
O
105 user = cycle_color(
106 name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
107 meta = color_func(c['TWEET']['clock'])(
108 '[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
7500d90b 109 if favorited:
632c6fa5 110 meta = meta + color_func(c['TWEET']['favorite'])(u'\u2605')
7500d90b
VNM
111 tweet = text.split()
112 # Replace url
113 if expanded_url:
114 for index in range(len(expanded_url)):
115 tweet = map(
116 lambda x: expanded_url[index] if x == url[index] else x,
117 tweet)
118 # Highlight RT
c075e6dc
O
119 tweet = map(
120 lambda x: color_func(
121 c['TWEET']['rt'])(x) if x == 'RT' else x,
122 tweet)
7500d90b
VNM
123 # Highlight screen_name
124 tweet = map(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
125 # Highlight link
c075e6dc
O
126 tweet = map(
127 lambda x: color_func(
128 c['TWEET']['link'])(x) if x[
129 0:4] == 'http' else x,
130 tweet)
7500d90b
VNM
131 # Highlight search keyword
132 if keyword:
133 tweet = map(
632c6fa5 134 lambda x: color_func(c['TWEET']['keyword'])(x) if
7500d90b
VNM
135 ''.join(c for c in x if c.isalnum()).lower() == keyword.lower()
136 else x,
137 tweet
138 )
139 # Recreate tweet
140 tweet = ' '.join(tweet)
141
142 # Draw rainbow
143 line1 = u"{u:>{uw}}:".format(
144 u=user,
145 uw=len(user) + 2,
146 )
147 line2 = u"{c:>{cw}}".format(
148 c=meta,
149 cw=len(meta) + 2,
150 )
151 line3 = ' ' + tweet
152
153 printNicely('')
154 printNicely(line1)
155 printNicely(line2)
156 printNicely(line3)
157
158 # Display Image
159 if iot and media_url:
160 for mu in media_url:
161 response = requests.get(mu)
162 image_to_display(StringIO(response.content))
163
164
165def print_message(m):
166 """
167 Print direct message
168 """
169 sender_screen_name = '@' + m['sender_screen_name']
170 sender_name = m['sender']['name']
171 text = m['text']
172 recipient_screen_name = '@' + m['recipient_screen_name']
173 recipient_name = m['recipient']['name']
174 mid = m['id']
175 date = parser.parse(m['created_at'])
176 date = date - datetime.timedelta(seconds=time.timezone)
177 clock = date.strftime('%Y/%m/%d %H:%M:%S')
178
179 # Get rainbow id
180 res = db.message_to_rainbow_query(mid)
181 if not res:
182 db.message_store(mid)
183 res = db.message_to_rainbow_query(mid)
184 rid = res[0].rainbow_id
185
6fa09c14 186 # Draw
c075e6dc
O
187 sender = cycle_color(
188 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
189 recipient = cycle_color(recipient_name) + color_func(
190 c['MESSAGE']['recipient'])(
191 ' ' + recipient_screen_name + ' ')
632c6fa5 192 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
c075e6dc
O
193 meta = color_func(
194 c['MESSAGE']['clock'])(
195 '[' + clock + ']') + color_func(
196 c['MESSAGE']['id'])(
197 ' [message_id=' + str(rid) + '] ')
7500d90b
VNM
198 text = ''.join(map(lambda x: x + ' ' if x == '\n' else x, text))
199
200 line1 = u"{u:>{uw}}:".format(
201 u=user,
202 uw=len(user) + 2,
203 )
204 line2 = u"{c:>{cw}}".format(
205 c=meta,
206 cw=len(meta) + 2,
207 )
208
209 line3 = ' ' + text
210
211 printNicely('')
212 printNicely(line1)
213 printNicely(line2)
214 printNicely(line3)
215
216
217def show_profile(u, iot=False):
218 """
219 Show a profile
220 """
221 # Retrieve info
222 name = u['name']
223 screen_name = u['screen_name']
224 description = u['description']
225 profile_image_url = u['profile_image_url']
226 location = u['location']
227 url = u['url']
228 created_at = u['created_at']
229 statuses_count = u['statuses_count']
230 friends_count = u['friends_count']
231 followers_count = u['followers_count']
6fa09c14 232
7500d90b 233 # Create content
c075e6dc
O
234 statuses_count = color_func(
235 c['PROFILE']['statuses_count'])(
236 str(statuses_count) +
237 ' tweets')
238 friends_count = color_func(
239 c['PROFILE']['friends_count'])(
240 str(friends_count) +
241 ' following')
242 followers_count = color_func(
243 c['PROFILE']['followers_count'])(
244 str(followers_count) +
245 ' followers')
7500d90b 246 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
247 user = cycle_color(
248 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
249 profile_image_raw_url = 'Profile photo: ' + \
250 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b
VNM
251 description = ''.join(
252 map(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
253 description = color_func(c['PROFILE']['description'])(description)
254 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
255 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b
VNM
256 date = parser.parse(created_at)
257 date = date - datetime.timedelta(seconds=time.timezone)
258 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 259 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 260
7500d90b
VNM
261 # Format
262 line1 = u"{u:>{uw}}".format(
263 u=user,
264 uw=len(user) + 2,
265 )
266 line2 = u"{p:>{pw}}".format(
267 p=profile_image_raw_url,
268 pw=len(profile_image_raw_url) + 4,
269 )
270 line3 = u"{d:>{dw}}".format(
271 d=description,
272 dw=len(description) + 4,
273 )
274 line4 = u"{l:>{lw}}".format(
275 l=location,
276 lw=len(location) + 4,
277 )
278 line5 = u"{u:>{uw}}".format(
279 u=url,
280 uw=len(url) + 4,
281 )
282 line6 = u"{c:>{cw}}".format(
283 c=clock,
284 cw=len(clock) + 4,
285 )
6fa09c14 286
7500d90b
VNM
287 # Display
288 printNicely('')
289 printNicely(line1)
290 if iot:
291 response = requests.get(profile_image_url)
292 image_to_display(StringIO(response.content), 2, 20)
293 else:
294 printNicely(line2)
295 for line in [line3, line4, line5, line6]:
296 printNicely(line)
297 printNicely('')
298
299
300def print_trends(trends):
301 """
302 Display topics
303 """
632c6fa5 304 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
305 name = topic['name']
306 url = topic['url']
8394e34b 307 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
308 printNicely(line)
309 printNicely('')