-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket_server.py
More file actions
145 lines (103 loc) · 4.36 KB
/
socket_server.py
File metadata and controls
145 lines (103 loc) · 4.36 KB
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
# XXX - at this point, this is just tracking the lifecycle of a
# websockets app, it doesn't actually serve the app
# usage:
# in your virtualenv: DJANGO_SETTINGS_MODULE='project.settings' python socket_server.py
import gevent
import time
import json
from datetime import datetime
import time
from gevent import monkey; monkey.patch_all()
from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin
from yarn.models import Artifact, WebsocketAuthToken, Person, FavoriteThreads
from yarn.views import data_for_thread_list, data_for_thread_info, post_new_artifact, save_favorite_thread_list, data_for_thread_updates
from django.db.models import Max, F
from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings
class Tester(BaseNamespace, RoomsMixin, BroadcastMixin):
def on_load_threads(self, args):
token = args['token']
login_name = args['user']
if not WebsocketAuthToken().validate_token(token, login_name):
return
person = Person.objects.get(login_name = login_name)
self.person = person
# These are used for the periodic message updates
self.thread_max_ids = {}
self.last_person_update = time.mktime(datetime.now().timetuple())
thread_data = data_for_thread_list(person)
self.emit('initial_thread_list', json.dumps(thread_data))
self.spawn(self.update_messages, server)
def on_thread_info(self, args):
thread_id = args['thread_id']
data = data_for_thread_info(thread_id, self.person)
self.thread_max_ids[int(thread_id)] = int(data['max_artifact_id'])
self.emit('thread_info', json.dumps({
'thread_info': data,
'args': args,
}))
def on_text_artifact(self, args):
thread_id = args['thread_id']
content = args['content']
post_new_artifact('text', { "value": content }, thread_id, self.person)
def on_set_favorite_threads(self, args):
save_favorite_thread_list(self.person, json.loads(args['thread_ids']))
def update_messages(self, server):
while True:
try:
updates = data_for_thread_updates(self.person, self.thread_max_ids, self.last_person_update)
self.last_person_update = time.mktime(datetime.now().timetuple())
thread_data = updates['updates']
for thread_id in thread_data:
self.thread_max_ids[int(thread_id)] = int(thread_data[int(thread_id)]['max_artifact_id'])
self.emit("messages", updates)
except Exception as ex:
print "Error running update: ", ex
time.sleep(2)
def recv_disconnect(self):
print "Disconnecting"
self.disconnect(silent=True)
self.kill_local_jobs()
#def update_messages(server):
# while True:
# print "In update_messages"
#
# for sessid, socket in server.sockets.iteritems():
# print "S1: ", sessid, "S2: ", socket
#
# pkt = dict(type="event",
# name="new_message",
# args=["What goes in here?"],
# endpoint="")
#
# socket.send_packet(pkt)
#
# time.sleep(2)
class Application(object):
def __init__(self):
self.request = { }
def __call__(self, environ, start_response):
path = environ['PATH_INFO'].strip('/')
if path.startswith("socket.io"):
socketio_manage(environ, {'': Tester}, self.request)
if __name__ == '__main__':
listen_interface = settings.WEBSOCKETS_LISTEN_INTERFACE
listen_port = settings.WEBSOCKETS_LISTEN_PORT
keyfile = None
certfile = None
if hasattr(settings, "WEBSOCKETS_CERTIFICATE_FILE"):
certfile = settings.WEBSOCKETS_CERTIFICATE_FILE
keyfile = settings.WEBSOCKETS_KEY_FILE
socketio_kwargs = {'resource': "socket.io"}
if certfile:
print 'Listening on wss://%s:%s/' % (listen_interface, listen_port)
socketio_kwargs['keyfile'] = keyfile
socketio_kwargs['certfile'] = certfile
else:
print 'Listening on ws://%s:%s/' % (listen_interface, listen_port)
server = SocketIOServer((listen_interface, listen_port), Application(),
**socketio_kwargs)
server.serve_forever()