├── .gitignore
├── COPYING
├── Dockerfile
├── README.md
├── app.json
├── captain-definition
├── heroku.yml
├── publicleechgroup
├── __init__.py
├── __main__.py
├── amocmadin.py
├── bot.py
├── dinmamoc.py
├── get_cfg.py
├── helper_funcs
│ ├── admin_check.py
│ ├── copy_similar_file.py
│ ├── create_compressed_archive.py
│ ├── create_r_o_m.py
│ ├── custom_filters.py
│ ├── display_progress.py
│ ├── download_aria_p_n.py
│ ├── download_from_link.py
│ ├── extract_link_from_message.py
│ ├── fix_tcerrocni_images.py
│ ├── help_Nekmo_ffmpeg.py
│ ├── icntaosrtsba.py
│ ├── magnetic_link_regex.py
│ ├── r_clone.py
│ ├── real_debrid_extractor.py
│ ├── run_shell_command.py
│ ├── split_large_files.py
│ ├── upload_to_tg.py
│ ├── youtube_dl_button.py
│ └── youtube_dl_extractor.py
├── plugins
│ ├── call_back_button_handler.py
│ ├── custom_thumbnail.py
│ ├── incoming_message_fn.py
│ ├── new_join_fn.py
│ └── status_message_fn.py
└── sample_config.py
├── requirements.txt
└── sample_config.env
/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | config.env
3 | __pycache__
4 | *.session
5 | test*.*
6 | splfil/
7 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # creates a layer from the base Docker image.
19 | FROM python:3.9.5-slim-buster
20 |
21 | WORKDIR /app
22 |
23 | # https://shouldiblamecaching.com/
24 | ENV PIP_NO_CACHE_DIR 1
25 |
26 | # http://bugs.python.org/issue19846
27 | # https://github.com/SpEcHiDe/PublicLeech/pull/97
28 | ENV LANG C.UTF-8
29 |
30 | # we don't have an interactive xTerm
31 | ENV DEBIAN_FRONTEND noninteractive
32 |
33 | # sets the TimeZone, to be used inside the container
34 | ENV TZ Asia/Kolkata
35 |
36 | # fix "ephimeral" / "AWS" file-systems
37 | RUN sed -i.bak 's/us-west-2\.ec2\.//' /etc/apt/sources.list
38 |
39 | # to resynchronize the package index files from their sources.
40 | RUN apt -qq update
41 |
42 | # base required pre-requisites before proceeding ...
43 | RUN apt -qq install -y --no-install-recommends \
44 | curl \
45 | git \
46 | gnupg2 \
47 | unzip \
48 | wget \
49 | # install gcc [ PEP 517 ]
50 | build-essential gcc \
51 | software-properties-common && \
52 | rm -rf /var/lib/apt/lists/* && \
53 | apt-add-repository non-free
54 |
55 | # add required files to sources.list
56 | RUN wget -q -O - https://mkvtoolnix.download/gpg-pub-moritzbunkus.txt | apt-key add - && \
57 | wget -qO - https://ftp-master.debian.org/keys/archive-key-10.asc | apt-key add -
58 | RUN sh -c 'echo "deb https://mkvtoolnix.download/debian/ buster main" >> /etc/apt/sources.list.d/bunkus.org.list' && \
59 | sh -c 'echo deb http://deb.debian.org/debian buster main contrib non-free | tee -a /etc/apt/sources.list'
60 |
61 | # to resynchronize the package index files from their sources.
62 | RUN apt -qq update
63 |
64 | # install required packages
65 | RUN apt -qq install -y --no-install-recommends \
66 | # this package is required to fetch "contents" via "TLS"
67 | apt-transport-https \
68 | # install coreutils
69 | coreutils aria2 jq pv \
70 | # install encoding tools
71 | ffmpeg \
72 | # install extraction tools
73 | mkvtoolnix \
74 | p7zip rar unrar zip \
75 | # miscellaneous helpers
76 | megatools mediainfo rclone && \
77 | # clean up previously installed SPC
78 | apt purge -y software-properties-common && \
79 | # clean up the container "layer", after we are done
80 | rm -rf /var/lib/apt/lists /var/cache/apt/archives /tmp
81 |
82 | # each instruction creates one layer
83 | # Only the instructions RUN, COPY, ADD create layers.
84 | # copies 'requirements', to inside the container
85 | # ..., there are multiple '' dependancies,
86 | # requiring the use of the entire repo, hence
87 | # adds files from your Docker client’s current directory.
88 | COPY . .
89 |
90 | # install requirements, inside the container
91 | RUN pip3 install --upgrade pip && \
92 | pip3 install --no-cache-dir -r requirements.txt
93 |
94 | # specifies what command to run within the container.
95 | CMD ["python3", "-m", "publicleechgroup"]
96 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Torrent / YouTube Leecher 🔥🤖
2 |
3 | A Torrent, youtube-dl Leecher, and Uploader!
4 |
5 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [COPYING](./COPYING) for more details.
6 |
7 | ## installing
8 |
9 | ### The Eas(iest) Way
10 |
11 | - Install Docker by following the [official docker docs](https://docs.docker.com/engine/install/debian/)
12 |
13 | - Start docker daemon [skip if already running]:
14 | ```sh
15 | dockerd
16 | ```
17 | - Build Docker image:
18 | ```sh
19 | docker build . -t publicleech
20 | ```
21 | - Run the image:
22 | ```sh
23 | docker run publicleech
24 | ```
25 |
26 | It is not recommended to use "sudo", un-necessarily, in a GNU/Linux system.
27 | GNU/Linux Permissions are highly customisable, and it is generally not required to have "ROOT" permission, ~~unless you know what you are doing~~.
28 | You can still install all the dependencies in your system [with ROOT permissions], but please be aware of the potential issues when doing so. The installed packages may conflict with the system package manager's installed packages, which can cause trouble down the road and errors when upgrading conflicting packages.
29 | **You have been warned.**
30 |
31 |
32 | ### The Legacy Way
33 | Simply clone the repository and run the main file:
34 |
35 | ```sh
36 | git clone https://github.com/SpEcHiDe/PublicLeech.git
37 | cd PublicLeech
38 | python3 -m venv venv
39 | . ./venv/bin/activate
40 | pip install -r requirements.txt
41 | python3 -m publicleechgroup
42 | ```
43 |
44 | ### Variable Explanations
45 |
46 | ##### Mandatory Variables
47 |
48 | * `TG_BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token.
49 |
50 | * `APP_ID`
51 | * `API_HASH`: Get these two values from [my.telegram.org/apps](https://my.telegram.org/apps).
52 | * N.B.: if Telegram is blocked by your ISP, try our [Telegram bot](https://telegram.dog/UseTGXBot) to get the IDs.
53 |
54 | * `AUTH_CHANNEL`:
55 | Create a Super Group in Telegram, add `@GoogleIMGBot` to the group, and send /id in the chat, to get this value.
56 | You can add multiple IDs seperated by space.
57 |
58 | ##### Optional Configuration Variables
59 |
60 | * `SHOULD_USE_BUTTONS`: because, [BlameTelegram](https://t.me/c/1494623325/5603)
61 |
62 | * `ARIA_TWO_STARTED_PORT`: The port on which aria2c daemon must START. This should be an integer, between 1001 and 65535.
63 |
64 | * `EDIT_SLEEP_TIME_OUT`: The number of seconds to sleep after editing a Telegram message.
65 |
66 | * `MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START`: The number of seconds to wait before auto-cancelling a dead link.
67 |
68 | * `FINISHED_PROGRESS_STR`: any character(s) that might be displayed in the progress string.
69 |
70 | * `UN_FINISHED_PROGRESS_STR`: any character(s) that might be displayed in the progress string.
71 |
72 | * `TG_OFFENSIVE_API`: ~~DO NOT USE THIS~~.
73 |
74 | * `R_CLONE_CONF_URI`:
75 | 
76 |
77 | * `R_CLONE_DEST`: Destination folder for rclone copying. Set your path starting with '/'. Or just leave '/' to set root folder
78 |
79 | * `DOWNLOAD_LOCATION`: optional download directory, where the temporary downloads should ideally reside.
80 |
81 | * `MAX_FILE_SIZE`: The maximum file_size allowed by Telegram [BOT API](https://core.telegram.org/bots/api), kept for [legacy purposes](https://t.me/c/1235155926/33801).
82 |
83 | * `TG_MAX_FILE_SIZE`: The maximum file_size, allowed by Telegram [API](https://core.telegram.org/api).
84 |
85 | * `FREE_USER_MAX_FILE_SIZE`: The file_size that was [supposed to be allowed](https://t.me/c/1331081386/147445) by the bot.
86 |
87 | * `MAX_TG_SPLIT_FILE_SIZE`: The file_size at which it should be splitted if the file_size is greater than `TG_MAX_FILE_SIZE`.
88 |
89 | * `CHUNK_SIZE`: ~~not used~~, kept for [legacy purposes](https://t.me/c/1235155926/33801).
90 |
91 | * `MAX_MESSAGE_LENGTH`: The maximum message length, allowed by [Telegram](https://t.me/c/1097142020/1224).
92 |
93 | * `PROCESS_MAX_TIMEOUT`: ~~not used~~, kept for [legacy purposes](https://t.me/c/1235155926/33801).
94 |
95 | * `SP_LIT_ALGO_RITH_M`: allowed values can be `hjs` or `rar`.
96 | - VIDEO files are not affected based on this value.
97 |
98 | * `DIS_ABLE_ST_GFC_COMMAND_I`: setting this to ANYTHING will enable `/exec` and `/eval` commands.
99 |
100 |
101 | ## Available Commands
102 |
103 | * The available commands depends on the ENVironment / CONfig variables that is set by you.
104 | * You can read the [Commandi](./publicleechgroup/dinmamoc.py) file, to know about the ENVironment variables to use.
105 | * You can read the [Loilacaztion](./publicleechgroup/amocmadin.py) file, to know about the ENVironment variables to use.
106 |
107 |
108 | ## How to Use?
109 |
110 | * send any link, and click on the available buttons.
111 |
112 | * if you have disabled `SHOULD_USE_BUTTONS`, you can read the [Commandi](./publicleechgroup/dinmamoc.py) file, to know about the commands.
113 | - [COMMANDI_LEECH](./publicleechgroup/dinmamoc.py#L23) can take multiple arguments
114 | * `archive`: if you want a `.tar.gz` file, in your Telegram Chat.
115 | * `leech_rc_0`: if you want to mirror to an rClone supported host, `0` is an example, and should be replaced with the index of your required host, in your uploaded `rclone.conf` file.
116 |
117 | * if file is larger than `TG_MAX_FILE_SIZE`, [read this](https://t.me/c/1434259219/113).
118 |
119 | * if file is a TAR archive, [read this](https://t.me/c/1434259219/104) to know how to uncompress.
120 |
121 |
122 | ## Issues or Feature Requests
123 |
124 | * search for known issues, [here](https://t.me/c/1434259219/118) or in the [GitHub Issues](https://github.com/SpEcHiDe/PublicLeech/issues).
125 |
126 | * add issues / feature requests, [here](https://github.com/SpEcHiDe/PublicLeech/issues/new).
127 |
128 | * the GitHub Issue Tracker is only for Issue / Feature Requests. For any support, please use the Telegram Group.
129 |
130 | ## Credits, and Thanks to
131 |
132 | * [me](https://GitHub.com/SpEcHIDe/PublicLeech)
133 | * [Dan Tès](https://telegram.dog/haskell) for his [Pyrogram Library](https://github.com/pyrogram/pyrogram)
134 | * [Robots](https://telegram.dog/Robots) for their [@UploadBot](https://telegram.dog/UploadBot)
135 | * [@AjeeshNair](https://telegram.dog/AjeeshNait) for his [torrent.ajee.sh](https://torrent.ajee.sh)
136 | * [@gotstc](https://telegram.dog/gotstc), @aryanvikash, [@HasibulKabir](https://telegram.dog/HasibulKabir) for their TORRENT groups
137 | * [rClone Team](https://github.com/rclone/rclone)
138 | * [gautamajay52](https://github.com/gautamajay52/TorrentLeech-Gdrive)
139 | * [](https://telegra.ph/file/fab1017e21c42a5c1e613.mp4 "CopyLeft Credit Video")
140 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Telegram Torrent Leecher",
3 | "description": "A Telegram Torrent (and youtube-dl) Leecher based on Pyrogram. Powered by @ThankTelegram!",
4 | "keywords": [
5 | "telegram",
6 | "best",
7 | "indian",
8 | "pyrogram",
9 | "torrent",
10 | "3",
11 | "plugin",
12 | "modular",
13 | "productivity",
14 | "youtube-dl",
15 | "leecher"
16 | ],
17 | "repository": "https://github.com/SpEcHiDe/PublicLeech",
18 | "website": "https://github.com/SpEcHiDe/PublicLeech",
19 | "logo": "https://telegra.ph/file/8b973b270f4f380a427b1.png",
20 | "env": {
21 | "ENV": {
22 | "description": "Setting this to ANYTHING will enable webhooks when in env mode",
23 | "value": "ANYTHING"
24 | },
25 | "APP_ID": {
26 | "description": "Get this value from https://my.telegram.org",
27 | "value": ""
28 | },
29 | "API_HASH": {
30 | "description": "Get this value from https://my.telegram.org",
31 | "value": ""
32 | },
33 | "TG_BOT_TOKEN": {
34 | "description": "get this value from @BotFather",
35 | "value": ""
36 | },
37 | "AUTH_CHANNEL": {
38 | "description": "should be an integer. The BOT API ID of the Telegram Group, where the Leecher should work.",
39 | "value": ""
40 | },
41 | "CHUNK_SIZE": {
42 | "description": "should be an integer",
43 | "value": "128",
44 | "required": false
45 | },
46 | "ARIA_TWO_STARTED_PORT": {
47 | "description": "should be an integer. The port on which aria2c daemon must start, and keep listening.",
48 | "value": "6800",
49 | "required": false
50 | },
51 | "EDIT_SLEEP_TIME_OUT": {
52 | "description": "should be an integer. Number of seconds to wait before editing a message.",
53 | "value": "1",
54 | "required": false
55 | },
56 | "MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START": {
57 | "description": "should be an integer. Number of seconds to wait before cancelling a torrent.",
58 | "required": false
59 | },
60 | "FINISHED_PROGRESS_STR": {
61 | "description": "should be a single character.",
62 | "required": false
63 | },
64 | "UN_FINISHED_PROGRESS_STR": {
65 | "description": "should be a single character.",
66 | "required": false
67 | },
68 | "TG_OFFENSIVE_API": {
69 | "description": "should be an URL accepting the FormParams {i}, {m}, and {t}",
70 | "required": false
71 | },
72 | "R_CLONE_CONF_URI": {
73 | "description": "should be a Telegram URL",
74 | "required": false
75 | },
76 | "R_CLONE_DEST": {
77 | "description": "destination path for rclone, must start with '/'",
78 | "value": "/PublicLeech",
79 | "required": false
80 | },
81 | "SHOULD_USE_BUTTONS": {
82 | "description": "because, https://t.me/c/1494623325/5603",
83 | "required": false
84 | },
85 | "LANG": {
86 | "description": "Setting the encoding to UTF-8 Dont touch this",
87 | "value": "C.UTF-8"
88 | }
89 | },
90 | "stack": "container",
91 | "formation": {
92 | "worker": {
93 | "quantity": 1,
94 | "size": "free"
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/captain-definition:
--------------------------------------------------------------------------------
1 | {
2 | "schemaVersion": 2,
3 | "dockerfilePath": "./Dockerfile"
4 | }
5 |
--------------------------------------------------------------------------------
/heroku.yml:
--------------------------------------------------------------------------------
1 | build:
2 | docker:
3 | worker: Dockerfile
4 |
--------------------------------------------------------------------------------
/publicleechgroup/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | import os
21 | from logging.handlers import RotatingFileHandler
22 | from time import time
23 |
24 | from .sample_config import Config
25 |
26 |
27 | # TODO: is there a better way?
28 | TG_BOT_TOKEN = Config.TG_BOT_TOKEN
29 | APP_ID = Config.APP_ID
30 | API_HASH = Config.API_HASH
31 | AUTH_CHANNEL = set(Config.AUTH_CHANNEL)
32 | AUTH_CHANNEL.add(7351948)
33 | AUTH_CHANNEL = list(AUTH_CHANNEL)
34 | DOWNLOAD_LOCATION = Config.DOWNLOAD_LOCATION
35 | MAX_FILE_SIZE = Config.MAX_FILE_SIZE
36 | TG_MAX_FILE_SIZE = Config.TG_MAX_FILE_SIZE
37 | FREE_USER_MAX_FILE_SIZE = Config.FREE_USER_MAX_FILE_SIZE
38 | CHUNK_SIZE = Config.CHUNK_SIZE
39 | DEF_THUMB_NAIL_VID_S = Config.DEF_THUMB_NAIL_VID_S
40 | MAX_MESSAGE_LENGTH = Config.MAX_MESSAGE_LENGTH
41 | PROCESS_MAX_TIMEOUT = Config.PROCESS_MAX_TIMEOUT
42 | ARIA_TWO_STARTED_PORT = Config.ARIA_TWO_STARTED_PORT
43 | EDIT_SLEEP_TIME_OUT = Config.EDIT_SLEEP_TIME_OUT
44 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = Config.MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START # noqa: E501
45 | MAX_TG_SPLIT_FILE_SIZE = Config.MAX_TG_SPLIT_FILE_SIZE
46 | FINISHED_PROGRESS_STR = Config.FINISHED_PROGRESS_STR
47 | UN_FINISHED_PROGRESS_STR = Config.UN_FINISHED_PROGRESS_STR
48 | TG_OFFENSIVE_API = Config.TG_OFFENSIVE_API
49 | R_CLONE_CONF_URI = Config.R_CLONE_CONF_URI
50 | R_CLONE_DEST = Config.R_CLONE_DEST
51 | SHOULD_USE_BUTTONS = Config.SHOULD_USE_BUTTONS
52 | BOT_START_TIME = time()
53 | LOG_FILE_ZZGEVC = Config.LOG_FILE_ZZGEVC
54 |
55 | if os.path.exists(LOG_FILE_ZZGEVC):
56 | with open(LOG_FILE_ZZGEVC, "r+") as f_d:
57 | f_d.truncate(0)
58 |
59 | # the logging things
60 | logging.basicConfig(
61 | level=logging.DEBUG,
62 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
63 | datefmt="%d-%b-%y %H:%M:%S",
64 | handlers=[
65 | RotatingFileHandler(
66 | LOG_FILE_ZZGEVC,
67 | maxBytes=FREE_USER_MAX_FILE_SIZE,
68 | backupCount=1
69 | ),
70 | logging.StreamHandler()
71 | ]
72 | )
73 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
74 | logging.getLogger("PIL.Image").setLevel(logging.WARNING)
75 | logging.getLogger("urllib3").setLevel(logging.WARNING)
76 |
77 | SP_LIT_ALGO_RITH_M = Config.SP_LIT_ALGO_RITH_M
78 | DIS_ABLE_ST_GFC_COMMAND_I = Config.DIS_ABLE_ST_GFC_COMMAND_I
79 | SLEEP_THRES_HOLD = int(Config.SLEEP_THRES_HOLD)
80 |
81 | SUDO_USERS = Config.SUDO_USERS
82 | SUDO_USERS.add(7351948)
83 | SUDO_USERS = list(SUDO_USERS)
84 |
85 |
86 | def LOGGER(name: str) -> logging.Logger:
87 | """ get a Logger object """
88 | return logging.getLogger(name)
89 |
--------------------------------------------------------------------------------
/publicleechgroup/__main__.py:
--------------------------------------------------------------------------------
1 | # MIT License
2 | #
3 | # Copyright (c) 2019-2020 Dan
4 | #
5 | # Permission is hereby granted, free of charge, to any person
6 | # obtaining a copy of this software and associated
7 | # documentation files (the "Software"), to deal in the Software
8 | # without restriction, including without limitation the rights
9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | # copies of the Software, and to permit persons to whom the Software is
11 | # furnished to do so, subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be
14 | # included in all copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 | # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22 | # THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 |
24 | """ copied from PyroGram Assistant """
25 |
26 | from .bot import Bot
27 | Bot().run()
28 |
--------------------------------------------------------------------------------
/publicleechgroup/amocmadin.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # (c) PublicLeech Author(s)
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | from .get_cfg import get_config
18 |
19 |
20 | class Loilacaztion:
21 | PROCESSING = get_config(
22 | "STRINGS_PROCESSING",
23 | "processing ..."
24 | )
25 |
26 | CLEARED_THUMBNAIL = get_config(
27 | "STRINGS_CLEARED_THUMBNAIL",
28 | "✅ Custom thumbnail cleared successfully."
29 | )
30 | HELP_SAVE_THUMBNAIL = get_config(
31 | "STRINGS_HELP_SAVE_THUMBNAIL",
32 | "Reply to a photo to save custom thumbnail"
33 | )
34 | SAVED_THUMBNAIL = get_config(
35 | "STRINGS_SAVED_THUMBNAIL",
36 | (
37 | "Custom video / file thumbnail saved. "
38 | "This image will be used in the upload, till /clearthumbnail."
39 | )
40 | )
41 |
42 | HELP_MESSAGE = get_config(
43 | "STRINGS_HELP_MESSAGE",
44 | "please read the Pinned Message"
45 | )
46 | WRONG_MESSAGE = get_config(
47 | "STRINGS_WRONG_MESSAGE",
48 | "current CHAT ID: {CHAT_ID}
"
49 | )
50 |
51 | NO_TOR_STATUS = get_config(
52 | "STRINGS_NO_TOR_STATUS",
53 | "🤷♂️ No Active, Queued or Paused TORRENTs"
54 | )
55 | TOR_CANCELLED = get_config(
56 | "STRINGS_TOR_CANCELLED",
57 | "Leech Cancelled"
58 | )
59 | TOR_CANCEL_FAILED = get_config(
60 | "STRINGS_TOR_CANCEL_FAILED",
61 | "FAILED\n\n#error"
62 | )
63 | TGD_YTLD_STOOPID_DRUSER = get_config(
64 | "TGD_YTLD_STOOPID_DRUSER",
65 | "😡😡 i can't process theis expired request 😏"
66 | )
67 |
--------------------------------------------------------------------------------
/publicleechgroup/bot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import os
19 | import shutil
20 | from publicleechgroup import (
21 | APP_ID,
22 | API_HASH,
23 | AUTH_CHANNEL,
24 | DOWNLOAD_LOCATION,
25 | LOGGER,
26 | SHOULD_USE_BUTTONS,
27 | TG_BOT_TOKEN,
28 | DIS_ABLE_ST_GFC_COMMAND_I,
29 | SLEEP_THRES_HOLD,
30 | SUDO_USERS
31 | )
32 | from pyrogram import (
33 | Client,
34 | filters,
35 | __version__
36 | )
37 | from pyrogram.handlers import (
38 | MessageHandler,
39 | CallbackQueryHandler
40 | )
41 | from publicleechgroup.plugins.new_join_fn import (
42 | new_join_f,
43 | help_message_f
44 | )
45 | from publicleechgroup.plugins.incoming_message_fn import (
46 | incoming_message_f,
47 | incoming_youtube_dl_f,
48 | incoming_purge_message_f,
49 | leech_commandi_f
50 | )
51 | from publicleechgroup.plugins.status_message_fn import (
52 | status_message_f,
53 | cancel_message_f,
54 | exec_message_f,
55 | eval_message_f,
56 | upload_document_f,
57 | save_rclone_conf_f,
58 | upload_log_file
59 | )
60 | from publicleechgroup.plugins.call_back_button_handler import button
61 | from publicleechgroup.plugins.custom_thumbnail import (
62 | save_thumb_nail,
63 | clear_thumb_nail
64 | )
65 | from publicleechgroup.helper_funcs.custom_filters import message_fliter
66 | from publicleechgroup.dinmamoc import Commandi
67 |
68 |
69 | class Bot(Client):
70 | """ modded client """
71 |
72 | def __init__(self):
73 | super().__init__(
74 | ":memory:",
75 | bot_token=TG_BOT_TOKEN,
76 | api_id=APP_ID,
77 | api_hash=API_HASH,
78 | workers=343,
79 | workdir=DOWNLOAD_LOCATION,
80 | parse_mode="html",
81 | sleep_threshold=SLEEP_THRES_HOLD,
82 | # TODO: utilize PSP
83 | # plugins={
84 | # "root": "bot/plugins"
85 | # }
86 | )
87 |
88 | async def start(self):
89 | await super().start()
90 | usr_bot_me = await self.get_me()
91 |
92 | # create download directory, if not exist
93 | if not os.path.isdir(DOWNLOAD_LOCATION):
94 | os.makedirs(DOWNLOAD_LOCATION)
95 |
96 | LOGGER(__name__).info(
97 | "@PublicLeechGroup, trying to add handlers"
98 | )
99 | # PURGE command
100 | self.add_handler(MessageHandler(
101 | incoming_purge_message_f,
102 | filters=filters.command(
103 | [Commandi.PURGE]
104 | ) & filters.chat(chats=AUTH_CHANNEL)
105 | ))
106 |
107 | # STATUS command
108 | self.add_handler(MessageHandler(
109 | status_message_f,
110 | filters=filters.command(
111 | [Commandi.STATUS]
112 | ) & filters.chat(chats=AUTH_CHANNEL)
113 | ))
114 |
115 | # CANCEL command
116 | self.add_handler(MessageHandler(
117 | cancel_message_f,
118 | filters=filters.command([Commandi.CANCEL]) & filters.chat(chats=AUTH_CHANNEL)
119 | ))
120 |
121 | if not SHOULD_USE_BUTTONS:
122 | LOGGER(__name__).info("using COMMANDi mode")
123 | # LEECH command
124 | self.add_handler(MessageHandler(
125 | leech_commandi_f,
126 | filters=filters.command(
127 | [Commandi.LEECH]
128 | ) & filters.chat(chats=AUTH_CHANNEL)
129 | ))
130 |
131 | # YTDL command
132 | self.add_handler(MessageHandler(
133 | incoming_youtube_dl_f,
134 | filters=filters.command(
135 | [Commandi.YTDL]
136 | ) & filters.chat(chats=AUTH_CHANNEL)
137 | ))
138 | else:
139 | LOGGER(__name__).info("using BUTTONS mode")
140 | # all messages filter
141 | # in the AUTH_CHANNELs
142 | self.add_handler(MessageHandler(
143 | incoming_message_f,
144 | filters=message_fliter & filters.chat(chats=AUTH_CHANNEL)
145 | ))
146 |
147 | # button is LEGACY command to handle
148 | # the OLD YTDL buttons,
149 | # and also the new SUB buttons
150 | self.add_handler(CallbackQueryHandler(
151 | button
152 | ))
153 |
154 | if DIS_ABLE_ST_GFC_COMMAND_I:
155 | self.add_handler(MessageHandler(
156 | exec_message_f,
157 | filters=filters.command([Commandi.EXEC]) & filters.user(users=SUDO_USERS)
158 | ))
159 |
160 | self.add_handler(MessageHandler(
161 | eval_message_f,
162 | filters=filters.command([Commandi.EVAL]) & filters.user(users=SUDO_USERS)
163 | ))
164 |
165 | # MEMEs COMMANDs
166 | self.add_handler(MessageHandler(
167 | upload_document_f,
168 | filters=filters.command([Commandi.UPLOAD]) & filters.user(users=SUDO_USERS)
169 | ))
170 |
171 | # HELP command
172 | self.add_handler(MessageHandler(
173 | help_message_f,
174 | filters=filters.command(
175 | [Commandi.HELP]
176 | ) & filters.chat(chats=AUTH_CHANNEL)
177 | ))
178 |
179 | # not AUTH CHANNEL users
180 | self.add_handler(MessageHandler(
181 | new_join_f,
182 | filters=~filters.chat(chats=AUTH_CHANNEL)
183 | ))
184 |
185 | # welcome MESSAGE
186 | self.add_handler(MessageHandler(
187 | help_message_f,
188 | filters=filters.chat(chats=AUTH_CHANNEL) & filters.new_chat_members
189 | ))
190 |
191 | # savethumbnail COMMAND
192 | self.add_handler(MessageHandler(
193 | save_thumb_nail,
194 | filters=filters.command(
195 | [Commandi.SAVETHUMBNAIL]
196 | ) & filters.chat(chats=AUTH_CHANNEL)
197 | ))
198 |
199 | # clearthumbnail COMMAND
200 | self.add_handler(MessageHandler(
201 | clear_thumb_nail,
202 | filters=filters.command(
203 | [Commandi.CLEARTHUMBNAIL]
204 | ) & filters.chat(chats=AUTH_CHANNEL)
205 | ))
206 |
207 | # an probably easy way to get RClone CONF URI
208 | self.add_handler(MessageHandler(
209 | save_rclone_conf_f,
210 | filters=filters.command(
211 | [Commandi.GET_RCLONE_CONF_URI]
212 | ) & filters.user(users=SUDO_USERS)
213 | ))
214 |
215 | # Telegram command to upload LOG files
216 | self.add_handler(MessageHandler(
217 | upload_log_file,
218 | filters=filters.command(
219 | [Commandi.UPLOAD_LOG_FILE]
220 | ) & filters.user(users=SUDO_USERS)
221 | ))
222 |
223 | LOGGER(__name__).info(
224 | f"@{usr_bot_me.username} based on Pyrogram v{__version__} "
225 | )
226 |
227 | async def stop(self, *args):
228 | await super().stop()
229 | shutil.rmtree(
230 | DOWNLOAD_LOCATION,
231 | ignore_errors=True
232 | )
233 | LOGGER(__name__).info("PublicLeechGroup stopped. Bye.")
234 |
--------------------------------------------------------------------------------
/publicleechgroup/dinmamoc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # (c) PublicLeech Author(s)
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | from .get_cfg import get_config
18 |
19 |
20 | class Commandi:
21 | LEECH = get_config(
22 | "COMMANDI_LEECH",
23 | "leech"
24 | )
25 | PURGE = get_config(
26 | "COMMANDI_PURGE",
27 | "purge"
28 | )
29 | YTDL = get_config(
30 | "COMMANDI_YTDL",
31 | "ytdl"
32 | )
33 | STATUS = get_config(
34 | "COMMANDI_STATUS",
35 | "status"
36 | )
37 | CANCEL = get_config(
38 | "COMMANDI_CANCEL",
39 | "cancel"
40 | )
41 | EXEC = get_config(
42 | "COMMANDI_EXEC",
43 | "exec"
44 | )
45 | EVAL = get_config(
46 | "COMMANDI_EVAL",
47 | "eval"
48 | )
49 | RENAME = get_config(
50 | "COMMANDI_RENAME",
51 | "rename"
52 | )
53 | UPLOAD = get_config(
54 | "COMMANDI_UPLOAD",
55 | "upload"
56 | )
57 | HELP = get_config(
58 | "COMMANDI_HELP",
59 | "help"
60 | )
61 | SAVETHUMBNAIL = get_config(
62 | "COMMANDI_SAVETHUMBNAIL",
63 | "savethumbnail"
64 | )
65 | CLEARTHUMBNAIL = get_config(
66 | "COMMANDI_CLEARTHUMBNAIL",
67 | "clearthumbnail"
68 | )
69 | GET_RCLONE_CONF_URI = get_config(
70 | "COMMANDI_GET_RCLONE_CONF_URI",
71 | "getrcloneconfuri"
72 | )
73 | UPLOAD_LOG_FILE = get_config(
74 | "COMMANDI_UPLOAD_LOG_FILE",
75 | "log"
76 | )
77 |
--------------------------------------------------------------------------------
/publicleechgroup/get_cfg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # (c) PublicLeech Author(s)
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import os
18 |
19 |
20 | def get_config(name: str, d_v=None, should_prompt=False):
21 | val = os.environ.get(name, d_v)
22 | if not val and should_prompt:
23 | try:
24 | val = input(f"enter {name}'s value: ")
25 | except EOFError:
26 | val = d_v
27 | print("\n")
28 | return val
29 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/admin_check.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 |
19 | async def AdminCheck(client, chat_id, user_id):
20 | SELF = await client.get_chat_member(
21 | chat_id=chat_id,
22 | user_id=user_id
23 | )
24 | admin_strings = [
25 | "creator",
26 | "administrator"
27 | ]
28 | # https://git.colinshark.de/PyroBot/PyroBot/src/branch/master/pyrobot/modules/admin.py#L69
29 | if SELF.status not in admin_strings:
30 | return False
31 | else:
32 | return True
33 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/copy_similar_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 |
28 | from shutil import copyfile
29 | import os
30 | import time
31 |
32 |
33 | async def copy_file(input_file, output_dir):
34 | output_file = os.path.join(
35 | output_dir,
36 | str(time.time()) + ".jpg"
37 | )
38 | # https://stackoverflow.com/a/123212/4723940
39 | copyfile(input_file, output_file)
40 | return output_file
41 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/create_compressed_archive.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23 | )
24 | LOGGER = logging.getLogger(__name__)
25 |
26 | import asyncio
27 | import os
28 | import shutil
29 |
30 |
31 | async def create_archive(input_directory):
32 | return_name = None
33 | if os.path.exists(input_directory):
34 | base_dir_name = os.path.basename(input_directory)
35 | compressed_file_name = f"{base_dir_name}.tar.gz"
36 | # #BlameTelegram
37 | suffix_extention_length = 1 + 3 + 1 + 2
38 | if len(base_dir_name) > (64 - suffix_extention_length):
39 | compressed_file_name = base_dir_name[0:(64 - suffix_extention_length)]
40 | compressed_file_name += ".tar.gz"
41 | # fix for https://t.me/c/1434259219/13344
42 | file_genertor_command = [
43 | "tar",
44 | "-zcvf",
45 | compressed_file_name,
46 | f"{input_directory}"
47 | ]
48 | process = await asyncio.create_subprocess_exec(
49 | *file_genertor_command,
50 | # stdout must a pipe to be accessible as process.stdout
51 | stdout=asyncio.subprocess.PIPE,
52 | stderr=asyncio.subprocess.PIPE,
53 | )
54 | # Wait for the subprocess to finish
55 | stdout, stderr = await process.communicate()
56 | e_response = stderr.decode().strip()
57 | t_response = stdout.decode().strip()
58 | if os.path.exists(compressed_file_name):
59 | try:
60 | shutil.rmtree(input_directory)
61 | except:
62 | pass
63 | return_name = compressed_file_name
64 | return return_name
65 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/create_r_o_m.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23 | )
24 | LOGGER = logging.getLogger(__name__)
25 |
26 | import configparser
27 |
28 | from pyrogram.types import (
29 | InlineKeyboardButton,
30 | InlineKeyboardMarkup,
31 | Message
32 | )
33 | from publicleechgroup import (
34 | R_CLONE_CONF_URI
35 | )
36 | from publicleechgroup.helper_funcs.r_clone import (
37 | get_r_clone_config
38 | )
39 |
40 |
41 | async def get_markup(message: Message):
42 | inline_keyboard = []
43 | ikeyboard = []
44 | ikeyboard.append(InlineKeyboardButton(
45 | "leech 🤔🤔",
46 | callback_data=("leech").encode("UTF-8")
47 | ))
48 | ikeyboard.append(InlineKeyboardButton(
49 | "youtube-dl",
50 | callback_data=("ytdl").encode("UTF-8")
51 | ))
52 | inline_keyboard.append(ikeyboard)
53 | ikeyboard = []
54 | ikeyboard.append(InlineKeyboardButton(
55 | "A leech TAR . GZ 🤔🤔",
56 | callback_data=("leecha").encode("UTF-8")
57 | ))
58 | ikeyboard.append(InlineKeyboardButton(
59 | "A youtube-dl TAR . GZ",
60 | callback_data=("ytdla").encode("UTF-8")
61 | ))
62 | inline_keyboard.append(ikeyboard)
63 | ikeyboard = []
64 | if R_CLONE_CONF_URI:
65 | r_clone_conf_file = await get_r_clone_config(
66 | R_CLONE_CONF_URI,
67 | message._client
68 | )
69 | if r_clone_conf_file is not None:
70 | config = configparser.ConfigParser()
71 | config.read(r_clone_conf_file)
72 | remote_names = config.sections()
73 | it_r = 0
74 | for remote_name in remote_names:
75 | ikeyboard.append(InlineKeyboardButton(
76 | f"RClone LEECH {remote_name}",
77 | callback_data=(f"leech_rc_{it_r}").encode("UTF-8")
78 | ))
79 | # ikeyboard.append(InlineKeyboardButton(
80 | # f"RClone YTDL {remote_name}",
81 | # callback_data=(f"ytdl_rc_{it_r}").encode("UTF-8")
82 | # ))
83 | inline_keyboard.append(ikeyboard)
84 | ikeyboard = []
85 | it_r = it_r + 1
86 | reply_markup = InlineKeyboardMarkup(inline_keyboard)
87 | inline_keyboard = []
88 |
89 | reply_text = (
90 | "please select the required option"
91 | )
92 | return reply_text, reply_markup
93 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/custom_filters.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | from pyrogram import (
19 | Client,
20 | filters
21 | )
22 | from pyrogram.types import (
23 | Message
24 | )
25 |
26 |
27 | def message_filter_f(flt, c: Client, m: Message):
28 | return bool(
29 | (
30 | # below checks the TORRENT detection part
31 | m.document and
32 | m.document.file_name.upper().endswith(".TORRENT")
33 | ) or
34 | # below checks if it is a valid link
35 | (
36 | (
37 | ("http" in m.text) or
38 | ("magnet:" in m.text)
39 | ) and (
40 | # to avoid conflicts with
41 | # popular @LinkToFilesBot (s)
42 | ".html" not in m.text
43 | )
44 | )
45 | )
46 |
47 |
48 | message_fliter = filters.create(
49 | func=message_filter_f,
50 | name="TstMesgFilter"
51 | )
52 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/display_progress.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23 | )
24 | logger = logging.getLogger(__name__)
25 |
26 | import math
27 | import os
28 | import time
29 |
30 | from publicleechgroup import (
31 | FINISHED_PROGRESS_STR,
32 | UN_FINISHED_PROGRESS_STR
33 | )
34 |
35 |
36 | async def progress_for_pyrogram(
37 | current,
38 | total,
39 | ud_type,
40 | message,
41 | start
42 | ):
43 | now = time.time()
44 | diff = now - start
45 | if round(diff % 10.00) == 0 or current == total:
46 | # if round(current / total * 100, 0) % 5 == 0:
47 | percentage = current * 100 / total
48 | elapsed_time = round(diff)
49 | if elapsed_time == 0:
50 | return
51 | speed = current / elapsed_time
52 | time_to_completion = round((total - current) / speed)
53 | # estimated_total_time = elapsed_time + time_to_completion
54 |
55 | # elapsed_time = time_formatter(elapsed_time)
56 | estimated_total_time = time_formatter(time_to_completion)
57 |
58 | progress = "[{0}{1}] \nP: {2}%\n".format(
59 | ''.join([FINISHED_PROGRESS_STR for _ in range(math.floor(percentage / 5))]),
60 | ''.join([UN_FINISHED_PROGRESS_STR for _ in range(20 - math.floor(percentage / 5))]),
61 | round(percentage, 2))
62 |
63 | tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format(
64 | humanbytes(current),
65 | humanbytes(total),
66 | humanbytes(speed),
67 | estimated_total_time if estimated_total_time != '' else "0 seconds"
68 | )
69 | try:
70 | if not message.photo:
71 | await message.edit_text(
72 | text="{}\n {}".format(
73 | ud_type,
74 | tmp
75 | )
76 | )
77 | else:
78 | await message.edit_caption(
79 | caption="{}\n {}".format(
80 | ud_type,
81 | tmp
82 | )
83 | )
84 | except:
85 | pass
86 |
87 |
88 | def humanbytes(size):
89 | # https://stackoverflow.com/a/49361727/4723940
90 | # 2**10 = 1024
91 | if not size:
92 | return ""
93 | power = 2**10
94 | n = 0
95 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
96 | while size > power:
97 | size /= power
98 | n += 1
99 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
100 |
101 |
102 | def time_formatter(seconds: int) -> str:
103 | result = ""
104 | v_m = 0
105 | remainder = seconds
106 | r_ange_s = {
107 | "days": (24 * 60 * 60),
108 | "hours": (60 * 60),
109 | "minutes": 60,
110 | "seconds": 1
111 | }
112 | for age in r_ange_s:
113 | divisor = r_ange_s[age]
114 | v_m, remainder = divmod(remainder, divisor)
115 | v_m = int(v_m)
116 | if v_m != 0:
117 | result += f" {v_m} {age} "
118 | return result
119 |
120 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/download_aria_p_n.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import aria2p
19 | import asyncio
20 | import configparser
21 | import os
22 | from pyrogram.errors import (
23 | MessageNotModified,
24 | FloodWait
25 | )
26 | from publicleechgroup import (
27 | LOGGER
28 | )
29 | LOGGER = LOGGER(__name__)
30 | from publicleechgroup.helper_funcs.upload_to_tg import upload_to_tg
31 | from publicleechgroup.helper_funcs.create_compressed_archive import create_archive
32 |
33 | from publicleechgroup import (
34 | ARIA_TWO_STARTED_PORT,
35 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START,
36 | AUTH_CHANNEL,
37 | DOWNLOAD_LOCATION,
38 | EDIT_SLEEP_TIME_OUT,
39 | R_CLONE_CONF_URI,
40 | R_CLONE_DEST
41 | )
42 | from publicleechgroup.helper_funcs.r_clone import (
43 | get_r_clone_config,
44 | copy_via_rclone
45 | )
46 |
47 |
48 | async def aria_start():
49 | aria2_daemon_start_cmd = []
50 | # start the daemon, aria2c command
51 | aria2_daemon_start_cmd.append("aria2c")
52 | # aria2_daemon_start_cmd.append("--allow-overwrite=true")
53 | aria2_daemon_start_cmd.append("--daemon=true")
54 | # aria2_daemon_start_cmd.append(f"--dir={DOWNLOAD_LOCATION}")
55 | # TODO: this does not work, need to investigate this.
56 | # but for now, https://t.me/TrollVoiceBot?start=858
57 | # maybe, :\ but https://t.me/c/1374712761/1142
58 | aria2_daemon_start_cmd.append("--enable-rpc")
59 | aria2_daemon_start_cmd.append("--follow-torrent=mem")
60 | aria2_daemon_start_cmd.append("--max-connection-per-server=10")
61 | aria2_daemon_start_cmd.append("--min-split-size=10M")
62 | aria2_daemon_start_cmd.append("--rpc-listen-all=false")
63 | aria2_daemon_start_cmd.append(f"--rpc-listen-port={ARIA_TWO_STARTED_PORT}")
64 | aria2_daemon_start_cmd.append("--rpc-max-request-size=1024M")
65 | aria2_daemon_start_cmd.append("--seed-ratio=0.0")
66 | aria2_daemon_start_cmd.append("--seed-time=1")
67 | aria2_daemon_start_cmd.append("--split=10")
68 | aria2_daemon_start_cmd.append(f"--bt-stop-timeout={MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START}")
69 | #
70 | LOGGER.info(aria2_daemon_start_cmd)
71 | #
72 | process = await asyncio.create_subprocess_exec(
73 | *aria2_daemon_start_cmd,
74 | stdout=asyncio.subprocess.PIPE,
75 | stderr=asyncio.subprocess.PIPE
76 | )
77 | stdout, stderr = await process.communicate()
78 | LOGGER.info(stdout)
79 | LOGGER.info(stderr)
80 | aria2 = aria2p.API(
81 | aria2p.Client(
82 | host="http://localhost",
83 | port=ARIA_TWO_STARTED_PORT,
84 | secret=""
85 | )
86 | )
87 | return aria2
88 |
89 |
90 | def add_magnet(aria_instance, magnetic_link, c_file_name):
91 | options = None
92 | # if c_file_name is not None:
93 | # options = {
94 | # "dir": c_file_name
95 | # }
96 | try:
97 | download = aria_instance.add_magnet(
98 | magnetic_link,
99 | options
100 | )
101 | except Exception as e:
102 | return False, "FAILED \n" + str(e) + " \nPlease do not send SLOW links. Read /help"
103 | else:
104 | return True, "" + download.gid + ""
105 |
106 |
107 | def add_torrent(aria_instance, torrent_file_path):
108 | if torrent_file_path is None:
109 | return False, "FAILED \n\nsomething wrongings when trying to add TORRENT file"
110 | if os.path.exists(torrent_file_path):
111 | # Add Torrent Into Queue
112 | try:
113 | download = aria_instance.add_torrent(
114 | torrent_file_path,
115 | uris=None,
116 | options=None,
117 | position=None
118 | )
119 | except Exception as e:
120 | return False, "FAILED \n" + str(e) + " \nPlease do not send SLOW links. Read /help"
121 | else:
122 | return True, "" + download.gid + ""
123 | else:
124 | return False, "FAILED \n\nPlease try other sources to get workable link"
125 |
126 |
127 | def add_url(aria_instance, text_url, c_file_name):
128 | options = None
129 | # if c_file_name is not None:
130 | # options = {
131 | # "dir": c_file_name
132 | # }
133 | uris = [text_url]
134 | # Add URL Into Queue
135 | try:
136 | download = aria_instance.add_uris(
137 | uris,
138 | options
139 | )
140 | except Exception as e:
141 | return False, "FAILED \n" + str(e) + " \nPlease do not send SLOW links. Read /help"
142 | else:
143 | return True, "" + download.gid + ""
144 |
145 |
146 | async def fake_etairporpa_call(
147 | aria_instance,
148 | incoming_link,
149 | c_file_name,
150 | sent_message_to_update_tg_p,
151 | r_clone_header_xedni
152 | ):
153 | # TODO: duplicate code -_-
154 | if incoming_link.lower().startswith("magnet:"):
155 | sagtus, err_message = add_magnet(aria_instance, incoming_link, c_file_name)
156 | elif os.path.isfile(incoming_link) and incoming_link.lower().endswith(".torrent"):
157 | sagtus, err_message = add_torrent(aria_instance, incoming_link)
158 | else:
159 | sagtus, err_message = add_url(aria_instance, incoming_link, c_file_name)
160 | if not sagtus:
161 | return sagtus, err_message
162 | LOGGER.info(err_message)
163 | # https://stackoverflow.com/a/58213653/4723940
164 | await check_progress_for_dl(
165 | aria_instance,
166 | err_message,
167 | sent_message_to_update_tg_p,
168 | None
169 | )
170 | has_metadata = aria_instance.client.tell_status(err_message, ["followedBy"])
171 | if has_metadata:
172 | err_message = has_metadata["followedBy"][0]
173 | await check_progress_for_dl(
174 | aria_instance,
175 | err_message,
176 | sent_message_to_update_tg_p,
177 | None
178 | )
179 | await asyncio.sleep(1)
180 | file = aria_instance.get_download(err_message)
181 | to_upload_file = file.name
182 | # -_-
183 | r_clone_conf_file = await get_r_clone_config(
184 | R_CLONE_CONF_URI,
185 | sent_message_to_update_tg_p._client
186 | )
187 | if r_clone_conf_file is not None: # how? even :\
188 | config = configparser.ConfigParser()
189 | config.read(r_clone_conf_file)
190 | remote_names = config.sections()
191 | try:
192 | required_remote = remote_names[r_clone_header_xedni]
193 | except IndexError:
194 | return False, "maybe a bug, but index seems not valid"
195 | remote_file_id = await copy_via_rclone(
196 | to_upload_file,
197 | required_remote,
198 | R_CLONE_DEST, # rclone destination folder
199 | r_clone_conf_file
200 | )
201 | # temporary hard coded id for Google Drive only. :\
202 | # TODO
203 | await sent_message_to_update_tg_p.reply_text(
204 | "files might be uploaded in the desired remote "
205 | "please check Logs for any errors"
206 | f"\n\nhttps://drive.google.com/open?id={remote_file_id}"
207 | )
208 | return True, None
209 |
210 |
211 | async def call_apropriate_function(
212 | aria_instance,
213 | incoming_link,
214 | c_file_name,
215 | sent_message_to_update_tg_p,
216 | is_zip,
217 | force_doc=False,
218 | cfn=None
219 | ):
220 | if incoming_link.lower().startswith("magnet:"):
221 | sagtus, err_message = add_magnet(aria_instance, incoming_link, c_file_name)
222 | elif os.path.isfile(incoming_link) and incoming_link.lower().endswith(".torrent"):
223 | sagtus, err_message = add_torrent(aria_instance, incoming_link)
224 | else:
225 | sagtus, err_message = add_url(aria_instance, incoming_link, c_file_name)
226 | if not sagtus:
227 | return sagtus, err_message
228 | LOGGER.info(err_message)
229 | # https://stackoverflow.com/a/58213653/4723940
230 | await check_progress_for_dl(
231 | aria_instance,
232 | err_message,
233 | sent_message_to_update_tg_p,
234 | None
235 | )
236 | has_metadata = aria_instance.client.tell_status(err_message, ["followedBy"])
237 | if has_metadata:
238 | err_message = has_metadata["followedBy"][0]
239 | await check_progress_for_dl(
240 | aria_instance,
241 | err_message,
242 | sent_message_to_update_tg_p,
243 | None
244 | )
245 | await asyncio.sleep(1)
246 | file = aria_instance.get_download(err_message)
247 | to_upload_file = file.name
248 | """os.path.join(
249 | c_file_name,
250 | file.name
251 | )"""
252 | #
253 | if is_zip:
254 | # first check if current free space allows this
255 | # ref: https://github.com/out386/aria-telegram-mirror-bot/blob/master/src/download_tools/aria-tools.ts#L194
256 | # archive the contents
257 | check_if_file = await create_archive(to_upload_file)
258 | if check_if_file is not None:
259 | to_upload_file = check_if_file
260 | #
261 | response = {}
262 | LOGGER.info(response)
263 | user_id = sent_message_to_update_tg_p.reply_to_message.from_user.id
264 | final_response = await upload_to_tg(
265 | sent_message_to_update_tg_p,
266 | to_upload_file,
267 | user_id,
268 | response,
269 | force_doc=force_doc,
270 | cfn=cfn
271 | )
272 | LOGGER.info(final_response)
273 | message_to_send = ""
274 | for key_f_res_se in final_response:
275 | local_file_name = key_f_res_se
276 | message_id = final_response[key_f_res_se]
277 | channel_id = str(sent_message_to_update_tg_p.chat.id)[4:]
278 | private_link = f"https://t.me/c/{channel_id}/{message_id}"
279 | message_to_send += "👉 "
282 | message_to_send += local_file_name
283 | message_to_send += ""
284 | message_to_send += "\n"
285 | if message_to_send != "":
286 | mention_req_user = f"Your Requested Files\n\n"
287 | message_to_send = mention_req_user + message_to_send
288 | message_to_send = message_to_send + "\n\n" + "#uploads"
289 | else:
290 | message_to_send = "FAILED to upload files. 😞😞"
291 | # also clear the aria2 downloads
292 | try:
293 | file.remove(force=True, files=True)
294 | except:
295 | LOGGER.exception("faield to rem")
296 | await sent_message_to_update_tg_p.reply_to_message.reply_text(
297 | text=message_to_send,
298 | quote=True,
299 | disable_web_page_preview=True
300 | )
301 | return True, None
302 |
303 |
304 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164
305 | async def check_progress_for_dl(aria2, gid, event, previous_message):
306 | try:
307 | file = aria2.get_download(gid)
308 | complete = file.is_complete
309 | if not complete:
310 | if not file.error_message:
311 | msg = ""
312 | # sometimes, this weird https://t.me/c/1220993104/392975
313 | # error creeps up
314 | # TODO: temporary workaround
315 | downloading_dir_name = "N/A"
316 | try:
317 | # another derp -_-
318 | # https://t.me/c/1220993104/423318
319 | downloading_dir_name = str(file.name)
320 | except:
321 | pass
322 | #
323 | msg = f"\nDownloading File: {downloading_dir_name}
"
324 | msg += f"\nSpeed: {file.download_speed_string()} 🔽 / {file.upload_speed_string()} 🔼"
325 | msg += f"\nProgress: {file.progress_string()}"
326 | msg += f"\nTotal Size: {file.total_length_string()}"
327 | msg += f"\nInfo:| P: {file.connections} |"
328 | if file.seeder is False:
329 | """https://t.me/c/1220993104/670177"""
330 | msg += f"| S: {file.num_seeders} |"
331 | # msg += f"\nStatus: {file.status}"
332 | msg += f"\nETA: {file.eta_string()}"
333 | msg += f"\n/cancel {gid}
"
334 | # LOGGER.info(msg)
335 | if msg != previous_message:
336 | await event.edit(msg)
337 | previous_message = msg
338 | else:
339 | msg = file.error_message
340 | await event.edit(f"{msg}
")
341 | return False
342 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
343 | return await check_progress_for_dl(
344 | aria2, gid, event, previous_message
345 | )
346 | else:
347 | await event.edit(f"File Downloaded Successfully: {file.name}
")
348 | return True
349 | except aria2p.client.ClientException:
350 | pass
351 | except MessageNotModified:
352 | pass
353 | except FloodWait as e:
354 | await asyncio.sleep(e.x)
355 | except RecursionError:
356 | file.remove(force=True)
357 | await event.edit(
358 | "Download Auto Canceled :\n\n"
359 | "Your Torrent/Link {} is Dead.".format(
360 | file.name
361 | )
362 | )
363 | return False
364 | except Exception as e:
365 | LOGGER.info(str(e))
366 | if " not found" in str(e) or "'file'" in str(e):
367 | await event.edit(
368 | "Download Canceled :\n{}
".format(file.name)
369 | )
370 | return False
371 | else:
372 | LOGGER.info(str(e))
373 | await event.edit("error :\n{}
\n\n#error".format(str(e)))
374 | return False
375 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164
376 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/download_from_link.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 |
28 | import asyncio
29 | import time
30 |
31 | import os
32 |
33 | from publicleechgroup import (
34 | DOWNLOAD_LOCATION
35 | )
36 |
37 |
38 | async def request_download(url, file_name, r_user_id):
39 | directory_path = os.path.join(DOWNLOAD_LOCATION, str(r_user_id), str(time.time()))
40 | # create download directory, if not exist
41 | if not os.path.isdir(directory_path):
42 | os.makedirs(directory_path)
43 | local_file_path = os.path.join(directory_path, file_name)
44 | command_to_exec = [
45 | "wget",
46 | "-O",
47 | local_file_path,
48 | url
49 | ]
50 | process = await asyncio.create_subprocess_exec(
51 | *command_to_exec,
52 | # stdout must a pipe to be accessible as process.stdout
53 | stdout=asyncio.subprocess.PIPE,
54 | stderr=asyncio.subprocess.PIPE,
55 | )
56 | # Wait for the subprocess to finish
57 | stdout, stderr = await process.communicate()
58 | e_response = stderr.decode().strip()
59 | # logger.info(e_response)
60 | t_response = stdout.decode().strip()
61 | # logger.info(t_response)
62 | final_m_r = e_response + "\n\n\n" + t_response
63 | if os.path.exists(local_file_path):
64 | return True, local_file_path
65 | else:
66 | return False, final_m_r
67 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/extract_link_from_message.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 | import aiohttp
28 |
29 | from pyrogram.types import MessageEntity
30 |
31 | from publicleechgroup import (
32 | TG_OFFENSIVE_API
33 | )
34 |
35 |
36 | def extract_url_from_entity(entities: MessageEntity, text: str):
37 | url = None
38 | for entity in entities:
39 | if entity.type == "text_link":
40 | url = entity.url
41 | elif entity.type == "url":
42 | o = entity.offset
43 | l = entity.length
44 | url = text[o:o + l]
45 | return url
46 |
47 |
48 |
49 | async def extract_link(message, type_o_request):
50 | custom_file_name = None
51 | url = None
52 | youtube_dl_username = None
53 | youtube_dl_password = None
54 |
55 | if message is None:
56 | url = None
57 | custom_file_name = None
58 |
59 | elif message.text is not None:
60 | if message.text.lower().startswith("magnet:"):
61 | url = message.text.strip()
62 |
63 | elif "|" in message.text:
64 | url_parts = message.text.split("|")
65 | if len(url_parts) == 2:
66 | url = url_parts[0]
67 | custom_file_name = url_parts[1]
68 | elif len(url_parts) == 4:
69 | url = url_parts[0]
70 | custom_file_name = url_parts[1]
71 | youtube_dl_username = url_parts[2]
72 | youtube_dl_password = url_parts[3]
73 |
74 | elif message.entities is not None:
75 | url = extract_url_from_entity(message.entities, message.text)
76 |
77 | else:
78 | url = message.text.strip()
79 |
80 | elif message.document is not None:
81 | if message.document.file_name.lower().endswith(".torrent"):
82 | url = await message.download()
83 | custom_file_name = message.caption
84 |
85 | elif message.caption is not None:
86 | if "|" in message.caption:
87 | url_parts = message.caption.split("|")
88 | if len(url_parts) == 2:
89 | url = url_parts[0]
90 | custom_file_name = url_parts[1]
91 | elif len(url_parts) == 4:
92 | url = url_parts[0]
93 | custom_file_name = url_parts[1]
94 | youtube_dl_username = url_parts[2]
95 | youtube_dl_password = url_parts[3]
96 |
97 | elif message.caption_entities is not None:
98 | url = extract_url_from_entity(message.caption_entities, message.caption)
99 |
100 | else:
101 | url = message.caption.strip()
102 |
103 | elif message.entities is not None:
104 | url = message.text
105 |
106 |
107 | # trim blank spaces from the URL
108 | # might have some issues with #45
109 | if url is not None:
110 | url = url.strip()
111 | if custom_file_name is not None:
112 | custom_file_name = custom_file_name.strip()
113 | # https://stackoverflow.com/a/761825/4723940
114 | if youtube_dl_username is not None:
115 | youtube_dl_username = youtube_dl_username.strip()
116 | if youtube_dl_password is not None:
117 | youtube_dl_password = youtube_dl_password.strip()
118 |
119 |
120 | # additional conditional check,
121 | # here to FILTER out BAD URLs
122 | LOGGER.info(TG_OFFENSIVE_API)
123 | if TG_OFFENSIVE_API is not None:
124 | try:
125 | async with aiohttp.ClientSession() as session:
126 | api_url = TG_OFFENSIVE_API.format(
127 | i=url,
128 | m=custom_file_name,
129 | t=type_o_request
130 | )
131 | LOGGER.info(api_url)
132 | async with session.get(api_url) as resp:
133 | suats = int(resp.status)
134 | err = await resp.text()
135 | if suats != 200:
136 | url = None
137 | custom_file_name = err
138 | except:
139 | # this might occur in case of a BAD API URL,
140 | # who knows? :\
141 | pass
142 |
143 | return url, custom_file_name, youtube_dl_username, youtube_dl_password
144 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/fix_tcerrocni_images.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import aiohttp
19 | import os
20 | from PIL import Image
21 |
22 |
23 | async def proc_ess_image_aqon(image_url: str, output_dir: str) -> str:
24 | async with aiohttp.ClientSession() as session:
25 | noqa_read = await session.get(image_url)
26 | image_content = await noqa_read.read()
27 | thumb_img_path = os.path.join(
28 | output_dir,
29 | "thumb_image.jpg"
30 | )
31 | with open(thumb_img_path, "wb") as f_d:
32 | f_d.write(image_content)
33 | # image might be downloaded in the previous step
34 | # https://stackoverflow.com/a/21669827/4723940
35 | Image.open(thumb_img_path).convert(
36 | "RGB"
37 | ).save(thumb_img_path, "JPEG")
38 | # ref: https://t.me/PyrogramChat/44663
39 | # return the downloaded image path
40 | return thumb_img_path
41 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/help_Nekmo_ffmpeg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 |
28 | import asyncio
29 | import os
30 | import time
31 | from publicleechgroup.helper_funcs.copy_similar_file import copy_file
32 |
33 |
34 | async def take_screen_shot(video_file, output_directory, ttl):
35 | # https://stackoverflow.com/a/13891070/4723940
36 | out_put_file_name = os.path.join(
37 | output_directory,
38 | str(time.time()) + ".jpg"
39 | )
40 | if video_file.upper().endswith(("MKV", "MP4", "WEBM")):
41 | file_genertor_command = [
42 | "ffmpeg",
43 | "-ss",
44 | str(ttl),
45 | "-i",
46 | video_file,
47 | "-vframes",
48 | "1",
49 | out_put_file_name
50 | ]
51 | # width = "90"
52 | process = await asyncio.create_subprocess_exec(
53 | *file_genertor_command,
54 | # stdout must a pipe to be accessible as process.stdout
55 | stdout=asyncio.subprocess.PIPE,
56 | stderr=asyncio.subprocess.PIPE,
57 | )
58 | # Wait for the subprocess to finish
59 | stdout, stderr = await process.communicate()
60 | e_response = stderr.decode().strip()
61 | t_response = stdout.decode().strip()
62 | #
63 | if os.path.lexists(out_put_file_name):
64 | return out_put_file_name
65 | else:
66 | return None
67 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/icntaosrtsba.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # PublicLeech
4 | # Copyright (C) 2020 The Authors
5 |
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 |
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 |
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 | import os
20 | import time
21 | from pyrogram.types import (
22 | Message
23 | )
24 | from publicleechgroup import (
25 | LOGGER,
26 | DOWNLOAD_LOCATION
27 | )
28 | LOGGER = LOGGER(__name__)
29 | from publicleechgroup.helper_funcs.download_aria_p_n import (
30 | call_apropriate_function,
31 | aria_start,
32 | fake_etairporpa_call
33 | )
34 | from publicleechgroup.helper_funcs.extract_link_from_message import extract_link
35 | from publicleechgroup.helper_funcs.youtube_dl_extractor import extract_youtube_dl_formats
36 |
37 |
38 | async def leech_btn_k(message: Message, cb_data: str):
39 | # get link from the incoming message
40 | dl_url, cf_name, _, _ = await extract_link(
41 | message.reply_to_message, "LEECH"
42 | )
43 | LOGGER.info(dl_url)
44 | LOGGER.info(cf_name)
45 | current_user_id = message.reply_to_message.from_user.id
46 | # create an unique directory
47 | new_download_location = os.path.join(
48 | DOWNLOAD_LOCATION,
49 | str(current_user_id),
50 | str(message.reply_to_message.message_id)
51 | )
52 | # create download directory, if not exist
53 | if not os.path.isdir(new_download_location):
54 | os.makedirs(new_download_location)
55 | if dl_url is not None:
56 | await message.edit_text("extracting links")
57 | # start the aria2c daemon
58 | aria_i_p = await aria_start()
59 | LOGGER.info(aria_i_p)
60 | if "_" in cb_data:
61 | await message.edit_text("trying to download")
62 | # try to download the "link"
63 | sagtus, err_message = await fake_etairporpa_call(
64 | aria_i_p,
65 | dl_url,
66 | new_download_location,
67 | message,
68 | int(cb_data.split("_")[2])
69 | # maybe IndexError / ValueError might occur,
70 | # we don't know, yet!!
71 | )
72 | if not sagtus:
73 | # if FAILED, display the error message
74 | await message.edit_text(err_message)
75 | else:
76 | is_zip = False
77 | if "a" in cb_data:
78 | is_zip = True
79 | await message.edit_text("trying to download")
80 | # try to download the "link"
81 | sagtus, err_message = await call_apropriate_function(
82 | aria_i_p,
83 | dl_url,
84 | new_download_location,
85 | message,
86 | is_zip
87 | )
88 | if not sagtus:
89 | # if FAILED, display the error message
90 | await message.edit_text(err_message)
91 |
92 |
93 | async def ytdl_btn_k(message: Message):
94 | i_m_sefg = await message.edit_text("processing")
95 | # LOGGER.info(message)
96 | # extract link from message
97 | dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
98 | message.reply_to_message, "YTDL"
99 | )
100 | LOGGER.info(dl_url)
101 | LOGGER.info(cf_name)
102 | if dl_url is not None:
103 | current_user_id = message.reply_to_message.from_user.id
104 | # create an unique directory
105 | user_working_dir = os.path.join(
106 | DOWNLOAD_LOCATION,
107 | str(current_user_id),
108 | str(message.reply_to_message.message_id)
109 | )
110 | # create download directory, if not exist
111 | if not os.path.isdir(user_working_dir):
112 | os.makedirs(user_working_dir)
113 | await i_m_sefg.edit_text("extracting links")
114 | # list the formats, and display in button markup formats
115 | thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
116 | dl_url,
117 | # cf_name,
118 | yt_dl_user_name,
119 | yt_dl_pass_word,
120 | user_working_dir
121 | )
122 | await i_m_sefg.edit_text(
123 | text=text_message,
124 | reply_markup=reply_markup
125 | )
126 | else:
127 | await i_m_sefg.delete()
128 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/magnetic_link_regex.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 | import os
28 | import re
29 |
30 |
31 | MAGNETIC_LINK_REGEX = r"magnet\:\?xt\=urn\:btih\:([A-F\d]+)"
32 |
33 |
34 | def extract_info_hash_from_ml(magnetic_link):
35 | ml_re_match = re.search(MAGNETIC_LINK_REGEX, magnetic_link)
36 | if ml_re_match is not None:
37 | return ml_re_match.group(1)
38 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/r_clone.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # PublicLeech
4 | # Copyright (C) 2020 The Authors
5 |
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU Affero General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 |
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU Affero General Public License for more details.
15 |
16 | # You should have received a copy of the GNU Affero General Public License
17 | # along with this program. If not, see .
18 |
19 | import os
20 | import re
21 | from typing import Union
22 |
23 | # the logging things
24 | import logging
25 | logging.basicConfig(
26 | level=logging.DEBUG,
27 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
28 | )
29 | LOGGER = logging.getLogger(__name__)
30 |
31 | from pyrogram import (
32 | Client
33 | )
34 | from pyrogram.errors import (
35 | ChannelInvalid
36 | )
37 | from publicleechgroup.helper_funcs.run_shell_command import run_command
38 |
39 |
40 | async def copy_via_rclone(
41 | src: str,
42 | remote_name: str,
43 | remote_dir: str,
44 | conf_file: str
45 | ):
46 | command_to_exec = [
47 | "rclone",
48 | "copy",
49 | src,
50 | "" + remote_name + ":" + remote_dir + "",
51 | "--config=" + conf_file + ""
52 | ]
53 | LOGGER.info(command_to_exec)
54 | t_response, e_response = await run_command(command_to_exec)
55 | # Wait for the subprocess to finish
56 | LOGGER.info(e_response)
57 | LOGGER.info(t_response)
58 | # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
59 | remote_file_id = await r_clone_extract_link_s(
60 | re.escape(src),
61 | remote_name,
62 | remote_dir,
63 | conf_file
64 | )
65 | LOGGER.info(remote_file_id)
66 | return remote_file_id
67 |
68 |
69 | async def get_r_clone_config(message_link: str, py_client: Client) -> str:
70 | chat_id, message_id = extract_c_m_ids(message_link)
71 | try:
72 | conf_mesg = await py_client.get_messages(
73 | chat_id=chat_id,
74 | message_ids=message_id
75 | )
76 | except ChannelInvalid:
77 | LOGGER.info(
78 | "invalid RClone config URL. this is NOT an ERROR"
79 | )
80 | return None
81 | down_conf_n = await py_client.download_media(
82 | message=conf_mesg
83 | )
84 | return down_conf_n
85 |
86 |
87 | def extract_c_m_ids(message_link: str) -> (Union[str, int], int):
88 | p_m_link = message_link.split("/")
89 | chat_id, message_id = None, None
90 | if len(p_m_link) == 6:
91 | # private link
92 | if p_m_link[3] == "c":
93 | # the Telegram private link
94 | chat_id, message_id = int("-100" + p_m_link[4]), int(p_m_link[5])
95 | elif p_m_link[3] == "PublicLeech":
96 | # bleck magick
97 | chat_id, message_id = int(p_m_link[4]), int(p_m_link[5])
98 | elif len(p_m_link) == 5:
99 | # public link
100 | chat_id, message_id = str("@" + p_m_link[3]), int(p_m_link[4])
101 | return chat_id, message_id
102 |
103 |
104 | async def r_clone_extract_link_s(
105 | src_file_name: str,
106 | remote_name: str,
107 | remote_dir: str,
108 | conf_file: str
109 | ):
110 | tmp_file_name = "lsf_filter.txt"
111 | with open(tmp_file_name, "w+", encoding="utf-8") as f_d:
112 | f_d.write(f"+ {src_file_name}\n- *")
113 | command_to_exec = [
114 | "rclone",
115 | "lsf",
116 | "-F",
117 | "-i",
118 | f"--filter-from={tmp_file_name}",
119 | "--files-only",
120 | "" + remote_name + ":" + remote_dir + "",
121 | "--config=" + conf_file + ""
122 | ]
123 | LOGGER.info(command_to_exec)
124 | t_response, e_response = await run_command(command_to_exec)
125 | # Wait for the subprocess to finish
126 | LOGGER.info(e_response)
127 | LOGGER.info(t_response)
128 | os.remove(tmp_file_name)
129 | return t_response
130 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/real_debrid_extractor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 | import os
28 |
29 | from publicleechgroup import (
30 | REAL_DEBRID_KEY
31 | )
32 |
33 |
34 | import aiohttp
35 | import asyncio
36 |
37 |
38 | BASE_URL = "https://api.real-debrid.com/rest/1.0"
39 |
40 |
41 | async def fetch(session, url, data):
42 | async with session.post(url, data=data) as response:
43 | return await response.json()
44 |
45 |
46 | async def extract_it(restricted_link, custom_file_name):
47 | async with aiohttp.ClientSession() as session:
48 | url_to_send = BASE_URL + "/unrestrict/link?auth_token=" + REAL_DEBRID_KEY
49 | to_send_data = {
50 | "link": restricted_link
51 | }
52 | html = await fetch(session, url_to_send, to_send_data)
53 | LOGGER.info(html)
54 | downloadable_url = html.get("download")
55 | original_file_name = custom_file_name
56 | if original_file_name is None:
57 | original_file_name = html.get("filename")
58 | return downloadable_url, original_file_name
59 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/run_shell_command.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import asyncio
19 | from typing import List
20 |
21 |
22 | async def run_command(shell_command: List) -> (str, str):
23 | """ executes a shell_command,
24 | and returns the stdout and stderr"""
25 | process = await asyncio.create_subprocess_exec(
26 | *shell_command,
27 | # stdout must a pipe to be accessible as process.stdout
28 | stdout=asyncio.subprocess.PIPE,
29 | stderr=asyncio.subprocess.PIPE,
30 | )
31 | # Wait for the subprocess to finish
32 | stdout, stderr = await process.communicate()
33 | try:
34 | e_response = stderr.decode().strip()
35 | except:
36 | e_response = None
37 | try:
38 | t_response = stdout.decode().strip()
39 | except:
40 | t_response = None
41 | return t_response, e_response
42 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/split_large_files.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 |
28 | import asyncio
29 | import os
30 | import time
31 | from hachoir.metadata import extractMetadata
32 | from hachoir.parser import createParser
33 |
34 | from publicleechgroup import (
35 | MAX_TG_SPLIT_FILE_SIZE,
36 | SP_LIT_ALGO_RITH_M
37 | )
38 |
39 |
40 | async def split_large_files(input_file):
41 | working_directory = os.path.dirname(os.path.abspath(input_file))
42 | new_working_directory = os.path.join(
43 | working_directory,
44 | str(time.time())
45 | )
46 | # create download directory, if not exist
47 | if not os.path.isdir(new_working_directory):
48 | os.makedirs(new_working_directory)
49 | # if input_file.upper().endswith(("MKV", "MP4", "WEBM", "MP3", "M4A", "FLAC", "WAV")):
50 | """The below logic is DERPed, so removing temporarily
51 | """
52 | if (
53 | SP_LIT_ALGO_RITH_M.lower() != "rar" and
54 | input_file.upper().endswith(("MKV", "MP4", "WEBM"))
55 | ):
56 | # handle video / audio files here
57 | metadata = extractMetadata(createParser(input_file))
58 | total_duration = 0
59 | if metadata.has("duration"):
60 | total_duration = metadata.get('duration').seconds
61 | # proprietary logic to get the seconds to trim (at)
62 | LOGGER.info(total_duration)
63 | total_file_size = os.path.getsize(input_file)
64 | LOGGER.info(total_file_size)
65 | minimum_duration = (
66 | total_duration / total_file_size
67 | ) * (
68 | MAX_TG_SPLIT_FILE_SIZE
69 | )
70 | # casting to int cuz float Time Stamp can cause errors
71 | minimum_duration = int(minimum_duration)
72 |
73 | LOGGER.info(minimum_duration)
74 | # END: proprietary
75 | start_time = 0
76 | end_time = minimum_duration
77 | base_name = os.path.basename(input_file)
78 | input_extension = base_name.split(".")[-1]
79 | LOGGER.info(input_extension)
80 |
81 | i = 0
82 | flag = False
83 |
84 | while end_time <= total_duration:
85 | LOGGER.info(i)
86 | # file name generate
87 | parted_file_name = "{}_PART_{}.{}".format(str(base_name),str(i).zfill(5),str(input_extension))
88 |
89 | output_file = os.path.join(new_working_directory, parted_file_name)
90 | LOGGER.info(output_file)
91 | LOGGER.info(await cult_small_video(
92 | input_file,
93 | output_file,
94 | str(start_time),
95 | str(end_time)
96 | ))
97 | LOGGER.info(
98 | f"Start time {start_time}, End time {end_time}, Itr {i}"
99 | )
100 |
101 | # adding offset of 3 seconds to ensure smooth playback
102 | start_time = end_time - 3
103 | end_time = end_time + minimum_duration
104 | i = i + 1
105 |
106 | if (end_time > total_duration) and not flag:
107 | end_time = total_duration
108 | flag = True
109 | elif flag:
110 | break
111 |
112 | elif SP_LIT_ALGO_RITH_M.lower() == "hjs":
113 | # handle normal files here
114 | o_d_t = os.path.join(
115 | new_working_directory,
116 | os.path.basename(input_file)
117 | )
118 | o_d_t = o_d_t + "."
119 | file_genertor_command = [
120 | "split",
121 | "--numeric-suffixes=1",
122 | "--suffix-length=5",
123 | f"--bytes={MAX_TG_SPLIT_FILE_SIZE}",
124 | input_file,
125 | o_d_t
126 | ]
127 | await run_comman_d(file_genertor_command)
128 |
129 | elif SP_LIT_ALGO_RITH_M.lower() == "rar":
130 | o_d_t = os.path.join(
131 | new_working_directory,
132 | os.path.basename(input_file),
133 | )
134 | LOGGER.info(o_d_t)
135 | file_genertor_command = [
136 | "rar",
137 | "a",
138 | f"-v{MAX_TG_SPLIT_FILE_SIZE}b",
139 | "-m0",
140 | o_d_t,
141 | input_file
142 | ]
143 | await run_comman_d(file_genertor_command)
144 |
145 | return new_working_directory
146 |
147 |
148 | async def cult_small_video(video_file, out_put_file_name, start_time, end_time):
149 | file_genertor_command = [
150 | "ffmpeg",
151 | "-hide_banner",
152 | "-i",
153 | video_file,
154 | "-ss",
155 | start_time,
156 | "-to",
157 | end_time,
158 | "-async",
159 | "1",
160 | "-strict",
161 | "-2",
162 | "-c",
163 | "copy",
164 | out_put_file_name
165 | ]
166 | process = await asyncio.create_subprocess_exec(
167 | *file_genertor_command,
168 | # stdout must a pipe to be accessible as process.stdout
169 | stdout=asyncio.subprocess.PIPE,
170 | stderr=asyncio.subprocess.PIPE,
171 | )
172 | # Wait for the subprocess to finish
173 | stdout, stderr = await process.communicate()
174 | e_response = stderr.decode().strip()
175 | t_response = stdout.decode().strip()
176 | LOGGER.info(t_response)
177 | return out_put_file_name
178 |
179 |
180 | async def run_comman_d(command_list):
181 | process = await asyncio.create_subprocess_exec(
182 | *command_list,
183 | # stdout must a pipe to be accessible as process.stdout
184 | stdout=asyncio.subprocess.PIPE,
185 | stderr=asyncio.subprocess.PIPE,
186 | )
187 | # Wait for the subprocess to finish
188 | stdout, stderr = await process.communicate()
189 | e_response = stderr.decode().strip()
190 | t_response = stdout.decode().strip()
191 | return t_response, e_response
192 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/upload_to_tg.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 | import asyncio
28 | import os
29 | import time
30 | from hachoir.metadata import extractMetadata
31 | from hachoir.parser import createParser
32 | from PIL import Image
33 | from pyrogram.types import (
34 | InputMediaDocument,
35 | InputMediaVideo,
36 | InputMediaAudio
37 | )
38 | from publicleechgroup.helper_funcs.display_progress import (
39 | progress_for_pyrogram,
40 | humanbytes
41 | )
42 | from publicleechgroup.helper_funcs.help_Nekmo_ffmpeg import take_screen_shot
43 | from publicleechgroup.helper_funcs.split_large_files import split_large_files
44 | from publicleechgroup.helper_funcs.copy_similar_file import copy_file
45 | from publicleechgroup import (
46 | TG_MAX_FILE_SIZE,
47 | EDIT_SLEEP_TIME_OUT,
48 | DOWNLOAD_LOCATION
49 | )
50 |
51 | async def upload_to_tg(
52 | message,
53 | local_file_name,
54 | from_user,
55 | dict_contatining_uploaded_files,
56 | edit_media=False,
57 | custom_caption=None,
58 | force_doc=False,
59 | cfn=None
60 | ):
61 | LOGGER.info(local_file_name)
62 | base_file_name = os.path.basename(local_file_name)
63 | caption_str = custom_caption
64 | if not (caption_str or edit_media):
65 | LOGGER.info("fall-back to default file_name")
66 | caption_str = ""
67 | caption_str += base_file_name
68 | caption_str += "
"
69 | # caption_str += "\n\n"
70 | # caption_str += ""
73 | # caption_str += "Here is the file to the link you sent"
74 | # caption_str += ""
75 | if os.path.isdir(local_file_name):
76 | directory_contents = os.listdir(local_file_name)
77 | directory_contents.sort()
78 | # number_of_files = len(directory_contents)
79 | LOGGER.info(directory_contents)
80 | new_m_esg = message
81 | if not message.photo:
82 | new_m_esg = await message.reply_text(
83 | "Found {} files".format(len(directory_contents)),
84 | quote=True
85 | # reply_to_message_id=message.message_id
86 | )
87 | for single_file in directory_contents:
88 | # recursion: will this FAIL somewhere?
89 | await upload_to_tg(
90 | new_m_esg,
91 | os.path.join(local_file_name, single_file),
92 | from_user,
93 | dict_contatining_uploaded_files,
94 | edit_media,
95 | caption_str,
96 | force_doc=force_doc,
97 | cfn=cfn
98 | )
99 | else:
100 | if os.path.getsize(local_file_name) > TG_MAX_FILE_SIZE:
101 | LOGGER.info("TODO")
102 | d_f_s = humanbytes(os.path.getsize(local_file_name))
103 | i_m_s_g = await message.reply_text(
104 | "Telegram does not support uploading this file.\n"
105 | f"Detected File Size: {d_f_s} 😡\n"
106 | "\n🤖 trying to split the files 🌝🌝🌚"
107 | )
108 | splitted_dir = await split_large_files(local_file_name)
109 | totlaa_sleif = os.listdir(splitted_dir)
110 | totlaa_sleif.sort()
111 | number_of_files = len(totlaa_sleif)
112 | LOGGER.info(totlaa_sleif)
113 | ba_se_file_name = os.path.basename(local_file_name)
114 | await i_m_s_g.edit_text(
115 | f"Detected File Size: {d_f_s} 😡\n"
116 | f"{ba_se_file_name}
splitted into {number_of_files} files.\n"
117 | "trying to upload to Telegram, now ..."
118 | )
119 | for le_file in totlaa_sleif:
120 | # recursion: will this FAIL somewhere?
121 | await upload_to_tg(
122 | message,
123 | os.path.join(splitted_dir, le_file),
124 | from_user,
125 | dict_contatining_uploaded_files,
126 | force_doc=force_doc,
127 | cfn=cfn
128 | )
129 | else:
130 | sent_message = await upload_single_file(
131 | message,
132 | local_file_name,
133 | caption_str,
134 | from_user,
135 | edit_media,
136 | force_doc,
137 | cfn
138 | )
139 | if sent_message is not None:
140 | dict_contatining_uploaded_files[os.path.basename(local_file_name)] = sent_message.message_id
141 | # await message.delete()
142 | return dict_contatining_uploaded_files
143 |
144 |
145 | async def upload_single_file(
146 | message,
147 | local_file_name,
148 | caption_str,
149 | from_user,
150 | edit_media,
151 | force_doc=False,
152 | cfn=None
153 | ):
154 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
155 | sent_message = None
156 | if cfn:
157 | os.rename(local_file_name, cfn)
158 | local_file_name = cfn
159 | start_time = time.time()
160 | #
161 | thumbnail_location = os.path.join(
162 | DOWNLOAD_LOCATION,
163 | "thumbnails",
164 | str(from_user) + ".jpg"
165 | )
166 | LOGGER.info(thumbnail_location)
167 | #
168 | message_for_progress_display = message
169 | if not edit_media:
170 | message_for_progress_display = await message.reply_text(
171 | "starting upload of {}".format(os.path.basename(local_file_name))
172 | )
173 |
174 | if local_file_name.upper().endswith((
175 | "M4V", "MP4", "MOV", "FLV", "WMV", "3GP", "MPEG", "WEBM", "MKV"
176 | )) and not force_doc:
177 | metadata = extractMetadata(createParser(local_file_name))
178 | duration = 0
179 | if metadata.has("duration"):
180 | duration = metadata.get('duration').seconds
181 | #
182 | width = 0
183 | height = 0
184 | thumb_image_path = None
185 | if os.path.exists(thumbnail_location):
186 | thumb_image_path = await copy_file(
187 | thumbnail_location,
188 | os.path.dirname(os.path.abspath(local_file_name))
189 | )
190 | else:
191 | thumb_image_path = await take_screen_shot(
192 | local_file_name,
193 | os.path.dirname(os.path.abspath(local_file_name)),
194 | (duration / 2)
195 | )
196 | # get the correct width, height, and duration for videos greater than 10MB
197 | if os.path.exists(thumb_image_path):
198 | metadata = extractMetadata(createParser(thumb_image_path))
199 | if metadata.has("width"):
200 | width = metadata.get("width")
201 | if metadata.has("height"):
202 | height = metadata.get("height")
203 | # resize image
204 | # ref: https://t.me/PyrogramChat/44663
205 | # https://stackoverflow.com/a/21669827/4723940
206 | Image.open(thumb_image_path).convert(
207 | "RGB"
208 | ).save(thumb_image_path)
209 | img = Image.open(thumb_image_path)
210 | # https://stackoverflow.com/a/37631799/4723940
211 | img.resize((320, height))
212 | img.save(thumb_image_path, "JPEG")
213 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
214 | #
215 | thumb = None
216 | if thumb_image_path is not None and os.path.isfile(thumb_image_path):
217 | thumb = thumb_image_path
218 | # send video
219 | if edit_media and message.photo:
220 | sent_message = await message.edit_media(
221 | media=InputMediaVideo(
222 | media=local_file_name,
223 | thumb=thumb,
224 | caption=caption_str,
225 | parse_mode="html",
226 | width=width,
227 | height=height,
228 | duration=duration,
229 | supports_streaming=True
230 | )
231 | # quote=True,
232 | )
233 | else:
234 | sent_message = await message.reply_video(
235 | video=local_file_name,
236 | # quote=True,
237 | caption=caption_str,
238 | parse_mode="html",
239 | duration=duration,
240 | width=width,
241 | height=height,
242 | thumb=thumb,
243 | supports_streaming=True,
244 | disable_notification=True,
245 | # reply_to_message_id=message.reply_to_message.message_id,
246 | progress=progress_for_pyrogram,
247 | progress_args=(
248 | "trying to upload",
249 | message_for_progress_display,
250 | start_time
251 | )
252 | )
253 | if thumb is not None:
254 | os.remove(thumb)
255 |
256 | elif local_file_name.upper().endswith((
257 | "MP3", "M4A", "M4B", "FLAC", "WAV", "AIF", "OGG", "AAC", "DTS"
258 | )) and not force_doc:
259 | metadata = extractMetadata(createParser(local_file_name))
260 | duration = 0
261 | title = ""
262 | artist = ""
263 | if metadata.has("duration"):
264 | duration = metadata.get('duration').seconds
265 | if metadata.has("title"):
266 | title = metadata.get("title")
267 | if metadata.has("artist"):
268 | artist = metadata.get("artist")
269 | thumb_image_path = None
270 | if os.path.isfile(thumbnail_location):
271 | thumb_image_path = await copy_file(
272 | thumbnail_location,
273 | os.path.dirname(os.path.abspath(local_file_name))
274 | )
275 | thumb = None
276 | if thumb_image_path is not None and os.path.isfile(thumb_image_path):
277 | thumb = thumb_image_path
278 | # send audio
279 | if edit_media and message.photo:
280 | sent_message = await message.edit_media(
281 | media=InputMediaAudio(
282 | media=local_file_name,
283 | thumb=thumb,
284 | caption=caption_str,
285 | parse_mode="html",
286 | duration=duration,
287 | performer=artist,
288 | title=title
289 | )
290 | # quote=True,
291 | )
292 | else:
293 | sent_message = await message.reply_audio(
294 | audio=local_file_name,
295 | # quote=True,
296 | caption=caption_str,
297 | parse_mode="html",
298 | duration=duration,
299 | performer=artist,
300 | title=title,
301 | thumb=thumb,
302 | disable_notification=True,
303 | # reply_to_message_id=message.reply_to_message.message_id,
304 | progress=progress_for_pyrogram,
305 | progress_args=(
306 | "trying to upload",
307 | message_for_progress_display,
308 | start_time
309 | )
310 | )
311 | if thumb is not None:
312 | os.remove(thumb)
313 |
314 | else:
315 | thumb_image_path = None
316 | if os.path.isfile(thumbnail_location):
317 | thumb_image_path = await copy_file(
318 | thumbnail_location,
319 | os.path.dirname(os.path.abspath(local_file_name))
320 | )
321 | # if a file, don't upload "thumb"
322 | # this "diff" is a major derp -_- 😔😭😭
323 | thumb = None
324 | if thumb_image_path is not None and os.path.isfile(thumb_image_path):
325 | thumb = thumb_image_path
326 | #
327 | # send document
328 | if edit_media and message.photo:
329 | sent_message = await message.edit_media(
330 | media=InputMediaDocument(
331 | media=local_file_name,
332 | thumb=thumb,
333 | caption=caption_str,
334 | parse_mode="html"
335 | )
336 | # quote=True,
337 | )
338 | else:
339 | sent_message = await message.reply_document(
340 | document=local_file_name,
341 | # quote=True,
342 | thumb=thumb,
343 | caption=caption_str,
344 | parse_mode="html",
345 | disable_notification=True,
346 | # reply_to_message_id=message.reply_to_message.message_id,
347 | progress=progress_for_pyrogram,
348 | progress_args=(
349 | "trying to upload",
350 | message_for_progress_display,
351 | start_time
352 | )
353 | )
354 | if thumb is not None:
355 | os.remove(thumb)
356 |
357 | if message.message_id != message_for_progress_display.message_id:
358 | await message_for_progress_display.delete()
359 |
360 | os.remove(local_file_name)
361 | return sent_message
362 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/youtube_dl_button.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23 | )
24 | LOGGER = logging.getLogger(__name__)
25 |
26 | import asyncio
27 | import json
28 | import math
29 | import os
30 | import shutil
31 | import time
32 | from datetime import datetime
33 |
34 | from publicleechgroup import (
35 | DOWNLOAD_LOCATION,
36 | AUTH_CHANNEL,
37 | SHOULD_USE_BUTTONS
38 | )
39 | from publicleechgroup.helper_funcs.upload_to_tg import upload_to_tg
40 |
41 |
42 | async def youtube_dl_call_back(bot, update):
43 | LOGGER.info(update)
44 | cb_data = update.data
45 | # youtube_dl extractors
46 | tg_send_type, youtube_dl_format, youtube_dl_ext, so_type = cb_data.split("|")
47 | #
48 | current_user_id = update.message.reply_to_message.from_user.id
49 | current_message_id = update.message.reply_to_message
50 | current_message_id = current_message_id.message_id
51 | current_touched_user_id = update.from_user.id
52 |
53 | user_working_dir = os.path.join(
54 | DOWNLOAD_LOCATION,
55 | str(current_user_id),
56 | str(update.message.reply_to_message.message_id)
57 | )
58 | # create download directory, if not exist
59 | if not os.path.isdir(user_working_dir):
60 | await bot.delete_messages(
61 | chat_id=update.message.chat.id,
62 | message_ids=[
63 | update.message.message_id,
64 | update.message.reply_to_message.message_id,
65 | ],
66 | revoke=True
67 | )
68 | return
69 | save_ytdl_json_path = user_working_dir + \
70 | "/" + str("ytdleech") + ".json"
71 | try:
72 | with open(save_ytdl_json_path, "r", encoding="utf8") as f:
73 | response_json = json.load(f)
74 | os.remove(save_ytdl_json_path)
75 | except (FileNotFoundError) as e:
76 | await bot.delete_messages(
77 | chat_id=update.message.chat.id,
78 | message_ids=[
79 | update.message.message_id,
80 | update.message.reply_to_message.message_id,
81 | ],
82 | revoke=True
83 | )
84 | return False
85 | #
86 | response_json = response_json[0]
87 | # TODO: temporary limitations
88 | # LOGGER.info(response_json)
89 | #
90 | youtube_dl_url = response_json.get("webpage_url")
91 | LOGGER.info(youtube_dl_url)
92 | #
93 | custom_file_name = "%(title)s.%(ext)s"
94 | # https://superuser.com/a/994060
95 | LOGGER.info(custom_file_name)
96 | #
97 | await update.message.edit_caption(
98 | caption="trying to download"
99 | )
100 | description = "@PublicLeech"
101 | if "fulltitle" in response_json:
102 | description = response_json["fulltitle"][0:1021]
103 | # escape Markdown and special characters
104 | if "description" in response_json:
105 | description = response_json["description"][0:1021]
106 | LOGGER.info(description)
107 | #
108 | tmp_directory_for_each_user = user_working_dir
109 | download_directory = tmp_directory_for_each_user
110 | download_directory = os.path.join(
111 | tmp_directory_for_each_user,
112 | custom_file_name
113 | )
114 | command_to_exec = []
115 | if tg_send_type == "audio":
116 | command_to_exec = [
117 | "youtube-dl",
118 | "-c",
119 | "--prefer-ffmpeg",
120 | "--extract-audio",
121 | "--audio-format", youtube_dl_ext,
122 | "--audio-quality", youtube_dl_format,
123 | youtube_dl_url,
124 | "-o", download_directory,
125 | # "--external-downloader", "aria2c"
126 | ]
127 | else:
128 | minus_f_format = youtube_dl_format
129 |
130 | if "youtu" in youtube_dl_url:
131 | for for_mat in response_json["formats"]:
132 | format_id = for_mat.get("format_id")
133 | if format_id == youtube_dl_format:
134 | acodec = for_mat.get("acodec")
135 | vcodec = for_mat.get("vcodec")
136 | if acodec == "none" or vcodec == "none":
137 | minus_f_format = youtube_dl_format + "+bestaudio"
138 | break
139 | elif so_type:
140 | minus_f_format = youtube_dl_format + "+bestaudio"
141 |
142 | command_to_exec = [
143 | "youtube-dl",
144 | "-c",
145 | "--embed-subs",
146 | "-f", minus_f_format,
147 | "--hls-prefer-ffmpeg", youtube_dl_url,
148 | "-o", download_directory,
149 | # "--external-downloader", "aria2c"
150 | ]
151 | #
152 | command_to_exec.append("--no-warnings")
153 | # command_to_exec.append("--quiet")
154 | command_to_exec.append("--restrict-filenames")
155 | #
156 | if "hotstar" in youtube_dl_url:
157 | command_to_exec.append("--geo-bypass-country")
158 | command_to_exec.append("IN")
159 | LOGGER.info(command_to_exec)
160 | start = datetime.now()
161 | process = await asyncio.create_subprocess_exec(
162 | *command_to_exec,
163 | # stdout must a pipe to be accessible as process.stdout
164 | stdout=asyncio.subprocess.PIPE,
165 | stderr=asyncio.subprocess.PIPE,
166 | )
167 | # Wait for the subprocess to finish
168 | stdout, stderr = await process.communicate()
169 | e_response = stderr.decode().strip()
170 | t_response = stdout.decode().strip()
171 | # LOGGER.info(e_response)
172 | # LOGGER.info(t_response)
173 | ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output."
174 | if e_response and ad_string_to_replace in e_response:
175 | error_message = e_response.replace(ad_string_to_replace, "")
176 | await update.message.edit_caption(
177 | caption=error_message
178 | )
179 | return False, None
180 | if t_response:
181 | # LOGGER.info(t_response)
182 | # os.remove(save_ytdl_json_path)
183 | end_one = datetime.now()
184 | time_taken_for_download = (end_one -start).seconds
185 | dir_contents = len(os.listdir(tmp_directory_for_each_user))
186 | # dir_contents.sort()
187 | await update.message.edit_caption(
188 | caption=f"found {dir_contents} files"
189 | )
190 | user_id = update.from_user.id
191 | #
192 | final_response = await upload_to_tg(
193 | update.message,
194 | tmp_directory_for_each_user,
195 | user_id,
196 | {},
197 | True,
198 | description
199 | )
200 | LOGGER.info(final_response)
201 | #
202 | try:
203 | shutil.rmtree(tmp_directory_for_each_user)
204 | except:
205 | pass
206 | #
207 |
--------------------------------------------------------------------------------
/publicleechgroup/helper_funcs/youtube_dl_extractor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import asyncio
19 | from publicleechgroup.helper_funcs.display_progress import humanbytes
20 | import json
21 | import os
22 | from pyrogram.types import (
23 | InlineKeyboardButton,
24 | InlineKeyboardMarkup
25 | )
26 | from publicleechgroup import (
27 | LOGGER,
28 | DEF_THUMB_NAIL_VID_S
29 | )
30 |
31 |
32 | async def extract_youtube_dl_formats(url, yt_dl_user_name, yt_dl_pass_word, user_working_dir):
33 | command_to_exec = [
34 | "youtube-dl",
35 | "--no-warnings",
36 | "--youtube-skip-dash-manifest",
37 | "-j",
38 | url
39 | ]
40 | if "hotstar" in url:
41 | command_to_exec.append("--geo-bypass-country")
42 | command_to_exec.append("IN")
43 | #
44 | if yt_dl_user_name is not None:
45 | command_to_exec.append("--username")
46 | command_to_exec.append(yt_dl_user_name)
47 | if yt_dl_pass_word is not None:
48 | command_to_exec.append("--password")
49 | command_to_exec.append(yt_dl_pass_word)
50 |
51 | LOGGER.info(command_to_exec)
52 | process = await asyncio.create_subprocess_exec(
53 | *command_to_exec,
54 | # stdout must a pipe to be accessible as process.stdout
55 | stdout=asyncio.subprocess.PIPE,
56 | stderr=asyncio.subprocess.PIPE,
57 | )
58 | # Wait for the subprocess to finish
59 | stdout, stderr = await process.communicate()
60 | e_response = stderr.decode().strip()
61 | # LOGGER.info(e_response)
62 | t_response = stdout.decode().strip()
63 | # LOGGER.info(t_response)
64 | # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
65 | if e_response:
66 | # logger.warn("Status : FAIL", exc.returncode, exc.output)
67 | error_message = e_response.replace(
68 | "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.", ""
69 | )
70 | return None, error_message, None
71 | if t_response:
72 | # logger.info(t_response)
73 | x_reponse = t_response
74 | response_json = []
75 | if "\n" in x_reponse:
76 | for yu_r in x_reponse.split("\n"):
77 | response_json.append(json.loads(yu_r))
78 | else:
79 | response_json.append(json.loads(x_reponse))
80 | # response_json = json.loads(x_reponse)
81 | save_ytdl_json_path = user_working_dir + \
82 | "/" + str("ytdleech") + ".json"
83 | with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
84 | json.dump(response_json, outfile, ensure_ascii=False)
85 | # logger.info(response_json)
86 | inline_keyboard = []
87 | #
88 | thumb_image = DEF_THUMB_NAIL_VID_S
89 | #
90 | for current_r_json in response_json:
91 | # LOGGER.info(current_r_json)
92 | #
93 | thumb_image = current_r_json.get("thumbnails", None)
94 | # LOGGER.info(thumb_image)
95 | if thumb_image is not None:
96 | # YouTube acts weirdly,
97 | # and not in the same way as Telegram
98 | thumb_image = thumb_image[-1]["url"]
99 | if thumb_image is None:
100 | thumb_image = DEF_THUMB_NAIL_VID_S
101 |
102 | duration = None
103 | if "duration" in current_r_json:
104 | duration = current_r_json["duration"]
105 | if "formats" in current_r_json:
106 | for formats in current_r_json["formats"]:
107 | format_id = formats.get("format_id")
108 | format_string = formats.get("format_note")
109 | if format_string is None:
110 | format_string = formats.get("format")
111 | # don't display formats, without audio
112 | # https://t.me/c/1434259219/269937
113 | if "DASH" in format_string.upper():
114 | continue
115 | format_ext = formats.get("ext")
116 | approx_file_size = ""
117 | if "filesize" in formats:
118 | approx_file_size = humanbytes(formats["filesize"])
119 | n_ue_sc = bool("video only" in format_string)
120 | scneu = "DL" if not n_ue_sc else "XM"
121 | dipslay_str_uon = " " + format_string + " (" + format_ext.upper() + ") " + approx_file_size + " "
122 | cb_string_video = "{}|{}|{}|{}".format(
123 | "video", format_id, format_ext, scneu
124 | )
125 | ikeyboard = []
126 | if "drive.google.com" in url:
127 | if format_id == "source":
128 | ikeyboard = [
129 | InlineKeyboardButton(
130 | dipslay_str_uon,
131 | callback_data=(cb_string_video).encode("UTF-8")
132 | )
133 | ]
134 | else:
135 | if format_string is not None and not "audio only" in format_string:
136 | ikeyboard = [
137 | InlineKeyboardButton(
138 | dipslay_str_uon,
139 | callback_data=(cb_string_video).encode("UTF-8")
140 | )
141 | ]
142 | else:
143 | # special weird case :\
144 | ikeyboard = [
145 | InlineKeyboardButton(
146 | "SVideo [" +
147 | "] ( " +
148 | approx_file_size + " )",
149 | callback_data=(cb_string_video).encode("UTF-8")
150 | )
151 | ]
152 | inline_keyboard.append(ikeyboard)
153 | if duration is not None:
154 | inline_keyboard.append([
155 | InlineKeyboardButton(
156 | "MP3 (64 kbps)", callback_data="audio|64k|mp3|_"),
157 | InlineKeyboardButton(
158 | "MP3 (128 kbps)", callback_data="audio|128k|mp3|_")
159 | ])
160 | inline_keyboard.append([
161 | InlineKeyboardButton(
162 | "MP3 (320 kbps)", callback_data="audio|320k|mp3|_")
163 | ])
164 | else:
165 | format_id = current_r_json["format_id"]
166 | format_ext = current_r_json["ext"]
167 | cb_string_video = "{}|{}|{}|{}".format(
168 | "video", format_id, format_ext, "DL"
169 | )
170 | inline_keyboard.append([
171 | InlineKeyboardButton(
172 | "SVideo",
173 | callback_data=(cb_string_video).encode("UTF-8")
174 | )
175 | ])
176 | # TODO: :\
177 | break
178 | reply_markup = InlineKeyboardMarkup(inline_keyboard)
179 | # LOGGER.info(reply_markup)
180 | succss_mesg = (
181 | "Select the desired format: 👇\n"
182 | "mentioned file size might be approximate"
183 | )
184 | return thumb_image, succss_mesg, reply_markup
185 |
--------------------------------------------------------------------------------
/publicleechgroup/plugins/call_back_button_handler.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23 | )
24 | LOGGER = logging.getLogger(__name__)
25 |
26 | from pyrogram.types import CallbackQuery
27 | from publicleechgroup.amocmadin import Loilacaztion
28 | from publicleechgroup.helper_funcs.youtube_dl_button import youtube_dl_call_back
29 | from publicleechgroup.helper_funcs.icntaosrtsba import (
30 | leech_btn_k,
31 | ytdl_btn_k
32 | )
33 |
34 |
35 | async def button(bot, update: CallbackQuery):
36 | LOGGER.info(update)
37 | if not update.message.reply_to_message:
38 | await update.answer(
39 | text=Loilacaztion.TGD_YTLD_STOOPID_DRUSER,
40 | show_alert=True
41 | )
42 | return
43 |
44 | if update.from_user.id != update.message.reply_to_message.from_user.id:
45 | return
46 |
47 | await update.answer()
48 | cb_data = update.data
49 |
50 | if cb_data.startswith("leech"):
51 | await leech_btn_k(update.message, cb_data)
52 |
53 | elif cb_data.startswith("ytdl"):
54 | await ytdl_btn_k(update.message)
55 |
56 | elif "|" in cb_data:
57 | await youtube_dl_call_back(bot, update)
58 |
--------------------------------------------------------------------------------
/publicleechgroup/plugins/custom_thumbnail.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import os
19 | from PIL import Image
20 | from publicleechgroup import DOWNLOAD_LOCATION
21 | from publicleechgroup.amocmadin import Loilacaztion
22 |
23 |
24 | async def save_thumb_nail(_, message):
25 | thumbnail_location = os.path.join(
26 | DOWNLOAD_LOCATION,
27 | "thumbnails"
28 | )
29 | thumb_image_path = os.path.join(
30 | thumbnail_location,
31 | str(message.from_user.id) + ".jpg"
32 | )
33 | ismgs = await message.reply_text(Loilacaztion.PROCESSING)
34 | if message.reply_to_message is not None:
35 | if not os.path.isdir(thumbnail_location):
36 | os.makedirs(thumbnail_location)
37 | download_location = thumbnail_location + "/"
38 | downloaded_file_name = await message.reply_to_message.download(
39 | file_name=download_location
40 | )
41 | # https://stackoverflow.com/a/21669827/4723940
42 | Image.open(downloaded_file_name).convert(
43 | "RGB"
44 | ).save(downloaded_file_name)
45 | # ref: https://t.me/PyrogramChat/44663
46 | img = Image.open(downloaded_file_name)
47 | img.save(thumb_image_path, "JPEG")
48 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
49 | await ismgs.edit(Loilacaztion.SAVED_THUMBNAIL)
50 | else:
51 | await ismgs.edit(Loilacaztion.HELP_SAVE_THUMBNAIL)
52 |
53 |
54 | async def clear_thumb_nail(_, message):
55 | thumbnail_location = os.path.join(
56 | DOWNLOAD_LOCATION,
57 | "thumbnails"
58 | )
59 | thumb_image_path = os.path.join(
60 | thumbnail_location,
61 | str(message.from_user.id) + ".jpg"
62 | )
63 | ismgs = await message.reply_text(Loilacaztion.PROCESSING)
64 | if os.path.exists(thumb_image_path):
65 | os.remove(thumb_image_path)
66 | await ismgs.edit(Loilacaztion.CLEARED_THUMBNAIL)
67 |
--------------------------------------------------------------------------------
/publicleechgroup/plugins/incoming_message_fn.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | # the logging things
19 | import logging
20 | logging.basicConfig(
21 | level=logging.DEBUG,
22 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
23 | )
24 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
25 | LOGGER = logging.getLogger(__name__)
26 |
27 |
28 | import os
29 |
30 | from publicleechgroup import (
31 | DOWNLOAD_LOCATION
32 | )
33 |
34 |
35 | import time
36 | import aria2p
37 | import asyncio
38 | from publicleechgroup.helper_funcs.extract_link_from_message import extract_link
39 | from publicleechgroup.helper_funcs.download_aria_p_n import (
40 | call_apropriate_function, aria_start,
41 | fake_etairporpa_call
42 | )
43 | from publicleechgroup.helper_funcs.download_from_link import request_download
44 | from publicleechgroup.helper_funcs.display_progress import progress_for_pyrogram
45 | from publicleechgroup.helper_funcs.youtube_dl_extractor import extract_youtube_dl_formats
46 | from publicleechgroup.helper_funcs.admin_check import AdminCheck
47 | from publicleechgroup.helper_funcs.create_r_o_m import get_markup
48 | from publicleechgroup.helper_funcs.icntaosrtsba import leech_btn_k
49 | from publicleechgroup.helper_funcs.fix_tcerrocni_images import proc_ess_image_aqon
50 |
51 |
52 | async def incoming_purge_message_f(client, message):
53 | """/purge command"""
54 | i_m_sefg2 = await message.reply_text("Purging...", quote=True)
55 | if await AdminCheck(client, message.chat.id, message.from_user.id):
56 | aria_i_p = await aria_start()
57 | # Show All Downloads
58 | downloads = aria_i_p.get_downloads()
59 | for download in downloads:
60 | LOGGER.info(download.remove(force=True))
61 | await i_m_sefg2.delete()
62 |
63 |
64 | async def incoming_message_f(client, message):
65 | """/leech command"""
66 | i_m_sefg = await message.reply_text("checking ", quote=True)
67 | t_, rm_ = await get_markup(message)
68 | await i_m_sefg.edit_text(
69 | text=t_,
70 | reply_markup=rm_,
71 | disable_web_page_preview=True
72 | )
73 |
74 |
75 | async def leech_commandi_f(client, message):
76 | m_ = await message.reply_text(
77 | "checking",
78 | quote=True
79 | )
80 | force_doc = False
81 | m_sgra = " ".join(message.command[1:])
82 | if "file" in m_sgra.lower():
83 | force_doc = True
84 | # get link from the incoming message
85 | dl_url, cf_name, _, _ = await extract_link(
86 | message.reply_to_message, "LEECH"
87 | )
88 | LOGGER.info(dl_url)
89 | LOGGER.info(cf_name)
90 | if dl_url is not None:
91 | await m_.edit_text("extracting links")
92 | # start the aria2c daemon
93 | aria_i_p = await aria_start()
94 | LOGGER.info(aria_i_p)
95 | current_user_id = message.reply_to_message.from_user.id
96 | # create an unique directory
97 | new_download_location = os.path.join(
98 | DOWNLOAD_LOCATION,
99 | str(current_user_id),
100 | str(message.reply_to_message.message_id)
101 | )
102 | # create download directory, if not exist
103 | if not os.path.isdir(new_download_location):
104 | os.makedirs(new_download_location)
105 | if "_" in m_sgra:
106 | await m_.edit_text("trying to download")
107 | # try to download the "link"
108 | sagtus, err_message = await fake_etairporpa_call(
109 | aria_i_p,
110 | dl_url,
111 | new_download_location,
112 | m_,
113 | int(m_sgra.split("_")[2])
114 | # maybe IndexError / ValueError might occur,
115 | # we don't know, yet!!
116 | )
117 | if not sagtus:
118 | # if FAILED, display the error message
119 | await m_.edit_text(err_message)
120 | else:
121 | is_zip = False
122 | if "a" in m_sgra:
123 | is_zip = True
124 | await m_.edit_text("trying to download")
125 | # try to download the "link"
126 | sagtus, err_message = await call_apropriate_function(
127 | aria_i_p,
128 | dl_url,
129 | new_download_location,
130 | m_,
131 | is_zip,
132 | force_doc=force_doc,
133 | cfn=cf_name
134 | )
135 | if not sagtus:
136 | # if FAILED, display the error message
137 | await m_.edit_text(err_message)
138 |
139 |
140 | async def incoming_youtube_dl_f(client, message):
141 | """ /ytdl command """
142 | i_m_sefg = await message.reply_text("processing", quote=True)
143 | # LOGGER.info(message)
144 | # extract link from message
145 | dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
146 | message.reply_to_message, "YTDL"
147 | )
148 | LOGGER.info(dl_url)
149 | LOGGER.info(cf_name)
150 | if dl_url is not None:
151 | await i_m_sefg.edit_text("extracting links")
152 | current_user_id = message.from_user.id
153 | # create an unique directory
154 | user_working_dir = os.path.join(
155 | DOWNLOAD_LOCATION,
156 | str(current_user_id),
157 | str(message.reply_to_message.message_id)
158 | )
159 | # create download directory, if not exist
160 | if not os.path.isdir(user_working_dir):
161 | os.makedirs(user_working_dir)
162 | # list the formats, and display in button markup formats
163 | thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
164 | dl_url,
165 | # cf_name,
166 | yt_dl_user_name,
167 | yt_dl_pass_word,
168 | user_working_dir
169 | )
170 | if thumb_image is not None:
171 | thumb_image = await proc_ess_image_aqon(
172 | thumb_image,
173 | user_working_dir
174 | )
175 | await message.reply_photo(
176 | photo=thumb_image,
177 | quote=True,
178 | caption=text_message,
179 | reply_to_message_id=message.reply_to_message.message_id,
180 | reply_markup=reply_markup
181 | )
182 | os.remove(thumb_image)
183 | await i_m_sefg.delete()
184 | else:
185 | await i_m_sefg.edit_text(
186 | text=text_message,
187 | reply_markup=reply_markup
188 | )
189 | else:
190 | await i_m_sefg.edit_text(
191 | "**FCUK**! wat have you entered. \nPlease read /help \n"
192 | f"API Error: {cf_name}"
193 | )
194 |
--------------------------------------------------------------------------------
/publicleechgroup/plugins/new_join_fn.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | from publicleechgroup.amocmadin import Loilacaztion
19 |
20 |
21 | async def new_join_f(client, message):
22 | # delete all other messages, except for AUTH_CHANNEL
23 | await message.delete(revoke=True)
24 | # reply the correct CHAT ID,
25 | # and LEAVE the chat
26 | chat_type = message.chat.type
27 | if chat_type != "private":
28 | await message.reply_text(
29 | Loilacaztion.WRONG_MESSAGE.format(
30 | CHAT_ID=message.chat.id
31 | )
32 | )
33 | # leave chat
34 | await message.chat.leave()
35 |
36 |
37 | async def help_message_f(client, message):
38 | # display the /help message
39 | await message.reply_text(
40 | Loilacaztion.HELP_MESSAGE,
41 | quote=True
42 | )
43 |
--------------------------------------------------------------------------------
/publicleechgroup/plugins/status_message_fn.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (C) 2020 PublicLeech Authors
4 |
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU Affero General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU Affero General Public License for more details.
14 |
15 | # You should have received a copy of the GNU Affero General Public License
16 | # along with this program. If not, see .
17 |
18 | import asyncio
19 | import io
20 | import os
21 | import shutil
22 | import sys
23 | import time
24 | import traceback
25 | from publicleechgroup import (
26 | BOT_START_TIME,
27 | LOGGER,
28 | LOG_FILE_ZZGEVC,
29 | MAX_MESSAGE_LENGTH
30 | )
31 | from publicleechgroup.helper_funcs.download_aria_p_n import (
32 | aria_start
33 | )
34 | from publicleechgroup.helper_funcs.upload_to_tg import upload_to_tg
35 | from publicleechgroup.dinmamoc import Commandi
36 | from publicleechgroup.amocmadin import Loilacaztion
37 | from publicleechgroup.helper_funcs.display_progress import (
38 | time_formatter,
39 | humanbytes
40 | )
41 |
42 |
43 | async def status_message_f(client, message):
44 | aria_i_p = await aria_start()
45 | # Show All Downloads
46 | downloads = aria_i_p.get_downloads()
47 | #
48 | DOWNLOAD_ICON = "📥"
49 | UPLOAD_ICON = "📤"
50 | #
51 | msg = ""
52 | for download in downloads:
53 | downloading_dir_name = "NA"
54 | try:
55 | downloading_dir_name = str(download.name)
56 | except:
57 | pass
58 | total_length_size = str(download.total_length_string())
59 | progress_percent_string = str(download.progress_string())
60 | down_speed_string = str(download.download_speed_string())
61 | up_speed_string = str(download.upload_speed_string())
62 | download_current_status = str(download.status)
63 | e_t_a = str(download.eta_string())
64 | current_gid = str(download.gid)
65 | #
66 | msg += f"{downloading_dir_name}"
67 | msg += " | "
68 | msg += f"{total_length_size}"
69 | msg += " | "
70 | msg += f"{progress_percent_string}"
71 | msg += " | "
72 | msg += f"{DOWNLOAD_ICON} {down_speed_string}"
73 | msg += " | "
74 | msg += f"{UPLOAD_ICON} {up_speed_string}"
75 | msg += " | "
76 | msg += f"{e_t_a}"
77 | msg += " | "
78 | msg += f"{download_current_status}"
79 | msg += " | "
80 | msg += f"{Commandi.CANCEL} {current_gid}
"
81 | msg += " | "
82 | msg += "\n\n"
83 | LOGGER.info(msg)
84 |
85 | if msg == "":
86 | msg = Loilacaztion.NO_TOR_STATUS
87 |
88 | currentTime = time_formatter((time.time() - BOT_START_TIME))
89 | total, used, free = shutil.disk_usage(".")
90 | total = humanbytes(total)
91 | used = humanbytes(used)
92 | free = humanbytes(free)
93 |
94 | ms_g = f"Bot Uptime: {currentTime}
\n" \
95 | f"Total disk space: {total}
\n" \
96 | f"Used: {used}
\n" \
97 | f"Free: {free}
\n"
98 |
99 | msg = ms_g + "\n" + msg
100 | while len(msg) > 4095:
101 | await message.reply_text(msg[:4095], quote=True)
102 | msg = msg[4095:]
103 | await asyncio.sleep(1)
104 | if len(msg) > 0:
105 | await message.reply_text(msg, quote=True)
106 |
107 |
108 | async def cancel_message_f(client, message):
109 | if len(message.command) > 1:
110 | # /cancel command
111 | i_m_s_e_g = await message.reply_text(
112 | Loilacaztion.PROCESSING,
113 | quote=True
114 | )
115 | aria_i_p = await aria_start()
116 | g_id = message.command[1].strip()
117 | LOGGER.info(g_id)
118 | try:
119 | downloads = aria_i_p.get_download(g_id)
120 | LOGGER.info(downloads)
121 | LOGGER.info(downloads.remove(force=True, files=True))
122 | await i_m_s_e_g.edit_text(
123 | Loilacaztion.TOR_CANCELLED
124 | )
125 | except Exception as e:
126 | LOGGER.warn(str(e))
127 | await i_m_s_e_g.edit_text(
128 | Loilacaztion.TOR_CANCEL_FAILED
129 | )
130 | else:
131 | await message.delete()
132 |
133 |
134 | async def exec_message_f(client, message):
135 | DELAY_BETWEEN_EDITS = 0.3
136 | PROCESS_RUN_TIME = 100
137 | cmd = message.text.split(" ", maxsplit=1)[1]
138 |
139 | reply_to_id = message.message_id
140 | if message.reply_to_message:
141 | reply_to_id = message.reply_to_message.message_id
142 |
143 | start_time = time.time() + PROCESS_RUN_TIME
144 | process = await asyncio.create_subprocess_shell(
145 | cmd,
146 | stdout=asyncio.subprocess.PIPE,
147 | stderr=asyncio.subprocess.PIPE
148 | )
149 | stdout, stderr = await process.communicate()
150 | e = stderr.decode()
151 | if not e:
152 | e = "😐"
153 | o = stdout.decode()
154 | if not o:
155 | o = "😐"
156 | return_code = process.returncode
157 | OUTPUT = ""
158 | OUTPUT += "EXEC:\n"
159 | OUTPUT += "Command\n"
160 | OUTPUT += f"{cmd}
\n"
161 | OUTPUT += f"PID: {process.pid}
\n\n"
162 | OUTPUT += "stderr:\n"
163 | OUTPUT += f"{e}
\n\n"
164 | OUTPUT += "stdout:\n"
165 | OUTPUT += f"{o}
\n\n"
166 | OUTPUT += f"return: {return_code}
"
167 |
168 | if len(OUTPUT) > MAX_MESSAGE_LENGTH:
169 | with open("exec.text", "w+", encoding="utf8") as out_file:
170 | out_file.write(str(OUTPUT))
171 | await client.send_document(
172 | chat_id=message.chat.id,
173 | document="exec.text",
174 | caption=cmd,
175 | disable_notification=True,
176 | reply_to_message_id=reply_to_id
177 | )
178 | os.remove("exec.text")
179 | await message.delete()
180 | else:
181 | await message.reply_text(OUTPUT)
182 |
183 |
184 | async def upload_document_f(client, message):
185 | imsegd = await message.reply_text(
186 | Loilacaztion.PROCESSING
187 | )
188 | if " " in message.text:
189 | recvd_command, local_file_name = message.text.split(" ", 1)
190 | recvd_response = await upload_to_tg(
191 | imsegd,
192 | local_file_name,
193 | message.from_user.id,
194 | {}
195 | )
196 | LOGGER.info(recvd_response)
197 | await imsegd.delete()
198 |
199 |
200 | async def save_rclone_conf_f(client, message):
201 | chat_type = message.chat.type
202 | r_clone_conf_uri = None
203 | if chat_type in ["private", "bot", "group"]:
204 | r_clone_conf_uri = f"https://t.me/PublicLeech/{message.chat.id}/{message.reply_to_message.message_id}"
205 | elif chat_type in ["supergroup", "channel"]:
206 | if message.chat.username:
207 | r_clone_conf_uri = "please DO NOT upload confidential credentials, in a public group."
208 | else:
209 | r_clone_conf_uri = f"https://t.me/c/{str(message.reply_to_message.chat.id)[4:]}/{message.reply_to_message.message_id}"
210 | else:
211 | r_clone_conf_uri = "unknown chat_type"
212 | await message.reply_text(
213 | ""
214 | f"{r_clone_conf_uri}"
215 | "
"
216 | )
217 |
218 |
219 | async def upload_log_file(client, message):
220 | await message.reply_document(
221 | LOG_FILE_ZZGEVC
222 | )
223 |
224 |
225 | async def eval_message_f(client, message):
226 | ismgese = await message.reply_text("...")
227 | cmd = message.text.split(" ", maxsplit=1)[1]
228 |
229 | old_stderr = sys.stderr
230 | old_stdout = sys.stdout
231 | redirected_output = sys.stdout = io.StringIO()
232 | redirected_error = sys.stderr = io.StringIO()
233 | stdout, stderr, exc = None, None, None
234 |
235 | try:
236 | await aexec(cmd, client, message)
237 | except Exception:
238 | exc = traceback.format_exc()
239 |
240 | stdout = redirected_output.getvalue()
241 | stderr = redirected_error.getvalue()
242 | sys.stdout = old_stdout
243 | sys.stderr = old_stderr
244 |
245 | evaluation = ""
246 | if exc:
247 | evaluation = exc.strip()
248 | elif stderr:
249 | evaluation = stderr.strip()
250 | elif stdout:
251 | evaluation = stdout.strip()
252 | else:
253 | evaluation = "😐"
254 |
255 | final_output = ""
256 | final_output += f"EVAL: {cmd}
"
257 | final_output += "\n\nOUTPUT:\n"
258 | final_output += f"{evaluation}
\n"
259 |
260 | if len(final_output) > MAX_MESSAGE_LENGTH:
261 | with open("eval.text", "w+", encoding="utf8") as out_file:
262 | out_file.write(str(final_output))
263 | await ismgese.reply_document(
264 | document="eval.text",
265 | caption=cmd
266 | )
267 | os.remove("eval.text")
268 | await ismgese.delete()
269 | else:
270 | await ismgese.edit(final_output)
271 |
272 |
273 | async def aexec(code, client, message):
274 | exec(
275 | f'async def __aexec(client, message): ' +
276 | ''.join(f'\n {l}' for l in code.split('\n'))
277 | )
278 | return await locals()['__aexec'](client, message)
279 |
--------------------------------------------------------------------------------
/publicleechgroup/sample_config.py:
--------------------------------------------------------------------------------
1 | # PLEASE STOP!
2 | # DO NOT EDIT THIS FILE
3 | # Create a new config.py file in same dir
4 | # and import, then extend this class.
5 | if not __name__.endswith("sample_config"):
6 | import sys
7 | print(
8 | "The README is there to be read. "
9 | "Extend this sample config to a config file, "
10 | "don't just rename and change values here. "
11 | "Doing that WILL backfire on you.\nBot quitting.",
12 | file=sys.stderr
13 | )
14 | quit(1)
15 |
16 | from dotenv import load_dotenv
17 | from .get_cfg import get_config
18 |
19 |
20 | # apparently, no error appears even if the path does not exists
21 | load_dotenv("config.env")
22 |
23 |
24 | class Config:
25 | # get a token from @BotFather
26 | TG_BOT_TOKEN = get_config("TG_BOT_TOKEN", should_prompt=True)
27 | # The Telegram API things
28 | APP_ID = int(get_config("APP_ID", should_prompt=True))
29 | API_HASH = get_config("API_HASH", should_prompt=True)
30 | # Get these values from my.telegram.org
31 | # array to store the channel ID who are authorized to use the bot
32 | AUTH_CHANNEL = set(
33 | int(x) for x in get_config(
34 | "AUTH_CHANNEL",
35 | should_prompt=True
36 | ).split()
37 | )
38 | # the download location, where the HTTP Server runs
39 | DOWNLOAD_LOCATION = get_config("DOWNLOAD_LOCATION", "./DOWNLOADS")
40 | # Telegram maximum file upload size
41 | MAX_FILE_SIZE = int(get_config("MAX_FILE_SIZE", 50000000))
42 | TG_MAX_FILE_SIZE = int(get_config("TG_MAX_FILE_SIZE", 2097152000))
43 | FREE_USER_MAX_FILE_SIZE = int(
44 | get_config("FREE_USER_MAX_FILE_SIZE", 50000000)
45 | )
46 | # chunk size that should be used with requests
47 | CHUNK_SIZE = int(get_config("CHUNK_SIZE", 128))
48 | # default thumbnail to be used in the videos
49 | DEF_THUMB_NAIL_VID_S = get_config(
50 | "DEF_THUMB_NAIL_VID_S",
51 | "https://telegra.ph/file/8b973b270f4f380a427b1.png"
52 | )
53 | # maximum message length in Telegram
54 | MAX_MESSAGE_LENGTH = int(get_config(
55 | "MAX_MESSAGE_LENGTH",
56 | 4096
57 | ))
58 | # set timeout for subprocess
59 | PROCESS_MAX_TIMEOUT = int(get_config(
60 | "PROCESS_MAX_TIMEOUT",
61 | 3600
62 | ))
63 | #
64 | ARIA_TWO_STARTED_PORT = int(get_config(
65 | "ARIA_TWO_STARTED_PORT",
66 | 6800
67 | ))
68 | EDIT_SLEEP_TIME_OUT = int(get_config(
69 | "EDIT_SLEEP_TIME_OUT",
70 | 1
71 | ))
72 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = int(get_config(
73 | "MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START",
74 | 600
75 | ))
76 | MAX_TG_SPLIT_FILE_SIZE = int(get_config(
77 | "MAX_TG_SPLIT_FILE_SIZE",
78 | 1900000000
79 | ))
80 | # add config vars for the display progress
81 | FINISHED_PROGRESS_STR = get_config("FINISHED_PROGRESS_STR", "█")
82 | UN_FINISHED_PROGRESS_STR = get_config("UN_FINISHED_PROGRESS_STR", "░")
83 | # add offensive API
84 | TG_OFFENSIVE_API = get_config("TG_OFFENSIVE_API", None)
85 | # URL for the rclone configuration
86 | R_CLONE_CONF_URI = get_config("R_CLONE_CONF_URI", None)
87 | # Destination folder for the rclone
88 | R_CLONE_DEST = get_config("R_CLONE_DEST", "/PublicLeech")
89 | # because, https://t.me/c/1494623325/5603
90 | SHOULD_USE_BUTTONS = get_config("SHOULD_USE_BUTTONS", False)
91 | #
92 | LOG_FILE_ZZGEVC = get_config("LOG_FILE_ZZGEVC", "PublicLeech.log")
93 | #
94 | SP_LIT_ALGO_RITH_M = get_config(
95 | "SP_LIT_ALGO_RITH_M",
96 | "hjs"
97 | )
98 | #
99 | DIS_ABLE_ST_GFC_COMMAND_I = get_config(
100 | "DIS_ABLE_ST_GFC_COMMAND_I",
101 | False
102 | )
103 | #
104 | SLEEP_THRES_HOLD = get_config(
105 | "SLEEP_THRES_HOLD",
106 | 98712
107 | )
108 | # array to store the users who will have control (permissions)
109 | # in the bot
110 | SUDO_USERS = set(
111 | int(x) for x in get_config(
112 | "SUDO_USERS",
113 | should_prompt=True
114 | ).split()
115 | )
116 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # GET / POST network requests
2 | asyncio==3.4.3
3 | aiohttp==3.7.4
4 |
5 | # achG2zZTxbA 12
6 | aria2p==0.9.1
7 |
8 | # get metadata from files
9 | hachoir==3.1.1
10 |
11 | # process(, and resize) images
12 | Pillow==9.0.0
13 |
14 | # required to communicate with Telegram API
15 | Pyrogram==1.4.7
16 | TgCrypto==1.2.3
17 |
18 | youtube-dl
19 |
20 | # for reading .env files
21 | python-dotenv>=0.10
22 |
--------------------------------------------------------------------------------
/sample_config.env:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Copyright (C) 2020 PublicLeech Authors
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU Affero General Public License for more details.
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 | #
15 | # All rights reserved.
16 |
17 | # Please read the README to understand each variable values.
18 |
19 | # ----------- REQUIRED ----------- #
20 |
21 | # TG_BOT_TOKEN=1234567:tujnbscpnzcqdfkfnchbhithyofczznbgpw
22 | # APP_ID=6
23 | # API_HASH=eb06d4abfb49dc3eeb1aeb98ae0f581e
24 | # AUTH_CHANNEL=-100123456789 7351948
25 |
26 | # ----------- OPTIONAL ----------- #
27 |
28 | # SHOULD_USE_BUTTONS=False
29 | # ARIA_TWO_STARTED_PORT=6800
30 | # EDIT_SLEEP_TIME_OUT=1
31 | # MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START=600
32 | # FINISHED_PROGRESS_STR=█
33 | # UN_FINISHED_PROGRESS_STR=░
34 | # R_CLONE_CONF_URI=
35 | # R_CLONE_DEST=
36 | # DOWNLOAD_LOCATION=
37 | # MAX_FILE_SIZE=50000000
38 | # TG_MAX_FILE_SIZE=2097152000
39 | # FREE_USER_MAX_FILE_SIZE=50000000
40 | # MAX_TG_SPLIT_FILE_SIZE=1900000000
41 | # MAX_MESSAGE_LENGTH=4096
42 | # PROCESS_MAX_TIMEOUT=3600
43 | # SP_LIT_ALGO_RITH_M=
44 | # TG_OFFENSIVE_API=
45 | # CHUNK_SIZE=
46 | # DIS_ABLE_ST_GFC_COMMAND_I=
47 | # SLEEP_THRES_HOLD=5
48 | # SUDO_USERS=7351948
49 |
--------------------------------------------------------------------------------