re saerch keyword without hashtag
[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, 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 = lmap(
206 lambda x: expanded_url[index] if x == url[index] else x,
207 tweet)
208 # Highlight RT
209 tweet = lmap(
210 lambda x: color_func(
211 c['TWEET']['rt'])(x) if x == 'RT' else x,
212 tweet)
213 # Highlight screen_name
214 tweet = lmap(lambda x: cycle_color(x) if x[0] == '@' else x, tweet)
215 # Highlight link
216 tweet = lmap(
217 lambda x: color_func(
218 c['TWEET']['link'])(x) if x[
219 0:4] == 'http' else x,
220 tweet)
221
222 # Highlight keyword
223 tweet = ' '.join(tweet)
224 if keyword:
225 roj = re.search(keyword,tweet,re.IGNORECASE)
226 if roj:
227 occur = roj.group()
228 ary = tweet.split(occur)
229 delimeter = color_func(c['TWEET']['keyword'])(occur)
230 tweet = delimeter.join(ary)
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 try:
252 response = requests.get(mu)
253 image_to_display(BytesIO(response.content))
254 except Exception:
255 printNicely(red('Sorry, image link is broken'))
256
257
258 def print_message(m):
259 """
260 Print direct message
261 """
262 sender_screen_name = '@' + m['sender_screen_name']
263 sender_name = m['sender']['name']
264 text = m['text']
265 recipient_screen_name = '@' + m['recipient_screen_name']
266 recipient_name = m['recipient']['name']
267 mid = m['id']
268 date = parser.parse(m['created_at'])
269 date = date - datetime.timedelta(seconds=time.timezone)
270 clock = date.strftime('%Y/%m/%d %H:%M:%S')
271
272 # Get rainbow id
273 res = db.message_to_rainbow_query(mid)
274 if not res:
275 db.message_store(mid)
276 res = db.message_to_rainbow_query(mid)
277 rid = res[0].rainbow_id
278
279 # Draw
280 sender = cycle_color(
281 sender_name) + color_func(c['MESSAGE']['sender'])(' ' + sender_screen_name + ' ')
282 recipient = cycle_color(recipient_name) + color_func(
283 c['MESSAGE']['recipient'])(
284 ' ' + recipient_screen_name + ' ')
285 user = sender + color_func(c['MESSAGE']['to'])(' >>> ') + recipient
286 meta = color_func(
287 c['MESSAGE']['clock'])(
288 '[' + clock + ']') + color_func(
289 c['MESSAGE']['id'])(
290 ' [message_id=' + str(rid) + '] ')
291 text = ''.join(lmap(lambda x: x + ' ' if x == '\n' else x, text))
292
293 line1 = u"{u:>{uw}}:".format(
294 u=user,
295 uw=len(user) + 2,
296 )
297 line2 = u"{c:>{cw}}".format(
298 c=meta,
299 cw=len(meta) + 2,
300 )
301
302 line3 = ' ' + text
303
304 printNicely('')
305 printNicely(line1)
306 printNicely(line2)
307 printNicely(line3)
308
309
310 def show_profile(u, iot=False):
311 """
312 Show a profile
313 """
314 # Retrieve info
315 name = u['name']
316 screen_name = u['screen_name']
317 description = u['description']
318 profile_image_url = u['profile_image_url']
319 location = u['location']
320 url = u['url']
321 created_at = u['created_at']
322 statuses_count = u['statuses_count']
323 friends_count = u['friends_count']
324 followers_count = u['followers_count']
325
326 # Create content
327 statuses_count = color_func(
328 c['PROFILE']['statuses_count'])(
329 str(statuses_count) +
330 ' tweets')
331 friends_count = color_func(
332 c['PROFILE']['friends_count'])(
333 str(friends_count) +
334 ' following')
335 followers_count = color_func(
336 c['PROFILE']['followers_count'])(
337 str(followers_count) +
338 ' followers')
339 count = statuses_count + ' ' + friends_count + ' ' + followers_count
340 user = cycle_color(
341 name) + color_func(c['PROFILE']['nick'])(' @' + screen_name + ' : ') + count
342 profile_image_raw_url = 'Profile photo: ' + \
343 color_func(c['PROFILE']['profile_image_url'])(profile_image_url)
344 description = ''.join(
345 lmap(lambda x: x + ' ' * 4 if x == '\n' else x, description))
346 description = color_func(c['PROFILE']['description'])(description)
347 location = 'Location : ' + color_func(c['PROFILE']['location'])(location)
348 url = 'URL : ' + (color_func(c['PROFILE']['url'])(url) if url else '')
349 date = parser.parse(created_at)
350 date = date - datetime.timedelta(seconds=time.timezone)
351 clock = date.strftime('%Y/%m/%d %H:%M:%S')
352 clock = 'Join at ' + color_func(c['PROFILE']['clock'])(clock)
353
354 # Format
355 line1 = u"{u:>{uw}}".format(
356 u=user,
357 uw=len(user) + 2,
358 )
359 line2 = u"{p:>{pw}}".format(
360 p=profile_image_raw_url,
361 pw=len(profile_image_raw_url) + 4,
362 )
363 line3 = u"{d:>{dw}}".format(
364 d=description,
365 dw=len(description) + 4,
366 )
367 line4 = u"{l:>{lw}}".format(
368 l=location,
369 lw=len(location) + 4,
370 )
371 line5 = u"{u:>{uw}}".format(
372 u=url,
373 uw=len(url) + 4,
374 )
375 line6 = u"{c:>{cw}}".format(
376 c=clock,
377 cw=len(clock) + 4,
378 )
379
380 # Display
381 printNicely('')
382 printNicely(line1)
383 if iot:
384 try:
385 response = requests.get(profile_image_url)
386 image_to_display(BytesIO(response.content), 2, 20)
387 except:
388 pass
389 else:
390 printNicely(line2)
391 for line in [line3, line4, line5, line6]:
392 printNicely(line)
393 printNicely('')
394
395
396 def print_trends(trends):
397 """
398 Display topics
399 """
400 for topic in trends[:c['TREND_MAX']]:
401 name = topic['name']
402 url = topic['url']
403 line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
404 printNicely(line)
405 printNicely('')
406
407
408 def print_list(group):
409 """
410 Display a list
411 """
412 for g in group:
413 # Format
414 name = g['full_name']
415 name = color_func(c['GROUP']['name'])(name + ' : ')
416 member = str(g['member_count'])
417 member = color_func(c['GROUP']['member'])(member + ' member')
418 subscriber = str(g['subscriber_count'])
419 subscriber = color_func(
420 c['GROUP']['subscriber'])(
421 subscriber +
422 ' subscriber')
423 description = g['description'].strip()
424 description = color_func(c['GROUP']['description'])(description)
425 mode = g['mode']
426 mode = color_func(c['GROUP']['mode'])('Type: ' + mode)
427 created_at = g['created_at']
428 date = parser.parse(created_at)
429 date = date - datetime.timedelta(seconds=time.timezone)
430 clock = date.strftime('%Y/%m/%d %H:%M:%S')
431 clock = 'Created at ' + color_func(c['GROUP']['clock'])(clock)
432
433 # Create lines
434 line1 = ' ' * 2 + name + member + ' ' + subscriber
435 line2 = ' ' * 4 + description
436 line3 = ' ' * 4 + mode
437 line4 = ' ' * 4 + clock
438
439 # Display
440 printNicely('')
441 printNicely(line1)
442 printNicely(line2)
443 printNicely(line3)
444 printNicely(line4)
445
446 printNicely('')
447
448
449 # Start the color cycle
450 start_cycle()