├── .gitignore
├── LICENSE
├── Procfile
├── README.md
├── add_to_team_drive.py
├── app.json
├── bot.py
├── config.py
├── gen_sa_accounts.py
├── generate_drive_token.py
├── helper_funcs
├── bot_utils.py
├── display_progress.py
├── fsub.py
└── gdriveTools.py
├── plugins
├── help_text.py
├── tg_to_gdrive.py
└── utils.py
├── requirements.txt
└── translation.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python3 bot.py
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # What is this repo about?
2 | This is a telegram bot writen in python for genrating streaming links
3 |
4 | # Demo BOT LINK:
5 |
6 |
7 | # Features supported:
8 | - Stream m3u8 links
9 | - Stream mpd links
10 | - Stream brightcove video using video id
11 | - Stream JW Player video using video id
12 | - Stream Telegram media
13 | - Stream YouTube video using link
14 |
15 | # How to deploy?
16 | Deploying is pretty much straight forward and is divided into several steps as follows:
17 |
18 | ### Heroku Deploy:
19 | [](https://heroku.com/deploy?template=https://github.com/Jigarvarma2005/Streaming-Link-Gen)
20 |
21 | # How to get token.pickle file (Recommnded)
22 |
23 | - Visit the [Google Cloud Console](https://console.developers.google.com/apis/credentials)
24 | - Go to the OAuth Consent tab, fill it, and save.
25 | - Go to the Credentials tab and click Create Credentials -> OAuth Client ID
26 | - Choose Other and Create.
27 | - Use the download button to download your credentials.
28 | - Move that file to the root of streaming-link-gen, and rename it to credentials.json
29 | - Visit [Google API page](https://console.developers.google.com/apis/library)
30 | - Search for Drive and enable it if it is disabled
31 | - Finally, run the script to generate token file (token.pickle) for Google Drive:
32 | ```
33 | pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
34 | python3 generate_drive_token.py
35 | ```
36 |
37 | # Using service accounts for uploading to avoid user rate limit
38 | For Service Account to work, you must set USE_SERVICE_ACCOUNTS="True" in config file or environment variables
39 | Many thanks to [AutoRClone](https://github.com/xyou365/AutoRclone) for the scripts
40 | **NOTE:** Using service accounts is only recommended while uploading to a team drive.
41 | ## Generating service accounts
42 | Step 1. Generate service accounts [What is service account](https://cloud.google.com/iam/docs/service-accounts)
43 | ---------------------------------
44 | Let us create only the service accounts that we need.
45 | **Warning:** abuse of this feature is not the aim of this project and we do **NOT** recommend that you make a lot of projects, just one project and 100 sa allow you plenty of use, its also possible that over abuse might get your projects banned by google.
46 |
47 | ```
48 | Note: 1 service account can copy around 750gb a day, 1 project can make 100 service accounts so that's 75tb a day, for most users this should easily suffice.
49 | ```
50 |
51 | `python3 gen_sa_accounts.py --quick-setup 1 --new-only`
52 |
53 | A folder named accounts will be created which will contain keys for the service accounts
54 |
55 | NOTE: If you have created SAs in past from this script, you can also just re download the keys by running:
56 | ```
57 | python3 gen_sa_accounts.py --download-keys project_id
58 | ```
59 |
60 | ### Add all the service accounts to the Team Drive
61 | - Run:
62 | ```
63 | python3 add_to_team_drive.py -d SharedTeamDriveSrcID
64 | ```
65 |
66 | ### Follow on:
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | #### Support Group
78 | - [JV Community](https://t.me/jv_community)
79 |
80 | #### Bots Updates Channel
81 | - [Universal Projects](https://t.me/Universal_Projects)
82 |
83 | ### Credits
84 | - [Jigar Varma](https://github.com/jigarvarma2005)
85 | - [lzzy12](https://github.com/lzzy12)
86 | - [SpEcHiDe](https://github.com/SpEcHiDe)
87 | - [Pyrogram](https://github.com/pyrogram/pyrogram)
88 |
--------------------------------------------------------------------------------
/add_to_team_drive.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | from google.oauth2.service_account import Credentials
3 | import googleapiclient.discovery, json, progress.bar, glob, sys, argparse, time
4 | from google_auth_oauthlib.flow import InstalledAppFlow
5 | from google.auth.transport.requests import Request
6 | import os, pickle
7 |
8 | stt = time.time()
9 |
10 | parse = argparse.ArgumentParser(
11 | description='A tool to add service accounts to a shared drive from a folder containing credential files.')
12 | parse.add_argument('--path', '-p', default='accounts',
13 | help='Specify an alternative path to the service accounts folder.')
14 | parse.add_argument('--credentials', '-c', default='./credentials.json',
15 | help='Specify the relative path for the credentials file.')
16 | parse.add_argument('--yes', '-y', default=False, action='store_true', help='Skips the sanity prompt.')
17 | parsereq = parse.add_argument_group('required arguments')
18 | parsereq.add_argument('--drive-id', '-d', help='The ID of the Shared Drive.', required=True)
19 |
20 | args = parse.parse_args()
21 | acc_dir = args.path
22 | did = args.drive_id
23 | credentials = glob.glob(args.credentials)
24 |
25 | try:
26 | open(credentials[0], 'r')
27 | print('>> Found credentials.')
28 | except IndexError:
29 | print('>> No credentials found.')
30 | sys.exit(0)
31 |
32 | if not args.yes:
33 | # input('Make sure the following client id is added to the shared drive as Manager:\n' + json.loads((open(
34 | # credentials[0],'r').read()))['installed']['client_id'])
35 | input('>> Make sure the **Google account** that has generated credentials.json\n is added into your Team Drive '
36 | '(shared drive) as Manager\n>> (Press any key to continue)')
37 |
38 | creds = None
39 | if os.path.exists('token_sa.pickle'):
40 | with open('token_sa.pickle', 'rb') as token:
41 | creds = pickle.load(token)
42 | # If there are no (valid) credentials available, let the user log in.
43 | if not creds or not creds.valid:
44 | if creds and creds.expired and creds.refresh_token:
45 | creds.refresh(Request())
46 | else:
47 | flow = InstalledAppFlow.from_client_secrets_file(credentials[0], scopes=[
48 | 'https://www.googleapis.com/auth/admin.directory.group',
49 | 'https://www.googleapis.com/auth/admin.directory.group.member'
50 | ])
51 | # creds = flow.run_local_server(port=0)
52 | creds = flow.run_console()
53 | # Save the credentials for the next run
54 | with open('token_sa.pickle', 'wb') as token:
55 | pickle.dump(creds, token)
56 |
57 | drive = googleapiclient.discovery.build("drive", "v3", credentials=creds)
58 | batch = drive.new_batch_http_request()
59 |
60 | aa = glob.glob('%s/*.json' % acc_dir)
61 | pbar = progress.bar.Bar("Readying accounts", max=len(aa))
62 | for i in aa:
63 | ce = json.loads(open(i, 'r').read())['client_email']
64 | batch.add(drive.permissions().create(fileId=did, supportsAllDrives=True, body={
65 | "role": "fileOrganizer",
66 | "type": "user",
67 | "emailAddress": ce
68 | }))
69 | pbar.next()
70 | pbar.finish()
71 | print('Adding...')
72 | batch.execute()
73 |
74 | print('Complete.')
75 | hours, rem = divmod((time.time() - stt), 3600)
76 | minutes, sec = divmod(rem, 60)
77 | print("Elapsed Time:\n{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), sec))
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Streaming Link",
3 | "description": "A telegram bot to generate direct streaming links",
4 | "keywords": [
5 | "telegram",
6 | "best",
7 | "open",
8 | "remote",
9 | "uploader",
10 | "stream",
11 | "google",
12 | "m3u8",
13 | "mpd"
14 | ],
15 | "success_url": "https://github.com/Jigarvarma2005/Streaming-Link-Gen",
16 | "website": "https://github.com/Jigarvarma2005/Streaming-Link-Gen",
17 | "repository": "https://github.com/Jigarvarma2005/Streaming-Link-Gen",
18 | "env": {
19 | "TG_BOT_TOKEN": {
20 | "description": "Your bot token, as a string.",
21 | "value": ""
22 | },
23 | "APP_ID": {
24 | "description": "Get this value from https://my.telegram.org",
25 | "value": ""
26 | },
27 | "API_HASH": {
28 | "description": "Get this value from https://my.telegram.org",
29 | "value": ""
30 | },
31 | "UPDATES_CHANNEL": {
32 | "description": "Your updates channel username",
33 | "required": false
34 | },
35 | "VIDEO_PLAYER_URL": {
36 | "description": "Your web video player url check 'https://github.com/Jigarvarma2005/video-player'",
37 | "required": false
38 | },
39 | "TOKEN_PICKLE": {
40 | "description": "`token.pickle` file link to download & use."
41 | },
42 | "GDRIVE_FOLDER_ID": {
43 | "description": "This is the folder ID of the Google Drive Folder to which you want to upload all the telegram media"
44 | },
45 | "IS_TEAM_DRIVE": {
46 | "description": "Set to 'True' if GDRIVE_FOLDER_ID is from a Team Drive else False or Leave it empty.",
47 | "required": false,
48 | "value": "False"
49 | },
50 | "USE_SERVICE_ACCOUNTS": {
51 | "description": "Whether to use service accounts or not. For this to work see 'Using service accounts' section readme file in repo",
52 | "value": "False"
53 | },
54 | "INDEX_URL": {
55 | "description": " Refer to https://github.com/maple3142/GDIndex/ The URL should not have any trailing '/'"
56 | }
57 | },
58 | "addons": [
59 | ],
60 | "buildpacks": [{
61 | "url": "heroku/python"
62 | }],
63 | "formation": {
64 | "worker": {
65 | "quantity": 1,
66 | "size": "free"
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import time
4 | from config import Config
5 | import pyrogram
6 | import wget
7 | import pyromod.listen
8 |
9 | logging.basicConfig(level=logging.DEBUG,
10 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
11 | logger = logging.getLogger(__name__)
12 | logging.getLogger("pyrogram").setLevel(logging.WARNING)
13 | botStartTime = time.time()
14 |
15 | # create download directory, if not exist
16 | if not os.path.isdir(Config.DOWNLOAD_LOCATION):
17 | os.makedirs(Config.DOWNLOAD_LOCATION)
18 | plugins = dict(
19 | root="plugins"
20 | )
21 |
22 | app = pyrogram.Client(
23 | "StreamingLinkRobot",
24 | bot_token=Config.TG_BOT_TOKEN,
25 | api_id=Config.APP_ID,
26 | api_hash=Config.API_HASH,
27 | plugins=plugins
28 | )
29 |
30 |
31 | def BootUpProcess() -> bool:
32 | token_pickle = "token.pickle"
33 | if Config.TOKEN_PICKLE:
34 | token_pickle = wget.download(Config.TOKEN_PICKLE, out=token_pickle)
35 | if not os.path.exists(token_pickle):
36 | print("token.pickle file not found!")
37 | return False
38 | return True
39 |
40 |
41 | if __name__ == "__main__":
42 | print("Starting ...")
43 | success = BootUpProcess()
44 | if success:
45 | app.start()
46 | print("\nBot Started!\n")
47 | pyrogram.idle()
48 | app.stop()
49 | print("Exiting ...")
50 | else:
51 | print("Exiting ...")
52 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | class Config(object):
5 | # get a token from @BotFather
6 | TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
7 | # Get these values from my.telegram.org
8 | APP_ID = int(os.environ.get("APP_ID", 1234567))
9 | API_HASH = os.environ.get("API_HASH", "")
10 | # Your Updates channel username
11 | UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", None)
12 | # token.pickle file link
13 | TOKEN_PICKLE = os.environ.get("TOKEN_PICKLE", None)
14 | # the download location, where the HTTP Server runs
15 | DOWNLOAD_LOCATION = "./DOWNLOADS"
16 | # Google drive folder id
17 | parent_id = os.environ.get("GDRIVE_FOLDER_ID", "")
18 | # Set True is drive folder id is Team Drive
19 | IS_TEAM_DRIVE = os.environ.get("IS_TEAM_DRIVE", "False")
20 | if IS_TEAM_DRIVE.lower() == 'true':
21 | IS_TEAM_DRIVE = True
22 | else:
23 | IS_TEAM_DRIVE = False
24 | # Set it True if using Service Account for uploading
25 | USE_SERVICE_ACCOUNTS = os.environ.get("USE_SERVICE_ACCOUNTS", "False")
26 | if USE_SERVICE_ACCOUNTS.lower() == 'true':
27 | USE_SERVICE_ACCOUNTS = True
28 | else:
29 | USE_SERVICE_ACCOUNTS = False
30 | # Your gdrive index url (Important)
31 | INDEX_URL = os.environ.get("INDEX_URL", "")
32 | # Your web video player url check 'https://github.com/Jigarvarma2005/video-player'
33 | VIDEO_PLAYER_URL = os.environ.get("VIDEO_PLAYER_URL", "jv-stream.herokuapp.com")
34 |
--------------------------------------------------------------------------------
/gen_sa_accounts.py:
--------------------------------------------------------------------------------
1 | import errno
2 | import os
3 | import pickle
4 | import sys
5 | from argparse import ArgumentParser
6 | from base64 import b64decode
7 | from glob import glob
8 | from json import loads
9 | from random import choice
10 | from time import sleep
11 |
12 | from google.auth.transport.requests import Request
13 | from google_auth_oauthlib.flow import InstalledAppFlow
14 | from googleapiclient.discovery import build
15 | from googleapiclient.errors import HttpError
16 |
17 | SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/cloud-platform',
18 | 'https://www.googleapis.com/auth/iam']
19 | project_create_ops = []
20 | current_key_dump = []
21 | sleep_time = 30
22 |
23 |
24 | # Create count SAs in project
25 | def _create_accounts(service, project, count):
26 | batch = service.new_batch_http_request(callback=_def_batch_resp)
27 | for i in range(count):
28 | aid = _generate_id('mfc-')
29 | batch.add(service.projects().serviceAccounts().create(name='projects/' + project, body={'accountId': aid,
30 | 'serviceAccount': {
31 | 'displayName': aid}}))
32 | batch.execute()
33 |
34 |
35 | # Create accounts needed to fill project
36 | def _create_remaining_accounts(iam, project):
37 | print('Creating accounts in %s' % project)
38 | sa_count = len(_list_sas(iam, project))
39 | while sa_count != 100:
40 | _create_accounts(iam, project, 100 - sa_count)
41 | sa_count = len(_list_sas(iam, project))
42 |
43 |
44 | # Generate a random id
45 | def _generate_id(prefix='saf-'):
46 | chars = '-abcdefghijklmnopqrstuvwxyz1234567890'
47 | return prefix + ''.join(choice(chars) for _ in range(25)) + choice(chars[1:])
48 |
49 |
50 | # List projects using service
51 | def _get_projects(service):
52 | return [i['projectId'] for i in service.projects().list().execute()['projects']]
53 |
54 |
55 | # Default batch callback handler
56 | def _def_batch_resp(id, resp, exception):
57 | if exception is not None:
58 | if str(exception).startswith(' 0:
219 | current_count = len(_get_projects(cloud))
220 | if current_count + create_projects <= max_projects:
221 | print('Creating %d projects' % (create_projects))
222 | nprjs = _create_projects(cloud, create_projects)
223 | selected_projects = nprjs
224 | else:
225 | sys.exit('No, you cannot create %d new project (s).\n'
226 | 'Please reduce value of --quick-setup.\n'
227 | 'Remember that you can totally create %d projects (%d already).\n'
228 | 'Please do not delete existing projects unless you know what you are doing' % (
229 | create_projects, max_projects, current_count))
230 | else:
231 | print('Will overwrite all service accounts in existing projects.\n'
232 | 'So make sure you have some projects already.')
233 | input("Press Enter to continue...")
234 |
235 | if enable_services:
236 | ste = []
237 | ste.append(enable_services)
238 | if enable_services == '~':
239 | ste = selected_projects
240 | elif enable_services == '*':
241 | ste = _get_projects(cloud)
242 | services = [i + '.googleapis.com' for i in services]
243 | print('Enabling services')
244 | _enable_services(serviceusage, ste, services)
245 | if create_sas:
246 | stc = []
247 | stc.append(create_sas)
248 | if create_sas == '~':
249 | stc = selected_projects
250 | elif create_sas == '*':
251 | stc = _get_projects(cloud)
252 | for i in stc:
253 | _create_remaining_accounts(iam, i)
254 | if download_keys:
255 | try:
256 | os.mkdir(path)
257 | except OSError as e:
258 | if e.errno == errno.EEXIST:
259 | pass
260 | else:
261 | raise
262 | std = []
263 | std.append(download_keys)
264 | if download_keys == '~':
265 | std = selected_projects
266 | elif download_keys == '*':
267 | std = _get_projects(cloud)
268 | _create_sa_keys(iam, std, path)
269 | if delete_sas:
270 | std = []
271 | std.append(delete_sas)
272 | if delete_sas == '~':
273 | std = selected_projects
274 | elif delete_sas == '*':
275 | std = _get_projects(cloud)
276 | for i in std:
277 | print('Deleting service accounts in %s' % i)
278 | _delete_sas(iam, i)
279 |
280 |
281 | if __name__ == '__main__':
282 | parse = ArgumentParser(description='A tool to create Google service accounts.')
283 | parse.add_argument('--path', '-p', default='accounts',
284 | help='Specify an alternate directory to output the credential files.')
285 | parse.add_argument('--token', default='token_sa.pickle', help='Specify the pickle token file path.')
286 | parse.add_argument('--credentials', default='credentials.json', help='Specify the credentials file path.')
287 | parse.add_argument('--list-projects', default=False, action='store_true',
288 | help='List projects viewable by the user.')
289 | parse.add_argument('--list-sas', default=False, help='List service accounts in a project.')
290 | parse.add_argument('--create-projects', type=int, default=None, help='Creates up to N projects.')
291 | parse.add_argument('--max-projects', type=int, default=12, help='Max amount of project allowed. Default: 12')
292 | parse.add_argument('--enable-services', default=None,
293 | help='Enables services on the project. Default: IAM and Drive')
294 | parse.add_argument('--services', nargs='+', default=['iam', 'drive'],
295 | help='Specify a different set of services to enable. Overrides the default.')
296 | parse.add_argument('--create-sas', default=None, help='Create service accounts in a project.')
297 | parse.add_argument('--delete-sas', default=None, help='Delete service accounts in a project.')
298 | parse.add_argument('--download-keys', default=None, help='Download keys for all the service accounts in a project.')
299 | parse.add_argument('--quick-setup', default=None, type=int,
300 | help='Create projects, enable services, create service accounts and download keys. ')
301 | parse.add_argument('--new-only', default=False, action='store_true', help='Do not use exisiting projects.')
302 | args = parse.parse_args()
303 | # If credentials file is invalid, search for one.
304 | if not os.path.exists(args.credentials):
305 | options = glob('*.json')
306 | print('No credentials found at %s. Please enable the Drive API in:\n'
307 | 'https://developers.google.com/drive/api/v3/quickstart/python\n'
308 | 'and save the json file as credentials.json' % args.credentials)
309 | if len(options) < 1:
310 | exit(-1)
311 | else:
312 | i = 0
313 | print('Select a credentials file below.')
314 | inp_options = [str(i) for i in list(range(1, len(options) + 1))] + options
315 | while i < len(options):
316 | print(' %d) %s' % (i + 1, options[i]))
317 | i += 1
318 | inp = None
319 | while True:
320 | inp = input('> ')
321 | if inp in inp_options:
322 | break
323 | if inp in options:
324 | args.credentials = inp
325 | else:
326 | args.credentials = options[int(inp) - 1]
327 | print('Use --credentials %s next time to use this credentials file.' % args.credentials)
328 | if args.quick_setup:
329 | opt = '*'
330 | if args.new_only:
331 | opt = '~'
332 | args.services = ['iam', 'drive']
333 | args.create_projects = args.quick_setup
334 | args.enable_services = opt
335 | args.create_sas = opt
336 | args.download_keys = opt
337 | resp = serviceaccountfactory(
338 | path=args.path,
339 | token=args.token,
340 | credentials=args.credentials,
341 | list_projects=args.list_projects,
342 | list_sas=args.list_sas,
343 | create_projects=args.create_projects,
344 | max_projects=args.max_projects,
345 | create_sas=args.create_sas,
346 | delete_sas=args.delete_sas,
347 | enable_services=args.enable_services,
348 | services=args.services,
349 | download_keys=args.download_keys
350 | )
351 | if resp is not None:
352 | if args.list_projects:
353 | if resp:
354 | print('Projects (%d):' % len(resp))
355 | for i in resp:
356 | print(' ' + i)
357 | else:
358 | print('No projects.')
359 | elif args.list_sas:
360 | if resp:
361 | print('Service accounts in %s (%d):' % (args.list_sas, len(resp)))
362 | for i in resp:
363 | print(' %s (%s)' % (i['email'], i['uniqueId']))
364 | else:
365 | print('No service accounts.')
366 |
--------------------------------------------------------------------------------
/generate_drive_token.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import os
3 | from google_auth_oauthlib.flow import InstalledAppFlow
4 | from google.auth.transport.requests import Request
5 |
6 | credentials = None
7 | __G_DRIVE_TOKEN_FILE = "token.pickle"
8 | __OAUTH_SCOPE = ["https://www.googleapis.com/auth/drive"]
9 | if os.path.exists(__G_DRIVE_TOKEN_FILE):
10 | with open(__G_DRIVE_TOKEN_FILE, 'rb') as f:
11 | credentials = pickle.load(f)
12 | if credentials is None or not credentials.valid:
13 | if credentials and credentials.expired and credentials.refresh_token:
14 | credentials.refresh(Request())
15 | else:
16 | flow = InstalledAppFlow.from_client_secrets_file(
17 | 'credentials.json', __OAUTH_SCOPE)
18 | credentials = flow.run_console(port=0)
19 |
20 | # Save the credentials for the next run
21 | with open(__G_DRIVE_TOKEN_FILE, 'wb') as token:
22 | pickle.dump(credentials, token)
--------------------------------------------------------------------------------
/helper_funcs/bot_utils.py:
--------------------------------------------------------------------------------
1 | # (c) Jigarvarma2005
2 |
3 | import logging
4 | import os
5 | import threading
6 | import time
7 | from asyncio import TimeoutError
8 | from pyrogram import filters
9 | from base64 import standard_b64encode, standard_b64decode
10 |
11 | LOGGER = logging.getLogger(__name__)
12 | SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
13 |
14 | class setInterval:
15 | def __init__(self, interval, action):
16 | self.interval = interval
17 | self.action = action
18 | self.stopEvent = threading.Event()
19 | thread = threading.Thread(target=self.__setInterval)
20 | thread.start()
21 |
22 | def __setInterval(self):
23 | nextTime = time.time() + self.interval
24 | while not self.stopEvent.wait(nextTime - time.time()):
25 | nextTime += self.interval
26 | self.action()
27 |
28 | def cancel(self):
29 | self.stopEvent.set()
30 |
31 |
32 | def get_readable_file_size(size_in_bytes) -> str:
33 | if size_in_bytes is None:
34 | return '0B'
35 | index = 0
36 | while size_in_bytes >= 1024:
37 | size_in_bytes /= 1024
38 | index += 1
39 | try:
40 | return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}'
41 | except IndexError:
42 | return 'File too large'
43 |
44 |
45 | def get_readable_time(seconds: int) -> str:
46 | result = ''
47 | (days, remainder) = divmod(seconds, 86400)
48 | days = int(days)
49 | if days != 0:
50 | result += f'{days}d'
51 | (hours, remainder) = divmod(remainder, 3600)
52 | hours = int(hours)
53 | if hours != 0:
54 | result += f'{hours}h'
55 | (minutes, seconds) = divmod(remainder, 60)
56 | minutes = int(minutes)
57 | if minutes != 0:
58 | result += f'{minutes}m'
59 | seconds = int(seconds)
60 | result += f'{seconds}s'
61 | return result
62 |
63 | def get_path_size(path):
64 | if os.path.isfile(path):
65 | return os.path.getsize(path)
66 | total_size = 0
67 | for root, dirs, files in os.walk(path):
68 | for f in files:
69 | abs_path = os.path.join(root, f)
70 | total_size += os.path.getsize(abs_path)
71 | return total_size
72 |
73 | def readable_time(seconds: int) -> str:
74 | result = ''
75 | (days, remainder) = divmod(seconds, 86400)
76 | days = int(days)
77 | if days != 0:
78 | result += f'{days}d'
79 | (hours, remainder) = divmod(remainder, 3600)
80 | hours = int(hours)
81 | if hours != 0:
82 | result += f'{hours}h'
83 | (minutes, seconds) = divmod(remainder, 60)
84 | minutes = int(minutes)
85 | if minutes != 0:
86 | result += f'{minutes}m'
87 | seconds = int(seconds)
88 | result += f'{seconds}s'
89 | return result
90 |
91 | def str_to_b64(__str: str) -> str:
92 | str_bytes = __str.encode('ascii')
93 | bytes_b64 = standard_b64encode(str_bytes)
94 | b64 = bytes_b64.decode('ascii')
95 | return b64
96 |
97 |
98 | def b64_to_str(b64: str) -> str:
99 | bytes_b64 = b64.encode('ascii')
100 | bytes_str = standard_b64decode(bytes_b64)
101 | __str = bytes_str.decode('ascii')
102 | return __str
103 |
104 | async def input_str(bot,message, msg):
105 | if len(message.command) <= 1:
106 | try:
107 | jv = await message.reply_text(msg+"\n\n(You can use /cancel command to cancel the process)")
108 | _text = await bot.listen(message.from_user.id, filters=filters.text, timeout=90)
109 | if _text.text:
110 | text = _text.text
111 | if text=="/cancel":
112 | await jv.edit("Process Cancelled Successfully")
113 | return 404
114 | else:
115 | return 404
116 | except TimeoutError:
117 | await jv.edit("I can't wait more for link, send command again to use me.")
118 | return 404
119 | else:
120 | text = message.command[1]
121 | return str_to_b64(text)
122 |
--------------------------------------------------------------------------------
/helper_funcs/display_progress.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # (c) Shrimadhav U K | Jigar Varma
4 |
5 | # the logging things
6 | import logging
7 | logging.basicConfig(level=logging.DEBUG,
8 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
9 | logger = logging.getLogger(__name__)
10 |
11 | import math
12 | import os
13 | import time
14 | from config import Config
15 |
16 | # the Strings used for this "thing"
17 | from translation import Translation
18 |
19 |
20 | async def progress_for_pyrogram(
21 | current,
22 | total,
23 | ud_type,
24 | message,
25 | start
26 | ):
27 | now = time.time()
28 | diff = now - start
29 | if round(diff % 10.00) == 0 or current == total:
30 | # if round(current / total * 100, 0) % 5 == 0:
31 | percentage = current * 100 / total
32 | speed = current / diff
33 | elapsed_time = round(diff) * 1000
34 | time_to_completion = round((total - current) / speed) * 1000
35 | estimated_total_time = elapsed_time + time_to_completion
36 |
37 | elapsed_time = TimeFormatter(milliseconds=elapsed_time)
38 | estimated_total_time = TimeFormatter(milliseconds=estimated_total_time)
39 |
40 | progress = "[{0}{1}] \nP: {2}%\n".format(
41 | ''.join(["❂" for i in range(math.floor(percentage / 5))]),
42 | ''.join(["○" for i in range(20 - math.floor(percentage / 5))]),
43 | round(percentage, 2))
44 |
45 | tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format(
46 | humanbytes(current),
47 | humanbytes(total),
48 | humanbytes(speed),
49 | # elapsed_time if elapsed_time != '' else "0 s",
50 | estimated_total_time if estimated_total_time != '' else "0 s"
51 | )
52 | try:
53 | await message.edit(
54 | text="{}\n {}".format(
55 | ud_type,
56 | tmp
57 | )
58 | )
59 | except:
60 | pass
61 |
62 |
63 | def humanbytes(size):
64 | # https://stackoverflow.com/a/49361727/4723940
65 | # 2**10 = 1024
66 | if not size:
67 | return ""
68 | power = 2**10
69 | n = 0
70 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
71 | while size > power:
72 | size /= power
73 | n += 1
74 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
75 |
76 |
77 | def TimeFormatter(milliseconds: int) -> str:
78 | seconds, milliseconds = divmod(int(milliseconds), 1000)
79 | minutes, seconds = divmod(seconds, 60)
80 | hours, minutes = divmod(minutes, 60)
81 | days, hours = divmod(hours, 24)
82 | tmp = ((str(days) + "d, ") if days else "") + \
83 | ((str(hours) + "h, ") if hours else "") + \
84 | ((str(minutes) + "m, ") if minutes else "") + \
85 | ((str(seconds) + "s, ") if seconds else "") + \
86 | ((str(milliseconds) + "ms, ") if milliseconds else "")
87 | return tmp[:-2]
88 |
--------------------------------------------------------------------------------
/helper_funcs/fsub.py:
--------------------------------------------------------------------------------
1 | # (c) Jigarvarma2005
2 |
3 | import os
4 | from config import Config
5 | from pyrogram.errors import UserNotParticipant
6 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
7 |
8 | async def handle_force_sub(bot, cmd):
9 | if Config.UPDATES_CHANNEL:
10 | invite_link = f"https://t.me/{Config.UPDATES_CHANNEL}"
11 | try:
12 | user = await bot.get_chat_member(Config.UPDATES_CHANNEL, cmd.from_user.id)
13 | if user.status == "kicked":
14 | await bot.send_message(
15 | chat_id=cmd.from_user.id,
16 | text="Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/JV_Community).",
17 | parse_mode="markdown",
18 | disable_web_page_preview=True
19 | )
20 | return 400
21 | else:
22 | return 500
23 | except UserNotParticipant:
24 | await bot.send_message(
25 | chat_id=cmd.from_user.id,
26 | text="**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
27 | reply_markup=InlineKeyboardMarkup(
28 | [
29 | [
30 | InlineKeyboardButton("🤖 Join Updates Channel", url=invite_link)
31 | ]
32 | ]
33 | ),
34 | parse_mode="markdown"
35 | )
36 | return 400
37 | except Exception:
38 | await bot.send_message(
39 | chat_id=cmd.from_user.id,
40 | text="Something went Wrong. Contact my [Support Group](https://t.me/JV_Community).",
41 | parse_mode="markdown",
42 | disable_web_page_preview=True
43 | )
44 | return 400
45 | else:
46 | return 500
47 |
--------------------------------------------------------------------------------
/helper_funcs/gdriveTools.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pathlib
3 | import pickle
4 | import time
5 | import urllib.parse as urlparse
6 | from urllib.parse import parse_qs
7 | import re
8 | import json
9 | import magic
10 | import requests
11 | import logging
12 | from google.auth.transport.requests import Request
13 | from google.oauth2 import service_account
14 | from google_auth_oauthlib.flow import InstalledAppFlow
15 | from googleapiclient.discovery import build
16 | from googleapiclient.errors import HttpError
17 | from googleapiclient.http import MediaFileUpload
18 | from tenacity import *
19 |
20 | from helper_funcs.bot_utils import setInterval
21 |
22 | LOGGER = logging.getLogger(__name__)
23 | logging.getLogger('googleapiclient.discovery').setLevel(logging.ERROR)
24 | SERVICE_ACCOUNT_INDEX = 0
25 | SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
26 | download_dict = {}
27 |
28 | # the secret configuration specific things
29 | from config import Config
30 |
31 |
32 | class GoogleDriveHelper:
33 | def __init__(self, name=None, listener=None):
34 | self.__G_DRIVE_TOKEN_FILE = "token.pickle"
35 | # Check https://developers.google.com/drive/scopes for all available scopes
36 | self.__OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive']
37 | # Redirect URI for installed apps, can be left as is
38 | self.__REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"
39 | self.__G_DRIVE_DIR_MIME_TYPE = "application/vnd.google-apps.folder"
40 | self.__G_DRIVE_BASE_DOWNLOAD_URL = "https://drive.google.com/uc?id={}&export=download"
41 | self.__G_DRIVE_DIR_BASE_DOWNLOAD_URL = "https://drive.google.com/drive/folders/{}"
42 | self.__listener = listener
43 | self.__service = self.authorize()
44 | self.__listener = listener
45 | self._file_uploaded_bytes = 0
46 | self.uploaded_bytes = 0
47 | self.UPDATE_INTERVAL = 5
48 | self.start_time = 0
49 | self.total_time = 0
50 | self._should_update = True
51 | self.is_uploading = True
52 | self.is_cancelled = False
53 | self.status = None
54 | self.updater = None
55 | self.name = name
56 | self.update_interval = 3
57 |
58 | def cancel(self):
59 | self.is_cancelled = True
60 | self.is_uploading = False
61 |
62 | def speed(self):
63 | """
64 | It calculates the average upload speed and returns it in bytes/seconds unit
65 | :return: Upload speed in bytes/second
66 | """
67 | try:
68 | return self.uploaded_bytes / self.total_time
69 | except ZeroDivisionError:
70 | return 0
71 |
72 | @staticmethod
73 | def getIdFromUrl(link: str):
74 | if "folders" in link or "file" in link:
75 | regex = r"https://drive\.google\.com/(drive)?/?u?/?\d?/?(mobile)?/?(file)?(folders)?/?d?/([-\w]+)[?+]?/?(w+)?"
76 | res = re.search(regex,link)
77 | if res is None:
78 | raise IndexError("GDrive ID not found.")
79 | return res.group(5)
80 | parsed = urlparse.urlparse(link)
81 | return parse_qs(parsed.query)['id'][0]
82 |
83 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
84 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
85 | def _on_upload_progress(self):
86 | if self.status is not None:
87 | chunk_size = self.status.total_size * self.status.progress() - self._file_uploaded_bytes
88 | self._file_uploaded_bytes = self.status.total_size * self.status.progress()
89 | LOGGER.debug(f'Uploading {self.name}, chunk size: {self.get_readable_file_size(chunk_size)}')
90 | self.uploaded_bytes += chunk_size
91 | self.total_time += self.update_interval
92 |
93 | def __upload_empty_file(self, path, file_name, mime_type, parent_id=None):
94 | media_body = MediaFileUpload(path,
95 | mimetype=mime_type,
96 | resumable=False)
97 | file_metadata = {
98 | 'name': file_name,
99 | 'description': 'mirror',
100 | 'mimeType': mime_type,
101 | }
102 | if parent_id is not None:
103 | file_metadata['parents'] = [parent_id]
104 | return self.__service.files().create(supportsTeamDrives=True,
105 | body=file_metadata, media_body=media_body).execute()
106 |
107 | def switchServiceAccount(self):
108 | global SERVICE_ACCOUNT_INDEX
109 | service_account_count = len(os.listdir("accounts"))
110 | if SERVICE_ACCOUNT_INDEX == service_account_count - 1:
111 | SERVICE_ACCOUNT_INDEX = 0
112 | SERVICE_ACCOUNT_INDEX += 1
113 | LOGGER.info(f"Switching to {SERVICE_ACCOUNT_INDEX}.json service account")
114 | self.__service = self.authorize()
115 |
116 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
117 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
118 | def __set_permission(self, drive_id):
119 | permissions = {
120 | 'role': 'reader',
121 | 'type': 'anyone',
122 | 'value': None,
123 | 'withLink': True
124 | }
125 | return self.__service.permissions().create(supportsTeamDrives=True, fileId=drive_id,
126 | body=permissions).execute()
127 |
128 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
129 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
130 | def upload_file(self, file_path, file_name, mime_type, parent_id):
131 | # File body description
132 | file_metadata = {
133 | 'name': file_name,
134 | 'description': 'mirror',
135 | 'mimeType': mime_type,
136 | }
137 | if parent_id is not None:
138 | file_metadata['parents'] = [parent_id]
139 |
140 | if os.path.getsize(file_path) == 0:
141 | media_body = MediaFileUpload(file_path,
142 | mimetype=mime_type,
143 | resumable=False)
144 | response = self.__service.files().create(supportsTeamDrives=True,
145 | body=file_metadata, media_body=media_body).execute()
146 | if not Config.IS_TEAM_DRIVE:
147 | self.__set_permission(response['id'])
148 |
149 | drive_file = self.__service.files().get(supportsTeamDrives=True,
150 | fileId=response['id']).execute()
151 | download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))
152 | return download_url
153 | media_body = MediaFileUpload(file_path,
154 | mimetype=mime_type,
155 | resumable=True,
156 | chunksize=50 * 1024 * 1024)
157 |
158 | # Insert a file
159 | drive_file = self.__service.files().create(supportsTeamDrives=True,
160 | body=file_metadata, media_body=media_body)
161 | response = None
162 | while response is None:
163 | if self.is_cancelled:
164 | return None
165 | try:
166 | self.status, response = drive_file.next_chunk()
167 | except HttpError as err:
168 | if err.resp.get('content-type', '').startswith('application/json'):
169 | reason = json.loads(err.content).get('error').get('errors')[0].get('reason')
170 | if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':
171 | if Config.USE_SERVICE_ACCOUNTS:
172 | self.switchServiceAccount()
173 | LOGGER.info(f"Got: {reason}, Trying Again.")
174 | return self.upload_file(file_path, file_name, mime_type, parent_id)
175 | else:
176 | raise err
177 | self._file_uploaded_bytes = 0
178 | # Insert new permissions
179 | if not Config.IS_TEAM_DRIVE:
180 | self.__set_permission(response['id'])
181 | # Define file instance and get url for download
182 | drive_file = self.__service.files().get(supportsTeamDrives=True, fileId=response['id']).execute()
183 | download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id'))
184 | return download_url
185 |
186 | def upload(self, file_path: str):
187 | url=None;
188 | if Config.USE_SERVICE_ACCOUNTS:
189 | self.service_account_count = len(os.listdir("accounts"))
190 | file_name = pathlib.PurePath(file_path).name
191 | LOGGER.info("Uploading File: " + file_path)
192 | self.start_time = time.time()
193 | self.updater = setInterval(self.update_interval, self._on_upload_progress)
194 | if os.path.isfile(file_path):
195 | try:
196 | mime_type = self.get_mime_type(file_path)
197 | link = self.upload_file(file_path, file_name, mime_type, Config.parent_id)
198 | if link is None:
199 | raise Exception('Upload has been manually cancelled')
200 | LOGGER.info("Uploaded To G-Drive: " + file_path)
201 | if Config.INDEX_URL is not None:
202 | url = requests.utils.requote_uri(f'{Config.INDEX_URL}/{file_name}')
203 | except Exception as e:
204 | if isinstance(e, RetryError):
205 | LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
206 | err = e.last_attempt.exception()
207 | else:
208 | err = e
209 | LOGGER.error(err)
210 | return
211 | finally:
212 | self.updater.cancel()
213 | else:
214 | try:
215 | dir_id = self.create_directory(os.path.basename(os.path.abspath(file_name)), Config.parent_id)
216 | result = self.upload_dir(file_path, dir_id)
217 | if result is None:
218 | raise Exception('Upload has been manually cancelled!')
219 | LOGGER.info("Uploaded To G-Drive: " + file_name)
220 | link = f"https://drive.google.com/folderview?id={dir_id}"
221 | except Exception as e:
222 | if isinstance(e, RetryError):
223 | LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
224 | err = e.last_attempt.exception()
225 | else:
226 | err = e
227 | LOGGER.error(err)
228 | self.__listener.onUploadError(str(err))
229 | return
230 | finally:
231 | self.updater.cancel()
232 | LOGGER.info(download_dict)
233 | LOGGER.info("Deleting downloaded file/folder..")
234 | return link,url
235 |
236 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
237 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
238 | def copyFile(self, file_id, dest_id):
239 | body = {
240 | 'parents': [dest_id]
241 | }
242 |
243 | try:
244 | res = self.__service.files().copy(supportsAllDrives=True,fileId=file_id,body=body).execute()
245 | return res
246 | except HttpError as err:
247 | if err.resp.get('content-type', '').startswith('application/json'):
248 | reason = json.loads(err.content).get('error').get('errors')[0].get('reason')
249 | if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded':
250 | if Config.USE_SERVICE_ACCOUNTS:
251 | self.switchServiceAccount()
252 | LOGGER.info(f"Got: {reason}, Trying Again.")
253 | return self.copyFile(file_id,dest_id)
254 | else:
255 | raise err
256 |
257 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
258 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
259 | def getFileMetadata(self,file_id):
260 | return self.__service.files().get(supportsAllDrives=True, fileId=file_id,
261 | fields="name,id,mimeType,size").execute()
262 |
263 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
264 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
265 | def getFilesByFolderId(self,folder_id):
266 | page_token = None
267 | q = f"'{folder_id}' in parents"
268 | files = []
269 | while True:
270 | response = self.__service.files().list(supportsTeamDrives=True,
271 | includeTeamDriveItems=True,
272 | q=q,
273 | spaces='drive',
274 | pageSize=200,
275 | fields='nextPageToken, files(id, name, mimeType,size)',
276 | pageToken=page_token).execute()
277 | for file in response.get('files', []):
278 | files.append(file)
279 | page_token = response.get('nextPageToken', None)
280 | if page_token is None:
281 | break
282 | return files
283 |
284 | def clone(self, link):
285 | self.transferred_size = 0
286 | try:
287 | file_id = self.getIdFromUrl(link)
288 | except (KeyError,IndexError):
289 | msg = "Google drive ID could not be found in the provided link"
290 | return msg
291 | msg = ""
292 | LOGGER.info(f"File ID: {file_id}")
293 | try:
294 | meta = self.getFileMetadata(file_id)
295 | if meta.get("mimeType") == self.__G_DRIVE_DIR_MIME_TYPE:
296 | dir_id = self.create_directory(meta.get('name'), Config.parent_id)
297 | result = self.cloneFolder(meta.get('name'), meta.get('name'), meta.get('id'), dir_id)
298 | msg += f'{meta.get("name")}' \
299 | f' ({self.get_readable_file_size(self.transferred_size)})'
300 | if Config.INDEX_URL is not None:
301 | url = requests.utils.requote_uri(f'{Config.INDEX_URL}/{meta.get("name")}/')
302 | msg += f' | Index URL'
303 | else:
304 | file = self.copyFile(meta.get('id'), Config.parent_id)
305 | msg += f'{file.get("name")}'
306 | try:
307 | msg += f' ({self.get_readable_file_size(int(meta.get("size")))}) '
308 | except TypeError:
309 | pass
310 | if Config.INDEX_URL is not None:
311 | url = requests.utils.requote_uri(f'{Config.INDEX_URL}/{file.get("name")}')
312 | msg += f' | Index URL'
313 | except Exception as err:
314 | if isinstance(err, RetryError):
315 | LOGGER.info(f"Total Attempts: {err.last_attempt.attempt_number}")
316 | err = err.last_attempt.exception()
317 | err = str(err).replace('>', '').replace('<', '')
318 | LOGGER.error(err)
319 | return err
320 | return msg
321 |
322 | def cloneFolder(self, name, local_path, folder_id, parent_id):
323 | LOGGER.info(f"Syncing: {local_path}")
324 | files = self.getFilesByFolderId(folder_id)
325 | new_id = None
326 | if len(files) == 0:
327 | return parent_id
328 | for file in files:
329 | if file.get('mimeType') == self.__G_DRIVE_DIR_MIME_TYPE:
330 | file_path = os.path.join(local_path, file.get('name'))
331 | current_dir_id = self.create_directory(file.get('name'), parent_id)
332 | new_id = self.cloneFolder(file.get('name'), file_path, file.get('id'), current_dir_id)
333 | else:
334 | try:
335 | self.transferred_size += int(file.get('size'))
336 | except TypeError:
337 | pass
338 | try:
339 | self.copyFile(file.get('id'), parent_id)
340 | new_id = parent_id
341 | except Exception as e:
342 | if isinstance(e, RetryError):
343 | LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
344 | err = e.last_attempt.exception()
345 | else:
346 | err = e
347 | LOGGER.error(err)
348 | return new_id
349 |
350 | @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5),
351 | retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG))
352 | def create_directory(self, directory_name, parent_id):
353 | file_metadata = {
354 | "name": directory_name,
355 | "mimeType": self.__G_DRIVE_DIR_MIME_TYPE
356 | }
357 | if parent_id is not None:
358 | file_metadata["parents"] = [parent_id]
359 | file = self.__service.files().create(supportsTeamDrives=True, body=file_metadata).execute()
360 | file_id = file.get("id")
361 | if not Config.IS_TEAM_DRIVE:
362 | self.__set_permission(file_id)
363 | LOGGER.info("Created Google-Drive Folder:\nName: {}\nID: {} ".format(file.get("name"), file_id))
364 | return file_id
365 |
366 | def upload_dir(self, input_directory, parent_id):
367 | list_dirs = os.listdir(input_directory)
368 | if len(list_dirs) == 0:
369 | return parent_id
370 | new_id = None
371 | for item in list_dirs:
372 | current_file_name = os.path.join(input_directory, item)
373 | if self.is_cancelled:
374 | return None
375 | if os.path.isdir(current_file_name):
376 | current_dir_id = self.create_directory(item, parent_id)
377 | new_id = self.upload_dir(current_file_name, current_dir_id)
378 | else:
379 | mime_type = self.get_mime_type(current_file_name)
380 | file_name = current_file_name.split("/")[-1]
381 | # current_file_name will have the full path
382 | self.upload_file(current_file_name, file_name, mime_type, parent_id)
383 | new_id = parent_id
384 | return new_id
385 |
386 | def authorize(self):
387 | # Get credentials
388 | credentials = None
389 | if not Config.USE_SERVICE_ACCOUNTS:
390 | if os.path.exists(self.__G_DRIVE_TOKEN_FILE):
391 | with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f:
392 | credentials = pickle.load(f)
393 | if credentials is None or not credentials.valid:
394 | if credentials and credentials.expired and credentials.refresh_token:
395 | credentials.refresh(Request())
396 | else:
397 | flow = InstalledAppFlow.from_client_secrets_file(
398 | 'credentials.json', self.__OAUTH_SCOPE)
399 | LOGGER.info(flow)
400 | credentials = flow.run_console(port=0)
401 |
402 | # Save the credentials for the next run
403 | with open(self.__G_DRIVE_TOKEN_FILE, 'wb') as token:
404 | pickle.dump(credentials, token)
405 | else:
406 | LOGGER.info(f"Authorizing with {SERVICE_ACCOUNT_INDEX}.json service account")
407 | credentials = service_account.Credentials.from_service_account_file(
408 | f'accounts/{SERVICE_ACCOUNT_INDEX}.json',
409 | scopes=self.__OAUTH_SCOPE)
410 | return build('drive', 'v3', credentials=credentials, cache_discovery=False)
411 |
412 | def escapes(self, str):
413 | chars = ['\\', "'", '"', r'\a', r'\b', r'\f', r'\n', r'\r', r'\t']
414 | for char in chars:
415 | str = str.replace(char, '\\'+char)
416 | return str
417 |
418 | def drive_list(self, fileName):
419 | msg = ""
420 | fileName = self.escapes(str(fileName))
421 | # Create Search Query for API request.
422 | query = f"'{Config.parent_id}' in parents and (name contains '{fileName}')"
423 | response = self.__service.files().list(supportsTeamDrives=True,
424 | includeTeamDriveItems=True,
425 | q=query,
426 | spaces='drive',
427 | pageSize=20,
428 | fields='files(id, name, mimeType, size)',
429 | orderBy='modifiedTime desc').execute()
430 | for file in response.get('files', []):
431 | if file.get(
432 | 'mimeType') == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File.
433 | msg += f"⁍ {file.get('name')}" \
434 | f" (folder)"
435 | if Config.INDEX_URL is not None:
436 | url = requests.utils.requote_uri(f'{Config.INDEX_URL}/{file.get("name")}/')
437 | msg += f' | Index URL'
438 | else:
439 | msg += f"⁍ {file.get('name')} ({self.get_readable_file_size(int(file.get('size')))})"
441 | if Config.INDEX_URL is not None:
442 | url = requests.utils.requote_uri(f'{Config.INDEX_URL}/{file.get("name")}')
443 | msg += f' | Index URL'
444 | msg += '\n'
445 | return msg
446 |
447 | def get_readable_file_size(self,size_in_bytes) -> str:
448 | if size_in_bytes is None:
449 | return '0B'
450 | index = 0
451 | while size_in_bytes >= 1024:
452 | size_in_bytes /= 1024
453 | index += 1
454 | try:
455 | return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}'
456 | except IndexError:
457 | return 'File too large'
458 |
459 | def get_mime_type(self,file_path):
460 | mime = magic.Magic(mime=True)
461 | mime_type = mime.from_file(file_path)
462 | mime_type = mime_type if mime_type else "text/plain"
463 | return mime_type
464 |
--------------------------------------------------------------------------------
/plugins/help_text.py:
--------------------------------------------------------------------------------
1 | # (c) Jigarvarma2005
2 |
3 | from translation import Translation
4 | from pyrogram import filters, Client as app
5 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
6 | from helper_funcs.fsub import handle_force_sub
7 |
8 | @app.on_message(filters.private & filters.command(["help", "about"]))
9 | async def help_user(bot, update):
10 | back = await handle_force_sub(bot, update)
11 | if back == 400:
12 | return
13 | HELP = Translation.HELP_USER.format(update.from_user.first_name, update.from_user.id)
14 | await bot.send_message(
15 | chat_id=update.chat.id,
16 | text=HELP,
17 | reply_markup=InlineKeyboardMarkup(
18 | [
19 | [
20 | InlineKeyboardButton("🚨Updates Channel🚨", url="https://t.me/Universal_Projects"),
21 | InlineKeyboardButton("👷Support Group👷", url="https://t.me/JV_Community")
22 | ],
23 | [
24 | InlineKeyboardButton("🧑💻Devloper🧑💻", url="https://t.me/Jigarvarma2005")
25 | ]
26 | ]
27 | ),
28 | parse_mode="markdown",
29 | disable_web_page_preview=True,
30 | reply_to_message_id=update.message_id
31 | )
32 |
33 |
34 |
35 | @app.on_message(filters.private & filters.command(["start"]))
36 | async def start(bot, update):
37 | back = await handle_force_sub(bot, update)
38 | if back == 400:
39 | return
40 | START = Translation.START_TEXT.format(update.from_user.first_name, update.from_user.id)
41 | await bot.send_message(
42 | chat_id=update.chat.id,
43 | text=START,
44 | reply_markup=InlineKeyboardMarkup(
45 | [
46 | [
47 | InlineKeyboardButton("🚨Updates Channel🚨", url="https://t.me/Universal_Projects"),
48 | InlineKeyboardButton("👷Support Group👷", url="https://t.me/JV_Community")
49 | ],
50 | [
51 | InlineKeyboardButton("🧑💻Devloper🧑💻", url="https://t.me/Jigarvarma2005")
52 | ]
53 | ]
54 | ),
55 | parse_mode="markdown",
56 | disable_web_page_preview=True,
57 | reply_to_message_id=update.message_id,
58 | )
59 |
60 |
61 |
--------------------------------------------------------------------------------
/plugins/tg_to_gdrive.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pathlib
3 | import time
4 | import pyrogram
5 | from bot import logger
6 | from helper_funcs import gdriveTools
7 | from helper_funcs.bot_utils import *
8 | from helper_funcs.display_progress import progress_for_pyrogram
9 | from translation import Translation
10 | from datetime import datetime
11 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
12 | from pyrogram import Client as app
13 | from config import Config
14 | from helper_funcs.fsub import handle_force_sub
15 |
16 | @app.on_message(pyrogram.filters.private & (pyrogram.filters.document | pyrogram.filters.video))
17 | async def tg_to_gdrive_upload(bot, update):
18 | back = await handle_force_sub(bot, update)
19 | if back == 400:
20 | return
21 | download_location = Config.DOWNLOAD_LOCATION + "/"
22 | reply_message = await bot.send_message(
23 | chat_id=update.chat.id,
24 | text=Translation.DOWNLOAD_START,
25 | reply_to_message_id=update.message_id
26 | )
27 | c_time = time.time()
28 | try:
29 | the_real_download_location = await bot.download_media(
30 | message=update,
31 | file_name=download_location,
32 | progress=progress_for_pyrogram,
33 | progress_args=(
34 | Translation.DOWNLOAD_START,
35 | reply_message,
36 | c_time
37 | )
38 | )
39 | except Exception as e:
40 | logger.error(str(e))
41 | pass
42 | if the_real_download_location is None:
43 | return await reply_message.edit_text("File Download Failed")
44 | else:
45 | try:
46 | await bot.edit_message_text(
47 | text=Translation.SAVED_RECVD_DOC_FILE,
48 | chat_id=update.chat.id,
49 | message_id=reply_message.message_id
50 | )
51 | except:
52 | pass
53 | download_directory = the_real_download_location
54 | if os.path.exists(download_directory):
55 | up_name = pathlib.PurePath(download_directory).name
56 | size = get_readable_file_size(get_path_size(download_directory))
57 | try:
58 | await bot.edit_message_text(
59 | text="📥Download Completed!!!\nNow Generating 🎬streaming 🔗links.",
60 | chat_id=reply_message.chat.id,
61 | message_id=reply_message.message_id
62 | )
63 | except Exception as e:
64 | logger.error(str(e))
65 | pass
66 | logger.info(f"Upload Name : {up_name}")
67 | drive = gdriveTools.GoogleDriveHelper(up_name)
68 | gd_url, index_url = drive.upload(download_directory)
69 | uri = str_to_b64(index_url)
70 | url = f"https://{Config.VIDEO_PLAYER_URL}/play?id={uri}"
71 | button_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="Play On Website", url=url)]])
72 | await bot.send_message(
73 | text=f"Streaming link Generated \n\nFile: {up_name} \n\nSize: {size}\n\nLink:{url}",
74 | chat_id=update.chat.id,
75 | reply_to_message_id=update.message_id,
76 | disable_web_page_preview=True,
77 | reply_markup=button_markup)
78 | try:
79 | os.remove(download_directory)
80 | except:
81 | pass
82 | await reply_message.delete()
83 |
--------------------------------------------------------------------------------
/plugins/utils.py:
--------------------------------------------------------------------------------
1 | # (c) Jigarvarma2005
2 |
3 | from helper_funcs.bot_utils import *
4 | from config import Config
5 | import time
6 | from bot import botStartTime
7 | import pyrogram
8 | import shutil, psutil
9 | from pyrogram import Client as app
10 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
11 | from helper_funcs.fsub import handle_force_sub
12 |
13 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["stats","status"]))
14 | async def stats(bot, update):
15 | back = await handle_force_sub(bot, update)
16 | if back == 400:
17 | return
18 | currentTime = readable_time((time.time() - botStartTime))
19 | total, used, free = shutil.disk_usage('.')
20 | total = get_readable_file_size(total)
21 | used = get_readable_file_size(used)
22 | free = get_readable_file_size(free)
23 | sent = get_readable_file_size(psutil.net_io_counters().bytes_sent)
24 | recv = get_readable_file_size(psutil.net_io_counters().bytes_recv)
25 | cpuUsage = psutil.cpu_percent(interval=0.5)
26 | memory = psutil.virtual_memory().percent
27 | disk = psutil.disk_usage('/').percent
28 | botstats = f'Bot Uptime: {currentTime}\n' \
29 | f'Total disk space: {total}\n' \
30 | f'Used: {used} ' \
31 | f'Free: {free}\n\n' \
32 | f'📊Data Usage📊\nUpload: {sent}\n' \
33 | f'Down: {recv}\n\n' \
34 | f'CPU: {cpuUsage}% ' \
35 | f'RAM: {memory}% ' \
36 | f'Disk: {disk}%'
37 | await update.reply_text(botstats)
38 |
39 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["brightcove"]))
40 | async def brightcove(bot, update):
41 | back = await handle_force_sub(bot, update)
42 | if back == 400:
43 | return
44 | msg = "Now send me BrightCove video id"
45 | uri = await input_str(bot, update,msg)
46 | if uri == 404:
47 | return
48 | uri = f"https://{Config.VIDEO_PLAYER_URL}/brightcove?id=" + uri
49 | await update.reply_text(text="Use the below url to stream in website",
50 | reply_markup=InlineKeyboardMarkup(
51 | [[
52 | InlineKeyboardButton("Stream", url=uri)
53 | ]]
54 | ))
55 |
56 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["jw"]))
57 | async def jwplayer_(bot, update):
58 | back = await handle_force_sub(bot, update)
59 | if back == 400:
60 | return
61 | msg = "Now send me JW Player video id"
62 | uri = await input_str(bot, update,msg)
63 | if uri == 404:
64 | return
65 | uri = f"https://{Config.VIDEO_PLAYER_URL}/jw?id=" + uri
66 | await update.reply_text(text="Use the below url to stream in website",
67 | reply_markup=InlineKeyboardMarkup(
68 | [[
69 | InlineKeyboardButton("Stream", url=uri)
70 | ]]
71 | ))
72 |
73 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["yt"]))
74 | async def yt__(bot, update):
75 | back = await handle_force_sub(bot, update)
76 | if back == 400:
77 | return
78 | msg = "Now send me YouTube video id or URL"
79 | uri = await input_str(bot, update,msg)
80 | if uri == 404:
81 | return
82 | uri = f"https://{Config.VIDEO_PLAYER_URL}/yt?id=" + uri
83 | await update.reply_text(text="Use the below url to stream in website",
84 | reply_markup=InlineKeyboardMarkup(
85 | [[
86 | InlineKeyboardButton("Stream", url=uri)
87 | ]]
88 | ))
89 |
90 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["m3u8"]))
91 | async def m3u8_(bot, update):
92 | back = await handle_force_sub(bot, update)
93 | if back == 400:
94 | return
95 | msg = "Now send me m3u8 URL"
96 | uri = await input_str(bot, update,msg)
97 | if uri == 404:
98 | return
99 | uri = f"https://{Config.VIDEO_PLAYER_URL}/m3u8?id=" + uri
100 | await update.reply_text(text="Use the below url to stream in website",
101 | reply_markup=InlineKeyboardMarkup(
102 | [[
103 | InlineKeyboardButton("Stream", url=uri)
104 | ]]
105 | ))
106 |
107 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["mpd"]))
108 | async def mpd_(bot, update):
109 | back = await handle_force_sub(bot, update)
110 | if back == 400:
111 | return
112 | msg = "Now send me mpd URL"
113 | uri = await input_str(bot, update,msg)
114 | if uri == 404:
115 | return
116 | uri = f"https://{Config.VIDEO_PLAYER_URL}/mpd?id=" + uri
117 | await update.reply_text(text="Use the below url to stream in website",
118 | reply_markup=InlineKeyboardMarkup(
119 | [[
120 | InlineKeyboardButton("Stream", url=uri)
121 | ]]
122 | ))
123 |
124 | @app.on_message(pyrogram.filters.private & pyrogram.filters.command(["play"]))
125 | async def direct_player_(bot, update):
126 | back = await handle_force_sub(bot, update)
127 | if back == 400:
128 | return
129 | msg = "Now send me Direct Video URL"
130 | uri = await input_str(bot, update,msg)
131 | if uri == 404:
132 | return
133 | uri = f"https://{Config.VIDEO_PLAYER_URL}/play?id=" + uri
134 | await update.reply_text(text="Use the below url to stream in website",
135 | reply_markup=InlineKeyboardMarkup(
136 | [[
137 | InlineKeyboardButton("Stream", url=uri)
138 | ]]
139 | ))
140 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | hachoir
2 | numpy
3 | asyncio
4 | Pillow
5 | pyrogram==1.0.7
6 | requests
7 | tgcrypto
8 | google-api-python-client>=1.7.11,<1.7.20
9 | google-auth-httplib2>=0.0.3,<0.1.0
10 | google-auth-oauthlib>=0.4.1,<0.10.0
11 | tenacity>=6.0.0
12 | python-magic
13 | psutil
14 | pyromod
15 | wget
--------------------------------------------------------------------------------
/translation.py:
--------------------------------------------------------------------------------
1 | class Translation(object):
2 | START_TEXT = """Hey [{}](tg://user?id={}), I am Video Streaming Link Generator Bot,
3 |
4 | check /help to know more."""
5 | DOWNLOAD_START = "📥Downloading📥"
6 | UPLOAD_START = "📤Uploading📤"
7 | HELP_USER = """Hey [{}](tg://user?id={}), I am Video Streaming Link Generator Bot,
8 |
9 | /jw - Stream any JWPlayer video .
10 | /brightcove - Stream any BrightCove video.
11 | /yt - Stream any youtube video.
12 | /play - stream any video with direct link.
13 | /m3u8 - Stream any m3u8 link.
14 | /mpd - Stream any mpd link.
15 | send media - Stream telegram files in Website.
16 | /status - Check bot usage.
17 | """
--------------------------------------------------------------------------------