-
Notifications
You must be signed in to change notification settings - Fork 41
/
protocol.py
147 lines (109 loc) · 2.6 KB
/
protocol.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
import dataclasses
import enum
import hashlib
from datetime import datetime
from typing import Union
ENCODING = "utf-8"
@enum.unique
class SessionState(enum.Enum):
NEW = 0
OPEN = 1
CLOSING = 2
CLOSED = 3
_days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
_months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
# json
# -----------
# Fastest
try:
import ujson as json
kwargs = {} # pragma: no cover
except ImportError: # pragma: no cover
def dthandler(obj):
if isinstance(obj, datetime):
now = obj.timetuple()
return "%s, %02d %s %04d %02d:%02d:%02d -0000" % (
_days[now[6]],
now[2],
_months[now[1] - 1],
now[0],
now[3],
now[4],
now[5],
)
kwargs = {"default": dthandler, "separators": (",", ":")}
# Faster
try:
import simplejson as json
except ImportError:
# Slowest
import json
# Frames
# ------
@enum.unique
class Frame(enum.Enum):
OPEN = "o"
CLOSE = "c"
MESSAGE = "a"
MESSAGE_BLOB = "a1"
HEARTBEAT = "h"
# ------------------
IFRAME_HTML = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="%s"></script>
<script>
document.domain = document.domain;
SockJS.bootstrap_iframe();
</script>
</head>
<body>
<h2>Don't panic!</h2>
<p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
</body>
</html>
""".strip()
IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest()
loads = json.loads
ENCODING = "utf-8"
def dumps(data):
return json.dumps(data, **kwargs)
def close_frame(code, reason):
return Frame.CLOSE.value + json.dumps([code, reason], **kwargs)
def message_frame(message):
return Frame.MESSAGE.value + json.dumps([message], **kwargs)
def messages_frame(messages):
return Frame.MESSAGE.value + json.dumps(messages, **kwargs)
# Handler messages
# ---------------------
@enum.unique
class MsgType(enum.Enum):
OPEN = 1
MESSAGE = 2
CLOSE = 3
CLOSED = 4
@dataclasses.dataclass(frozen=True)
class SockjsMessage:
type: MsgType
data: Union[str, Exception, None]
@property
def tp(self) -> MsgType:
return self.type
OPEN_MESSAGE = SockjsMessage(MsgType.OPEN, None)
CLOSE_MESSAGE = SockjsMessage(MsgType.CLOSE, None)
CLOSED_MESSAGE = SockjsMessage(MsgType.CLOSED, None)