-
Notifications
You must be signed in to change notification settings - Fork 139
/
services.py
277 lines (242 loc) · 10.8 KB
/
services.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
from aria2p.downloads import Download
import aria
import time
from telegram.ext.dispatcher import run_async
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from handlers import uploader
def build_menu(buttons,
n_cols):
"""Builds the "Pause" and "Cancel" buttons """
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
return menu
def create_markup(gid):
"""Creates Inline Keyboard Buttons and assigns callback data to them"""
button_list = [
InlineKeyboardButton("pause", callback_data=f"pause:{gid}"),
InlineKeyboardButton("cancel", callback_data=f"cancel:{gid}")
]
reply_markup = InlineKeyboardMarkup(
build_menu(buttons=button_list, n_cols=2))
return reply_markup
def create_resume_button(gid):
button_list = [
# The "gid" argument allows us to send a request to aria2 to stop that particular download
InlineKeyboardButton("resume", callback_data=f"resume:{gid}"),
InlineKeyboardButton("cancel", callback_data=f"cancel:{gid}")
]
reply_markup = InlineKeyboardMarkup(
build_menu(buttons=button_list, n_cols=2))
return reply_markup
def progessbar(new, tot):
"""Builds progressbar
Args:
new: current progress
tot: total length of the download
Returns:
progressbar as a string of length 20
"""
length = 20
progress = int(round(length * new / float(tot)))
percent = round(new/float(tot) * 100.0, 1)
bar = '=' * progress + '-' * (length - progress)
return '[%s] %s %s\r' % (bar, percent, '%')
@run_async
def murror(update, updater, context):
link = update.message.text
message = update.message.reply_text("Starting...")
link = link.replace('/mirror', '') # Extracting url from message
link = link.strip() # Removing whitespaces
print(link)
download: Download = None
try:
download = aria.aria2.add_uris([link]) # Adding URL to aria2
except Exception as e:
print(e)
if (str(e).endswith("No URI to download.")):
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="No link provided!")
return None
prevmessage = None
time.sleep(1)
while download.is_active or not download.is_complete:
try:
download.update()
except Exception as e:
# Handles the case if a download is manually deleted from aria2 dashboard
if (str(e).endswith("is not found")):
print("Mirror Deleted")
updater.bot.edit_mtessage_text(
chat_id=message.chat.id, message_id=message.message_id, text="Download removed")
break
print(e)
print("Issue in downloading!")
# Handle download cancel
if download.status == 'removed':
print("Mirror was cancelled")
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="Download removed")
break
# Handles case if aria2 faces an error while downloading
if download.status == 'error':
print("Mirror had an error")
download.remove(force=True, files=True)
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="Download failed to resume/download!")
break
print(f"Mirror Status? {download.status}")
if download.status == "active":
try:
download.update()
# progressbar
barop = progessbar(download.completed_length,
download.total_length)
print(barop)
updateText = f"Downloading \n'{download.name}'\nProgress : {(float(download.completed_length)/ 1024 ** 2):.2f}/{(float(download.total_length)/ 1024 ** 2):.2f} MBs \nat {(float(download.download_speed)/ 1024 ** 2):.2f} MBps\n{barop}"
if prevmessage != updateText:
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text=updateText, reply_markup=create_markup(download.gid))
prevmessage = updateText
print("downloading")
time.sleep(2)
except Exception as e:
if (str(e).endswith("is not found")):
break
print(e)
print("Issue in downloading!/Flood Control")
time.sleep(2)
elif download.status == "paused":
try:
download.update()
updateText = f"Download Paused \n'{download.name}'\nProgress : {(float(download.completed_length)/ 1024 ** 2):.2f}/{(float(download.total_length)/ 1024 ** 2):.2f} MBs"
# To get past telegram flood control, we make sure that the text in every message edit is new
if prevmessage != updateText:
updater.bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id,
text=updateText, reply_markup=create_resume_button(download.gid))
prevmessage = updateText
print("paused")
time.sleep(2)
except Exception as e:
print(e)
print("Download Paused Flood!")
time.sleep(2)
time.sleep(2)
if download.status == "complete":
if download.is_complete:
print(download.name)
try:
uploader(updater, update, message, download, 'folder')
except Exception as e:
print(e)
print("Upload Issue!")
return None
@run_async
def muggnet(update, updater, context):
link = update.message.text
message = update.message.reply_text("Starting...")
link = link.replace('/magnet', '')
link = link.strip()
download: Download = None
try:
download = aria.aria2.add_magnet(link)
except Exception as e:
print(e)
if (str(e).endswith("No URI to download.")):
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="No link provided!")
return None
prevmessagemag = None
while download.is_active:
try:
download.update()
print("Downloading metadata")
updateText = f"Downloading \n'{download.name}'\nProgress : {(float(download.completed_length)/ 1024):.2f}/{(float(download.total_length)/ 1024):.2f} KBs"
if prevmessagemag != updateText:
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text=updateText)
prevmessagemag = updateText
time.sleep(2)
except:
print("Metadata download problem/Flood Control Measures!")
try:
download.update()
except Exception as e:
if (str(e).endswith("is not found")):
print("Metadata Cancelled/Failed")
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="Metadata couldn't be downloaded")
return None
time.sleep(2)
time.sleep(2)
match = str(download.followed_by_ids[0])
downloads = aria.aria2.get_downloads()
currdownload = None
for download in downloads:
if download.gid == match:
currdownload = download
break
print("Download complete")
prevmessage = None
while currdownload.is_active or not currdownload.is_complete:
try:
currdownload.update()
except Exception as e:
if (str(e).endswith("is not found")):
print("Magnet Deleted")
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="Magnet download was removed")
break
print(e)
print("Issue in downloading!")
if currdownload.status == 'removed':
print("Magnet was cancelled")
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text="Magnet download was cancelled")
break
if currdownload.status == 'error':
print("Mirror had an error")
currdownload.remove(force=True, files=True)
updater.bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id,
text="Magnet failed to resume/download!\nRun /cancel once and try again.")
break
print(f"Magnet Status? {currdownload.status}")
if currdownload.status == "active":
try:
currdownload.update()
barop = progessbar(
currdownload.completed_length, currdownload.total_length)
print(barop)
updateText = f"Downloading \n'{currdownload.name}'\nProgress : {(float(currdownload.completed_length)/ 1024 ** 2):.2f}/{(float(currdownload.total_length)/ 1024 ** 2):.2f} MBs \nat {(float(currdownload.download_speed)/ 1024 ** 2):.2f} MBps\n{barop}"
if prevmessage != updateText:
updater.bot.edit_message_text(
chat_id=message.chat.id, message_id=message.message_id, text=updateText, reply_markup=create_markup(currdownload.gid))
prevmessage = updateText
time.sleep(2)
except Exception as e:
if (str(e).endswith("is not found")):
break
print(e)
print("Issue in downloading!")
time.sleep(2)
elif currdownload.status == "paused":
try:
currdownload.update()
updateText = f"Download Paused \n'{currdownload.name}'\nProgress : {(float(currdownload.completed_length)/ 1024 ** 2):.2f}/{(float(currdownload.total_length)/ 1024 ** 2):.2f} MBs"
if prevmessage != updateText:
updater.bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id,
text=updateText, reply_markup=create_resume_button(currdownload.gid))
prevmessage = updateText
time.sleep(2)
except Exception as e:
print(e)
print("Download Paused Flood")
time.sleep(2)
time.sleep(2)
time.sleep(1)
if currdownload.is_complete:
print(currdownload.name)
try:
uploader(updater, update, message, currdownload, 'folder')
except Exception as e:
print(e)
print("Upload Issue!")
return None