Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
anasty17
GitHub Repository: anasty17/mirror-leech-telegram-bot
Path: blob/master/bot/core/startup.py
1629 views
1
from aiofiles.os import path as aiopath, remove, makedirs
2
from aiofiles import open as aiopen
3
from aioshutil import rmtree
4
from asyncio import create_subprocess_exec, create_subprocess_shell, sleep
5
from importlib import import_module
6
7
from .. import (
8
aria2_options,
9
qbit_options,
10
nzb_options,
11
drives_ids,
12
drives_names,
13
index_urls,
14
user_data,
15
excluded_extensions,
16
included_extensions,
17
LOGGER,
18
rss_dict,
19
sabnzbd_client,
20
auth_chats,
21
sudo_users,
22
)
23
from ..helper.ext_utils.db_handler import database
24
from .config_manager import Config
25
from .telegram_manager import TgClient
26
from .torrent_manager import TorrentManager
27
28
29
async def update_qb_options():
30
LOGGER.info("Get qBittorrent options from server")
31
if not qbit_options:
32
opt = await TorrentManager.qbittorrent.app.preferences()
33
qbit_options.update(opt)
34
del qbit_options["listen_port"]
35
for k in list(qbit_options.keys()):
36
if k.startswith("rss"):
37
del qbit_options[k]
38
qbit_options["web_ui_password"] = "mltbmltb"
39
await TorrentManager.qbittorrent.app.set_preferences(
40
{"web_ui_password": "mltbmltb"}
41
)
42
else:
43
await TorrentManager.qbittorrent.app.set_preferences(qbit_options)
44
45
46
async def update_aria2_options():
47
LOGGER.info("Get aria2 options from server")
48
if not aria2_options:
49
op = await TorrentManager.aria2.getGlobalOption()
50
aria2_options.update(op)
51
else:
52
await TorrentManager.aria2.changeGlobalOption(aria2_options)
53
54
55
async def update_nzb_options():
56
LOGGER.info("Get SABnzbd options from server")
57
while True:
58
try:
59
no = (await sabnzbd_client.get_config())["config"]["misc"]
60
nzb_options.update(no)
61
except:
62
await sleep(0.5)
63
continue
64
break
65
66
67
async def load_settings():
68
if not Config.DATABASE_URL:
69
return
70
for p in ["thumbnails", "tokens", "rclone"]:
71
if await aiopath.exists(p):
72
await rmtree(p, ignore_errors=True)
73
await database.connect()
74
if database.db is not None:
75
BOT_ID = Config.BOT_TOKEN.split(":", 1)[0]
76
settings = import_module("config")
77
config_file = {
78
key: value.strip() if isinstance(value, str) else value
79
for key, value in vars(settings).items()
80
if not key.startswith("__")
81
}
82
old_config = await database.db.settings.deployConfig.find_one(
83
{"_id": BOT_ID}, {"_id": 0}
84
)
85
if old_config is None:
86
await database.db.settings.deployConfig.replace_one(
87
{"_id": BOT_ID}, config_file, upsert=True
88
)
89
if old_config and old_config != config_file:
90
LOGGER.info("Replacing existing deploy config in Database")
91
await database.db.settings.deployConfig.replace_one(
92
{"_id": BOT_ID}, config_file, upsert=True
93
)
94
else:
95
config_dict = await database.db.settings.config.find_one(
96
{"_id": BOT_ID}, {"_id": 0}
97
)
98
if config_dict:
99
Config.load_dict(config_dict)
100
101
if pf_dict := await database.db.settings.files.find_one(
102
{"_id": BOT_ID}, {"_id": 0}
103
):
104
for key, value in pf_dict.items():
105
if value:
106
file_ = key.replace("__", ".")
107
async with aiopen(file_, "wb+") as f:
108
await f.write(value)
109
110
if a2c_options := await database.db.settings.aria2c.find_one(
111
{"_id": BOT_ID}, {"_id": 0}
112
):
113
aria2_options.update(a2c_options)
114
115
if qbit_opt := await database.db.settings.qbittorrent.find_one(
116
{"_id": BOT_ID}, {"_id": 0}
117
):
118
qbit_options.update(qbit_opt)
119
120
if nzb_opt := await database.db.settings.nzb.find_one(
121
{"_id": BOT_ID}, {"_id": 0}
122
):
123
if await aiopath.exists("sabnzbd/SABnzbd.ini.bak"):
124
await remove("sabnzbd/SABnzbd.ini.bak")
125
((key, value),) = nzb_opt.items()
126
file_ = key.replace("__", ".")
127
async with aiopen(f"sabnzbd/{file_}", "wb+") as f:
128
await f.write(value)
129
130
if await database.db.users.find_one():
131
for p in ["thumbnails", "tokens", "rclone"]:
132
if not await aiopath.exists(p):
133
await makedirs(p)
134
rows = database.db.users.find({})
135
async for row in rows:
136
uid = row["_id"]
137
del row["_id"]
138
thumb_path = f"thumbnails/{uid}.jpg"
139
rclone_config_path = f"rclone/{uid}.conf"
140
token_path = f"tokens/{uid}.pickle"
141
if row.get("THUMBNAIL"):
142
async with aiopen(thumb_path, "wb+") as f:
143
await f.write(row["THUMBNAIL"])
144
row["THUMBNAIL"] = thumb_path
145
if row.get("RCLONE_CONFIG"):
146
async with aiopen(rclone_config_path, "wb+") as f:
147
await f.write(row["RCLONE_CONFIG"])
148
row["RCLONE_CONFIG"] = rclone_config_path
149
if row.get("TOKEN_PICKLE"):
150
async with aiopen(token_path, "wb+") as f:
151
await f.write(row["TOKEN_PICKLE"])
152
row["TOKEN_PICKLE"] = token_path
153
user_data[uid] = row
154
LOGGER.info("Users data has been imported from Database")
155
156
if await database.db.rss[BOT_ID].find_one():
157
rows = database.db.rss[BOT_ID].find({})
158
async for row in rows:
159
user_id = row["_id"]
160
del row["_id"]
161
rss_dict[user_id] = row
162
LOGGER.info("Rss data has been imported from Database.")
163
164
165
async def save_settings():
166
if database.db is None:
167
return
168
config_dict = Config.get_all()
169
await database.db.settings.config.replace_one(
170
{"_id": TgClient.ID}, config_dict, upsert=True
171
)
172
if await database.db.settings.aria2c.find_one({"_id": TgClient.ID}) is None:
173
await database.db.settings.aria2c.update_one(
174
{"_id": TgClient.ID}, {"$set": aria2_options}, upsert=True
175
)
176
if await database.db.settings.qbittorrent.find_one({"_id": TgClient.ID}) is None:
177
await database.save_qbit_settings()
178
if await database.db.settings.nzb.find_one({"_id": TgClient.ID}) is None:
179
async with aiopen("sabnzbd/SABnzbd.ini", "rb+") as pf:
180
nzb_conf = await pf.read()
181
await database.db.settings.nzb.update_one(
182
{"_id": TgClient.ID}, {"$set": {"SABnzbd__ini": nzb_conf}}, upsert=True
183
)
184
185
186
async def update_variables():
187
if (
188
Config.LEECH_SPLIT_SIZE > TgClient.MAX_SPLIT_SIZE
189
or Config.LEECH_SPLIT_SIZE == 2097152000
190
or not Config.LEECH_SPLIT_SIZE
191
):
192
Config.LEECH_SPLIT_SIZE = TgClient.MAX_SPLIT_SIZE
193
194
Config.HYBRID_LEECH = bool(Config.HYBRID_LEECH and TgClient.IS_PREMIUM_USER)
195
Config.USER_TRANSMISSION = bool(
196
Config.USER_TRANSMISSION and TgClient.IS_PREMIUM_USER
197
)
198
199
if Config.AUTHORIZED_CHATS:
200
aid = Config.AUTHORIZED_CHATS.split()
201
for id_ in aid:
202
chat_id, *thread_ids = id_.split("|")
203
chat_id = int(chat_id.strip())
204
if thread_ids:
205
thread_ids = list(map(lambda x: int(x.strip()), thread_ids))
206
auth_chats[chat_id] = thread_ids
207
else:
208
auth_chats[chat_id] = []
209
210
if Config.SUDO_USERS:
211
aid = Config.SUDO_USERS.split()
212
for id_ in aid:
213
sudo_users.append(int(id_.strip()))
214
215
if Config.EXCLUDED_EXTENSIONS:
216
fx = Config.EXCLUDED_EXTENSIONS.split()
217
for x in fx:
218
x = x.lstrip(".")
219
excluded_extensions.append(x.strip().lower())
220
221
if Config.INCLUDED_EXTENSIONS:
222
fx = Config.INCLUDED_EXTENSIONS.split()
223
for x in fx:
224
x = x.lstrip(".")
225
included_extensions.append(x.strip().lower())
226
227
if Config.GDRIVE_ID:
228
drives_names.append("Main")
229
drives_ids.append(Config.GDRIVE_ID)
230
index_urls.append(Config.INDEX_URL)
231
232
if await aiopath.exists("list_drives.txt"):
233
async with aiopen("list_drives.txt", "r+") as f:
234
lines = await f.readlines()
235
for line in lines:
236
temp = line.split()
237
drives_ids.append(temp[1])
238
drives_names.append(temp[0].replace("_", " "))
239
if len(temp) > 2:
240
index_urls.append(temp[2])
241
else:
242
index_urls.append("")
243
244
245
async def load_configurations():
246
247
if not await aiopath.exists(".netrc"):
248
async with aiopen(".netrc", "w"):
249
pass
250
251
await (
252
await create_subprocess_shell(
253
"chmod 600 .netrc && cp .netrc /root/.netrc && chmod +x aria-nox-nzb.sh && ./aria-nox-nzb.sh"
254
)
255
).wait()
256
257
if Config.BASE_URL:
258
await create_subprocess_shell(
259
f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{Config.BASE_URL_PORT}"
260
)
261
262
if await aiopath.exists("cfg.zip"):
263
if await aiopath.exists("/JDownloader/cfg"):
264
await rmtree("/JDownloader/cfg", ignore_errors=True)
265
await (
266
await create_subprocess_exec("7z", "x", "cfg.zip", "-o/JDownloader")
267
).wait()
268
269
if await aiopath.exists("accounts.zip"):
270
if await aiopath.exists("accounts"):
271
await rmtree("accounts")
272
await (
273
await create_subprocess_exec(
274
"7z", "x", "-o.", "-aoa", "accounts.zip", "accounts/*.json"
275
)
276
).wait()
277
await (await create_subprocess_exec("chmod", "-R", "777", "accounts")).wait()
278
await remove("accounts.zip")
279
280
if not await aiopath.exists("accounts"):
281
Config.USE_SERVICE_ACCOUNTS = False
282
283