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