prad9036 commited on
Commit
0a41ecf
·
1 Parent(s): 6de4594
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +15 -0
  2. LICENSE +674 -0
  3. _config.yml +1 -0
  4. add_to_team_drive.py +104 -0
  5. aria-nox-nzb.sh +11 -0
  6. bot/__init__.py +80 -0
  7. bot/__main__.py +66 -0
  8. bot/core/__init__.py +1 -0
  9. bot/core/config_manager.py +240 -0
  10. bot/core/handlers.py +321 -0
  11. bot/core/jdownloader_booter.py +91 -0
  12. bot/core/startup.py +288 -0
  13. bot/core/telegram_manager.py +82 -0
  14. bot/core/torrent_manager.py +134 -0
  15. bot/helper/__init__.py +1 -0
  16. bot/helper/common.py +1217 -0
  17. bot/helper/ext_utils/__init__.py +1 -0
  18. bot/helper/ext_utils/bot_utils.py +256 -0
  19. bot/helper/ext_utils/bulk_links.py +35 -0
  20. bot/helper/ext_utils/db_handler.py +220 -0
  21. bot/helper/ext_utils/exceptions.py +22 -0
  22. bot/helper/ext_utils/files_utils.py +463 -0
  23. bot/helper/ext_utils/help_messages.py +435 -0
  24. bot/helper/ext_utils/links_utils.py +49 -0
  25. bot/helper/ext_utils/media_utils.py +767 -0
  26. bot/helper/ext_utils/status_utils.py +254 -0
  27. bot/helper/ext_utils/task_manager.py +154 -0
  28. bot/helper/ext_utils/telegraph_helper.py +86 -0
  29. bot/helper/listeners/__init__.py +1 -0
  30. bot/helper/listeners/aria2_listener.py +195 -0
  31. bot/helper/listeners/direct_listener.py +86 -0
  32. bot/helper/listeners/jdownloader_listener.py +91 -0
  33. bot/helper/listeners/nzb_listener.py +104 -0
  34. bot/helper/listeners/qbit_listener.py +202 -0
  35. bot/helper/listeners/task_listener.py +494 -0
  36. bot/helper/mirror_leech_utils/__init__.py +1 -0
  37. bot/helper/mirror_leech_utils/download_utils/__init__.py +1 -0
  38. bot/helper/mirror_leech_utils/download_utils/aria2_download.py +103 -0
  39. bot/helper/mirror_leech_utils/download_utils/direct_downloader.py +60 -0
  40. bot/helper/mirror_leech_utils/download_utils/direct_link_generator.py +1918 -0
  41. bot/helper/mirror_leech_utils/download_utils/direct_link_generator_license.md +82 -0
  42. bot/helper/mirror_leech_utils/download_utils/gd_download.py +54 -0
  43. bot/helper/mirror_leech_utils/download_utils/jd_download.py +374 -0
  44. bot/helper/mirror_leech_utils/download_utils/nzb_downloader.py +167 -0
  45. bot/helper/mirror_leech_utils/download_utils/qbit_download.py +149 -0
  46. bot/helper/mirror_leech_utils/download_utils/rclone_download.py +124 -0
  47. bot/helper/mirror_leech_utils/download_utils/telegram_download.py +178 -0
  48. bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py +358 -0
  49. bot/helper/mirror_leech_utils/gdrive_utils/__init__.py +1 -0
  50. bot/helper/mirror_leech_utils/gdrive_utils/clone.py +169 -0
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM anasty17/mltb:latest
2
+
3
+ WORKDIR /app
4
+ RUN chmod 777 /app
5
+
6
+ RUN python3 -m venv mltbenv
7
+
8
+ COPY requirements.txt .
9
+ RUN mltbenv/bin/pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY . .
12
+
13
+ RUN sed -i 's/\r$//' *.sh
14
+
15
+ CMD ["bash", "start.sh"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
_config.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ theme: jekyll-theme-time-machine
add_to_team_drive.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+
3
+ import argparse
4
+ import glob
5
+ import googleapiclient.discovery
6
+ import json
7
+ import os
8
+ import pickle
9
+ import progress.bar
10
+ import sys
11
+ import time
12
+ from google.auth.transport.requests import Request
13
+ from google_auth_oauthlib.flow import InstalledAppFlow
14
+
15
+ stt = time.time()
16
+
17
+ parse = argparse.ArgumentParser(
18
+ description="A tool to add service accounts to a shared drive from a folder containing credential files."
19
+ )
20
+ parse.add_argument(
21
+ "--path",
22
+ "-p",
23
+ default="accounts",
24
+ help="Specify an alternative path to the service accounts folder.",
25
+ )
26
+ parse.add_argument(
27
+ "--credentials",
28
+ "-c",
29
+ default="./credentials.json",
30
+ help="Specify the relative path for the credentials file.",
31
+ )
32
+ parse.add_argument(
33
+ "--yes", "-y", default=False, action="store_true", help="Skips the sanity prompt."
34
+ )
35
+ parsereq = parse.add_argument_group("required arguments")
36
+ parsereq.add_argument(
37
+ "--drive-id", "-d", help="The ID of the Shared Drive.", required=True
38
+ )
39
+
40
+ args = parse.parse_args()
41
+ acc_dir = args.path
42
+ did = args.drive_id
43
+ credentials = glob.glob(args.credentials)
44
+
45
+ try:
46
+ open(credentials[0], "r")
47
+ print(">> Found credentials.")
48
+ except IndexError:
49
+ print(">> No credentials found.")
50
+ sys.exit(0)
51
+
52
+ if not args.yes:
53
+ # input('Make sure the following client id is added to the shared drive as Manager:\n' + json.loads((open(
54
+ # credentials[0],'r').read()))['installed']['client_id'])
55
+ input(
56
+ ">> Make sure the **Google account** that has generated credentials.json\n is added into your Team Drive "
57
+ "(shared drive) as Manager\n>> (Press any key to continue)"
58
+ )
59
+
60
+ creds = None
61
+ if os.path.exists("token_sa.pickle"):
62
+ with open("token_sa.pickle", "rb") as token:
63
+ creds = pickle.load(token)
64
+ # If there are no (valid) credentials available, let the user log in.
65
+ if not creds or not creds.valid:
66
+ if creds and creds.expired and creds.refresh_token:
67
+ creds.refresh(Request())
68
+ else:
69
+ flow = InstalledAppFlow.from_client_secrets_file(
70
+ credentials[0],
71
+ scopes=[
72
+ "https://www.googleapis.com/auth/admin.directory.group",
73
+ "https://www.googleapis.com/auth/admin.directory.group.member",
74
+ ],
75
+ )
76
+ # creds = flow.run_local_server(port=0)
77
+ creds = flow.run_console()
78
+ # Save the credentials for the next run
79
+ with open("token_sa.pickle", "wb") as token:
80
+ pickle.dump(creds, token)
81
+
82
+ drive = googleapiclient.discovery.build("drive", "v3", credentials=creds)
83
+ batch = drive.new_batch_http_request()
84
+
85
+ aa = glob.glob(f"{acc_dir}/*.json")
86
+ pbar = progress.bar.Bar("Readying accounts", max=len(aa))
87
+ for i in aa:
88
+ ce = json.loads(open(i, "r").read())["client_email"]
89
+ batch.add(
90
+ drive.permissions().create(
91
+ fileId=did,
92
+ supportsAllDrives=True,
93
+ body={"role": "organizer", "type": "user", "emailAddress": ce},
94
+ )
95
+ )
96
+ pbar.next()
97
+ pbar.finish()
98
+ print("Adding...")
99
+ batch.execute()
100
+
101
+ print("Complete.")
102
+ hours, rem = divmod((time.time() - stt), 3600)
103
+ minutes, sec = divmod(rem, 60)
104
+ print("Elapsed Time:\n{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), sec))
aria-nox-nzb.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tracker_list=$(curl -Ns https://ngosang.github.io/trackerslist/trackers_all_http.txt | awk '$0' | tr '\n\n' ',')
2
+ aria2c --allow-overwrite=true --auto-file-renaming=true --bt-enable-lpd=true --bt-detach-seed-only=true \
3
+ --bt-remove-unselected-file=true --bt-tracker="[$tracker_list]" --bt-max-peers=0 --enable-rpc=true \
4
+ --rpc-max-request-size=1024M --max-connection-per-server=10 --max-concurrent-downloads=1000 --split=10 \
5
+ --seed-ratio=0 --check-integrity=true --continue=true --daemon=true --disk-cache=40M --force-save=true \
6
+ --min-split-size=10M --follow-torrent=mem --check-certificate=false --optimize-concurrent-downloads=true \
7
+ --http-accept-gzip=true --max-file-not-found=0 --max-tries=20 --peer-id-prefix=-qB4520- --reuse-uri=true \
8
+ --content-disposition-default-utf8=true --user-agent=Wget/1.12 --peer-agent=qBittorrent/4.5.2 --quiet=true \
9
+ --summary-interval=0 --max-upload-limit=1K
10
+ qbittorrent-nox -d --profile="$(pwd)"
11
+ sabnzbdplus -f sabnzbd/SABnzbd.ini -s :::8070 -b 0 -d -c -l 0 --console
bot/__init__.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from uvloop import install
2
+
3
+ install()
4
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
5
+ from asyncio import Lock, new_event_loop, set_event_loop
6
+ from logging import (
7
+ getLogger,
8
+ FileHandler,
9
+ StreamHandler,
10
+ INFO,
11
+ basicConfig,
12
+ WARNING,
13
+ ERROR,
14
+ )
15
+ from sabnzbdapi import SabnzbdClient
16
+ from time import time
17
+ from os import cpu_count
18
+
19
+ getLogger("requests").setLevel(WARNING)
20
+ getLogger("urllib3").setLevel(WARNING)
21
+ getLogger("pyrogram").setLevel(ERROR)
22
+ getLogger("httpx").setLevel(WARNING)
23
+ getLogger("pymongo").setLevel(WARNING)
24
+ getLogger("aiohttp").setLevel(WARNING)
25
+
26
+ bot_start_time = time()
27
+
28
+ bot_loop = new_event_loop()
29
+ set_event_loop(bot_loop)
30
+
31
+ basicConfig(
32
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
33
+ handlers=[FileHandler("log.txt"), StreamHandler()],
34
+ level=INFO,
35
+ )
36
+
37
+ LOGGER = getLogger(__name__)
38
+ cpu_no = cpu_count()
39
+ threads = max(1, cpu_no // 2)
40
+ cores = ",".join(str(i) for i in reversed(range(threads)))
41
+
42
+ DOWNLOAD_DIR = "/app/downloads/"
43
+ intervals = {"status": {}, "qb": "", "jd": "", "nzb": "", "stopAll": False}
44
+ qb_torrents = {}
45
+ jd_downloads = {}
46
+ nzb_jobs = {}
47
+ user_data = {}
48
+ aria2_options = {}
49
+ qbit_options = {}
50
+ nzb_options = {}
51
+ queued_dl = {}
52
+ queued_up = {}
53
+ status_dict = {}
54
+ task_dict = {}
55
+ rss_dict = {}
56
+ auth_chats = {}
57
+ excluded_extensions = ["aria2", "!qB"]
58
+ included_extensions = []
59
+ drives_names = []
60
+ drives_ids = []
61
+ index_urls = []
62
+ sudo_users = []
63
+ non_queued_dl = set()
64
+ non_queued_up = set()
65
+ multi_tags = set()
66
+ task_dict_lock = Lock()
67
+ queue_dict_lock = Lock()
68
+ qb_listener_lock = Lock()
69
+ nzb_listener_lock = Lock()
70
+ jd_listener_lock = Lock()
71
+ cpu_eater_lock = Lock()
72
+ same_directory_lock = Lock()
73
+
74
+ sabnzbd_client = SabnzbdClient(
75
+ host="http://localhost",
76
+ api_key="mltb",
77
+ port="8070",
78
+ )
79
+
80
+ scheduler = AsyncIOScheduler(event_loop=bot_loop)
bot/__main__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import LOGGER, bot_loop
2
+ from .core.telegram_manager import TgClient
3
+ from .core.config_manager import Config
4
+
5
+ Config.load()
6
+
7
+
8
+ async def main():
9
+ from asyncio import gather
10
+ from .core.startup import (
11
+ load_settings,
12
+ load_configurations,
13
+ save_settings,
14
+ update_aria2_options,
15
+ update_nzb_options,
16
+ update_qb_options,
17
+ update_variables,
18
+ )
19
+
20
+ await load_settings()
21
+
22
+ await gather(TgClient.start_bot(), TgClient.start_user())
23
+ await gather(load_configurations(), update_variables())
24
+
25
+ from .core.torrent_manager import TorrentManager
26
+
27
+ await TorrentManager.initiate()
28
+ await gather(
29
+ update_qb_options(),
30
+ update_aria2_options(),
31
+ update_nzb_options(),
32
+ )
33
+ from .helper.ext_utils.files_utils import clean_all
34
+ from .core.jdownloader_booter import jdownloader
35
+ from .helper.ext_utils.telegraph_helper import telegraph
36
+ from .helper.mirror_leech_utils.rclone_utils.serve import rclone_serve_booter
37
+ from .modules import (
38
+ initiate_search_tools,
39
+ get_packages_version,
40
+ restart_notification,
41
+ )
42
+
43
+ await gather(
44
+ save_settings(),
45
+ jdownloader.boot(),
46
+ clean_all(),
47
+ initiate_search_tools(),
48
+ get_packages_version(),
49
+ restart_notification(),
50
+ telegraph.create_account(),
51
+ rclone_serve_booter(),
52
+ )
53
+
54
+
55
+ bot_loop.run_until_complete(main())
56
+
57
+ from .helper.ext_utils.bot_utils import create_help_buttons
58
+ from .helper.listeners.aria2_listener import add_aria2_callbacks
59
+ from .core.handlers import add_handlers
60
+
61
+ add_aria2_callbacks()
62
+ create_help_buttons()
63
+ add_handlers()
64
+
65
+ LOGGER.info("Bot Started!")
66
+ bot_loop.run_forever()
bot/core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/core/config_manager.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from importlib import import_module
2
+ from ast import literal_eval
3
+ from os import getenv
4
+
5
+ from bot import LOGGER
6
+
7
+
8
+ class Config:
9
+ AS_DOCUMENT = False
10
+ AUTHORIZED_CHATS = ""
11
+ BASE_URL = ""
12
+ BASE_URL_PORT = 80
13
+ BOT_TOKEN = ""
14
+ CMD_SUFFIX = ""
15
+ CLONE_DUMP_CHATS = ""
16
+ DATABASE_URL = ""
17
+ DATABASE_NAME = "mltb"
18
+ DEFAULT_UPLOAD = "rc"
19
+ EQUAL_SPLITS = False
20
+ EXCLUDED_EXTENSIONS = ""
21
+ INCLUDED_EXTENSIONS = ""
22
+ FFMPEG_CMDS = {}
23
+ FILELION_API = ""
24
+ FILES_LINKS = False
25
+ GDRIVE_ID = ""
26
+ INCOMPLETE_TASK_NOTIFIER = False
27
+ INDEX_URL = ""
28
+ IS_TEAM_DRIVE = False
29
+ JD_EMAIL = ""
30
+ JD_PASS = ""
31
+ LEECH_DUMP_CHAT = ""
32
+ LEECH_FILENAME_PREFIX = ""
33
+ LEECH_SPLIT_SIZE = 2097152000
34
+ MEDIA_GROUP = False
35
+ HYBRID_LEECH = False
36
+ HYDRA_IP = ""
37
+ HYDRA_API_KEY = ""
38
+ NAME_SUBSTITUTE = r""
39
+ OWNER_ID = 0
40
+ QUEUE_ALL = 0
41
+ QUEUE_DOWNLOAD = 0
42
+ QUEUE_UPLOAD = 0
43
+ RCLONE_FLAGS = ""
44
+ RCLONE_PATH = ""
45
+ RCLONE_SERVE_URL = ""
46
+ RCLONE_SERVE_USER = ""
47
+ RCLONE_SERVE_PASS = ""
48
+ RCLONE_SERVE_PORT = 8080
49
+ RSS_CHAT = ""
50
+ RSS_DELAY = 600
51
+ RSS_SIZE_LIMIT = 0
52
+ SEARCH_API_LINK = ""
53
+ SEARCH_LIMIT = 0
54
+ SEARCH_PLUGINS = []
55
+ STATUS_LIMIT = 4
56
+ STATUS_UPDATE_INTERVAL = 15
57
+ STOP_DUPLICATE = False
58
+ STREAMWISH_API = ""
59
+ SUDO_USERS = ""
60
+ TELEGRAM_API = 0
61
+ TELEGRAM_HASH = ""
62
+ TG_PROXY = {}
63
+ THUMBNAIL_LAYOUT = ""
64
+ TORRENT_TIMEOUT = 0
65
+ UPLOAD_PATHS = {}
66
+ UPSTREAM_REPO = ""
67
+ UPSTREAM_BRANCH = "master"
68
+ USENET_SERVERS = []
69
+ USER_SESSION_STRING = ""
70
+ USER_TRANSMISSION = False
71
+ USE_SERVICE_ACCOUNTS = False
72
+ WEB_PINCODE = False
73
+ YT_DLP_OPTIONS = {}
74
+
75
+ @classmethod
76
+ def _convert(cls, key: str, value):
77
+ if not hasattr(cls, key):
78
+ raise KeyError(f"{key} is not a valid configuration key.")
79
+
80
+ expected_type = type(getattr(cls, key))
81
+
82
+ if value is None:
83
+ return None
84
+
85
+ if isinstance(value, expected_type):
86
+ return value
87
+
88
+ if expected_type is bool:
89
+ return str(value).strip().lower() in {"true", "1", "yes"}
90
+
91
+ if expected_type in [list, dict]:
92
+ if not isinstance(value, str):
93
+ raise TypeError(
94
+ f"{key} should be {expected_type.__name__}, got {type(value).__name__}"
95
+ )
96
+
97
+ if not value:
98
+ return expected_type()
99
+
100
+ try:
101
+ evaluated = literal_eval(value)
102
+ if not isinstance(evaluated, expected_type):
103
+ raise TypeError(
104
+ f"Expected {expected_type.__name__}, got {type(evaluated).__name__}"
105
+ )
106
+ return evaluated
107
+ except (ValueError, SyntaxError, TypeError) as e:
108
+ raise TypeError(
109
+ f"{key} should be {expected_type.__name__}, got invalid string: {value}"
110
+ ) from e
111
+
112
+ try:
113
+ return expected_type(value)
114
+ except (ValueError, TypeError) as exc:
115
+ raise TypeError(
116
+ f"Invalid type for {key}: expected {expected_type}, got {type(value)}"
117
+ ) from exc
118
+
119
+ @classmethod
120
+ def get(cls, key: str):
121
+ return getattr(cls, key, None)
122
+
123
+ @classmethod
124
+ def set(cls, key: str, value) -> None:
125
+ if not hasattr(cls, key):
126
+ raise KeyError(f"{key} is not a valid configuration key.")
127
+
128
+ converted_value = cls._convert(key, value)
129
+ setattr(cls, key, converted_value)
130
+
131
+ @classmethod
132
+ def get_all(cls):
133
+ return {
134
+ key: getattr(cls, key)
135
+ for key in cls.__dict__.keys()
136
+ if not key.startswith("__") and not callable(getattr(cls, key))
137
+ }
138
+
139
+ @classmethod
140
+ def _is_valid_config_attr(cls, attr: str) -> bool:
141
+ if attr.startswith("__") or callable(getattr(cls, attr, None)):
142
+ return False
143
+ return hasattr(cls, attr)
144
+
145
+ @classmethod
146
+ def _process_config_value(cls, attr: str, value):
147
+ if not value:
148
+ return None
149
+
150
+ converted_value = cls._convert(attr, value)
151
+
152
+ if isinstance(converted_value, str):
153
+ converted_value = converted_value.strip()
154
+
155
+ if attr == "DEFAULT_UPLOAD" and converted_value != "gd":
156
+ return "rc"
157
+
158
+ if attr in {
159
+ "BASE_URL",
160
+ "RCLONE_SERVE_URL",
161
+ "SEARCH_API_LINK",
162
+ }:
163
+ return converted_value.strip("/") if converted_value else ""
164
+
165
+ if attr == "USENET_SERVERS" and (
166
+ not converted_value or not converted_value[0].get("host")
167
+ ):
168
+ return None
169
+
170
+ return converted_value
171
+
172
+ @classmethod
173
+ def _load_from_module(cls) -> bool:
174
+ try:
175
+ settings = import_module("config")
176
+ except ModuleNotFoundError:
177
+ return False
178
+
179
+ for attr in dir(settings):
180
+ if not cls._is_valid_config_attr(attr):
181
+ continue
182
+
183
+ raw_value = getattr(settings, attr)
184
+ processed_value = cls._process_config_value(attr, raw_value)
185
+
186
+ if processed_value is not None:
187
+ setattr(cls, attr, processed_value)
188
+
189
+ return True
190
+
191
+ @classmethod
192
+ def _load_from_env(cls) -> None:
193
+ for attr in dir(cls):
194
+ if not cls._is_valid_config_attr(attr):
195
+ continue
196
+
197
+ env_value = getenv(attr)
198
+ if env_value is None:
199
+ continue
200
+
201
+ processed_value = cls._process_config_value(attr, env_value)
202
+ if processed_value is not None:
203
+ setattr(cls, attr, processed_value)
204
+
205
+ @classmethod
206
+ def _validate_required_config(cls) -> None:
207
+ required_keys = ["BOT_TOKEN", "OWNER_ID", "TELEGRAM_API", "TELEGRAM_HASH"]
208
+
209
+ for key in required_keys:
210
+ value = getattr(cls, key)
211
+ if isinstance(value, str):
212
+ value = value.strip()
213
+ if not value:
214
+ raise ValueError(f"{key} variable is missing!")
215
+
216
+ @classmethod
217
+ def load(cls) -> None:
218
+ if not cls._load_from_module():
219
+ LOGGER.info(
220
+ "Config module not found, loading from environment variables..."
221
+ )
222
+ cls._load_from_env()
223
+
224
+ cls._validate_required_config()
225
+
226
+ @classmethod
227
+ def load_dict(cls, config_dict) -> None:
228
+ for key, value in config_dict.items():
229
+ if not hasattr(cls, key):
230
+ continue
231
+
232
+ processed_value = cls._process_config_value(key, value)
233
+
234
+ if key == "USENET_SERVERS" and processed_value is None:
235
+ processed_value = []
236
+
237
+ if processed_value is not None:
238
+ setattr(cls, key, processed_value)
239
+
240
+ cls._validate_required_config()
bot/core/handlers.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram.filters import command, regex
2
+ from pyrogram.handlers import MessageHandler, CallbackQueryHandler, EditedMessageHandler
3
+
4
+ from ..modules import *
5
+ from ..helper.telegram_helper.bot_commands import BotCommands
6
+ from ..helper.telegram_helper.filters import CustomFilters
7
+ from .telegram_manager import TgClient
8
+
9
+
10
+ def add_handlers():
11
+ TgClient.bot.add_handler(
12
+ MessageHandler(
13
+ authorize,
14
+ filters=command(BotCommands.AuthorizeCommand, case_sensitive=True)
15
+ & CustomFilters.sudo,
16
+ )
17
+ )
18
+ TgClient.bot.add_handler(
19
+ MessageHandler(
20
+ unauthorize,
21
+ filters=command(BotCommands.UnAuthorizeCommand, case_sensitive=True)
22
+ & CustomFilters.sudo,
23
+ )
24
+ )
25
+ TgClient.bot.add_handler(
26
+ MessageHandler(
27
+ add_sudo,
28
+ filters=command(BotCommands.AddSudoCommand, case_sensitive=True)
29
+ & CustomFilters.owner,
30
+ )
31
+ )
32
+ TgClient.bot.add_handler(
33
+ MessageHandler(
34
+ remove_sudo,
35
+ filters=command(BotCommands.RmSudoCommand, case_sensitive=True)
36
+ & CustomFilters.owner,
37
+ )
38
+ )
39
+ TgClient.bot.add_handler(
40
+ MessageHandler(
41
+ send_bot_settings,
42
+ filters=command(BotCommands.BotSetCommand, case_sensitive=True)
43
+ & CustomFilters.sudo,
44
+ )
45
+ )
46
+ TgClient.bot.add_handler(
47
+ CallbackQueryHandler(
48
+ edit_bot_settings, filters=regex("^botset") & CustomFilters.sudo
49
+ )
50
+ )
51
+ TgClient.bot.add_handler(
52
+ MessageHandler(
53
+ cancel,
54
+ filters=command(BotCommands.CancelTaskCommand, case_sensitive=True)
55
+ & CustomFilters.authorized,
56
+ )
57
+ )
58
+ TgClient.bot.add_handler(
59
+ MessageHandler(
60
+ cancel_all_buttons,
61
+ filters=command(BotCommands.CancelAllCommand, case_sensitive=True)
62
+ & CustomFilters.authorized,
63
+ )
64
+ )
65
+ TgClient.bot.add_handler(
66
+ CallbackQueryHandler(cancel_all_update, filters=regex("^canall"))
67
+ )
68
+ TgClient.bot.add_handler(
69
+ CallbackQueryHandler(cancel_multi, filters=regex("^stopm"))
70
+ )
71
+ TgClient.bot.add_handler(
72
+ MessageHandler(
73
+ clone_node,
74
+ filters=command(BotCommands.CloneCommand, case_sensitive=True)
75
+ & CustomFilters.authorized,
76
+ )
77
+ )
78
+ TgClient.bot.add_handler(
79
+ MessageHandler(
80
+ aioexecute,
81
+ filters=command(BotCommands.AExecCommand, case_sensitive=True)
82
+ & CustomFilters.owner,
83
+ )
84
+ )
85
+ TgClient.bot.add_handler(
86
+ MessageHandler(
87
+ execute,
88
+ filters=command(BotCommands.ExecCommand, case_sensitive=True)
89
+ & CustomFilters.owner,
90
+ )
91
+ )
92
+ TgClient.bot.add_handler(
93
+ MessageHandler(
94
+ clear,
95
+ filters=command(BotCommands.ClearLocalsCommand, case_sensitive=True)
96
+ & CustomFilters.owner,
97
+ )
98
+ )
99
+ TgClient.bot.add_handler(
100
+ MessageHandler(
101
+ select,
102
+ filters=command(BotCommands.SelectCommand, case_sensitive=True)
103
+ & CustomFilters.authorized,
104
+ )
105
+ )
106
+ TgClient.bot.add_handler(
107
+ CallbackQueryHandler(confirm_selection, filters=regex("^sel"))
108
+ )
109
+ TgClient.bot.add_handler(
110
+ MessageHandler(
111
+ remove_from_queue,
112
+ filters=command(BotCommands.ForceStartCommand, case_sensitive=True)
113
+ & CustomFilters.authorized,
114
+ )
115
+ )
116
+ TgClient.bot.add_handler(
117
+ MessageHandler(
118
+ count_node,
119
+ filters=command(BotCommands.CountCommand, case_sensitive=True)
120
+ & CustomFilters.authorized,
121
+ )
122
+ )
123
+ TgClient.bot.add_handler(
124
+ MessageHandler(
125
+ delete_file,
126
+ filters=command(BotCommands.DeleteCommand, case_sensitive=True)
127
+ & CustomFilters.authorized,
128
+ )
129
+ )
130
+ TgClient.bot.add_handler(
131
+ MessageHandler(
132
+ gdrive_search,
133
+ filters=command(BotCommands.ListCommand, case_sensitive=True)
134
+ & CustomFilters.authorized,
135
+ )
136
+ )
137
+ TgClient.bot.add_handler(
138
+ CallbackQueryHandler(select_type, filters=regex("^list_types"))
139
+ )
140
+ TgClient.bot.add_handler(CallbackQueryHandler(arg_usage, filters=regex("^help")))
141
+ TgClient.bot.add_handler(
142
+ MessageHandler(
143
+ mirror,
144
+ filters=command(BotCommands.MirrorCommand, case_sensitive=True)
145
+ & CustomFilters.authorized,
146
+ )
147
+ )
148
+ TgClient.bot.add_handler(
149
+ MessageHandler(
150
+ qb_mirror,
151
+ filters=command(BotCommands.QbMirrorCommand, case_sensitive=True)
152
+ & CustomFilters.authorized,
153
+ )
154
+ )
155
+ TgClient.bot.add_handler(
156
+ MessageHandler(
157
+ jd_mirror,
158
+ filters=command(BotCommands.JdMirrorCommand, case_sensitive=True)
159
+ & CustomFilters.authorized,
160
+ )
161
+ )
162
+ TgClient.bot.add_handler(
163
+ MessageHandler(
164
+ nzb_mirror,
165
+ filters=command(BotCommands.NzbMirrorCommand, case_sensitive=True)
166
+ & CustomFilters.authorized,
167
+ )
168
+ )
169
+ TgClient.bot.add_handler(
170
+ MessageHandler(
171
+ leech,
172
+ filters=command(BotCommands.LeechCommand, case_sensitive=True)
173
+ & CustomFilters.authorized,
174
+ )
175
+ )
176
+ TgClient.bot.add_handler(
177
+ MessageHandler(
178
+ qb_leech,
179
+ filters=command(BotCommands.QbLeechCommand, case_sensitive=True)
180
+ & CustomFilters.authorized,
181
+ )
182
+ )
183
+ TgClient.bot.add_handler(
184
+ MessageHandler(
185
+ jd_leech,
186
+ filters=command(BotCommands.JdLeechCommand, case_sensitive=True)
187
+ & CustomFilters.authorized,
188
+ )
189
+ )
190
+ TgClient.bot.add_handler(
191
+ MessageHandler(
192
+ nzb_leech,
193
+ filters=command(BotCommands.NzbLeechCommand, case_sensitive=True)
194
+ & CustomFilters.authorized,
195
+ )
196
+ )
197
+ TgClient.bot.add_handler(
198
+ MessageHandler(
199
+ get_rss_menu,
200
+ filters=command(BotCommands.RssCommand, case_sensitive=True)
201
+ & CustomFilters.authorized,
202
+ )
203
+ )
204
+ TgClient.bot.add_handler(CallbackQueryHandler(rss_listener, filters=regex("^rss")))
205
+ TgClient.bot.add_handler(
206
+ MessageHandler(
207
+ run_shell,
208
+ filters=command(BotCommands.ShellCommand, case_sensitive=True)
209
+ & CustomFilters.owner,
210
+ )
211
+ )
212
+ TgClient.bot.add_handler(
213
+ EditedMessageHandler(
214
+ run_shell,
215
+ filters=command(BotCommands.ShellCommand, case_sensitive=True)
216
+ & CustomFilters.owner,
217
+ )
218
+ )
219
+ TgClient.bot.add_handler(
220
+ MessageHandler(
221
+ start, filters=command(BotCommands.StartCommand, case_sensitive=True)
222
+ )
223
+ )
224
+ TgClient.bot.add_handler(
225
+ MessageHandler(
226
+ log,
227
+ filters=command(BotCommands.LogCommand, case_sensitive=True)
228
+ & CustomFilters.sudo,
229
+ )
230
+ )
231
+ TgClient.bot.add_handler(
232
+ MessageHandler(
233
+ restart_bot,
234
+ filters=command(BotCommands.RestartCommand, case_sensitive=True)
235
+ & CustomFilters.sudo,
236
+ )
237
+ )
238
+ TgClient.bot.add_handler(
239
+ CallbackQueryHandler(
240
+ confirm_restart, filters=regex("^botrestart") & CustomFilters.sudo
241
+ )
242
+ )
243
+ TgClient.bot.add_handler(
244
+ MessageHandler(
245
+ ping,
246
+ filters=command(BotCommands.PingCommand, case_sensitive=True)
247
+ & CustomFilters.authorized,
248
+ )
249
+ )
250
+ TgClient.bot.add_handler(
251
+ MessageHandler(
252
+ bot_help,
253
+ filters=command(BotCommands.HelpCommand, case_sensitive=True)
254
+ & CustomFilters.authorized,
255
+ )
256
+ )
257
+ TgClient.bot.add_handler(
258
+ MessageHandler(
259
+ bot_stats,
260
+ filters=command(BotCommands.StatsCommand, case_sensitive=True)
261
+ & CustomFilters.authorized,
262
+ )
263
+ )
264
+ TgClient.bot.add_handler(
265
+ MessageHandler(
266
+ task_status,
267
+ filters=command(BotCommands.StatusCommand, case_sensitive=True)
268
+ & CustomFilters.authorized,
269
+ )
270
+ )
271
+ TgClient.bot.add_handler(
272
+ CallbackQueryHandler(status_pages, filters=regex("^status"))
273
+ )
274
+ TgClient.bot.add_handler(
275
+ MessageHandler(
276
+ torrent_search,
277
+ filters=command(BotCommands.SearchCommand, case_sensitive=True)
278
+ & CustomFilters.authorized,
279
+ )
280
+ )
281
+ TgClient.bot.add_handler(
282
+ CallbackQueryHandler(torrent_search_update, filters=regex("^torser"))
283
+ )
284
+ TgClient.bot.add_handler(
285
+ MessageHandler(
286
+ get_users_settings,
287
+ filters=command(BotCommands.UsersCommand, case_sensitive=True)
288
+ & CustomFilters.sudo,
289
+ )
290
+ )
291
+ TgClient.bot.add_handler(
292
+ MessageHandler(
293
+ send_user_settings,
294
+ filters=command(BotCommands.UserSetCommand, case_sensitive=True)
295
+ & CustomFilters.authorized,
296
+ )
297
+ )
298
+ TgClient.bot.add_handler(
299
+ CallbackQueryHandler(edit_user_settings, filters=regex("^userset"))
300
+ )
301
+ TgClient.bot.add_handler(
302
+ MessageHandler(
303
+ ytdl,
304
+ filters=command(BotCommands.YtdlCommand, case_sensitive=True)
305
+ & CustomFilters.authorized,
306
+ )
307
+ )
308
+ TgClient.bot.add_handler(
309
+ MessageHandler(
310
+ ytdl_leech,
311
+ filters=command(BotCommands.YtdlLeechCommand, case_sensitive=True)
312
+ & CustomFilters.authorized,
313
+ )
314
+ )
315
+ TgClient.bot.add_handler(
316
+ MessageHandler(
317
+ hydra_search,
318
+ filters=command(BotCommands.NzbSearchCommand, case_sensitive=True)
319
+ & CustomFilters.authorized,
320
+ )
321
+ )
bot/core/jdownloader_booter.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import path, makedirs, listdir, rename
2
+ from aioshutil import rmtree
3
+ from json import dump
4
+ from random import randint
5
+ from re import match
6
+
7
+ from .. import LOGGER
8
+ from ..helper.ext_utils.bot_utils import cmd_exec, new_task
9
+ from .telegram_manager import TgClient
10
+ from .config_manager import Config
11
+ from myjd import MyJdApi
12
+
13
+
14
+ class JDownloader(MyJdApi):
15
+ def __init__(self):
16
+ super().__init__()
17
+ self._username = ""
18
+ self._password = ""
19
+ self._device_name = ""
20
+ self.is_connected = False
21
+ self.error = "JDownloader Credentials not provided!"
22
+
23
+ @new_task
24
+ async def boot(self):
25
+ await cmd_exec(["pkill", "-9", "-f", "java"])
26
+ if not Config.JD_EMAIL or not Config.JD_PASS:
27
+ self.is_connected = False
28
+ self.error = "JDownloader Credentials not provided!"
29
+ return
30
+ self.error = "Connecting... Try again after couple of seconds"
31
+ self._device_name = f"{randint(0, 1000)}@{TgClient.NAME}"
32
+ if await path.exists("/JDownloader/logs"):
33
+ LOGGER.info(
34
+ "Starting JDownloader... This might take up to 10 sec and might restart once if update available!"
35
+ )
36
+ else:
37
+ LOGGER.info(
38
+ "Starting JDownloader... This might take up to 8 sec and might restart once after build!"
39
+ )
40
+ jdata = {
41
+ "autoconnectenabledv2": True,
42
+ "password": Config.JD_PASS,
43
+ "devicename": f"{self._device_name}",
44
+ "email": Config.JD_EMAIL,
45
+ }
46
+ remote_data = {
47
+ "localapiserverheaderaccesscontrollalloworigin": "",
48
+ "deprecatedapiport": 3128,
49
+ "localapiserverheaderxcontenttypeoptions": "nosniff",
50
+ "localapiserverheaderxframeoptions": "DENY",
51
+ "externinterfaceenabled": True,
52
+ "deprecatedapilocalhostonly": True,
53
+ "localapiserverheaderreferrerpolicy": "no-referrer",
54
+ "deprecatedapienabled": True,
55
+ "localapiserverheadercontentsecuritypolicy": "default-src 'self'",
56
+ "jdanywhereapienabled": True,
57
+ "externinterfacelocalhostonly": False,
58
+ "localapiserverheaderxxssprotection": "1; mode=block",
59
+ }
60
+ await makedirs("/JDownloader/cfg", exist_ok=True)
61
+ with open(
62
+ "/JDownloader/cfg/org.jdownloader.api.myjdownloader.MyJDownloaderSettings.json",
63
+ "w",
64
+ ) as sf:
65
+ sf.truncate(0)
66
+ dump(jdata, sf)
67
+ with open(
68
+ "/JDownloader/cfg/org.jdownloader.api.RemoteAPIConfig.json",
69
+ "w",
70
+ ) as rf:
71
+ rf.truncate(0)
72
+ dump(remote_data, rf)
73
+ if not await path.exists("/JDownloader/JDownloader.jar"):
74
+ pattern = r"JDownloader\.jar\.backup.\d$"
75
+ for filename in await listdir("/JDownloader"):
76
+ if match(pattern, filename):
77
+ await rename(
78
+ f"/JDownloader/{filename}", "/JDownloader/JDownloader.jar"
79
+ )
80
+ break
81
+ await rmtree("/JDownloader/update")
82
+ await rmtree("/JDownloader/tmp")
83
+ cmd = "java -Dsun.jnu.encoding=UTF-8 -Dfile.encoding=UTF-8 -Djava.awt.headless=true -jar /JDownloader/JDownloader.jar"
84
+ self.is_connected = True
85
+ _, __, code = await cmd_exec(cmd, shell=True)
86
+ self.is_connected = False
87
+ if code != -9:
88
+ await self.boot()
89
+
90
+
91
+ jdownloader = JDownloader()
bot/core/startup.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
71
+ for p in ["thumbnails", "tokens", "rclone"]:
72
+ if await aiopath.exists(p):
73
+ await rmtree(p, ignore_errors=True)
74
+
75
+ await database.connect()
76
+ if database.db is None:
77
+ return
78
+
79
+ BOT_ID = Config.BOT_TOKEN.split(":", 1)[0]
80
+
81
+ try:
82
+ settings = import_module("config")
83
+ config_file = {
84
+ key: value.strip() if isinstance(value, str) else value
85
+ for key, value in vars(settings).items()
86
+ if not key.startswith("__")
87
+ }
88
+ except ModuleNotFoundError:
89
+ config_file = {}
90
+
91
+ old_config = await database.db.settings.deployConfig.find_one(
92
+ {"_id": BOT_ID}, {"_id": 0}
93
+ )
94
+ if old_config is None and config_file:
95
+ await database.db.settings.deployConfig.replace_one(
96
+ {"_id": BOT_ID}, config_file, upsert=True
97
+ )
98
+ elif old_config and config_file and old_config != config_file:
99
+ LOGGER.info("Replacing existing deploy config in Database")
100
+ await database.db.settings.deployConfig.replace_one(
101
+ {"_id": BOT_ID}, config_file, upsert=True
102
+ )
103
+ else:
104
+ config_dict = await database.db.settings.config.find_one(
105
+ {"_id": BOT_ID}, {"_id": 0}
106
+ )
107
+ if config_dict:
108
+ Config.load_dict(config_dict)
109
+
110
+ if pf_dict := await database.db.settings.files.find_one(
111
+ {"_id": BOT_ID}, {"_id": 0}
112
+ ):
113
+ for key, value in pf_dict.items():
114
+ if value:
115
+ file_ = key.replace("__", ".")
116
+ async with aiopen(file_, "wb+") as f:
117
+ await f.write(value)
118
+
119
+ if a2c_options := await database.db.settings.aria2c.find_one(
120
+ {"_id": BOT_ID}, {"_id": 0}
121
+ ):
122
+ aria2_options.update(a2c_options)
123
+
124
+ if qbit_opt := await database.db.settings.qbittorrent.find_one(
125
+ {"_id": BOT_ID}, {"_id": 0}
126
+ ):
127
+ qbit_options.update(qbit_opt)
128
+
129
+ if nzb_opt := await database.db.settings.nzb.find_one({"_id": BOT_ID}, {"_id": 0}):
130
+ if await aiopath.exists("sabnzbd/SABnzbd.ini.bak"):
131
+ await remove("sabnzbd/SABnzbd.ini.bak")
132
+ ((key, value),) = nzb_opt.items()
133
+ file_ = key.replace("__", ".")
134
+ async with aiopen(f"sabnzbd/{file_}", "wb+") as f:
135
+ await f.write(value)
136
+
137
+ if await database.db.users.find_one():
138
+ for p in ["thumbnails", "tokens", "rclone"]:
139
+ if not await aiopath.exists(p):
140
+ await makedirs(p)
141
+ rows = database.db.users.find({})
142
+ async for row in rows:
143
+ uid = row["_id"]
144
+ del row["_id"]
145
+ thumb_path = f"thumbnails/{uid}.jpg"
146
+ rclone_config_path = f"rclone/{uid}.conf"
147
+ token_path = f"tokens/{uid}.pickle"
148
+ if row.get("THUMBNAIL"):
149
+ async with aiopen(thumb_path, "wb+") as f:
150
+ await f.write(row["THUMBNAIL"])
151
+ row["THUMBNAIL"] = thumb_path
152
+ if row.get("RCLONE_CONFIG"):
153
+ async with aiopen(rclone_config_path, "wb+") as f:
154
+ await f.write(row["RCLONE_CONFIG"])
155
+ row["RCLONE_CONFIG"] = rclone_config_path
156
+ if row.get("TOKEN_PICKLE"):
157
+ async with aiopen(token_path, "wb+") as f:
158
+ await f.write(row["TOKEN_PICKLE"])
159
+ row["TOKEN_PICKLE"] = token_path
160
+ user_data[uid] = row
161
+ LOGGER.info("Users data has been imported from Database")
162
+
163
+ if await database.db.rss[BOT_ID].find_one():
164
+ rows = database.db.rss[BOT_ID].find({})
165
+ async for row in rows:
166
+ user_id = row["_id"]
167
+ del row["_id"]
168
+ rss_dict[user_id] = row
169
+ LOGGER.info("Rss data has been imported from Database.")
170
+
171
+
172
+ async def save_settings():
173
+ if database.db is None:
174
+ return
175
+ config_dict = Config.get_all()
176
+ await database.db.settings.config.replace_one(
177
+ {"_id": TgClient.ID}, config_dict, upsert=True
178
+ )
179
+ if await database.db.settings.aria2c.find_one({"_id": TgClient.ID}) is None:
180
+ await database.db.settings.aria2c.update_one(
181
+ {"_id": TgClient.ID}, {"$set": aria2_options}, upsert=True
182
+ )
183
+ if await database.db.settings.qbittorrent.find_one({"_id": TgClient.ID}) is None:
184
+ await database.save_qbit_settings()
185
+ if await database.db.settings.nzb.find_one({"_id": TgClient.ID}) is None:
186
+ async with aiopen("sabnzbd/SABnzbd.ini", "rb+") as pf:
187
+ nzb_conf = await pf.read()
188
+ await database.db.settings.nzb.update_one(
189
+ {"_id": TgClient.ID}, {"$set": {"SABnzbd__ini": nzb_conf}}, upsert=True
190
+ )
191
+
192
+
193
+ async def update_variables():
194
+ if (
195
+ Config.LEECH_SPLIT_SIZE > TgClient.MAX_SPLIT_SIZE
196
+ or Config.LEECH_SPLIT_SIZE == 2097152000
197
+ or not Config.LEECH_SPLIT_SIZE
198
+ ):
199
+ Config.LEECH_SPLIT_SIZE = TgClient.MAX_SPLIT_SIZE
200
+
201
+ Config.HYBRID_LEECH = bool(Config.HYBRID_LEECH and TgClient.IS_PREMIUM_USER)
202
+ Config.USER_TRANSMISSION = bool(
203
+ Config.USER_TRANSMISSION and TgClient.IS_PREMIUM_USER
204
+ )
205
+
206
+ if Config.AUTHORIZED_CHATS:
207
+ aid = Config.AUTHORIZED_CHATS.split()
208
+ for id_ in aid:
209
+ chat_id, *thread_ids = id_.split("|")
210
+ chat_id = int(chat_id.strip())
211
+ if thread_ids:
212
+ thread_ids = list(map(lambda x: int(x.strip()), thread_ids))
213
+ auth_chats[chat_id] = thread_ids
214
+ else:
215
+ auth_chats[chat_id] = []
216
+
217
+ if Config.SUDO_USERS:
218
+ aid = Config.SUDO_USERS.split()
219
+ for id_ in aid:
220
+ sudo_users.append(int(id_.strip()))
221
+
222
+ if Config.EXCLUDED_EXTENSIONS:
223
+ fx = Config.EXCLUDED_EXTENSIONS.split()
224
+ for x in fx:
225
+ x = x.lstrip(".")
226
+ excluded_extensions.append(x.strip().lower())
227
+
228
+ if Config.INCLUDED_EXTENSIONS:
229
+ fx = Config.INCLUDED_EXTENSIONS.split()
230
+ for x in fx:
231
+ x = x.lstrip(".")
232
+ included_extensions.append(x.strip().lower())
233
+
234
+ if Config.GDRIVE_ID:
235
+ drives_names.append("Main")
236
+ drives_ids.append(Config.GDRIVE_ID)
237
+ index_urls.append(Config.INDEX_URL)
238
+
239
+ if await aiopath.exists("list_drives.txt"):
240
+ async with aiopen("list_drives.txt", "r+") as f:
241
+ lines = await f.readlines()
242
+ for line in lines:
243
+ temp = line.split()
244
+ drives_ids.append(temp[1])
245
+ drives_names.append(temp[0].replace("_", " "))
246
+ if len(temp) > 2:
247
+ index_urls.append(temp[2])
248
+ else:
249
+ index_urls.append("")
250
+
251
+
252
+ async def load_configurations():
253
+
254
+ if not await aiopath.exists(".netrc"):
255
+ async with aiopen(".netrc", "w"):
256
+ pass
257
+
258
+ await (
259
+ await create_subprocess_shell(
260
+ "chmod 600 .netrc && cp .netrc /root/.netrc && chmod +x aria-nox-nzb.sh && ./aria-nox-nzb.sh"
261
+ )
262
+ ).wait()
263
+
264
+ if Config.BASE_URL:
265
+ await create_subprocess_shell(
266
+ f"gunicorn -k uvicorn.workers.UvicornWorker -w 1 web.wserver:app --bind 0.0.0.0:{Config.BASE_URL_PORT}"
267
+ )
268
+
269
+ if await aiopath.exists("cfg.zip"):
270
+ if await aiopath.exists("/JDownloader/cfg"):
271
+ await rmtree("/JDownloader/cfg", ignore_errors=True)
272
+ await (
273
+ await create_subprocess_exec("7z", "x", "cfg.zip", "-o/JDownloader")
274
+ ).wait()
275
+
276
+ if await aiopath.exists("accounts.zip"):
277
+ if await aiopath.exists("accounts"):
278
+ await rmtree("accounts")
279
+ await (
280
+ await create_subprocess_exec(
281
+ "7z", "x", "-o.", "-aoa", "accounts.zip", "accounts/*.json"
282
+ )
283
+ ).wait()
284
+ await (await create_subprocess_exec("chmod", "-R", "777", "accounts")).wait()
285
+ await remove("accounts.zip")
286
+
287
+ if not await aiopath.exists("accounts"):
288
+ Config.USE_SERVICE_ACCOUNTS = False
bot/core/telegram_manager.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import Client, enums
2
+ from pyrogram.types import LinkPreviewOptions
3
+ from asyncio import Lock
4
+
5
+ from .. import LOGGER
6
+ from .config_manager import Config
7
+
8
+
9
+ class TgClient:
10
+ _lock = Lock()
11
+ bot = None
12
+ user = None
13
+ NAME = ""
14
+ ID = 0
15
+ IS_PREMIUM_USER = False
16
+ MAX_SPLIT_SIZE = 2097152000
17
+
18
+ @classmethod
19
+ async def start_bot(cls):
20
+ LOGGER.info("Creating client from BOT_TOKEN")
21
+ cls.ID = Config.BOT_TOKEN.split(":", 1)[0]
22
+ cls.bot = Client(
23
+ cls.ID,
24
+ Config.TELEGRAM_API,
25
+ Config.TELEGRAM_HASH,
26
+ proxy=Config.TG_PROXY,
27
+ bot_token=Config.BOT_TOKEN,
28
+ workdir="/app",
29
+ parse_mode=enums.ParseMode.HTML,
30
+ max_concurrent_transmissions=10,
31
+ max_message_cache_size=15000,
32
+ max_topic_cache_size=15000,
33
+ sleep_threshold=0,
34
+ link_preview_options=LinkPreviewOptions(is_disabled=True),
35
+ )
36
+ await cls.bot.start()
37
+ cls.NAME = cls.bot.me.username
38
+
39
+ @classmethod
40
+ async def start_user(cls):
41
+ if Config.USER_SESSION_STRING:
42
+ LOGGER.info("Creating client from USER_SESSION_STRING")
43
+ try:
44
+ cls.user = Client(
45
+ "user",
46
+ Config.TELEGRAM_API,
47
+ Config.TELEGRAM_HASH,
48
+ proxy=Config.TG_PROXY,
49
+ session_string=Config.USER_SESSION_STRING,
50
+ workdir="/app",
51
+ parse_mode=enums.ParseMode.HTML,
52
+ sleep_threshold=60,
53
+ max_concurrent_transmissions=10,
54
+ max_message_cache_size=15000,
55
+ max_topic_cache_size=15000,
56
+ link_preview_options=LinkPreviewOptions(is_disabled=True),
57
+ )
58
+ await cls.user.start()
59
+ cls.IS_PREMIUM_USER = cls.user.me.is_premium
60
+ if cls.IS_PREMIUM_USER:
61
+ cls.MAX_SPLIT_SIZE = 4194304000
62
+ except Exception as e:
63
+ LOGGER.error(f"Failed to start client from USER_SESSION_STRING. {e}")
64
+ cls.IS_PREMIUM_USER = False
65
+ cls.user = None
66
+
67
+ @classmethod
68
+ async def stop(cls):
69
+ async with cls._lock:
70
+ if cls.bot:
71
+ await cls.bot.stop()
72
+ if cls.user:
73
+ await cls.user.stop()
74
+ LOGGER.info("Client(s) stopped")
75
+
76
+ @classmethod
77
+ async def reload(cls):
78
+ async with cls._lock:
79
+ await cls.bot.restart()
80
+ if cls.user:
81
+ await cls.user.restart()
82
+ LOGGER.info("Client(s) restarted")
bot/core/torrent_manager.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aioaria2 import Aria2WebsocketClient
2
+ from aioqbt.client import create_client
3
+ from asyncio import gather, TimeoutError
4
+ from aiohttp import ClientError
5
+ from pathlib import Path
6
+ from inspect import iscoroutinefunction
7
+ from tenacity import (
8
+ retry,
9
+ stop_after_attempt,
10
+ wait_exponential,
11
+ retry_if_exception_type,
12
+ )
13
+
14
+ from .. import LOGGER, aria2_options
15
+
16
+
17
+ def wrap_with_retry(obj, max_retries=3):
18
+ for attr_name in dir(obj):
19
+ if attr_name.startswith("_"):
20
+ continue
21
+
22
+ attr = getattr(obj, attr_name)
23
+ if iscoroutinefunction(attr):
24
+ retry_policy = retry(
25
+ stop=stop_after_attempt(max_retries),
26
+ wait=wait_exponential(multiplier=1, min=1, max=5),
27
+ retry=retry_if_exception_type(
28
+ (ClientError, TimeoutError, RuntimeError)
29
+ ),
30
+ )
31
+ wrapped = retry_policy(attr)
32
+ setattr(obj, attr_name, wrapped)
33
+ return obj
34
+
35
+
36
+ class TorrentManager:
37
+ aria2 = None
38
+ qbittorrent = None
39
+
40
+ @classmethod
41
+ async def initiate(cls):
42
+ cls.aria2, cls.qbittorrent = await gather(
43
+ Aria2WebsocketClient.new("http://localhost:6800/jsonrpc"),
44
+ create_client("http://localhost:8090/api/v2/"),
45
+ )
46
+ cls.qbittorrent = wrap_with_retry(cls.qbittorrent)
47
+
48
+ @classmethod
49
+ async def close_all(cls):
50
+ await gather(cls.aria2.close(), cls.qbittorrent.close())
51
+
52
+ @classmethod
53
+ async def aria2_remove(cls, download):
54
+ if download.get("status", "") in ["active", "paused", "waiting"]:
55
+ await cls.aria2.forceRemove(download.get("gid", ""))
56
+ else:
57
+ try:
58
+ await cls.aria2.removeDownloadResult(download.get("gid", ""))
59
+ except:
60
+ pass
61
+
62
+ @classmethod
63
+ async def remove_all(cls):
64
+ await cls.pause_all()
65
+ await gather(
66
+ cls.qbittorrent.torrents.delete("all", False),
67
+ cls.aria2.purgeDownloadResult(),
68
+ )
69
+ downloads = []
70
+ results = await gather(cls.aria2.tellActive(), cls.aria2.tellWaiting(0, 1000))
71
+ for res in results:
72
+ downloads.extend(res)
73
+ tasks = []
74
+ tasks.extend(
75
+ cls.aria2.forceRemove(download.get("gid")) for download in downloads
76
+ )
77
+ try:
78
+ await gather(*tasks)
79
+ except:
80
+ pass
81
+
82
+ @classmethod
83
+ async def overall_speed(cls):
84
+ s1, s2 = await gather(
85
+ cls.qbittorrent.transfer.info(), cls.aria2.getGlobalStat()
86
+ )
87
+ download_speed = s1.dl_info_speed + int(s2.get("downloadSpeed", "0"))
88
+ upload_speed = s1.up_info_speed + int(s2.get("uploadSpeed", "0"))
89
+ return download_speed, upload_speed
90
+
91
+ @classmethod
92
+ async def pause_all(cls):
93
+ await gather(cls.aria2.forcePauseAll(), cls.qbittorrent.torrents.stop("all"))
94
+
95
+ @classmethod
96
+ async def change_aria2_option(cls, key, value):
97
+ downloads = []
98
+ results = await gather(cls.aria2.tellActive(), cls.aria2.tellWaiting(0, 1000))
99
+ for res in results:
100
+ downloads.extend(res)
101
+ tasks = []
102
+ for download in downloads:
103
+ if download.get("status", "") != "complete":
104
+ tasks.append(cls.aria2.changeOption(download.get("gid"), {key: value}))
105
+ if tasks:
106
+ try:
107
+ await gather(*tasks)
108
+ except Exception as e:
109
+ LOGGER.error(e)
110
+ if key not in ["checksum", "index-out", "out", "pause", "select-file"]:
111
+ await cls.aria2.changeGlobalOption({key: value})
112
+ aria2_options[key] = value
113
+
114
+
115
+ def aria2_name(download_info):
116
+ if "bittorrent" in download_info and download_info["bittorrent"].get("info"):
117
+ return download_info["bittorrent"]["info"]["name"]
118
+ elif download_info.get("files"):
119
+ if download_info["files"][0]["path"].startswith("[METADATA]"):
120
+ return download_info["files"][0]["path"]
121
+ file_path = download_info["files"][0]["path"]
122
+ dir_path = download_info["dir"]
123
+ if file_path.startswith(dir_path):
124
+ return Path(file_path[len(dir_path) + 1 :]).parts[0]
125
+ else:
126
+ return ""
127
+ else:
128
+ return ""
129
+
130
+
131
+ def is_metadata(download_info):
132
+ return any(
133
+ f["path"].startswith("[METADATA]") for f in download_info.get("files", [])
134
+ )
bot/helper/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/common.py ADDED
@@ -0,0 +1,1217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import path as aiopath, remove, makedirs, listdir
2
+ from aiofiles import open as aiopen
3
+ from asyncio import sleep, gather
4
+ from os import walk, path as ospath
5
+ from secrets import token_urlsafe
6
+ from aioshutil import move, rmtree
7
+ from pyrogram.enums import ChatAction
8
+ from re import sub, I, findall
9
+ from shlex import split
10
+ from collections import Counter
11
+ from copy import deepcopy
12
+ from natsort import natsorted
13
+
14
+ from .. import (
15
+ user_data,
16
+ multi_tags,
17
+ LOGGER,
18
+ task_dict_lock,
19
+ task_dict,
20
+ excluded_extensions,
21
+ included_extensions,
22
+ cpu_eater_lock,
23
+ intervals,
24
+ DOWNLOAD_DIR,
25
+ cores,
26
+ )
27
+ from ..core.config_manager import Config
28
+ from ..core.telegram_manager import TgClient
29
+ from .ext_utils.bot_utils import new_task, sync_to_async, get_size_bytes
30
+ from .ext_utils.bulk_links import extract_bulk_links
31
+ from .mirror_leech_utils.gdrive_utils.list import GoogleDriveList
32
+ from .mirror_leech_utils.rclone_utils.list import RcloneList
33
+ from .mirror_leech_utils.status_utils.sevenz_status import SevenZStatus
34
+ from .mirror_leech_utils.status_utils.ffmpeg_status import FFmpegStatus
35
+ from .telegram_helper.bot_commands import BotCommands
36
+ from .ext_utils.files_utils import (
37
+ get_base_name,
38
+ is_first_archive_split,
39
+ is_archive,
40
+ is_archive_split,
41
+ get_path_size,
42
+ split_file,
43
+ SevenZ,
44
+ )
45
+ from .ext_utils.links_utils import (
46
+ is_gdrive_id,
47
+ is_rclone_path,
48
+ is_gdrive_link,
49
+ is_telegram_link,
50
+ )
51
+ from .ext_utils.media_utils import (
52
+ create_thumb,
53
+ take_ss,
54
+ get_document_type,
55
+ FFMpeg,
56
+ ffconcat_escape,
57
+ )
58
+ from .telegram_helper.message_utils import (
59
+ send_message,
60
+ send_status_message,
61
+ get_tg_link_message,
62
+ temp_download,
63
+ )
64
+
65
+
66
+ class TaskConfig:
67
+ def __init__(self):
68
+ self.mid = self.message.id
69
+ self.user = self.message.from_user or self.message.sender_chat
70
+ self.user_id = self.user.id
71
+ self.user_dict = user_data.get(self.user_id, {})
72
+ self.clone_dump_chats = {}
73
+ self.dir = f"{DOWNLOAD_DIR}{self.mid}"
74
+ self.up_dir = ""
75
+ self.link = ""
76
+ self.up_dest = ""
77
+ self.rc_flags = ""
78
+ self.tag = ""
79
+ self.name = ""
80
+ self.subname = ""
81
+ self.name_sub = ""
82
+ self.thumbnail_layout = ""
83
+ self.folder_name = ""
84
+ self.split_size = 0
85
+ self.max_split_size = 0
86
+ self.multi = 0
87
+ self.size = 0
88
+ self.subsize = 0
89
+ self.proceed_count = 0
90
+ self.is_leech = False
91
+ self.is_qbit = False
92
+ self.is_nzb = False
93
+ self.is_jd = False
94
+ self.is_clone = False
95
+ self.is_ytdlp = False
96
+ self.equal_splits = False
97
+ self.user_transmission = False
98
+ self.hybrid_leech = False
99
+ self.extract = False
100
+ self.compress = False
101
+ self.select = False
102
+ self.seed = False
103
+ self.compress = False
104
+ self.extract = False
105
+ self.join = False
106
+ self.private_link = False
107
+ self.stop_duplicate = False
108
+ self.sample_video = False
109
+ self.convert_audio = False
110
+ self.convert_video = False
111
+ self.screen_shots = False
112
+ self.is_cancelled = False
113
+ self.force_run = False
114
+ self.force_download = False
115
+ self.force_upload = False
116
+ self.is_torrent = False
117
+ self.as_med = False
118
+ self.as_doc = False
119
+ self.is_file = False
120
+ self.bot_trans = False
121
+ self.user_trans = False
122
+ self.is_rss = False
123
+ self.progress = True
124
+ self.ffmpeg_cmds = None
125
+ self.chat_thread_id = None
126
+ self.subproc = None
127
+ self.thumb = None
128
+ self.excluded_extensions = []
129
+ self.included_extensions = []
130
+ self.files_to_proceed = []
131
+ self.is_super_chat = self.message.chat.type.name in [
132
+ "SUPERGROUP",
133
+ "CHANNEL",
134
+ "FORUM",
135
+ ]
136
+
137
+ def get_token_path(self, dest):
138
+ if dest.startswith("mtp:"):
139
+ return f"tokens/{self.user_id}.pickle"
140
+ elif (
141
+ dest.startswith("sa:")
142
+ or Config.USE_SERVICE_ACCOUNTS
143
+ and not dest.startswith("tp:")
144
+ ):
145
+ return "accounts"
146
+ else:
147
+ return "token.pickle"
148
+
149
+ def get_config_path(self, dest):
150
+ return (
151
+ f"rclone/{self.user_id}.conf" if dest.startswith("mrcc:") else "rclone.conf"
152
+ )
153
+
154
+ async def is_token_exists(self, path, status):
155
+ if is_rclone_path(path):
156
+ config_path = self.get_config_path(path)
157
+ if config_path != "rclone.conf" and status == "up":
158
+ self.private_link = True
159
+ if not await aiopath.exists(config_path):
160
+ raise ValueError(f"Rclone Config: {config_path} not Exists!")
161
+ elif (
162
+ status == "dl"
163
+ and is_gdrive_link(path)
164
+ or status == "up"
165
+ and is_gdrive_id(path)
166
+ ):
167
+ token_path = self.get_token_path(path)
168
+ if token_path.startswith("tokens/") and status == "up":
169
+ self.private_link = True
170
+ if not await aiopath.exists(token_path):
171
+ raise ValueError(f"NO TOKEN! {token_path} not Exists!")
172
+
173
+ async def before_start(self):
174
+ self.name_sub = (
175
+ self.name_sub
176
+ or self.user_dict.get("NAME_SUBSTITUTE", False)
177
+ or (
178
+ Config.NAME_SUBSTITUTE
179
+ if "NAME_SUBSTITUTE" not in self.user_dict
180
+ else ""
181
+ )
182
+ )
183
+ if self.name_sub:
184
+ self.name_sub = [x.split("/") for x in self.name_sub.split(" | ")]
185
+ self.excluded_extensions = self.user_dict.get("EXCLUDED_EXTENSIONS") or (
186
+ excluded_extensions
187
+ if "EXCLUDED_EXTENSIONS" not in self.user_dict
188
+ else ["aria2", "!qB"]
189
+ )
190
+ self.included_extensions = self.user_dict.get("INCLUDED_EXTENSIONS") or (
191
+ included_extensions if "INCLUDED_EXTENSIONS" not in self.user_dict else []
192
+ )
193
+ if not self.rc_flags:
194
+ if self.user_dict.get("RCLONE_FLAGS"):
195
+ self.rc_flags = self.user_dict["RCLONE_FLAGS"]
196
+ elif "RCLONE_FLAGS" not in self.user_dict and Config.RCLONE_FLAGS:
197
+ self.rc_flags = Config.RCLONE_FLAGS
198
+ if self.link not in ["rcl", "gdl"]:
199
+ if not self.is_jd:
200
+ if is_rclone_path(self.link):
201
+ if not self.link.startswith("mrcc:") and self.user_dict.get(
202
+ "USER_TOKENS", False
203
+ ):
204
+ self.link = f"mrcc:{self.link}"
205
+ await self.is_token_exists(self.link, "dl")
206
+ elif is_gdrive_link(self.link):
207
+ if not self.link.startswith(
208
+ ("mtp:", "tp:", "sa:")
209
+ ) and self.user_dict.get("USER_TOKENS", False):
210
+ self.link = f"mtp:{self.link}"
211
+ await self.is_token_exists(self.link, "dl")
212
+ elif self.link == "rcl":
213
+ if not self.is_ytdlp and not self.is_jd:
214
+ self.link = await RcloneList(self).get_rclone_path("rcd")
215
+ if not is_rclone_path(self.link):
216
+ raise ValueError(self.link)
217
+ elif self.link == "gdl":
218
+ if not self.is_ytdlp and not self.is_jd:
219
+ self.link = await GoogleDriveList(self).get_target_id("gdd")
220
+ if not is_gdrive_id(self.link):
221
+ raise ValueError(self.link)
222
+
223
+ self.user_transmission = TgClient.IS_PREMIUM_USER and (
224
+ self.user_dict.get("USER_TRANSMISSION")
225
+ or Config.USER_TRANSMISSION
226
+ and "USER_TRANSMISSION" not in self.user_dict
227
+ )
228
+
229
+ if self.user_dict.get("UPLOAD_PATHS", False):
230
+ if self.up_dest in self.user_dict["UPLOAD_PATHS"]:
231
+ self.up_dest = self.user_dict["UPLOAD_PATHS"][self.up_dest]
232
+ elif (
233
+ "UPLOAD_PATHS" not in self.user_dict or not self.user_dict["UPLOAD_PATHS"]
234
+ ) and Config.UPLOAD_PATHS:
235
+ if self.up_dest in Config.UPLOAD_PATHS:
236
+ self.up_dest = Config.UPLOAD_PATHS[self.up_dest]
237
+
238
+ if self.ffmpeg_cmds:
239
+ if self.user_dict.get("FFMPEG_CMDS", None):
240
+ ffmpeg_dict = deepcopy(self.user_dict["FFMPEG_CMDS"])
241
+ elif (
242
+ "FFMPEG_CMDS" not in self.user_dict or not self.user_dict["FFMPEG_CMDS"]
243
+ ) and Config.FFMPEG_CMDS:
244
+ ffmpeg_dict = deepcopy(Config.FFMPEG_CMDS)
245
+ else:
246
+ ffmpeg_dict = None
247
+ cmds = []
248
+ for key in list(self.ffmpeg_cmds):
249
+ if isinstance(key, tuple):
250
+ cmds.extend(list(key))
251
+ elif ffmpeg_dict is not None:
252
+ if key in ffmpeg_dict.keys():
253
+ for ind, vl in enumerate(ffmpeg_dict[key]):
254
+ if variables := set(findall(r"\{(.*?)\}", vl)):
255
+ ff_values = (
256
+ self.user_dict.get("FFMPEG_VARIABLES", {})
257
+ .get(key, {})
258
+ .get(str(ind), {})
259
+ )
260
+ if Counter(list(variables)) == Counter(
261
+ list(ff_values.keys())
262
+ ):
263
+ cmds.append(vl.format(**ff_values))
264
+ else:
265
+ cmds.append(vl)
266
+ self.ffmpeg_cmds = cmds
267
+
268
+ if not self.is_leech:
269
+ self.stop_duplicate = (
270
+ self.user_dict.get("STOP_DUPLICATE")
271
+ or "STOP_DUPLICATE" not in self.user_dict
272
+ and Config.STOP_DUPLICATE
273
+ )
274
+ default_upload = (
275
+ self.user_dict.get("DEFAULT_UPLOAD", "") or Config.DEFAULT_UPLOAD
276
+ )
277
+ if (not self.up_dest and default_upload == "rc") or self.up_dest == "rc":
278
+ self.up_dest = self.user_dict.get("RCLONE_PATH") or Config.RCLONE_PATH
279
+ elif (not self.up_dest and default_upload == "gd") or self.up_dest == "gd":
280
+ self.up_dest = self.user_dict.get("GDRIVE_ID") or Config.GDRIVE_ID
281
+ if not self.up_dest:
282
+ raise ValueError("No Upload Destination!")
283
+ if self.up_dest not in ["rcl", "gdl"]:
284
+ if is_gdrive_id(self.up_dest):
285
+ if not self.up_dest.startswith(
286
+ ("mtp:", "tp:", "sa:")
287
+ ) and self.user_dict.get("USER_TOKENS", False):
288
+ self.up_dest = f"mtp:{self.up_dest}"
289
+ elif is_rclone_path(self.up_dest):
290
+ if not self.up_dest.startswith("mrcc:") and self.user_dict.get(
291
+ "USER_TOKENS", False
292
+ ):
293
+ self.up_dest = f"mrcc:{self.up_dest}"
294
+ self.up_dest = self.up_dest.strip("/")
295
+ else:
296
+ raise ValueError("Wrong Upload Destination!")
297
+ await self.is_token_exists(self.up_dest, "up")
298
+
299
+ if self.up_dest == "rcl":
300
+ if self.is_clone:
301
+ if not is_rclone_path(self.link):
302
+ raise ValueError(
303
+ "You can't clone from different types of tools"
304
+ )
305
+ config_path = self.get_config_path(self.link)
306
+ else:
307
+ config_path = None
308
+ self.up_dest = await RcloneList(self).get_rclone_path(
309
+ "rcu", config_path
310
+ )
311
+ if not is_rclone_path(self.up_dest):
312
+ raise ValueError(self.up_dest)
313
+ elif self.up_dest == "gdl":
314
+ if self.is_clone:
315
+ if not is_gdrive_link(self.link):
316
+ raise ValueError(
317
+ "You can't clone from different types of tools"
318
+ )
319
+ token_path = self.get_token_path(self.link)
320
+ else:
321
+ token_path = None
322
+ self.up_dest = await GoogleDriveList(self).get_target_id(
323
+ "gdu", token_path
324
+ )
325
+ if not is_gdrive_id(self.up_dest):
326
+ raise ValueError(self.up_dest)
327
+ elif self.is_clone:
328
+ if is_gdrive_link(self.link) and self.get_token_path(
329
+ self.link
330
+ ) != self.get_token_path(self.up_dest):
331
+ raise ValueError("You must use the same token to clone!")
332
+ elif is_rclone_path(self.link) and self.get_config_path(
333
+ self.link
334
+ ) != self.get_config_path(self.up_dest):
335
+ raise ValueError("You must use the same config to clone!")
336
+ else:
337
+ self.up_dest = (
338
+ self.up_dest
339
+ or self.user_dict.get("LEECH_DUMP_CHAT")
340
+ or (
341
+ Config.LEECH_DUMP_CHAT
342
+ if "LEECH_DUMP_CHAT" not in self.user_dict
343
+ else None
344
+ )
345
+ )
346
+ self.hybrid_leech = TgClient.IS_PREMIUM_USER and (
347
+ self.user_dict.get("HYBRID_LEECH")
348
+ or Config.HYBRID_LEECH
349
+ and "HYBRID_LEECH" not in self.user_dict
350
+ )
351
+ if self.bot_trans:
352
+ self.user_transmission = False
353
+ self.hybrid_leech = False
354
+ if self.user_trans:
355
+ self.user_transmission = TgClient.IS_PREMIUM_USER
356
+ if self.up_dest:
357
+ if not isinstance(self.up_dest, int):
358
+ if self.up_dest.startswith("b:"):
359
+ self.up_dest = self.up_dest.replace("b:", "", 1)
360
+ self.user_transmission = False
361
+ self.hybrid_leech = False
362
+ elif self.up_dest.startswith("u:"):
363
+ self.up_dest = self.up_dest.replace("u:", "", 1)
364
+ self.user_transmission = TgClient.IS_PREMIUM_USER
365
+ elif self.up_dest.startswith("h:"):
366
+ self.up_dest = self.up_dest.replace("h:", "", 1)
367
+ self.user_transmission = TgClient.IS_PREMIUM_USER
368
+ self.hybrid_leech = self.user_transmission
369
+ if "|" in self.up_dest:
370
+ self.up_dest, self.chat_thread_id = list(
371
+ map(
372
+ lambda x: int(x) if x.lstrip("-").isdigit() else x,
373
+ self.up_dest.split("|", 1),
374
+ )
375
+ )
376
+ elif self.up_dest.lstrip("-").isdigit():
377
+ self.up_dest = int(self.up_dest)
378
+ elif self.up_dest.lower() == "pm":
379
+ self.up_dest = self.user_id
380
+
381
+ if self.user_transmission:
382
+ try:
383
+ chat = await TgClient.user.get_chat(self.up_dest)
384
+ except:
385
+ chat = None
386
+ if chat is None:
387
+ LOGGER.warning(
388
+ "Account of user session can't find the the destination chat!"
389
+ )
390
+ self.user_transmission = False
391
+ self.hybrid_leech = False
392
+ else:
393
+ if chat.type.name not in [
394
+ "SUPERGROUP",
395
+ "CHANNEL",
396
+ "GROUP",
397
+ "FORUM",
398
+ ]:
399
+ self.user_transmission = False
400
+ self.hybrid_leech = False
401
+ elif chat.is_admin:
402
+ member = await chat.get_member(TgClient.user.me.id)
403
+ if (
404
+ not member.privileges.can_manage_chat
405
+ or not member.privileges.can_delete_messages
406
+ ):
407
+ self.user_transmission = False
408
+ self.hybrid_leech = False
409
+ LOGGER.warning(
410
+ "Enable manage chat and delete messages to account of the user session from administration settings!"
411
+ )
412
+ else:
413
+ LOGGER.warning(
414
+ "Promote the account of the user session to admin in the chat to get the benefit of user transmission!"
415
+ )
416
+ self.user_transmission = False
417
+ self.hybrid_leech = False
418
+
419
+ if not self.user_transmission or self.hybrid_leech:
420
+ try:
421
+ chat = await self.client.get_chat(self.up_dest)
422
+ except:
423
+ chat = None
424
+ if chat is None:
425
+ if self.user_transmission:
426
+ self.hybrid_leech = False
427
+ else:
428
+ raise ValueError("Chat not found!")
429
+ else:
430
+ if chat.type.name in [
431
+ "SUPERGROUP",
432
+ "CHANNEL",
433
+ "GROUP",
434
+ "FORUM",
435
+ ]:
436
+ if not chat.is_admin:
437
+ raise ValueError(
438
+ "Bot is not admin in the destination chat!"
439
+ )
440
+ else:
441
+ member = await chat.get_member(self.client.me.id)
442
+ if (
443
+ not member.privileges.can_manage_chat
444
+ or not member.privileges.can_delete_messages
445
+ ):
446
+ if not self.user_transmission:
447
+ raise ValueError(
448
+ "You don't have enough privileges in this chat! Enable manage chat and delete messages for this bot!"
449
+ )
450
+ else:
451
+ self.hybrid_leech = False
452
+ else:
453
+ try:
454
+ await self.client.send_chat_action(
455
+ self.up_dest, ChatAction.TYPING
456
+ )
457
+ except:
458
+ raise ValueError("Start the bot and try again!")
459
+ elif (
460
+ self.user_transmission or self.hybrid_leech
461
+ ) and not self.is_super_chat:
462
+ self.user_transmission = False
463
+ self.hybrid_leech = False
464
+ if self.split_size:
465
+ if self.split_size.isdigit():
466
+ self.split_size = int(self.split_size)
467
+ else:
468
+ self.split_size = get_size_bytes(self.split_size)
469
+ self.split_size = (
470
+ self.split_size
471
+ or self.user_dict.get("LEECH_SPLIT_SIZE")
472
+ or Config.LEECH_SPLIT_SIZE
473
+ )
474
+ self.equal_splits = (
475
+ self.user_dict.get("EQUAL_SPLITS")
476
+ or Config.EQUAL_SPLITS
477
+ and "EQUAL_SPLITS" not in self.user_dict
478
+ )
479
+ self.max_split_size = (
480
+ TgClient.MAX_SPLIT_SIZE if self.user_transmission else 2097152000
481
+ )
482
+ self.split_size = min(self.split_size, self.max_split_size)
483
+
484
+ if not self.as_doc:
485
+ self.as_doc = (
486
+ not self.as_med
487
+ if self.as_med
488
+ else (
489
+ self.user_dict.get("AS_DOCUMENT", False)
490
+ or Config.AS_DOCUMENT
491
+ and "AS_DOCUMENT" not in self.user_dict
492
+ )
493
+ )
494
+
495
+ self.thumbnail_layout = (
496
+ self.thumbnail_layout
497
+ or self.user_dict.get("THUMBNAIL_LAYOUT", False)
498
+ or (
499
+ Config.THUMBNAIL_LAYOUT
500
+ if "THUMBNAIL_LAYOUT" not in self.user_dict
501
+ else ""
502
+ )
503
+ )
504
+
505
+ self.clone_dump_chats = self.user_dict.get("CLONE_DUMP_CHATS", {}) or (
506
+ Config.CLONE_DUMP_CHATS
507
+ if "CLONE_DUMP_CHATS" not in self.user_dict and Config.CLONE_DUMP_CHATS
508
+ else {}
509
+ )
510
+ if self.clone_dump_chats:
511
+ if isinstance(self.clone_dump_chats, int):
512
+ self.clone_dump_chats = [self.clone_dump_chats]
513
+ elif isinstance(self.clone_dump_chats, str):
514
+ if self.clone_dump_chats.startswith(
515
+ "["
516
+ ) and self.clone_dump_chats.endswith("]"):
517
+ self.clone_dump_chats = eval(self.clone_dump_chats)
518
+ else:
519
+ self.clone_dump_chats = [self.clone_dump_chats]
520
+ temp_dict = {}
521
+ for ch in self.clone_dump_chats:
522
+ if isinstance(ch, str) and "|" in ch:
523
+ ci, ti = map(
524
+ lambda x: int(x) if x.lstrip("-").isdigit() else x,
525
+ ch.split("|", 1),
526
+ )
527
+ temp_dict[ci] = {"thread_id": ti, "last_sent_msg": None}
528
+ elif isinstance(ch, str):
529
+ if ch.lower() == "pm":
530
+ ci = self.user_id
531
+ else:
532
+ ci = int(ch) if ch.lstrip("-").isdigit() else ch
533
+ temp_dict[ci] = {"thread_id": None, "last_sent_msg": None}
534
+ else:
535
+ temp_dict[ch] = {"thread_id": None, "last_sent_msg": None}
536
+ self.clone_dump_chats = temp_dict
537
+ if self.thumb != "none" and is_telegram_link(self.thumb):
538
+ msg = (await get_tg_link_message(self.thumb))[0]
539
+ self.thumb = (
540
+ await create_thumb(msg) if msg.photo or msg.document else ""
541
+ )
542
+
543
+ async def get_tag(self, text: list):
544
+ if len(text) > 1 and text[1].startswith("Tag: "):
545
+ self.is_rss = True
546
+ user_info = text[1].split("Tag: ")
547
+ if len(user_info) >= 3:
548
+ id_ = user_info[-1]
549
+ self.tag = " ".join(user_info[:-1])
550
+ else:
551
+ self.tag, id_ = text[1].split("Tag: ")[1].split()
552
+ self.user = self.message.from_user = await self.client.get_users(int(id_))
553
+ self.user_id = self.user.id
554
+ self.user_dict = user_data.get(self.user_id, {})
555
+ try:
556
+ await self.message.unpin()
557
+ except:
558
+ pass
559
+ if self.user:
560
+ if username := self.user.username:
561
+ self.tag = f"@{username}"
562
+ elif hasattr(self.user, "mention"):
563
+ self.tag = self.user.mention
564
+ else:
565
+ self.tag = self.user.title
566
+
567
+ @new_task
568
+ async def run_multi(self, input_list, obj):
569
+ await sleep(7)
570
+ if not self.multi_tag and self.multi > 1:
571
+ self.multi_tag = token_urlsafe(3)
572
+ multi_tags.add(self.multi_tag)
573
+ elif self.multi <= 1:
574
+ if self.multi_tag in multi_tags:
575
+ multi_tags.discard(self.multi_tag)
576
+ return
577
+ if self.multi_tag and self.multi_tag not in multi_tags:
578
+ await send_message(
579
+ self.message, f"{self.tag} Multi Task has been cancelled!"
580
+ )
581
+ await send_status_message(self.message)
582
+ async with task_dict_lock:
583
+ for fd_name in self.same_dir:
584
+ self.same_dir[fd_name]["total"] -= self.multi
585
+ return
586
+ if len(self.bulk) != 0:
587
+ msg = input_list[:1]
588
+ msg.append(f"{self.bulk[0]} -i {self.multi - 1} {self.options}")
589
+ msgts = " ".join(msg)
590
+ if self.multi > 2:
591
+ msgts += f"\nCancel Multi: <code>/{BotCommands.CancelTaskCommand[1]} {self.multi_tag}</code>"
592
+ nextmsg = await send_message(self.message, msgts)
593
+ else:
594
+ msg = [s.strip() for s in input_list]
595
+ index = msg.index("-i")
596
+ msg[index + 1] = f"{self.multi - 1}"
597
+ nextmsg = await self.client.get_messages(
598
+ chat_id=self.message.chat.id,
599
+ message_ids=self.message.reply_to_message_id + 1,
600
+ )
601
+ if nextmsg.empty:
602
+ await send_message(
603
+ self.message,
604
+ "Bot can't fetch old messages (older than 48H), forward those messages and try multi/bulk again!",
605
+ )
606
+ await send_status_message(self.message)
607
+ return
608
+ msgts = " ".join(msg)
609
+ if self.multi > 2:
610
+ msgts += f"\nCancel Multi: <code>/{BotCommands.CancelTaskCommand[1]} {self.multi_tag}</code>"
611
+ nextmsg = await send_message(nextmsg, msgts)
612
+ if self.message.from_user:
613
+ nextmsg.from_user = self.user
614
+ else:
615
+ nextmsg.sender_chat = self.user
616
+ if intervals["stopAll"]:
617
+ return
618
+ await obj(
619
+ self.client,
620
+ nextmsg,
621
+ self.is_qbit,
622
+ self.is_leech,
623
+ self.is_jd,
624
+ self.is_nzb,
625
+ self.same_dir,
626
+ self.bulk,
627
+ self.multi_tag,
628
+ self.options,
629
+ ).new_event()
630
+
631
+ async def init_bulk(self, input_list, bulk_start, bulk_end, obj):
632
+ try:
633
+ self.bulk = await extract_bulk_links(self.message, bulk_start, bulk_end)
634
+ if len(self.bulk) == 0:
635
+ raise ValueError("Bulk Empty!")
636
+ b_msg = input_list[:1]
637
+ self.options = input_list[1:]
638
+ index = self.options.index("-b")
639
+ del self.options[index]
640
+ if bulk_start or bulk_end:
641
+ del self.options[index]
642
+ self.options = " ".join(self.options)
643
+ b_msg.append(f"{self.bulk[0]} -i {len(self.bulk)} {self.options}")
644
+ msg = " ".join(b_msg)
645
+ if len(self.bulk) > 2:
646
+ self.multi_tag = token_urlsafe(3)
647
+ multi_tags.add(self.multi_tag)
648
+ msg += f"\nCancel Multi: <code>/{BotCommands.CancelTaskCommand[1]} {self.multi_tag}</code>"
649
+ nextmsg = await send_message(self.message, msg)
650
+ if self.message.from_user:
651
+ nextmsg.from_user = self.user
652
+ else:
653
+ nextmsg.sender_chat = self.user
654
+ await obj(
655
+ self.client,
656
+ nextmsg,
657
+ self.is_qbit,
658
+ self.is_leech,
659
+ self.is_jd,
660
+ self.is_nzb,
661
+ self.same_dir,
662
+ self.bulk,
663
+ self.multi_tag,
664
+ self.options,
665
+ ).new_event()
666
+ except Exception as e:
667
+ await send_message(
668
+ self.message,
669
+ f"Reply to text file or to telegram message that have links separated by new line! {e}",
670
+ )
671
+
672
+ async def proceed_extract(self, dl_path, gid):
673
+ pswd = self.extract if isinstance(self.extract, str) else ""
674
+ self.files_to_proceed = []
675
+ if self.is_file and is_archive(dl_path):
676
+ self.files_to_proceed.append(dl_path)
677
+ else:
678
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
679
+ for file_ in files:
680
+ if (
681
+ is_first_archive_split(file_)
682
+ or is_archive(file_)
683
+ and not file_.strip().lower().endswith(".rar")
684
+ ):
685
+ f_path = ospath.join(dirpath, file_)
686
+ self.files_to_proceed.append(f_path)
687
+
688
+ if not self.files_to_proceed:
689
+ return dl_path
690
+ t_path = dl_path
691
+ sevenz = SevenZ(self)
692
+ LOGGER.info(f"Extracting: {self.name}")
693
+ async with task_dict_lock:
694
+ task_dict[self.mid] = SevenZStatus(self, sevenz, gid, "Extract")
695
+ for dirpath, _, files in await sync_to_async(
696
+ walk, self.up_dir or self.dir, topdown=False
697
+ ):
698
+ code = 0
699
+ for file_ in files:
700
+ if self.is_cancelled:
701
+ return False
702
+ if (
703
+ is_first_archive_split(file_)
704
+ or is_archive(file_)
705
+ and not file_.strip().lower().endswith(".rar")
706
+ ):
707
+
708
+ self.proceed_count += 1
709
+ f_path = ospath.join(dirpath, file_)
710
+ t_path = get_base_name(f_path) if self.is_file else dirpath
711
+ if not self.is_file:
712
+ self.subname = file_
713
+ code = await sevenz.extract(f_path, t_path, pswd)
714
+ if self.is_cancelled:
715
+ return code
716
+ if code == 0:
717
+ for file_ in files:
718
+ if is_archive_split(file_) or is_archive(file_):
719
+ del_path = ospath.join(dirpath, file_)
720
+ try:
721
+ await remove(del_path)
722
+ except:
723
+ self.is_cancelled = True
724
+ if self.proceed_count == 0:
725
+ LOGGER.info("No files able to extract!")
726
+ return t_path if self.is_file and code == 0 else dl_path
727
+
728
+ async def proceed_ffmpeg(self, dl_path, gid):
729
+ checked = False
730
+ inputs = {}
731
+ cmds = [
732
+ [part.strip() for part in split(item) if part.strip()]
733
+ for item in self.ffmpeg_cmds
734
+ ]
735
+ try:
736
+ ffmpeg = FFMpeg(self)
737
+ for ffmpeg_cmd in cmds:
738
+ self.proceed_count = 0
739
+ cmd = [
740
+ "taskset",
741
+ "-c",
742
+ f"{cores}",
743
+ "ffmpeg",
744
+ "-hide_banner",
745
+ "-loglevel",
746
+ "error",
747
+ "-progress",
748
+ "pipe:1",
749
+ ] + ffmpeg_cmd
750
+ if "-del" in cmd:
751
+ cmd.remove("-del")
752
+ delete_files = True
753
+ else:
754
+ delete_files = False
755
+ input_indexes = [
756
+ index for index, value in enumerate(cmd) if value == "-i"
757
+ ]
758
+ input_file = next(
759
+ (
760
+ cmd[index + 1]
761
+ for index in input_indexes
762
+ if cmd[index + 1].startswith("mltb")
763
+ ),
764
+ "",
765
+ )
766
+ if not input_file:
767
+ LOGGER.error("Wrong FFmpeg cmd!")
768
+ return dl_path
769
+ if input_file.strip().endswith(".video") or input_file.strip().endswith(
770
+ ".txt"
771
+ ):
772
+ ext = "video"
773
+ elif input_file.strip().endswith(".audio"):
774
+ ext = "audio"
775
+ elif "." not in input_file:
776
+ ext = "all"
777
+ else:
778
+ ext = ospath.splitext(input_file)[-1].lower()
779
+ if await aiopath.isfile(dl_path):
780
+ is_video, is_audio, _ = await get_document_type(dl_path)
781
+ if not is_video and not is_audio:
782
+ break
783
+ elif is_video and ext == "audio":
784
+ break
785
+ elif is_audio and not is_video and ext == "video":
786
+ break
787
+ elif ext not in [
788
+ "all",
789
+ "audio",
790
+ "video",
791
+ ] and not dl_path.strip().lower().endswith(ext):
792
+ break
793
+ new_folder = ospath.splitext(dl_path)[0]
794
+ name = ospath.basename(dl_path)
795
+ await makedirs(new_folder, exist_ok=True)
796
+ file_path = f"{new_folder}/{name}"
797
+ await move(dl_path, file_path)
798
+ if not checked:
799
+ checked = True
800
+ async with task_dict_lock:
801
+ task_dict[self.mid] = FFmpegStatus(
802
+ self, ffmpeg, gid, "FFmpeg"
803
+ )
804
+ self.progress = False
805
+ await cpu_eater_lock.acquire()
806
+ self.progress = True
807
+ LOGGER.info(f"Running ffmpeg cmd for: {file_path}")
808
+ var_cmd = cmd.copy()
809
+ for index in input_indexes:
810
+ if cmd[index + 1].startswith("mltb"):
811
+ var_cmd[index + 1] = file_path
812
+ elif is_telegram_link(cmd[index + 1]):
813
+ msg = (await get_tg_link_message(cmd[index + 1]))[0]
814
+ file_dir = await temp_download(msg)
815
+ inputs[index + 1] = file_dir
816
+ var_cmd[index + 1] = file_dir
817
+ self.subsize = self.size
818
+ res = await ffmpeg.ffmpeg_cmds(var_cmd, file_path)
819
+ if res:
820
+ if delete_files:
821
+ await remove(file_path)
822
+ if len(await listdir(new_folder)) == 1:
823
+ folder = new_folder.rsplit("/", 1)[0]
824
+ self.name = ospath.basename(res[0])
825
+ if self.name.startswith("ffmpeg"):
826
+ self.name = self.name.split(".", 1)[-1]
827
+ dl_path = ospath.join(folder, self.name)
828
+ await move(res[0], dl_path)
829
+ await rmtree(new_folder)
830
+ else:
831
+ dl_path = new_folder
832
+ self.name = new_folder.rsplit("/", 1)[-1]
833
+ else:
834
+ dl_path = new_folder
835
+ self.name = new_folder.rsplit("/", 1)[-1]
836
+ else:
837
+ await move(file_path, dl_path)
838
+ await rmtree(new_folder)
839
+ else:
840
+ for dirpath, _, files in natsorted(
841
+ await sync_to_async(walk, dl_path, topdown=False)
842
+ ):
843
+ f_path = []
844
+ for file_ in natsorted(files):
845
+ if (
846
+ ospath.join(dirpath, file_) in f_path
847
+ or file_ == "mltb.txt"
848
+ ):
849
+ continue
850
+ var_cmd = cmd.copy()
851
+ if self.is_cancelled:
852
+ return False
853
+ if "concat" not in var_cmd:
854
+ f_path = ospath.join(dirpath, file_)
855
+ is_video, is_audio, _ = await get_document_type(f_path)
856
+ if not is_video and not is_audio:
857
+ continue
858
+ elif is_video and ext == "audio":
859
+ continue
860
+ elif is_audio and not is_video and ext == "video":
861
+ continue
862
+ elif ext not in [
863
+ "all",
864
+ "audio",
865
+ "video",
866
+ ] and not f_path.strip().lower().endswith(ext):
867
+ continue
868
+ self.proceed_count += 1
869
+ for index in input_indexes:
870
+ if cmd[index + 1].startswith("mltb"):
871
+ if cmd[index + 1].endswith("txt"):
872
+ txt = ""
873
+ for mf in natsorted(files):
874
+ df = ospath.join(dirpath, mf)
875
+ if (await get_document_type(df))[0]:
876
+ f_path.append(df)
877
+ txt += f"file '{ffconcat_escape(df)}'\n"
878
+ async with aiopen(
879
+ f"{dirpath}/mltb.txt", "w"
880
+ ) as f:
881
+ await f.write(txt)
882
+ var_cmd[index + 1] = f"{dirpath}/mltb.txt"
883
+ else:
884
+ var_cmd[index + 1] = f_path
885
+ elif is_telegram_link(cmd[index + 1]):
886
+ msg = (await get_tg_link_message(cmd[index + 1]))[0]
887
+ file_dir = await temp_download(msg)
888
+ inputs[index + 1] = file_dir
889
+ var_cmd[index + 1] = file_dir
890
+ if not checked:
891
+ checked = True
892
+ async with task_dict_lock:
893
+ task_dict[self.mid] = FFmpegStatus(
894
+ self, ffmpeg, gid, "FFmpeg"
895
+ )
896
+ self.progress = False
897
+ await cpu_eater_lock.acquire()
898
+ self.progress = True
899
+ LOGGER.info(f"Running ffmpeg cmd for: {f_path}")
900
+ if isinstance(f_path, list):
901
+ self.subsize = 0
902
+ for mf in f_path:
903
+ self.subsize += await get_path_size(mf)
904
+ else:
905
+ self.subsize = await get_path_size(f_path)
906
+ self.subname = file_
907
+ res = await ffmpeg.ffmpeg_cmds(var_cmd, f_path)
908
+ if res and delete_files:
909
+ if isinstance(f_path, list):
910
+ for mf in f_path:
911
+ await remove(mf)
912
+ else:
913
+ await remove(f_path)
914
+ if len(res) == 1:
915
+ file_name = ospath.basename(res[0])
916
+ if file_name.startswith("ffmpeg"):
917
+ newname = file_name.split(".", 1)[-1]
918
+ newres = ospath.join(dirpath, newname)
919
+ await move(res[0], newres)
920
+ if await aiopath.exists(f"{dirpath}/mltb.txt"):
921
+ await remove(f"{dirpath}/mltb.txt")
922
+ for inp in inputs.values():
923
+ if "/temp/" in inp and await aiopath.exists(inp):
924
+ await remove(inp)
925
+ finally:
926
+ if checked:
927
+ cpu_eater_lock.release()
928
+ return dl_path
929
+
930
+ async def substitute(self, dl_path):
931
+ def perform_substitution(name, substitutions):
932
+ for substitution in substitutions:
933
+ sen = False
934
+ pattern = substitution[0]
935
+ if pattern.startswith('"') and pattern.endswith('"'):
936
+ pattern = pattern.strip('"')
937
+ if len(substitution) > 1:
938
+ if len(substitution) > 2:
939
+ sen = substitution[2] == "s"
940
+ res = substitution[1]
941
+ elif len(substitution[1]) == 0:
942
+ res = " "
943
+ else:
944
+ res = substitution[1]
945
+ else:
946
+ res = ""
947
+ try:
948
+ name = sub(pattern, res, name, flags=I if sen else 0)
949
+ except Exception as e:
950
+ LOGGER.error(
951
+ f"Substitute Error: pattern: {pattern} res: {res}. Error: {e}"
952
+ )
953
+ return False
954
+ if len(name.encode()) > 255:
955
+ LOGGER.error(f"Substitute: {name} is too long")
956
+ return False
957
+ return name
958
+
959
+ if self.is_file:
960
+ up_dir, name = dl_path.rsplit("/", 1)
961
+ new_name = perform_substitution(name, self.name_sub)
962
+ if not new_name:
963
+ return dl_path
964
+ new_path = ospath.join(up_dir, new_name)
965
+ await move(dl_path, new_path)
966
+ return new_path
967
+ else:
968
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
969
+ for file_ in files:
970
+ f_path = ospath.join(dirpath, file_)
971
+ new_name = perform_substitution(file_, self.name_sub)
972
+ if not new_name:
973
+ continue
974
+ await move(f_path, ospath.join(dirpath, new_name))
975
+ return dl_path
976
+
977
+ async def generate_screenshots(self, dl_path):
978
+ ss_nb = int(self.screen_shots) if isinstance(self.screen_shots, str) else 10
979
+ if self.is_file:
980
+ if (await get_document_type(dl_path))[0]:
981
+ LOGGER.info(f"Creating Screenshot for: {dl_path}")
982
+ res = await take_ss(dl_path, ss_nb)
983
+ if res:
984
+ new_folder = ospath.splitext(dl_path)[0]
985
+ name = ospath.basename(dl_path)
986
+ await makedirs(new_folder, exist_ok=True)
987
+ await gather(
988
+ move(dl_path, f"{new_folder}/{name}"),
989
+ move(res, new_folder),
990
+ )
991
+ return new_folder
992
+ else:
993
+ LOGGER.info(f"Creating Screenshot for: {dl_path}")
994
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
995
+ for file_ in files:
996
+ f_path = ospath.join(dirpath, file_)
997
+ if (await get_document_type(f_path))[0]:
998
+ await take_ss(f_path, ss_nb)
999
+ return dl_path
1000
+
1001
+ async def convert_media(self, dl_path, gid):
1002
+ fvext = []
1003
+ if self.convert_video:
1004
+ vdata = self.convert_video.split()
1005
+ vext = vdata[0].lower()
1006
+ if len(vdata) > 2:
1007
+ if "+" in vdata[1].split():
1008
+ vstatus = "+"
1009
+ elif "-" in vdata[1].split():
1010
+ vstatus = "-"
1011
+ else:
1012
+ vstatus = ""
1013
+ fvext.extend(f".{ext.lower()}" for ext in vdata[2:])
1014
+ else:
1015
+ vstatus = ""
1016
+ else:
1017
+ vext = ""
1018
+ vstatus = ""
1019
+
1020
+ faext = []
1021
+ if self.convert_audio:
1022
+ adata = self.convert_audio.split()
1023
+ aext = adata[0].lower()
1024
+ if len(adata) > 2:
1025
+ if "+" in adata[1].split():
1026
+ astatus = "+"
1027
+ elif "-" in adata[1].split():
1028
+ astatus = "-"
1029
+ else:
1030
+ astatus = ""
1031
+ faext.extend(f".{ext.lower()}" for ext in adata[2:])
1032
+ else:
1033
+ astatus = ""
1034
+ else:
1035
+ aext = ""
1036
+ astatus = ""
1037
+
1038
+ self.files_to_proceed = {}
1039
+ all_files = []
1040
+ if self.is_file:
1041
+ all_files.append(dl_path)
1042
+ else:
1043
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
1044
+ for file_ in files:
1045
+ f_path = ospath.join(dirpath, file_)
1046
+ all_files.append(f_path)
1047
+
1048
+ for f_path in all_files:
1049
+ is_video, is_audio, _ = await get_document_type(f_path)
1050
+ if (
1051
+ is_video
1052
+ and vext
1053
+ and not f_path.strip().lower().endswith(f".{vext}")
1054
+ and (
1055
+ vstatus == "+"
1056
+ and f_path.strip().lower().endswith(tuple(fvext))
1057
+ or vstatus == "-"
1058
+ and not f_path.strip().lower().endswith(tuple(fvext))
1059
+ or not vstatus
1060
+ )
1061
+ ):
1062
+ self.files_to_proceed[f_path] = "video"
1063
+ elif (
1064
+ is_audio
1065
+ and aext
1066
+ and not is_video
1067
+ and not f_path.strip().lower().endswith(f".{aext}")
1068
+ and (
1069
+ astatus == "+"
1070
+ and f_path.strip().lower().endswith(tuple(faext))
1071
+ or astatus == "-"
1072
+ and not f_path.strip().lower().endswith(tuple(faext))
1073
+ or not astatus
1074
+ )
1075
+ ):
1076
+ self.files_to_proceed[f_path] = "audio"
1077
+ del all_files
1078
+
1079
+ if self.files_to_proceed:
1080
+ ffmpeg = FFMpeg(self)
1081
+ async with task_dict_lock:
1082
+ task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Convert")
1083
+ self.progress = False
1084
+ async with cpu_eater_lock:
1085
+ self.progress = True
1086
+ for f_path, f_type in self.files_to_proceed.items():
1087
+ self.proceed_count += 1
1088
+ LOGGER.info(f"Converting: {f_path}")
1089
+ if self.is_file:
1090
+ self.subsize = self.size
1091
+ else:
1092
+ self.subsize = await get_path_size(f_path)
1093
+ self.subname = ospath.basename(f_path)
1094
+ if f_type == "video":
1095
+ res = await ffmpeg.convert_video(f_path, vext)
1096
+ else:
1097
+ res = await ffmpeg.convert_audio(f_path, aext)
1098
+ if res:
1099
+ try:
1100
+ await remove(f_path)
1101
+ except:
1102
+ self.is_cancelled = True
1103
+ return False
1104
+ if self.is_file:
1105
+ return res
1106
+ return dl_path
1107
+
1108
+ async def generate_sample_video(self, dl_path, gid):
1109
+ data = (
1110
+ self.sample_video.split(":") if isinstance(self.sample_video, str) else ""
1111
+ )
1112
+ if data:
1113
+ sample_duration = int(data[0]) if data[0] else 60
1114
+ part_duration = int(data[1]) if len(data) > 1 else 4
1115
+ else:
1116
+ sample_duration = 60
1117
+ part_duration = 4
1118
+
1119
+ self.files_to_proceed = {}
1120
+ if self.is_file and (await get_document_type(dl_path))[0]:
1121
+ file_ = ospath.basename(dl_path)
1122
+ self.files_to_proceed[dl_path] = file_
1123
+ else:
1124
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
1125
+ for file_ in files:
1126
+ f_path = ospath.join(dirpath, file_)
1127
+ if (await get_document_type(f_path))[0]:
1128
+ self.files_to_proceed[f_path] = file_
1129
+ if self.files_to_proceed:
1130
+ ffmpeg = FFMpeg(self)
1131
+ async with task_dict_lock:
1132
+ task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Sample Video")
1133
+ self.progress = False
1134
+ async with cpu_eater_lock:
1135
+ self.progress = True
1136
+ LOGGER.info(f"Creating Sample video: {self.name}")
1137
+ for f_path, file_ in self.files_to_proceed.items():
1138
+ self.proceed_count += 1
1139
+ if self.is_file:
1140
+ self.subsize = self.size
1141
+ else:
1142
+ self.subsize = await get_path_size(f_path)
1143
+ self.subname = file_
1144
+ res = await ffmpeg.sample_video(
1145
+ f_path, sample_duration, part_duration
1146
+ )
1147
+ if res and self.is_file:
1148
+ new_folder = ospath.splitext(f_path)[0]
1149
+ await makedirs(new_folder, exist_ok=True)
1150
+ await gather(
1151
+ move(f_path, f"{new_folder}/{file_}"),
1152
+ move(res, f"{new_folder}/SAMPLE.{file_}"),
1153
+ )
1154
+ return new_folder
1155
+ return dl_path
1156
+
1157
+ async def proceed_compress(self, dl_path, gid):
1158
+ pswd = self.compress if isinstance(self.compress, str) else ""
1159
+ if self.is_leech and self.is_file:
1160
+ new_folder = ospath.splitext(dl_path)[0]
1161
+ name = ospath.basename(dl_path)
1162
+ await makedirs(new_folder, exist_ok=True)
1163
+ new_dl_path = f"{new_folder}/{name}"
1164
+ await move(dl_path, new_dl_path)
1165
+ dl_path = new_dl_path
1166
+ up_path = f"{new_dl_path}.zip"
1167
+ self.is_file = False
1168
+ else:
1169
+ up_path = f"{dl_path}.zip"
1170
+ sevenz = SevenZ(self)
1171
+ async with task_dict_lock:
1172
+ task_dict[self.mid] = SevenZStatus(self, sevenz, gid, "Zip")
1173
+ return await sevenz.zip(dl_path, up_path, pswd)
1174
+
1175
+ async def proceed_split(self, dl_path, gid):
1176
+ self.files_to_proceed = {}
1177
+ if self.is_file:
1178
+ f_size = await get_path_size(dl_path)
1179
+ if f_size > self.split_size:
1180
+ self.files_to_proceed[dl_path] = [f_size, ospath.basename(dl_path)]
1181
+ else:
1182
+ for dirpath, _, files in await sync_to_async(walk, dl_path, topdown=False):
1183
+ for file_ in files:
1184
+ f_path = ospath.join(dirpath, file_)
1185
+ f_size = await get_path_size(f_path)
1186
+ if f_size > self.split_size:
1187
+ self.files_to_proceed[f_path] = [f_size, file_]
1188
+ if self.files_to_proceed:
1189
+ ffmpeg = FFMpeg(self)
1190
+ async with task_dict_lock:
1191
+ task_dict[self.mid] = FFmpegStatus(self, ffmpeg, gid, "Split")
1192
+ LOGGER.info(f"Splitting: {self.name}")
1193
+ for f_path, (f_size, file_) in self.files_to_proceed.items():
1194
+ self.proceed_count += 1
1195
+ if self.is_file:
1196
+ self.subsize = self.size
1197
+ else:
1198
+ self.subsize = f_size
1199
+ self.subname = file_
1200
+ parts = -(-f_size // self.split_size)
1201
+ if self.equal_splits:
1202
+ split_size = (f_size // parts) + (f_size % parts)
1203
+ else:
1204
+ split_size = self.split_size
1205
+ if not self.as_doc and (await get_document_type(f_path))[0]:
1206
+ self.progress = True
1207
+ res = await ffmpeg.split(f_path, file_, parts, split_size)
1208
+ else:
1209
+ self.progress = False
1210
+ res = await split_file(f_path, split_size, self)
1211
+ if self.is_cancelled:
1212
+ return False
1213
+ if res or f_size >= self.max_split_size:
1214
+ try:
1215
+ await remove(f_path)
1216
+ except:
1217
+ self.is_cancelled = True
bot/helper/ext_utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/ext_utils/bot_utils.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from httpx import AsyncClient
2
+ from asyncio.subprocess import PIPE
3
+ from functools import partial, wraps
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from asyncio import (
6
+ create_subprocess_exec,
7
+ create_subprocess_shell,
8
+ run_coroutine_threadsafe,
9
+ sleep,
10
+ )
11
+
12
+ from ... import user_data, bot_loop
13
+ from ...core.config_manager import Config
14
+ from ..telegram_helper.button_build import ButtonMaker
15
+ from .telegraph_helper import telegraph
16
+ from .help_messages import (
17
+ YT_HELP_DICT,
18
+ MIRROR_HELP_DICT,
19
+ CLONE_HELP_DICT,
20
+ )
21
+
22
+ COMMAND_USAGE = {}
23
+
24
+ THREAD_POOL = ThreadPoolExecutor(max_workers=500)
25
+
26
+
27
+ class SetInterval:
28
+ def __init__(self, interval, action, *args, **kwargs):
29
+ self.interval = interval
30
+ self.action = action
31
+ self.task = bot_loop.create_task(self._set_interval(*args, **kwargs))
32
+
33
+ async def _set_interval(self, *args, **kwargs):
34
+ while True:
35
+ await sleep(self.interval)
36
+ await self.action(*args, **kwargs)
37
+
38
+ def cancel(self):
39
+ self.task.cancel()
40
+
41
+
42
+ def _build_command_usage(help_dict, command_key):
43
+ buttons = ButtonMaker()
44
+ for name in list(help_dict.keys())[1:]:
45
+ buttons.data_button(name, f"help {command_key} {name}")
46
+ buttons.data_button("Close", "help close")
47
+ COMMAND_USAGE[command_key] = [help_dict["main"], buttons.build_menu(3)]
48
+ buttons.reset()
49
+
50
+
51
+ def create_help_buttons():
52
+ _build_command_usage(MIRROR_HELP_DICT, "mirror")
53
+ _build_command_usage(YT_HELP_DICT, "yt")
54
+ _build_command_usage(CLONE_HELP_DICT, "clone")
55
+
56
+
57
+ def bt_selection_buttons(id_):
58
+ gid = id_[:12] if len(id_) > 25 else id_
59
+ pin = "".join([n for n in id_ if n.isdigit()][:4])
60
+ buttons = ButtonMaker()
61
+ if Config.WEB_PINCODE:
62
+ buttons.url_button("Select Files", f"{Config.BASE_URL}/app/files?gid={id_}")
63
+ buttons.data_button("Pincode", f"sel pin {gid} {pin}")
64
+ else:
65
+ buttons.url_button(
66
+ "Select Files", f"{Config.BASE_URL}/app/files?gid={id_}&pin={pin}"
67
+ )
68
+ buttons.data_button("Done Selecting", f"sel done {gid} {id_}")
69
+ buttons.data_button("Cancel", f"sel cancel {gid}")
70
+ return buttons.build_menu(2)
71
+
72
+
73
+ async def get_telegraph_list(telegraph_content):
74
+ path = [
75
+ (
76
+ await telegraph.create_page(
77
+ title="Mirror-Leech-Bot Drive Search", content=content
78
+ )
79
+ )["path"]
80
+ for content in telegraph_content
81
+ ]
82
+ if len(path) > 1:
83
+ await telegraph.edit_telegraph(path, telegraph_content)
84
+ buttons = ButtonMaker()
85
+ buttons.url_button("🔎 VIEW", f"https://telegra.ph/{path[0]}")
86
+ return buttons.build_menu(1)
87
+
88
+
89
+ def arg_parser(items, arg_base):
90
+
91
+ if not items:
92
+ return
93
+
94
+ arg_start = -1
95
+ i = 0
96
+ total = len(items)
97
+
98
+ bool_arg_set = {
99
+ "-b",
100
+ "-e",
101
+ "-z",
102
+ "-s",
103
+ "-j",
104
+ "-d",
105
+ "-sv",
106
+ "-ss",
107
+ "-f",
108
+ "-fd",
109
+ "-fu",
110
+ "-sync",
111
+ "-hl",
112
+ "-doc",
113
+ "-med",
114
+ "-ut",
115
+ "-bt",
116
+ }
117
+
118
+ while i < total:
119
+ part = items[i]
120
+
121
+ if part in arg_base:
122
+ if arg_start == -1:
123
+ arg_start = i
124
+
125
+ if (
126
+ i + 1 == total
127
+ and part in bool_arg_set
128
+ or part
129
+ in [
130
+ "-s",
131
+ "-j",
132
+ "-f",
133
+ "-fd",
134
+ "-fu",
135
+ "-sync",
136
+ "-hl",
137
+ "-doc",
138
+ "-med",
139
+ "-ut",
140
+ "-bt",
141
+ ]
142
+ ):
143
+ arg_base[part] = True
144
+ else:
145
+ sub_list = []
146
+ for j in range(i + 1, total):
147
+ if items[j] in arg_base:
148
+ if part == "-c" and items[j] == "-c":
149
+ sub_list.append(items[j])
150
+ continue
151
+ if part in bool_arg_set and not sub_list:
152
+ arg_base[part] = True
153
+ break
154
+ if not sub_list:
155
+ break
156
+ check = " ".join(sub_list).strip()
157
+ if part != "-ff":
158
+ break
159
+ if check.startswith("[") and check.endswith("]"):
160
+ break
161
+ elif not check.startswith("["):
162
+ break
163
+ sub_list.append(items[j])
164
+ if sub_list:
165
+ value = " ".join(sub_list)
166
+ if part == "-ff":
167
+ if not value.strip().startswith("["):
168
+ arg_base[part].add(value)
169
+ else:
170
+ try:
171
+ arg_base[part].add(tuple(eval(value)))
172
+ except:
173
+ pass
174
+ else:
175
+ arg_base[part] = value
176
+ i += len(sub_list)
177
+ i += 1
178
+ if "link" in arg_base:
179
+ link_items = items[:arg_start] if arg_start != -1 else items
180
+ if link_items:
181
+ arg_base["link"] = " ".join(link_items)
182
+
183
+
184
+ def get_size_bytes(size):
185
+ size = size.lower()
186
+ if "k" in size:
187
+ size = int(float(size.split("k")[0]) * 1024)
188
+ elif "m" in size:
189
+ size = int(float(size.split("m")[0]) * 1048576)
190
+ elif "g" in size:
191
+ size = int(float(size.split("g")[0]) * 1073741824)
192
+ elif "t" in size:
193
+ size = int(float(size.split("t")[0]) * 1099511627776)
194
+ else:
195
+ size = 0
196
+ return size
197
+
198
+
199
+ async def get_content_type(url):
200
+ try:
201
+ async with AsyncClient() as client:
202
+ response = await client.get(url, allow_redirects=True, verify=False)
203
+ return response.headers.get("Content-Type")
204
+ except:
205
+ return None
206
+
207
+
208
+ def update_user_ldata(id_, key, value):
209
+ user_data.setdefault(id_, {})
210
+ user_data[id_][key] = value
211
+
212
+
213
+ async def cmd_exec(cmd, shell=False):
214
+ if shell:
215
+ proc = await create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
216
+ else:
217
+ proc = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE)
218
+ stdout, stderr = await proc.communicate()
219
+ try:
220
+ stdout = stdout.decode().strip()
221
+ except:
222
+ stdout = "Unable to decode the response!"
223
+ try:
224
+ stderr = stderr.decode().strip()
225
+ except:
226
+ stderr = "Unable to decode the error!"
227
+ return stdout, stderr, proc.returncode
228
+
229
+
230
+ def new_task(func):
231
+ @wraps(func)
232
+ async def wrapper(*args, **kwargs):
233
+ task = bot_loop.create_task(func(*args, **kwargs))
234
+ return task
235
+
236
+ return wrapper
237
+
238
+
239
+ async def sync_to_async(func, *args, wait=True, **kwargs):
240
+ pfunc = partial(func, *args, **kwargs)
241
+ future = bot_loop.run_in_executor(THREAD_POOL, pfunc)
242
+ return await future if wait else future
243
+
244
+
245
+ def async_to_sync(func, *args, wait=True, **kwargs):
246
+ future = run_coroutine_threadsafe(func(*args, **kwargs), bot_loop)
247
+ return future.result() if wait else future
248
+
249
+
250
+ def loop_thread(func):
251
+ @wraps(func)
252
+ def wrapper(*args, wait=False, **kwargs):
253
+ future = run_coroutine_threadsafe(func(*args, **kwargs), bot_loop)
254
+ return future.result() if wait else future
255
+
256
+ return wrapper
bot/helper/ext_utils/bulk_links.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles import open as aiopen
2
+ from aiofiles.os import remove
3
+
4
+
5
+ def filter_links(links_list, bulk_start, bulk_end):
6
+ start = bulk_start if bulk_start > 0 else None
7
+ end = bulk_end if bulk_end > 0 else None
8
+ return links_list[start:end]
9
+
10
+
11
+ def get_links_from_message(text):
12
+ links_list = text.split("\n")
13
+ return [item.strip() for item in links_list if len(item) != 0]
14
+
15
+
16
+ async def get_links_from_file(message):
17
+ links_list = []
18
+ text_file_dir = await message.download()
19
+ async with aiopen(text_file_dir, "r+") as f:
20
+ lines = await f.readlines()
21
+ links_list.extend(line.strip() for line in lines if len(line) != 0)
22
+ await remove(text_file_dir)
23
+ return links_list
24
+
25
+
26
+ async def extract_bulk_links(message, bulk_start, bulk_end):
27
+ bulk_start = int(bulk_start)
28
+ bulk_end = int(bulk_end)
29
+ links_list = []
30
+ if reply_to := message.reply_to_message:
31
+ if (file_ := reply_to.document) and (file_.mime_type == "text/plain"):
32
+ links_list = await get_links_from_file(reply_to)
33
+ elif text := reply_to.text:
34
+ links_list = get_links_from_message(text)
35
+ return filter_links(links_list, bulk_start, bulk_end) if links_list else links_list
bot/helper/ext_utils/db_handler.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles import open as aiopen
2
+ from aiofiles.os import path as aiopath
3
+ from importlib import import_module
4
+ from pymongo import AsyncMongoClient
5
+ from pymongo.server_api import ServerApi
6
+ from pymongo.errors import PyMongoError
7
+
8
+ from ... import LOGGER, user_data, rss_dict, qbit_options
9
+ from ...core.telegram_manager import TgClient
10
+ from ...core.config_manager import Config
11
+
12
+
13
+ class DbManager:
14
+ def __init__(self):
15
+ self._return = True
16
+ self._conn = None
17
+ self.db = None
18
+
19
+ async def connect(self):
20
+ try:
21
+ if self._conn is not None:
22
+ await self._conn.close()
23
+ self._conn = AsyncMongoClient(
24
+ Config.DATABASE_URL,
25
+ server_api=ServerApi("1"),
26
+ connectTimeoutMS=60000,
27
+ serverSelectionTimeoutMS=60000,
28
+ )
29
+ self.db = self._conn[Config.DATABASE_NAME]
30
+ self._return = False
31
+ except PyMongoError as e:
32
+ LOGGER.error(f"Error in DB connection: {e}")
33
+ self.db = None
34
+ self._return = True
35
+ self._conn = None
36
+
37
+ async def disconnect(self):
38
+ self._return = True
39
+ if self._conn is not None:
40
+ await self._conn.close()
41
+ self._conn = None
42
+
43
+ async def update_deploy_config(self):
44
+ if self._return:
45
+ return
46
+ try:
47
+ settings = import_module("config")
48
+ config_file = {
49
+ key: value.strip() if isinstance(value, str) else value
50
+ for key, value in vars(settings).items()
51
+ if not key.startswith("__")
52
+ }
53
+ except ModuleNotFoundError:
54
+ return
55
+ await self.db.settings.deployConfig.replace_one(
56
+ {"_id": TgClient.ID}, config_file, upsert=True
57
+ )
58
+
59
+ async def update_config(self, dict_):
60
+ if self._return:
61
+ return
62
+ await self.db.settings.config.update_one(
63
+ {"_id": TgClient.ID}, {"$set": dict_}, upsert=True
64
+ )
65
+
66
+ async def update_aria2(self, key, value):
67
+ if self._return:
68
+ return
69
+ await self.db.settings.aria2c.update_one(
70
+ {"_id": TgClient.ID}, {"$set": {key: value}}, upsert=True
71
+ )
72
+
73
+ async def update_qbittorrent(self, key, value):
74
+ if self._return:
75
+ return
76
+ await self.db.settings.qbittorrent.update_one(
77
+ {"_id": TgClient.ID}, {"$set": {key: value}}, upsert=True
78
+ )
79
+
80
+ async def save_qbit_settings(self):
81
+ if self._return:
82
+ return
83
+ await self.db.settings.qbittorrent.update_one(
84
+ {"_id": TgClient.ID}, {"$set": qbit_options}, upsert=True
85
+ )
86
+
87
+ async def update_private_file(self, path):
88
+ if self._return:
89
+ return
90
+ db_path = path.replace(".", "__")
91
+ if await aiopath.exists(path):
92
+ async with aiopen(path, "rb+") as pf:
93
+ pf_bin = await pf.read()
94
+ await self.db.settings.files.update_one(
95
+ {"_id": TgClient.ID}, {"$set": {db_path: pf_bin}}, upsert=True
96
+ )
97
+ if path == "config.py":
98
+ await self.update_deploy_config()
99
+ else:
100
+ await self.db.settings.files.update_one(
101
+ {"_id": TgClient.ID}, {"$unset": {db_path: ""}}, upsert=True
102
+ )
103
+
104
+ async def update_nzb_config(self):
105
+ if self._return:
106
+ return
107
+ async with aiopen("sabnzbd/SABnzbd.ini", "rb+") as pf:
108
+ nzb_conf = await pf.read()
109
+ await self.db.settings.nzb.replace_one(
110
+ {"_id": TgClient.ID}, {"SABnzbd__ini": nzb_conf}, upsert=True
111
+ )
112
+
113
+ async def update_user_data(self, user_id):
114
+ if self._return:
115
+ return
116
+ data = user_data.get(user_id, {})
117
+ data = data.copy()
118
+ for key in ("THUMBNAIL", "RCLONE_CONFIG", "TOKEN_PICKLE"):
119
+ data.pop(key, None)
120
+ pipeline = [
121
+ {
122
+ "$replaceRoot": {
123
+ "newRoot": {
124
+ "$mergeObjects": [
125
+ data,
126
+ {
127
+ "$arrayToObject": {
128
+ "$filter": {
129
+ "input": {"$objectToArray": "$$ROOT"},
130
+ "as": "field",
131
+ "cond": {
132
+ "$in": [
133
+ "$$field.k",
134
+ [
135
+ "THUMBNAIL",
136
+ "RCLONE_CONFIG",
137
+ "TOKEN_PICKLE",
138
+ ],
139
+ ]
140
+ },
141
+ }
142
+ }
143
+ },
144
+ ]
145
+ }
146
+ }
147
+ }
148
+ ]
149
+ await self.db.users.update_one({"_id": user_id}, pipeline, upsert=True)
150
+
151
+ async def update_user_doc(self, user_id, key, path=""):
152
+ if self._return:
153
+ return
154
+ if path:
155
+ async with aiopen(path, "rb+") as doc:
156
+ doc_bin = await doc.read()
157
+ await self.db.users.update_one(
158
+ {"_id": user_id}, {"$set": {key: doc_bin}}, upsert=True
159
+ )
160
+ else:
161
+ await self.db.users.update_one(
162
+ {"_id": user_id}, {"$unset": {key: ""}}, upsert=True
163
+ )
164
+
165
+ async def rss_update_all(self):
166
+ if self._return:
167
+ return
168
+ for user_id in list(rss_dict.keys()):
169
+ await self.db.rss[TgClient.ID].replace_one(
170
+ {"_id": user_id}, rss_dict[user_id], upsert=True
171
+ )
172
+
173
+ async def rss_update(self, user_id):
174
+ if self._return:
175
+ return
176
+ await self.db.rss[TgClient.ID].replace_one(
177
+ {"_id": user_id}, rss_dict[user_id], upsert=True
178
+ )
179
+
180
+ async def rss_delete(self, user_id):
181
+ if self._return:
182
+ return
183
+ await self.db.rss[TgClient.ID].delete_one({"_id": user_id})
184
+
185
+ async def add_incomplete_task(self, cid, link, tag):
186
+ if self._return:
187
+ return
188
+ await self.db.tasks[TgClient.ID].insert_one(
189
+ {"_id": link, "cid": cid, "tag": tag}
190
+ )
191
+
192
+ async def rm_complete_task(self, link):
193
+ if self._return:
194
+ return
195
+ await self.db.tasks[TgClient.ID].delete_one({"_id": link})
196
+
197
+ async def get_incomplete_tasks(self):
198
+ notifier_dict = {}
199
+ if self._return:
200
+ return notifier_dict
201
+ if await self.db.tasks[TgClient.ID].find_one():
202
+ rows = self.db.tasks[TgClient.ID].find({})
203
+ async for row in rows:
204
+ if row["cid"] in list(notifier_dict.keys()):
205
+ if row["tag"] in list(notifier_dict[row["cid"]]):
206
+ notifier_dict[row["cid"]][row["tag"]].append(row["_id"])
207
+ else:
208
+ notifier_dict[row["cid"]][row["tag"]] = [row["_id"]]
209
+ else:
210
+ notifier_dict[row["cid"]] = {row["tag"]: [row["_id"]]}
211
+ await self.db.tasks[TgClient.ID].drop()
212
+ return notifier_dict
213
+
214
+ async def trunc_table(self, name):
215
+ if self._return:
216
+ return
217
+ await self.db[name][TgClient.ID].drop()
218
+
219
+
220
+ database = DbManager()
bot/helper/ext_utils/exceptions.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class DirectDownloadLinkException(Exception):
2
+ """Not method found for extracting direct download link from the http link"""
3
+
4
+ pass
5
+
6
+
7
+ class NotSupportedExtractionArchive(Exception):
8
+ """The archive format use is trying to extract is not supported"""
9
+
10
+ pass
11
+
12
+
13
+ class RssShutdownException(Exception):
14
+ """This exception should be raised when shutdown is called to stop the monitor"""
15
+
16
+ pass
17
+
18
+
19
+ class TgLinkException(Exception):
20
+ """No Access granted for this chat"""
21
+
22
+ pass
bot/helper/ext_utils/files_utils.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aioshutil import rmtree as aiormtree, move
2
+ from asyncio import create_subprocess_exec, wait_for
3
+ from asyncio.subprocess import PIPE
4
+ from magic import Magic
5
+ from os import walk, path as ospath, readlink
6
+ from re import split as re_split, I, search as re_search, escape
7
+ from aiofiles.os import (
8
+ remove,
9
+ path as aiopath,
10
+ listdir,
11
+ rmdir,
12
+ readlink as aioreadlink,
13
+ symlink,
14
+ makedirs as aiomakedirs,
15
+ )
16
+
17
+ from ... import LOGGER, DOWNLOAD_DIR
18
+ from ...core.torrent_manager import TorrentManager
19
+ from .bot_utils import sync_to_async, cmd_exec
20
+ from .exceptions import NotSupportedExtractionArchive
21
+
22
+ ARCH_EXT = [
23
+ ".tar.bz2",
24
+ ".tar.gz",
25
+ ".bz2",
26
+ ".gz",
27
+ ".tar.xz",
28
+ ".tar",
29
+ ".tbz2",
30
+ ".tgz",
31
+ ".lzma2",
32
+ ".zip",
33
+ ".7z",
34
+ ".z",
35
+ ".rar",
36
+ ".iso",
37
+ ".wim",
38
+ ".cab",
39
+ ".apm",
40
+ ".arj",
41
+ ".chm",
42
+ ".cpio",
43
+ ".cramfs",
44
+ ".deb",
45
+ ".dmg",
46
+ ".fat",
47
+ ".hfs",
48
+ ".lzh",
49
+ ".lzma",
50
+ ".mbr",
51
+ ".msi",
52
+ ".mslz",
53
+ ".nsis",
54
+ ".ntfs",
55
+ ".rpm",
56
+ ".squashfs",
57
+ ".udf",
58
+ ".vhd",
59
+ ".xar",
60
+ ".zst",
61
+ ".zstd",
62
+ ".cbz",
63
+ ".apfs",
64
+ ".ar",
65
+ ".qcow",
66
+ ".macho",
67
+ ".exe",
68
+ ".dll",
69
+ ".sys",
70
+ ".pmd",
71
+ ".swf",
72
+ ".swfc",
73
+ ".simg",
74
+ ".vdi",
75
+ ".vhdx",
76
+ ".vmdk",
77
+ ".gzip",
78
+ ".lzma86",
79
+ ".sha256",
80
+ ".sha512",
81
+ ".sha224",
82
+ ".sha384",
83
+ ".sha1",
84
+ ".md5",
85
+ ".crc32",
86
+ ".crc64",
87
+ ]
88
+
89
+
90
+ FIRST_SPLIT_REGEX = (
91
+ r"\.part0*1\.rar$|\.7z\.0*1$|\.zip\.0*1$|^(?!.*\.part\d+\.rar$).*\.rar$"
92
+ )
93
+
94
+ SPLIT_REGEX = r"\.r\d+$|\.7z\.\d+$|\.z\d+$|\.zip\.\d+$|\.part\d+\.rar$"
95
+
96
+
97
+ def is_first_archive_split(file):
98
+ return bool(re_search(FIRST_SPLIT_REGEX, file.lower(), I))
99
+
100
+
101
+ def is_archive(file):
102
+ return file.strip().lower().endswith(tuple(ARCH_EXT))
103
+
104
+
105
+ def is_archive_split(file):
106
+ return bool(re_search(SPLIT_REGEX, file.lower(), I))
107
+
108
+
109
+ async def clean_target(opath):
110
+ if await aiopath.exists(opath):
111
+ LOGGER.info(f"Cleaning Target: {opath}")
112
+ try:
113
+ if await aiopath.isdir(opath):
114
+ await aiormtree(opath, ignore_errors=True)
115
+ else:
116
+ await remove(opath)
117
+ except Exception as e:
118
+ LOGGER.error(str(e))
119
+
120
+
121
+ async def clean_download(opath):
122
+ if await aiopath.exists(opath):
123
+ LOGGER.info(f"Cleaning Download: {opath}")
124
+ try:
125
+ await aiormtree(opath, ignore_errors=True)
126
+ except Exception as e:
127
+ LOGGER.error(str(e))
128
+
129
+
130
+ async def clean_all():
131
+ await TorrentManager.remove_all()
132
+ LOGGER.info("Cleaning Download Directory")
133
+ await (await create_subprocess_exec("rm", "-rf", DOWNLOAD_DIR)).wait()
134
+ await aiomakedirs(DOWNLOAD_DIR, exist_ok=True)
135
+
136
+
137
+ async def clean_unwanted(opath):
138
+ LOGGER.info(f"Cleaning unwanted files/folders: {opath}")
139
+ for dirpath, _, files in await sync_to_async(walk, opath, topdown=False):
140
+ for filee in files:
141
+ f_path = ospath.join(dirpath, filee)
142
+ if filee.strip().endswith(".parts") and filee.startswith("."):
143
+ await remove(f_path)
144
+ if dirpath.strip().endswith(".unwanted"):
145
+ await aiormtree(dirpath, ignore_errors=True)
146
+ for dirpath, _, files in await sync_to_async(walk, opath, topdown=False):
147
+ if not await listdir(dirpath):
148
+ await rmdir(dirpath)
149
+
150
+
151
+ async def get_path_size(opath):
152
+ total_size = 0
153
+ if await aiopath.isfile(opath):
154
+ if await aiopath.islink(opath):
155
+ opath = await aioreadlink(opath)
156
+ return await aiopath.getsize(opath)
157
+ for root, _, files in await sync_to_async(walk, opath):
158
+ for f in files:
159
+ abs_path = ospath.join(root, f)
160
+ if await aiopath.islink(abs_path):
161
+ abs_path = await aioreadlink(abs_path)
162
+ total_size += await aiopath.getsize(abs_path)
163
+ return total_size
164
+
165
+
166
+ async def count_files_and_folders(opath):
167
+ total_files = 0
168
+ total_folders = 0
169
+ for _, dirs, files in await sync_to_async(walk, opath):
170
+ total_files += len(files)
171
+ total_folders += len(dirs)
172
+ return total_folders, total_files
173
+
174
+
175
+ def get_base_name(orig_path):
176
+ extension = next(
177
+ (ext for ext in ARCH_EXT if orig_path.strip().lower().endswith(ext)), ""
178
+ )
179
+ if extension != "":
180
+ return re_split(f"{extension}$", orig_path, maxsplit=1, flags=I)[0]
181
+ else:
182
+ raise NotSupportedExtractionArchive("File format not supported for extraction")
183
+
184
+
185
+ async def create_recursive_symlink(source, destination):
186
+ if ospath.isdir(source):
187
+ await aiomakedirs(destination, exist_ok=True)
188
+ for item in await listdir(source):
189
+ item_source = ospath.join(source, item)
190
+ item_dest = ospath.join(destination, item)
191
+ await create_recursive_symlink(item_source, item_dest)
192
+ elif ospath.isfile(source):
193
+ try:
194
+ await symlink(source, destination)
195
+ except FileExistsError:
196
+ LOGGER.error(f"Shortcut already exists: {destination}")
197
+ except Exception as e:
198
+ LOGGER.error(f"Error creating shortcut for {source}: {e}")
199
+
200
+
201
+ def get_mime_type(file_path):
202
+ if ospath.islink(file_path):
203
+ file_path = readlink(file_path)
204
+ mime = Magic(mime=True)
205
+ mime_type = mime.from_file(file_path)
206
+ mime_type = mime_type or "text/plain"
207
+ return mime_type
208
+
209
+
210
+ async def remove_excluded_files(fpath, ee):
211
+ for root, _, files in await sync_to_async(walk, fpath):
212
+ if root.strip().endswith("/yt-dlp-thumb"):
213
+ continue
214
+ for f in files:
215
+ if f.strip().lower().endswith(tuple(ee)):
216
+ await remove(ospath.join(root, f))
217
+
218
+
219
+ async def remove_non_included_files(fpath, ie):
220
+ for root, _, files in await sync_to_async(walk, fpath):
221
+ if root.strip().endswith("/yt-dlp-thumb"):
222
+ continue
223
+ for f in files:
224
+ if f.strip().lower().endswith(tuple(ie)):
225
+ continue
226
+ await remove(ospath.join(root, f))
227
+
228
+
229
+ async def move_and_merge(source, destination, mid):
230
+ if not await aiopath.exists(destination):
231
+ await aiomakedirs(destination, exist_ok=True)
232
+ for item in await listdir(source):
233
+ item = item.strip()
234
+ src_path = f"{source}/{item}"
235
+ dest_path = f"{destination}/{item}"
236
+ if await aiopath.isdir(src_path):
237
+ if await aiopath.exists(dest_path):
238
+ await move_and_merge(src_path, dest_path, mid)
239
+ else:
240
+ await move(src_path, dest_path)
241
+ else:
242
+ if item.endswith((".aria2", ".!qB")):
243
+ continue
244
+ if await aiopath.exists(dest_path):
245
+ dest_path = f"{destination}/{mid}-{item}"
246
+ await move(src_path, dest_path)
247
+
248
+
249
+ async def join_files(opath):
250
+ files = await listdir(opath)
251
+ results = []
252
+ exists = False
253
+ for file_ in files:
254
+ if re_search(r"\.0+2$", file_) and await sync_to_async(
255
+ get_mime_type, f"{opath}/{file_}"
256
+ ) not in ["application/x-7z-compressed", "application/zip"]:
257
+ exists = True
258
+ final_name = file_.rsplit(".", 1)[0]
259
+ fpath = f"{opath}/{final_name}"
260
+ cmd = f'cat "{fpath}."* > "{fpath}"'
261
+ _, stderr, code = await cmd_exec(cmd, True)
262
+ if code != 0:
263
+ LOGGER.error(f"Failed to join {final_name}, stderr: {stderr}")
264
+ if await aiopath.isfile(fpath):
265
+ await remove(fpath)
266
+ else:
267
+ results.append(final_name)
268
+
269
+ if not exists:
270
+ LOGGER.warning("No files to join!")
271
+ elif results:
272
+ LOGGER.info("Join Completed!")
273
+ for res in results:
274
+ for file_ in files:
275
+ if re_search(rf"{escape(res)}\.0[0-9]+$", file_):
276
+ await remove(f"{opath}/{file_}")
277
+
278
+
279
+ async def split_file(f_path, split_size, listener):
280
+ out_path = f"{f_path}."
281
+ if listener.is_cancelled:
282
+ return False
283
+ listener.subproc = await create_subprocess_exec(
284
+ "split",
285
+ "--numeric-suffixes=1",
286
+ "--suffix-length=3",
287
+ f"--bytes={split_size}",
288
+ f_path,
289
+ out_path,
290
+ stderr=PIPE,
291
+ )
292
+ _, stderr = await listener.subproc.communicate()
293
+ code = listener.subproc.returncode
294
+ if listener.is_cancelled:
295
+ return False
296
+ if code == -9:
297
+ listener.is_cancelled = True
298
+ return False
299
+ elif code != 0:
300
+ try:
301
+ stderr = stderr.decode().strip()
302
+ except:
303
+ stderr = "Unable to decode the error!"
304
+ LOGGER.error(f"{stderr}. Split Document: {f_path}")
305
+ return True
306
+
307
+
308
+ class SevenZ:
309
+ def __init__(self, listener):
310
+ self._listener = listener
311
+ self._processed_bytes = 0
312
+ self._percentage = "0%"
313
+
314
+ @property
315
+ def processed_bytes(self):
316
+ return self._processed_bytes
317
+
318
+ @property
319
+ def progress(self):
320
+ return self._percentage
321
+
322
+ async def _sevenz_progress(self):
323
+ pattern = (
324
+ r"(\d+)\s+bytes|Total Physical Size\s*=\s*(\d+)|Physical Size\s*=\s*(\d+)"
325
+ )
326
+ while not (
327
+ self._listener.subproc.returncode is not None
328
+ or self._listener.is_cancelled
329
+ or self._listener.subproc.stdout.at_eof()
330
+ ):
331
+ try:
332
+ line = await wait_for(self._listener.subproc.stdout.readline(), 2)
333
+ except:
334
+ break
335
+ line = line.decode().strip()
336
+ if "%" in line:
337
+ perc = line.split("%", 1)[0]
338
+ if perc.isdigit():
339
+ self._percentage = f"{perc}%"
340
+ self._processed_bytes = (int(perc) / 100) * self._listener.subsize
341
+ else:
342
+ self._percentage = "0%"
343
+ continue
344
+ if match := re_search(pattern, line):
345
+ self._listener.subsize = int(match[1] or match[2] or match[3])
346
+ s = b""
347
+ while not (
348
+ self._listener.is_cancelled
349
+ or self._listener.subproc.returncode is not None
350
+ or self._listener.subproc.stdout.at_eof()
351
+ ):
352
+ try:
353
+ char = await wait_for(self._listener.subproc.stdout.read(1), 60)
354
+ except:
355
+ break
356
+ if not char:
357
+ break
358
+ s += char
359
+ if char == b"%":
360
+ try:
361
+ self._percentage = s.decode().rsplit(" ", 1)[-1].strip()
362
+ self._processed_bytes = (
363
+ int(self._percentage.strip("%")) / 100
364
+ ) * self._listener.subsize
365
+ except:
366
+ self._processed_bytes = 0
367
+ self._percentage = "0%"
368
+ s = b""
369
+
370
+ self._processed_bytes = 0
371
+ self._percentage = "0%"
372
+
373
+ async def extract(self, f_path, t_path, pswd):
374
+ cmd = [
375
+ "7z",
376
+ "x",
377
+ f"-p{pswd}",
378
+ f_path,
379
+ f"-o{t_path}",
380
+ "-aot",
381
+ "-xr!@PaxHeader",
382
+ "-bsp1",
383
+ "-bse1",
384
+ "-bb3",
385
+ ]
386
+ if not pswd:
387
+ del cmd[2]
388
+ if self._listener.is_cancelled:
389
+ return False
390
+ self._listener.subproc = await create_subprocess_exec(
391
+ *cmd,
392
+ stdout=PIPE,
393
+ stderr=PIPE,
394
+ )
395
+ await self._sevenz_progress()
396
+ _, stderr = await self._listener.subproc.communicate()
397
+ code = self._listener.subproc.returncode
398
+ if self._listener.is_cancelled:
399
+ return False
400
+ if code == -9:
401
+ self._listener.is_cancelled = True
402
+ return False
403
+ elif code != 0:
404
+ try:
405
+ stderr = stderr.decode().strip()
406
+ except:
407
+ stderr = "Unable to decode the error!"
408
+ LOGGER.error(f"{stderr}. Unable to extract archive!. Path: {f_path}")
409
+ return code
410
+
411
+ async def zip(self, dl_path, up_path, pswd):
412
+ size = await get_path_size(dl_path)
413
+ if self._listener.equal_splits:
414
+ parts = -(-size // self._listener.split_size)
415
+ split_size = (size // parts) + (size % parts)
416
+ else:
417
+ split_size = self._listener.split_size
418
+ cmd = [
419
+ "7z",
420
+ f"-v{split_size}b",
421
+ "a",
422
+ "-mx=0",
423
+ f"-p{pswd}",
424
+ up_path,
425
+ dl_path,
426
+ "-bsp1",
427
+ "-bse1",
428
+ "-bb3",
429
+ ]
430
+ if self._listener.is_leech and int(size) > self._listener.split_size:
431
+ if not pswd:
432
+ del cmd[4]
433
+ LOGGER.info(f"Zip: orig_path: {dl_path}, zip_path: {up_path}.0*")
434
+ else:
435
+ del cmd[1]
436
+ if not pswd:
437
+ del cmd[3]
438
+ LOGGER.info(f"Zip: orig_path: {dl_path}, zip_path: {up_path}")
439
+ if self._listener.is_cancelled:
440
+ return False
441
+ self._listener.subproc = await create_subprocess_exec(
442
+ *cmd, stdout=PIPE, stderr=PIPE
443
+ )
444
+ await self._sevenz_progress()
445
+ _, stderr = await self._listener.subproc.communicate()
446
+ code = self._listener.subproc.returncode
447
+ if self._listener.is_cancelled:
448
+ return False
449
+ if code == -9:
450
+ self._listener.is_cancelled = True
451
+ return False
452
+ elif code == 0:
453
+ await clean_target(dl_path)
454
+ return up_path
455
+ else:
456
+ if await aiopath.exists(up_path):
457
+ await remove(up_path)
458
+ try:
459
+ stderr = stderr.decode().strip()
460
+ except:
461
+ stderr = "Unable to decode the error!"
462
+ LOGGER.error(f"{stderr}. Unable to zip this path: {dl_path}")
463
+ return dl_path
bot/helper/ext_utils/help_messages.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..telegram_helper.bot_commands import BotCommands
2
+ from ...core.telegram_manager import TgClient
3
+
4
+ mirror = """<b>Send link along with command line or </b>
5
+
6
+ /cmd link
7
+
8
+ <b>By replying to link/file</b>:
9
+
10
+ /cmd -n new name -e -up upload destination
11
+
12
+ <b>NOTE:</b>
13
+ 1. Commands that start with <b>qb</b> are ONLY for torrents."""
14
+
15
+ yt = """<b>Send link along with command line</b>:
16
+
17
+ /cmd link
18
+ <b>By replying to link</b>:
19
+ /cmd -n new name -z password -opt x:y|x1:y1
20
+
21
+ Check here all supported <a href='https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md'>SITES</a>
22
+ Check all yt-dlp api options from this <a href='https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py#L212'>FILE</a> or use this <a href='https://t.me/mltb_official_channel/177'>script</a> to convert cli arguments to api options."""
23
+
24
+ clone = """Send Gdrive|Gdot|Filepress|Filebee|Appdrive|Gdflix link or rclone path along with command or by replying to the link/rc_path by command.
25
+ Use -sync to use sync method in rclone. Example: /cmd rcl/rclone_path -up rcl/rclone_path/rc -sync"""
26
+
27
+ new_name = """<b>New Name</b>: -n
28
+
29
+ /cmd link -n new name
30
+ Note: Doesn't work with torrents"""
31
+
32
+ multi_link = """<b>Multi links only by replying to first link/file</b>: -i
33
+
34
+ /cmd -i 10(number of links/files)"""
35
+
36
+ same_dir = """<b>Move file(s)/folder(s) to new folder</b>: -m
37
+
38
+ You can use this arg also to move multiple links/torrents contents to the same directory, so all links will be uploaded together as one task
39
+
40
+ /cmd link -m new folder (only one link inside new folder)
41
+ /cmd -i 10(number of links/files) -m folder name (all links contents in one folder)
42
+ /cmd -b -m folder name (reply to batch of message/file(each link on new line))
43
+
44
+ While using bulk you can also use this arg with different folder name along with the links in message or file batch
45
+ Example:
46
+ link1 -m folder1
47
+ link2 -m folder1
48
+ link3 -m folder2
49
+ link4 -m folder2
50
+ link5 -m folder3
51
+ link6
52
+ so link1 and link2 content will be uploaded from same folder which is folder1
53
+ link3 and link4 content will be uploaded from same folder also which is folder2
54
+ link5 will uploaded alone inside new folder named folder3
55
+ link6 will get uploaded normally alone
56
+ """
57
+
58
+ thumb = """<b>Thumbnail for current task</b>: -t
59
+
60
+ /cmd link -t tg-message-link (doc or photo) or none (file without thumb)"""
61
+
62
+ split_size = """<b>Split size for current task</b>: -sp
63
+
64
+ /cmd link -sp (500mb or 2gb or 4000000000)
65
+ Note: Only mb and gb are supported or write in bytes without unit!"""
66
+
67
+ upload = """<b>Upload Destination</b>: -up
68
+
69
+ /cmd link -up rcl/gdl (rcl: to select rclone config, remote & path | gdl: To select token.pickle, gdrive id) using buttons
70
+ You can directly add the upload path: -up remote:dir/subdir or -up Gdrive_id or -up id/username (telegram) or -up id/username|topic_id (telegram)
71
+ If DEFAULT_UPLOAD is `rc` then you can pass up: `gd` to upload using gdrive tools to GDRIVE_ID.
72
+ If DEFAULT_UPLOAD is `gd` then you can pass up: `rc` to upload to RCLONE_PATH.
73
+
74
+ If you want to add path or gdrive manually from your config/token (UPLOADED FROM USETTING) add mrcc: for rclone and mtp: before the path/gdrive_id without space.
75
+ /cmd link -up mrcc:main:dump or -up mtp:gdrive_id <strong>or you can simply edit upload using owner/user token/config from usetting without adding mtp: or mrcc: before the upload path/id</strong>
76
+
77
+ To add leech destination:
78
+ -up id/@username/pm
79
+ -up b:id/@username/pm (b: means leech by bot) (id or username of the chat or write pm means private message so bot will send the files in private to you)
80
+ when you should use b:(leech by bot)? When your default settings is leech by user and you want to leech by bot for specific task.
81
+ -up u:id/@username(u: means leech by user) This incase OWNER added USER_STRING_SESSION.
82
+ -up h:id/@username(hybrid leech) h: to upload files by bot and user based on file size.
83
+ -up id/@username|topic_id(leech in specific chat and topic) add | without space and write topic id after chat id or username.
84
+
85
+ In case you want to specify whether using token.pickle or service accounts you can add tp:gdrive_id (using token.pickle) or sa:gdrive_id (using service accounts) or mtp:gdrive_id (using token.pickle uploaded from usetting).
86
+ DEFAULT_UPLOAD doesn't affect on leech cmds.
87
+ """
88
+
89
+ user_download = """<b>User Download</b>: link
90
+
91
+ /cmd tp:link to download using owner token.pickle incase service account enabled.
92
+ /cmd sa:link to download using service account incase service account disabled.
93
+ /cmd tp:gdrive_id to download using token.pickle and file_id incase service account enabled.
94
+ /cmd sa:gdrive_id to download using service account and file_id incase service account disabled.
95
+ /cmd mtp:gdrive_id or mtp:link to download using user token.pickle uploaded from usetting
96
+ /cmd mrcc:remote:path to download using user rclone config uploaded from usetting
97
+ you can simply edit upload using owner/user token/config from usetting without adding mtp: or mrcc: before the path/id"""
98
+
99
+ rcf = """<b>Rclone Flags</b>: -rcf
100
+
101
+ /cmd link|path|rcl -up path|rcl -rcf --buffer-size:8M|--drive-starred-only|key|key:value
102
+ This will override all other flags except --exclude
103
+ Check here all <a href='https://rclone.org/flags/'>RcloneFlags</a>."""
104
+
105
+ bulk = """<b>Bulk Download</b>: -b
106
+
107
+ Bulk can be used only by replying to text message or text file contains links separated by new line.
108
+ Example:
109
+ link1 -n new name -up remote1:path1 -rcf |key:value|key:value
110
+ link2 -z -n new name -up remote2:path2
111
+ link3 -e -n new name -up remote2:path2
112
+ Reply to this example by this cmd -> /cmd -b(bulk)
113
+
114
+ Note: Any arg along with the cmd will be setted to all links
115
+ /cmd -b -up remote: -z -m folder name (all links contents in one zipped folder uploaded to one destination)
116
+ so you can't set different upload destinations along with link incase you have added -m along with cmd
117
+ You can set start and end of the links from the bulk like seed, with -b start:end or only end by -b :end or only start by -b start.
118
+ The default start is from zero(first link) to inf."""
119
+
120
+ rlone_dl = """<b>Rclone Download</b>:
121
+
122
+ Treat rclone paths exactly like links
123
+ /cmd main:dump/ubuntu.iso or rcl(To select config, remote and path)
124
+ Users can add their own rclone from user settings
125
+ If you want to add path manually from your config add mrcc: before the path without space
126
+ /cmd mrcc:main:dump/ubuntu.iso
127
+ You can simply edit using owner/user config from usetting without adding mrcc: before the path"""
128
+
129
+ extract_zip = """<b>Extract/Zip</b>: -e -z
130
+
131
+ /cmd link -e password (extract password protected)
132
+ /cmd link -z password (zip password protected)
133
+ /cmd link -z password -e (extract and zip password protected)
134
+ Note: When both extract and zip added with cmd it will extract first and then zip, so always extract first"""
135
+
136
+ join = """<b>Join Splitted Files</b>: -j
137
+
138
+ This option will only work before extract and zip, so mostly it will be used with -m argument (samedir)
139
+ By Reply:
140
+ /cmd -i 3 -j -m folder name
141
+ /cmd -b -j -m folder name
142
+ if u have link(folder) have splitted files:
143
+ /cmd link -j"""
144
+
145
+ tg_links = """<b>TG Links</b>:
146
+
147
+ Treat links like any direct link
148
+ Some links need user access so you must add USER_SESSION_STRING for it.
149
+ Three types of links:
150
+ Public: https://t.me/channel_name/message_id
151
+ Private: tg://openmessage?user_id=xxxxxx&message_id=xxxxx
152
+ Super: https://t.me/c/channel_id/message_id
153
+ Range: https://t.me/channel_name/first_message_id-last_message_id
154
+ Range Example: tg://openmessage?user_id=xxxxxx&message_id=555-560 or https://t.me/channel_name/100-150
155
+ Note: Range link will work only by replying cmd to it"""
156
+
157
+ sample_video = """<b>Sample Video</b>: -sv
158
+
159
+ Create sample video for one video or folder of videos.
160
+ /cmd -sv (it will take the default values which 60sec sample duration and part duration is 4sec).
161
+ You can control those values. Example: /cmd -sv 70:5(sample-duration:part-duration) or /cmd -sv :5 or /cmd -sv 70."""
162
+
163
+ screenshot = """<b>ScreenShots</b>: -ss
164
+
165
+ Create screenshots for one video or folder of videos.
166
+ /cmd -ss (it will take the default values which is 10 photos).
167
+ You can control this value. Example: /cmd -ss 6."""
168
+
169
+ seed = """<b>Bittorrent seed</b>: -d
170
+
171
+ /cmd link -d ratio:seed_time or by replying to file/link
172
+ To specify ratio and seed time add -d ratio:time.
173
+ Example: -d 0.7:10 (ratio and time) or -d 0.7 (only ratio) or -d :10 (only time) where time in minutes"""
174
+
175
+ zip_arg = """<b>Zip</b>: -z password
176
+
177
+ /cmd link -z (zip)
178
+ /cmd link -z password (zip password protected)"""
179
+
180
+ qual = """<b>Quality Buttons</b>: -s
181
+
182
+ In case default quality added from yt-dlp options using format option and you need to select quality for specific link or links with multi links feature.
183
+ /cmd link -s"""
184
+
185
+ yt_opt = """<b>Options</b>: -opt
186
+
187
+ /cmd link -opt {"format": "bv*+mergeall[vcodec=none]", "nocheckcertificate": True, "playliststart": 10, "fragment_retries": float("inf"), "matchtitle": "S13", "writesubtitles": True, "live_from_start": True, "postprocessor_args": {"ffmpeg": ["-threads", "4"]}, "wait_for_video": (5, 100), "download_ranges": [{"start_time": 0, "end_time": 10}]}
188
+
189
+ Check all yt-dlp api options from this <a href='https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py#L184'>FILE</a> or use this <a href='https://t.me/mltb_official_channel/177'>script</a> to convert cli arguments to api options."""
190
+
191
+ convert_media = """<b>Convert Media</b>: -ca -cv
192
+ /cmd link -ca mp3 -cv mp4 (convert all audios to mp3 and all videos to mp4)
193
+ /cmd link -ca mp3 (convert all audios to mp3)
194
+ /cmd link -cv mp4 (convert all videos to mp4)
195
+ /cmd link -ca mp3 + flac ogg (convert only flac and ogg audios to mp3)
196
+ /cmd link -cv mkv - webm flv (convert all videos to mp4 except webm and flv)"""
197
+
198
+ force_start = """<b>Force Start</b>: -f -fd -fu
199
+ /cmd link -f (force download and upload)
200
+ /cmd link -fd (force download only)
201
+ /cmd link -fu (force upload directly after download finish)"""
202
+
203
+ gdrive = """<b>Gdrive</b>: link
204
+ If DEFAULT_UPLOAD is `rc` then you can pass up: `gd` to upload using gdrive tools to GDRIVE_ID.
205
+ /cmd gdriveLink or gdl or gdriveId -up gdl or gdriveId or gd
206
+ /cmd tp:gdriveLink or tp:gdriveId -up tp:gdriveId or gdl or gd (to use token.pickle if service account enabled)
207
+ /cmd sa:gdriveLink or sa:gdriveId -p sa:gdriveId or gdl or gd (to use service account if service account disabled)
208
+ /cmd mtp:gdriveLink or mtp:gdriveId -up mtp:gdriveId or gdl or gd(if you have added upload gdriveId from usetting) (to use user token.pickle that uploaded by usetting)
209
+ You can simply edit using owner/user token from usetting without adding mtp: before the id"""
210
+
211
+ rclone_cl = """<b>Rclone</b>: path
212
+ If DEFAULT_UPLOAD is `gd` then you can pass up: `rc` to upload to RCLONE_PATH.
213
+ /cmd rcl/rclone_path -up rcl/rclone_path/rc -rcf flagkey:flagvalue|flagkey|flagkey:flagvalue
214
+ /cmd rcl or rclone_path -up rclone_path or rc or rcl
215
+ /cmd mrcc:rclone_path -up rcl or rc(if you have add rclone path from usetting) (to use user config)
216
+ You can simply edit using owner/user config from usetting without adding mrcc: before the path"""
217
+
218
+ name_sub = r"""<b>Name Substitution</b>: -ns
219
+ /cmd link -ns script/code/s | mirror/leech | tea/ /s | clone | cpu/ | \[mltb\]/mltb | \\text\\/text/s
220
+ This will affect on all files. Format: wordToReplace/wordToReplaceWith/sensitiveCase
221
+ Word Subtitions. You can add pattern instead of normal text. Timeout: 60 sec
222
+ NOTE: You must add \ before any character, those are the characters: \^$.|?*+()[]{}-
223
+ 1. script will get replaced by code with sensitive case
224
+ 2. mirror will get replaced by leech
225
+ 4. tea will get replaced by space with sensitive case
226
+ 5. clone will get removed
227
+ 6. cpu will get replaced by space
228
+ 7. [mltb] will get replaced by mltb
229
+ 8. \text\ will get replaced by text with sensitive case
230
+ """
231
+
232
+ transmission = """<b>Tg transmission</b>: -hl -ut -bt
233
+ /cmd link -hl (leech by user and bot session with respect to size) (Hybrid Leech)
234
+ /cmd link -bt (leech by bot session)
235
+ /cmd link -ut (leech by user)"""
236
+
237
+ thumbnail_layout = """Thumbnail Layout: -tl
238
+ /cmd link -tl 3x3 (widthxheight) 3 photos in row and 3 photos in column"""
239
+
240
+ leech_as = """<b>Leech as</b>: -doc -med
241
+ /cmd link -doc (Leech as document)
242
+ /cmd link -med (Leech as media)"""
243
+
244
+ ffmpeg_cmds = """<b>FFmpeg Commands</b>: -ff
245
+ list of lists of ffmpeg commands. You can set multiple ffmpeg commands for all files before upload. Don't write ffmpeg at beginning, start directly with the arguments.
246
+ Notes:
247
+ 1. Add <code>-del</code> to the list(s) which you want from the bot to delete the original files after command run complete!
248
+ 3. To execute one of pre-added lists in bot like: ({"subtitle": ["-i mltb.mkv -c copy -c:s srt mltb.mkv"]}), you must use -ff subtitle (list key)
249
+ Examples: ["-i mltb.mkv -c copy -c:s srt mltb.mkv", "-i mltb.video -c copy -c:s srt mltb", "-i mltb.m4a -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb.audio -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb -map 0:a -c copy mltb.mka -map 0:s -c copy mltb.srt", "-i mltb -i tg://openmessage?user_id=5272663208&message_id=322801 -filter_complex 'overlay=W-w-10:H-h-10' -c:a copy mltb"]
250
+ Here I will explain how to use mltb.* which is reference to files you want to work on.
251
+ 1. First cmd: the input is mltb.mkv so this cmd will work only on mkv videos and the output is mltb.mkv also so all outputs is mkv. -del will delete the original media after complete run of the cmd.
252
+ 2. Second cmd: the input is mltb.video so this cmd will work on all videos and the output is only mltb so the extension is same as input files.
253
+ 3. Third cmd: the input in mltb.m4a so this cmd will work only on m4a audios and the output is mltb.mp3 so the output extension is mp3.
254
+ 4. Fourth cmd: the input is mltb.audio so this cmd will work on all audios and the output is mltb.mp3 so the output extension is mp3.
255
+ 5. Fifth cmd: You can add telegram link for small size input like photo to set watermark"""
256
+
257
+ YT_HELP_DICT = {
258
+ "main": yt,
259
+ "New-Name": f"{new_name}\nNote: Don't add file extension",
260
+ "Zip": zip_arg,
261
+ "Quality": qual,
262
+ "Options": yt_opt,
263
+ "Multi-Link": multi_link,
264
+ "Same-Directory": same_dir,
265
+ "Thumb": thumb,
266
+ "Split-Size": split_size,
267
+ "Upload-Destination": upload,
268
+ "Rclone-Flags": rcf,
269
+ "Bulk": bulk,
270
+ "Sample-Video": sample_video,
271
+ "Screenshot": screenshot,
272
+ "Convert-Media": convert_media,
273
+ "Force-Start": force_start,
274
+ "Name-Substitute": name_sub,
275
+ "TG-Transmission": transmission,
276
+ "Thumb-Layout": thumbnail_layout,
277
+ "Leech-Type": leech_as,
278
+ "FFmpeg-Cmds": ffmpeg_cmds,
279
+ }
280
+
281
+ MIRROR_HELP_DICT = {
282
+ "main": mirror,
283
+ "New-Name": new_name,
284
+ "DL-Auth": "<b>Direct link authorization</b>: -au -ap\n\n/cmd link -au username -ap password",
285
+ "Headers": "<b>Direct link custom headers</b>: -h\n\n/cmd link -h key:value|key1:value1",
286
+ "Extract/Zip": extract_zip,
287
+ "Select-Files": "<b>Bittorrent/JDownloader/Sabnzbd File Selection</b>: -s\n\n/cmd link -s or by replying to file/link",
288
+ "Torrent-Seed": seed,
289
+ "Multi-Link": multi_link,
290
+ "Same-Directory": same_dir,
291
+ "Thumb": thumb,
292
+ "Split-Size": split_size,
293
+ "Upload-Destination": upload,
294
+ "Rclone-Flags": rcf,
295
+ "Bulk": bulk,
296
+ "Join": join,
297
+ "Rclone-DL": rlone_dl,
298
+ "Tg-Links": tg_links,
299
+ "Sample-Video": sample_video,
300
+ "Screenshot": screenshot,
301
+ "Convert-Media": convert_media,
302
+ "Force-Start": force_start,
303
+ "User-Download": user_download,
304
+ "Name-Substitute": name_sub,
305
+ "TG-Transmission": transmission,
306
+ "Thumb-Layout": thumbnail_layout,
307
+ "Leech-Type": leech_as,
308
+ "FFmpeg-Cmds": ffmpeg_cmds,
309
+ }
310
+
311
+ CLONE_HELP_DICT = {
312
+ "main": clone,
313
+ "Multi-Link": multi_link,
314
+ "Bulk": bulk,
315
+ "Gdrive": gdrive,
316
+ "Rclone": rclone_cl,
317
+ }
318
+
319
+ RSS_HELP_MESSAGE = """
320
+ Use this format to add feed url:
321
+ Title1 link (required)
322
+ Title2 link -c cmd -inf xx -exf xx
323
+ Title3 link -c cmd -d ratio:time -z password
324
+
325
+ -c command -up mrcc:remote:path/subdir -rcf --buffer-size:8M|key|key:value
326
+ -inf For included words filter.
327
+ -exf For excluded words filter.
328
+ -stv true or false (sensitive filter)
329
+
330
+ Example: Title https://www.rss-url.com -inf 1080 or 720 or 144p|mkv or mp4|hevc -exf flv or web|xxx
331
+ This filter will parse links that its titles contain `(1080 or 720 or 144p) and (mkv or mp4) and hevc` and doesn't contain (flv or web) and xxx words. You can add whatever you want.
332
+
333
+ Another example: -inf 1080 or 720p|.web. or .webrip.|hvec or x264. This will parse titles that contain ( 1080 or 720p) and (.web. or .webrip.) and (hvec or x264). I have added space before and after 1080 to avoid wrong matching. If this `10805695` number in title it will match 1080 if added 1080 without spaces after it.
334
+
335
+ Filter Notes:
336
+ 1. | means and.
337
+ 2. Add `or` between similar keys, you can add it between qualities or between extensions, so don't add filter like this f: 1080|mp4 or 720|web because this will parse 1080 and (mp4 or 720) and web ... not (1080 and mp4) or (720 and web).
338
+ 3. You can add `or` and `|` as much as you want.
339
+ 4. Take a look at the title if it has a static special character after or before the qualities or extensions or whatever and use them in the filter to avoid wrong match.
340
+ Timeout: 60 sec.
341
+ """
342
+
343
+ PASSWORD_ERROR_MESSAGE = """
344
+ <b>This link requires a password!</b>
345
+ - Insert <b>::</b> after the link and write the password after the sign.
346
+
347
+ <b>Example:</b> link::my password
348
+ """
349
+
350
+ user_settings_text = {
351
+ "LEECH_SPLIT_SIZE": f"Send Leech split size in bytes or use gb or mb. Example: 40000000 or 2.5gb or 1000mb. IS_PREMIUM_USER: {TgClient.IS_PREMIUM_USER}. Timeout: 60 sec",
352
+ "LEECH_DUMP_CHAT": """Send leech destination ID/USERNAME/PM.
353
+ * b:id/@username/pm (b: means leech by bot) (id or username of the chat or write pm means private message so bot will send the files in private to you) when you should use b:(leech by bot)? When your default settings is leech by user and you want to leech by bot for specific task.
354
+ * u:id/@username(u: means leech by user) This incase OWNER added USER_STRING_SESSION.
355
+ * h:id/@username(hybrid leech) h: to upload files by bot and user based on file size.
356
+ * id/@username|topic_id(leech in specific chat and topic) add | without space and write topic id after chat id or username. Timeout: 60 sec""",
357
+ "LEECH_FILENAME_PREFIX": r"Send Leech Filename Prefix. You can add HTML tags. Example: <code>@mychannel</code>. Timeout: 60 sec",
358
+ "THUMBNAIL_LAYOUT": "Send thumbnail layout (widthxheight, 2x2, 3x3, 2x4, 4x4, ...). Example: 3x3. Timeout: 60 sec",
359
+ "RCLONE_PATH": "Send Rclone Path. If you want to use your rclone config edit using owner/user config from usetting or add mrcc: before rclone path. Example mrcc:remote:folder. Timeout: 60 sec",
360
+ "RCLONE_FLAGS": "key:value|key|key|key:value . Check here all <a href='https://rclone.org/flags/'>RcloneFlags</a>\nEx: --buffer-size:8M|--drive-starred-only",
361
+ "GDRIVE_ID": "Send Gdrive ID. If you want to use your token.pickle edit using owner/user token from usetting or add mtp: before the id. Example: mtp:F435RGGRDXXXXXX . Timeout: 60 sec",
362
+ "INDEX_URL": "Send Index URL. Timeout: 60 sec",
363
+ "UPLOAD_PATHS": "Send Dict of keys that have path values. Example: {'path 1': 'remote:rclonefolder', 'path 2': 'gdrive1 id', 'path 3': 'tg chat id', 'path 4': 'mrcc:remote:', 'path 5': b:@username} . Timeout: 60 sec",
364
+ "EXCLUDED_EXTENSIONS": "Send excluded extensions separated by space without dot at beginning. Timeout: 60 sec",
365
+ "INCLUDED_EXTENSIONS": "Send included extensions separated by space without dot at beginning. Timeout: 60 sec",
366
+ "NAME_SUBSTITUTE": r"""Word Subtitions. You can add pattern instead of normal text. Timeout: 60 sec
367
+ NOTE: You must add \ before any character, those are the characters: \^$.|?*+()[]{}-
368
+ Example: script/code/s | mirror/leech | tea/ /s | clone | cpu/ | \[mltb\]/mltb | \\text\\/text/s
369
+ 1. script will get replaced by code with sensitive case
370
+ 2. mirror will get replaced by leech
371
+ 4. tea will get replaced by space with sensitive case
372
+ 5. clone will get removed
373
+ 6. cpu will get replaced by space
374
+ 7. [mltb] will get replaced by mltb
375
+ 8. \text\ will get replaced by text with sensitive case
376
+ """,
377
+ "YT_DLP_OPTIONS": """Send dict of YT-DLP Options. Timeout: 60 sec
378
+ Format: {key: value, key: value, key: value}.
379
+ Example: {"format": "bv*+mergeall[vcodec=none]", "nocheckcertificate": True, "playliststart": 10, "fragment_retries": float("inf"), "matchtitle": "S13", "writesubtitles": True, "live_from_start": True, "postprocessor_args": {"ffmpeg": ["-threads", "4"]}, "wait_for_video": (5, 100), "download_ranges": [{"start_time": 0, "end_time": 10}]}
380
+ Check all yt-dlp api options from this <a href='https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py#L184'>FILE</a> or use this <a href='https://t.me/mltb_official_channel/177'>script</a> to convert cli arguments to api options.""",
381
+ "FFMPEG_CMDS": """Dict of list values of ffmpeg commands. You can set multiple ffmpeg commands for all files before upload. Don't write ffmpeg at beginning, start directly with the arguments.
382
+ Examples: {"subtitle": ["-i mltb.mkv -c copy -c:s srt mltb.mkv", "-i mltb.video -c copy -c:s srt mltb"], "convert": ["-i mltb.m4a -c:a libmp3lame -q:a 2 mltb.mp3", "-i mltb.audio -c:a libmp3lame -q:a 2 mltb.mp3"], "extract": ["-i mltb -map 0:a -c copy mltb.mka -map 0:s -c copy mltb.srt"], "metadata": ["-i mltb.mkv -map 0 -map -0:v:1 -map -0:s -map 0:s:0 -map -0:v:m:attachment -c copy -metadata:s:v:0 title={title} -metadata:s:a:0 title={title} -metadata:s:a:1 title={title2} -metadata:s:a:2 title={title2} -c:s srt -metadata:s:s:0 title={title3} mltb -y -del"], "watermark": ["-i mltb -i tg://openmessage?user_id=5272663208&message_id=322801 -filter_complex 'overlay=W-w-10:H-h-10' -c:a copy mltb"]}
383
+ Notes:
384
+ - Add `-del` to the list which you want from the bot to delete the original files after command run complete!
385
+ - To execute one of those lists in bot for example, you must use -ff subtitle (list key) or -ff convert (list key)
386
+ Here I will explain how to use mltb.* which is reference to files you want to work on.
387
+ 1. First cmd: the input is mltb.mkv so this cmd will work only on mkv videos and the output is mltb.mkv also so all outputs is mkv. -del will delete the original media after complete run of the cmd.
388
+ 2. Second cmd: the input is mltb.video so this cmd will work on all videos and the output is only mltb so the extension is same as input files.
389
+ 3. Third cmd: the input in mltb.m4a so this cmd will work only on m4a audios and the output is mltb.mp3 so the output extension is mp3.
390
+ 4. Fourth cmd: the input is mltb.audio so this cmd will work on all audios and the output is mltb.mp3 so the output extension is mp3.
391
+ 5. FFmpeg Variables in last cmd which is metadata ({title}, {title2}, etc...), you can edit them in usetting
392
+ 6. Telegram link for small size inputs like photo to set watermark.""",
393
+ "CLONE_DUMP_CHATS": "Send List/Int/Str Chat_id/username|thread_id. Example: -100xxxx555|5 or @dumpchat|8 or @mltb_dump or pm or List like: [-100xxx885552|6, '@username', 65585541254, 'pm']",
394
+ }
395
+
396
+
397
+ help_string = f"""
398
+ NOTE: Try each command without any argument to see more detalis.
399
+ /{BotCommands.MirrorCommand[0]} or /{BotCommands.MirrorCommand[1]}: Start mirroring to cloud.
400
+ /{BotCommands.QbMirrorCommand[0]} or /{BotCommands.QbMirrorCommand[1]}: Start Mirroring to cloud using qBittorrent.
401
+ /{BotCommands.JdMirrorCommand[0]} or /{BotCommands.JdMirrorCommand[1]}: Start Mirroring to cloud using JDownloader.
402
+ /{BotCommands.NzbMirrorCommand[0]} or /{BotCommands.NzbMirrorCommand[1]}: Start Mirroring to cloud using Sabnzbd.
403
+ /{BotCommands.YtdlCommand[0]} or /{BotCommands.YtdlCommand[1]}: Mirror yt-dlp supported link.
404
+ /{BotCommands.LeechCommand[0]} or /{BotCommands.LeechCommand[1]}: Start leeching to Telegram.
405
+ /{BotCommands.QbLeechCommand[0]} or /{BotCommands.QbLeechCommand[1]}: Start leeching using qBittorrent.
406
+ /{BotCommands.JdLeechCommand[0]} or /{BotCommands.JdLeechCommand[1]}: Start leeching using JDownloader.
407
+ /{BotCommands.NzbLeechCommand[0]} or /{BotCommands.NzbLeechCommand[1]}: Start leeching using Sabnzbd.
408
+ /{BotCommands.YtdlLeechCommand[0]} or /{BotCommands.YtdlLeechCommand[1]}: Leech yt-dlp supported link.
409
+ /{BotCommands.CloneCommand} [drive_url]: Copy file/folder to Google Drive.
410
+ /{BotCommands.CountCommand} [drive_url]: Count file/folder of Google Drive.
411
+ /{BotCommands.DeleteCommand} [drive_url]: Delete file/folder from Google Drive (Only Owner & Sudo).
412
+ /{BotCommands.UserSetCommand[0]} or /{BotCommands.UserSetCommand[1]} [query]: Users settings.
413
+ /{BotCommands.BotSetCommand[0]} or /{BotCommands.BotSetCommand[1]} [query]: Bot settings.
414
+ /{BotCommands.SelectCommand}: Select files from torrents or nzb by gid or reply.
415
+ /{BotCommands.CancelTaskCommand[0]} or /{BotCommands.CancelTaskCommand[1]} [gid]: Cancel task by gid or reply.
416
+ /{BotCommands.ForceStartCommand[0]} or /{BotCommands.ForceStartCommand[1]} [gid]: Force start task by gid or reply.
417
+ /{BotCommands.CancelAllCommand} [query]: Cancel all [status] tasks.
418
+ /{BotCommands.ListCommand} [query]: Search in Google Drive(s).
419
+ /{BotCommands.SearchCommand} [query]: Search for torrents with API.
420
+ /{BotCommands.StatusCommand}: Shows a status of all the downloads.
421
+ /{BotCommands.StatsCommand}: Show stats of the machine where the bot is hosted in.
422
+ /{BotCommands.PingCommand}: Check how long it takes to Ping the Bot (Only Owner & Sudo).
423
+ /{BotCommands.AuthorizeCommand}: Authorize a chat or a user to use the bot (Only Owner & Sudo).
424
+ /{BotCommands.UnAuthorizeCommand}: Unauthorize a chat or a user to use the bot (Only Owner & Sudo).
425
+ /{BotCommands.UsersCommand}: show users settings (Only Owner & Sudo).
426
+ /{BotCommands.AddSudoCommand}: Add sudo user (Only Owner).
427
+ /{BotCommands.RmSudoCommand}: Remove sudo users (Only Owner).
428
+ /{BotCommands.RestartCommand}: Restart and update the bot (Only Owner & Sudo).
429
+ /{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports (Only Owner & Sudo).
430
+ /{BotCommands.ShellCommand}: Run shell commands (Only Owner).
431
+ /{BotCommands.AExecCommand}: Exec async functions (Only Owner).
432
+ /{BotCommands.ExecCommand}: Exec sync functions (Only Owner).
433
+ /{BotCommands.ClearLocalsCommand}: Clear {BotCommands.AExecCommand} or {BotCommands.ExecCommand} locals (Only Owner).
434
+ /{BotCommands.RssCommand}: RSS Menu.
435
+ """
bot/helper/ext_utils/links_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from re import match as re_match
2
+
3
+
4
+ def is_magnet(url: str):
5
+ return bool(re_match(r"^magnet:\?.*xt=urn:(btih|btmh):([a-zA-Z0-9]{32,40}|[a-z2-7]{32}).*", url))
6
+
7
+
8
+ def is_url(url: str):
9
+ return bool(
10
+ re_match(
11
+ r"^(?!\/)(rtmps?:\/\/|mms:\/\/|rtsp:\/\/|https?:\/\/|ftp:\/\/)?([^\/:]+:[^\/@]+@)?(www\.)?(?=[^\/:\s]+\.[^\/:\s]+)([^\/:\s]+\.[^\/:\s]+)(:\d+)?(\/[^#\s]*[\s\S]*)?(\?[^#\s]*)?(#.*)?$",
12
+ url,
13
+ )
14
+ )
15
+
16
+
17
+ def is_gdrive_link(url: str):
18
+ return "drive.google.com" in url or "drive.usercontent.google.com" in url
19
+
20
+
21
+ def is_telegram_link(url: str):
22
+ return url.startswith(("https://t.me/", "tg://openmessage?user_id="))
23
+
24
+
25
+ def is_share_link(url: str):
26
+ return bool(
27
+ re_match(
28
+ r"https?:\/\/.+\.gdtot\.\S+|https?:\/\/(filepress|filebee|appdrive|gdflix)\.\S+",
29
+ url,
30
+ )
31
+ )
32
+
33
+
34
+ def is_rclone_path(path: str):
35
+ return bool(
36
+ re_match(
37
+ r"^(mrcc:)?(?!(magnet:|mtp:|sa:|tp:))(?![- ])[a-zA-Z0-9_\. -]+(?<! ):(?!.*\/\/).*$|^rcl$",
38
+ path,
39
+ )
40
+ )
41
+
42
+
43
+ def is_gdrive_id(id_: str):
44
+ return bool(
45
+ re_match(
46
+ r"^(tp:|sa:|mtp:)?(?:[a-zA-Z0-9-_]{33}|[a-zA-Z0-9_-]{19})$|^gdl$|^(tp:|mtp:)?root$",
47
+ id_,
48
+ )
49
+ )
bot/helper/ext_utils/media_utils.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from aiofiles.os import remove, path as aiopath, makedirs
3
+ from asyncio import (
4
+ create_subprocess_exec,
5
+ gather,
6
+ wait_for,
7
+ )
8
+ from asyncio.subprocess import PIPE
9
+ from os import path as ospath
10
+ from re import search as re_search, escape
11
+ from time import time
12
+ from aioshutil import rmtree
13
+
14
+ from ... import LOGGER, DOWNLOAD_DIR, threads, cores
15
+ from .bot_utils import cmd_exec, sync_to_async
16
+ from .files_utils import get_mime_type, is_archive, is_archive_split
17
+ from .status_utils import time_to_seconds
18
+
19
+
20
+ async def create_thumb(msg, _id=""):
21
+ if not _id:
22
+ _id = time()
23
+ path = f"{DOWNLOAD_DIR}thumbnails"
24
+ else:
25
+ path = "thumbnails"
26
+ await makedirs(path, exist_ok=True)
27
+ photo_dir = await msg.download()
28
+ output = ospath.join(path, f"{_id}.jpg")
29
+ await sync_to_async(Image.open(photo_dir).convert("RGB").save, output, "JPEG")
30
+ await remove(photo_dir)
31
+ return output
32
+
33
+
34
+ def ffconcat_escape(path):
35
+ return path.replace("'", r"'\''")
36
+
37
+
38
+ async def get_media_info(path):
39
+ try:
40
+ result = await cmd_exec(
41
+ [
42
+ "ffprobe",
43
+ "-hide_banner",
44
+ "-loglevel",
45
+ "error",
46
+ "-print_format",
47
+ "json",
48
+ "-show_format",
49
+ path,
50
+ ]
51
+ )
52
+ except Exception as e:
53
+ LOGGER.error(f"Get Media Info: {e}. Mostly File not found! - File: {path}")
54
+ return 0, None, None
55
+ if result[0] and result[2] == 0:
56
+ fields = eval(result[0]).get("format")
57
+ if fields is None:
58
+ LOGGER.error(f"get_media_info: {result}")
59
+ return 0, None, None
60
+ duration = round(float(fields.get("duration", 0)))
61
+ tags = fields.get("tags", {})
62
+ artist = tags.get("artist") or tags.get("ARTIST") or tags.get("Artist")
63
+ title = tags.get("title") or tags.get("TITLE") or tags.get("Title")
64
+ return duration, artist, title
65
+ return 0, None, None
66
+
67
+
68
+ async def get_document_type(path):
69
+ is_video, is_audio, is_image = False, False, False
70
+ if (
71
+ is_archive(path)
72
+ or is_archive_split(path)
73
+ or re_search(r".+(\.|_)(rar|7z|zip|bin)(\.0*\d+)?$", path)
74
+ ):
75
+ return is_video, is_audio, is_image
76
+ mime_type = await sync_to_async(get_mime_type, path)
77
+ if mime_type.startswith("image"):
78
+ return False, False, True
79
+ try:
80
+ result = await cmd_exec(
81
+ [
82
+ "ffprobe",
83
+ "-hide_banner",
84
+ "-loglevel",
85
+ "error",
86
+ "-print_format",
87
+ "json",
88
+ "-show_streams",
89
+ path,
90
+ ]
91
+ )
92
+ if result[1] and mime_type.startswith("video"):
93
+ is_video = True
94
+ except Exception as e:
95
+ LOGGER.error(f"Get Document Type: {e}. Mostly File not found! - File: {path}")
96
+ if mime_type.startswith("audio"):
97
+ return False, True, False
98
+ if not mime_type.startswith("video") and not mime_type.endswith("octet-stream"):
99
+ return is_video, is_audio, is_image
100
+ if mime_type.startswith("video"):
101
+ is_video = True
102
+ return is_video, is_audio, is_image
103
+ if result[0] and result[2] == 0:
104
+ fields = eval(result[0]).get("streams")
105
+ if fields is None:
106
+ LOGGER.error(f"get_document_type: {result}")
107
+ return is_video, is_audio, is_image
108
+ is_video = False
109
+ for stream in fields:
110
+ if stream.get("codec_type") == "video":
111
+ codec_name = stream.get("codec_name", "").lower()
112
+ if codec_name not in {"mjpeg", "png", "bmp"}:
113
+ is_video = True
114
+ elif stream.get("codec_type") == "audio":
115
+ is_audio = True
116
+ return is_video, is_audio, is_image
117
+
118
+
119
+ async def take_ss(video_file, ss_nb) -> bool:
120
+ duration = (await get_media_info(video_file))[0]
121
+ if duration != 0:
122
+ dirpath, name = video_file.rsplit("/", 1)
123
+ name, _ = ospath.splitext(name)
124
+ dirpath = f"{dirpath}/{name}_mltbss"
125
+ await makedirs(dirpath, exist_ok=True)
126
+ interval = duration // (ss_nb + 1)
127
+ cap_time = interval
128
+ cmds = []
129
+ for i in range(ss_nb):
130
+ output = f"{dirpath}/SS.{name}_{i:02}.png"
131
+ cmd = [
132
+ "taskset",
133
+ "-c",
134
+ f"{cores}",
135
+ "ffmpeg",
136
+ "-hide_banner",
137
+ "-loglevel",
138
+ "error",
139
+ "-ss",
140
+ f"{cap_time}",
141
+ "-i",
142
+ video_file,
143
+ "-q:v",
144
+ "1",
145
+ "-frames:v",
146
+ "1",
147
+ "-threads",
148
+ f"{threads}",
149
+ output,
150
+ ]
151
+ cap_time += interval
152
+ cmds.append(cmd_exec(cmd))
153
+ try:
154
+ resutls = await wait_for(gather(*cmds), timeout=60)
155
+ if resutls[0][2] != 0:
156
+ LOGGER.error(
157
+ f"Error while creating screenshots from video. Path: {video_file}. stderr: {resutls[0][1]}"
158
+ )
159
+ await rmtree(dirpath, ignore_errors=True)
160
+ return False
161
+ except:
162
+ LOGGER.error(
163
+ f"Error while creating screenshots from video. Path: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!"
164
+ )
165
+ await rmtree(dirpath, ignore_errors=True)
166
+ return False
167
+ return dirpath
168
+ else:
169
+ LOGGER.error("take_ss: Can't get the duration of video")
170
+ return False
171
+
172
+
173
+ async def get_audio_thumbnail(audio_file):
174
+ output_dir = f"{DOWNLOAD_DIR}thumbnails"
175
+ await makedirs(output_dir, exist_ok=True)
176
+ output = ospath.join(output_dir, f"{time()}.jpg")
177
+ cmd = [
178
+ "taskset",
179
+ "-c",
180
+ f"{cores}",
181
+ "ffmpeg",
182
+ "-hide_banner",
183
+ "-loglevel",
184
+ "error",
185
+ "-i",
186
+ audio_file,
187
+ "-an",
188
+ "-vcodec",
189
+ "copy",
190
+ "-threads",
191
+ f"{threads}",
192
+ output,
193
+ ]
194
+ try:
195
+ _, err, code = await wait_for(cmd_exec(cmd), timeout=60)
196
+ if code != 0 or not await aiopath.exists(output):
197
+ LOGGER.error(
198
+ f"Error while extracting thumbnail from audio. Name: {audio_file} stderr: {err}"
199
+ )
200
+ return None
201
+ except:
202
+ LOGGER.error(
203
+ f"Error while extracting thumbnail from audio. Name: {audio_file}. Error: Timeout some issues with ffmpeg with specific arch!"
204
+ )
205
+ return None
206
+ return output
207
+
208
+
209
+ async def get_video_thumbnail(video_file, duration):
210
+ output_dir = f"{DOWNLOAD_DIR}thumbnails"
211
+ await makedirs(output_dir, exist_ok=True)
212
+ output = ospath.join(output_dir, f"{time()}.jpg")
213
+ if duration is None:
214
+ duration = (await get_media_info(video_file))[0]
215
+ if duration == 0:
216
+ duration = 3
217
+ duration = duration // 2
218
+ cmd = [
219
+ "taskset",
220
+ "-c",
221
+ f"{cores}",
222
+ "ffmpeg",
223
+ "-hide_banner",
224
+ "-loglevel",
225
+ "error",
226
+ "-ss",
227
+ f"{duration}",
228
+ "-i",
229
+ video_file,
230
+ "-vf",
231
+ "thumbnail",
232
+ "-q:v",
233
+ "1",
234
+ "-frames:v",
235
+ "1",
236
+ "-threads",
237
+ f"{threads}",
238
+ output,
239
+ ]
240
+ try:
241
+ _, err, code = await wait_for(cmd_exec(cmd), timeout=60)
242
+ if code != 0 or not await aiopath.exists(output):
243
+ LOGGER.error(
244
+ f"Error while extracting thumbnail from video. Name: {video_file} stderr: {err}"
245
+ )
246
+ return None
247
+ except:
248
+ LOGGER.error(
249
+ f"Error while extracting thumbnail from video. Name: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!"
250
+ )
251
+ return None
252
+ return output
253
+
254
+
255
+ async def get_multiple_frames_thumbnail(video_file, layout, keep_screenshots):
256
+ ss_nb = layout.split("x")
257
+ ss_nb = int(ss_nb[0]) * int(ss_nb[1])
258
+ dirpath = await take_ss(video_file, ss_nb)
259
+ if not dirpath:
260
+ return None
261
+ output_dir = f"{DOWNLOAD_DIR}thumbnails"
262
+ await makedirs(output_dir, exist_ok=True)
263
+ output = ospath.join(output_dir, f"{time()}.jpg")
264
+ cmd = [
265
+ "taskset",
266
+ "-c",
267
+ f"{cores}",
268
+ "ffmpeg",
269
+ "-hide_banner",
270
+ "-loglevel",
271
+ "error",
272
+ "-pattern_type",
273
+ "glob",
274
+ "-i",
275
+ f"{escape(dirpath)}/*.png",
276
+ "-vf",
277
+ f"tile={layout}, thumbnail",
278
+ "-q:v",
279
+ "1",
280
+ "-frames:v",
281
+ "1",
282
+ "-f",
283
+ "mjpeg",
284
+ "-threads",
285
+ f"{threads}",
286
+ output,
287
+ ]
288
+ try:
289
+ _, err, code = await wait_for(cmd_exec(cmd), timeout=60)
290
+ if code != 0 or not await aiopath.exists(output):
291
+ LOGGER.error(
292
+ f"Error while combining thumbnails for video. Name: {video_file} stderr: {err}"
293
+ )
294
+ return None
295
+ except:
296
+ LOGGER.error(
297
+ f"Error while combining thumbnails from video. Name: {video_file}. Error: Timeout some issues with ffmpeg with specific arch!"
298
+ )
299
+ return None
300
+ finally:
301
+ if not keep_screenshots:
302
+ await rmtree(dirpath, ignore_errors=True)
303
+ return output
304
+
305
+
306
+ class FFMpeg:
307
+
308
+ def __init__(self, listener):
309
+ self._listener = listener
310
+ self._processed_bytes = 0
311
+ self._last_processed_bytes = 0
312
+ self._processed_time = 0
313
+ self._last_processed_time = 0
314
+ self._speed_raw = 0
315
+ self._progress_raw = 0
316
+ self._total_time = 0
317
+ self._eta_raw = 0
318
+ self._time_rate = 0.1
319
+ self._start_time = 0
320
+
321
+ @property
322
+ def processed_bytes(self):
323
+ return self._processed_bytes
324
+
325
+ @property
326
+ def speed_raw(self):
327
+ return self._speed_raw
328
+
329
+ @property
330
+ def progress_raw(self):
331
+ return self._progress_raw
332
+
333
+ @property
334
+ def eta_raw(self):
335
+ return self._eta_raw
336
+
337
+ def clear(self):
338
+ self._start_time = time()
339
+ self._processed_bytes = 0
340
+ self._processed_time = 0
341
+ self._speed_raw = 0
342
+ self._progress_raw = 0
343
+ self._eta_raw = 0
344
+ self._time_rate = 0.1
345
+ self._last_processed_time = 0
346
+ self._last_processed_bytes = 0
347
+
348
+ async def _ffmpeg_progress(self):
349
+ while not (
350
+ self._listener.subproc.returncode is not None
351
+ or self._listener.is_cancelled
352
+ or self._listener.subproc.stdout.at_eof()
353
+ ):
354
+ try:
355
+ line = await wait_for(self._listener.subproc.stdout.readline(), 60)
356
+ except:
357
+ break
358
+ line = line.decode().strip()
359
+ if not line:
360
+ break
361
+ if "=" in line:
362
+ key, value = line.split("=", 1)
363
+ if value != "N/A":
364
+ if key == "total_size":
365
+ self._processed_bytes = int(value) + self._last_processed_bytes
366
+ self._speed_raw = self._processed_bytes / (
367
+ time() - self._start_time
368
+ )
369
+ elif key == "speed":
370
+ self._time_rate = max(0.1, float(value.strip("x")))
371
+ elif key == "out_time":
372
+ self._processed_time = (
373
+ time_to_seconds(value) + self._last_processed_time
374
+ )
375
+ try:
376
+ self._progress_raw = (
377
+ self._processed_time * 100
378
+ ) / self._total_time
379
+ self._eta_raw = (
380
+ self._total_time - self._processed_time
381
+ ) / self._time_rate
382
+ except:
383
+ self._progress_raw = 0
384
+ self._eta_raw = 0
385
+
386
+ async def ffmpeg_cmds(self, ffmpeg, f_path):
387
+ self.clear()
388
+ if isinstance(f_path, list):
389
+ self._total_time = 0
390
+ for f in f_path:
391
+ self._total_time += (await get_media_info(f))[0]
392
+ base_name = ospath.commonprefix(f_path)
393
+ ext = f_path[0].rsplit(".", 1)[-1]
394
+ else:
395
+ self._total_time = (await get_media_info(f_path))[0]
396
+ base_name, ext = ospath.splitext(f_path)
397
+ dir, base_name = base_name.rsplit("/", 1)
398
+ indices = [
399
+ index
400
+ for index, item in enumerate(ffmpeg)
401
+ if (item.startswith("mltb") or item == "mltb") and item != "mltb.txt"
402
+ ]
403
+ outputs = []
404
+ for index in indices:
405
+ output_file = ffmpeg[index]
406
+ if output_file != "mltb" and output_file.startswith("mltb"):
407
+ bo, oext = ospath.splitext(output_file)
408
+ if oext:
409
+ if isinstance(f_path, list) or ext != oext:
410
+ prefix = ""
411
+ else:
412
+ prefix = f"ffmpeg{index}." if bo == "mltb" else ""
413
+ ext = ""
414
+ else:
415
+ prefix = ""
416
+ else:
417
+ prefix = f"ffmpeg{index}."
418
+ output = f"{dir}/{prefix}{output_file.replace("mltb", base_name)}{ext}"
419
+ outputs.append(output)
420
+ ffmpeg[index] = output
421
+ if self._listener.is_cancelled:
422
+ return False
423
+ self._listener.subproc = await create_subprocess_exec(
424
+ *ffmpeg, stdout=PIPE, stderr=PIPE
425
+ )
426
+ await self._ffmpeg_progress()
427
+ _, stderr = await self._listener.subproc.communicate()
428
+ code = self._listener.subproc.returncode
429
+ if self._listener.is_cancelled:
430
+ return False
431
+ if code == 0:
432
+ return outputs
433
+ elif code == -9:
434
+ self._listener.is_cancelled = True
435
+ return False
436
+ else:
437
+ try:
438
+ stderr = stderr.decode().strip()
439
+ except:
440
+ stderr = "Unable to decode the error!"
441
+ LOGGER.error(
442
+ f"{stderr}. Something went wrong while running ffmpeg cmd, mostly file requires different/specific arguments. Path: {f_path}"
443
+ )
444
+ for op in outputs:
445
+ if await aiopath.exists(op):
446
+ await remove(op)
447
+ return False
448
+
449
+ async def convert_video(self, video_file, ext, retry=False):
450
+ self.clear()
451
+ self._total_time = (await get_media_info(video_file))[0]
452
+ base_name = ospath.splitext(video_file)[0]
453
+ output = f"{base_name}.{ext}"
454
+ if retry:
455
+ cmd = [
456
+ "taskset",
457
+ "-c",
458
+ f"{cores}",
459
+ "ffmpeg",
460
+ "-hide_banner",
461
+ "-loglevel",
462
+ "error",
463
+ "-progress",
464
+ "pipe:1",
465
+ "-i",
466
+ video_file,
467
+ "-map",
468
+ "0",
469
+ "-c:v",
470
+ "libx264",
471
+ "-c:a",
472
+ "aac",
473
+ "-threads",
474
+ f"{threads}",
475
+ output,
476
+ ]
477
+ if ext == "mp4":
478
+ cmd[17:17] = ["-c:s", "mov_text"]
479
+ elif ext == "mkv":
480
+ cmd[17:17] = ["-c:s", "ass"]
481
+ else:
482
+ cmd[17:17] = ["-c:s", "copy"]
483
+ else:
484
+ cmd = [
485
+ "taskset",
486
+ "-c",
487
+ f"{cores}",
488
+ "ffmpeg",
489
+ "-hide_banner",
490
+ "-loglevel",
491
+ "error",
492
+ "-progress",
493
+ "pipe:1",
494
+ "-i",
495
+ video_file,
496
+ "-map",
497
+ "0",
498
+ "-c",
499
+ "copy",
500
+ "-threads",
501
+ f"{threads}",
502
+ output,
503
+ ]
504
+ if self._listener.is_cancelled:
505
+ return False
506
+ self._listener.subproc = await create_subprocess_exec(
507
+ *cmd, stdout=PIPE, stderr=PIPE
508
+ )
509
+ await self._ffmpeg_progress()
510
+ _, stderr = await self._listener.subproc.communicate()
511
+ code = self._listener.subproc.returncode
512
+ if self._listener.is_cancelled:
513
+ return False
514
+ if code == 0:
515
+ return output
516
+ elif code == -9:
517
+ self._listener.is_cancelled = True
518
+ return False
519
+ else:
520
+ if await aiopath.exists(output):
521
+ await remove(output)
522
+ if not retry:
523
+ return await self.convert_video(video_file, ext, True)
524
+ try:
525
+ stderr = stderr.decode().strip()
526
+ except:
527
+ stderr = "Unable to decode the error!"
528
+ LOGGER.error(
529
+ f"{stderr}. Something went wrong while converting video, mostly file need specific codec. Path: {video_file}"
530
+ )
531
+ return False
532
+
533
+ async def convert_audio(self, audio_file, ext):
534
+ self.clear()
535
+ self._total_time = (await get_media_info(audio_file))[0]
536
+ base_name = ospath.splitext(audio_file)[0]
537
+ output = f"{base_name}.{ext}"
538
+ cmd = [
539
+ "taskset",
540
+ "-c",
541
+ f"{cores}",
542
+ "ffmpeg",
543
+ "-hide_banner",
544
+ "-loglevel",
545
+ "error",
546
+ "-progress",
547
+ "pipe:1",
548
+ "-i",
549
+ audio_file,
550
+ "-threads",
551
+ f"{threads}",
552
+ output,
553
+ ]
554
+ if self._listener.is_cancelled:
555
+ return False
556
+ self._listener.subproc = await create_subprocess_exec(
557
+ *cmd, stdout=PIPE, stderr=PIPE
558
+ )
559
+ await self._ffmpeg_progress()
560
+ _, stderr = await self._listener.subproc.communicate()
561
+ code = self._listener.subproc.returncode
562
+ if self._listener.is_cancelled:
563
+ return False
564
+ if code == 0:
565
+ return output
566
+ elif code == -9:
567
+ self._listener.is_cancelled = True
568
+ return False
569
+ else:
570
+ try:
571
+ stderr = stderr.decode().strip()
572
+ except:
573
+ stderr = "Unable to decode the error!"
574
+ LOGGER.error(
575
+ f"{stderr}. Something went wrong while converting audio, mostly file need specific codec. Path: {audio_file}"
576
+ )
577
+ if await aiopath.exists(output):
578
+ await remove(output)
579
+ return False
580
+
581
+ async def sample_video(self, video_file, sample_duration, part_duration):
582
+ self.clear()
583
+ self._total_time = sample_duration
584
+ dir, name = video_file.rsplit("/", 1)
585
+ output_file = f"{dir}/SAMPLE.{name}"
586
+ segments = [(0, part_duration)]
587
+ duration = (await get_media_info(video_file))[0]
588
+ remaining_duration = duration - (part_duration * 2)
589
+ parts = (sample_duration - (part_duration * 2)) // part_duration
590
+ time_interval = remaining_duration // parts
591
+ next_segment = time_interval
592
+ for _ in range(parts):
593
+ segments.append((next_segment, next_segment + part_duration))
594
+ next_segment += time_interval
595
+ segments.append((duration - part_duration, duration))
596
+
597
+ filter_complex = ""
598
+ for i, (start, end) in enumerate(segments):
599
+ filter_complex += (
600
+ f"[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS[v{i}]; "
601
+ )
602
+ filter_complex += (
603
+ f"[0:a]atrim=start={start}:end={end},asetpts=PTS-STARTPTS[a{i}]; "
604
+ )
605
+
606
+ for i in range(len(segments)):
607
+ filter_complex += f"[v{i}][a{i}]"
608
+
609
+ filter_complex += f"concat=n={len(segments)}:v=1:a=1[vout][aout]"
610
+
611
+ cmd = [
612
+ "taskset",
613
+ "-c",
614
+ f"{cores}",
615
+ "ffmpeg",
616
+ "-hide_banner",
617
+ "-loglevel",
618
+ "error",
619
+ "-progress",
620
+ "pipe:1",
621
+ "-i",
622
+ video_file,
623
+ "-filter_complex",
624
+ filter_complex,
625
+ "-map",
626
+ "[vout]",
627
+ "-map",
628
+ "[aout]",
629
+ "-c:v",
630
+ "libx264",
631
+ "-c:a",
632
+ "aac",
633
+ "-threads",
634
+ f"{threads}",
635
+ output_file,
636
+ ]
637
+
638
+ if self._listener.is_cancelled:
639
+ return False
640
+ self._listener.subproc = await create_subprocess_exec(
641
+ *cmd, stdout=PIPE, stderr=PIPE
642
+ )
643
+ await self._ffmpeg_progress()
644
+ _, stderr = await self._listener.subproc.communicate()
645
+ code = self._listener.subproc.returncode
646
+ if self._listener.is_cancelled:
647
+ return False
648
+ if code == -9:
649
+ self._listener.is_cancelled = True
650
+ return False
651
+ elif code == 0:
652
+ return output_file
653
+ else:
654
+ try:
655
+ stderr = stderr.decode().strip()
656
+ except Exception:
657
+ stderr = "Unable to decode the error!"
658
+ LOGGER.error(
659
+ f"{stderr}. Something went wrong while creating sample video, mostly file is corrupted. Path: {video_file}"
660
+ )
661
+ if await aiopath.exists(output_file):
662
+ await remove(output_file)
663
+ return False
664
+
665
+ async def split(self, f_path, file_, parts, split_size):
666
+ self.clear()
667
+ multi_streams = True
668
+ self._total_time = duration = (await get_media_info(f_path))[0]
669
+ base_name, extension = ospath.splitext(file_)
670
+ split_size -= 3000000
671
+ start_time = 0
672
+ i = 1
673
+ while i <= parts or start_time < duration - 4:
674
+ out_path = f_path.replace(file_, f"{base_name}.part{i:03}{extension}")
675
+ cmd = [
676
+ "taskset",
677
+ "-c",
678
+ f"{cores}",
679
+ "ffmpeg",
680
+ "-hide_banner",
681
+ "-loglevel",
682
+ "error",
683
+ "-progress",
684
+ "pipe:1",
685
+ "-ss",
686
+ str(start_time),
687
+ "-i",
688
+ f_path,
689
+ "-fs",
690
+ str(split_size),
691
+ "-map",
692
+ "0",
693
+ "-map_chapters",
694
+ "-1",
695
+ "-async",
696
+ "1",
697
+ "-strict",
698
+ "-2",
699
+ "-c",
700
+ "copy",
701
+ "-threads",
702
+ f"{threads}",
703
+ out_path,
704
+ ]
705
+ if not multi_streams:
706
+ del cmd[15]
707
+ del cmd[15]
708
+ if self._listener.is_cancelled:
709
+ return False
710
+ self._listener.subproc = await create_subprocess_exec(
711
+ *cmd, stdout=PIPE, stderr=PIPE
712
+ )
713
+ await self._ffmpeg_progress()
714
+ _, stderr = await self._listener.subproc.communicate()
715
+ code = self._listener.subproc.returncode
716
+ if self._listener.is_cancelled:
717
+ return False
718
+ if code == -9:
719
+ self._listener.is_cancelled = True
720
+ return False
721
+ elif code != 0:
722
+ try:
723
+ stderr = stderr.decode().strip()
724
+ except:
725
+ stderr = "Unable to decode the error!"
726
+ try:
727
+ await remove(out_path)
728
+ except:
729
+ pass
730
+ if multi_streams:
731
+ LOGGER.warning(
732
+ f"{stderr}. Retrying without map, -map 0 not working in all situations. Path: {f_path}"
733
+ )
734
+ multi_streams = False
735
+ continue
736
+ else:
737
+ LOGGER.warning(
738
+ f"{stderr}. Unable to split this video, if it's size less than {self._listener.max_split_size} will be uploaded as it is. Path: {f_path}"
739
+ )
740
+ return False
741
+ out_size = await aiopath.getsize(out_path)
742
+ if out_size > self._listener.max_split_size:
743
+ split_size -= (out_size - self._listener.max_split_size) + 5000000
744
+ LOGGER.warning(
745
+ f"Part size is {out_size}. Trying again with lower split size!. Path: {f_path}"
746
+ )
747
+ await remove(out_path)
748
+ continue
749
+ lpd = (await get_media_info(out_path))[0]
750
+ if lpd == 0:
751
+ LOGGER.error(
752
+ f"Something went wrong while splitting, mostly file is corrupted. Path: {f_path}"
753
+ )
754
+ break
755
+ elif duration == lpd:
756
+ LOGGER.warning(
757
+ f"This file has been splitted with default stream and audio, so you will only see one part with less size from original one because it doesn't have all streams and audios. This happens mostly with MKV videos. Path: {f_path}"
758
+ )
759
+ break
760
+ elif lpd <= 3:
761
+ await remove(out_path)
762
+ break
763
+ self._last_processed_time += lpd
764
+ self._last_processed_bytes += out_size
765
+ start_time += lpd - 3
766
+ i += 1
767
+ return True
bot/helper/ext_utils/status_utils.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from html import escape
2
+ from psutil import virtual_memory, cpu_percent, disk_usage
3
+ from time import time
4
+ from asyncio import iscoroutinefunction, gather
5
+
6
+ from ... import task_dict, task_dict_lock, bot_start_time, status_dict, DOWNLOAD_DIR
7
+ from ...core.config_manager import Config
8
+ from ..telegram_helper.button_build import ButtonMaker
9
+ from ..telegram_helper.bot_commands import BotCommands
10
+
11
+ SIZE_UNITS = ["B", "KB", "MB", "GB", "TB", "PB"]
12
+
13
+
14
+ class MirrorStatus:
15
+ STATUS_UPLOAD = "Upload"
16
+ STATUS_DOWNLOAD = "Download"
17
+ STATUS_CLONE = "Clone"
18
+ STATUS_QUEUEDL = "QueueDl"
19
+ STATUS_QUEUEUP = "QueueUp"
20
+ STATUS_PAUSED = "Pause"
21
+ STATUS_ARCHIVE = "Archive"
22
+ STATUS_EXTRACT = "Extract"
23
+ STATUS_SPLIT = "Split"
24
+ STATUS_CHECK = "CheckUp"
25
+ STATUS_SEED = "Seed"
26
+ STATUS_SAMVID = "SamVid"
27
+ STATUS_CONVERT = "Convert"
28
+ STATUS_FFMPEG = "FFmpeg"
29
+
30
+
31
+ STATUSES = {
32
+ "ALL": "All",
33
+ "DL": MirrorStatus.STATUS_DOWNLOAD,
34
+ "UP": MirrorStatus.STATUS_UPLOAD,
35
+ "QD": MirrorStatus.STATUS_QUEUEDL,
36
+ "QU": MirrorStatus.STATUS_QUEUEUP,
37
+ "AR": MirrorStatus.STATUS_ARCHIVE,
38
+ "EX": MirrorStatus.STATUS_EXTRACT,
39
+ "SD": MirrorStatus.STATUS_SEED,
40
+ "CL": MirrorStatus.STATUS_CLONE,
41
+ "CM": MirrorStatus.STATUS_CONVERT,
42
+ "SP": MirrorStatus.STATUS_SPLIT,
43
+ "SV": MirrorStatus.STATUS_SAMVID,
44
+ "FF": MirrorStatus.STATUS_FFMPEG,
45
+ "PA": MirrorStatus.STATUS_PAUSED,
46
+ "CK": MirrorStatus.STATUS_CHECK,
47
+ }
48
+
49
+
50
+ async def get_task_by_gid(gid: str):
51
+ async with task_dict_lock:
52
+ for tk in task_dict.values():
53
+ if hasattr(tk, "seeding"):
54
+ await tk.update()
55
+ if tk.gid() == gid:
56
+ return tk
57
+ return None
58
+
59
+
60
+ async def get_specific_tasks(status, user_id):
61
+ if status == "All":
62
+ if user_id:
63
+ return [tk for tk in task_dict.values() if tk.listener.user_id == user_id]
64
+ else:
65
+ return list(task_dict.values())
66
+ tasks_to_check = (
67
+ [tk for tk in task_dict.values() if tk.listener.user_id == user_id]
68
+ if user_id
69
+ else list(task_dict.values())
70
+ )
71
+ coro_tasks = []
72
+ coro_tasks.extend(tk for tk in tasks_to_check if iscoroutinefunction(tk.status))
73
+ coro_statuses = await gather(*[tk.status() for tk in coro_tasks])
74
+ result = []
75
+ coro_index = 0
76
+ for tk in tasks_to_check:
77
+ if tk in coro_tasks:
78
+ st = coro_statuses[coro_index]
79
+ coro_index += 1
80
+ else:
81
+ st = tk.status()
82
+ if (st == status) or (
83
+ status == MirrorStatus.STATUS_DOWNLOAD and st not in STATUSES.values()
84
+ ):
85
+ result.append(tk)
86
+ return result
87
+
88
+
89
+ async def get_all_tasks(req_status: str, user_id):
90
+ async with task_dict_lock:
91
+ return await get_specific_tasks(req_status, user_id)
92
+
93
+
94
+ def get_readable_file_size(size_in_bytes):
95
+ if not size_in_bytes:
96
+ return "0B"
97
+
98
+ index = 0
99
+ while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1:
100
+ size_in_bytes /= 1024
101
+ index += 1
102
+
103
+ return f"{size_in_bytes:.2f}{SIZE_UNITS[index]}"
104
+
105
+
106
+ def get_readable_time(seconds: int):
107
+ periods = [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)]
108
+ result = ""
109
+ for period_name, period_seconds in periods:
110
+ if seconds >= period_seconds:
111
+ period_value, seconds = divmod(seconds, period_seconds)
112
+ result += f"{int(period_value)}{period_name}"
113
+ return result
114
+
115
+
116
+ def time_to_seconds(time_duration):
117
+ try:
118
+ parts = time_duration.split(":")
119
+ if len(parts) == 3:
120
+ hours, minutes, seconds = map(float, parts)
121
+ elif len(parts) == 2:
122
+ hours = 0
123
+ minutes, seconds = map(float, parts)
124
+ elif len(parts) == 1:
125
+ hours = 0
126
+ minutes = 0
127
+ seconds = float(parts[0])
128
+ else:
129
+ return 0
130
+ return hours * 3600 + minutes * 60 + seconds
131
+ except:
132
+ return 0
133
+
134
+
135
+ def speed_string_to_bytes(size_text: str):
136
+ size = 0
137
+ size_text = size_text.lower()
138
+ if "k" in size_text:
139
+ size += float(size_text.split("k")[0]) * 1024
140
+ elif "m" in size_text:
141
+ size += float(size_text.split("m")[0]) * 1048576
142
+ elif "g" in size_text:
143
+ size += float(size_text.split("g")[0]) * 1073741824
144
+ elif "t" in size_text:
145
+ size += float(size_text.split("t")[0]) * 1099511627776
146
+ elif "b" in size_text:
147
+ size += float(size_text.split("b")[0])
148
+ return size
149
+
150
+
151
+ def get_progress_bar_string(pct):
152
+ pct = float(pct.strip("%"))
153
+ p = min(max(pct, 0), 100)
154
+ cFull = int(p // 8)
155
+ p_str = "■" * cFull
156
+ p_str += "□" * (12 - cFull)
157
+ return f"[{p_str}]"
158
+
159
+
160
+ async def get_readable_message(sid, is_user, page_no=1, status="All", page_step=1):
161
+ msg = ""
162
+ button = None
163
+
164
+ tasks = await get_specific_tasks(status, sid if is_user else None)
165
+
166
+ STATUS_LIMIT = Config.STATUS_LIMIT
167
+ tasks_no = len(tasks)
168
+ pages = (max(tasks_no, 1) + STATUS_LIMIT - 1) // STATUS_LIMIT
169
+ if page_no > pages:
170
+ page_no = (page_no - 1) % pages + 1
171
+ status_dict[sid]["page_no"] = page_no
172
+ elif page_no < 1:
173
+ page_no = pages - (abs(page_no) % pages)
174
+ status_dict[sid]["page_no"] = page_no
175
+ start_position = (page_no - 1) * STATUS_LIMIT
176
+
177
+ for index, task in enumerate(
178
+ tasks[start_position : STATUS_LIMIT + start_position], start=1
179
+ ):
180
+ if status != "All":
181
+ tstatus = status
182
+ elif iscoroutinefunction(task.status):
183
+ tstatus = await task.status()
184
+ else:
185
+ tstatus = task.status()
186
+ if task.listener.is_super_chat:
187
+ msg += f"<b>{index + start_position}.<a href='{task.listener.message.link}'>{tstatus}</a>: </b>"
188
+ else:
189
+ msg += f"<b>{index + start_position}.{tstatus}: </b>"
190
+ msg += f"<code>{escape(f'{task.name()}')}</code>"
191
+ if task.listener.subname:
192
+ msg += f"\n<i>{task.listener.subname}</i>"
193
+ if (
194
+ tstatus not in [MirrorStatus.STATUS_SEED, MirrorStatus.STATUS_QUEUEUP]
195
+ and task.listener.progress
196
+ ):
197
+ progress = task.progress()
198
+ msg += f"\n{get_progress_bar_string(progress)} {progress}"
199
+ if task.listener.subname:
200
+ subsize = f"/{get_readable_file_size(task.listener.subsize)}"
201
+ ac = len(task.listener.files_to_proceed)
202
+ count = f"{task.listener.proceed_count}/{ac or '?'}"
203
+ else:
204
+ subsize = ""
205
+ count = ""
206
+ msg += f"\n<b>Processed:</b> {task.processed_bytes()}{subsize}"
207
+ if count:
208
+ msg += f"\n<b>Count:</b> {count}"
209
+ msg += f"\n<b>Size:</b> {task.size()}"
210
+ msg += f"\n<b>Speed:</b> {task.speed()}"
211
+ msg += f"\n<b>ETA:</b> {task.eta()}"
212
+ if (
213
+ tstatus == MirrorStatus.STATUS_DOWNLOAD
214
+ and task.listener.is_torrent
215
+ or task.listener.is_qbit
216
+ ):
217
+ try:
218
+ msg += f"\n<b>Seeders:</b> {task.seeders_num()} | <b>Leechers:</b> {task.leechers_num()}"
219
+ except:
220
+ pass
221
+ elif tstatus == MirrorStatus.STATUS_SEED:
222
+ msg += f"\n<b>Size: </b>{task.size()}"
223
+ msg += f"\n<b>Speed: </b>{task.seed_speed()}"
224
+ msg += f"\n<b>Uploaded: </b>{task.uploaded_bytes()}"
225
+ msg += f"\n<b>Ratio: </b>{task.ratio()}"
226
+ msg += f" | <b>Time: </b>{task.seeding_time()}"
227
+ else:
228
+ msg += f"\n<b>Size: </b>{task.size()}"
229
+ msg += f"\n<code>/{BotCommands.CancelTaskCommand[1]} {task.gid()}</code>\n\n"
230
+
231
+ if len(msg) == 0:
232
+ if status == "All":
233
+ return None, None
234
+ else:
235
+ msg = f"No Active {status} Tasks!\n\n"
236
+ buttons = ButtonMaker()
237
+ if not is_user:
238
+ buttons.data_button("📜", f"status {sid} ov", position="header")
239
+ if len(tasks) > STATUS_LIMIT:
240
+ msg += f"<b>Page:</b> {page_no}/{pages} | <b>Tasks:</b> {tasks_no} | <b>Step:</b> {page_step}\n"
241
+ buttons.data_button("<<", f"status {sid} pre", position="header")
242
+ buttons.data_button(">>", f"status {sid} nex", position="header")
243
+ if tasks_no > 30:
244
+ for i in [1, 2, 4, 6, 8, 10, 15]:
245
+ buttons.data_button(i, f"status {sid} ps {i}", position="footer")
246
+ if status != "All" or tasks_no > 20:
247
+ for label, status_value in list(STATUSES.items()):
248
+ if status_value != status:
249
+ buttons.data_button(label, f"status {sid} st {status_value}")
250
+ buttons.data_button("♻️", f"status {sid} ref", position="header")
251
+ button = buttons.build_menu(8)
252
+ msg += f"<b>CPU:</b> {cpu_percent()}% | <b>FREE:</b> {get_readable_file_size(disk_usage(DOWNLOAD_DIR).free)}"
253
+ msg += f"\n<b>RAM:</b> {virtual_memory().percent}% | <b>UPTIME:</b> {get_readable_time(time() - bot_start_time)}"
254
+ return msg, button
bot/helper/ext_utils/task_manager.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import Event
2
+
3
+ from ... import (
4
+ queued_dl,
5
+ queued_up,
6
+ non_queued_up,
7
+ non_queued_dl,
8
+ queue_dict_lock,
9
+ LOGGER,
10
+ )
11
+ from ...core.config_manager import Config
12
+ from ..mirror_leech_utils.gdrive_utils.search import GoogleDriveSearch
13
+ from .bot_utils import sync_to_async, get_telegraph_list
14
+ from .files_utils import get_base_name
15
+ from .links_utils import is_gdrive_id
16
+
17
+
18
+ async def stop_duplicate_check(listener):
19
+ if (
20
+ listener.is_leech
21
+ or not listener.stop_duplicate
22
+ or listener.same_dir
23
+ or listener.select
24
+ or not is_gdrive_id(listener.up_dest)
25
+ ):
26
+ return False, None
27
+
28
+ name = listener.name
29
+ LOGGER.info(f"Checking File/Folder if already in Drive: {name}")
30
+
31
+ if listener.compress:
32
+ name = f"{name}.zip"
33
+ elif listener.extract:
34
+ try:
35
+ name = get_base_name(name)
36
+ except:
37
+ name = None
38
+
39
+ if name is not None:
40
+ telegraph_content, contents_no = await sync_to_async(
41
+ GoogleDriveSearch(stop_dup=True, no_multi=listener.is_clone).drive_list,
42
+ name,
43
+ listener.up_dest,
44
+ listener.user_id,
45
+ )
46
+ if telegraph_content:
47
+ msg = f"File/Folder is already available in Drive.\nHere are {contents_no} list results:"
48
+ button = await get_telegraph_list(telegraph_content)
49
+ return msg, button
50
+
51
+ return False, None
52
+
53
+
54
+ async def check_running_tasks(listener, state="dl"):
55
+ all_limit = Config.QUEUE_ALL
56
+ state_limit = Config.QUEUE_DOWNLOAD if state == "dl" else Config.QUEUE_UPLOAD
57
+ event = None
58
+ is_over_limit = False
59
+ async with queue_dict_lock:
60
+ if state == "up" and listener.mid in non_queued_dl:
61
+ non_queued_dl.remove(listener.mid)
62
+ if (
63
+ (all_limit or state_limit)
64
+ and not listener.force_run
65
+ and not (listener.force_upload and state == "up")
66
+ and not (listener.force_download and state == "dl")
67
+ ):
68
+ dl_count = len(non_queued_dl)
69
+ up_count = len(non_queued_up)
70
+ t_count = dl_count if state == "dl" else up_count
71
+ is_over_limit = (
72
+ all_limit
73
+ and dl_count + up_count >= all_limit
74
+ and (not state_limit or t_count >= state_limit)
75
+ ) or (state_limit and t_count >= state_limit)
76
+ if is_over_limit:
77
+ event = Event()
78
+ if state == "dl":
79
+ queued_dl[listener.mid] = event
80
+ else:
81
+ queued_up[listener.mid] = event
82
+ if not is_over_limit:
83
+ if state == "up":
84
+ non_queued_up.add(listener.mid)
85
+ else:
86
+ non_queued_dl.add(listener.mid)
87
+
88
+ return is_over_limit, event
89
+
90
+
91
+ async def start_dl_from_queued(mid: int):
92
+ queued_dl[mid].set()
93
+ del queued_dl[mid]
94
+ non_queued_dl.add(mid)
95
+
96
+
97
+ async def start_up_from_queued(mid: int):
98
+ queued_up[mid].set()
99
+ del queued_up[mid]
100
+ non_queued_up.add(mid)
101
+
102
+
103
+ async def start_from_queued():
104
+ if all_limit := Config.QUEUE_ALL:
105
+ dl_limit = Config.QUEUE_DOWNLOAD
106
+ up_limit = Config.QUEUE_UPLOAD
107
+ async with queue_dict_lock:
108
+ dl = len(non_queued_dl)
109
+ up = len(non_queued_up)
110
+ all_ = dl + up
111
+ if all_ < all_limit:
112
+ f_tasks = all_limit - all_
113
+ if queued_up and (not up_limit or up < up_limit):
114
+ for index, mid in enumerate(list(queued_up.keys()), start=1):
115
+ await start_up_from_queued(mid)
116
+ f_tasks -= 1
117
+ if f_tasks == 0 or (up_limit and index >= up_limit - up):
118
+ break
119
+ if queued_dl and (not dl_limit or dl < dl_limit) and f_tasks != 0:
120
+ for index, mid in enumerate(list(queued_dl.keys()), start=1):
121
+ await start_dl_from_queued(mid)
122
+ if (dl_limit and index >= dl_limit - dl) or index == f_tasks:
123
+ break
124
+ return
125
+
126
+ if up_limit := Config.QUEUE_UPLOAD:
127
+ async with queue_dict_lock:
128
+ up = len(non_queued_up)
129
+ if queued_up and up < up_limit:
130
+ f_tasks = up_limit - up
131
+ for index, mid in enumerate(list(queued_up.keys()), start=1):
132
+ await start_up_from_queued(mid)
133
+ if index == f_tasks:
134
+ break
135
+ else:
136
+ async with queue_dict_lock:
137
+ if queued_up:
138
+ for mid in list(queued_up.keys()):
139
+ await start_up_from_queued(mid)
140
+
141
+ if dl_limit := Config.QUEUE_DOWNLOAD:
142
+ async with queue_dict_lock:
143
+ dl = len(non_queued_dl)
144
+ if queued_dl and dl < dl_limit:
145
+ f_tasks = dl_limit - dl
146
+ for index, mid in enumerate(list(queued_dl.keys()), start=1):
147
+ await start_dl_from_queued(mid)
148
+ if index == f_tasks:
149
+ break
150
+ else:
151
+ async with queue_dict_lock:
152
+ if queued_dl:
153
+ for mid in list(queued_dl.keys()):
154
+ await start_dl_from_queued(mid)
bot/helper/ext_utils/telegraph_helper.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import sleep
2
+ from secrets import token_urlsafe
3
+ from telegraph.aio import Telegraph
4
+ from telegraph.exceptions import RetryAfterError
5
+
6
+ from ... import LOGGER
7
+
8
+
9
+ class TelegraphHelper:
10
+ def __init__(self, author_name=None, author_url=None):
11
+ self._telegraph = Telegraph(domain="graph.org")
12
+ self._author_name = author_name
13
+ self._author_url = author_url
14
+
15
+ async def create_account(self):
16
+ LOGGER.info("Creating Telegraph Account")
17
+ try:
18
+ await self._telegraph.create_account(
19
+ short_name=token_urlsafe(8),
20
+ author_name=self._author_name,
21
+ author_url=self._author_url,
22
+ )
23
+ except Exception as e:
24
+ LOGGER.error(f"Failed to create Telegraph Account: {e}")
25
+
26
+ async def create_page(self, title, content):
27
+ try:
28
+ return await self._telegraph.create_page(
29
+ title=title,
30
+ author_name=self._author_name,
31
+ author_url=self._author_url,
32
+ html_content=content,
33
+ )
34
+ except RetryAfterError as st:
35
+ LOGGER.warning(
36
+ f"Telegraph Flood control exceeded. I will sleep for {st.retry_after} seconds."
37
+ )
38
+ await sleep(st.retry_after)
39
+ return await self.create_page(title, content)
40
+
41
+ async def edit_page(self, path, title, content):
42
+ try:
43
+ return await self._telegraph.edit_page(
44
+ path=path,
45
+ title=title,
46
+ author_name=self._author_name,
47
+ author_url=self._author_url,
48
+ html_content=content,
49
+ )
50
+ except RetryAfterError as st:
51
+ LOGGER.warning(
52
+ f"Telegraph Flood control exceeded. I will sleep for {st.retry_after} seconds."
53
+ )
54
+ await sleep(st.retry_after)
55
+ return await self.edit_page(path, title, content)
56
+
57
+ async def edit_telegraph(self, path, telegraph_content):
58
+ nxt_page = 1
59
+ prev_page = 0
60
+ num_of_path = len(path)
61
+ for content in telegraph_content:
62
+ if nxt_page == 1:
63
+ content += (
64
+ f'<b><a href="https://telegra.ph/{path[nxt_page]}">Next</a></b>'
65
+ )
66
+ nxt_page += 1
67
+ else:
68
+ if prev_page <= num_of_path:
69
+ content += f'<b><a href="https://telegra.ph/{path[prev_page]}">Prev</a></b>'
70
+ prev_page += 1
71
+ if nxt_page < num_of_path:
72
+ content += f'<b> | <a href="https://telegra.ph/{path[nxt_page]}">Next</a></b>'
73
+ nxt_page += 1
74
+ await self.edit_page(
75
+ path=path[prev_page],
76
+ title="Mirror-leech-bot Torrent Search",
77
+ content=content,
78
+ )
79
+ return
80
+
81
+
82
+ telegraph = TelegraphHelper(
83
+ "Mirror-Leech-Telegram-Bot", "https://github.com/anasty17/mirror-leech-telegram-bot"
84
+ )
85
+
86
+ print(__name__)
bot/helper/listeners/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/listeners/aria2_listener.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import remove, path as aiopath
2
+ from asyncio import sleep, TimeoutError
3
+ from time import time
4
+ from aiohttp.client_exceptions import ClientError
5
+
6
+ from ... import task_dict_lock, task_dict, LOGGER, intervals
7
+ from ...core.config_manager import Config
8
+ from ...core.torrent_manager import TorrentManager, is_metadata, aria2_name
9
+ from ..ext_utils.bot_utils import bt_selection_buttons
10
+ from ..ext_utils.files_utils import clean_unwanted
11
+ from ..ext_utils.status_utils import get_task_by_gid
12
+ from ..ext_utils.task_manager import stop_duplicate_check
13
+ from ..mirror_leech_utils.status_utils.aria2_status import Aria2Status
14
+ from ..telegram_helper.message_utils import (
15
+ send_message,
16
+ delete_message,
17
+ update_status_message,
18
+ )
19
+
20
+
21
+ async def _on_download_started(api, data):
22
+ gid = data["params"][0]["gid"]
23
+ download = await api.tellStatus(gid)
24
+ options = await api.getOption(gid)
25
+ if options.get("follow-torrent", "") == "false":
26
+ return
27
+ if is_metadata(download):
28
+ LOGGER.info(f"onDownloadStarted: {gid} METADATA")
29
+ await sleep(1)
30
+ if task := await get_task_by_gid(gid):
31
+ task.listener.is_torrent = True
32
+ if task.listener.select:
33
+ metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait."
34
+ meta = await send_message(task.listener.message, metamsg)
35
+ while True:
36
+ await sleep(0.5)
37
+ if download.get("status", "") == "removed" or download.get(
38
+ "followedBy", []
39
+ ):
40
+ await delete_message(meta)
41
+ break
42
+ download = await api.tellStatus(gid)
43
+ return
44
+ else:
45
+ LOGGER.info(f"onDownloadStarted: {aria2_name(download)} - Gid: {gid}")
46
+ await sleep(1)
47
+
48
+ await sleep(2)
49
+ if task := await get_task_by_gid(gid):
50
+ download = await api.tellStatus(gid)
51
+ if "bittorrent" in download:
52
+ task.listener.is_torrent = True
53
+ task.listener.name = aria2_name(download)
54
+ msg, button = await stop_duplicate_check(task.listener)
55
+ if msg:
56
+ await TorrentManager.aria2_remove(download)
57
+ await task.listener.on_download_error(msg, button)
58
+
59
+
60
+ async def _on_download_complete(api, data):
61
+ try:
62
+ gid = data["params"][0]["gid"]
63
+ download = await api.tellStatus(gid)
64
+ options = await api.getOption(gid)
65
+ except (TimeoutError, ClientError, Exception) as e:
66
+ LOGGER.error(f"onDownloadComplete: {e}")
67
+ return
68
+ if options.get("follow-torrent", "") == "false":
69
+ return
70
+ if download.get("followedBy", []):
71
+ new_gid = download.get("followedBy", [])[0]
72
+ LOGGER.info(f"Gid changed from {gid} to {new_gid}")
73
+ if task := await get_task_by_gid(new_gid):
74
+ task.listener.is_torrent = True
75
+ if Config.BASE_URL and task.listener.select:
76
+ if not task.queued:
77
+ await api.forcePause(new_gid)
78
+ SBUTTONS = bt_selection_buttons(new_gid)
79
+ msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
80
+ await send_message(task.listener.message, msg, SBUTTONS)
81
+ elif "bittorrent" in download:
82
+ if task := await get_task_by_gid(gid):
83
+ task.listener.is_torrent = True
84
+ if hasattr(task, "seeding") and task.seeding:
85
+ LOGGER.info(
86
+ f"Cancelling Seed: {aria2_name(download)} onDownloadComplete"
87
+ )
88
+ await TorrentManager.aria2_remove(download)
89
+ await task.listener.on_upload_error(
90
+ f"Seeding stopped with Ratio: {task.ratio()} and Time: {task.seeding_time()}"
91
+ )
92
+ else:
93
+ LOGGER.info(f"onDownloadComplete: {aria2_name(download)} - Gid: {gid}")
94
+ if task := await get_task_by_gid(gid):
95
+ await task.listener.on_download_complete()
96
+ if intervals["stopAll"]:
97
+ return
98
+ await TorrentManager.aria2_remove(download)
99
+
100
+
101
+ async def _on_bt_download_complete(api, data):
102
+ gid = data["params"][0]["gid"]
103
+ await sleep(1)
104
+ download = await api.tellStatus(gid)
105
+ LOGGER.info(f"onBtDownloadComplete: {aria2_name(download)} - Gid: {gid}")
106
+ if task := await get_task_by_gid(gid):
107
+ task.listener.is_torrent = True
108
+ if task.listener.select:
109
+ res = download.get("files", [])
110
+ for file_o in res:
111
+ f_path = file_o.get("path", "")
112
+ if file_o.get("selected", "") != "true" and await aiopath.exists(
113
+ f_path
114
+ ):
115
+ try:
116
+ await remove(f_path)
117
+ except:
118
+ pass
119
+ await clean_unwanted(download.get("dir", ""))
120
+ if task.listener.seed:
121
+ try:
122
+ await api.changeOption(gid, {"max-upload-limit": "0"})
123
+ except (TimeoutError, ClientError, Exception) as e:
124
+ LOGGER.error(
125
+ f"{e} You are not able to seed because you added global option seed-time=0 without adding specific seed_time for this torrent GID: {gid}"
126
+ )
127
+ else:
128
+ try:
129
+ await api.forcePause(gid)
130
+ except (TimeoutError, ClientError, Exception) as e:
131
+ LOGGER.error(f"onBtDownloadComplete: {e} GID: {gid}")
132
+ await task.listener.on_download_complete()
133
+ if intervals["stopAll"]:
134
+ return
135
+ download = await api.tellStatus(gid)
136
+ if (
137
+ task.listener.seed
138
+ and download.get("status", "") == "complete"
139
+ and await get_task_by_gid(gid)
140
+ ):
141
+ LOGGER.info(f"Cancelling Seed: {aria2_name(download)}")
142
+ await TorrentManager.aria2_remove(download)
143
+ await task.listener.on_upload_error(
144
+ f"Seeding stopped with Ratio: {task.ratio()} and Time: {task.seeding_time()}"
145
+ )
146
+ elif (
147
+ task.listener.seed
148
+ and download.get("status", "") == "complete"
149
+ and not await get_task_by_gid(gid)
150
+ ):
151
+ pass
152
+ elif task.listener.seed and not task.listener.is_cancelled:
153
+ async with task_dict_lock:
154
+ if task.listener.mid not in task_dict:
155
+ await TorrentManager.aria2_remove(download)
156
+ return
157
+ task_dict[task.listener.mid] = Aria2Status(task.listener, gid, True)
158
+ task_dict[task.listener.mid].start_time = time()
159
+ LOGGER.info(f"Seeding started: {aria2_name(download)} - Gid: {gid}")
160
+ await update_status_message(task.listener.message.chat.id)
161
+ else:
162
+ await TorrentManager.aria2_remove(download)
163
+
164
+
165
+ async def _on_download_stopped(_, data):
166
+ gid = data["params"][0]["gid"]
167
+ await sleep(4)
168
+ if task := await get_task_by_gid(gid):
169
+ await task.listener.on_download_error("Dead torrent!")
170
+
171
+
172
+ async def _on_download_error(api, data):
173
+ gid = data["params"][0]["gid"]
174
+ await sleep(1)
175
+ LOGGER.info(f"onDownloadError: {gid}")
176
+ error = "None"
177
+ try:
178
+ download = await api.tellStatus(gid)
179
+ options = await api.getOption(gid)
180
+ error = download.get("errorMessage", "")
181
+ LOGGER.info(f"Download Error: {error}")
182
+ if options.get("follow-torrent", "") == "false":
183
+ return
184
+ except (TimeoutError, ClientError, Exception) as e:
185
+ return
186
+ if task := await get_task_by_gid(gid):
187
+ await task.listener.on_download_error(error)
188
+
189
+
190
+ def add_aria2_callbacks():
191
+ TorrentManager.aria2.onBtDownloadComplete(_on_bt_download_complete)
192
+ TorrentManager.aria2.onDownloadComplete(_on_download_complete)
193
+ TorrentManager.aria2.onDownloadError(_on_download_error)
194
+ TorrentManager.aria2.onDownloadStart(_on_download_started)
195
+ TorrentManager.aria2.onDownloadStop(_on_download_stopped)
bot/helper/listeners/direct_listener.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import sleep, TimeoutError
2
+ from aiohttp.client_exceptions import ClientError
3
+
4
+ from ... import LOGGER
5
+ from ...core.torrent_manager import TorrentManager, aria2_name
6
+
7
+
8
+ class DirectListener:
9
+ def __init__(self, path, listener, a2c_opt):
10
+ self.listener = listener
11
+ self._path = path
12
+ self._a2c_opt = a2c_opt
13
+ self._proc_bytes = 0
14
+ self._failed = 0
15
+ self.download_task = None
16
+ self.name = self.listener.name
17
+
18
+ @property
19
+ def processed_bytes(self):
20
+ if self.download_task:
21
+ return self._proc_bytes + int(
22
+ self.download_task.get("completedLength", "0")
23
+ )
24
+ return self._proc_bytes
25
+
26
+ @property
27
+ def speed(self):
28
+ return (
29
+ int(self.download_task.get("downloadSpeed", "0"))
30
+ if self.download_task
31
+ else 0
32
+ )
33
+
34
+ async def download(self, contents):
35
+ self.is_downloading = True
36
+ for content in contents:
37
+ if self.listener.is_cancelled:
38
+ break
39
+ if content["path"]:
40
+ self._a2c_opt["dir"] = f"{self._path}/{content['path']}"
41
+ else:
42
+ self._a2c_opt["dir"] = self._path
43
+ filename = content["filename"]
44
+ self._a2c_opt["out"] = filename
45
+ try:
46
+ gid = await TorrentManager.aria2.addUri(
47
+ uris=[content["url"]], options=self._a2c_opt, position=0
48
+ )
49
+ except (TimeoutError, ClientError, Exception) as e:
50
+ self._failed += 1
51
+ LOGGER.error(f"Unable to download {filename} due to: {e}")
52
+ continue
53
+ self.download_task = await TorrentManager.aria2.tellStatus(gid)
54
+ while True:
55
+ if self.listener.is_cancelled:
56
+ if self.download_task:
57
+ await TorrentManager.aria2_remove(self.download_task)
58
+ break
59
+ self.download_task = await TorrentManager.aria2.tellStatus(gid)
60
+ if error_message := self.download_task.get("errorMessage"):
61
+ self._failed += 1
62
+ LOGGER.error(
63
+ f"Unable to download {aria2_name(self.download_task)} due to: {error_message}"
64
+ )
65
+ await TorrentManager.aria2_remove(self.download_task)
66
+ break
67
+ elif self.download_task.get("status", "") == "complete":
68
+ self._proc_bytes += int(self.download_task.get("totalLength", "0"))
69
+ await TorrentManager.aria2_remove(self.download_task)
70
+ break
71
+ await sleep(1)
72
+ self.download_task = None
73
+ if self.listener.is_cancelled:
74
+ return
75
+ if self._failed == len(contents):
76
+ await self.listener.on_download_error("All files are failed to download!")
77
+ return
78
+ await self.listener.on_download_complete()
79
+ return
80
+
81
+ async def cancel_task(self):
82
+ self.listener.is_cancelled = True
83
+ LOGGER.info(f"Cancelling Download: {self.listener.name}")
84
+ await self.listener.on_download_error("Download Cancelled by User!")
85
+ if self.download_task:
86
+ await TorrentManager.aria2_remove(self.download_task)
bot/helper/listeners/jdownloader_listener.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import sleep
2
+
3
+ from ... import intervals, jd_listener_lock, jd_downloads
4
+ from ..ext_utils.bot_utils import new_task
5
+ from ...core.jdownloader_booter import jdownloader
6
+ from ..ext_utils.status_utils import get_task_by_gid
7
+
8
+
9
+ @new_task
10
+ async def remove_download(gid):
11
+ if intervals["stopAll"]:
12
+ return
13
+ await jdownloader.device.downloads.remove_links(
14
+ package_ids=jd_downloads[gid]["ids"]
15
+ )
16
+ if task := await get_task_by_gid(gid):
17
+ await task.listener.on_download_error("Download removed manually!")
18
+ async with jd_listener_lock:
19
+ del jd_downloads[gid]
20
+
21
+
22
+ @new_task
23
+ async def _on_download_complete(gid):
24
+ if task := await get_task_by_gid(gid):
25
+ if task.listener.select:
26
+ async with jd_listener_lock:
27
+ await jdownloader.device.downloads.cleanup(
28
+ "DELETE_DISABLED",
29
+ "REMOVE_LINKS_AND_DELETE_FILES",
30
+ "ALL",
31
+ package_ids=jd_downloads[gid]["ids"],
32
+ )
33
+ await task.listener.on_download_complete()
34
+ if intervals["stopAll"]:
35
+ return
36
+ async with jd_listener_lock:
37
+ if gid in jd_downloads:
38
+ await jdownloader.device.downloads.remove_links(
39
+ package_ids=jd_downloads[gid]["ids"],
40
+ )
41
+ del jd_downloads[gid]
42
+
43
+
44
+ @new_task
45
+ async def _jd_listener():
46
+ while True:
47
+ await sleep(3)
48
+ async with jd_listener_lock:
49
+ if len(jd_downloads) == 0:
50
+ intervals["jd"] = ""
51
+ break
52
+ try:
53
+ packages = await jdownloader.device.downloads.query_packages(
54
+ [{"finished": True, "saveTo": True}]
55
+ )
56
+ except:
57
+ continue
58
+
59
+ all_packages = {pack["uuid"]: pack for pack in packages}
60
+ for d_gid, d_dict in list(jd_downloads.items()):
61
+ if d_dict["status"] == "down":
62
+ for index, pid in enumerate(d_dict["ids"]):
63
+ if pid not in all_packages:
64
+ del jd_downloads[d_gid]["ids"][index]
65
+ if len(jd_downloads[d_gid]["ids"]) == 0:
66
+ path = jd_downloads[d_gid]["path"]
67
+ jd_downloads[d_gid]["ids"] = [
68
+ uid
69
+ for uid, pk in all_packages.items()
70
+ if pk["saveTo"].startswith(path)
71
+ ]
72
+ if len(jd_downloads[d_gid]["ids"]) == 0:
73
+ await remove_download(d_gid)
74
+
75
+ if completed_packages := [
76
+ pack["uuid"] for pack in packages if pack.get("finished", False)
77
+ ]:
78
+ for d_gid, d_dict in list(jd_downloads.items()):
79
+ if d_dict["status"] == "down":
80
+ is_finished = all(
81
+ did in completed_packages for did in d_dict["ids"]
82
+ )
83
+ if is_finished:
84
+ jd_downloads[d_gid]["status"] = "done"
85
+ await _on_download_complete(d_gid)
86
+
87
+
88
+ async def on_download_start():
89
+ async with jd_listener_lock:
90
+ if not intervals["jd"]:
91
+ intervals["jd"] = await _jd_listener()
bot/helper/listeners/nzb_listener.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import sleep, gather
2
+
3
+ from ... import (
4
+ intervals,
5
+ sabnzbd_client,
6
+ nzb_jobs,
7
+ nzb_listener_lock,
8
+ LOGGER,
9
+ )
10
+ from ..ext_utils.bot_utils import new_task
11
+ from ..ext_utils.status_utils import get_task_by_gid
12
+ from ..ext_utils.task_manager import stop_duplicate_check
13
+
14
+
15
+ async def _remove_job(nzo_id, mid):
16
+ res1, _ = await gather(
17
+ sabnzbd_client.delete_history(nzo_id, delete_files=True),
18
+ sabnzbd_client.delete_category(f"{mid}"),
19
+ )
20
+ if not res1:
21
+ await sabnzbd_client.delete_job(nzo_id, True)
22
+ async with nzb_listener_lock:
23
+ if nzo_id in nzb_jobs:
24
+ del nzb_jobs[nzo_id]
25
+
26
+
27
+ @new_task
28
+ async def _on_download_error(err, nzo_id, button=None):
29
+ if task := await get_task_by_gid(nzo_id):
30
+ LOGGER.info(f"Cancelling Download: {task.name()}")
31
+ await gather(
32
+ task.listener.on_download_error(err, button),
33
+ _remove_job(nzo_id, task.listener.mid),
34
+ )
35
+
36
+
37
+ @new_task
38
+ async def _stop_duplicate(nzo_id):
39
+ if task := await get_task_by_gid(nzo_id):
40
+ await task.update()
41
+ task.listener.name = task.name()
42
+ msg, button = await stop_duplicate_check(task.listener)
43
+ if msg:
44
+ _on_download_error(msg, nzo_id, button)
45
+
46
+
47
+ @new_task
48
+ async def _on_download_complete(nzo_id):
49
+ if task := await get_task_by_gid(nzo_id):
50
+ await task.listener.on_download_complete()
51
+ if intervals["stopAll"]:
52
+ return
53
+ await _remove_job(nzo_id, task.listener.mid)
54
+
55
+
56
+ @new_task
57
+ async def _nzb_listener():
58
+ while not intervals["stopAll"]:
59
+ async with nzb_listener_lock:
60
+ try:
61
+ jobs = (await sabnzbd_client.get_history())["history"]["slots"]
62
+ downloads = (await sabnzbd_client.get_downloads())["queue"]["slots"]
63
+ if len(nzb_jobs) == 0:
64
+ intervals["nzb"] = ""
65
+ break
66
+ for job in jobs:
67
+ nzo_id = job["nzo_id"]
68
+ if nzo_id not in nzb_jobs:
69
+ continue
70
+ if job["status"] == "Completed":
71
+ if not nzb_jobs[nzo_id]["uploaded"]:
72
+ nzb_jobs[nzo_id]["uploaded"] = True
73
+ await _on_download_complete(nzo_id)
74
+ nzb_jobs[nzo_id]["status"] = "Completed"
75
+ elif job["status"] == "Failed":
76
+ await _on_download_error(job["fail_message"], nzo_id)
77
+ for dl in downloads:
78
+ nzo_id = dl["nzo_id"]
79
+ if nzo_id not in nzb_jobs:
80
+ continue
81
+ if dl["labels"] and dl["labels"][0] == "ALTERNATIVE":
82
+ await _on_download_error("Duplicated Job!", nzo_id)
83
+ continue
84
+ if (
85
+ dl["status"] == "Downloading"
86
+ and not nzb_jobs[nzo_id]["stop_dup_check"]
87
+ and not dl["filename"].startswith("Trying")
88
+ ):
89
+ nzb_jobs[nzo_id]["stop_dup_check"] = True
90
+ await _stop_duplicate(nzo_id)
91
+ except Exception as e:
92
+ LOGGER.error(str(e))
93
+ await sleep(3)
94
+
95
+
96
+ async def on_download_start(nzo_id):
97
+ async with nzb_listener_lock:
98
+ nzb_jobs[nzo_id] = {
99
+ "uploaded": False,
100
+ "stop_dup_check": False,
101
+ "status": "Downloading",
102
+ }
103
+ if not intervals["nzb"]:
104
+ intervals["nzb"] = await _nzb_listener()
bot/helper/listeners/qbit_listener.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import remove, path as aiopath
2
+ from asyncio import sleep, TimeoutError
3
+ from time import time
4
+ from aiohttp.client_exceptions import ClientError
5
+ from aioqbt.exc import AQError
6
+
7
+ from ... import (
8
+ task_dict,
9
+ task_dict_lock,
10
+ intervals,
11
+ qb_torrents,
12
+ qb_listener_lock,
13
+ LOGGER,
14
+ )
15
+ from ...core.config_manager import Config
16
+ from ...core.torrent_manager import TorrentManager
17
+ from ..ext_utils.bot_utils import new_task
18
+ from ..ext_utils.files_utils import clean_unwanted
19
+ from ..ext_utils.status_utils import get_readable_time, get_task_by_gid
20
+ from ..ext_utils.task_manager import stop_duplicate_check
21
+ from ..mirror_leech_utils.status_utils.qbit_status import QbittorrentStatus
22
+ from ..telegram_helper.message_utils import update_status_message
23
+
24
+
25
+ async def _remove_torrent(hash_, tag):
26
+ await TorrentManager.qbittorrent.torrents.delete([hash_], True)
27
+ async with qb_listener_lock:
28
+ if tag in qb_torrents:
29
+ del qb_torrents[tag]
30
+ await TorrentManager.qbittorrent.torrents.delete_tags([tag])
31
+
32
+
33
+ @new_task
34
+ async def _on_download_error(err, tor, button=None):
35
+ LOGGER.info(f"Cancelling Download: {tor.name}")
36
+ ext_hash = tor.hash
37
+ if task := await get_task_by_gid(ext_hash[:12]):
38
+ await task.listener.on_download_error(err, button)
39
+ await TorrentManager.qbittorrent.torrents.stop([ext_hash])
40
+ await sleep(0.3)
41
+ await _remove_torrent(ext_hash, tor.tags[0])
42
+
43
+
44
+ @new_task
45
+ async def _on_seed_finish(tor):
46
+ ext_hash = tor.hash
47
+ LOGGER.info(f"Cancelling Seed: {tor.name}")
48
+ if task := await get_task_by_gid(ext_hash[:12]):
49
+ msg = f"Seeding stopped with Ratio: {round(tor.ratio, 3)} and Time: {get_readable_time(int(tor.seeding_time.total_seconds() or "0"))}"
50
+ await task.listener.on_upload_error(msg)
51
+ await _remove_torrent(ext_hash, tor.tags[0])
52
+
53
+
54
+ @new_task
55
+ async def _stop_duplicate(tor):
56
+ if task := await get_task_by_gid(tor.hash[:12]):
57
+ if task.listener.stop_duplicate:
58
+ task.listener.name = tor.content_path.rsplit("/", 1)[-1].rsplit(".!qB", 1)[
59
+ 0
60
+ ]
61
+ msg, button = await stop_duplicate_check(task.listener)
62
+ if msg:
63
+ _on_download_error(msg, tor, button)
64
+
65
+
66
+ @new_task
67
+ async def _on_download_complete(tor):
68
+ ext_hash = tor.hash
69
+ tag = tor.tags[0]
70
+ if task := await get_task_by_gid(ext_hash[:12]):
71
+ if not task.listener.seed:
72
+ await TorrentManager.qbittorrent.torrents.stop([ext_hash])
73
+ if task.listener.select:
74
+ await clean_unwanted(task.listener.dir)
75
+ path = tor.content_path.rsplit("/", 1)[0]
76
+ res = await TorrentManager.qbittorrent.torrents.files(ext_hash)
77
+ for f in res:
78
+ if f.priority == 0 and await aiopath.exists(f"{path}/{f.name}"):
79
+ try:
80
+ await remove(f"{path}/{f.name}")
81
+ except:
82
+ pass
83
+ await task.listener.on_download_complete()
84
+ if intervals["stopAll"]:
85
+ return
86
+ if task.listener.seed and not task.listener.is_cancelled:
87
+ async with task_dict_lock:
88
+ if task.listener.mid in task_dict:
89
+ removed = False
90
+ task_dict[task.listener.mid] = QbittorrentStatus(
91
+ task.listener, True
92
+ )
93
+ else:
94
+ removed = True
95
+ if removed:
96
+ await _remove_torrent(ext_hash, tag)
97
+ return
98
+ async with qb_listener_lock:
99
+ if tag in qb_torrents:
100
+ qb_torrents[tag]["seeding"] = True
101
+ else:
102
+ return
103
+ await update_status_message(task.listener.message.chat.id)
104
+ LOGGER.info(f"Seeding started: {tor.name} - Hash: {ext_hash}")
105
+ else:
106
+ await _remove_torrent(ext_hash, tag)
107
+ else:
108
+ await _remove_torrent(ext_hash, tag)
109
+
110
+
111
+ @new_task
112
+ async def _qb_listener():
113
+ while True:
114
+ async with qb_listener_lock:
115
+ try:
116
+ torrents = await TorrentManager.qbittorrent.torrents.info()
117
+ if len(torrents) == 0:
118
+ intervals["qb"] = ""
119
+ break
120
+ for tor_info in torrents:
121
+ tag = tor_info.tags[0]
122
+ if tag not in qb_torrents:
123
+ continue
124
+ state = tor_info.state
125
+ if state == "metaDL":
126
+ qb_torrents[tag]["stalled_time"] = time()
127
+ if (
128
+ Config.TORRENT_TIMEOUT
129
+ and time() - qb_torrents[tag]["start_time"]
130
+ >= Config.TORRENT_TIMEOUT
131
+ ):
132
+ await _on_download_error("Dead Torrent!", tor_info)
133
+ else:
134
+ await TorrentManager.qbittorrent.torrents.reannounce(
135
+ [tor_info.hash]
136
+ )
137
+ elif state == "downloading":
138
+ qb_torrents[tag]["stalled_time"] = time()
139
+ if not qb_torrents[tag]["stop_dup_check"]:
140
+ qb_torrents[tag]["stop_dup_check"] = True
141
+ await _stop_duplicate(tor_info)
142
+ elif state == "stalledDL":
143
+ if (
144
+ not qb_torrents[tag]["rechecked"]
145
+ and 0.99989999999999999 < tor_info.progress < 1
146
+ ):
147
+ msg = f"Force recheck - Name: {tor_info.name} Hash: "
148
+ msg += f"{tor_info.hash} Downloaded Bytes: {tor_info.downloaded} "
149
+ msg += f"Size: {tor_info.size} Total Size: {tor_info.total_size}"
150
+ LOGGER.warning(msg)
151
+ await TorrentManager.qbittorrent.torrents.recheck(
152
+ [tor_info.hash]
153
+ )
154
+ qb_torrents[tag]["rechecked"] = True
155
+ elif (
156
+ Config.TORRENT_TIMEOUT
157
+ and time() - qb_torrents[tag]["stalled_time"]
158
+ >= Config.TORRENT_TIMEOUT
159
+ ):
160
+ await _on_download_error("Dead Torrent!", tor_info)
161
+ else:
162
+ await TorrentManager.qbittorrent.torrents.reannounce(
163
+ [tor_info.hash]
164
+ )
165
+ elif state == "missingFiles":
166
+ await TorrentManager.qbittorrent.torrents.recheck(
167
+ [tor_info.hash]
168
+ )
169
+ elif state == "error":
170
+ await _on_download_error(
171
+ "No enough space for this torrent on device", tor_info
172
+ )
173
+ elif (
174
+ int(tor_info.completion_on.timestamp()) != -1
175
+ and not qb_torrents[tag]["uploaded"]
176
+ ):
177
+ qb_torrents[tag]["uploaded"] = True
178
+ await _on_download_complete(tor_info)
179
+ elif (
180
+ state in ["stoppedUP", "stoppedDL"]
181
+ and qb_torrents[tag]["seeding"]
182
+ ):
183
+ qb_torrents[tag]["seeding"] = False
184
+ await _on_seed_finish(tor_info)
185
+ await sleep(0.5)
186
+ except (ClientError, TimeoutError, Exception, AQError) as e:
187
+ LOGGER.error(str(e))
188
+ await sleep(3)
189
+
190
+
191
+ async def on_download_start(tag):
192
+ async with qb_listener_lock:
193
+ qb_torrents[tag] = {
194
+ "start_time": time(),
195
+ "stalled_time": time(),
196
+ "stop_dup_check": False,
197
+ "rechecked": False,
198
+ "uploaded": False,
199
+ "seeding": False,
200
+ }
201
+ if not intervals["qb"]:
202
+ intervals["qb"] = await _qb_listener()
bot/helper/listeners/task_listener.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import path as aiopath, listdir, remove
2
+ from asyncio import sleep, gather
3
+ from html import escape
4
+ from requests import utils as rutils
5
+
6
+ from ... import (
7
+ intervals,
8
+ task_dict,
9
+ task_dict_lock,
10
+ LOGGER,
11
+ non_queued_up,
12
+ non_queued_dl,
13
+ queued_up,
14
+ queued_dl,
15
+ queue_dict_lock,
16
+ same_directory_lock,
17
+ DOWNLOAD_DIR,
18
+ )
19
+ from ...core.config_manager import Config
20
+ from ...core.torrent_manager import TorrentManager
21
+ from ..common import TaskConfig
22
+ from ..ext_utils.bot_utils import sync_to_async
23
+ from ..ext_utils.db_handler import database
24
+ from ..ext_utils.files_utils import (
25
+ get_path_size,
26
+ clean_download,
27
+ clean_target,
28
+ join_files,
29
+ create_recursive_symlink,
30
+ remove_excluded_files,
31
+ remove_non_included_files,
32
+ move_and_merge,
33
+ )
34
+ from ..ext_utils.links_utils import is_gdrive_id
35
+ from ..ext_utils.status_utils import get_readable_file_size
36
+ from ..ext_utils.task_manager import start_from_queued, check_running_tasks
37
+ from ..mirror_leech_utils.gdrive_utils.upload import GoogleDriveUpload
38
+ from ..mirror_leech_utils.rclone_utils.transfer import RcloneTransferHelper
39
+ from ..mirror_leech_utils.status_utils.gdrive_status import GoogleDriveStatus
40
+ from ..mirror_leech_utils.status_utils.queue_status import QueueStatus
41
+ from ..mirror_leech_utils.status_utils.rclone_status import RcloneStatus
42
+ from ..mirror_leech_utils.status_utils.telegram_status import TelegramStatus
43
+ from ..mirror_leech_utils.telegram_uploader import TelegramUploader
44
+ from ..telegram_helper.button_build import ButtonMaker
45
+ from ..telegram_helper.message_utils import (
46
+ send_message,
47
+ delete_status,
48
+ update_status_message,
49
+ )
50
+
51
+
52
+ class TaskListener(TaskConfig):
53
+ def __init__(self):
54
+ super().__init__()
55
+
56
+ async def clean(self):
57
+ try:
58
+ if st := intervals["status"]:
59
+ for intvl in list(st.values()):
60
+ intvl.cancel()
61
+ intervals["status"].clear()
62
+ await gather(TorrentManager.aria2.purgeDownloadResult(), delete_status())
63
+ except:
64
+ pass
65
+
66
+ def clear(self):
67
+ self.subname = ""
68
+ self.subsize = 0
69
+ self.files_to_proceed = []
70
+ self.proceed_count = 0
71
+ self.progress = True
72
+
73
+ async def remove_from_same_dir(self):
74
+ async with task_dict_lock:
75
+ if (
76
+ self.folder_name
77
+ and self.same_dir
78
+ and self.mid in self.same_dir[self.folder_name]["tasks"]
79
+ ):
80
+ self.same_dir[self.folder_name]["tasks"].remove(self.mid)
81
+ self.same_dir[self.folder_name]["total"] -= 1
82
+
83
+ async def on_download_start(self):
84
+ if (
85
+ self.is_super_chat
86
+ and Config.INCOMPLETE_TASK_NOTIFIER
87
+ and Config.DATABASE_URL
88
+ ):
89
+ await database.add_incomplete_task(
90
+ self.message.chat.id, self.message.link, self.tag
91
+ )
92
+
93
+ async def on_download_complete(self):
94
+ await sleep(2)
95
+ if self.is_cancelled:
96
+ return
97
+ multi_links = False
98
+ if (
99
+ self.folder_name
100
+ and self.same_dir
101
+ and self.mid in self.same_dir[self.folder_name]["tasks"]
102
+ ):
103
+ async with same_directory_lock:
104
+ while True:
105
+ async with task_dict_lock:
106
+ if self.mid not in self.same_dir[self.folder_name]["tasks"]:
107
+ return
108
+ if (
109
+ self.same_dir[self.folder_name]["total"] <= 1
110
+ or len(self.same_dir[self.folder_name]["tasks"]) > 1
111
+ ):
112
+ if self.same_dir[self.folder_name]["total"] > 1:
113
+ self.same_dir[self.folder_name]["tasks"].remove(
114
+ self.mid
115
+ )
116
+ self.same_dir[self.folder_name]["total"] -= 1
117
+ spath = f"{self.dir}{self.folder_name}"
118
+ des_id = list(self.same_dir[self.folder_name]["tasks"])[
119
+ 0
120
+ ]
121
+ des_path = f"{DOWNLOAD_DIR}{des_id}{self.folder_name}"
122
+ LOGGER.info(f"Moving files from {self.mid} to {des_id}")
123
+ await move_and_merge(spath, des_path, self.mid)
124
+ multi_links = True
125
+ break
126
+ await sleep(1)
127
+ async with task_dict_lock:
128
+ if self.is_cancelled:
129
+ return
130
+ if self.mid not in task_dict:
131
+ return
132
+ download = task_dict[self.mid]
133
+ self.name = download.name()
134
+ gid = download.gid()
135
+ LOGGER.info(f"Download completed: {self.name}")
136
+
137
+ if not (self.is_torrent or self.is_qbit):
138
+ self.seed = False
139
+
140
+ if multi_links:
141
+ self.seed = False
142
+ await self.on_upload_error(
143
+ f"{self.name} Downloaded!\n\nWaiting for other tasks to finish..."
144
+ )
145
+ return
146
+ elif self.same_dir:
147
+ self.seed = False
148
+
149
+ if self.folder_name:
150
+ self.name = self.folder_name.strip("/").split("/", 1)[0]
151
+
152
+ if not await aiopath.exists(f"{self.dir}/{self.name}"):
153
+ try:
154
+ files = await listdir(self.dir)
155
+ self.name = files[-1]
156
+ if self.name == "yt-dlp-thumb":
157
+ self.name = files[0]
158
+ except Exception as e:
159
+ await self.on_upload_error(str(e))
160
+ return
161
+
162
+ dl_path = f"{self.dir}/{self.name}"
163
+ self.size = await get_path_size(dl_path)
164
+ self.is_file = await aiopath.isfile(dl_path)
165
+
166
+ if self.seed:
167
+ up_dir = self.up_dir = f"{self.dir}10000"
168
+ up_path = f"{self.up_dir}/{self.name}"
169
+ await create_recursive_symlink(self.dir, self.up_dir)
170
+ LOGGER.info(f"Shortcut created: {dl_path} -> {up_path}")
171
+ else:
172
+ up_dir = self.dir
173
+ up_path = dl_path
174
+
175
+ if not self.included_extensions:
176
+ await remove_excluded_files(
177
+ self.up_dir or self.dir, self.excluded_extensions
178
+ )
179
+ else:
180
+ await remove_non_included_files(
181
+ self.up_dir or self.dir, self.included_extensions
182
+ )
183
+
184
+ if not await aiopath.exists(up_path):
185
+ e = "No files to upload. In case you have filled EXCLUDED/INCLUDED EXTENSIONS, then check if all files have those extensions or not."
186
+ await self.on_upload_error(str(e))
187
+ return
188
+
189
+ if not Config.QUEUE_ALL:
190
+ async with queue_dict_lock:
191
+ if self.mid in non_queued_dl:
192
+ non_queued_dl.remove(self.mid)
193
+ await start_from_queued()
194
+
195
+ if self.join and not self.is_file:
196
+ await join_files(up_path)
197
+
198
+ if self.extract and not self.is_nzb:
199
+ up_path = await self.proceed_extract(up_path, gid)
200
+ if self.is_cancelled:
201
+ return
202
+ self.is_file = await aiopath.isfile(up_path)
203
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
204
+ self.size = await get_path_size(up_dir)
205
+ self.clear()
206
+ if not self.included_extensions:
207
+ await remove_excluded_files(up_dir, self.excluded_extensions)
208
+ else:
209
+ await remove_non_included_files(up_dir, self.included_extensions)
210
+
211
+ if self.ffmpeg_cmds:
212
+ up_path = await self.proceed_ffmpeg(
213
+ up_path,
214
+ gid,
215
+ )
216
+ if self.is_cancelled:
217
+ return
218
+ self.is_file = await aiopath.isfile(up_path)
219
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
220
+ self.size = await get_path_size(up_dir)
221
+ self.clear()
222
+
223
+ if self.name_sub:
224
+ LOGGER.info(f"Start Name Substitution {up_path}")
225
+ up_path = await self.substitute(up_path)
226
+ if self.is_cancelled:
227
+ return
228
+ self.is_file = await aiopath.isfile(up_path)
229
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
230
+
231
+ if self.screen_shots:
232
+ up_path = await self.generate_screenshots(up_path)
233
+ if self.is_cancelled:
234
+ return
235
+ self.is_file = await aiopath.isfile(up_path)
236
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
237
+ self.size = await get_path_size(up_dir)
238
+
239
+ if self.convert_audio or self.convert_video:
240
+ up_path = await self.convert_media(
241
+ up_path,
242
+ gid,
243
+ )
244
+ if self.is_cancelled:
245
+ return
246
+ self.is_file = await aiopath.isfile(up_path)
247
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
248
+ self.size = await get_path_size(up_dir)
249
+ self.clear()
250
+
251
+ if self.sample_video:
252
+ up_path = await self.generate_sample_video(up_path, gid)
253
+ if self.is_cancelled:
254
+ return
255
+ self.is_file = await aiopath.isfile(up_path)
256
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
257
+ self.size = await get_path_size(up_dir)
258
+ self.clear()
259
+
260
+ if self.compress:
261
+ up_path = await self.proceed_compress(
262
+ up_path,
263
+ gid,
264
+ )
265
+ self.is_file = await aiopath.isfile(up_path)
266
+ if self.is_cancelled:
267
+ return
268
+ self.clear()
269
+
270
+ self.name = up_path.replace(f"{up_dir}/", "").split("/", 1)[0]
271
+ self.size = await get_path_size(up_dir)
272
+
273
+ if self.is_leech and not self.compress:
274
+ await self.proceed_split(up_path, gid)
275
+ if self.is_cancelled:
276
+ return
277
+ self.clear()
278
+
279
+ self.subproc = None
280
+
281
+ add_to_queue, event = await check_running_tasks(self, "up")
282
+ await start_from_queued()
283
+ if add_to_queue:
284
+ LOGGER.info(f"Added to Queue/Upload: {self.name}")
285
+ async with task_dict_lock:
286
+ task_dict[self.mid] = QueueStatus(self, gid, "Up")
287
+ await event.wait()
288
+ if self.is_cancelled:
289
+ return
290
+ LOGGER.info(f"Start from Queued/Upload: {self.name}")
291
+
292
+ self.size = await get_path_size(up_dir)
293
+
294
+ if self.is_leech:
295
+ LOGGER.info(f"Leech Name: {self.name}")
296
+ tg = TelegramUploader(self, up_dir)
297
+ async with task_dict_lock:
298
+ task_dict[self.mid] = TelegramStatus(self, tg, gid, "up")
299
+ await gather(
300
+ update_status_message(self.message.chat.id),
301
+ tg.upload(),
302
+ )
303
+ del tg
304
+ elif is_gdrive_id(self.up_dest):
305
+ LOGGER.info(f"Gdrive Upload Name: {self.name}")
306
+ drive = GoogleDriveUpload(self, up_path)
307
+ async with task_dict_lock:
308
+ task_dict[self.mid] = GoogleDriveStatus(self, drive, gid, "up")
309
+ await gather(
310
+ update_status_message(self.message.chat.id),
311
+ sync_to_async(drive.upload),
312
+ )
313
+ del drive
314
+ else:
315
+ LOGGER.info(f"Rclone Upload Name: {self.name}")
316
+ RCTransfer = RcloneTransferHelper(self)
317
+ async with task_dict_lock:
318
+ task_dict[self.mid] = RcloneStatus(self, RCTransfer, gid, "up")
319
+ await gather(
320
+ update_status_message(self.message.chat.id),
321
+ RCTransfer.upload(up_path),
322
+ )
323
+ del RCTransfer
324
+ return
325
+
326
+ async def on_upload_complete(
327
+ self, link, files, folders, mime_type, rclone_path="", dir_id=""
328
+ ):
329
+ if (
330
+ self.is_super_chat
331
+ and Config.INCOMPLETE_TASK_NOTIFIER
332
+ and Config.DATABASE_URL
333
+ ):
334
+ await database.rm_complete_task(self.message.link)
335
+ msg = f"<b>Name: </b><code>{escape(self.name)}</code>\n\n<b>Size: </b>{get_readable_file_size(self.size)}"
336
+ LOGGER.info(f"Task Done: {self.name}")
337
+ if self.is_leech:
338
+ msg += f"\n<b>Total Files: </b>{folders}"
339
+ if mime_type != 0:
340
+ msg += f"\n<b>Corrupted Files: </b>{mime_type}"
341
+ msg += f"\n<b>cc: </b>{self.tag}\n\n"
342
+ if not files:
343
+ await send_message(self.message, msg)
344
+ else:
345
+ fmsg = ""
346
+ for index, (link, name) in enumerate(files.items(), start=1):
347
+ fmsg += f"{index}. <a href='{link}'>{name}</a>\n"
348
+ if len(fmsg.encode() + msg.encode()) > 4000:
349
+ await send_message(self.message, msg + fmsg)
350
+ await sleep(1)
351
+ fmsg = ""
352
+ if fmsg != "":
353
+ await send_message(self.message, msg + fmsg)
354
+ else:
355
+ msg += f"\n\n<b>Type: </b>{mime_type}"
356
+ if mime_type == "Folder":
357
+ msg += f"\n<b>SubFolders: </b>{folders}"
358
+ msg += f"\n<b>Files: </b>{files}"
359
+ if (
360
+ link
361
+ or rclone_path
362
+ and Config.RCLONE_SERVE_URL
363
+ and not self.private_link
364
+ ):
365
+ buttons = ButtonMaker()
366
+ if link:
367
+ buttons.url_button("☁️ Cloud Link", link)
368
+ else:
369
+ msg += f"\n\nPath: <code>{rclone_path}</code>"
370
+ if rclone_path and Config.RCLONE_SERVE_URL and not self.private_link:
371
+ remote, rpath = rclone_path.split(":", 1)
372
+ url_path = rutils.quote(f"{rpath}")
373
+ share_url = f"{Config.RCLONE_SERVE_URL}/{remote}/{url_path}"
374
+ if mime_type == "Folder":
375
+ share_url += "/"
376
+ buttons.url_button("🔗 Rclone Link", share_url)
377
+ if not rclone_path and dir_id:
378
+ INDEX_URL = ""
379
+ if self.private_link:
380
+ INDEX_URL = self.user_dict.get("INDEX_URL", "") or ""
381
+ elif Config.INDEX_URL:
382
+ INDEX_URL = Config.INDEX_URL
383
+ if INDEX_URL:
384
+ share_url = f"{INDEX_URL}findpath?id={dir_id}"
385
+ buttons.url_button("⚡ Index Link", share_url)
386
+ if mime_type.startswith(("image", "video", "audio")):
387
+ share_urls = f"{INDEX_URL}findpath?id={dir_id}&view=true"
388
+ buttons.url_button("🌐 View Link", share_urls)
389
+ button = buttons.build_menu(2)
390
+ else:
391
+ msg += f"\n\nPath: <code>{rclone_path}</code>"
392
+ button = None
393
+ msg += f"\n\n<b>cc: </b>{self.tag}"
394
+ await send_message(self.message, msg, button)
395
+ if self.seed:
396
+ await clean_target(self.up_dir)
397
+ async with queue_dict_lock:
398
+ if self.mid in non_queued_up:
399
+ non_queued_up.remove(self.mid)
400
+ await start_from_queued()
401
+ return
402
+ await clean_download(self.dir)
403
+ async with task_dict_lock:
404
+ if self.mid in task_dict:
405
+ del task_dict[self.mid]
406
+ count = len(task_dict)
407
+ if count == 0:
408
+ await self.clean()
409
+ else:
410
+ await update_status_message(self.message.chat.id)
411
+
412
+ async with queue_dict_lock:
413
+ if self.mid in non_queued_up:
414
+ non_queued_up.remove(self.mid)
415
+
416
+ await start_from_queued()
417
+
418
+ async def on_download_error(self, error, button=None):
419
+ async with task_dict_lock:
420
+ if self.mid in task_dict:
421
+ del task_dict[self.mid]
422
+ count = len(task_dict)
423
+ await self.remove_from_same_dir()
424
+ msg = f"{self.tag} Download: {escape(str(error))}"
425
+ await send_message(self.message, msg, button)
426
+ if count == 0:
427
+ await self.clean()
428
+ else:
429
+ await update_status_message(self.message.chat.id)
430
+
431
+ if (
432
+ self.is_super_chat
433
+ and Config.INCOMPLETE_TASK_NOTIFIER
434
+ and Config.DATABASE_URL
435
+ ):
436
+ await database.rm_complete_task(self.message.link)
437
+
438
+ async with queue_dict_lock:
439
+ if self.mid in queued_dl:
440
+ queued_dl[self.mid].set()
441
+ del queued_dl[self.mid]
442
+ if self.mid in queued_up:
443
+ queued_up[self.mid].set()
444
+ del queued_up[self.mid]
445
+ if self.mid in non_queued_dl:
446
+ non_queued_dl.remove(self.mid)
447
+ if self.mid in non_queued_up:
448
+ non_queued_up.remove(self.mid)
449
+
450
+ await start_from_queued()
451
+ await sleep(3)
452
+ await clean_download(self.dir)
453
+ if self.up_dir:
454
+ await clean_download(self.up_dir)
455
+ if self.thumb and await aiopath.exists(self.thumb):
456
+ await remove(self.thumb)
457
+
458
+ async def on_upload_error(self, error):
459
+ async with task_dict_lock:
460
+ if self.mid in task_dict:
461
+ del task_dict[self.mid]
462
+ count = len(task_dict)
463
+ await send_message(self.message, f"{self.tag} {escape(str(error))}")
464
+ if count == 0:
465
+ await self.clean()
466
+ else:
467
+ await update_status_message(self.message.chat.id)
468
+
469
+ if (
470
+ self.is_super_chat
471
+ and Config.INCOMPLETE_TASK_NOTIFIER
472
+ and Config.DATABASE_URL
473
+ ):
474
+ await database.rm_complete_task(self.message.link)
475
+
476
+ async with queue_dict_lock:
477
+ if self.mid in queued_dl:
478
+ queued_dl[self.mid].set()
479
+ del queued_dl[self.mid]
480
+ if self.mid in queued_up:
481
+ queued_up[self.mid].set()
482
+ del queued_up[self.mid]
483
+ if self.mid in non_queued_dl:
484
+ non_queued_dl.remove(self.mid)
485
+ if self.mid in non_queued_up:
486
+ non_queued_up.remove(self.mid)
487
+
488
+ await start_from_queued()
489
+ await sleep(3)
490
+ await clean_download(self.dir)
491
+ if self.up_dir:
492
+ await clean_download(self.up_dir)
493
+ if self.thumb and await aiopath.exists(self.thumb):
494
+ await remove(self.thumb)
bot/helper/mirror_leech_utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/mirror_leech_utils/download_utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/mirror_leech_utils/download_utils/aria2_download.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import remove, path as aiopath
2
+ from aiofiles import open as aiopen
3
+ from base64 import b64encode
4
+ from aiohttp.client_exceptions import ClientError
5
+ from asyncio import TimeoutError
6
+
7
+ from .... import task_dict_lock, task_dict, LOGGER
8
+ from ....core.config_manager import Config
9
+ from ....core.torrent_manager import TorrentManager, is_metadata, aria2_name
10
+ from ...ext_utils.bot_utils import bt_selection_buttons
11
+ from ...ext_utils.task_manager import check_running_tasks
12
+ from ...mirror_leech_utils.status_utils.aria2_status import Aria2Status
13
+ from ...telegram_helper.message_utils import send_status_message, send_message
14
+
15
+
16
+ async def add_aria2_download(listener, dpath, header, ratio, seed_time):
17
+ a2c_opt = {"dir": dpath}
18
+ if listener.name:
19
+ a2c_opt["out"] = listener.name
20
+ if header:
21
+ a2c_opt["header"] = header
22
+ if ratio:
23
+ a2c_opt["seed-ratio"] = ratio
24
+ if seed_time:
25
+ a2c_opt["seed-time"] = seed_time
26
+ if TORRENT_TIMEOUT := Config.TORRENT_TIMEOUT:
27
+ a2c_opt["bt-stop-timeout"] = f"{TORRENT_TIMEOUT}"
28
+
29
+ add_to_queue, event = await check_running_tasks(listener)
30
+ if add_to_queue:
31
+ if listener.link.startswith("magnet:"):
32
+ a2c_opt["pause-metadata"] = "true"
33
+ else:
34
+ a2c_opt["pause"] = "true"
35
+
36
+ try:
37
+ if await aiopath.exists(listener.link):
38
+ async with aiopen(listener.link, "rb") as tf:
39
+ torrent = await tf.read()
40
+ encoded = b64encode(torrent).decode()
41
+ params = [encoded, [], a2c_opt]
42
+ gid = await TorrentManager.aria2.jsonrpc("addTorrent", params)
43
+ """gid = await TorrentManager.aria2.add_torrent(path=listener.link, options=a2c_opt)"""
44
+ else:
45
+ gid = await TorrentManager.aria2.addUri(
46
+ uris=[listener.link], options=a2c_opt
47
+ )
48
+ except (TimeoutError, ClientError, Exception) as e:
49
+ LOGGER.info(f"Aria2c Download Error: {e}")
50
+ await listener.on_download_error(f"{e}")
51
+ return
52
+ download = await TorrentManager.aria2.tellStatus(gid)
53
+ if download.get("errorMessage"):
54
+ error = str(download["errorMessage"]).replace("<", " ").replace(">", " ")
55
+ LOGGER.info(f"Aria2c Download Error: {error}")
56
+ await TorrentManager.aria2_remove(download)
57
+ await listener.on_download_error(error)
58
+ return
59
+ if await aiopath.exists(listener.link):
60
+ await remove(listener.link)
61
+
62
+ name = aria2_name(download)
63
+ async with task_dict_lock:
64
+ task_dict[listener.mid] = Aria2Status(listener, gid, queued=add_to_queue)
65
+ if add_to_queue:
66
+ LOGGER.info(f"Added to Queue/Download: {name}. Gid: {gid}")
67
+ if (
68
+ (not listener.select or "bittorrent" not in download)
69
+ and listener.multi <= 1
70
+ and not listener.is_rss
71
+ ):
72
+ await send_status_message(listener.message)
73
+ else:
74
+ LOGGER.info(f"Aria2Download started: {name}. Gid: {gid}")
75
+
76
+ await listener.on_download_start()
77
+
78
+ if (
79
+ not add_to_queue
80
+ and (not listener.select or not Config.BASE_URL)
81
+ and listener.multi <= 1
82
+ and not listener.is_rss
83
+ ):
84
+ await send_status_message(listener.message)
85
+ elif listener.select and "bittorrent" in download and not is_metadata(download):
86
+ if not add_to_queue:
87
+ await TorrentManager.aria2.forcePause(gid)
88
+ SBUTTONS = bt_selection_buttons(gid)
89
+ msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
90
+ await send_message(listener.message, msg, SBUTTONS)
91
+
92
+ if add_to_queue:
93
+ await event.wait()
94
+ if listener.is_cancelled:
95
+ return
96
+ async with task_dict_lock:
97
+ task = task_dict[listener.mid]
98
+ task.queued = False
99
+ await task.update()
100
+ new_gid = task.gid()
101
+
102
+ await TorrentManager.aria2.unpause(new_gid)
103
+ LOGGER.info(f"Start Queued Download from Aria2c: {name}. Gid: {new_gid}")
bot/helper/mirror_leech_utils/download_utils/direct_downloader.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from secrets import token_urlsafe
2
+
3
+ from .... import (
4
+ LOGGER,
5
+ task_dict,
6
+ task_dict_lock,
7
+ )
8
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
9
+ from ...listeners.direct_listener import DirectListener
10
+ from ...mirror_leech_utils.status_utils.direct_status import DirectStatus
11
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
12
+ from ...telegram_helper.message_utils import send_status_message
13
+
14
+
15
+ async def add_direct_download(listener, path):
16
+ details = listener.link
17
+ if not (contents := details.get("contents")):
18
+ await listener.on_download_error("There is nothing to download!")
19
+ return
20
+ listener.size = details["total_size"]
21
+
22
+ if not listener.name:
23
+ listener.name = details["title"]
24
+ path = f"{path}/{listener.name}"
25
+
26
+ msg, button = await stop_duplicate_check(listener)
27
+ if msg:
28
+ await listener.on_download_error(msg, button)
29
+ return
30
+
31
+ gid = token_urlsafe(10)
32
+ add_to_queue, event = await check_running_tasks(listener)
33
+ if add_to_queue:
34
+ LOGGER.info(f"Added to Queue/Download: {listener.name}")
35
+ async with task_dict_lock:
36
+ task_dict[listener.mid] = QueueStatus(listener, gid, "dl")
37
+ await listener.on_download_start()
38
+ if listener.multi <= 1 and not listener.is_rss:
39
+ await send_status_message(listener.message)
40
+ await event.wait()
41
+ if listener.is_cancelled:
42
+ return
43
+
44
+ a2c_opt = {"follow-torrent": "false", "follow-metalink": "false"}
45
+ if header := details.get("header"):
46
+ a2c_opt["header"] = header
47
+ directListener = DirectListener(path, listener, a2c_opt)
48
+
49
+ async with task_dict_lock:
50
+ task_dict[listener.mid] = DirectStatus(listener, directListener, gid)
51
+
52
+ if add_to_queue:
53
+ LOGGER.info(f"Start Queued Download from Direct Download: {listener.name}")
54
+ else:
55
+ LOGGER.info(f"Download from Direct Download: {listener.name}")
56
+ await listener.on_download_start()
57
+ if listener.multi <= 1 and not listener.is_rss:
58
+ await send_status_message(listener.message)
59
+
60
+ await directListener.download(contents)
bot/helper/mirror_leech_utils/download_utils/direct_link_generator.py ADDED
@@ -0,0 +1,1918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cloudscraper import create_scraper
2
+ from hashlib import sha256
3
+ from http.cookiejar import MozillaCookieJar
4
+ from json import loads
5
+ from lxml.etree import HTML
6
+ from os import path as ospath
7
+ from re import findall, match, search
8
+ from requests import Session, post, get
9
+ from requests.adapters import HTTPAdapter
10
+ from time import sleep
11
+ from urllib.parse import parse_qs, urlparse, quote
12
+ from urllib3.util.retry import Retry
13
+ from uuid import uuid4
14
+ from base64 import b64decode, b64encode
15
+
16
+ from ....core.config_manager import Config
17
+ from ...ext_utils.exceptions import DirectDownloadLinkException
18
+ from ...ext_utils.help_messages import PASSWORD_ERROR_MESSAGE
19
+ from ...ext_utils.links_utils import is_share_link
20
+ from ...ext_utils.status_utils import speed_string_to_bytes
21
+
22
+ user_agent = (
23
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0"
24
+ )
25
+
26
+
27
+ def direct_link_generator(link):
28
+ """direct links generator"""
29
+ domain = urlparse(link).hostname
30
+ if not domain:
31
+ raise DirectDownloadLinkException("ERROR: Invalid URL")
32
+ elif "yadi.sk" in link or "disk.yandex." in link:
33
+ return yandex_disk(link)
34
+ elif "buzzheavier.com" in domain:
35
+ return buzzheavier(link)
36
+ elif "devuploads" in domain:
37
+ return devuploads(link)
38
+ elif "lulacloud.com" in domain:
39
+ return lulacloud(link)
40
+ elif "uploadhaven" in domain:
41
+ return uploadhaven(link)
42
+ elif "fuckingfast.co" in domain:
43
+ return fuckingfast_dl(link)
44
+ elif "mediafile.cc" in domain:
45
+ return mediafile(link)
46
+ elif "mediafire.com" in domain:
47
+ return mediafire(link)
48
+ elif "osdn.net" in domain:
49
+ return osdn(link)
50
+ elif "github.com" in domain:
51
+ return github(link)
52
+ elif "transfer.it" in domain:
53
+ return transfer_it(link)
54
+ elif "hxfile.co" in domain:
55
+ return hxfile(link)
56
+ elif "1drv.ms" in domain:
57
+ return onedrive(link)
58
+ elif any(x in domain for x in ["pixeldrain.com", "pixeldra.in"]):
59
+ return pixeldrain(link)
60
+ elif "racaty" in domain:
61
+ return racaty(link)
62
+ elif "1fichier.com" in domain:
63
+ return fichier(link)
64
+ elif "solidfiles.com" in domain:
65
+ return solidfiles(link)
66
+ elif "krakenfiles.com" in domain:
67
+ return krakenfiles(link)
68
+ elif "upload.ee" in domain:
69
+ return uploadee(link)
70
+ elif "gofile.io" in domain:
71
+ return gofile(link)
72
+ elif "send.cm" in domain:
73
+ return send_cm(link)
74
+ elif "tmpsend.com" in domain:
75
+ return tmpsend(link)
76
+ elif "easyupload.io" in domain:
77
+ return easyupload(link)
78
+ elif "streamvid.net" in domain:
79
+ return streamvid(link)
80
+ elif "shrdsk.me" in domain:
81
+ return shrdsk(link)
82
+ elif "u.pcloud.link" in domain:
83
+ return pcloud(link)
84
+ elif "qiwi.gg" in domain:
85
+ return qiwi(link)
86
+ elif "mp4upload.com" in domain:
87
+ return mp4upload(link)
88
+ elif "berkasdrive.com" in domain:
89
+ return berkasdrive(link)
90
+ elif "swisstransfer.com" in domain:
91
+ return swisstransfer(link)
92
+ elif any(x in domain for x in ["akmfiles.com", "akmfls.xyz"]):
93
+ return akmfiles(link)
94
+ elif any(
95
+ x in domain
96
+ for x in [
97
+ "dood.watch",
98
+ "doodstream.com",
99
+ "dood.to",
100
+ "dood.so",
101
+ "dood.cx",
102
+ "dood.la",
103
+ "dood.ws",
104
+ "dood.sh",
105
+ "doodstream.co",
106
+ "dood.pm",
107
+ "dood.wf",
108
+ "dood.re",
109
+ "dood.video",
110
+ "dooood.com",
111
+ "dood.yt",
112
+ "doods.yt",
113
+ "dood.stream",
114
+ "doods.pro",
115
+ "ds2play.com",
116
+ "d0o0d.com",
117
+ "ds2video.com",
118
+ "do0od.com",
119
+ "d000d.com",
120
+ ]
121
+ ):
122
+ return doods(link)
123
+ elif any(
124
+ x in domain
125
+ for x in [
126
+ "streamtape.com",
127
+ "streamtape.co",
128
+ "streamtape.cc",
129
+ "streamtape.to",
130
+ "streamtape.net",
131
+ "streamta.pe",
132
+ "streamtape.xyz",
133
+ ]
134
+ ):
135
+ return streamtape(link)
136
+ elif any(x in domain for x in ["wetransfer.com", "we.tl"]):
137
+ return wetransfer(link)
138
+ elif any(
139
+ x in domain
140
+ for x in [
141
+ "terabox.com",
142
+ "nephobox.com",
143
+ "4funbox.com",
144
+ "mirrobox.com",
145
+ "momerybox.com",
146
+ "teraboxapp.com",
147
+ "1024tera.com",
148
+ "terabox.app",
149
+ "gibibox.com",
150
+ "goaibox.com",
151
+ "terasharelink.com",
152
+ "teraboxlink.com",
153
+ "freeterabox.com",
154
+ "1024terabox.com",
155
+ "teraboxshare.com",
156
+ "terafileshare.com",
157
+ "terabox.club",
158
+ ]
159
+ ):
160
+ return terabox(link)
161
+ elif any(
162
+ x in domain
163
+ for x in [
164
+ "filelions.co",
165
+ "filelions.site",
166
+ "filelions.live",
167
+ "filelions.to",
168
+ "mycloudz.cc",
169
+ "cabecabean.lol",
170
+ "filelions.online",
171
+ "embedwish.com",
172
+ "kitabmarkaz.xyz",
173
+ "wishfast.top",
174
+ "streamwish.to",
175
+ "kissmovies.net",
176
+ ]
177
+ ):
178
+ return filelions_and_streamwish(link)
179
+ elif any(x in domain for x in ["streamhub.ink", "streamhub.to"]):
180
+ return streamhub(link)
181
+ elif any(
182
+ x in domain
183
+ for x in [
184
+ "linkbox.to",
185
+ "lbx.to",
186
+ "teltobx.net",
187
+ "telbx.net",
188
+ "linkbox.cloud",
189
+ ]
190
+ ):
191
+ return linkBox(link)
192
+ elif is_share_link(link):
193
+ return filepress(link) if "filepress" in domain else sharer_scraper(link)
194
+ elif any(
195
+ x in domain
196
+ for x in [
197
+ "anonfiles.com",
198
+ "zippyshare.com",
199
+ "letsupload.io",
200
+ "hotfile.io",
201
+ "bayfiles.com",
202
+ "megaupload.nz",
203
+ "letsupload.cc",
204
+ "filechan.org",
205
+ "myfile.is",
206
+ "vshare.is",
207
+ "rapidshare.nu",
208
+ "lolabits.se",
209
+ "openload.cc",
210
+ "share-online.is",
211
+ "upvid.cc",
212
+ "uptobox.com",
213
+ "uptobox.fr",
214
+ ]
215
+ ):
216
+ raise DirectDownloadLinkException(f"ERROR: R.I.P {domain}")
217
+ else:
218
+ raise DirectDownloadLinkException(f"No Direct link function found for {link}")
219
+
220
+
221
+ def get_captcha_token(session, params):
222
+ recaptcha_api = "https://www.google.com/recaptcha/api2"
223
+ res = session.get(f"{recaptcha_api}/anchor", params=params)
224
+ anchor_html = HTML(res.text)
225
+ if not (anchor_token := anchor_html.xpath('//input[@id="recaptcha-token"]/@value')):
226
+ return None
227
+ params["c"] = anchor_token[0]
228
+ params["reason"] = "q"
229
+ res = session.post(f"{recaptcha_api}/reload", params=params)
230
+ if token := findall(r'"rresp","(.*?)"', res.text):
231
+ return token[0]
232
+
233
+
234
+ def transfer_it(url):
235
+ resp = post("https://transfer-it-henna.vercel.app/post", json={"url": url})
236
+ if resp.status_code == 200:
237
+ return resp.json()["url"]
238
+ else:
239
+ raise DirectDownloadLinkException("ERROR: File Expired or File Not Found")
240
+
241
+
242
+ def buzzheavier(url):
243
+ """
244
+ Generate a direct download link for buzzheavier URLs.
245
+ @param link: URL from buzzheavier
246
+ @return: Direct download link
247
+ """
248
+ pattern = r"^https?://buzzheavier\.com/[a-zA-Z0-9]+$"
249
+ if not match(pattern, url):
250
+ return url
251
+
252
+ def _bhscraper(url, folder=False):
253
+ session = Session()
254
+ if "/download" not in url:
255
+ url += "/download"
256
+ url = url.strip()
257
+ session.headers.update(
258
+ {
259
+ "referer": url.split("/download")[0],
260
+ "hx-current-url": url.split("/download")[0],
261
+ "hx-request": "true",
262
+ "priority": "u=1, i",
263
+ }
264
+ )
265
+ try:
266
+ response = session.get(url)
267
+ d_url = response.headers.get("Hx-Redirect")
268
+ if not d_url:
269
+ if not folder:
270
+ raise DirectDownloadLinkException("ERROR: Gagal mendapatkan data")
271
+ return
272
+ return d_url
273
+ except Exception as e:
274
+ raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e
275
+
276
+ with Session() as session:
277
+ tree = HTML(session.get(url).text)
278
+ if link := tree.xpath(
279
+ "//a[contains(@class, 'link-button') and contains(@class, 'gay-button')]/@hx-get"
280
+ ):
281
+ return _bhscraper(f"https://buzzheavier.com{link[0]}")
282
+ elif folders := tree.xpath("//tbody[@id='tbody']/tr"):
283
+ details = {"contents": [], "title": "", "total_size": 0}
284
+ for data in folders:
285
+ try:
286
+ filename = data.xpath(".//a")[0].text.strip()
287
+ _id = data.xpath(".//a")[0].attrib.get("href", "").strip()
288
+ size = data.xpath(".//td[@class='text-center']/text()")[0].strip()
289
+ url = _bhscraper(f"https://buzzheavier.com{_id}", True)
290
+ item = {
291
+ "path": "",
292
+ "filename": filename,
293
+ "url": url,
294
+ }
295
+ details["contents"].append(item)
296
+ size = speed_string_to_bytes(size)
297
+ details["total_size"] += size
298
+ except:
299
+ continue
300
+ details["title"] = tree.xpath("//span/text()")[0].strip()
301
+ return details
302
+ else:
303
+ raise DirectDownloadLinkException("ERROR: No download link found")
304
+
305
+
306
+ def fuckingfast_dl(url):
307
+ """
308
+ Generate a direct download link for fuckingfast.co URLs.
309
+ @param url: URL from fuckingfast.co
310
+ @return: Direct download link
311
+ """
312
+ url = url.strip()
313
+
314
+ try:
315
+ response = get(url)
316
+ content = response.text
317
+ pattern = r'window\.open\((["\'])(https://fuckingfast\.co/dl/[^"\']+)\1'
318
+ if match := search(pattern, content):
319
+ return match.group(2)
320
+ else:
321
+ raise DirectDownloadLinkException(
322
+ "ERROR: Could not find download link in page"
323
+ )
324
+
325
+ except Exception as e:
326
+ raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e
327
+
328
+
329
+ def lulacloud(url):
330
+ """
331
+ Generate a direct download link for www.lulacloud.com URLs.
332
+ @param url: URL from www.lulacloud.com
333
+ @return: Direct download link
334
+ """
335
+ try:
336
+ res = post(url, headers={"Referer": url}, allow_redirects=False)
337
+ return res.headers["location"]
338
+ except Exception as e:
339
+ raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e
340
+
341
+
342
+ def devuploads(url):
343
+ """
344
+ Generate a direct download link for devuploads.com URLs.
345
+ @param url: URL from devuploads.com
346
+ @return: Direct download link
347
+ """
348
+ with Session() as session:
349
+ res = session.get(url)
350
+ html = HTML(res.text)
351
+ if not html.xpath("//input[@name]"):
352
+ raise DirectDownloadLinkException("ERROR: Unable to find link data")
353
+ data = {i.get("name"): i.get("value") for i in html.xpath("//input[@name]")}
354
+ res = session.post("https://gujjukhabar.in/", data=data)
355
+ html = HTML(res.text)
356
+ if not html.xpath("//input[@name]"):
357
+ raise DirectDownloadLinkException("ERROR: Unable to find link data")
358
+ data = {i.get("name"): i.get("value") for i in html.xpath("//input[@name]")}
359
+ resp = session.get(
360
+ "https://du2.devuploads.com/dlhash.php",
361
+ headers={
362
+ "Origin": "https://gujjukhabar.in",
363
+ "Referer": "https://gujjukhabar.in/",
364
+ },
365
+ )
366
+ if not resp.text:
367
+ raise DirectDownloadLinkException("ERROR: Unable to find ipp value")
368
+ data["ipp"] = resp.text.strip()
369
+ if not data.get("rand"):
370
+ raise DirectDownloadLinkException("ERROR: Unable to find rand value")
371
+ randpost = session.post(
372
+ "https://devuploads.com/token/token.php",
373
+ data={"rand": data["rand"], "msg": ""},
374
+ headers={
375
+ "Origin": "https://gujjukhabar.in",
376
+ "Referer": "https://gujjukhabar.in/",
377
+ },
378
+ )
379
+ if not randpost:
380
+ raise DirectDownloadLinkException("ERROR: Unable to find xd value")
381
+ data["xd"] = randpost.text.strip()
382
+ res = session.post(url, data=data)
383
+ html = HTML(res.text)
384
+ if not html.xpath("//input[@name='orilink']/@value"):
385
+ raise DirectDownloadLinkException("ERROR: Unable to find Direct Link")
386
+ direct_link = html.xpath("//input[@name='orilink']/@value")
387
+ return direct_link[0]
388
+
389
+
390
+ def uploadhaven(url):
391
+ """
392
+ Generate a direct download link for uploadhaven.com URLs.
393
+ @param url: URL from uploadhaven.com
394
+ @return: Direct download link
395
+ """
396
+ try:
397
+ res = get(url, headers={"Referer": "http://steamunlocked.net/"})
398
+ html = HTML(res.text)
399
+ if not html.xpath('//form[@method="POST"]//input'):
400
+ raise DirectDownloadLinkException("ERROR: Unable to find link data")
401
+ data = {
402
+ i.get("name"): i.get("value")
403
+ for i in html.xpath('//form[@method="POST"]//input')
404
+ }
405
+ sleep(15)
406
+ res = post(url, data=data, headers={"Referer": url}, cookies=res.cookies)
407
+ html = HTML(res.text)
408
+ if not html.xpath('//div[@class="alert alert-success mb-0"]//a'):
409
+ raise DirectDownloadLinkException("ERROR: Unable to find link data")
410
+ a = html.xpath('//div[@class="alert alert-success mb-0"]//a')[0]
411
+ return a.get("href")
412
+ except Exception as e:
413
+ raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e
414
+
415
+
416
+ def mediafile(url):
417
+ """
418
+ Generate a direct download link for mediafile.cc URLs.
419
+ @param url: URL from mediafile.cc
420
+ @return: Direct download link
421
+ """
422
+ try:
423
+ res = get(url, allow_redirects=True)
424
+ match = search(r"href='([^']+)'", res.text)
425
+ if not match:
426
+ raise DirectDownloadLinkException("ERROR: Unable to find link data")
427
+ download_url = match[1]
428
+ sleep(60)
429
+ res = get(download_url, headers={"Referer": url}, cookies=res.cookies)
430
+ postvalue = search(r"showFileInformation(.*);", res.text)
431
+ if not postvalue:
432
+ raise DirectDownloadLinkException("ERROR: Unable to find post value")
433
+ postid = postvalue[1].replace("(", "").replace(")", "")
434
+ response = post(
435
+ "https://mediafile.cc/account/ajax/file_details",
436
+ data={"u": postid},
437
+ headers={"X-Requested-With": "XMLHttpRequest"},
438
+ )
439
+ html = response.json()["html"]
440
+ return [
441
+ i for i in findall(r'https://[^\s"\']+', html) if "download_token" in i
442
+ ][1]
443
+ except Exception as e:
444
+ raise DirectDownloadLinkException(f"ERROR: {str(e)}") from e
445
+
446
+
447
+ def mediafire(url, session=None):
448
+ if "/folder/" in url:
449
+ return mediafireFolder(url)
450
+ if "::" in url:
451
+ _password = url.split("::")[-1]
452
+ url = url.split("::")[-2]
453
+ else:
454
+ _password = ""
455
+ if final_link := findall(
456
+ r"https?:\/\/download\d+\.mediafire\.com\/\S+\/\S+\/\S+", url
457
+ ):
458
+ return final_link[0]
459
+
460
+ def _repair_download(url, session):
461
+ try:
462
+ html = HTML(session.get(url).text)
463
+ if new_link := html.xpath('//a[@id="continue-btn"]/@href'):
464
+ return mediafire(f"https://mediafire.com/{new_link[0]}")
465
+ except Exception as e:
466
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
467
+
468
+ if session is None:
469
+ session = create_scraper()
470
+ parsed_url = urlparse(url)
471
+ url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
472
+ try:
473
+ html = HTML(session.get(url).text)
474
+ except Exception as e:
475
+ session.close()
476
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
477
+ if error := html.xpath('//p[@class="notranslate"]/text()'):
478
+ session.close()
479
+ raise DirectDownloadLinkException(f"ERROR: {error[0]}")
480
+ if html.xpath("//div[@class='passwordPrompt']"):
481
+ if not _password:
482
+ session.close()
483
+ raise DirectDownloadLinkException(
484
+ f"ERROR: {PASSWORD_ERROR_MESSAGE}".format(url)
485
+ )
486
+ try:
487
+ html = HTML(session.post(url, data={"downloadp": _password}).text)
488
+ except Exception as e:
489
+ session.close()
490
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
491
+ if html.xpath("//div[@class='passwordPrompt']"):
492
+ session.close()
493
+ raise DirectDownloadLinkException("ERROR: Wrong password.")
494
+ if not (final_link := html.xpath('//a[@aria-label="Download file"]/@href')):
495
+ if repair_link := html.xpath("//a[@class='retry']/@href"):
496
+ return _repair_download(repair_link[0], session)
497
+ raise DirectDownloadLinkException(
498
+ "ERROR: No links found in this page Try Again"
499
+ )
500
+ if final_link[0].startswith("//"):
501
+ final_url = f"https://{final_link[0][2:]}"
502
+ if _password:
503
+ final_url += f"::{_password}"
504
+ return mediafire(final_url, session)
505
+ session.close()
506
+ return final_link[0]
507
+
508
+
509
+ def osdn(url):
510
+ with create_scraper() as session:
511
+ try:
512
+ html = HTML(session.get(url).text)
513
+ except Exception as e:
514
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
515
+ if not (direct_link := html.xapth('//a[@class="mirror_link"]/@href')):
516
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
517
+ return f"https://osdn.net{direct_link[0]}"
518
+
519
+
520
+ def yandex_disk(url: str) -> str:
521
+ """Yandex.Disk direct link generator
522
+ Based on https://github.com/wldhx/yadisk-direct"""
523
+ try:
524
+ link = findall(r"\b(https?://(yadi\.sk|disk\.yandex\.(com|ru))\S+)", url)[0][0]
525
+ except IndexError:
526
+ return "No Yandex.Disk links found\n"
527
+ api = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}"
528
+ try:
529
+ return get(api.format(link)).json()["href"]
530
+ except KeyError as e:
531
+ raise DirectDownloadLinkException(
532
+ "ERROR: File not found/Download limit reached"
533
+ ) from e
534
+
535
+
536
+ def github(url):
537
+ """GitHub direct links generator"""
538
+ try:
539
+ findall(r"\bhttps?://.*github\.com.*releases\S+", url)[0]
540
+ except IndexError as e:
541
+ raise DirectDownloadLinkException("No GitHub Releases links found") from e
542
+ with create_scraper() as session:
543
+ _res = session.get(url, stream=True, allow_redirects=False)
544
+ if "location" in _res.headers:
545
+ return _res.headers["location"]
546
+ raise DirectDownloadLinkException("ERROR: Can't extract the link")
547
+
548
+
549
+ def hxfile(url):
550
+ if not ospath.isfile("hxfile.txt"):
551
+ raise DirectDownloadLinkException("ERROR: hxfile.txt (cookies) Not Found!")
552
+ try:
553
+ jar = MozillaCookieJar()
554
+ jar.load("hxfile.txt")
555
+ except Exception as e:
556
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
557
+ cookies = {cookie.name: cookie.value for cookie in jar}
558
+ try:
559
+ if url.strip().endswith(".html"):
560
+ url = url[:-5]
561
+ file_code = url.split("/")[-1]
562
+ html = HTML(
563
+ post(
564
+ url,
565
+ data={"op": "download2", "id": file_code},
566
+ cookies=cookies,
567
+ ).text
568
+ )
569
+ except Exception as e:
570
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
571
+ if direct_link := html.xpath("//a[@class='btn btn-dow']/@href"):
572
+ header = [f"Referer: {url}"]
573
+ return direct_link[0], header
574
+ raise DirectDownloadLinkException("ERROR: Direct download link not found")
575
+
576
+
577
+ def onedrive(link):
578
+ """Onedrive direct link generator
579
+ By https://github.com/junedkh"""
580
+ with create_scraper() as session:
581
+ try:
582
+ link = session.get(link).url
583
+ parsed_link = urlparse(link)
584
+ link_data = parse_qs(parsed_link.query)
585
+ except Exception as e:
586
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
587
+ if not link_data:
588
+ raise DirectDownloadLinkException("ERROR: Unable to find link_data")
589
+ folder_id = link_data.get("resid")
590
+ if not folder_id:
591
+ raise DirectDownloadLinkException("ERROR: folder id not found")
592
+ folder_id = folder_id[0]
593
+ authkey = link_data.get("authkey")
594
+ if not authkey:
595
+ raise DirectDownloadLinkException("ERROR: authkey not found")
596
+ authkey = authkey[0]
597
+ boundary = uuid4()
598
+ headers = {"content-type": f"multipart/form-data;boundary={boundary}"}
599
+ data = f"--{boundary}\r\nContent-Disposition: form-data;name=data\r\nPrefer: Migration=EnableRedirect;FailOnMigratedFiles\r\nX-HTTP-Method-Override: GET\r\nContent-Type: application/json\r\n\r\n--{boundary}--"
600
+ try:
601
+ resp = session.get(
602
+ f'https://api.onedrive.com/v1.0/drives/{folder_id.split("!", 1)[0]}/items/{folder_id}?$select=id,@content.downloadUrl&ump=1&authKey={authkey}',
603
+ headers=headers,
604
+ data=data,
605
+ ).json()
606
+ except Exception as e:
607
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
608
+ if "@content.downloadUrl" not in resp:
609
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
610
+ return resp["@content.downloadUrl"]
611
+
612
+
613
+ def pixeldrain(url):
614
+ try:
615
+ url = url.rstrip("/")
616
+ code = url.split("/")[-1].split("?", 1)[0]
617
+ response = get("https://pd.cybar.xyz/", allow_redirects=True)
618
+ return response.url + code
619
+ except Exception as e:
620
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
621
+
622
+
623
+ def streamtape(url):
624
+ splitted_url = url.split("/")
625
+ _id = splitted_url[4] if len(splitted_url) >= 6 else splitted_url[-1]
626
+ try:
627
+ html = HTML(get(url).text)
628
+ except Exception as e:
629
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
630
+ script = html.xpath(
631
+ "//script[contains(text(),'ideoooolink')]/text()"
632
+ ) or html.xpath("//script[contains(text(),'ideoolink')]/text()")
633
+ if not script:
634
+ raise DirectDownloadLinkException("ERROR: requeries script not found")
635
+ if not (link := findall(r"(&expires\S+)'", script[0])):
636
+ raise DirectDownloadLinkException("ERROR: Download link not found")
637
+ return f"https://streamtape.com/get_video?id={_id}{link[-1]}"
638
+
639
+
640
+ def racaty(url):
641
+ with create_scraper() as session:
642
+ try:
643
+ url = session.get(url).url
644
+ json_data = {"op": "download2", "id": url.split("/")[-1]}
645
+ html = HTML(session.post(url, data=json_data).text)
646
+ except Exception as e:
647
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
648
+ if direct_link := html.xpath("//a[@id='uniqueExpirylink']/@href"):
649
+ return direct_link[0]
650
+ else:
651
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
652
+
653
+
654
+ def fichier(link):
655
+ """1Fichier direct link generator
656
+ Based on https://github.com/Maujar
657
+ """
658
+ regex = r"^([http:\/\/|https:\/\/]+)?.*1fichier\.com\/\?.+"
659
+ gan = match(regex, link)
660
+ if not gan:
661
+ raise DirectDownloadLinkException("ERROR: The link you entered is wrong!")
662
+ if "::" in link:
663
+ pswd = link.split("::")[-1]
664
+ url = link.split("::")[-2]
665
+ else:
666
+ pswd = None
667
+ url = link
668
+ cget = create_scraper().request
669
+ try:
670
+ if pswd is None:
671
+ req = cget("post", url)
672
+ else:
673
+ pw = {"pass": pswd}
674
+ req = cget("post", url, data=pw)
675
+ except Exception as e:
676
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
677
+ if req.status_code == 404:
678
+ raise DirectDownloadLinkException(
679
+ "ERROR: File not found/The link you entered is wrong!"
680
+ )
681
+ html = HTML(req.text)
682
+ if dl_url := html.xpath('//a[@class="ok btn-general btn-orange"]/@href'):
683
+ return dl_url[0]
684
+ if not (ct_warn := html.xpath('//div[@class="ct_warn"]')):
685
+ raise DirectDownloadLinkException(
686
+ "ERROR: Error trying to generate Direct Link from 1fichier!"
687
+ )
688
+ if len(ct_warn) == 3:
689
+ str_2 = ct_warn[-1].text
690
+ if "you must wait" in str_2.lower():
691
+ if numbers := [int(word) for word in str_2.split() if word.isdigit()]:
692
+ raise DirectDownloadLinkException(
693
+ f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute."
694
+ )
695
+ else:
696
+ raise DirectDownloadLinkException(
697
+ "ERROR: 1fichier is on a limit. Please wait a few minutes/hour."
698
+ )
699
+ elif "protect access" in str_2.lower():
700
+ raise DirectDownloadLinkException(
701
+ f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(link)}"
702
+ )
703
+ else:
704
+ raise DirectDownloadLinkException(
705
+ "ERROR: Failed to generate Direct Link from 1fichier!"
706
+ )
707
+ elif len(ct_warn) == 4:
708
+ str_1 = ct_warn[-2].text
709
+ str_3 = ct_warn[-1].text
710
+ if "you must wait" in str_1.lower():
711
+ if numbers := [int(word) for word in str_1.split() if word.isdigit()]:
712
+ raise DirectDownloadLinkException(
713
+ f"ERROR: 1fichier is on a limit. Please wait {numbers[0]} minute."
714
+ )
715
+ else:
716
+ raise DirectDownloadLinkException(
717
+ "ERROR: 1fichier is on a limit. Please wait a few minutes/hour."
718
+ )
719
+ elif "bad password" in str_3.lower():
720
+ raise DirectDownloadLinkException(
721
+ "ERROR: The password you entered is wrong!"
722
+ )
723
+ raise DirectDownloadLinkException(
724
+ "ERROR: Error trying to generate Direct Link from 1fichier!"
725
+ )
726
+
727
+
728
+ def solidfiles(url):
729
+ """Solidfiles direct link generator
730
+ Based on https://github.com/Xonshiz/SolidFiles-Downloader
731
+ By https://github.com/Jusidama18"""
732
+ with create_scraper() as session:
733
+ try:
734
+ headers = {
735
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"
736
+ }
737
+ pageSource = session.get(url, headers=headers).text
738
+ mainOptions = str(
739
+ search(r"viewerOptions\'\,\ (.*?)\)\;", pageSource).group(1)
740
+ )
741
+ return loads(mainOptions)["downloadUrl"]
742
+ except Exception as e:
743
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
744
+
745
+
746
+ def krakenfiles(url):
747
+ with Session() as session:
748
+ try:
749
+ _res = session.get(url)
750
+ except Exception as e:
751
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
752
+ html = HTML(_res.text)
753
+ if post_url := html.xpath('//form[@id="dl-form"]/@action'):
754
+ post_url = f"https://krakenfiles.com{post_url[0]}"
755
+ else:
756
+ raise DirectDownloadLinkException("ERROR: Unable to find post link.")
757
+ if token := html.xpath('//input[@id="dl-token"]/@value'):
758
+ data = {"token": token[0]}
759
+ else:
760
+ raise DirectDownloadLinkException("ERROR: Unable to find token for post.")
761
+ try:
762
+ _json = session.post(post_url, data=data).json()
763
+ except Exception as e:
764
+ raise DirectDownloadLinkException(
765
+ f"ERROR: {e.__class__.__name__} While send post request"
766
+ ) from e
767
+ if _json["status"] != "ok":
768
+ raise DirectDownloadLinkException(
769
+ "ERROR: Unable to find download after post request"
770
+ )
771
+ return _json["url"]
772
+
773
+
774
+ def uploadee(url):
775
+ with create_scraper() as session:
776
+ try:
777
+ html = HTML(session.get(url).text)
778
+ except Exception as e:
779
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
780
+ if link := html.xpath("//a[@id='d_l']/@href"):
781
+ return link[0]
782
+ else:
783
+ raise DirectDownloadLinkException("ERROR: Direct Link not found")
784
+
785
+
786
+ def terabox(url):
787
+ if "/file/" in url:
788
+ return url
789
+ api_url = f"https://wdzone-terabox-api.vercel.app/api?url={quote(url)}"
790
+ try:
791
+ with Session() as session:
792
+ req = session.get(api_url, headers={"User-Agent": user_agent}).json()
793
+ except Exception as e:
794
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
795
+
796
+ details = {"contents": [], "title": "", "total_size": 0}
797
+ if "✅ Status" not in req:
798
+ raise DirectDownloadLinkException("ERROR: File not found!")
799
+ for data in req["📜 Extracted Info"]:
800
+ item = {
801
+ "path": "",
802
+ "filename": data["📂 Title"],
803
+ "url": data["🔽 Direct Download Link"],
804
+ }
805
+ details["contents"].append(item)
806
+ size = (data["📏 Size"]).replace(" ", "")
807
+ size = speed_string_to_bytes(size)
808
+ details["total_size"] += size
809
+ details["title"] = req["📜 Extracted Info"][0]["📂 Title"]
810
+ if len(details["contents"]) == 1:
811
+ return details["contents"][0]["url"]
812
+ return details
813
+
814
+
815
+ def filepress(url):
816
+ try:
817
+ url = get(f"https://filebee.xyz/file/{url.split('/')[-1]}").url
818
+ raw = urlparse(url)
819
+ json_data = {
820
+ "id": raw.path.split("/")[-1],
821
+ "method": "publicDownlaod",
822
+ }
823
+ api = f"{raw.scheme}://{raw.hostname}/api/file/downlaod/"
824
+ res2 = post(
825
+ api,
826
+ headers={"Referer": f"{raw.scheme}://{raw.hostname}"},
827
+ json=json_data,
828
+ ).json()
829
+ json_data2 = {
830
+ "id": res2["data"],
831
+ "method": "publicDownlaod",
832
+ }
833
+ api2 = f"{raw.scheme}://{raw.hostname}/api/file/downlaod2/"
834
+ res = post(
835
+ api2,
836
+ headers={"Referer": f"{raw.scheme}://{raw.hostname}"},
837
+ json=json_data2,
838
+ ).json()
839
+ except Exception as e:
840
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
841
+
842
+ if "data" not in res:
843
+ raise DirectDownloadLinkException(f'ERROR: {res["statusText"]}')
844
+ return f'https://drive.google.com/uc?id={res["data"]}&export=download'
845
+
846
+
847
+ def sharer_scraper(url):
848
+ cget = create_scraper().request
849
+ try:
850
+ url = cget("GET", url).url
851
+ raw = urlparse(url)
852
+ header = {
853
+ "useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.548.0 Safari/534.10"
854
+ }
855
+ res = cget("GET", url, headers=header)
856
+ except Exception as e:
857
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
858
+ key = findall(r'"key",\s+"(.*?)"', res.text)
859
+ if not key:
860
+ raise DirectDownloadLinkException("ERROR: Key not found!")
861
+ key = key[0]
862
+ if not HTML(res.text).xpath("//button[@id='drc']"):
863
+ raise DirectDownloadLinkException(
864
+ "ERROR: This link don't have direct download button"
865
+ )
866
+ boundary = uuid4()
867
+ headers = {
868
+ "Content-Type": f"multipart/form-data; boundary=----WebKitFormBoundary{boundary}",
869
+ "x-token": raw.hostname,
870
+ "useragent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.548.0 Safari/534.10",
871
+ }
872
+
873
+ data = (
874
+ f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="action"\r\n\r\ndirect\r\n'
875
+ f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="key"\r\n\r\n{key}\r\n'
876
+ f'------WebKitFormBoundary{boundary}\r\nContent-Disposition: form-data; name="action_token"\r\n\r\n\r\n'
877
+ f"------WebKitFormBoundary{boundary}--\r\n"
878
+ )
879
+ try:
880
+ res = cget("POST", url, cookies=res.cookies, headers=headers, data=data).json()
881
+ except Exception as e:
882
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
883
+ if "url" not in res:
884
+ raise DirectDownloadLinkException(
885
+ "ERROR: Drive Link not found, Try in your browser"
886
+ )
887
+ if "drive.google.com" in res["url"] or "drive.usercontent.google.com" in res["url"]:
888
+ return res["url"]
889
+ try:
890
+ res = cget("GET", res["url"])
891
+ except Exception as e:
892
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
893
+ if (drive_link := HTML(res.text).xpath("//a[contains(@class,'btn')]/@href")) and (
894
+ "drive.google.com" in drive_link[0]
895
+ or "drive.usercontent.google.com" in drive_link[0]
896
+ ):
897
+ return drive_link[0]
898
+ else:
899
+ raise DirectDownloadLinkException(
900
+ "ERROR: Drive Link not found, Try in your browser"
901
+ )
902
+
903
+
904
+ def wetransfer(url):
905
+ with create_scraper() as session:
906
+ try:
907
+ url = session.get(url).url
908
+ splited_url = url.split("/")
909
+ json_data = {"security_hash": splited_url[-1], "intent": "entire_transfer"}
910
+ res = session.post(
911
+ f"https://wetransfer.com/api/v4/transfers/{splited_url[-2]}/download",
912
+ json=json_data,
913
+ ).json()
914
+ except Exception as e:
915
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
916
+ if "direct_link" in res:
917
+ return res["direct_link"]
918
+ elif "message" in res:
919
+ raise DirectDownloadLinkException(f"ERROR: {res['message']}")
920
+ elif "error" in res:
921
+ raise DirectDownloadLinkException(f"ERROR: {res['error']}")
922
+ else:
923
+ raise DirectDownloadLinkException("ERROR: cannot find direct link")
924
+
925
+
926
+ def akmfiles(url):
927
+ with create_scraper() as session:
928
+ try:
929
+ html = HTML(
930
+ session.post(
931
+ url,
932
+ data={"op": "download2", "id": url.split("/")[-1]},
933
+ ).text
934
+ )
935
+ except Exception as e:
936
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
937
+ if direct_link := html.xpath("//a[contains(@class,'btn btn-dow')]/@href"):
938
+ return direct_link[0]
939
+ else:
940
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
941
+
942
+
943
+ def shrdsk(url):
944
+ with create_scraper() as session:
945
+ try:
946
+ _json = session.get(
947
+ f'https://us-central1-affiliate2apk.cloudfunctions.net/get_data?shortid={url.split("/")[-1]}',
948
+ ).json()
949
+ except Exception as e:
950
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
951
+ if "download_data" not in _json:
952
+ raise DirectDownloadLinkException("ERROR: Download data not found")
953
+ try:
954
+ _res = session.get(
955
+ f"https://shrdsk.me/download/{_json['download_data']}",
956
+ allow_redirects=False,
957
+ )
958
+ if "Location" in _res.headers:
959
+ return _res.headers["Location"]
960
+ except Exception as e:
961
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
962
+ raise DirectDownloadLinkException("ERROR: cannot find direct link in headers")
963
+
964
+
965
+ def linkBox(url: str):
966
+ parsed_url = urlparse(url)
967
+ try:
968
+ shareToken = parsed_url.path.split("/")[-1]
969
+ except:
970
+ raise DirectDownloadLinkException("ERROR: invalid URL")
971
+
972
+ details = {"contents": [], "title": "", "total_size": 0}
973
+
974
+ def __singleItem(session, itemId):
975
+ try:
976
+ _json = session.get(
977
+ "https://www.linkbox.to/api/file/detail",
978
+ params={"itemId": itemId},
979
+ ).json()
980
+ except Exception as e:
981
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
982
+ data = _json["data"]
983
+ if not data:
984
+ if "msg" in _json:
985
+ raise DirectDownloadLinkException(f"ERROR: {_json['msg']}")
986
+ raise DirectDownloadLinkException("ERROR: data not found")
987
+ itemInfo = data["itemInfo"]
988
+ if not itemInfo:
989
+ raise DirectDownloadLinkException("ERROR: itemInfo not found")
990
+ filename = itemInfo["name"]
991
+ sub_type = itemInfo.get("sub_type")
992
+ if sub_type and not filename.strip().endswith(sub_type):
993
+ filename += f".{sub_type}"
994
+ if not details["title"]:
995
+ details["title"] = filename
996
+ item = {
997
+ "path": "",
998
+ "filename": filename,
999
+ "url": itemInfo["url"],
1000
+ }
1001
+ if "size" in itemInfo:
1002
+ size = itemInfo["size"]
1003
+ if isinstance(size, str) and size.isdigit():
1004
+ size = float(size)
1005
+ details["total_size"] += size
1006
+ details["contents"].append(item)
1007
+
1008
+ def __fetch_links(session, _id=0, folderPath=""):
1009
+ params = {
1010
+ "shareToken": shareToken,
1011
+ "pageSize": 1000,
1012
+ "pid": _id,
1013
+ }
1014
+ try:
1015
+ _json = session.get(
1016
+ "https://www.linkbox.to/api/file/share_out_list",
1017
+ params=params,
1018
+ ).json()
1019
+ except Exception as e:
1020
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1021
+ data = _json["data"]
1022
+ if not data:
1023
+ if "msg" in _json:
1024
+ raise DirectDownloadLinkException(f"ERROR: {_json['msg']}")
1025
+ raise DirectDownloadLinkException("ERROR: data not found")
1026
+ try:
1027
+ if data["shareType"] == "singleItem":
1028
+ return __singleItem(session, data["itemId"])
1029
+ except:
1030
+ pass
1031
+ if not details["title"]:
1032
+ details["title"] = data["dirName"]
1033
+ contents = data["list"]
1034
+ if not contents:
1035
+ return None
1036
+ for content in contents:
1037
+ if content["type"] == "dir" and "url" not in content:
1038
+ if not folderPath:
1039
+ newFolderPath = ospath.join(details["title"], content["name"])
1040
+ else:
1041
+ newFolderPath = ospath.join(folderPath, content["name"])
1042
+ if not details["title"]:
1043
+ details["title"] = content["name"]
1044
+ __fetch_links(session, content["id"], newFolderPath)
1045
+ elif "url" in content:
1046
+ if not folderPath:
1047
+ folderPath = details["title"]
1048
+ filename = content["name"]
1049
+ if (
1050
+ sub_type := content.get("sub_type")
1051
+ ) and not filename.strip().endswith(sub_type):
1052
+ filename += f".{sub_type}"
1053
+ item = {
1054
+ "path": ospath.join(folderPath),
1055
+ "filename": filename,
1056
+ "url": content["url"],
1057
+ }
1058
+ if "size" in content:
1059
+ size = content["size"]
1060
+ if isinstance(size, str) and size.isdigit():
1061
+ size = float(size)
1062
+ details["total_size"] += size
1063
+ details["contents"].append(item)
1064
+
1065
+ try:
1066
+ with Session() as session:
1067
+ __fetch_links(session)
1068
+ except DirectDownloadLinkException as e:
1069
+ raise e
1070
+ return details
1071
+
1072
+
1073
+ def gofile(url):
1074
+ try:
1075
+ if "::" in url:
1076
+ _password = url.split("::")[-1]
1077
+ _password = sha256(_password.encode("utf-8")).hexdigest()
1078
+ url = url.split("::")[-2]
1079
+ else:
1080
+ _password = ""
1081
+ _id = url.split("/")[-1]
1082
+ except Exception as e:
1083
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}")
1084
+
1085
+ def __get_token(session):
1086
+ headers = {
1087
+ "User-Agent": user_agent,
1088
+ "Accept-Encoding": "gzip, deflate, br",
1089
+ "Accept": "*/*",
1090
+ "Connection": "keep-alive",
1091
+ }
1092
+ __url = "https://api.gofile.io/accounts"
1093
+ try:
1094
+ __res = session.post(__url, headers=headers).json()
1095
+ if __res["status"] != "ok":
1096
+ raise DirectDownloadLinkException("ERROR: Failed to get token.")
1097
+ return __res["data"]["token"]
1098
+ except Exception as e:
1099
+ raise e
1100
+
1101
+ def __fetch_links(session, _id, folderPath=""):
1102
+ _url = f"https://api.gofile.io/contents/{_id}?cache=true"
1103
+ headers = {
1104
+ "User-Agent": user_agent,
1105
+ "Accept-Encoding": "gzip, deflate, br",
1106
+ "Accept": "*/*",
1107
+ "Connection": "keep-alive",
1108
+ "Authorization": "Bearer" + " " + token,
1109
+ "X-Website-Token": "4fd6sg89d7s6",
1110
+ }
1111
+ if _password:
1112
+ _url += f"&password={_password}"
1113
+ try:
1114
+ _json = session.get(_url, headers=headers).json()
1115
+ except Exception as e:
1116
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}")
1117
+ if _json["status"] in "error-passwordRequired":
1118
+ raise DirectDownloadLinkException(
1119
+ f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}"
1120
+ )
1121
+ if _json["status"] in "error-passwordWrong":
1122
+ raise DirectDownloadLinkException("ERROR: This password is wrong !")
1123
+ if _json["status"] in "error-notFound":
1124
+ raise DirectDownloadLinkException(
1125
+ "ERROR: File not found on gofile's server"
1126
+ )
1127
+ if _json["status"] in "error-notPublic":
1128
+ raise DirectDownloadLinkException("ERROR: This folder is not public")
1129
+
1130
+ data = _json["data"]
1131
+
1132
+ if not details["title"]:
1133
+ details["title"] = data["name"] if data["type"] == "folder" else _id
1134
+
1135
+ contents = data["children"]
1136
+ for content in contents.values():
1137
+ if content["type"] == "folder":
1138
+ if not content["public"]:
1139
+ continue
1140
+ if not folderPath:
1141
+ newFolderPath = ospath.join(details["title"], content["name"])
1142
+ else:
1143
+ newFolderPath = ospath.join(folderPath, content["name"])
1144
+ __fetch_links(session, content["id"], newFolderPath)
1145
+ else:
1146
+ if not folderPath:
1147
+ folderPath = details["title"]
1148
+ item = {
1149
+ "path": ospath.join(folderPath),
1150
+ "filename": content["name"],
1151
+ "url": content["link"],
1152
+ }
1153
+ if "size" in content:
1154
+ size = content["size"]
1155
+ if isinstance(size, str) and size.isdigit():
1156
+ size = float(size)
1157
+ details["total_size"] += size
1158
+ details["contents"].append(item)
1159
+
1160
+ details = {"contents": [], "title": "", "total_size": 0}
1161
+ with Session() as session:
1162
+ try:
1163
+ token = __get_token(session)
1164
+ except Exception as e:
1165
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}")
1166
+ details["header"] = f"Cookie: accountToken={token}"
1167
+ try:
1168
+ __fetch_links(session, _id)
1169
+ except Exception as e:
1170
+ raise DirectDownloadLinkException(e)
1171
+
1172
+ if len(details["contents"]) == 1:
1173
+ return (details["contents"][0]["url"], details["header"])
1174
+ return details
1175
+
1176
+
1177
+ def mediafireFolder(url):
1178
+ if "::" in url:
1179
+ _password = url.split("::")[-1]
1180
+ url = url.split("::")[-2]
1181
+ else:
1182
+ _password = ""
1183
+ try:
1184
+ raw = url.split("/", 4)[-1]
1185
+ folderkey = raw.split("/", 1)[0]
1186
+ folderkey = folderkey.split(",")
1187
+ except:
1188
+ raise DirectDownloadLinkException("ERROR: Could not parse ")
1189
+ if len(folderkey) == 1:
1190
+ folderkey = folderkey[0]
1191
+ details = {"contents": [], "title": "", "total_size": 0, "header": ""}
1192
+
1193
+ session = create_scraper()
1194
+ adapter = HTTPAdapter(
1195
+ max_retries=Retry(total=10, read=10, connect=10, backoff_factor=0.3)
1196
+ )
1197
+ session.mount("http://", adapter)
1198
+ session.mount("https://", adapter)
1199
+ session = create_scraper(
1200
+ browser={"browser": "firefox", "platform": "windows", "mobile": False},
1201
+ delay=10,
1202
+ sess=session,
1203
+ )
1204
+ folder_infos = []
1205
+
1206
+ def __get_info(folderkey):
1207
+ try:
1208
+ if isinstance(folderkey, list):
1209
+ folderkey = ",".join(folderkey)
1210
+ _json = session.post(
1211
+ "https://www.mediafire.com/api/1.5/folder/get_info.php",
1212
+ data={
1213
+ "recursive": "yes",
1214
+ "folder_key": folderkey,
1215
+ "response_format": "json",
1216
+ },
1217
+ ).json()
1218
+ except Exception as e:
1219
+ raise DirectDownloadLinkException(
1220
+ f"ERROR: {e.__class__.__name__} While getting info"
1221
+ )
1222
+ _res = _json["response"]
1223
+ if "folder_infos" in _res:
1224
+ folder_infos.extend(_res["folder_infos"])
1225
+ elif "folder_info" in _res:
1226
+ folder_infos.append(_res["folder_info"])
1227
+ elif "message" in _res:
1228
+ raise DirectDownloadLinkException(f"ERROR: {_res['message']}")
1229
+ else:
1230
+ raise DirectDownloadLinkException("ERROR: something went wrong!")
1231
+
1232
+ try:
1233
+ __get_info(folderkey)
1234
+ except Exception as e:
1235
+ raise DirectDownloadLinkException(e)
1236
+
1237
+ details["title"] = folder_infos[0]["name"]
1238
+
1239
+ def __scraper(url):
1240
+ session = create_scraper()
1241
+ parsed_url = urlparse(url)
1242
+ url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
1243
+
1244
+ try:
1245
+ html = HTML(session.get(url).text)
1246
+ except:
1247
+ return None
1248
+ if html.xpath("//div[@class='passwordPrompt']"):
1249
+ if not _password:
1250
+ raise DirectDownloadLinkException(
1251
+ f"ERROR: {PASSWORD_ERROR_MESSAGE}".format(url)
1252
+ )
1253
+ try:
1254
+ html = HTML(session.post(url, data={"downloadp": _password}).text)
1255
+ except:
1256
+ return None
1257
+ if html.xpath("//div[@class='passwordPrompt']"):
1258
+ return None
1259
+ try:
1260
+ final_link = __decode_url(html)
1261
+ except:
1262
+ return None
1263
+ return final_link
1264
+
1265
+ def __decode_url(html):
1266
+ enc_url = html.xpath('//a[@id="downloadButton"]')
1267
+ if enc_url:
1268
+ final_link = enc_url[0].attrib.get("href")
1269
+ scrambled = enc_url[0].attrib.get("data-scrambled-url")
1270
+ if final_link and scrambled:
1271
+ try:
1272
+ final_link = b64decode(scrambled).decode("utf-8")
1273
+ return final_link
1274
+ except:
1275
+ return None
1276
+ elif final_link.startswith("http"):
1277
+ return final_link
1278
+ elif final_link.startswith("//"):
1279
+ return __scraper(f"https:{final_link}")
1280
+ else:
1281
+ return None
1282
+ else:
1283
+ return None
1284
+
1285
+ def __get_content(folderKey, folderPath="", content_type="folders"):
1286
+ try:
1287
+ params = {
1288
+ "content_type": content_type,
1289
+ "folder_key": folderKey,
1290
+ "response_format": "json",
1291
+ }
1292
+ _json = session.get(
1293
+ "https://www.mediafire.com/api/1.5/folder/get_content.php",
1294
+ params=params,
1295
+ ).json()
1296
+ except Exception as e:
1297
+ raise DirectDownloadLinkException(
1298
+ f"ERROR: {e.__class__.__name__} While getting content"
1299
+ )
1300
+ _res = _json["response"]
1301
+ if "message" in _res:
1302
+ raise DirectDownloadLinkException(f"ERROR: {_res['message']}")
1303
+ _folder_content = _res["folder_content"]
1304
+ if content_type == "folders":
1305
+ folders = _folder_content["folders"]
1306
+ for folder in folders:
1307
+ if folderPath:
1308
+ newFolderPath = ospath.join(folderPath, folder["name"])
1309
+ else:
1310
+ newFolderPath = ospath.join(folder["name"])
1311
+ __get_content(folder["folderkey"], newFolderPath)
1312
+ __get_content(folderKey, folderPath, "files")
1313
+ else:
1314
+ files = _folder_content["files"]
1315
+ for file in files:
1316
+ item = {}
1317
+ if not (_url := __scraper(file["links"]["normal_download"])):
1318
+ continue
1319
+ item["filename"] = file["filename"]
1320
+ if not folderPath:
1321
+ folderPath = details["title"]
1322
+ item["path"] = ospath.join(folderPath)
1323
+ item["url"] = _url
1324
+ if "size" in file:
1325
+ size = file["size"]
1326
+ if isinstance(size, str) and size.isdigit():
1327
+ size = float(size)
1328
+ details["total_size"] += size
1329
+ details["contents"].append(item)
1330
+
1331
+ try:
1332
+ for folder in folder_infos:
1333
+ __get_content(folder["folderkey"], folder["name"])
1334
+ except Exception as e:
1335
+ raise DirectDownloadLinkException(e)
1336
+ finally:
1337
+ session.close()
1338
+ if len(details["contents"]) == 1:
1339
+ return (details["contents"][0]["url"], [details["header"]])
1340
+ return details
1341
+
1342
+
1343
+ def cf_bypass(url):
1344
+ "DO NOT ABUSE THIS"
1345
+ try:
1346
+ data = {"cmd": "request.get", "url": url, "maxTimeout": 60000}
1347
+ _json = post(
1348
+ "https://cf.jmdkh.eu.org/v1",
1349
+ headers={"Content-Type": "application/json"},
1350
+ json=data,
1351
+ ).json()
1352
+ if _json["status"] == "ok":
1353
+ return _json["solution"]["response"]
1354
+ except Exception as e:
1355
+ e
1356
+ raise DirectDownloadLinkException("ERROR: Con't bypass cloudflare")
1357
+
1358
+
1359
+ def send_cm_file(url, file_id=None):
1360
+ if "::" in url:
1361
+ _password = url.split("::")[-1]
1362
+ url = url.split("::")[-2]
1363
+ else:
1364
+ _password = ""
1365
+ _passwordNeed = False
1366
+ with create_scraper() as session:
1367
+ if file_id is None:
1368
+ try:
1369
+ html = HTML(session.get(url).text)
1370
+ except Exception as e:
1371
+ raise DirectDownloadLinkException(
1372
+ f"ERROR: {e.__class__.__name__}"
1373
+ ) from e
1374
+ if html.xpath("//input[@name='password']"):
1375
+ _passwordNeed = True
1376
+ if not (file_id := html.xpath("//input[@name='id']/@value")):
1377
+ raise DirectDownloadLinkException("ERROR: file_id not found")
1378
+ try:
1379
+ data = {"op": "download2", "id": file_id}
1380
+ if _password and _passwordNeed:
1381
+ data["password"] = _password
1382
+ _res = session.post("https://send.cm/", data=data, allow_redirects=False)
1383
+ if "Location" in _res.headers:
1384
+ return (_res.headers["Location"], ["Referer: https://send.cm/"])
1385
+ except Exception as e:
1386
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1387
+ if _passwordNeed:
1388
+ raise DirectDownloadLinkException(
1389
+ f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}"
1390
+ )
1391
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
1392
+
1393
+
1394
+ def send_cm(url):
1395
+ if "/d/" in url:
1396
+ return send_cm_file(url)
1397
+ elif "/s/" not in url:
1398
+ file_id = url.split("/")[-1]
1399
+ return send_cm_file(url, file_id)
1400
+ splitted_url = url.split("/")
1401
+ details = {
1402
+ "contents": [],
1403
+ "title": "",
1404
+ "total_size": 0,
1405
+ "header": "Referer: https://send.cm/",
1406
+ }
1407
+ if len(splitted_url) == 5:
1408
+ url += "/"
1409
+ splitted_url = url.split("/")
1410
+ if len(splitted_url) >= 7:
1411
+ details["title"] = splitted_url[5]
1412
+ else:
1413
+ details["title"] = splitted_url[-1]
1414
+ session = Session()
1415
+
1416
+ def __collectFolders(html):
1417
+ folders = []
1418
+ folders_urls = html.xpath("//h6/a/@href")
1419
+ folders_names = html.xpath("//h6/a/text()")
1420
+ for folders_url, folders_name in zip(folders_urls, folders_names):
1421
+ folders.append(
1422
+ {
1423
+ "folder_link": folders_url.strip(),
1424
+ "folder_name": folders_name.strip(),
1425
+ }
1426
+ )
1427
+ return folders
1428
+
1429
+ def __getFile_link(file_id):
1430
+ try:
1431
+ _res = session.post(
1432
+ "https://send.cm/",
1433
+ data={"op": "download2", "id": file_id},
1434
+ allow_redirects=False,
1435
+ )
1436
+ if "Location" in _res.headers:
1437
+ return _res.headers["Location"]
1438
+ except:
1439
+ pass
1440
+
1441
+ def __getFiles(html):
1442
+ files = []
1443
+ hrefs = html.xpath('//tr[@class="selectable"]//a/@href')
1444
+ file_names = html.xpath('//tr[@class="selectable"]//a/text()')
1445
+ sizes = html.xpath('//tr[@class="selectable"]//span/text()')
1446
+ for href, file_name, size_text in zip(hrefs, file_names, sizes):
1447
+ files.append(
1448
+ {
1449
+ "file_id": href.split("/")[-1],
1450
+ "file_name": file_name.strip(),
1451
+ "size": speed_string_to_bytes(size_text.strip()),
1452
+ }
1453
+ )
1454
+ return files
1455
+
1456
+ def __writeContents(html_text, folderPath=""):
1457
+ folders = __collectFolders(html_text)
1458
+ for folder in folders:
1459
+ _html = HTML(cf_bypass(folder["folder_link"]))
1460
+ __writeContents(_html, ospath.join(folderPath, folder["folder_name"]))
1461
+ files = __getFiles(html_text)
1462
+ for file in files:
1463
+ if not (link := __getFile_link(file["file_id"])):
1464
+ continue
1465
+ item = {"url": link, "filename": file["filename"], "path": folderPath}
1466
+ details["total_size"] += file["size"]
1467
+ details["contents"].append(item)
1468
+
1469
+ try:
1470
+ mainHtml = HTML(cf_bypass(url))
1471
+ except DirectDownloadLinkException as e:
1472
+ raise e
1473
+ except Exception as e:
1474
+ raise DirectDownloadLinkException(
1475
+ f"ERROR: {e.__class__.__name__} While getting mainHtml"
1476
+ )
1477
+
1478
+ try:
1479
+ __writeContents(mainHtml, details["title"])
1480
+ except DirectDownloadLinkException as e:
1481
+ raise e
1482
+ except Exception as e:
1483
+ raise DirectDownloadLinkException(
1484
+ f"ERROR: {e.__class__.__name__} While writing Contents"
1485
+ )
1486
+ finally:
1487
+ session.close()
1488
+ if len(details["contents"]) == 1:
1489
+ return (details["contents"][0]["url"], [details["header"]])
1490
+ return details
1491
+
1492
+
1493
+ def doods(url):
1494
+ if "/e/" in url:
1495
+ url = url.replace("/e/", "/d/")
1496
+ parsed_url = urlparse(url)
1497
+ with create_scraper() as session:
1498
+ try:
1499
+ html = HTML(session.get(url).text)
1500
+ except Exception as e:
1501
+ raise DirectDownloadLinkException(
1502
+ f"ERROR: {e.__class__.__name__} While fetching token link"
1503
+ ) from e
1504
+ if not (link := html.xpath("//div[@class='download-content']//a/@href")):
1505
+ raise DirectDownloadLinkException(
1506
+ "ERROR: Token Link not found or maybe not allow to download! open in browser."
1507
+ )
1508
+ link = f"{parsed_url.scheme}://{parsed_url.hostname}{link[0]}"
1509
+ sleep(2)
1510
+ try:
1511
+ _res = session.get(link)
1512
+ except Exception as e:
1513
+ raise DirectDownloadLinkException(
1514
+ f"ERROR: {e.__class__.__name__} While fetching download link"
1515
+ ) from e
1516
+ if not (link := search(r"window\.open\('(\S+)'", _res.text)):
1517
+ raise DirectDownloadLinkException("ERROR: Download link not found try again")
1518
+ return (link.group(1), [f"Referer: {parsed_url.scheme}://{parsed_url.hostname}/"])
1519
+
1520
+
1521
+ def easyupload(url):
1522
+ if "::" in url:
1523
+ _password = url.split("::")[-1]
1524
+ url = url.split("::")[-2]
1525
+ else:
1526
+ _password = ""
1527
+ file_id = url.split("/")[-1]
1528
+ with create_scraper() as session:
1529
+ try:
1530
+ _res = session.get(url)
1531
+ except Exception as e:
1532
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}")
1533
+ first_page_html = HTML(_res.text)
1534
+ if (
1535
+ first_page_html.xpath("//h6[contains(text(),'Password Protected')]")
1536
+ and not _password
1537
+ ):
1538
+ raise DirectDownloadLinkException(
1539
+ f"ERROR:\n{PASSWORD_ERROR_MESSAGE.format(url)}"
1540
+ )
1541
+ if not (
1542
+ match := search(
1543
+ r"https://eu(?:[1-9][0-9]?|100)\.easyupload\.io/action\.php", _res.text
1544
+ )
1545
+ ):
1546
+ raise DirectDownloadLinkException(
1547
+ "ERROR: Failed to get server for EasyUpload Link"
1548
+ )
1549
+ action_url = match.group()
1550
+ session.headers.update({"referer": "https://easyupload.io/"})
1551
+ recaptcha_params = {
1552
+ "k": "6LfWajMdAAAAAGLXz_nxz2tHnuqa-abQqC97DIZ3",
1553
+ "ar": "1",
1554
+ "co": "aHR0cHM6Ly9lYXN5dXBsb2FkLmlvOjQ0Mw..",
1555
+ "hl": "en",
1556
+ "v": "0hCdE87LyjzAkFO5Ff-v7Hj1",
1557
+ "size": "invisible",
1558
+ "cb": "c3o1vbaxbmwe",
1559
+ }
1560
+ if not (captcha_token := get_captcha_token(session, recaptcha_params)):
1561
+ raise DirectDownloadLinkException("ERROR: Captcha token not found")
1562
+ try:
1563
+ data = {
1564
+ "type": "download-token",
1565
+ "url": file_id,
1566
+ "value": _password,
1567
+ "captchatoken": captcha_token,
1568
+ "method": "regular",
1569
+ }
1570
+ json_resp = session.post(url=action_url, data=data).json()
1571
+ except Exception as e:
1572
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1573
+ if "download_link" in json_resp:
1574
+ return json_resp["download_link"]
1575
+ elif "data" in json_resp:
1576
+ raise DirectDownloadLinkException(
1577
+ f"ERROR: Failed to generate direct link due to {json_resp['data']}"
1578
+ )
1579
+ raise DirectDownloadLinkException(
1580
+ "ERROR: Failed to generate direct link from EasyUpload."
1581
+ )
1582
+
1583
+
1584
+ def filelions_and_streamwish(url):
1585
+ parsed_url = urlparse(url)
1586
+ hostname = parsed_url.hostname
1587
+ scheme = parsed_url.scheme
1588
+ if any(
1589
+ x in hostname
1590
+ for x in [
1591
+ "filelions.co",
1592
+ "filelions.live",
1593
+ "filelions.to",
1594
+ "filelions.site",
1595
+ "cabecabean.lol",
1596
+ "filelions.online",
1597
+ "mycloudz.cc",
1598
+ ]
1599
+ ):
1600
+ apiKey = Config.FILELION_API
1601
+ apiUrl = "https://vidhideapi.com"
1602
+ elif any(
1603
+ x in hostname
1604
+ for x in [
1605
+ "embedwish.com",
1606
+ "kissmovies.net",
1607
+ "kitabmarkaz.xyz",
1608
+ "wishfast.top",
1609
+ "streamwish.to",
1610
+ ]
1611
+ ):
1612
+ apiKey = Config.STREAMWISH_API
1613
+ apiUrl = "https://api.streamwish.com"
1614
+ if not apiKey:
1615
+ raise DirectDownloadLinkException(
1616
+ f"ERROR: API is not provided get it from {scheme}://{hostname}"
1617
+ )
1618
+ file_code = url.split("/")[-1]
1619
+ quality = ""
1620
+ if bool(file_code.strip().endswith(("_o", "_h", "_n", "_l"))):
1621
+ spited_file_code = file_code.rsplit("_", 1)
1622
+ quality = spited_file_code[1]
1623
+ file_code = spited_file_code[0]
1624
+ url = f"{scheme}://{hostname}/{file_code}"
1625
+ try:
1626
+ _res = get(
1627
+ f"{apiUrl}/api/file/direct_link",
1628
+ params={"key": apiKey, "file_code": file_code, "hls": "1"},
1629
+ ).json()
1630
+ except Exception as e:
1631
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1632
+ if _res["status"] != 200:
1633
+ raise DirectDownloadLinkException(f"ERROR: {_res['msg']}")
1634
+ result = _res["result"]
1635
+ if not result["versions"]:
1636
+ raise DirectDownloadLinkException("ERROR: File Not Found")
1637
+ error = "\nProvide a quality to download the video\nAvailable Quality:"
1638
+ for version in result["versions"]:
1639
+ if quality == version["name"]:
1640
+ return version["url"]
1641
+ elif version["name"] == "l":
1642
+ error += "\nLow"
1643
+ elif version["name"] == "n":
1644
+ error += "\nNormal"
1645
+ elif version["name"] == "o":
1646
+ error += "\nOriginal"
1647
+ elif version["name"] == "h":
1648
+ error += "\nHD"
1649
+ error += f" <code>{url}_{version['name']}</code>"
1650
+ raise DirectDownloadLinkException(f"ERROR: {error}")
1651
+
1652
+
1653
+ def streamvid(url: str):
1654
+ file_code = url.split("/")[-1]
1655
+ parsed_url = urlparse(url)
1656
+ url = f"{parsed_url.scheme}://{parsed_url.hostname}/d/{file_code}"
1657
+ quality_defined = bool(url.strip().endswith(("_o", "_h", "_n", "_l")))
1658
+ with create_scraper() as session:
1659
+ try:
1660
+ html = HTML(session.get(url).text)
1661
+ except Exception as e:
1662
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1663
+ if quality_defined:
1664
+ data = {}
1665
+ if not (inputs := html.xpath('//form[@id="F1"]//input')):
1666
+ raise DirectDownloadLinkException("ERROR: No inputs found")
1667
+ for i in inputs:
1668
+ if key := i.get("name"):
1669
+ data[key] = i.get("value")
1670
+ try:
1671
+ html = HTML(session.post(url, data=data).text)
1672
+ except Exception as e:
1673
+ raise DirectDownloadLinkException(
1674
+ f"ERROR: {e.__class__.__name__}"
1675
+ ) from e
1676
+ if not (
1677
+ script := html.xpath(
1678
+ '//script[contains(text(),"document.location.href")]/text()'
1679
+ )
1680
+ ):
1681
+ if error := html.xpath(
1682
+ '//div[@class="alert alert-danger"][1]/text()[2]'
1683
+ ):
1684
+ raise DirectDownloadLinkException(f"ERROR: {error[0]}")
1685
+ raise DirectDownloadLinkException(
1686
+ "ERROR: direct link script not found!"
1687
+ )
1688
+ if directLink := findall(r'document\.location\.href="(.*)"', script[0]):
1689
+ return directLink[0]
1690
+ raise DirectDownloadLinkException(
1691
+ "ERROR: direct link not found! in the script"
1692
+ )
1693
+ elif (qualities_urls := html.xpath('//div[@id="dl_versions"]/a/@href')) and (
1694
+ qualities := html.xpath('//div[@id="dl_versions"]/a/text()[2]')
1695
+ ):
1696
+ error = "\nProvide a quality to download the video\nAvailable Quality:"
1697
+ for quality_url, quality in zip(qualities_urls, qualities):
1698
+ error += f"\n{quality.strip()} <code>{quality_url}</code>"
1699
+ raise DirectDownloadLinkException(f"ERROR: {error}")
1700
+ elif error := html.xpath('//div[@class="not-found-text"]/text()'):
1701
+ raise DirectDownloadLinkException(f"ERROR: {error[0]}")
1702
+ raise DirectDownloadLinkException("ERROR: Something went wrong")
1703
+
1704
+
1705
+ def streamhub(url):
1706
+ file_code = url.split("/")[-1]
1707
+ parsed_url = urlparse(url)
1708
+ url = f"{parsed_url.scheme}://{parsed_url.hostname}/d/{file_code}"
1709
+ with create_scraper() as session:
1710
+ try:
1711
+ html = HTML(session.get(url).text)
1712
+ except Exception as e:
1713
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1714
+ if not (inputs := html.xpath('//form[@name="F1"]//input')):
1715
+ raise DirectDownloadLinkException("ERROR: No inputs found")
1716
+ data = {}
1717
+ for i in inputs:
1718
+ if key := i.get("name"):
1719
+ data[key] = i.get("value")
1720
+ session.headers.update({"referer": url})
1721
+ sleep(1)
1722
+ try:
1723
+ html = HTML(session.post(url, data=data).text)
1724
+ except Exception as e:
1725
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1726
+ if directLink := html.xpath(
1727
+ '//a[@class="btn btn-primary btn-go downloadbtn"]/@href'
1728
+ ):
1729
+ return directLink[0]
1730
+ if error := html.xpath('//div[@class="alert alert-danger"]/text()[2]'):
1731
+ raise DirectDownloadLinkException(f"ERROR: {error[0]}")
1732
+ raise DirectDownloadLinkException("ERROR: direct link not found!")
1733
+
1734
+
1735
+ def pcloud(url):
1736
+ with create_scraper() as session:
1737
+ try:
1738
+ res = session.get(url)
1739
+ except Exception as e:
1740
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1741
+ if link := findall(r".downloadlink.:..(https:.*)..", res.text):
1742
+ return link[0].replace(r"\/", "/")
1743
+ raise DirectDownloadLinkException("ERROR: Direct link not found")
1744
+
1745
+
1746
+ def tmpsend(url):
1747
+ parsed_url = urlparse(url)
1748
+ if any(x in parsed_url.path for x in ["thank-you", "download"]):
1749
+ query_params = parse_qs(parsed_url.query)
1750
+ if file_id := query_params.get("d"):
1751
+ file_id = file_id[0]
1752
+ elif not (file_id := parsed_url.path.strip("/")):
1753
+ raise DirectDownloadLinkException("ERROR: Invalid URL format")
1754
+ referer_url = f"https://tmpsend.com/thank-you?d={file_id}"
1755
+ header = [f"Referer: {referer_url}"]
1756
+ download_link = f"https://tmpsend.com/download?d={file_id}"
1757
+ return download_link, header
1758
+
1759
+
1760
+ def qiwi(url):
1761
+ """qiwi.gg link generator
1762
+ based on https://github.com/aenulrofik"""
1763
+ file_id = url.split("/")[-1]
1764
+ try:
1765
+ res = get(url).text
1766
+ except Exception as e:
1767
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1768
+ tree = HTML(res)
1769
+ if name := tree.xpath('//h1[@class="page_TextHeading__VsM7r"]/text()'):
1770
+ ext = name[0].split(".")[-1]
1771
+ return f"https://spyderrock.com/{file_id}.{ext}"
1772
+ else:
1773
+ raise DirectDownloadLinkException("ERROR: File not found")
1774
+
1775
+
1776
+ def mp4upload(url):
1777
+ with Session() as session:
1778
+ try:
1779
+ url = url.replace("embed-", "")
1780
+ req = session.get(url).text
1781
+ tree = HTML(req)
1782
+ inputs = tree.xpath("//input")
1783
+ header = ["Referer: https://www.mp4upload.com/"]
1784
+ data = {input.get("name"): input.get("value") for input in inputs}
1785
+ if not data:
1786
+ raise DirectDownloadLinkException("ERROR: File Not Found!")
1787
+ post = session.post(
1788
+ url,
1789
+ data=data,
1790
+ headers={
1791
+ "User-Agent": user_agent,
1792
+ "Referer": "https://www.mp4upload.com/",
1793
+ },
1794
+ ).text
1795
+ tree = HTML(post)
1796
+ inputs = tree.xpath('//form[@name="F1"]//input')
1797
+ data = {
1798
+ input.get("name"): input.get("value").replace(" ", "")
1799
+ for input in inputs
1800
+ }
1801
+ if not data:
1802
+ raise DirectDownloadLinkException("ERROR: File Not Found!")
1803
+ data["referer"] = url
1804
+ direct_link = session.post(url, data=data).url
1805
+ return direct_link, header
1806
+ except:
1807
+ raise DirectDownloadLinkException("ERROR: File Not Found!")
1808
+
1809
+
1810
+ def berkasdrive(url):
1811
+ """berkasdrive.com link generator
1812
+ by https://github.com/aenulrofik"""
1813
+ try:
1814
+ sesi = get(url).text
1815
+ except Exception as e:
1816
+ raise DirectDownloadLinkException(f"ERROR: {e.__class__.__name__}") from e
1817
+ html = HTML(sesi)
1818
+ if link := html.xpath("//script")[0].text.split('"')[1]:
1819
+ return b64decode(link).decode("utf-8")
1820
+ else:
1821
+ raise DirectDownloadLinkException("ERROR: File Not Found!")
1822
+
1823
+
1824
+ def swisstransfer(link):
1825
+ matched_link = match(
1826
+ r"https://www\.swisstransfer\.com/d/([\w-]+)(?:\:\:(\w+))?", link
1827
+ )
1828
+ if not matched_link:
1829
+ raise DirectDownloadLinkException(
1830
+ f"ERROR: Invalid SwissTransfer link format {link}"
1831
+ )
1832
+
1833
+ transfer_id, password = matched_link.groups()
1834
+ password = password or ""
1835
+
1836
+ def encode_password(password):
1837
+ return b64encode(password.encode("utf-8")).decode("utf-8") if password else ""
1838
+
1839
+ def getfile(transfer_id, password):
1840
+ url = f"https://www.swisstransfer.com/api/links/{transfer_id}"
1841
+ headers = {
1842
+ "User-Agent": "Mozilla/5.0",
1843
+ "Authorization": encode_password(password) if password else "",
1844
+ "Content-Type": "" if password else "application/json",
1845
+ }
1846
+ response = get(url, headers=headers)
1847
+
1848
+ if response.status_code == 200:
1849
+ try:
1850
+ return response.json(), [f"{k}: {v}" for k, v in headers.items() if v]
1851
+ except ValueError:
1852
+ raise DirectDownloadLinkException(
1853
+ f"ERROR: Error parsing JSON response {response.text}"
1854
+ )
1855
+ raise DirectDownloadLinkException(
1856
+ f"ERROR: Error fetching file details {response.status_code}, {response.text}"
1857
+ )
1858
+
1859
+ def gettoken(password, containerUUID, fileUUID):
1860
+ url = "https://www.swisstransfer.com/api/generateDownloadToken"
1861
+ headers = {
1862
+ "User-Agent": "Mozilla/5.0",
1863
+ "Content-Type": "application/json",
1864
+ }
1865
+ body = {
1866
+ "password": password,
1867
+ "containerUUID": containerUUID,
1868
+ "fileUUID": fileUUID,
1869
+ }
1870
+
1871
+ response = post(url, headers=headers, json=body)
1872
+
1873
+ if response.status_code == 200:
1874
+ return response.text.strip().replace('"', "")
1875
+ raise DirectDownloadLinkException(
1876
+ f"ERROR: Error generating download token {response.status_code}, {response.text}"
1877
+ )
1878
+
1879
+ data, _ = getfile(transfer_id, password)
1880
+ if not data:
1881
+ return None
1882
+
1883
+ try:
1884
+ container_uuid = data["data"]["containerUUID"]
1885
+ download_host = data["data"]["downloadHost"]
1886
+ files = data["data"]["container"]["files"]
1887
+ folder_name = data["data"]["container"]["message"] or "unknown"
1888
+ except (KeyError, IndexError, TypeError) as e:
1889
+ raise DirectDownloadLinkException(f"ERROR: Error parsing file details {e}")
1890
+
1891
+ total_size = sum(file["fileSizeInBytes"] for file in files)
1892
+
1893
+ if len(files) == 1:
1894
+ file = files[0]
1895
+ file_uuid = file["UUID"]
1896
+ token = gettoken(password, container_uuid, file_uuid)
1897
+ download_url = f"https://{download_host}/api/download/{transfer_id}/{file_uuid}?token={token}"
1898
+ return download_url, ["User-Agent:Mozilla/5.0"]
1899
+
1900
+ contents = []
1901
+ for file in files:
1902
+ file_uuid = file["UUID"]
1903
+ file_name = file["fileName"]
1904
+ file_size = file["fileSizeInBytes"]
1905
+
1906
+ token = gettoken(password, container_uuid, file_uuid)
1907
+ if not token:
1908
+ continue
1909
+
1910
+ download_url = f"https://{download_host}/api/download/{transfer_id}/{file_uuid}?token={token}"
1911
+ contents.append({"filename": file_name, "path": "", "url": download_url})
1912
+
1913
+ return {
1914
+ "contents": contents,
1915
+ "title": folder_name,
1916
+ "total_size": total_size,
1917
+ "header": "User-Agent:Mozilla/5.0",
1918
+ }
bot/helper/mirror_leech_utils/download_utils/direct_link_generator_license.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RAPHIELSCAPE PUBLIC LICENSE
2
+ Version 1.c, June 2019
3
+
4
+ Copyright (C) 2019 Raphielscape LLC.
5
+ Copyright (C) 2019 Devscapes Open Source Holding GmbH.
6
+
7
+ Everyone is permitted to copy and distribute verbatim or modified
8
+ copies of this license document, and changing it is allowed as long
9
+ as the name is changed.
10
+
11
+ RAPHIELSCAPE PUBLIC LICENSE
12
+ A-1. DEFINITIONS
13
+
14
+ 0. “This License” refers to version 1.c of the Raphielscape Public License.
15
+
16
+ 1. “Copyright” also means copyright-like laws that apply to other kinds of works.
17
+
18
+ 2. “The Work" refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”.
19
+ “Licensees” and “recipients” may be individuals or organizations.
20
+
21
+ 3. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission,
22
+ other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work
23
+ or a work “based on” the earlier work.
24
+
25
+ 4. Source Form. The “source form” for a work means the preferred form of the work for making modifications to it.
26
+ “Object code” means any non-source form of a work.
27
+
28
+ The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and
29
+ (for an executable work) run the object code and to modify the work, including scripts to control those activities.
30
+
31
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the
32
+ Corresponding Source.
33
+ The Corresponding Source for a work in source code form is that same work.
34
+
35
+ 5. "The author" refers to "author" of the code, which is the one that made the particular code which exists inside of
36
+ the Corresponding Source.
37
+
38
+ 6. "Owner" refers to any parties which is made the early form of the Corresponding Source.
39
+
40
+ A-2. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
41
+
42
+ 0. You must give any other recipients of the Work or Derivative Works a copy of this License; and
43
+
44
+ 1. You must cause any modified files to carry prominent notices stating that You changed the files; and
45
+
46
+ 2. You must retain, in the Source form of any Derivative Works that You distribute,
47
+ this license, all copyright, patent, trademark, authorships and attribution notices
48
+ from the Source form of the Work; and
49
+
50
+ 3. Respecting the author and owner of works that are distributed in any way.
51
+
52
+ You may add Your own copyright statement to Your modifications and may provide
53
+ additional or different license terms and conditions for use, reproduction,
54
+ or distribution of Your modifications, or for any such Derivative Works as a whole,
55
+ provided Your use, reproduction, and distribution of the Work otherwise complies
56
+ with the conditions stated in this License.
57
+
58
+ B. DISCLAIMER OF WARRANTY
59
+
60
+ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
61
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
62
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
63
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
64
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
65
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
67
+ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68
+
69
+ C. REVISED VERSION OF THIS LICENSE
70
+
71
+ The Devscapes Open Source Holding GmbH. may publish revised and/or new versions of the
72
+ Raphielscape Public License from time to time. Such new versions will be similar in spirit
73
+ to the present version, but may differ in detail to address new problems or concerns.
74
+
75
+ Each version is given a distinguishing version number. If the Program specifies that a
76
+ certain numbered version of the Raphielscape Public License "or any later version" applies to it,
77
+ you have the option of following the terms and conditions either of that numbered version or of
78
+ any later version published by the Devscapes Open Source Holding GmbH. If the Program does not specify a
79
+ version number of the Raphielscape Public License, you may choose any version ever published
80
+ by the Devscapes Open Source Holding GmbH.
81
+
82
+ END OF LICENSE
bot/helper/mirror_leech_utils/download_utils/gd_download.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from secrets import token_urlsafe
2
+
3
+ from .... import task_dict, task_dict_lock, LOGGER
4
+ from ...ext_utils.bot_utils import sync_to_async
5
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
6
+ from ...mirror_leech_utils.gdrive_utils.count import GoogleDriveCount
7
+ from ...mirror_leech_utils.gdrive_utils.download import GoogleDriveDownload
8
+ from ...mirror_leech_utils.status_utils.gdrive_status import GoogleDriveStatus
9
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
10
+ from ...telegram_helper.message_utils import send_status_message
11
+
12
+
13
+ async def add_gd_download(listener, path):
14
+ drive = GoogleDriveCount()
15
+ name, mime_type, listener.size, _, _ = await sync_to_async(
16
+ drive.count, listener.link, listener.user_id
17
+ )
18
+ if mime_type is None:
19
+ await listener.on_download_error(name)
20
+ return
21
+
22
+ listener.name = listener.name or name
23
+ gid = token_urlsafe(12)
24
+
25
+ msg, button = await stop_duplicate_check(listener)
26
+ if msg:
27
+ await listener.on_download_error(msg, button)
28
+ return
29
+
30
+ add_to_queue, event = await check_running_tasks(listener)
31
+ if add_to_queue:
32
+ LOGGER.info(f"Added to Queue/Download: {listener.name}")
33
+ async with task_dict_lock:
34
+ task_dict[listener.mid] = QueueStatus(listener, gid, "dl")
35
+ await listener.on_download_start()
36
+ if listener.multi <= 1:
37
+ await send_status_message(listener.message)
38
+ await event.wait()
39
+ if listener.is_cancelled:
40
+ return
41
+
42
+ drive = GoogleDriveDownload(listener, path)
43
+ async with task_dict_lock:
44
+ task_dict[listener.mid] = GoogleDriveStatus(listener, drive, gid, "dl")
45
+
46
+ if add_to_queue:
47
+ LOGGER.info(f"Start Queued Download from GDrive: {listener.name}")
48
+ else:
49
+ LOGGER.info(f"Download from GDrive: {listener.name}")
50
+ await listener.on_download_start()
51
+ if listener.multi <= 1:
52
+ await send_status_message(listener.message)
53
+
54
+ await sync_to_async(drive.download)
bot/helper/mirror_leech_utils/download_utils/jd_download.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import wait_for, Event, sleep
2
+ from functools import partial
3
+ from pyrogram.filters import regex, user
4
+ from pyrogram.handlers import CallbackQueryHandler
5
+ from time import time
6
+ from aiofiles.os import path as aiopath, remove
7
+ from aiofiles import open as aiopen
8
+ from base64 import b64encode
9
+ from secrets import token_urlsafe
10
+ from myjd.exception import MYJDException
11
+
12
+ from .... import (
13
+ task_dict,
14
+ task_dict_lock,
15
+ LOGGER,
16
+ jd_listener_lock,
17
+ jd_downloads,
18
+ )
19
+ from ...ext_utils.bot_utils import new_task
20
+ from ....core.jdownloader_booter import jdownloader
21
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
22
+ from ...listeners.jdownloader_listener import on_download_start
23
+ from ...mirror_leech_utils.status_utils.jdownloader_status import JDownloaderStatus
24
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
25
+ from ...telegram_helper.button_build import ButtonMaker
26
+ from ...telegram_helper.message_utils import (
27
+ send_message,
28
+ send_status_message,
29
+ edit_message,
30
+ delete_message,
31
+ )
32
+
33
+
34
+ @new_task
35
+ async def configureDownload(_, query, obj):
36
+ data = query.data.split()
37
+ message = query.message
38
+ await query.answer()
39
+ if data[1] == "sdone":
40
+ obj.event.set()
41
+ elif data[1] == "cancel":
42
+ await edit_message(message, "Task has been cancelled.")
43
+ obj.listener.is_cancelled = True
44
+ obj.event.set()
45
+
46
+
47
+ class JDownloaderHelper:
48
+ def __init__(self, listener):
49
+ self._timeout = 600
50
+ self._reply_to = ""
51
+ self.listener = listener
52
+ self.event = Event()
53
+
54
+ async def _event_handler(self):
55
+ pfunc = partial(configureDownload, obj=self)
56
+ handler = self.listener.client.add_handler(
57
+ CallbackQueryHandler(
58
+ pfunc, filters=regex("^jdq") & user(self.listener.user_id)
59
+ ),
60
+ group=-1,
61
+ )
62
+ try:
63
+ await wait_for(self.event.wait(), timeout=self._timeout)
64
+ except:
65
+ await edit_message(self._reply_to, "Timed Out. Task has been cancelled!")
66
+ self.listener.is_cancelled = True
67
+ self.event.set()
68
+ finally:
69
+ self.listener.client.remove_handler(*handler)
70
+
71
+ async def wait_for_configurations(self):
72
+ buttons = ButtonMaker()
73
+ buttons.url_button("Select", "https://my.jdownloader.org")
74
+ buttons.data_button("Done Selecting", "jdq sdone")
75
+ buttons.data_button("Cancel", "jdq cancel")
76
+ button = buttons.build_menu(2)
77
+ msg = f"Remove the unwanted files or change variants or edit files names from myJdownloader site for <b>{self.listener.name}</b>.\nDon't start it manually!\n\nAfter finish press Done Selecting!\nTimeout: 10 min"
78
+ self._reply_to = await send_message(self.listener.message, msg, button)
79
+ await self._event_handler()
80
+ if not self.listener.is_cancelled:
81
+ await delete_message(self._reply_to)
82
+ return not self.listener.is_cancelled
83
+
84
+
85
+ async def get_online_packages(path, state="grabbing"):
86
+ if state == "grabbing":
87
+ queued_downloads = await jdownloader.device.linkgrabber.query_packages(
88
+ [{"saveTo": True}]
89
+ )
90
+ return [qd["uuid"] for qd in queued_downloads if qd["saveTo"].startswith(path)]
91
+ else:
92
+ download_packages = await jdownloader.device.downloads.query_packages(
93
+ [{"saveTo": True}]
94
+ )
95
+ return [dl["uuid"] for dl in download_packages if dl["saveTo"].startswith(path)]
96
+
97
+
98
+ def trim_path(path):
99
+ path_components = path.split("/")
100
+
101
+ trimmed_components = [
102
+ component[:255] if len(component) > 255 else component
103
+ for component in path_components
104
+ ]
105
+
106
+ return "/".join(trimmed_components)
107
+
108
+
109
+ async def get_jd_download_directory():
110
+ res = await jdownloader.device.config.get(
111
+ "org.jdownloader.settings.GeneralSettings", None, "DefaultDownloadFolder"
112
+ )
113
+ return f'/{res.strip("/")}/'
114
+
115
+
116
+ async def add_jd_download(listener, path):
117
+ try:
118
+ async with jd_listener_lock:
119
+ gid = token_urlsafe(12)
120
+ if not jdownloader.is_connected:
121
+ raise MYJDException(jdownloader.error)
122
+
123
+ default_path = await get_jd_download_directory()
124
+ if not jd_downloads:
125
+ await jdownloader.device.linkgrabber.clear_list()
126
+ if odl := await jdownloader.device.downloads.query_packages([{}]):
127
+ odl_list = [od["uuid"] for od in odl]
128
+ await jdownloader.device.downloads.remove_links(
129
+ package_ids=odl_list
130
+ )
131
+ elif odl := await jdownloader.device.linkgrabber.query_packages([{}]):
132
+ if odl_list := [
133
+ od["uuid"]
134
+ for od in odl
135
+ if od.get("saveTo", "").startswith(default_path)
136
+ ]:
137
+ await jdownloader.device.linkgrabber.remove_links(
138
+ package_ids=odl_list
139
+ )
140
+
141
+ jd_downloads[gid] = {"status": "collect", "path": path}
142
+
143
+ if await aiopath.exists(listener.link):
144
+ async with aiopen(listener.link, "rb") as dlc:
145
+ content = await dlc.read()
146
+ content = b64encode(content)
147
+ await jdownloader.device.linkgrabber.add_container(
148
+ "DLC", f"data:;base64,{content.decode()}"
149
+ )
150
+ else:
151
+ await jdownloader.device.linkgrabber.add_links(
152
+ [
153
+ {
154
+ "autoExtract": False,
155
+ "links": listener.link,
156
+ "deepDecrypt": True,
157
+ "overwritePackagizerRules": listener.join,
158
+ }
159
+ ],
160
+ )
161
+ await sleep(1)
162
+ LOGGER.info(f"JDownloader Collecting Data: {listener.link}")
163
+ while await jdownloader.device.linkgrabber.is_collecting():
164
+ await sleep(0.5)
165
+ LOGGER.info(f"JDownloader Finished Collecting Data: {listener.link}")
166
+ start_time = time()
167
+ online_packages = []
168
+ corrupted_packages = []
169
+ remove_unknown = False
170
+ name = ""
171
+ error = ""
172
+ while (time() - start_time) < 90:
173
+ queued_downloads = await jdownloader.device.linkgrabber.query_packages(
174
+ [
175
+ {
176
+ "bytesTotal": True,
177
+ "saveTo": True,
178
+ "availableOnlineCount": True,
179
+ "availableOfflineCount": True,
180
+ "availableTempUnknownCount": True,
181
+ "availableUnknownCount": True,
182
+ }
183
+ ],
184
+ )
185
+
186
+ if not online_packages and corrupted_packages and error:
187
+ await jdownloader.device.linkgrabber.remove_links(
188
+ package_ids=corrupted_packages,
189
+ )
190
+ raise MYJDException(error)
191
+
192
+ for pack in queued_downloads:
193
+ if pack.get("onlineCount", 1) == 0:
194
+ error = f"{pack.get('name', '')}"
195
+ LOGGER.error(error)
196
+ corrupted_packages.append(pack["uuid"])
197
+ continue
198
+
199
+ if (
200
+ pack.get("tempUnknownCount", 0) > 0
201
+ or pack.get("unknownCount", 0) > 0
202
+ or pack.get("offlineCount", 0) > 0
203
+ ):
204
+ remove_unknown = True
205
+
206
+ listener.size += pack.get("bytesTotal", 0)
207
+ online_packages.append(pack["uuid"])
208
+ if not name:
209
+ name = pack.get("name", "").replace("/", "").split("/")[0]
210
+ save_to = pack["saveTo"]
211
+ if save_to.startswith(default_path):
212
+ save_to = trim_path(save_to)
213
+ await jdownloader.device.linkgrabber.set_download_directory(
214
+ save_to.replace(default_path, f"{path}/", 1),
215
+ [pack["uuid"]],
216
+ )
217
+
218
+ if online_packages:
219
+ break
220
+ else:
221
+ error = (
222
+ name
223
+ or "Download Not Added! Maybe some issues in jdownloader or site!"
224
+ )
225
+ if corrupted_packages or online_packages:
226
+ packages_to_remove = corrupted_packages + online_packages
227
+ await jdownloader.device.linkgrabber.remove_links(
228
+ package_ids=packages_to_remove,
229
+ )
230
+ raise MYJDException(error)
231
+
232
+ jd_downloads[gid]["ids"] = online_packages
233
+
234
+ corrupted_links = []
235
+ if remove_unknown:
236
+ links = await jdownloader.device.linkgrabber.query_links(
237
+ [{"packageUUIDs": online_packages, "availability": True}],
238
+ )
239
+ corrupted_links = [
240
+ link["uuid"]
241
+ for link in links
242
+ if link["availability"].lower() != "online"
243
+ ]
244
+ if corrupted_packages or corrupted_links:
245
+ await jdownloader.device.linkgrabber.remove_links(
246
+ corrupted_links,
247
+ corrupted_packages,
248
+ )
249
+
250
+ listener.name = listener.name or name
251
+
252
+ msg, button = await stop_duplicate_check(listener)
253
+ if msg:
254
+ await jdownloader.device.linkgrabber.remove_links(
255
+ package_ids=online_packages
256
+ )
257
+ await listener.on_download_error(msg, button)
258
+ async with jd_listener_lock:
259
+ del jd_downloads[gid]
260
+ return
261
+
262
+ if listener.select:
263
+ if not await JDownloaderHelper(listener).wait_for_configurations():
264
+ await jdownloader.device.linkgrabber.remove_links(
265
+ package_ids=online_packages
266
+ )
267
+ await listener.remove_from_same_dir()
268
+ async with jd_listener_lock:
269
+ del jd_downloads[gid]
270
+ return
271
+ else:
272
+ online_packages = await get_online_packages(path)
273
+ if not online_packages:
274
+ raise MYJDException(
275
+ "Select: This Download have been removed manually!"
276
+ )
277
+ async with jd_listener_lock:
278
+ jd_downloads[gid]["ids"] = online_packages
279
+
280
+ add_to_queue, event = await check_running_tasks(listener)
281
+ if add_to_queue:
282
+ LOGGER.info(f"Added to Queue/Download: {listener.name}")
283
+ async with task_dict_lock:
284
+ task_dict[listener.mid] = QueueStatus(listener, gid, "dl")
285
+ await listener.on_download_start()
286
+ if listener.multi <= 1:
287
+ await send_status_message(listener.message)
288
+ await event.wait()
289
+ if listener.is_cancelled:
290
+ return
291
+
292
+ online_packages = await get_online_packages(path)
293
+ if not online_packages:
294
+ raise MYJDException("Queue: This Download have been removed manually!")
295
+ async with jd_listener_lock:
296
+ jd_downloads[gid]["ids"] = online_packages
297
+
298
+ await jdownloader.device.linkgrabber.move_to_downloadlist(
299
+ package_ids=online_packages
300
+ )
301
+
302
+ await sleep(0.5)
303
+
304
+ online_packages = await get_online_packages(path, "down")
305
+ if not online_packages:
306
+ online_packages = await get_online_packages(path)
307
+ if not online_packages:
308
+ raise MYJDException(
309
+ "Linkgrabber: This Download have been removed manually!"
310
+ )
311
+ await jdownloader.device.linkgrabber.move_to_downloadlist(
312
+ package_ids=online_packages
313
+ )
314
+ await sleep(0.5)
315
+ online_packages = await get_online_packages(path, "down")
316
+ if not online_packages:
317
+ raise MYJDException(
318
+ "Download List: This Download have been removed manually!"
319
+ )
320
+
321
+ async with jd_listener_lock:
322
+ jd_downloads[gid]["status"] = "down"
323
+ jd_downloads[gid]["ids"] = online_packages
324
+
325
+ await jdownloader.device.downloads.force_download(package_ids=online_packages)
326
+
327
+ async with task_dict_lock:
328
+ task_dict[listener.mid] = JDownloaderStatus(listener, gid)
329
+
330
+ await on_download_start()
331
+
332
+ if add_to_queue:
333
+ LOGGER.info(f"Start Queued Download from JDownloader: {listener.name}")
334
+ else:
335
+ LOGGER.info(f"Download with JDownloader: {listener.name}")
336
+ await listener.on_download_start()
337
+ if listener.multi <= 1:
338
+ await send_status_message(listener.message)
339
+ except (Exception, MYJDException) as e:
340
+ await listener.on_download_error(f"{e}".strip())
341
+ async with jd_listener_lock:
342
+ if gid in jd_downloads:
343
+ del jd_downloads[gid]
344
+ return
345
+ finally:
346
+ if await aiopath.exists(listener.link):
347
+ await remove(listener.link)
348
+
349
+ await sleep(2)
350
+
351
+ links = await jdownloader.device.downloads.query_links(
352
+ [
353
+ {
354
+ "packageUUIDs": online_packages,
355
+ "status": True,
356
+ }
357
+ ],
358
+ )
359
+ links_to_remove = []
360
+ force_download = False
361
+ for dlink in links:
362
+ if dlink.get("status", "") == "Invalid download directory":
363
+ force_download = True
364
+ new_name, ext = dlink["name"].rsplit(".", 1)
365
+ new_name = new_name[: 250 - len(f".{ext}".encode())]
366
+ new_name = f"{new_name}.{ext}"
367
+ await jdownloader.device.downloads.rename_link(dlink["uuid"], new_name)
368
+ elif dlink.get("status", "") == "HLS stream broken?":
369
+ links_to_remove.append(dlink["uuid"])
370
+
371
+ if links_to_remove:
372
+ await jdownloader.device.downloads.remove_links(links_to_remove)
373
+ if force_download:
374
+ await jdownloader.device.downloads.force_download(package_ids=online_packages)
bot/helper/mirror_leech_utils/download_utils/nzb_downloader.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import remove, path as aiopath
2
+ from asyncio import gather, sleep
3
+ from sabnzbdapi.exception import NotLoggedIn, LoginFailed
4
+
5
+ from .... import (
6
+ task_dict,
7
+ task_dict_lock,
8
+ sabnzbd_client,
9
+ LOGGER,
10
+ )
11
+ from ....core.config_manager import Config
12
+ from ...ext_utils.task_manager import check_running_tasks
13
+ from ...listeners.nzb_listener import on_download_start
14
+ from ...ext_utils.db_handler import database
15
+ from ...ext_utils.bot_utils import bt_selection_buttons
16
+ from ...mirror_leech_utils.status_utils.nzb_status import SabnzbdStatus
17
+ from ...telegram_helper.message_utils import (
18
+ send_status_message,
19
+ send_message,
20
+ delete_message,
21
+ )
22
+
23
+
24
+ async def add_servers():
25
+ res = await sabnzbd_client.check_login()
26
+ if res and (servers := res["servers"]):
27
+ sabnzbd_client.LOGGED_IN = True
28
+ tasks = []
29
+ servers_hosts = [x["host"] for x in servers]
30
+ for server in list(Config.USENET_SERVERS):
31
+ if server["host"] not in servers_hosts:
32
+ tasks.append(sabnzbd_client.add_server(server))
33
+ Config.USENET_SERVERS.append(server)
34
+ if Config.DATABASE_URL:
35
+ tasks.append(
36
+ database.update_config({"USENET_SERVERS": Config.USENET_SERVERS})
37
+ )
38
+ if tasks:
39
+ try:
40
+ await gather(*tasks)
41
+ except LoginFailed as e:
42
+ raise e
43
+ elif not res and (
44
+ Config.USENET_SERVERS
45
+ and (
46
+ not Config.USENET_SERVERS[0]["host"]
47
+ or not Config.USENET_SERVERS[0]["username"]
48
+ or not Config.USENET_SERVERS[0]["password"]
49
+ )
50
+ or not Config.USENET_SERVERS
51
+ ):
52
+ sabnzbd_client.LOGGED_IN = False
53
+ raise NotLoggedIn("Set USENET_SERVERS in bsetting or config!")
54
+ else:
55
+ if tasks := [
56
+ sabnzbd_client.add_server(server) for server in Config.USENET_SERVERS
57
+ ]:
58
+ try:
59
+ await gather(*tasks)
60
+ sabnzbd_client.LOGGED_IN = True
61
+ except LoginFailed as e:
62
+ if len(tasks) == 1:
63
+ sabnzbd_client.LOGGED_IN = False
64
+ raise e
65
+
66
+
67
+ async def add_nzb(listener, path):
68
+ if not sabnzbd_client.LOGGED_IN:
69
+ try:
70
+ await add_servers()
71
+ except Exception as e:
72
+ await listener.on_download_error(str(e))
73
+ return
74
+ try:
75
+ await sabnzbd_client.create_category(f"{listener.mid}", path)
76
+ url = listener.link
77
+ nzbpath = None
78
+ if await aiopath.exists(listener.link):
79
+ url = None
80
+ nzbpath = listener.link
81
+ add_to_queue, event = await check_running_tasks(listener)
82
+ res = await sabnzbd_client.add_uri(
83
+ url,
84
+ nzbpath,
85
+ listener.name,
86
+ listener.extract if isinstance(listener.extract, str) else "",
87
+ f"{listener.mid}",
88
+ priority=-2 if add_to_queue else 0,
89
+ pp=3 if listener.extract else 1,
90
+ )
91
+ if not res["status"]:
92
+ await listener.on_download_error(
93
+ "Not added! Mostly issue in the link",
94
+ )
95
+ return
96
+
97
+ job_id = res["nzo_ids"][0]
98
+
99
+ await sleep(0.5)
100
+
101
+ downloads = await sabnzbd_client.get_downloads(nzo_ids=job_id)
102
+ if not downloads["queue"]["slots"]:
103
+ await sleep(1)
104
+ history = await sabnzbd_client.get_history(nzo_ids=job_id)
105
+ if err := history["history"]["slots"][0]["fail_message"]:
106
+ await gather(
107
+ listener.on_download_error(err),
108
+ sabnzbd_client.delete_history(job_id, delete_files=True),
109
+ )
110
+ return
111
+ name = history["history"]["slots"][0]["name"]
112
+ else:
113
+ name = downloads["queue"]["slots"][0]["filename"]
114
+
115
+ async with task_dict_lock:
116
+ task_dict[listener.mid] = SabnzbdStatus(
117
+ listener, job_id, queued=add_to_queue
118
+ )
119
+ await on_download_start(job_id)
120
+
121
+ if add_to_queue:
122
+ LOGGER.info(f"Added to Queue/Download: {name} - Job_id: {job_id}")
123
+ else:
124
+ LOGGER.info(f"NzbDownload started: {name} - Job_id: {job_id}")
125
+
126
+ await listener.on_download_start()
127
+
128
+ if Config.BASE_URL and listener.select:
129
+ if url and name.startswith("Trying"):
130
+ metamsg = "Fetching URL, wait then you can select files. Use nzb file to avoid this wait."
131
+ meta = await send_message(listener.message, metamsg)
132
+ while True:
133
+ nzb_info = await sabnzbd_client.get_downloads(nzo_ids=job_id)
134
+ if nzb_info["queue"]["slots"]:
135
+ if not nzb_info["queue"]["slots"][0]["filename"].startswith(
136
+ "Trying"
137
+ ):
138
+ await delete_message(meta)
139
+ break
140
+ else:
141
+ await delete_message(meta)
142
+ return
143
+ await sleep(1)
144
+ if not add_to_queue:
145
+ await sabnzbd_client.pause_job(job_id)
146
+ SBUTTONS = bt_selection_buttons(job_id)
147
+ msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
148
+ await send_message(listener.message, msg, SBUTTONS)
149
+ elif listener.multi <= 1:
150
+ await send_status_message(listener.message)
151
+
152
+ if add_to_queue:
153
+ await event.wait()
154
+ if listener.is_cancelled:
155
+ return
156
+ async with task_dict_lock:
157
+ task_dict[listener.mid].queued = False
158
+
159
+ await sabnzbd_client.resume_job(job_id)
160
+ LOGGER.info(
161
+ f"Start Queued Download from Sabnzbd: {name} - Job_id: {job_id}"
162
+ )
163
+ except Exception as e:
164
+ await listener.on_download_error(f"{e}")
165
+ finally:
166
+ if nzbpath and await aiopath.exists(listener.link):
167
+ await remove(listener.link)
bot/helper/mirror_leech_utils/download_utils/qbit_download.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiofiles.os import remove, path as aiopath
2
+ from aiofiles import open as aiopen
3
+ from asyncio import sleep, TimeoutError
4
+ from aioqbt.api import AddFormBuilder
5
+ from aioqbt.exc import AQError
6
+ from aiohttp.client_exceptions import ClientError
7
+
8
+ from .... import (
9
+ task_dict,
10
+ task_dict_lock,
11
+ LOGGER,
12
+ qb_torrents,
13
+ )
14
+ from ....core.config_manager import Config
15
+ from ....core.torrent_manager import TorrentManager
16
+ from ...ext_utils.bot_utils import bt_selection_buttons
17
+ from ...ext_utils.task_manager import check_running_tasks
18
+ from ...listeners.qbit_listener import on_download_start
19
+ from ...mirror_leech_utils.status_utils.qbit_status import QbittorrentStatus
20
+ from ...telegram_helper.message_utils import (
21
+ send_message,
22
+ delete_message,
23
+ send_status_message,
24
+ )
25
+
26
+ """
27
+ Only v1 torrents
28
+ #from hashlib import sha1
29
+ #from base64 import b16encode, b32decode
30
+ #from bencoding import bencode, bdecode
31
+ #from re import search as re_search
32
+ def _get_hash_magnet(mgt: str):
33
+ hash_ = re_search(r'(?<=xt=urn:btih:)[a-zA-Z0-9]+', mgt).group(0)
34
+ if len(hash_) == 32:
35
+ hash_ = b16encode(b32decode(hash_.upper())).decode()
36
+ return hash_
37
+
38
+ def _get_hash_file(fpath):
39
+ with open(fpath, "rb") as f:
40
+ decodedDict = bdecode(f.read())
41
+ return sha1(bencode(decodedDict[b'info'])).hexdigest()
42
+ """
43
+
44
+
45
+ async def add_qb_torrent(listener, path, ratio, seed_time):
46
+ try:
47
+ form = AddFormBuilder.with_client(TorrentManager.qbittorrent)
48
+ if await aiopath.exists(listener.link):
49
+ async with aiopen(listener.link, "rb") as f:
50
+ data = await f.read()
51
+ form = form.include_file(data)
52
+ else:
53
+ form = form.include_url(listener.link)
54
+ form = form.savepath(path).tags([f"{listener.mid}"])
55
+ add_to_queue, event = await check_running_tasks(listener)
56
+ if add_to_queue:
57
+ form = form.stopped(add_to_queue)
58
+ if ratio:
59
+ form = form.ratio_limit(ratio)
60
+ if seed_time:
61
+ form = form.seeding_time_limit(int(seed_time))
62
+ try:
63
+ await TorrentManager.qbittorrent.torrents.add(form.build())
64
+ except (ClientError, TimeoutError, Exception, AQError) as e:
65
+ LOGGER.error(
66
+ f"{e}. {listener.mid}. Already added torrent or unsupported link/file type!"
67
+ )
68
+ await listener.on_download_error(
69
+ f"{e}. {listener.mid}. Already added torrent or unsupported link/file type!"
70
+ )
71
+ return
72
+ tor_info = await TorrentManager.qbittorrent.torrents.info(tag=f"{listener.mid}")
73
+ if len(tor_info) == 0:
74
+ while True:
75
+ if add_to_queue and event.is_set():
76
+ add_to_queue = False
77
+ tor_info = await TorrentManager.qbittorrent.torrents.info(
78
+ tag=f"{listener.mid}"
79
+ )
80
+ if len(tor_info) > 0:
81
+ break
82
+ await sleep(1)
83
+ tor_info = tor_info[0]
84
+ listener.name = tor_info.name
85
+ ext_hash = tor_info.hash
86
+
87
+ async with task_dict_lock:
88
+ task_dict[listener.mid] = QbittorrentStatus(listener, queued=add_to_queue)
89
+ await on_download_start(f"{listener.mid}")
90
+
91
+ if add_to_queue:
92
+ LOGGER.info(f"Added to Queue/Download: {tor_info.name} - Hash: {ext_hash}")
93
+ else:
94
+ LOGGER.info(f"QbitDownload started: {tor_info.name} - Hash: {ext_hash}")
95
+
96
+ await listener.on_download_start()
97
+
98
+ if Config.BASE_URL and listener.select:
99
+ if listener.link.startswith("magnet:"):
100
+ metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait."
101
+ meta = await send_message(listener.message, metamsg)
102
+ while True:
103
+ tor_info = await TorrentManager.qbittorrent.torrents.info(
104
+ tag=f"{listener.mid}"
105
+ )
106
+ if len(tor_info) == 0:
107
+ await delete_message(meta)
108
+ return
109
+ try:
110
+ tor_info = tor_info[0]
111
+ if tor_info.state not in [
112
+ "metaDL",
113
+ "checkingResumeData",
114
+ "stoppedDL",
115
+ ]:
116
+ await delete_message(meta)
117
+ break
118
+ except:
119
+ await delete_message(meta)
120
+ return
121
+
122
+ ext_hash = tor_info.hash
123
+ if not add_to_queue:
124
+ await TorrentManager.qbittorrent.torrents.stop([ext_hash])
125
+ SBUTTONS = bt_selection_buttons(ext_hash)
126
+ msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
127
+ await send_message(listener.message, msg, SBUTTONS)
128
+ elif listener.multi <= 1 and not listener.is_rss:
129
+ await send_status_message(listener.message)
130
+
131
+ if event is not None:
132
+ if not event.is_set():
133
+ await event.wait()
134
+ if listener.is_cancelled:
135
+ return
136
+ async with task_dict_lock:
137
+ task_dict[listener.mid].queued = False
138
+ LOGGER.info(
139
+ f"Start Queued Download from Qbittorrent: {tor_info.name} - Hash: {ext_hash}"
140
+ )
141
+ await on_download_start(f"{listener.mid}")
142
+ await TorrentManager.qbittorrent.torrents.start([ext_hash])
143
+ except (ClientError, TimeoutError, Exception, AQError) as e:
144
+ if f"{listener.mid}" in qb_torrents:
145
+ del qb_torrents[f"{listener.mid}"]
146
+ await listener.on_download_error(f"{e}")
147
+ finally:
148
+ if await aiopath.exists(listener.link):
149
+ await remove(listener.link)
bot/helper/mirror_leech_utils/download_utils/rclone_download.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import gather
2
+ from json import loads
3
+ from secrets import token_urlsafe
4
+ from aiofiles.os import remove
5
+
6
+ from .... import task_dict, task_dict_lock, LOGGER
7
+ from ...ext_utils.bot_utils import cmd_exec
8
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
9
+ from ...mirror_leech_utils.rclone_utils.transfer import RcloneTransferHelper
10
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
11
+ from ...mirror_leech_utils.status_utils.rclone_status import RcloneStatus
12
+ from ...telegram_helper.message_utils import send_status_message
13
+
14
+
15
+ async def add_rclone_download(listener, path):
16
+ if listener.link.startswith("mrcc:"):
17
+ listener.link = listener.link.split("mrcc:", 1)[1]
18
+ config_path = f"rclone/{listener.user_id}.conf"
19
+ else:
20
+ config_path = "rclone.conf"
21
+
22
+ remote, listener.link = listener.link.split(":", 1)
23
+ listener.link = listener.link.strip("/")
24
+ rclone_select = False
25
+ if listener.link.startswith("rclone_select"):
26
+ rclone_select = True
27
+ rpath = ""
28
+ else:
29
+ rpath = listener.link
30
+
31
+ cmd1 = [
32
+ "rclone",
33
+ "lsjson",
34
+ "--fast-list",
35
+ "--stat",
36
+ "--no-mimetype",
37
+ "--no-modtime",
38
+ "--config",
39
+ config_path,
40
+ f"{remote}:{rpath}",
41
+ ]
42
+ cmd2 = [
43
+ "rclone",
44
+ "size",
45
+ "--fast-list",
46
+ "--json",
47
+ "--config",
48
+ config_path,
49
+ f"{remote}:{rpath}",
50
+ ]
51
+ if rclone_select:
52
+ cmd2.extend(("--files-from", listener.link))
53
+ res = await cmd_exec(cmd2)
54
+ if res[2] != 0:
55
+ if res[2] != -9:
56
+ msg = f"Error: While getting rclone stat/size. Path: {remote}:{listener.link}. Stderr: {res[1][:4000]}"
57
+ await listener.on_download_error(msg)
58
+ return
59
+ try:
60
+ rsize = loads(res[0])
61
+ except Exception as err:
62
+ await listener.on_download_error(f"RcloneDownload JsonLoad: {err}")
63
+ return
64
+ if not listener.name:
65
+ listener.name = listener.link
66
+ path += listener.name
67
+ else:
68
+ res1, res2 = await gather(cmd_exec(cmd1), cmd_exec(cmd2))
69
+ if res1[2] != 0 or res2[2] != 0:
70
+ if res1[2] != -9:
71
+ err = res1[1] or res2[1]
72
+ msg = f"Error: While getting rclone stat/size. Path: {remote}:{listener.link}. Stderr: {err[:4000]}"
73
+ await listener.on_download_error(msg)
74
+ return
75
+ try:
76
+ rstat = loads(res1[0])
77
+ rsize = loads(res2[0])
78
+ except Exception as err:
79
+ await listener.on_download_error(f"RcloneDownload JsonLoad: {err}")
80
+ return
81
+ if rstat["IsDir"]:
82
+ if not listener.name:
83
+ listener.name = (
84
+ listener.link.rsplit("/", 1)[-1] if listener.link else remote
85
+ )
86
+ path += listener.name
87
+ else:
88
+ listener.name = listener.link.rsplit("/", 1)[-1]
89
+ listener.size = rsize["bytes"]
90
+ gid = token_urlsafe(12)
91
+
92
+ if not rclone_select:
93
+ msg, button = await stop_duplicate_check(listener)
94
+ if msg:
95
+ await listener.on_download_error(msg, button)
96
+ return
97
+
98
+ add_to_queue, event = await check_running_tasks(listener)
99
+ if add_to_queue:
100
+ LOGGER.info(f"Added to Queue/Download: {listener.name}")
101
+ async with task_dict_lock:
102
+ task_dict[listener.mid] = QueueStatus(listener, gid, "dl")
103
+ await listener.on_download_start()
104
+ if listener.multi <= 1:
105
+ await send_status_message(listener.message)
106
+ await event.wait()
107
+ if listener.is_cancelled:
108
+ return
109
+
110
+ RCTransfer = RcloneTransferHelper(listener)
111
+ async with task_dict_lock:
112
+ task_dict[listener.mid] = RcloneStatus(listener, RCTransfer, gid, "dl")
113
+
114
+ if add_to_queue:
115
+ LOGGER.info(f"Start Queued Download with rclone: {listener.link}")
116
+ else:
117
+ await listener.on_download_start()
118
+ if listener.multi <= 1:
119
+ await send_status_message(listener.message)
120
+ LOGGER.info(f"Download with rclone: {listener.link}")
121
+
122
+ await RCTransfer.download(remote, config_path, path)
123
+ if rclone_select:
124
+ await remove(listener.link)
bot/helper/mirror_leech_utils/download_utils/telegram_download.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import Lock, sleep
2
+ from time import time
3
+ from pyrogram.errors import FloodWait, FloodPremiumWait
4
+
5
+ from .... import (
6
+ LOGGER,
7
+ task_dict,
8
+ task_dict_lock,
9
+ )
10
+ from ....core.telegram_manager import TgClient
11
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
12
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
13
+ from ...mirror_leech_utils.status_utils.telegram_status import TelegramStatus
14
+ from ...telegram_helper.message_utils import send_status_message
15
+
16
+ global_lock = Lock()
17
+ GLOBAL_GID = set()
18
+
19
+
20
+ class TelegramDownloadHelper:
21
+ def __init__(self, listener):
22
+ self._processed_bytes = 0
23
+ self._start_time = 1
24
+ self._listener = listener
25
+ self._id = ""
26
+ self.session = ""
27
+
28
+ @property
29
+ def speed(self):
30
+ return self._processed_bytes / (time() - self._start_time)
31
+
32
+ @property
33
+ def processed_bytes(self):
34
+ return self._processed_bytes
35
+
36
+ async def _on_download_start(self, file_id, from_queue):
37
+ async with global_lock:
38
+ GLOBAL_GID.add(file_id)
39
+ self._id = file_id
40
+ async with task_dict_lock:
41
+ task_dict[self._listener.mid] = TelegramStatus(
42
+ self._listener, self, file_id[:12], "dl"
43
+ )
44
+ if not from_queue:
45
+ await self._listener.on_download_start()
46
+ if self._listener.multi <= 1:
47
+ await send_status_message(self._listener.message)
48
+ LOGGER.info(f"Download from Telegram: {self._listener.name}")
49
+ else:
50
+ LOGGER.info(f"Start Queued Download from Telegram: {self._listener.name}")
51
+
52
+ async def _on_download_progress(self, current, _):
53
+ if self._listener.is_cancelled:
54
+ if self.session == "user":
55
+ TgClient.user.stop_transmission()
56
+ else:
57
+ TgClient.bot.stop_transmission()
58
+ self._processed_bytes = current
59
+
60
+ async def _on_download_error(self, error):
61
+ async with global_lock:
62
+ if self._id in GLOBAL_GID:
63
+ GLOBAL_GID.remove(self._id)
64
+ await self._listener.on_download_error(error)
65
+
66
+ async def _on_download_complete(self):
67
+ async with global_lock:
68
+ if self._id in GLOBAL_GID:
69
+ GLOBAL_GID.remove(self._id)
70
+ await self._listener.on_download_complete()
71
+
72
+ async def _download(self, message, path):
73
+ try:
74
+ download = await message.download(
75
+ file_name=path, progress=self._on_download_progress
76
+ )
77
+ if self._listener.is_cancelled:
78
+ return
79
+ except (FloodWait, FloodPremiumWait) as f:
80
+ LOGGER.warning(str(f))
81
+ await sleep(f.value)
82
+ await self._download(message, path)
83
+ return
84
+ except Exception as e:
85
+ LOGGER.error(str(e))
86
+ await self._on_download_error(str(e))
87
+ return
88
+ if download is not None:
89
+ await self._on_download_complete()
90
+ elif not self._listener.is_cancelled:
91
+ await self._on_download_error("Internal error occurred")
92
+
93
+ async def add_download(self, message, path, session):
94
+ self.session = session
95
+ if not self.session:
96
+ if self._listener.user_transmission and self._listener.is_super_chat:
97
+ self.session = "user"
98
+ message = await TgClient.user.get_messages(
99
+ chat_id=message.chat.id, message_ids=message.id
100
+ )
101
+ else:
102
+ self.session = "bot"
103
+ media = (
104
+ message.document
105
+ or message.photo
106
+ or message.video
107
+ or message.audio
108
+ or message.voice
109
+ or message.video_note
110
+ or message.sticker
111
+ or message.animation
112
+ or None
113
+ )
114
+
115
+ if media is not None:
116
+ async with global_lock:
117
+ download = media.file_unique_id not in GLOBAL_GID
118
+
119
+ if download:
120
+ if not self._listener.name:
121
+ if hasattr(media, "file_name") and media.file_name:
122
+ if "/" in media.file_name:
123
+ self._listener.name = media.file_name.rsplit("/", 1)[-1]
124
+ path = path + self._listener.name
125
+ else:
126
+ self._listener.name = media.file_name
127
+ else:
128
+ self._listener.name = "None"
129
+ else:
130
+ path = path + self._listener.name
131
+ self._listener.size = media.file_size
132
+ gid = media.file_unique_id
133
+
134
+ msg, button = await stop_duplicate_check(self._listener)
135
+ if msg:
136
+ await self._listener.on_download_error(msg, button)
137
+ return
138
+
139
+ add_to_queue, event = await check_running_tasks(self._listener)
140
+ if add_to_queue:
141
+ LOGGER.info(f"Added to Queue/Download: {self._listener.name}")
142
+ async with task_dict_lock:
143
+ task_dict[self._listener.mid] = QueueStatus(
144
+ self._listener, gid, "dl"
145
+ )
146
+ await self._listener.on_download_start()
147
+ if self._listener.multi <= 1:
148
+ await send_status_message(self._listener.message)
149
+ await event.wait()
150
+ if self.session == "bot":
151
+ message = await self._listener.client.get_messages(
152
+ chat_id=message.chat.id, message_ids=message.id
153
+ )
154
+ else:
155
+ message = await TgClient.user.get_messages(
156
+ chat_id=message.chat.id, message_ids=message.id
157
+ )
158
+ if self._listener.is_cancelled:
159
+ async with global_lock:
160
+ if self._id in GLOBAL_GID:
161
+ GLOBAL_GID.remove(self._id)
162
+ return
163
+ self._start_time = time()
164
+ await self._on_download_start(gid, add_to_queue)
165
+ await self._download(message, path)
166
+ else:
167
+ await self._on_download_error("File already being downloaded!")
168
+ else:
169
+ await self._on_download_error(
170
+ "No document in the replied message! Use SuperGroup incase you are trying to download with User session!"
171
+ )
172
+
173
+ async def cancel_task(self):
174
+ self._listener.is_cancelled = True
175
+ LOGGER.info(
176
+ f"Cancelling download on user request: name: {self._listener.name} id: {self._id}"
177
+ )
178
+ await self._on_download_error("Stopped by user!")
bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import getLogger
2
+ from os import path as ospath, listdir
3
+ from re import search as re_search
4
+ from secrets import token_urlsafe
5
+ from yt_dlp import YoutubeDL, DownloadError
6
+
7
+
8
+ from .... import task_dict_lock, task_dict
9
+ from ...ext_utils.bot_utils import sync_to_async, async_to_sync
10
+ from ...ext_utils.task_manager import check_running_tasks, stop_duplicate_check
11
+ from ...mirror_leech_utils.status_utils.queue_status import QueueStatus
12
+ from ...telegram_helper.message_utils import send_status_message
13
+ from ..status_utils.yt_dlp_status import YtDlpStatus
14
+
15
+ LOGGER = getLogger(__name__)
16
+
17
+
18
+ class MyLogger:
19
+ def __init__(self, obj, listener):
20
+ self._obj = obj
21
+ self._listener = listener
22
+
23
+ def debug(self, msg):
24
+ # Hack to fix changing extension
25
+ if not self._obj.is_playlist:
26
+ if match := re_search(
27
+ r".Merger..Merging formats into..(.*?).$", msg
28
+ ) or re_search(r".ExtractAudio..Destination..(.*?)$", msg):
29
+ LOGGER.info(msg)
30
+ newname = match.group(1)
31
+ newname = newname.rsplit("/", 1)[-1]
32
+ self._listener.name = newname
33
+
34
+ @staticmethod
35
+ def warning(msg):
36
+ LOGGER.warning(msg)
37
+
38
+ @staticmethod
39
+ def error(msg):
40
+ if msg != "ERROR: Cancelling...":
41
+ LOGGER.error(msg)
42
+
43
+
44
+ class YoutubeDLHelper:
45
+ def __init__(self, listener):
46
+ self._last_downloaded = 0
47
+ self._progress = 0
48
+ self._downloaded_bytes = 0
49
+ self._download_speed = 0
50
+ self._eta = "-"
51
+ self._listener = listener
52
+ self._gid = ""
53
+ self._ext = ""
54
+ self.is_playlist = False
55
+ self.keep_thumb = False
56
+ self.opts = {
57
+ "progress_hooks": [self._on_download_progress],
58
+ "logger": MyLogger(self, self._listener),
59
+ "usenetrc": True,
60
+ "cookiefile": "cookies.txt",
61
+ "allow_multiple_video_streams": True,
62
+ "allow_multiple_audio_streams": True,
63
+ "noprogress": True,
64
+ "allow_playlist_files": True,
65
+ "overwrites": True,
66
+ "writethumbnail": True,
67
+ "trim_file_name": 220,
68
+ "fragment_retries": 10,
69
+ "retries": 10,
70
+ "retry_sleep_functions": {
71
+ "http": lambda n: 3,
72
+ "fragment": lambda n: 3,
73
+ "file_access": lambda n: 3,
74
+ "extractor": lambda n: 3,
75
+ },
76
+ }
77
+
78
+ @property
79
+ def download_speed(self):
80
+ return self._download_speed
81
+
82
+ @property
83
+ def downloaded_bytes(self):
84
+ return self._downloaded_bytes
85
+
86
+ @property
87
+ def size(self):
88
+ return self._listener.size
89
+
90
+ @property
91
+ def progress(self):
92
+ return self._progress
93
+
94
+ @property
95
+ def eta(self):
96
+ return self._eta
97
+
98
+ def _on_download_progress(self, d):
99
+ if self._listener.is_cancelled:
100
+ raise ValueError("Cancelling...")
101
+ if d["status"] == "finished":
102
+ if self.is_playlist:
103
+ self._last_downloaded = 0
104
+ elif d["status"] == "downloading":
105
+ self._download_speed = d["speed"] or 0
106
+ if self.is_playlist:
107
+ downloadedBytes = d["downloaded_bytes"] or 0
108
+ chunk_size = downloadedBytes - self._last_downloaded
109
+ self._last_downloaded = downloadedBytes
110
+ self._downloaded_bytes += chunk_size
111
+ else:
112
+ if d.get("total_bytes"):
113
+ self._listener.size = d["total_bytes"] or 0
114
+ elif d.get("total_bytes_estimate"):
115
+ self._listener.size = d["total_bytes_estimate"] or 0
116
+ self._downloaded_bytes = d["downloaded_bytes"] or 0
117
+ self._eta = d.get("eta", "-") or "-"
118
+ try:
119
+ self._progress = (self._downloaded_bytes / self._listener.size) * 100
120
+ except:
121
+ pass
122
+
123
+ async def _on_download_start(self, from_queue=False):
124
+ async with task_dict_lock:
125
+ task_dict[self._listener.mid] = YtDlpStatus(self._listener, self, self._gid)
126
+ if not from_queue:
127
+ await self._listener.on_download_start()
128
+ if self._listener.multi <= 1 and not self._listener.is_rss:
129
+ await send_status_message(self._listener.message)
130
+
131
+ def _on_download_error(self, error):
132
+ self._listener.is_cancelled = True
133
+ async_to_sync(self._listener.on_download_error, error)
134
+
135
+ def _extract_meta_data(self):
136
+ if self._listener.link.startswith(("rtmp", "mms", "rstp", "rtmps")):
137
+ self.opts["external_downloader"] = "ffmpeg"
138
+ with YoutubeDL(self.opts) as ydl:
139
+ try:
140
+ result = ydl.extract_info(self._listener.link, download=False)
141
+ if result is None:
142
+ raise ValueError("Info result is None")
143
+ except Exception as e:
144
+ return self._on_download_error(str(e))
145
+ if "entries" in result:
146
+ for entry in result["entries"]:
147
+ if not entry:
148
+ continue
149
+ elif "filesize_approx" in entry:
150
+ self._listener.size += entry.get("filesize_approx", 0) or 0
151
+ elif "filesize" in entry:
152
+ self._listener.size += entry.get("filesize", 0) or 0
153
+ if not self._listener.name:
154
+ outtmpl_ = "%(series,playlist_title,channel)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d.%(ext)s"
155
+ self._listener.name, ext = ospath.splitext(
156
+ ydl.prepare_filename(entry, outtmpl=outtmpl_)
157
+ )
158
+ if not self._ext:
159
+ self._ext = ext
160
+ else:
161
+ outtmpl_ = "%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s"
162
+ realName = ydl.prepare_filename(result, outtmpl=outtmpl_)
163
+ ext = ospath.splitext(realName)[-1]
164
+ self._listener.name = (
165
+ f"{self._listener.name}{ext}" if self._listener.name else realName
166
+ )
167
+ if not self._ext:
168
+ self._ext = ext
169
+
170
+ def _download(self, path):
171
+ try:
172
+ with YoutubeDL(self.opts) as ydl:
173
+ try:
174
+ ydl.download([self._listener.link])
175
+ except DownloadError as e:
176
+ if not self._listener.is_cancelled:
177
+ self._on_download_error(str(e))
178
+ return
179
+ if self.is_playlist and (
180
+ not ospath.exists(path) or len(listdir(path)) == 0
181
+ ):
182
+ self._on_download_error(
183
+ "No video available to download from this playlist. Check logs for more details"
184
+ )
185
+ return
186
+ if self._listener.is_cancelled:
187
+ return
188
+ async_to_sync(self._listener.on_download_complete)
189
+ except:
190
+ pass
191
+ return
192
+
193
+ async def add_download(self, path, qual, playlist, options):
194
+ if playlist:
195
+ self.opts["ignoreerrors"] = True
196
+ self.is_playlist = True
197
+
198
+ self._gid = token_urlsafe(10)
199
+
200
+ await self._on_download_start()
201
+
202
+ self.opts["postprocessors"] = [
203
+ {
204
+ "add_chapters": True,
205
+ "add_infojson": "if_exists",
206
+ "add_metadata": True,
207
+ "key": "FFmpegMetadata",
208
+ }
209
+ ]
210
+
211
+ if qual.startswith("ba/b-"):
212
+ audio_info = qual.split("-")
213
+ qual = audio_info[0]
214
+ audio_format = audio_info[1]
215
+ rate = audio_info[2]
216
+ self.opts["postprocessors"].append(
217
+ {
218
+ "key": "FFmpegExtractAudio",
219
+ "preferredcodec": audio_format,
220
+ "preferredquality": rate,
221
+ }
222
+ )
223
+ if audio_format == "vorbis":
224
+ self._ext = ".ogg"
225
+ elif audio_format == "alac":
226
+ self._ext = ".m4a"
227
+ else:
228
+ self._ext = f".{audio_format}"
229
+
230
+ if not self._listener.is_leech or self._listener.thumbnail_layout:
231
+ self.opts["writethumbnail"] = False
232
+
233
+ if options:
234
+ self._set_options(options)
235
+
236
+ self.opts["format"] = qual
237
+
238
+ await sync_to_async(self._extract_meta_data)
239
+ if self._listener.is_cancelled:
240
+ return
241
+
242
+ base_name, ext = ospath.splitext(self._listener.name)
243
+ trim_name = self._listener.name if self.is_playlist else base_name
244
+ if len(trim_name.encode()) > 200:
245
+ self._listener.name = (
246
+ self._listener.name[:200]
247
+ if self.is_playlist
248
+ else f"{base_name[:200]}{ext}"
249
+ )
250
+ base_name = ospath.splitext(self._listener.name)[0]
251
+
252
+ start_path = path if self.keep_thumb else f"{path}/yt-dlp-thumb"
253
+ if self.is_playlist:
254
+ self.opts["outtmpl"] = {
255
+ "default": f"{path}/{self._listener.name}/%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s",
256
+ "thumbnail": f"{start_path}/%(title,fulltitle,alt_title)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d%(episode_number&E|)s%(episode_number|)02d%(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s",
257
+ }
258
+ elif "download_ranges" in options:
259
+ self.opts["outtmpl"] = {
260
+ "default": f"{path}/{base_name}/%(section_number|)s%(section_number&.|)s%(section_title|)s%(section_title&-|)s%(title,fulltitle,alt_title)s %(section_start)s to %(section_end)s.%(ext)s",
261
+ "thumbnail": f"{start_path}/%(section_number|)s%(section_number&.|)s%(section_title|)s%(section_title&-|)s%(title,fulltitle,alt_title)s %(section_start)s to %(section_end)s.%(ext)s",
262
+ }
263
+ elif any(
264
+ key in options
265
+ for key in [
266
+ "writedescription",
267
+ "writeinfojson",
268
+ "writeannotations",
269
+ "writedesktoplink",
270
+ "writewebloclink",
271
+ "writelink",
272
+ "writeurllink",
273
+ "writesubtitles",
274
+ "write_all_thumbnails",
275
+ ]
276
+ ):
277
+ self.opts["outtmpl"] = {
278
+ "default": f"{path}/{base_name}/{self._listener.name}",
279
+ "thumbnail": f"{start_path}/{base_name}.%(ext)s",
280
+ }
281
+ else:
282
+ self.opts["outtmpl"] = {
283
+ "default": f"{path}/{self._listener.name}",
284
+ "thumbnail": f"{start_path}/{base_name}.%(ext)s",
285
+ }
286
+
287
+ if qual.startswith("ba/b"):
288
+ self._listener.name = f"{base_name}{self._ext}"
289
+
290
+ if self.opts["writethumbnail"]:
291
+ self.opts["postprocessors"].append(
292
+ {
293
+ "format": "jpg",
294
+ "key": "FFmpegThumbnailsConvertor",
295
+ "when": "before_dl",
296
+ }
297
+ )
298
+ if self._ext in [
299
+ ".mp3",
300
+ ".mkv",
301
+ ".mka",
302
+ ".ogg",
303
+ ".opus",
304
+ ".flac",
305
+ ".m4a",
306
+ ".mp4",
307
+ ".mov",
308
+ ".m4v",
309
+ ]:
310
+ self.opts["postprocessors"].append(
311
+ {
312
+ "already_have_thumbnail": self.opts["writethumbnail"],
313
+ "key": "EmbedThumbnail",
314
+ }
315
+ )
316
+
317
+ msg, button = await stop_duplicate_check(self._listener)
318
+ if msg:
319
+ await self._listener.on_download_error(msg, button)
320
+ return
321
+
322
+ add_to_queue, event = await check_running_tasks(self._listener)
323
+ if add_to_queue:
324
+ LOGGER.info(f"Added to Queue/Download: {self._listener.name}")
325
+ async with task_dict_lock:
326
+ task_dict[self._listener.mid] = QueueStatus(
327
+ self._listener, self._gid, "dl"
328
+ )
329
+ await event.wait()
330
+ if self._listener.is_cancelled:
331
+ return
332
+ LOGGER.info(f"Start Queued Download from YT_DLP: {self._listener.name}")
333
+ await self._on_download_start(True)
334
+
335
+ if not add_to_queue:
336
+ LOGGER.info(f"Download with YT_DLP: {self._listener.name}")
337
+
338
+ await sync_to_async(self._download, path)
339
+
340
+ async def cancel_task(self):
341
+ self._listener.is_cancelled = True
342
+ LOGGER.info(f"Cancelling Download: {self._listener.name}")
343
+ await self._listener.on_download_error("Stopped by User!")
344
+
345
+ def _set_options(self, options):
346
+ for key, value in options.items():
347
+ if key == "postprocessors":
348
+ if isinstance(value, list):
349
+ self.opts[key].extend(tuple(value))
350
+ elif isinstance(value, dict):
351
+ self.opts[key].append(value)
352
+ elif key == "download_ranges":
353
+ if isinstance(value, list):
354
+ self.opts[key] = lambda info, ytdl: value
355
+ else:
356
+ if key == "writethumbnail" and value is True:
357
+ self.keep_thumb = True
358
+ self.opts[key] = value
bot/helper/mirror_leech_utils/gdrive_utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
bot/helper/mirror_leech_utils/gdrive_utils/clone.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from googleapiclient.errors import HttpError
2
+ from logging import getLogger
3
+ from os import path as ospath
4
+ from tenacity import (
5
+ retry,
6
+ wait_exponential,
7
+ stop_after_attempt,
8
+ retry_if_exception_type,
9
+ RetryError,
10
+ )
11
+ from time import time
12
+
13
+ from ...ext_utils.bot_utils import async_to_sync
14
+ from ...mirror_leech_utils.gdrive_utils.helper import GoogleDriveHelper
15
+
16
+ LOGGER = getLogger(__name__)
17
+
18
+
19
+ class GoogleDriveClone(GoogleDriveHelper):
20
+ def __init__(self, listener):
21
+ self.listener = listener
22
+ self._start_time = time()
23
+ super().__init__()
24
+ self.is_cloning = True
25
+ self.user_setting()
26
+
27
+ def user_setting(self):
28
+ if self.listener.up_dest.startswith("mtp:") or self.listener.link.startswith(
29
+ "mtp:"
30
+ ):
31
+ self.token_path = f"tokens/{self.listener.user_id}.pickle"
32
+ self.listener.up_dest = self.listener.up_dest.replace("mtp:", "", 1)
33
+ self.use_sa = False
34
+ elif self.listener.up_dest.startswith("tp:"):
35
+ self.listener.up_dest = self.listener.up_dest.replace("tp:", "", 1)
36
+ self.use_sa = False
37
+ elif self.listener.up_dest.startswith("sa:") or self.listener.link.startswith(
38
+ "sa:"
39
+ ):
40
+ self.listener.up_dest = self.listener.up_dest.replace("sa:", "", 1)
41
+ self.use_sa = True
42
+
43
+ def clone(self):
44
+ try:
45
+ file_id = self.get_id_from_url(self.listener.link)
46
+ except (KeyError, IndexError):
47
+ return (
48
+ "Google Drive ID could not be found in the provided link",
49
+ None,
50
+ None,
51
+ None,
52
+ None,
53
+ )
54
+ self.service = self.authorize()
55
+ msg = ""
56
+ LOGGER.info(f"File ID: {file_id}")
57
+ try:
58
+ meta = self.get_file_metadata(file_id)
59
+ mime_type = meta.get("mimeType")
60
+ if mime_type == self.G_DRIVE_DIR_MIME_TYPE:
61
+ dir_id = self.create_directory(meta.get("name"), self.listener.up_dest)
62
+ self._clone_folder(meta.get("name"), meta.get("id"), dir_id)
63
+ durl = self.G_DRIVE_DIR_BASE_DOWNLOAD_URL.format(dir_id)
64
+ if self.listener.is_cancelled:
65
+ LOGGER.info("Deleting cloned data from Drive...")
66
+ self.service.files().delete(
67
+ fileId=dir_id, supportsAllDrives=True
68
+ ).execute()
69
+ return None, None, None, None, None
70
+ mime_type = "Folder"
71
+ self.listener.size = self.proc_bytes
72
+ else:
73
+ file = self._copy_file(meta.get("id"), self.listener.up_dest)
74
+ msg += f'<b>Name: </b><code>{file.get("name")}</code>'
75
+ durl = self.G_DRIVE_BASE_DOWNLOAD_URL.format(file.get("id"))
76
+ if mime_type is None:
77
+ mime_type = "File"
78
+ self.listener.size = int(meta.get("size", 0))
79
+ return (
80
+ durl,
81
+ mime_type,
82
+ self.total_files,
83
+ self.total_folders,
84
+ self.get_id_from_url(durl),
85
+ )
86
+ except Exception as err:
87
+ if isinstance(err, RetryError):
88
+ LOGGER.info(f"Total Attempts: {err.last_attempt.attempt_number}")
89
+ err = err.last_attempt.exception()
90
+ err = str(err).replace(">", "").replace("<", "")
91
+ if "User rate limit exceeded" in err:
92
+ msg = "User rate limit exceeded."
93
+ elif "File not found" in err:
94
+ if not self.alt_auth and self.use_sa:
95
+ self.alt_auth = True
96
+ self.use_sa = False
97
+ LOGGER.error("File not found. Trying with token.pickle...")
98
+ return self.clone()
99
+ msg = "File not found."
100
+ else:
101
+ msg = f"Error.\n{err}"
102
+ async_to_sync(self.listener.on_upload_error, msg)
103
+ return None, None, None, None, None
104
+
105
+ def _clone_folder(self, folder_name, folder_id, dest_id):
106
+ LOGGER.info(f"Syncing: {folder_name}")
107
+ files = self.get_files_by_folder_id(folder_id)
108
+ if len(files) == 0:
109
+ return dest_id
110
+ for file in files:
111
+ if file.get("mimeType") == self.G_DRIVE_DIR_MIME_TYPE:
112
+ self.total_folders += 1
113
+ file_path = ospath.join(folder_name, file.get("name"))
114
+ current_dir_id = self.create_directory(file.get("name"), dest_id)
115
+ self._clone_folder(file_path, file.get("id"), current_dir_id)
116
+ elif self.listener.included_extensions and not file.get(
117
+ "name"
118
+ ).strip().lower().endswith(tuple(self.listener.included_extensions)):
119
+ continue
120
+ elif not self.listener.included_extensions and file.get(
121
+ "name"
122
+ ).strip().lower().endswith(tuple(self.listener.excluded_extensions)):
123
+ continue
124
+ else:
125
+ self.total_files += 1
126
+ self._copy_file(file.get("id"), dest_id)
127
+ self.proc_bytes += int(file.get("size", 0))
128
+ self.total_time = int(time() - self._start_time)
129
+ if self.listener.is_cancelled:
130
+ break
131
+
132
+ @retry(
133
+ wait=wait_exponential(multiplier=2, min=3, max=6),
134
+ stop=stop_after_attempt(3),
135
+ retry=retry_if_exception_type(Exception),
136
+ )
137
+ def _copy_file(self, file_id, dest_id):
138
+ body = {"parents": [dest_id]}
139
+ try:
140
+ return (
141
+ self.service.files()
142
+ .copy(fileId=file_id, body=body, supportsAllDrives=True)
143
+ .execute()
144
+ )
145
+ except HttpError as err:
146
+ if err.resp.get("content-type", "").startswith("application/json"):
147
+ reason = eval(err.content).get("error").get("errors")[0].get("reason")
148
+ if reason not in [
149
+ "userRateLimitExceeded",
150
+ "dailyLimitExceeded",
151
+ "cannotCopyFile",
152
+ ]:
153
+ raise err
154
+ if reason == "cannotCopyFile":
155
+ LOGGER.error(err)
156
+ elif self.use_sa:
157
+ if self.sa_count >= self.sa_number:
158
+ LOGGER.info(
159
+ f"Reached maximum number of service accounts switching, which is {self.sa_count}"
160
+ )
161
+ raise err
162
+ else:
163
+ if self.listener.is_cancelled:
164
+ return
165
+ self.switch_service_account()
166
+ return self._copy_file(file_id, dest_id)
167
+ else:
168
+ LOGGER.error(f"Got: {reason}")
169
+ raise err