include dm in timeline
[rainbowstream.git] / rainbowstream / draw.py
1 import random
2 import itertools
3 import requests
4 import datetime
5 import time
6 import re
7
8 from twitter.util import printNicely
9 from functools import wraps
10 from pyfiglet import figlet_format
11 from dateutil import parser
12 from .c_image import *
13 from .colors import *
14 from .config import *
15 from .db import *
16 from .py3patch import *
17
18
19 db = RainbowDB()
20 g = {}
21
22
23 def init_cycle():
24 """
25 Init the cycle
26 """
27 colors_shuffle = [globals()[i.encode('utf8')]
28 if not str(i).isdigit()
29 else term_color(int(i))
30 for i in c['CYCLE_COLOR']]
31 return itertools.cycle(colors_shuffle)
32
33
34 def start_cycle():
35 """
36 Notify from rainbow
37 """
38 g['cyc'] = init_cycle()
39 g['cache'] = {}
40
41
42 def order_rainbow(s):
43 """
44 Print a string with ordered color with each character
45 """
46 colors_shuffle = [globals()[i.encode('utf8')]
47 if not str(i).isdigit()
48 else term_color(int(i))
49 for i in c['CYCLE_COLOR']]
50 colored = [colors_shuffle[i % 7](s[i]) for i in xrange(len(s))]
51 return ''.join(colored)
52
53
54 def random_rainbow(s):
55 """
56 Print a string with random color with each character
57 """
58 colors_shuffle = [globals()[i.encode('utf8')]
59 if not str(i).isdigit()
60 else term_color(int(i))
61 for i in c['CYCLE_COLOR']]
62 colored = [random.choice(colors_shuffle)(i) for i in s]
63 return ''.join(colored)
64
65
66 def Memoize(func):
67 """
68 Memoize decorator
69 """
70 @wraps(func)
71 def wrapper(*args):
72 if args not in g['cache']:
73 g['cache'][args] = func(*args)
74 return g['cache'][args]
75 return wrapper
76
77
78 @Memoize
79 def cycle_color(s):
80 """
81 Cycle the colors_shuffle
82 """
83 return next(g['cyc'])(s)
84
85
86 def ascii_art(text):
87 """
88 Draw the Ascii Art
89 """
90 fi = figlet_format(text, font='doom')
91 print('\n'.join(
92 [next(g['cyc'])(i) for i in fi.split('\n')]
93 ))
94
95
96 def show_calendar(month, date, rel):
97 """
98 Show the calendar in rainbow mode
99 """
100 month = random_rainbow(month)
101 date = ' '.join([cycle_color(i) for i in date.split(' ')])
102 today = str(int(os.popen('date +\'%d\'').read().strip()))
103 # Display
104 printNicely(month)
105 printNicely(date)
106 for line in rel:
107 ary = line.split(' ')
108 ary = lmap(lambda x: color_func(c['CAL']['today'])(x)
109 if x == today
110 else color_func(c['CAL']['days'])(x), ary)
111 printNicely(' '.join(ary))
112
113
114 def check_theme():
115 """
116 Check current theme and update if necessary
117 """
118 exists = db.theme_query()
119 themes = [t.theme_name for t in exists]
120 if c['THEME'] != themes[0]:
121 c['THEME'] = themes[0]
122 config = os.path.dirname(
123 __file__) + '/colorset/' + c['THEME'] + '.json'
124 # Load new config
125 data = load_config(config)
126 if data:
127 for d in data:
128 c[d] = data[d]
129 # Re-init color cycle
130 g['cyc'] = init_cycle()
131
132
133 def color_func(func_name):
134 """
135 Call color function base on name
136 """
137 if str(func_name).isdigit():
138 return term_color(int(func_name))
139 return globals()[func_name]
140
141
142 def draw(t, iot=False, keyword=None, check_semaphore=False, 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 # Pull extended retweet text
160 try:
161 text = 'RT @' + t['retweeted_status']['user']['screen_name'] + ': ' +\
162 t['retweeted_status']['text']
163 except:
164 pass
165
166 # Unescape HTML character
167 text = unescape(text)
168
169 # Get expanded url
170 try:
171 expanded_url = []
172 url = []
173 urls = t['entities']['urls']
174 for u in urls:
175 expanded_url.append(u['expanded_url'])
176 url.append(u['url'])
177 except:
178 expanded_url = None
179 url = None
180
181 # Get media
182 try:
183 media_url = []
184 media = t['entities']['media']
185 for m in media:
186 media_url.append(m['media_url'])
187 except:
188 media_url = None
189
190 # Filter and ignore
191 screen_name = '@' + screen_name
192 if fil and screen_name not in fil:
193 return
194 if ig and screen_name in ig:
195 return
196
197 # Get rainbow id
198 res = db.tweet_to_rainbow_query(tid)
199 if not res:
200 db.tweet_store(tid)
201 res = db.tweet_to_rainbow_query(tid)
202 rid = res[0].rainbow_id
203
204 # Format info
205 user = cycle_color(
206 name) + color_func(c['TWEET']['nick'])(' ' + screen_name + ' ')
207 meta = color_func(c['TWEET']['clock'])(
208 '[' + clock + '] ') + color_func(c['TWEET']['id'])('[id=' + str(rid) + '] ')
209 if favorited:
210 meta = meta + color_func(c['TWEET']['favorited'])(u'\u2605')
211 tweet = text.split()
212 # Replace url
213 if expanded_url:
214 for index in range(len(expanded_url)):
215 tweet = lmap(
216 lambda x: expanded_url[index] if x == url[index] else x,
217 tweet)
218 # Highlight RT
219 tweet = lmap(
220 lambda x: color_func(
221 c['TWEET']['rt'])(x) if x == 'RT' else x,
222 tweet)
223 # Highlight screen_name
224 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
225 # Highlight link
226 tweet = lmap(
227 lambda x: color_func(
228 c['TWEET']['link'])(x) if x[
229 0:4] == 'http' else x,
230 tweet)
231
232 # Highlight keyword
233 tweet = ' '.join(tweet)
234 if keyword:
235 roj = re.search(keyword, tweet, re.IGNORECASE)
236 if roj:
237 occur = roj.group()
238 ary = tweet.split(occur)
239 delimeter = color_func(c['TWEET']['keyword'])(occur)
240 tweet = delimeter.join(ary)
241
242 # Draw rainbow
243 line1 = u"{u:>{uw}}:".format(
244 u=user,
245 uw=len(user) + 2,
246 )
247 line2 = u"{c:>{cw}}".format(
248 c=meta,
249 cw=len(meta) + 2,
250 )
251 line3 = ' ' + tweet
252
253 # Check the semaphore lock
254 if check_semaphore:
255 while db.semaphore_query():
256 time.sleep(0.5)
257
258 # Output
259 printNicely('')
260 printNicely(line1)
261 printNicely(line2)
262 printNicely(line3)
263
264 # Display Image
265 if iot and media_url:
266 for mu in media_url:
267 try:
268 response = requests.get(mu)
269 image_to_display(BytesIO(response.content))
270 except Exception:
271 printNicely(red('Sorry, image link is broken'))
272
273
274 def print_message(m):
275 """
276 Print direct message
277 """
278 sender_screen_name = '@' + m['sender_screen_name']
279 sender_name = m['sender']['name']
280 text = unescape(m['text'])
281 recipient_screen_name = '@' + m['recipient_screen_name']
282 recipient_name = m['recipient']['name']
283 mid = m['id']
284 date = parser.parse(m['created_at'])
285 date = date - datetime.timedelta(seconds=time.timezone)
286 clock = date.strftime('%Y/%m/%d %H:%M:%S')
287
288 # Get rainbow id
289 res = db.message_to_rainbow_query(mid)
290 if not res:
291 db.message_store(mid)
292 res = db.message_to_rainbow_query(mid)
293 rid = res[0].rainbow_id
294
295 # Draw
296 sender = cycle_color(
297 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
298 recipient = cycle_color(recipient_name) + color_func(
299 c['MESSAGE']['recipient'])(
300 ' ' + recipient_screen_name + ' ')
301 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
302 meta = color_func(
303 c['MESSAGE']['clock'])(
304 '[' + clock + ']') + color_func(
305 c['MESSAGE']['id'])(
306 ' [message_id=' + str(rid) + '] ')
307 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
308
309 line1 = u"{u:>{uw}}:".format(
310 u=user,
311 uw=len(user) + 2,
312 )
313 line2 = u"{c:>{cw}}".format(
314 c=meta,
315 cw=len(meta) + 2,
316 )
317
318 line3 = ' ' + text
319
320 printNicely('')
321 printNicely(line1)
322 printNicely(line2)
323 printNicely(line3)
324
325
326 def show_profile(u, iot=False):
327 """
328 Show a profile
329 """
330 # Retrieve info
331 name = u['name']
332 screen_name = u['screen_name']
333 description = u['description']
334 profile_image_url = u['profile_image_url']
335 location = u['location']
336 url = u['url']
337 created_at = u['created_at']
338 statuses_count = u['statuses_count']
339 friends_count = u['friends_count']
340 followers_count = u['followers_count']
341
342 # Create content
343 statuses_count = color_func(
344 c['PROFILE']['statuses_count'])(
345 str(statuses_count) +
346 ' tweets')
347 friends_count = color_func(
348 c['PROFILE']['friends_count'])(
349 str(friends_count) +
350 ' following')
351 followers_count = color_func(
352 c['PROFILE']['followers_count'])(
353 str(followers_count) +
354 ' followers')
355 count = statuses_count + ' ' + friends_count + ' ' + followers_count
356 user = cycle_color(
357 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
358 profile_image_raw_url = 'Profile photo: ' + \
359 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
360 description = ''.join(
361 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
362 description = color_func(c['PROFILE']['description'])(description)
363 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
364 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
365 date = parser.parse(created_at)
366 date = date - datetime.timedelta(seconds=time.timezone)
367 clock = date.strftime('%Y/%m/%d %H:%M:%S')
368 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
369
370 # Format
371 line1 = u"{u:>{uw}}".format(
372 u=user,
373 uw=len(user) + 2,
374 )
375 line2 = u"{p:>{pw}}".format(
376 p=profile_image_raw_url,
377 pw=len(profile_image_raw_url) + 4,
378 )
379 line3 = u"{d:>{dw}}".format(
380 d=description,
381 dw=len(description) + 4,
382 )
383 line4 = u"{l:>{lw}}".format(
384 l=location,
385 lw=len(location) + 4,
386 )
387 line5 = u"{u:>{uw}}".format(
388 u=url,
389 uw=len(url) + 4,
390 )
391 line6 = u"{c:>{cw}}".format(
392 c=clock,
393 cw=len(clock) + 4,
394 )
395
396 # Display
397 printNicely('')
398 printNicely(line1)
399 if iot:
400 try:
401 response = requests.get(profile_image_url)
402 image_to_display(BytesIO(response.content), 2, 20)
403 except:
404 pass
405 else:
406 printNicely(line2)
407 for line in [line3, line4, line5, line6]:
408 printNicely(line)
409 printNicely('')
410
411
412 def print_trends(trends):
413 """
414 Display topics
415 """
416 for topic in trends[:c['TREND_MAX']]:
417 name = topic['name']
418 url = topic['url']
419 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
420 printNicely(line)
421 printNicely('')
422
423
424 def print_list(group):
425 """
426 Display a list
427 """
428 for g in group:
429 # Format
430 name = g['full_name']
431 name = color_func(c['GROUP']['name'])(name + ' : ')
432 member = str(g['member_count'])
433 member = color_func(c['GROUP']['member'])(member + ' member')
434 subscriber = str(g['subscriber_count'])
435 subscriber = color_func(
436 c['GROUP']['subscriber'])(
437 subscriber +
438 ' subscriber')
439 description = g['description'].strip()
440 description = color_func(c['GROUP']['description'])(description)
441 mode = g['mode']
442 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
443 created_at = g['created_at']
444 date = parser.parse(created_at)
445 date = date - datetime.timedelta(seconds=time.timezone)
446 clock = date.strftime('%Y/%m/%d %H:%M:%S')
447 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
448
449 # Create lines
450 line1 = ' ' * 2 + name + member + ' ' + subscriber
451 line2 = ' ' * 4 + description
452 line3 = ' ' * 4 + mode
453 line4 = ' ' * 4 + clock
454
455 # Display
456 printNicely('')
457 printNicely(line1)
458 printNicely(line2)
459 printNicely(line3)
460 printNicely(line4)
461
462 printNicely('')
463
464
465 # Start the color cycle
466 start_cycle()