bumped version
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import itertools
3 import requests
4 import datetime
5 import time
6
7 from twitter.util import printNicely
8 from functools import wraps
9 from pyfiglet import figlet_format
10 from functools import reduce
11 from StringIO import StringIO
12 from dateutil import parser
13 from .c_image import *
14 from .colors import *
15 from .config import *
16 from .db import *
17
18 db = RainbowDB()
19 g = {}
20
21 def init_cycle():
22 """
23 Init the cycle
24 """
25 colors_shuffle = [globals()[i.encode('utf8')]
26 if not i.startswith('term_')
27 else term_color(int(i[5:]))
28 for i in c['CYCLE_COLOR']]
29 return colors_shuffle, itertools.cycle(colors_shuffle)
30 g['colors_shuffle'], g['cyc'] = init_cycle()
31
32
33 def notify_cycle():
34 """
35 Notify from rainbow
36 """
37 g['colors_shuffle'], g['cyc'] = init_cycle()
38
39
40 def order_rainbow(s):
41 """
42 Print a string with ordered color with each character
43 """
44 c = [g['colors_shuffle'][i % 7](s[i]) for i in xrange(len(s))]
45 return reduce(lambda x, y: x + y, c)
46
47
48 def random_rainbow(s):
49 """
50 Print a string with random color with each character
51 """
52 c = [random.choice(g['colors_shuffle'])(i) for i in s]
53 return reduce(lambda x, y: x + y, c)
54
55
56 def 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
71 def cycle_color(s):
72 """
73 Cycle the colors_shuffle
74 """
75 return next(g['cyc'])(s)
76
77
78 def ascii_art(text):
79 """
80 Draw the Ascii Art
81 """
82 fi = figlet_format(text, font='doom')
83 print('\n'.join(
84 [next(g['cyc'])(i) for i in fi.split('\n')]
85 ))
86
87
88 def 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
107 def 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]
113 if c['theme'] != themes[0]:
114 c['theme'] = themes[0]
115 # Determine path
116 if c['theme'] == 'custom':
117 config = os.environ.get(
118 'HOME',
119 os.environ.get('USERPROFILE',
120 '')) + os.sep + '.rainbow_config.json'
121 else:
122 config = os.path.dirname(__file__) + '/colorset/'+c['theme']+'.json'
123 # Load new config
124 data = load_config(config)
125 if data:
126 for d in data:
127 c[d] = data[d]
128 # Re-init color cycle
129 g['cyc'] = init_cycle()
130
131
132 def color_func(func_name):
133 """
134 Call color function base on name
135 """
136 pure = func_name.encode('utf8')
137 if pure.startswith('term_') and pure[5:].isdigit():
138 return term_color(int(pure[5:]))
139 return globals()[pure]
140
141
142 def draw(t, iot=False, keyword=None, fil=[], ig=[]):
143 """
144 Draw the rainbow
145 """
146
147 check_theme()
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
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) + '] ')
199 if favorited:
200 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
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
209 tweet = map(
210 lambda x: color_func(
211 c['TWEET']['rt'])(x) if x == 'RT' else x,
212 tweet)
213 # Highlight screen_name
214 tweet = map(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
215 # Highlight link
216 tweet = map(
217 lambda x: color_func(
218 c['TWEET']['link'])(x) if x[
219 0:4] == 'http' else x,
220 tweet)
221 # Highlight search keyword
222 if keyword:
223 tweet = map(
224 lambda x: color_func(c['TWEET']['keyword'])(x) if
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
255 def 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
276 # Draw
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 + ' ')
282 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
283 meta = color_func(
284 c['MESSAGE']['clock'])(
285 '[' + clock + ']') + color_func(
286 c['MESSAGE']['id'])(
287 ' [message_id=' + str(rid) + '] ')
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
307 def 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']
322
323 # Create content
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')
336 count = statuses_count + ' ' + friends_count + ' ' + followers_count
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)
341 description = ''.join(
342 map(lambda x: x + ' ' * 4 if x == '\n' else x, description))
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 '')
346 date = parser.parse(created_at)
347 date = date - datetime.timedelta(seconds=time.timezone)
348 clock = date.strftime('%Y/%m/%d %H:%M:%S')
349 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
350
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 )
376
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
390 def print_trends(trends):
391 """
392 Display topics
393 """
394 for topic in trends[:c['TREND_MAX']]:
395 name = topic['name']
396 url = topic['url']
397 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
398 printNicely(line)
399 printNicely('')