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
|
from pkg_resources import resource_string
import json
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
class RootHandler(tornado.web.RequestHandler):
def get(self):
self.write(resource_string(__name__, "index.html"))
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self, publisher):
self.publisher = publisher
self.watching_id = None
self.initialized = False
self.publisher.subscribe(self)
def on_message(self, message):
print(message)
data = json.loads(message)
if data["type"] == "request_streamer_list":
streamers = self.publisher.request_all("get_streamers")
reply = {
"type": "streamer_list",
"streamers": [ { "id": s["id"], "name": s["name"].decode('utf-8', 'replace') } for s in streamers ],
}
self.write_message(json.dumps(reply))
elif data["type"] == "start_watching":
self.watching_id = data["who"]
self.publisher.notify("new_viewer", self.watching_id)
def on_close(self):
self.publisher.unsubscribe(self)
self.publisher.notify("viewer_disconnect", self.watching_id)
def msg_new_data(self, connection_id, prev_buf, data, screen, updates):
if self.watching_id != connection_id:
return
if updates:
reply = {
"type": "update_screen",
"updates": updates,
}
else:
reply = {
"type": "redraw_screen",
"screen": screen,
}
try:
self.write_message(json.dumps(reply))
except:
self.publisher.unsubscribe(self)
def make_app(publisher):
return tornado.web.Application([
('/', RootHandler),
('/-/', WebSocketHandler, dict(publisher=publisher)),
])
def start_server(sock, publisher, pemfile):
# XXX set up ssl with pemfile
server = tornado.httpserver.HTTPServer(make_app(publisher))
server.add_socket(sock)
tornado.ioloop.IOLoop.instance().start()
|