/
bend.py
157 lines (136 loc) · 4.88 KB
/
bend.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
import os
import socket
import errno
import logging
import urlparse
import re
import gobject
import cgi
from constants import BASEPATH
from tinyhttpserver import TinyHTTPServer
def uri_path_is_safe(path):
if not BASEPATH and path[0] == '/':
return False
elif path[0:1] == '..':
return False
l = path.split('/')
b = [d for d in l if d == '..']
if len(b) >= len(l):
return False
return True
class Backend(object):
"""
This is the main comunication module,
all comunication to the JS frontend will be issued from here
"""
def __init__(self, core):
self._core = core
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setblocking(0)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._socket.bind(("127.0.0.1", 8080))
self._socket.listen(1)
self._workers = []
self._rules = (
(re.compile('/$'), self.get_index, None),
(re.compile('/static/(.*)'), self.get_static_file, None),
(re.compile('/out$'), self.out, self.out),
(re.compile('/signin'), None, self.post_signin),
(re.compile('/contactClicked'), None, self.post_contact_clicked),
(re.compile('/sendMsg'), None, self.post_send_msg),
)
gobject.io_add_watch(self._socket, gobject.IO_IN, self.on_accept)
self._q = ""
self.login_window = None
self.cl_window = None
self.chat_windows = {}
self.chat_widgets = {}
def on_accept(self, s, c):
w = s.accept()
t = TinyHTTPServer(self, *w, rules = self._rules)
self._workers.append(t)
return True
def emit_event(self, event, *args, **kwargs):
"""
if event in self.listeners.keys():
for func in self.listeners[event]:
try:
func(*args, **kwargs)
except:
pass
"""
def out(self, w, uri, headers, body = None):
if len(self._q):
print ">>> %s" % (self._q,)
w._200(self._q)
self._q = ""
def _args2JS(self, *args):
call = ""
for value in args:
t = type(value).__name__
if (t == 'tuple' or t == 'list'):
call += '['+ self._args2JS(*value)+']'
elif (t == 'str'):
call += "'" + str(value).encode('string_escape') + "',"
elif (t == 'int'):
call += str(value) + ","
else:
print t
call += "'" + str(value).encode('string_escape') + "',"
return call.rstrip(",")
def send(self, event, *args):
# The backend sent a message to the JS client
# select the JS function to call depending on the type of event
if args:
self._q += event + '(' + self._args2JS(*args) + ');'
else:
self._q += event + '();'
def get_index(self, w, uri, headers, body = None):
w.send_file(BASEPATH + "/static/amsn2.html")
def get_static_file(self, w, uri, headers, body = None):
path = uri[2]
if uri_path_is_safe(path):
w.send_file(BASEPATH + path)
else:
w._404()
def post_signin(self, w, uri, headers, body = None):
if self.login_window is None:
w._400()
return
if (body and 'content-type' in headers
and headers['content-type'].startswith('application/x-www-form-urlencoded')):
args = cgi.parse_qs(body)
print "<<< signin: %s" %(args,)
self.login_window.signin(args['username'][0], args['password'][0])
w.write("HTTP/1.1 200 OK\r\n\r\n")
w.close()
return
w._400()
def post_contact_clicked(self, w, uri, headers, body = None):
if self.cl_window is None:
w._400()
return
if (body and 'Content-Type' in headers
and headers['Content-Type'].startswith('application/x-www-form-urlencoded')):
args = cgi.parse_qs(body)
print "<<< contactClicked: %s" %(args,)
self.cl_window.get_contactlist_widget().contact_clicked(args['uid'][0])
w.write("HTTP/1.1 200 OK\r\n\r\n")
w.close()
return
w._400()
def post_send_msg(self, w, uri, headers, body = None):
if (body and 'Content-Type' in headers
and headers['Content-Type'].startswith('application/x-www-form-urlencoded')):
args = cgi.parse_qs(body)
print "<<< sendMsg: %s" %(args,)
uid = args['uid'][0]
if uid not in self.chat_widgets:
w._400()
return
cw = self.chat_widgets[uid]
cw.send_message(uid, args['msg'])
w.write("HTTP/1.1 200 OK\r\n\r\n")
w.close()
return
w._400()