add calendar and calculator support in theme
[rainbowstream.git] / rainbowstream / draw.py
CommitLineData
e9f5200b
VNM
1import random
2import itertools
7500d90b
VNM
3import requests
4import datetime
5import time
6
2da50cc4 7from twitter.util import printNicely
e9f5200b
VNM
8from functools import wraps
9from pyfiglet import figlet_format
10from functools import reduce
7500d90b
VNM
11from StringIO import StringIO
12from dateutil import parser
2da50cc4 13from .c_image import *
7500d90b
VNM
14from .colors import *
15from .config import *
16from .db import *
17
18db = RainbowDB()
1fdd6a5c
VNM
19g = {}
20
e9f5200b
VNM
21def init_cycle():
22 """
23 Init the cycle
24 """
25 colors_shuffle = [globals()[i.encode('utf8')]
37ae740e 26 if not i.startswith('term_')
8124f3a8 27 else term_color(int(i[5:]))
e9f5200b 28 for i in c['CYCLE_COLOR']]
2a0cabee
O
29 return colors_shuffle, itertools.cycle(colors_shuffle)
30g['colors_shuffle'], g['cyc'] = init_cycle()
1fdd6a5c 31
e9f5200b 32
2359c276
VNM
33def notify_cycle():
34 """
35 Notify from rainbow
36 """
2a0cabee 37 g['colors_shuffle'], g['cyc'] = init_cycle()
2359c276
VNM
38
39
e9f5200b
VNM
40def order_rainbow(s):
41 """
42 Print a string with ordered color with each character
43 """
2a0cabee 44 c = [g['colors_shuffle'][i % 7](s[i]) for i in xrange(len(s))]
e9f5200b
VNM
45 return reduce(lambda x, y: x + y, c)
46
47
48def random_rainbow(s):
49 """
50 Print a string with random color with each character
51 """
2a0cabee 52 c = [random.choice(g['colors_shuffle'])(i) for i in s]
e9f5200b
VNM
53 return reduce(lambda x, y: x + y, c)
54
55
56def Memoize(func):
57 """
58 Memoize decorator
59 """
60 cache = {}
61
62 @wraps(func)
63 def wrapper(*args):
64 if args not in cache:
65 cache[args] = func(*args)
66 return cache[args]
67 return wrapper
68
69
70@Memoize
71def cycle_color(s):
72 """
73 Cycle the colors_shuffle
74 """
1fdd6a5c 75 return next(g['cyc'])(s)
e9f5200b
VNM
76
77
78def ascii_art(text):
79 """
80 Draw the Ascii Art
81 """
82 fi = figlet_format(text, font='doom')
83 print('\n'.join(
1fdd6a5c 84 [next(g['cyc'])(i) for i in fi.split('\n')]
e9f5200b
VNM
85 ))
86
87
2a0cabee
O
88def show_calendar(month, date, rel):
89 """
90 Show the calendar in rainbow mode
91 """
92 month = random_rainbow(month)
93 date = ' '.join([cycle_color(i) for i in date.split(' ')])
94 today = str(int(os.popen('date +\'%d\'').read().strip()))
95 # Display
96 printNicely(month)
97 printNicely(date)
98 for line in rel:
99 ary = line.split(' ')
100 ary = map(lambda x: color_func(c['CAL']['today'])(x)
101 if x == today
102 else color_func(c['CAL']['days'])(x)
103 , ary)
104 printNicely(' '.join(ary))
105
106
4cf86720
VNM
107def check_theme():
108 """
109 Check current theme and update if necessary
110 """
111 exists = db.theme_query()
112 themes = [t.theme_name for t in exists]
ddb1e615
VNM
113 if c['theme'] != themes[0]:
114 c['theme'] = themes[0]
4cf86720 115 # Determine path
ddb1e615 116 if c['theme'] == 'custom':
4cf86720
VNM
117 config = os.environ.get(
118 'HOME',
9c7342ca 119 os.environ.get('USERPROFILE',
4cf86720
VNM
120 '')) + os.sep + '.rainbow_config.json'
121 else:
15f3e155 122 config = os.path.dirname(__file__) + '/colorset/'+c['theme']+'.json'
4cf86720
VNM
123 # Load new config
124 data = load_config(config)
a5301bc0
VNM
125 if data:
126 for d in data:
127 c[d] = data[d]
9c7342ca 128 # Re-init color cycle
1fdd6a5c 129 g['cyc'] = init_cycle()
7500d90b 130
fe08f905
VNM
131
132def color_func(func_name):
133 """
134 Call color function base on name
135 """
136 pure = func_name.encode('utf8')
8124f3a8
VNM
137 if pure.startswith('term_') and pure[5:].isdigit():
138 return term_color(int(pure[5:]))
1face019 139 return globals()[pure]
fe08f905
VNM
140
141
7500d90b
VNM
142def draw(t, iot=False, keyword=None, fil=[], ig=[]):
143 """
144 Draw the rainbow
145 """
146
4cf86720 147 check_theme()
7500d90b
VNM
148 # Retrieve tweet
149 tid = t['id']
150 text = t['text']
151 screen_name = t['user']['screen_name']
152 name = t['user']['name']
153 created_at = t['created_at']
154 favorited = t['favorited']
155 date = parser.parse(created_at)
156 date = date - datetime.timedelta(seconds=time.timezone)
157 clock = date.strftime('%Y/%m/%d %H:%M:%S')
158
159 # Get expanded url
160 try:
161 expanded_url = []
162 url = []
163 urls = t['entities']['urls']
164 for u in urls:
165 expanded_url.append(u['expanded_url'])
166 url.append(u['url'])
167 except:
168 expanded_url = None
169 url = None
170
171 # Get media
172 try:
173 media_url = []
174 media = t['entities']['media']
175 for m in media:
176 media_url.append(m['media_url'])
177 except:
178 media_url = None
179
180 # Filter and ignore
181 screen_name = '@' + screen_name
182 if fil and screen_name not in fil:
183 return
184 if ig and screen_name in ig:
185 return
186
187 # Get rainbow id
188 res = db.tweet_to_rainbow_query(tid)
189 if not res:
190 db.tweet_store(tid)
191 res = db.tweet_to_rainbow_query(tid)
192 rid = res[0].rainbow_id
193
194 # Format info
c075e6dc
O
195 user = cycle_color(
196 name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
197 meta = color_func(c['TWEET']['clock'])(
198 '[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
7500d90b 199 if favorited:
632c6fa5 200 meta = meta + color_func(c['TWEET']['favorite'])(u'\u2605')
7500d90b
VNM
201 tweet = text.split()
202 # Replace url
203 if expanded_url:
204 for index in range(len(expanded_url)):
205 tweet = map(
206 lambda x: expanded_url[index] if x == url[index] else x,
207 tweet)
208 # Highlight RT
c075e6dc
O
209 tweet = map(
210 lambda x: color_func(
211 c['TWEET']['rt'])(x) if x == 'RT' else x,
212 tweet)
7500d90b
VNM
213 # Highlight screen_name
214 tweet = map(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
215 # Highlight link
c075e6dc
O
216 tweet = map(
217 lambda x: color_func(
218 c['TWEET']['link'])(x) if x[
219 0:4] == 'http' else x,
220 tweet)
7500d90b
VNM
221 # Highlight search keyword
222 if keyword:
223 tweet = map(
632c6fa5 224 lambda x: color_func(c['TWEET']['keyword'])(x) if
7500d90b
VNM
225 ''.join(c for c in x if c.isalnum()).lower() == keyword.lower()
226 else x,
227 tweet
228 )
229 # Recreate tweet
230 tweet = ' '.join(tweet)
231
232 # Draw rainbow
233 line1 = u"{u:>{uw}}:".format(
234 u=user,
235 uw=len(user) + 2,
236 )
237 line2 = u"{c:>{cw}}".format(
238 c=meta,
239 cw=len(meta) + 2,
240 )
241 line3 = ' ' + tweet
242
243 printNicely('')
244 printNicely(line1)
245 printNicely(line2)
246 printNicely(line3)
247
248 # Display Image
249 if iot and media_url:
250 for mu in media_url:
251 response = requests.get(mu)
252 image_to_display(StringIO(response.content))
253
254
255def print_message(m):
256 """
257 Print direct message
258 """
259 sender_screen_name = '@' + m['sender_screen_name']
260 sender_name = m['sender']['name']
261 text = m['text']
262 recipient_screen_name = '@' + m['recipient_screen_name']
263 recipient_name = m['recipient']['name']
264 mid = m['id']
265 date = parser.parse(m['created_at'])
266 date = date - datetime.timedelta(seconds=time.timezone)
267 clock = date.strftime('%Y/%m/%d %H:%M:%S')
268
269 # Get rainbow id
270 res = db.message_to_rainbow_query(mid)
271 if not res:
272 db.message_store(mid)
273 res = db.message_to_rainbow_query(mid)
274 rid = res[0].rainbow_id
275
6fa09c14 276 # Draw
c075e6dc
O
277 sender = cycle_color(
278 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
279 recipient = cycle_color(recipient_name) + color_func(
280 c['MESSAGE']['recipient'])(
281 ' ' + recipient_screen_name + ' ')
632c6fa5 282 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
c075e6dc
O
283 meta = color_func(
284 c['MESSAGE']['clock'])(
285 '[' + clock + ']') + color_func(
286 c['MESSAGE']['id'])(
287 ' [message_id=' + str(rid) + '] ')
7500d90b
VNM
288 text = ''.join(map(lambda x: x + ' ' if x == '\n' else x, text))
289
290 line1 = u"{u:>{uw}}:".format(
291 u=user,
292 uw=len(user) + 2,
293 )
294 line2 = u"{c:>{cw}}".format(
295 c=meta,
296 cw=len(meta) + 2,
297 )
298
299 line3 = ' ' + text
300
301 printNicely('')
302 printNicely(line1)
303 printNicely(line2)
304 printNicely(line3)
305
306
307def show_profile(u, iot=False):
308 """
309 Show a profile
310 """
311 # Retrieve info
312 name = u['name']
313 screen_name = u['screen_name']
314 description = u['description']
315 profile_image_url = u['profile_image_url']
316 location = u['location']
317 url = u['url']
318 created_at = u['created_at']
319 statuses_count = u['statuses_count']
320 friends_count = u['friends_count']
321 followers_count = u['followers_count']
6fa09c14 322
7500d90b 323 # Create content
c075e6dc
O
324 statuses_count = color_func(
325 c['PROFILE']['statuses_count'])(
326 str(statuses_count) +
327 ' tweets')
328 friends_count = color_func(
329 c['PROFILE']['friends_count'])(
330 str(friends_count) +
331 ' following')
332 followers_count = color_func(
333 c['PROFILE']['followers_count'])(
334 str(followers_count) +
335 ' followers')
7500d90b 336 count = statuses_count + ' ' + friends_count + ' ' + followers_count
c075e6dc
O
337 user = cycle_color(
338 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
339 profile_image_raw_url = 'Profile photo: ' + \
340 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
7500d90b
VNM
341 description = ''.join(
342 map(lambda x: x + ' ' * 4 if x == '\n' else x, description))
632c6fa5
O
343 description = color_func(c['PROFILE']['description'])(description)
344 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
345 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
7500d90b
VNM
346 date = parser.parse(created_at)
347 date = date - datetime.timedelta(seconds=time.timezone)
348 clock = date.strftime('%Y/%m/%d %H:%M:%S')
632c6fa5 349 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
6fa09c14 350
7500d90b
VNM
351 # Format
352 line1 = u"{u:>{uw}}".format(
353 u=user,
354 uw=len(user) + 2,
355 )
356 line2 = u"{p:>{pw}}".format(
357 p=profile_image_raw_url,
358 pw=len(profile_image_raw_url) + 4,
359 )
360 line3 = u"{d:>{dw}}".format(
361 d=description,
362 dw=len(description) + 4,
363 )
364 line4 = u"{l:>{lw}}".format(
365 l=location,
366 lw=len(location) + 4,
367 )
368 line5 = u"{u:>{uw}}".format(
369 u=url,
370 uw=len(url) + 4,
371 )
372 line6 = u"{c:>{cw}}".format(
373 c=clock,
374 cw=len(clock) + 4,
375 )
6fa09c14 376
7500d90b
VNM
377 # Display
378 printNicely('')
379 printNicely(line1)
380 if iot:
381 response = requests.get(profile_image_url)
382 image_to_display(StringIO(response.content), 2, 20)
383 else:
384 printNicely(line2)
385 for line in [line3, line4, line5, line6]:
386 printNicely(line)
387 printNicely('')
388
389
390def print_trends(trends):
391 """
392 Display topics
393 """
632c6fa5 394 for topic in trends[:c['TREND_MAX']]:
7500d90b
VNM
395 name = topic['name']
396 url = topic['url']
8394e34b 397 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
7500d90b
VNM
398 printNicely(line)
399 printNicely('')