warp-beacon 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- etc/warp_beacon/warp_beacon.conf +10 -0
- lib/systemd/system/warp_beacon.service +14 -0
- warp_beacon/__init__.py +0 -0
- warp_beacon/__version__.py +2 -0
- warp_beacon/jobs/__init__.py +0 -0
- warp_beacon/jobs/abstract.py +60 -0
- warp_beacon/jobs/download_job.py +23 -0
- warp_beacon/jobs/upload_job.py +26 -0
- warp_beacon/mediainfo/__init__.py +0 -0
- warp_beacon/mediainfo/video.py +80 -0
- warp_beacon/scrapler/__init__.py +155 -0
- warp_beacon/scrapler/abstract.py +16 -0
- warp_beacon/scrapler/instagram.py +191 -0
- warp_beacon/storage/__init__.py +82 -0
- warp_beacon/uploader/__init__.py +118 -0
- warp_beacon/warp_beacon.py +360 -0
- warp_beacon-1.0.2.dist-info/LICENSE +201 -0
- warp_beacon-1.0.2.dist-info/METADATA +286 -0
- warp_beacon-1.0.2.dist-info/RECORD +22 -0
- warp_beacon-1.0.2.dist-info/WHEEL +5 -0
- warp_beacon-1.0.2.dist-info/entry_points.txt +5 -0
- warp_beacon-1.0.2.dist-info/top_level.txt +14 -0
@@ -0,0 +1,118 @@
|
|
1
|
+
import threading
|
2
|
+
import multiprocessing
|
3
|
+
from warp_beacon.jobs.upload_job import UploadJob
|
4
|
+
#import time
|
5
|
+
import logging
|
6
|
+
|
7
|
+
import asyncio
|
8
|
+
from telegram import Update
|
9
|
+
from telegram.ext import ContextTypes
|
10
|
+
|
11
|
+
from typing import Optional, Callable, Coroutine
|
12
|
+
|
13
|
+
from warp_beacon.storage import Storage
|
14
|
+
|
15
|
+
class AsyncUploader(object):
|
16
|
+
threads = []
|
17
|
+
allow_loop = True
|
18
|
+
job_queue = None
|
19
|
+
callbacks = {}
|
20
|
+
storage = None
|
21
|
+
in_process = set()
|
22
|
+
loop = None
|
23
|
+
pool_size = 1
|
24
|
+
|
25
|
+
def __init__(self, loop: asyncio.AbstractEventLoop, storage: Storage, pool_size: int=multiprocessing.cpu_count()) -> None:
|
26
|
+
self.storage = storage
|
27
|
+
self.loop = loop
|
28
|
+
self.job_queue = multiprocessing.Queue()
|
29
|
+
self.pool_size = pool_size
|
30
|
+
|
31
|
+
def __del__(self) -> None:
|
32
|
+
self.stop_all()
|
33
|
+
|
34
|
+
def start(self) -> None:
|
35
|
+
for _ in range(self.pool_size):
|
36
|
+
thread = threading.Thread(target=self.do_work)
|
37
|
+
self.threads.append(thread)
|
38
|
+
thread.start()
|
39
|
+
|
40
|
+
def add_callback(self, message_id: int, callback: Callable, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
41
|
+
def callback_wrap(*args, **kwargs) -> None:
|
42
|
+
ret = callback(*args, **kwargs)
|
43
|
+
self.remove_callback(message_id)
|
44
|
+
return ret
|
45
|
+
self.callbacks[message_id] = {"callback": callback_wrap, "update": update, "context": context}
|
46
|
+
|
47
|
+
def remove_callback(self, message_id: int) -> None:
|
48
|
+
if message_id in self.callbacks:
|
49
|
+
del self.callbacks[message_id]
|
50
|
+
|
51
|
+
def stop_all(self) -> None:
|
52
|
+
self.allow_loop = False
|
53
|
+
for i in self.threads:
|
54
|
+
i.join()
|
55
|
+
self.threads.clear()
|
56
|
+
|
57
|
+
def is_inprocess(self, uniq_id: str) -> bool:
|
58
|
+
return uniq_id in self.in_process
|
59
|
+
|
60
|
+
def process_done(self, uniq_id: str) -> None:
|
61
|
+
self.in_process.discard(uniq_id)
|
62
|
+
|
63
|
+
def set_inprocess(self, uniq_id: str) -> None:
|
64
|
+
self.in_process.add(uniq_id)
|
65
|
+
|
66
|
+
def queue_task(self, job: UploadJob) -> None:
|
67
|
+
self.job_queue.put_nowait(job)
|
68
|
+
|
69
|
+
def do_work(self) -> None:
|
70
|
+
logging.info("Upload worker started")
|
71
|
+
while self.allow_loop:
|
72
|
+
try:
|
73
|
+
try:
|
74
|
+
job = self.job_queue.get()
|
75
|
+
path = ""
|
76
|
+
if job.media_type == "collection":
|
77
|
+
for i in job.media_collection:
|
78
|
+
path += "%s; " % i.local_media_path
|
79
|
+
else:
|
80
|
+
path = job.local_media_path
|
81
|
+
in_process = job.in_process
|
82
|
+
uniq_id = job.uniq_id
|
83
|
+
message_id = job.message_id
|
84
|
+
if not in_process:
|
85
|
+
logging.info("Accepted upload job, file(s): '%s'", path)
|
86
|
+
try:
|
87
|
+
for m_id in self.callbacks.copy():
|
88
|
+
if m_id == message_id:
|
89
|
+
if job.job_failed:
|
90
|
+
logging.info("URL '%s' download failed. Skipping upload job ...", job.url)
|
91
|
+
if job.job_failed_msg: # we want to say something to user
|
92
|
+
asyncio.ensure_future(self.callbacks[m_id]["callback"](job), loop=self.loop)
|
93
|
+
self.process_done(uniq_id)
|
94
|
+
self.remove_callback(message_id)
|
95
|
+
continue
|
96
|
+
if in_process:
|
97
|
+
db_list_dicts = self.storage.db_lookup_id(uniq_id)
|
98
|
+
if db_list_dicts:
|
99
|
+
tg_file_ids = [i["tg_file_id"] for i in db_list_dicts]
|
100
|
+
dlds_len = len(db_list_dicts)
|
101
|
+
if dlds_len > 1:
|
102
|
+
job.tg_file_id = ",".join(tg_file_ids)
|
103
|
+
job.media_type = "collection"
|
104
|
+
elif dlds_len:
|
105
|
+
job.tg_file_id = ",".join(tg_file_ids)
|
106
|
+
job.media_type = db_list_dicts.pop()["media_type"]
|
107
|
+
asyncio.ensure_future(self.callbacks[m_id]["callback"](job), loop=self.loop)
|
108
|
+
else:
|
109
|
+
self.queue_task(job)
|
110
|
+
else:
|
111
|
+
asyncio.ensure_future(self.callbacks[m_id]["callback"](job), loop=self.loop)
|
112
|
+
except Exception as e:
|
113
|
+
logging.exception(e)
|
114
|
+
except multiprocessing.Queue.empty:
|
115
|
+
pass
|
116
|
+
except Exception as e:
|
117
|
+
logging.error("Exception occurred inside upload worker!")
|
118
|
+
logging.exception(e)
|
@@ -0,0 +1,360 @@
|
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
# -*- coding: utf-8 -*-
|
3
|
+
|
4
|
+
import os
|
5
|
+
import signal
|
6
|
+
import asyncio
|
7
|
+
import logging
|
8
|
+
|
9
|
+
from urlextract import URLExtract
|
10
|
+
|
11
|
+
from telegram import ForceReply, Update, Chat, error, InputMediaVideo, InputMediaPhoto
|
12
|
+
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
|
13
|
+
|
14
|
+
import warp_beacon.scrapler
|
15
|
+
from warp_beacon.storage import Storage
|
16
|
+
from warp_beacon.uploader import AsyncUploader
|
17
|
+
from warp_beacon.jobs.download_job import DownloadJob, UploadJob
|
18
|
+
|
19
|
+
# Enable logging
|
20
|
+
logging.basicConfig(
|
21
|
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
22
|
+
)
|
23
|
+
# set higher logging level for httpx to avoid all GET and POST requests being logged
|
24
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
25
|
+
|
26
|
+
logger = logging.getLogger(__name__)
|
27
|
+
|
28
|
+
storage = Storage()
|
29
|
+
uploader = None
|
30
|
+
downloader = None
|
31
|
+
|
32
|
+
# Define a few command handlers. These usually take the two arguments update and
|
33
|
+
# context.
|
34
|
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
35
|
+
"""Send a message when the command /start is issued."""
|
36
|
+
user = update.effective_user
|
37
|
+
await update.message.reply_html(
|
38
|
+
rf"Hi {user.mention_html()}!",
|
39
|
+
reply_markup=ForceReply(selective=True),
|
40
|
+
)
|
41
|
+
|
42
|
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
43
|
+
"""Send a message when the command /help is issued."""
|
44
|
+
await update.message.reply_text("Send me a link to remote media")
|
45
|
+
|
46
|
+
async def random(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
47
|
+
d = storage.get_random()
|
48
|
+
if not d:
|
49
|
+
await update.message.reply_text("No random content yet.")
|
50
|
+
return
|
51
|
+
await upload_job(update, context, UploadJob(tg_file_id=d["tg_file_id"], media_type=d["media_type"], message_id=update.message.message_id))
|
52
|
+
|
53
|
+
async def send_text(update: Update, context: ContextTypes.DEFAULT_TYPE, reply_id: int, text: str) -> None:
|
54
|
+
try:
|
55
|
+
await update.message.reply_text(
|
56
|
+
text,
|
57
|
+
reply_to_message_id=reply_id
|
58
|
+
)
|
59
|
+
except Exception as e:
|
60
|
+
logging.error("Failed to send text message!")
|
61
|
+
logging.exception(e)
|
62
|
+
|
63
|
+
def build_tg_args(job: UploadJob) -> dict:
|
64
|
+
args = {}
|
65
|
+
timeout = int(os.environ.get("TG_WRITE_TIMEOUT", default=120))
|
66
|
+
if job.media_type == "video":
|
67
|
+
if job.tg_file_id:
|
68
|
+
args["video"] = job.tg_file_id.replace(":video", '')
|
69
|
+
else:
|
70
|
+
args["video"] = open(job.local_media_path, 'rb')
|
71
|
+
args["supports_streaming"] = True
|
72
|
+
args["duration"] = int(job.media_info["duration"])
|
73
|
+
args["width"] = job.media_info["width"]
|
74
|
+
args["height"] = job.media_info["height"]
|
75
|
+
args["thumbnail"] = job.media_info["thumb"]
|
76
|
+
elif job.media_type == "image":
|
77
|
+
if job.tg_file_id:
|
78
|
+
args["photo"] = job.tg_file_id.replace(":image", '')
|
79
|
+
else:
|
80
|
+
args["photo"] = open(job.local_media_path, 'rb')
|
81
|
+
elif job.media_type == "collection":
|
82
|
+
if job.tg_file_id:
|
83
|
+
args["media"] = []
|
84
|
+
for i in job.tg_file_id.split(','):
|
85
|
+
tg_id, mtype = i.split(':')
|
86
|
+
ptr = None
|
87
|
+
if mtype == "video":
|
88
|
+
ptr = InputMediaVideo(media=tg_id)
|
89
|
+
elif mtype == "image":
|
90
|
+
ptr = InputMediaPhoto(media=tg_id)
|
91
|
+
args["media"].append(ptr)
|
92
|
+
else:
|
93
|
+
mediafs = []
|
94
|
+
for j in job.media_collection:
|
95
|
+
if j.media_type == "video":
|
96
|
+
vid = InputMediaVideo(
|
97
|
+
media=open(j.local_media_path, 'rb'),
|
98
|
+
supports_streaming=True,
|
99
|
+
width=j.media_info["width"],
|
100
|
+
height=j.media_info["height"],
|
101
|
+
duration=int(j.media_info["duration"]),
|
102
|
+
thumbnail=j.media_info["thumb"]
|
103
|
+
)
|
104
|
+
mediafs.append(vid)
|
105
|
+
elif j.media_type == "image":
|
106
|
+
photo = InputMediaPhoto(
|
107
|
+
media=open(j.local_media_path, 'rb')
|
108
|
+
)
|
109
|
+
mediafs.append(photo)
|
110
|
+
args["media"] = mediafs
|
111
|
+
|
112
|
+
# common args
|
113
|
+
args["disable_notification"] = True
|
114
|
+
args["write_timeout"] = timeout
|
115
|
+
args["read_timeout"] = timeout
|
116
|
+
args["connect_timeout"] = timeout
|
117
|
+
args["reply_to_message_id"] = job.message_id
|
118
|
+
|
119
|
+
return args
|
120
|
+
|
121
|
+
async def upload_job(update: Update, context: ContextTypes.DEFAULT_TYPE, job: UploadJob) -> list[str]:
|
122
|
+
timeout = int(os.environ.get("TG_WRITE_TIMEOUT", default=120))
|
123
|
+
tg_file_ids = []
|
124
|
+
try:
|
125
|
+
retry_amount = 0
|
126
|
+
max_retries = int(os.environ.get("TG_MAX_RETRIES", default=5))
|
127
|
+
while not retry_amount >= max_retries:
|
128
|
+
try:
|
129
|
+
if job.media_type == "video":
|
130
|
+
message = await update.message.reply_video(**build_tg_args(job))
|
131
|
+
tg_file_ids.append(message.video.file_id)
|
132
|
+
job.tg_file_id = message.video.file_id
|
133
|
+
elif job.media_type == "image":
|
134
|
+
message = await update.message.reply_photo(**build_tg_args(job))
|
135
|
+
if message.photo:
|
136
|
+
tg_file_ids.append(message.photo[-1].file_id)
|
137
|
+
job.tg_file_id = message.photo[-1].file_id
|
138
|
+
elif job.media_type == "collection":
|
139
|
+
sent_messages = await update.message.reply_media_group(**build_tg_args(job))
|
140
|
+
for i, msg in enumerate(sent_messages):
|
141
|
+
if msg.video:
|
142
|
+
tg_file_ids.append(msg.video.file_id + ':video')
|
143
|
+
if job.media_collection:
|
144
|
+
job.media_collection[i].tg_file_id = msg.video.file_id + ':video'
|
145
|
+
elif msg.photo:
|
146
|
+
tg_file_ids.append(msg.photo[-1].file_id + ':image')
|
147
|
+
if job.media_collection:
|
148
|
+
job.media_collection[i].tg_file_id = msg.photo[-1].file_id + ':image'
|
149
|
+
logging.info("Uploaded to Telegram")
|
150
|
+
break
|
151
|
+
except error.TimedOut as e:
|
152
|
+
logging.error("TG timeout error!")
|
153
|
+
logging.exception(e)
|
154
|
+
await send_text(
|
155
|
+
update,
|
156
|
+
context,
|
157
|
+
job.message_id,
|
158
|
+
"Telegram timeout error occurred! Your configuration timeout value is `%d`" % timeout
|
159
|
+
)
|
160
|
+
break
|
161
|
+
except error.NetworkError as e:
|
162
|
+
logging.error("Failed to upload due telegram limits :(")
|
163
|
+
logging.exception(e)
|
164
|
+
if not "Request Entity Too Large" in e.message:
|
165
|
+
logging.info("TG upload will be retried. Configuration `TG_MAX_RETRIES` values is %d.", max_retries)
|
166
|
+
|
167
|
+
if "Message to reply not found" in e.message:
|
168
|
+
logging.warning("No message to reply found. Looks like original message was deleted by author.")
|
169
|
+
job.message_id = None
|
170
|
+
continue
|
171
|
+
|
172
|
+
if retry_amount+1 >= max_retries or "Request Entity Too Large" in e.message:
|
173
|
+
msg = ""
|
174
|
+
if e.message:
|
175
|
+
msg = "Telegram error: %s" % str(e.message)
|
176
|
+
else:
|
177
|
+
msg = "Unfortunately, Telegram limits were exceeded. Your video size is %.2f MB." % job.media_info["filesize"]
|
178
|
+
await send_text(
|
179
|
+
update,
|
180
|
+
context,
|
181
|
+
job.message_id,
|
182
|
+
msg
|
183
|
+
)
|
184
|
+
break
|
185
|
+
retry_amount += 1
|
186
|
+
except Exception as e:
|
187
|
+
logging.error("Error occurred!")
|
188
|
+
logging.exception(e)
|
189
|
+
finally:
|
190
|
+
if job.media_type == "collection":
|
191
|
+
for j in job.media_collection:
|
192
|
+
if os.path.exists(j.local_media_path):
|
193
|
+
os.unlink(j.local_media_path)
|
194
|
+
else:
|
195
|
+
if os.path.exists(job.local_media_path):
|
196
|
+
os.unlink(job.local_media_path)
|
197
|
+
|
198
|
+
return tg_file_ids
|
199
|
+
|
200
|
+
async def handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
201
|
+
if update.message is None:
|
202
|
+
return
|
203
|
+
chat = update.effective_chat
|
204
|
+
effective_message_id = update.message.message_id
|
205
|
+
extractor = URLExtract()
|
206
|
+
urls = extractor.find_urls(update.message.text_html)
|
207
|
+
|
208
|
+
reply_text = "Wut?"
|
209
|
+
if not urls:
|
210
|
+
reply_text = "Your message should contains URLs"
|
211
|
+
else:
|
212
|
+
for url in urls:
|
213
|
+
if "instagram.com" not in url:
|
214
|
+
logging.info("Only instagram.com is now supported. Skipping.")
|
215
|
+
continue
|
216
|
+
entities, tg_file_ids = [], []
|
217
|
+
uniq_id = Storage.compute_uniq(url)
|
218
|
+
try:
|
219
|
+
entities = storage.db_lookup_id(uniq_id)
|
220
|
+
except Exception as e:
|
221
|
+
logging.error("Failed to search link in DB!")
|
222
|
+
logging.exception(e)
|
223
|
+
if entities:
|
224
|
+
tg_file_ids = [i["tg_file_id"] for i in entities]
|
225
|
+
logging.info("URL '%s' is found in DB. Sending with tg_file_ids = '%s'", url, str(tg_file_ids))
|
226
|
+
ent_len = len(entities)
|
227
|
+
if ent_len > 1:
|
228
|
+
await upload_job(
|
229
|
+
update,
|
230
|
+
context,
|
231
|
+
UploadJob(
|
232
|
+
tg_file_id=",".join(tg_file_ids),
|
233
|
+
message_id=effective_message_id,
|
234
|
+
media_type="collection"
|
235
|
+
)
|
236
|
+
)
|
237
|
+
elif ent_len:
|
238
|
+
media_type = entities.pop()["media_type"]
|
239
|
+
await upload_job(
|
240
|
+
update,
|
241
|
+
context,
|
242
|
+
UploadJob(
|
243
|
+
tg_file_id=tg_file_ids.pop(),
|
244
|
+
message_id=effective_message_id,
|
245
|
+
media_type=media_type
|
246
|
+
)
|
247
|
+
)
|
248
|
+
else:
|
249
|
+
async def upload_wrapper(job: UploadJob) -> None:
|
250
|
+
try:
|
251
|
+
if job.job_failed and job.job_failed_msg:
|
252
|
+
return await send_text(update, context, reply_id=job.message_id, text=job.job_failed_msg)
|
253
|
+
tg_file_ids = await upload_job(update, context, job)
|
254
|
+
if tg_file_ids:
|
255
|
+
if job.media_type == "collection" and job.save_items:
|
256
|
+
for i in job.media_collection:
|
257
|
+
storage.add_media(tg_file_ids=[i.tg_file_id], media_url=i.effective_url, media_type=i.media_type, origin="instagram")
|
258
|
+
else:
|
259
|
+
storage.add_media(tg_file_ids=[','.join(tg_file_ids)], media_url=job.url, media_type=job.media_type, origin="instagram")
|
260
|
+
except Exception as e:
|
261
|
+
logging.error("Exception occurred while performing upload callback!")
|
262
|
+
logging.exception(e)
|
263
|
+
finally:
|
264
|
+
uploader.process_done(job.uniq_id)
|
265
|
+
uploader.remove_callback(job.message_id)
|
266
|
+
|
267
|
+
uploader.add_callback(effective_message_id, upload_wrapper, update, context)
|
268
|
+
|
269
|
+
try:
|
270
|
+
downloader.queue_task(DownloadJob.build(
|
271
|
+
url=url,
|
272
|
+
message_id=effective_message_id,
|
273
|
+
in_process=uploader.is_inprocess(uniq_id),
|
274
|
+
uniq_id=uniq_id
|
275
|
+
))
|
276
|
+
uploader.set_inprocess(uniq_id)
|
277
|
+
except Exception as e:
|
278
|
+
logging.error("Failed to schedule download task!")
|
279
|
+
logging.exception(e)
|
280
|
+
|
281
|
+
if chat.type not in (Chat.GROUP, Chat.SUPERGROUP) and not urls:
|
282
|
+
await update.message.reply_text(reply_text, reply_to_message_id=effective_message_id)
|
283
|
+
|
284
|
+
@staticmethod
|
285
|
+
def _raise_system_exit() -> None:
|
286
|
+
raise SystemExit
|
287
|
+
|
288
|
+
def main() -> None:
|
289
|
+
"""Start the bot."""
|
290
|
+
try:
|
291
|
+
global uploader, downloader
|
292
|
+
|
293
|
+
loop = asyncio.get_event_loop()
|
294
|
+
stop_signals = (signal.SIGINT, signal.SIGTERM, signal.SIGABRT)
|
295
|
+
for sig in stop_signals or []:
|
296
|
+
loop.add_signal_handler(sig, _raise_system_exit)
|
297
|
+
loop.add_signal_handler(sig, _raise_system_exit)
|
298
|
+
|
299
|
+
uploader = AsyncUploader(
|
300
|
+
storage=storage,
|
301
|
+
pool_size=int(os.environ.get("UPLOAD_POOL_SIZE", default=warp_beacon.scrapler.CONST_CPU_COUNT)),
|
302
|
+
loop=loop
|
303
|
+
)
|
304
|
+
downloader = warp_beacon.scrapler.AsyncDownloader(
|
305
|
+
workers_count=int(os.environ.get("WORKERS_POOL_SIZE", default=warp_beacon.scrapler.CONST_CPU_COUNT)),
|
306
|
+
uploader=uploader
|
307
|
+
)
|
308
|
+
downloader.start()
|
309
|
+
uploader.start()
|
310
|
+
|
311
|
+
# Create the Application and pass it your bot's token.
|
312
|
+
tg_token = os.environ.get("TG_TOKEN", default=None)
|
313
|
+
application = Application.builder().token(tg_token).concurrent_updates(True).build()
|
314
|
+
|
315
|
+
# on different commands - answer in Telegram
|
316
|
+
application.add_handler(CommandHandler("start", start))
|
317
|
+
application.add_handler(CommandHandler("random", random))
|
318
|
+
application.add_handler(CommandHandler("help", help_command))
|
319
|
+
|
320
|
+
# on non command i.e message - echo the message on Telegram
|
321
|
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handler))
|
322
|
+
|
323
|
+
allow_loop = True
|
324
|
+
try:
|
325
|
+
loop.run_until_complete(application.initialize())
|
326
|
+
if application.post_init:
|
327
|
+
loop.run_until_complete(application.post_init(application))
|
328
|
+
loop.run_until_complete(application.updater.start_polling())
|
329
|
+
loop.run_until_complete(application.start())
|
330
|
+
while allow_loop:
|
331
|
+
try:
|
332
|
+
loop.run_forever()
|
333
|
+
except (KeyboardInterrupt, SystemExit) as e:
|
334
|
+
allow_loop = False
|
335
|
+
raise e
|
336
|
+
except Exception as e:
|
337
|
+
logging.error("Main loop Telegram error!")
|
338
|
+
logging.exception(e)
|
339
|
+
except (KeyboardInterrupt, SystemExit):
|
340
|
+
logging.debug("Application received stop signal. Shutting down.")
|
341
|
+
finally:
|
342
|
+
try:
|
343
|
+
if application.updater.running: # type: ignore[union-attr]
|
344
|
+
loop.run_until_complete(application.updater.stop()) # type: ignore[union-attr]
|
345
|
+
if application.running:
|
346
|
+
loop.run_until_complete(application.stop())
|
347
|
+
if application.post_stop:
|
348
|
+
loop.run_until_complete(application.post_stop(application))
|
349
|
+
loop.run_until_complete(application.shutdown())
|
350
|
+
if application.post_shutdown:
|
351
|
+
loop.run_until_complete(application.post_shutdown(application))
|
352
|
+
finally:
|
353
|
+
loop.close()
|
354
|
+
downloader.stop_all()
|
355
|
+
uploader.stop_all()
|
356
|
+
except Exception as e:
|
357
|
+
logging.exception(e)
|
358
|
+
|
359
|
+
if __name__ == "__main__":
|
360
|
+
main()
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|