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