-
Notifications
You must be signed in to change notification settings - Fork 4
/
push.py
488 lines (364 loc) · 16 KB
/
push.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# -*- coding: utf-8 -*-
# @Author : wzdnzd
# @Time : 2022-07-15
import json
import os
import traceback
import urllib
import urllib.parse
import urllib.request
from enum import Enum
from http.client import HTTPResponse
import utils
from logger import logger
class PushTo(object):
def __init__(self, token: str = "") -> None:
self.api_address = ""
self.name = ""
self.method = "PUT"
self.token = "" if not token or not isinstance(token, str) else token
def _storage(self, content: str, filename: str, folder: str = "") -> bool:
if not content or not filename:
return False
basedir = os.path.abspath(os.environ.get("LOCAL_BASEDIR", ""))
try:
savepath = os.path.abspath(os.path.join(basedir, folder, filename))
os.makedirs(os.path.dirname(savepath), exist_ok=True)
with open(savepath, "w+", encoding="utf8") as f:
f.write(content)
f.flush()
return True
except:
return False
def push_file(self, filepath: str, push_conf: dict, group: str = "", retry: int = 5) -> bool:
if not os.path.exists(filepath) or not os.path.isfile(filepath):
logger.error(f"[PushFileError] file {filepath} not found")
return False
content = " "
with open(filepath, "r", encoding="utf8") as f:
content = f.read()
return self.push_to(content=content, push_conf=push_conf, group=group, retry=retry)
def push_to(self, content: str, push_conf: dict, group: str = "", retry: int = 5, **kwargs) -> bool:
if not self.validate(push_conf=push_conf):
logger.error(f"[PushError] push config is invalidate, domain: {self.name}")
return False
if push_conf.get("local", ""):
self._storage(content=content, filename=push_conf.get("local"))
url, data, headers = self._generate_payload(content=content, push_conf=push_conf)
payload = kwargs.get("payload", None)
if payload and isinstance(payload, dict):
try:
data = json.dumps(payload).encode("UTF8")
except:
logger.error(f"[PushError] invalid payload, domain: {self.name}")
return False
try:
request = urllib.request.Request(url=url, data=data, headers=headers, method=self.method)
response = urllib.request.urlopen(request, timeout=60, context=utils.CTX)
if self._is_success(response):
logger.info(f"[PushSuccess] push subscribes information to {self.name} successed, group=[{group}]")
return True
else:
logger.info(
"[PushError]: group=[{}], name: {}, error message: \n{}".format(
group, self.name, response.read().decode("unicode_escape")
)
)
return False
except Exception:
self._error_handler(group=group)
retry -= 1
if retry > 0:
return self.push_to(content, push_conf, group, retry)
return False
def _is_success(self, response: HTTPResponse) -> bool:
return response and response.getcode() == 200
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
raise NotImplementedError
def _error_handler(self, group: str = "") -> None:
logger.error(f"[PushError]: group=[{group}], name: {self.name}, error message: \n{traceback.format_exc()}")
def validate(self, push_conf: dict) -> bool:
raise NotImplementedError
def filter_push(self, push_conf: dict) -> dict:
raise NotImplementedError
def raw_url(self, push_conf: dict) -> str:
raise NotImplementedError
class PushToPasteGG(PushTo):
"""https://paste.gg"""
def __init__(self, token: str) -> None:
super().__init__(token=token)
self.api_address = "https://api.paste.gg/v1/pastes"
self.name = "paste.gg"
self.method = "PATCH"
def validate(self, push_conf: dict) -> bool:
if not push_conf or type(push_conf) != dict:
return False
folderid = push_conf.get("folderid", "")
fileid = push_conf.get("fileid", "")
return "" != self.token.strip() and "" != folderid.strip() and "" != fileid.strip()
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
folderid = push_conf.get("folderid", "")
fileid = push_conf.get("fileid", "")
headers = {
"Authorization": f"Key {self.token}",
"Content-Type": "application/json",
"User-Agent": utils.USER_AGENT,
}
data = json.dumps({"content": {"format": "text", "value": content}}).encode("UTF8")
url = f"{self.api_address}/{folderid}/files/{fileid}"
return url, data, headers
def _is_success(self, response: HTTPResponse) -> bool:
return response and response.getcode() == 204
def _error_handler(self, group: str = "") -> None:
logger.error(f"[PushError]: group=[{group}], name: {self.name}, error message: \n{traceback.format_exc()}")
def filter_push(self, push_conf: dict) -> dict:
configs = {}
for k, v in push_conf.items():
if self.token and v.get("folderid", "") and v.get("fileid", "") and v.get("username", ""):
configs[k] = v
return configs
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict:
return ""
fileid = push_conf.get("fileid", "")
folderid = push_conf.get("folderid", "")
username = push_conf.get("username", "")
if not fileid or not folderid or not username:
return ""
return f"https://paste.gg/p/{username}/{folderid}/files/{fileid}/raw"
class PushToFarsEE(PushTo):
"""https://fars.ee"""
def __init__(self) -> None:
super().__init__()
self.name = "fars.ee"
self.api_address = "https://fars.ee"
self.method = "PUT"
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
uuid = push_conf.get("uuid", "")
headers = {"Content-Type": "application/json"}
data = json.dumps({"content": content, "private": 1}).encode("UTF8")
url = f"{self.api_address}/{uuid}"
return url, data, headers
def validate(self, push_conf: dict) -> bool:
return push_conf is not None and type(push_conf) == dict and push_conf.get("uuid", "")
def filter_push(self, push_conf: dict) -> dict:
configs = {}
for k, v in push_conf.items():
if v and v.get("uuid", ""):
configs[k] = v
return configs
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict or not push_conf.get("fileid", ""):
return ""
fileid = push_conf.get("fileid", "")
return f"{self.api_address}/{fileid}"
class PushToDevbin(PushToPasteGG):
"""https://devbin.dev"""
def __init__(self, token: str) -> None:
super().__init__(token=token)
self.name = "devbin.dev"
self.api_address = "https://devbin.dev/api/v3/paste"
def validate(self, push_conf: dict) -> bool:
if not push_conf or type(push_conf) != dict:
return False
fileid = push_conf.get("fileid", "")
return "" != self.token.strip() and "" != fileid.strip()
def filter_push(self, push_conf: dict) -> dict:
configs = {}
for k, v in push_conf.items():
if v.get("fileid", "") and self.token:
configs[k] = v
return configs
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
fileid = push_conf.get("fileid", "")
headers = {
"Authorization": self.token,
"Content-Type": "application/json",
"Accept": "*/*",
}
data = json.dumps({"content": content, "syntaxName": "auto"}).encode("UTF8")
url = f"{self.api_address}/{fileid}"
return url, data, headers
def _is_success(self, response: HTTPResponse) -> bool:
return response and response.getcode() == 201
def _error_handler(self, group: str = "") -> None:
super()._error_handler(group)
# TODO: waitting for product enviroment api
self.api_address = "https://beta.devbin.dev/api/v3/paste"
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict or not push_conf.get("fileid", ""):
return ""
fileid = push_conf.get("fileid", "")
return f"https://devbin.dev/Raw/{fileid}"
class PushToPastefy(PushToDevbin):
"""https://pastefy.ga"""
def __init__(self, token: str) -> None:
super().__init__(token)
self.name = "pastefy.ga"
self.api_address = "https://pastefy.ga/api/v2/paste"
self.method = "PUT"
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
fileid = push_conf.get("fileid", "")
headers = {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": utils.USER_AGENT,
}
data = json.dumps({"content": content}).encode("UTF8")
url = f"{self.api_address}/{fileid}"
return url, data, headers
def _is_success(self, response: HTTPResponse) -> bool:
if not response or response.getcode() != 200:
return False
try:
return json.loads(response.read()).get("success", "false")
except:
return False
def _error_handler(self, group: str = "") -> None:
logger.error(f"[PushError]: group=[{group}], name: {self.name}, error message: \n{traceback.format_exc()}")
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict:
return ""
fileid = utils.trim(push_conf.get("fileid", ""))
if not fileid:
return ""
return f"https://pastefy.ga/{fileid}/raw"
class PushToDrift(PushToPastefy):
"""waitting for public api"""
def __init__(self, token: str) -> None:
super().__init__(token=token)
self.name = "drift"
self.api_address = "https://paste.ding.free.hr/api/file"
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict:
return ""
fileid = push_conf.get("fileid", "")
if utils.isblank(text=fileid):
return ""
return f"{self.api_address}/raw/{fileid}"
def _is_success(self, response: HTTPResponse) -> bool:
return response and response.getcode() in [200, 204]
class PushToImperial(PushToPastefy):
def __init__(self, token: str) -> None:
super().__init__(token)
self.name = "imperial"
self.api_address = "https://api.imperialb.in/v1/document"
self.method = "PATCH"
def raw_url(self, push_conf: dict) -> str:
if not self.validate(push_conf):
return ""
fileid = push_conf.get("fileid", "")
return f"https://imperialb.in/r/{fileid}"
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
fileid = push_conf.get("fileid", "")
headers = {
"Authorization": self.token,
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": utils.USER_AGENT,
}
data = json.dumps({"id": fileid, "content": content}).encode("UTF8")
return self.api_address, data, headers
class PushToLocal(PushTo):
def __init__(self) -> None:
super().__init__(token="")
self.name = "local"
def validate(self, push_conf: dict) -> bool:
return push_conf is not None and push_conf.get("fileid", "")
def push_to(self, content: str, push_conf: dict, group: str = "", retry: int = 5) -> bool:
folder = push_conf.get("folderid", "")
filename = push_conf.get("fileid", "")
success = self._storage(content=content, filename=filename, folder=folder)
message = "successed" if success else "failed"
logger.info(f"[PushInfo] push subscribes information to {self.name} {message}, group=[{group}]")
return success
def filter_push(self, push_conf: dict) -> dict:
return {k: v for k, v in push_conf.items() if v.get("fileid", "")}
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict:
return ""
fileid = push_conf.get("fileid", "")
folderid = push_conf.get("folderid", "")
filepath = os.path.abspath(os.path.join(folderid, fileid))
return f"{utils.FILEPATH_PROTOCAL}{filepath}"
class PushToGist(PushTo):
def __init__(self, token: str) -> None:
super().__init__(token=token)
self.name = "gist"
self.api_address = "https://api.github.com/gists"
self.method = "PATCH"
def validate(self, push_conf: dict) -> bool:
if not isinstance(push_conf, dict):
return False
gistid = push_conf.get("gistid", "")
filename = push_conf.get("filename", "")
return "" != self.token.strip() and "" != gistid.strip() and "" != filename.strip()
def _generate_payload(self, content: str, push_conf: dict) -> tuple[str, str, dict]:
gistid = push_conf.get("gistid", "")
filename = push_conf.get("filename", "")
url = f"{self.api_address}/{gistid}"
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": utils.USER_AGENT,
}
data = json.dumps({"files": {filename: {"content": content, "filename": filename}}}).encode("UTF8")
return url, data, headers
def _is_success(self, response: HTTPResponse) -> bool:
return response and response.getcode() == 200
def filter_push(self, push_conf: dict) -> dict:
if not self.token or not isinstance(push_conf, dict):
return {}
return {
k: v
for k, v in push_conf.items()
if k and isinstance(v, dict) and v.get("gistid", "") and v.get("filename", "")
}
def raw_url(self, push_conf: dict) -> str:
if not push_conf or type(push_conf) != dict:
return ""
username = utils.trim(push_conf.get("username", ""))
gistid = utils.trim(push_conf.get("gistid", ""))
revision = utils.trim(push_conf.get("revision", ""))
filename = utils.trim(push_conf.get("filename", ""))
if not username or not gistid or not filename:
return ""
prefix = f"https://gist.githubusercontent.com/{username}/{gistid}"
if revision:
return f"{prefix}/raw/{revision}/{filename}"
return f"{prefix}/raw/{filename}"
PUSHTYPE = Enum(
"PUSHTYPE",
(
"paste.ding.free.hr",
"pastefy.ga",
"paste.gg",
"imperialb.in",
"gist.githubusercontent.com",
),
)
def get_instance(domain: str) -> PushTo:
def confirm_pushtype(url: str) -> int:
domain = utils.extract_domain(url=url, include_protocal=False)
for item in PUSHTYPE:
if domain == item.name:
return item.value
return 0
push_type = confirm_pushtype(url=domain)
token = os.environ.get("PUSH_TOKEN", "").strip()
if push_type != 0 and not token:
raise ValueError(f"[PushError] not found 'PUSH_TOKEN' in environment variables, please check it and try again")
if push_type == 1:
return PushToDrift(token=token)
elif push_type == 2:
return PushToPastefy(token=token)
elif push_type == 3:
return PushToPasteGG(token=token)
elif push_type == 4:
return PushToImperial(token=token)
elif push_type == 5:
return PushToGist(token=token)
return PushToLocal()