message.py
2.31 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
# -*- coding: utf-8 -*-
__all__ = ["decode", "Message", "OkMessage", "KoMessage", "DownloadRequest"
, "UploadRequest", "DownloadPrimRequest", "ClientDone", "ServerDone"
, "NumMessage", "BoolMessage", "ReturnRequest", "CheckoutRequest",
"CheckinRequest", "StatsRequest"]
class Message(object):
"""
Base class for SSL communication messages.
"""
def __init__(self, contents=""):
self.contents = contents
def get_contents(self):
return self.contents
@classmethod
def from_contents(cls, contents):
return cls(contents)
def encode(self):
"""
Prepare message to be sent over network.
WARNING: Do not override this method.
"""
# Add "-" on the beggining to prevent
# message contents from being void.
return self.msg_type, "-" + self.get_contents()
class NumMessage(Message):
def __init__(self, n):
self.number = n
def get_contents(self):
return str(self.number)
@classmethod
def from_contents(cls, contents):
return cls(int(contents))
def get_number(self):
return self.number
class BoolMessage(Message):
def __init__(self, b):
self.b = b
def get_contents(self):
return "1" if self.b else "0"
@classmethod
def from_contents(cls, contents):
return cls(bool(int(contents)))
def get_boolean(self):
return self.b
class ReturnRequest(NumMessage):
pass
class CheckoutRequest(Message):
pass
class CheckinRequest(NumMessage):
pass
class DownloadRequest(NumMessage):
pass
class DownloadPrimRequest(NumMessage):
pass
class UploadRequest(NumMessage):
pass
class OkMessage(Message):
pass
class KoMessage(Message):
pass
class StatsRequest(Message):
pass
class ServerDone(Message):
pass
class ClientDone(Message):
pass
def subclasses(cls):
yield cls
for child in cls.__subclasses__():
for desc in subclasses(child):
yield desc
def decode(msg_type, contents):
for cls in subclasses(Message):
if cls.msg_type == msg_type:
# Discard first, dummy character;
# Confront Message.encode method.
return cls.from_contents(contents[1:])
for i, cls in enumerate(subclasses(Message)):
cls.msg_type = i