-
Notifications
You must be signed in to change notification settings - Fork 129
/
agent.py
343 lines (301 loc) · 11.6 KB
/
agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/env python
# -*- coding:utf8 -*-
import json
import config
import time
import base64
import urllib, urllib2
import gtk
import threading
import gobject
import utils
import hotot
import os
import sys
import subprocess
try: import i18n
except: from gettext import gettext as _
reload(sys)
sys.setdefaultencoding('utf8')
USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM = True
## Disable GtkNotification on Gnome3
screen = gtk.gdk.screen_get_default()
window_manager_name = screen.get_window_manager_name().lower() if screen else ''
if 'mutter' in window_manager_name:
USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM = False
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
import gtknotification
class Notification(object):
def do_notify(self, summary, body, icon_file = None):
if (icon_file == None or not os.path.isfile(icon_file)):
icon_file = utils.get_ui_object(os.path.join('image','ic64_hotot.png'));
icon_file = 'file://' + icon_file
title = _("Hotot Notification")
text = summary + '\n' + body
gobject.idle_add(gtknotification.gtknotification, title, text, icon_file)
update = do_notify
show = str
notify = Notification()
else:
import pynotify
pynotify.init(_("Hotot Notification"))
notify = pynotify.Notification('Init', '')
webv = None
app = None
http_code_msg_table = {
404: 'The URL you request does not exist. Please check your API Base/OAuth Base/Search Base.'
, 401: 'Server cannot authenticate you. Please check your username/password and API base.'
, 500: 'Server is broken. Please try again later.'
, 502: 'Server is down or being upgraded. Please try again later.'
, 503: 'Server is overcapacity. Please try again later.'
}
def init_notify():
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
return
notify.set_icon_from_pixbuf(
gtk.gdk.pixbuf_new_from_file(
utils.get_ui_object(os.path.join('image','ic64_hotot.png'))))
notify.set_timeout(5000)
def do_notify(summary, body, icon_file = None):
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
return notify.do_notify(summary, body, icon_file)
n = pynotify.Notification(summary, body)
if (icon_file == None or not os.path.isfile(icon_file)):
icon_file = utils.get_ui_object(os.path.join('image','ic64_hotot.png'));
n.set_icon_from_pixbuf(gtk.gdk.pixbuf_new_from_file(icon_file))
n.set_timeout(5000)
n.show()
def crack_hotot(uri):
params = uri.split('/')
try:
if params[0] == 'system':
crack_system(params)
elif params[0] == 'action':
crack_action(params)
elif params[0] == 'request':
raw_json = urllib.unquote(params[1])
req_params = dict([(k.encode('utf8'), v)
for k, v in json.loads(raw_json).items()])
crack_request(req_params)
except Exception, e:
import traceback
print "Exception:"
traceback.print_exc(file=sys.stdout)
def crack_action(params):
if params[1] == 'search':
load_search(params[2])
elif params[1] == 'choose_file':
callback = params[2]
file_path = utils.open_file_chooser_dialog()
webv.execute_script('%s("%s")' % (callback, file_path))
elif params[1] == 'save_avatar':
img_uri = urllib.unquote(params[2])
avatar_file = urllib.unquote(params[3])
avatar_path = os.path.join(config.AVATAR_CACHE_DIR, avatar_file)
if not (os.path.exists(avatar_path) and avatar_file.endswith(img_uri[img_uri.rfind('/')+1:])):
print 'Download:', img_uri , 'To' , avatar_path
th = threading.Thread(
target = save_file_proc,
args=(img_uri, avatar_path))
th.start()
elif params[1] == 'log':
print '\033[1;31;40m[%s]\033[0m %s' % (urllib.unquote(params[2]) ,urllib.unquote(params[3]))
elif params[1] == 'paste_clipboard_text':
webv.paste_clipboard();
elif params[1] == 'set_clipboard_text':
clipboard = gtk.clipboard_get()
text = list(params)
del text[0:2]
clipboard.set_text('/'.join(text))
def crack_system(params):
if params[1] == 'notify':
type = urllib.unquote(params[2])
summary = urllib.unquote(params[3])
body = urllib.unquote(params[4])
if type == 'content':
try:
avatar_file = os.path.join(config.AVATAR_CACHE_DIR, urllib.unquote(params[5]))
except:
avatar_file = None
do_notify(summary, body, avatar_file)
elif type == 'count':
notify.update(summary, body)
notify.show()
elif params[1] == 'load_settings':
settings = json.loads(urllib.unquote(params[2]))
config.load_settings(settings)
app.apply_settings()
elif params[1] == 'sign_in':
app.on_sign_in()
elif params[1] == 'sign_out':
app.on_sign_out()
elif params[1] == 'quit':
app.quit()
def crack_request(req_params):
args = ( req_params['uuid']
, req_params['method']
, req_params['url']
, req_params['params']
, req_params['headers']
, req_params['files'])
th = threading.Thread(target = request, args=args)
th.start()
def save_file_proc(uri, save_path):
if (not os.path.isfile(save_path)):
try:
avatar = open(save_path, "wb")
avatar.write(_get(uri, req_timeout=5))
avatar.close()
except:
import traceback
print "Exception:"
traceback.print_exc(file=sys.stdout)
os.unlink(save_path)
def execute_script(scripts):
return webv.execute_script(scripts)
def update_status(text):
webv.execute_script('''
ui.StatusBox.update_status('%s');
''' % text);
def load_search(query):
webv.execute_script('''
ui.Main.reset_search_page('%s');
$('#search_tweet_block > ul').html('');
ui.Notification.set(_("Loading Search result %s ...")).show();
daemon.update_search();
''' % (query, query));
def set_style_scheme():
style = app.window.get_style()
base, fg, bg, text = style.base, style.fg, style.bg, style.text
webv.execute_script('''
$('#header').css('background', '%s');
''' % str(bg[gtk.STATE_NORMAL]));
def get_prefs(name):
return config.settings[name]
def set_prefs(name, value):
config.settings[name] = value
def request(uuid, method, url, params={}, headers={},files=[],additions=''):
scripts = ''
try:
if (method == 'POST'):
result = _post(url, params, headers, files, additions)
else:
result = _get(url, params, headers)
except urllib2.HTTPError, e:
msg = 'Unknown Errors ... '
if http_code_msg_table.has_key(e.getcode()):
msg = http_code_msg_table[e.getcode()]
tech_info = 'HTTP Code: %s\\nURL: %s\\nDetails: %s' % (e.getcode(), e.geturl(), str(e))
content = '<p>%s</p><h3>- Technological Info -</h3><div class="dlg_group"><pre>%s</pre></div>' % (msg, tech_info)
scripts = '''
widget.DialogManager.alert('%s', '%s');
lib.network.error_task_table['%s']('');
''' % ('Ooops, an Error occurred!', content, uuid);
except urllib2.URLError, e:
content = '<p><label>Error Code:</label>%s<br/><label>Reason:</label> %s, %s<br/></p>' % (e.errno, e.reason, e.strerror)
scripts = '''
widget.DialogManager.alert('%s', '%s');
lib.network.error_task_table['%s']('');
''' % ('Ooops, an Error occurred!', content, uuid);
else:
if uuid != None:
if result[0] != '{' and result[0] != '[':
scripts = '''lib.network.success_task_table['%s']('%s');
''' % (uuid, result)
else:
scripts = '''lib.network.success_task_table['%s'](%s);
''' % (uuid, result)
scripts += '''delete lib.network.success_task_table['%s'];
delete lib.network.error_task_table['%s'];
''' % (uuid, uuid);
gobject.idle_add(webv.execute_script, scripts)
def get_urlopen():
if not get_prefs('use_http_proxy'):
return urllib2.urlopen
scheme = 'https'
host = str(get_prefs('http_proxy_host'))
port = str(get_prefs('http_proxy_port'))
url = scheme + '://' + host + ':' + port
if get_prefs('use_http_proxy_auth'):
proxy_support = urllib2.ProxyHandler({ 'http': url, 'https': url })
username = str(get_prefs('http_proxy_name'))
password = str(get_prefs('http_proxy_password'))
auth_handler = urllib2.ProxyBasicAuthHandler()
auth_handler.add_password(None, url, username, password)
return urllib2.build_opener(proxy_support, auth_handler).open
else:
proxy_support = urllib2.ProxyHandler({ 'http': url, 'https': url })
return urllib2.build_opener(proxy_support).open
def _get(url, params={}, req_headers={}, req_timeout=None):
urlopen = get_urlopen()
request = urllib2.Request(url, headers=req_headers)
ret = urlopen(request, timeout=req_timeout).read()
return ret
def _post(url, params={}, req_headers={}, files=[], additions='', req_timeout=None):
if files != []:
files_headers, files_data = utils.encode_multipart_formdata(params, files)
params ={}
req_headers.update(files_headers)
additions += files_data
urlopen = get_urlopen()
params = dict([(k.encode('utf8')
, v.encode('utf8') if type(v)==unicode else v)
for k, v in params.items()])
request = urllib2.Request(url,
urlencode(params) + additions, headers=req_headers);
ret = urlopen(request, timeout=req_timeout).read()
return ret
pycurl = None
StringIO = None
def _curl(url, params=None, post=False, username=None, password=None, header=None, body=None):
global pycurl, StringIO
if not pycurl:
import pycurl
try: import cStringIO as StringIO
except: import StringIO
curl = pycurl.Curl()
if get_prefs('use_http_proxy'):
HTTP_PROXY = '%s:%s' % (get_prefs('http_proxy_host'), get_prefs('http_proxy_port'))
curl.setopt(pycurl.PROXY, HTTP_PROXY)
if header:
curl.setopt(pycurl.HTTPHEADER, [str(k) + ':' + str(v) for k, v in header.items()])
if post:
curl.setopt(pycurl.POST, 1)
if params:
if post:
curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(params))
else:
url = "?".join((url, urllib.urlencode(params)))
curl.setopt(pycurl.URL, str(url))
if username and password:
curl.setopt(pycurl.USERPWD, "%s:%s" % (str(username), str(password)))
curl.setopt(pycurl.FOLLOWLOCATION, 1)
curl.setopt(pycurl.MAXREDIRS, 5)
curl.setopt(pycurl.TIMEOUT, 15)
curl.setopt(pycurl.CONNECTTIMEOUT, 8)
curl.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0)
content = StringIO.StringIO()
hdr = StringIO.StringIO()
curl.setopt(pycurl.WRITEFUNCTION, content.write)
curl.setopt(pycurl.HEADERFUNCTION, hdr.write)
print curl, url, header
try:
curl.perform()
except pycurl.error, e:
raise e
http_code = curl.getinfo(pycurl.HTTP_CODE)
if http_code != 200:
status_line = hdr.getvalue().splitlines()[0]
status_message = status_line
e =urllib2.HTTPError (str(url), http_code, status_message, {}, None)
e.url = url
raise e
else:
return content.getvalue()
def urlencode(query):
for k,v in query.items():
if not v:
del query[k]
return urllib.urlencode(query)
def idle_it(fn):
return lambda *args: gobject.idle_add(fn, *args)