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