-
Notifications
You must be signed in to change notification settings - Fork 6
/
pymobird.py
164 lines (133 loc) · 5.35 KB
/
pymobird.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
158
159
160
161
162
163
from datetime import datetime
from base64 import b64encode
from PIL import Image
from io import BytesIO
import requests
__version__ = "0.2.1"
_current_timestamp = lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class APIError(Exception):
def __init__(self, res_code, res_error):
self.res_code = res_code
self.res_error = res_error
def __str__(self):
return "res_code: {} res_error: {}".format(self.res_code, self.res_error)
def check_api_error(resp):
resp.raise_for_status()
data = resp.json()
if data["showapi_res_code"] != 1:
raise APIError(data["showapi_res_code"], data["showapi_res_error"])
class Content(object):
IMAGE_MAX_WIDTH = 384
def __init__(self):
self.parts = []
def add_text(self, text):
self.parts.append(("T", text))
def add_image(self, fp_or_file_path):
image = Image.open(fp_or_file_path)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
width, height = image.size
if width > self.IMAGE_MAX_WIDTH:
image = image.resize((self.IMAGE_MAX_WIDTH, height * 384 // width),
Image.ANTIALIAS)
image = image.convert("1")
p = BytesIO()
image.save(p, "BMP")
self.parts.append(("P", p.getvalue()))
def to_string(self):
encoded = []
last = len(self.parts) - 1
for index, (content_type, data) in enumerate(self.parts):
if content_type == "T":
if not index == last and not data.endswith("\n"):
data += "\n"
encoded.append("T:"+b64encode(data.encode("GBK", errors="ignore")).decode("ascii"))
elif content_type == "P":
encoded.append("P:"+b64encode(data).decode("ascii"))
return "|".join(encoded)
class Pymobird(object):
"""for advanced usage (multiple devices), use this class directly"""
BASE_URL = "http://open.memobird.cn/home"
_headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
def __init__(self, ak):
if not ak:
print("ak not provided")
self._ak = ak
self._session = requests.session()
def _url(self, path):
return self.BASE_URL + path
def get_user_id(self, device_id, user_identifying=""):
path = "/setuserbind"
data = {
"ak": self._ak,
"timestamp": _current_timestamp(),
"memobirdID": device_id,
"useridentifying": user_identifying,
}
resp = self._session.get(self._url(path), params=data, headers=self._headers)
check_api_error(resp)
user_id = resp.json()["showapi_userid"]
return user_id
def _print(self, device_id, user_id, content):
path = "/printpaper"
data = {
"ak": self._ak,
"timestamp": _current_timestamp(),
"printcontent": content.to_string(),
"memobirdID": device_id,
"userID": user_id,
}
resp = self._session.post(self._url(path), json=data, headers=self._headers)
check_api_error(resp)
content_id = resp.json()["printcontentid"]
return content_id
def print_text(self, device_id, user_id, text):
content = Content()
content.add_text(text)
return self._print(device_id, user_id, content)
def print_image(self, device_id, user_id, image):
content = Content()
content.add_image(image)
return self._print(device_id, user_id, content)
def print_multi_part_content(self, device_id, user_id, content):
return self._print(device_id, user_id, content)
def print_url(self, device_id, user_id, url):
path = "/printpaperFromUrl"
data = {
"ak": self._ak,
"timestamp": _current_timestamp(),
"printUrl": url,
"memobirdID": device_id,
"userID": user_id,
}
resp = self._session.post(self._url(path), json=data, headers=self._headers)
check_api_error(resp)
content_id = resp.json()["printcontentid"]
return content_id
def check_printed(self, content_id):
path = "/getprintstatus"
resp = self._session.get(self._url(path),
params={"ak": self._ak,
"timestamp": _current_timestamp(),
"printcontentid": content_id},
headers=self._headers)
check_api_error(resp)
return resp.json()["printflag"] == 1
class SimplePymobird(object):
"""for single device"""
def __init__(self, ak, device_id, user_identifying=""):
self._bird = Pymobird(ak)
self.device_id = device_id
self.user_id = self._bird.get_user_id(self.device_id, user_identifying)
def print_text(self, text):
return self._bird.print_text(self.device_id, self.user_id, text)
def print_image(self, image):
return self._bird.print_image(self.device_id, self.user_id, image)
def print_multi_part_content(self, content):
return self._bird.print_multi_part_content(self.device_id, self.user_id, content)
def print_url(self, url):
return self._bird.print_url(self.device_id, self.user_id, url)
def check_printed(self, content_id):
return self._bird.check_printed(content_id)