├── .gitignore
├── LICENSE
├── README.org
├── __init__.py
├── cfiles
├── Makefile
├── plugin.c
└── readstatus.c
├── commands.py
├── config.py
├── debug_shell.py
├── extras
├── plot.png
├── process.py
└── visualize.py
├── ggshell.py
├── notification.py
├── outputs.py
├── players
├── README.org
├── __init__.py
└── mpv.py
├── requirements.txt
├── screenshots
├── help1.png
├── help2.png
├── history.png
├── info.png
├── log.png
├── number.png
├── others.png
├── recent.png
├── track.png
└── watch.png
├── shell.conf
├── sources
├── README.org
├── __init__.py
├── gogoanime.py
└── url-to-videos.sh
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # environments
2 | venv
3 | .venv
4 | .env
5 |
6 | # Compiled files
7 | __pycache__
8 | *.o
9 | *.so
10 |
11 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | * Anime Helper Shell [play/stream/download temporarily fixed]
2 |
3 | Since I was tired of searching for different websites and different animes to watch. And wanted my player to remember what I watched without having to depend on yet another website.
4 |
5 | I created this solution. It's not super useful, or the best, but it works fine for me.
6 |
7 |
8 | * NOTE:
9 | It may stop working all of a sudden one day if the site goes down, so I can't guarantee till when it'll work.
10 |
11 | In such cases:
12 |
13 | ~play~, ~download~, ~continue~ commands won't work because of changes in the gogoanime website which was the only source for now. You can try to fix it by changing the website link in ~sources/gogoanime.py~ file or some other logic in that module.
14 |
15 | I have added a ~web~ & ~webcontinue~ command to browse the episode page and watch it in the browser in such cases.
16 |
17 | If I find some other sources which are easier to get the videos from I'll update it.
18 |
19 | I also found recently another CLI interface known as [[https://github.com/pystardust/ani-cli][ani-cli]] that has the functionality of ~play~ and ~download~ commands from here (probably more), and have used a small script from there to patch the problem for now, but it might not last long without other people to contribute. My understanding of networking is pretty low so I can't always track down how to reach the source videos to stream.
20 |
21 | * Disclaimer
22 | I do not own the videos or the right to distribute the videos which can be accessed through this program. It is just a helper program created for personal purposes and is like a terminal api for gogoanime site to ease the access as well as add the functionality of recording the watched animes and updates.
23 |
24 | * Installation (Linux & Mac OS)
25 | Clone this repository.
26 | #+begin_src bash
27 | git clone https://github.com/Atreyagaurav/anime-helper-shell.git && cd anime-helper-shell
28 | #+end_src
29 |
30 | Install the requirements.
31 |
32 | #+begin_src bash
33 | pip install -r requirements.txt
34 | #+end_src
35 |
36 | Make the ~ggshell.py~ executable and then symlink it to ~/usr/local/bin~ or other ~bin~ directory.
37 | #+begin_src bash
38 | chmod +x ggshell.py
39 | ln -s /usr/local/bin/ggshell.py
40 | #+end_src
41 |
42 | If the anime folder doesn't already exist in your home directory "~/" then create one, and move the shell.conf file into there.
43 | #+begin_src bash
44 | mkdir ~/anime
45 | #+end_src
46 |
47 | #+begin_src bash
48 | cp shell.conf ~/anime
49 | #+end_src
50 |
51 |
52 | Be sure to edit the ~config.py~ to change the ~ext_media_command~ variable if you use other players than ~mpv~, and change the ~anime_dir~ to the place you want to store your anime.
53 |
54 | By defaults it makes ~anime~ directory in your home and stores it there.
55 | You can symlink your anime storage directory to home too.
56 |
57 | * Usages
58 | ** Supported devices
59 | Till now it works on (tested only on these; can probably work on others too):
60 |
61 | Arch Linux; Windows 10 & Termux android app.
62 |
63 | But the notify command doesn't work on windows and termux because of issue with availability of dbus.
64 |
65 | ** Basic Usages
66 | - Watch anime from online stream
67 | - Download anime for offline watch
68 | - Search anime from keywords
69 | - Automatic/manual record list of watched anime
70 | - Continue from where you left off (episode wise not time of the episode)
71 | - Keep track of ongoing anime
72 |
73 | - Other utilities:
74 | * get notification on updates (notify command - UNIX only)
75 | * use shell commands with ! (e.g. !clear)
76 |
77 | ** Usage instructions
78 | Some examples are on [[*Screenshots][Screenshots]] section.
79 |
80 | Assuming you have symlinked the ~ggshell.py~ to ~/use/bin/gogoanime~. Look at [[*Installation][Installation]] for more detail on this.
81 |
82 | For interactive shell, run ~python ggshell.py~, or ~ggshell.py~ (if you made it executable), or ~gogoanime~ (if you symlinked to this name).
83 |
84 | After that you can enter the commands in the shell; type ~help~ on overall help, and ~help command~ for specific help on some command. The help is not that detailed for each command for now, but I have tried to write what the command does.
85 |
86 | To run shell commands like ~clear~ use ~shell command~ syntax or ~!command~ syntax, where the command is the shell command you want to execute. (not tested in windows).
87 |
88 | For single use pass the command & arguments as command line arguments:
89 | #+begin_src bash
90 | gogoanime play one-piece
91 | #+end_src
92 | ** Interactive shell
93 | *** inputs
94 | The interactive shell is written in python and [[https://www.man7.org/linux/man-pages/man3/readline.3.html][readline]] is used to get the input, hence supports emacs like keybindings. like C-r for reverse search of commands, and others, look at readline manual for other info on this. ~!man readline~ on interactive shell or ~man readline~ on bash.
95 |
96 | *** Autocomplete
97 | Auto-Completion is supported but it used the log list and cache list (previous search result) for completion of most commands so at the beginning there won't be much. Try searching animes then using the key to autocomplete. As you use more and enter the animes on logs the autocomplete becomes more usable.
98 |
99 | Autocomplete for commands like help/ fullscreen/ quality etc doesn't depend on those so are usable from the start.
100 |
101 | ** Debug Shell for developers
102 | If you are familiar with python, now only can you edit the code, you can also use the debug shell to test the code, the history won't be updated on this shell. You can use it just like python REPL but has the necessary modules preloaded for debugging purposes.
103 |
104 | You can use the ~shell~ command or ~!~ at the beginning to run that command in ggshell but unlike there you can look at the error and analyze the problem here.
105 |
106 | This is still a prototype so it isn't very good.
107 |
108 | ** Mpv Plugin
109 | There is a cfiles folder with c codes for mpv plugin and status checking program, both can be compiled with ~make~ and installed with ~make install~.
110 | Just update the path macros on the C files and then compile with make (I don't know how to make that automatic with make right now - help will be appreciated.)
111 |
112 | There are some scripts in ~extras~ folders, which can be used to visualize the log from these plugins.
113 |
114 | The ~process.py~ processes the log and ~visualize.py~ is for visualization. Here is an example plots.
115 |
116 | [[./extras/plot.png]]
117 |
118 | The gaps in the plot with no anime watchtime isn't me being responsible but rather the time it was broke and I was watching it in the browser.
119 |
120 | * Known Bugs
121 | - Sometimes the input has residue texts from long command lines.
122 | - Sometimes the mpv can't stream the stream link obtained with 403: Forbidden error.
123 | - The quality selection doesn't work unless the upstream provides m3u8 file.
124 | - Debug shell is a prototype and has glitches.
125 | * Future plans
126 | - Quality selection
127 | - Import watched logs from myanimelist.(dropped)
128 | - Choose the source for the video
129 | * Screenshots
130 |
131 | Latest episode updates from home page:
132 |
133 | ~NEW~ and ~WATCHED~ tags are shown for animes on the tracklist.
134 |
135 | [[./screenshots/recent.png]]
136 |
137 | Searching and getting info on anime:
138 |
139 | [[./screenshots/info.png]]
140 |
141 | getting info from search list.
142 |
143 | [[./screenshots/number.png]]
144 |
145 |
146 | Watching anime:
147 |
148 | [[./screenshots/watch.png]]
149 |
150 | Logs on watched anime/episodes:
151 |
152 | [[./screenshots/log.png]]
153 |
154 |
155 | Adjustments:
156 | Geometry and fullscreen for player. Quality for stream/download.
157 |
158 | [[./screenshots/others.png]]
159 |
160 | Tracking an anime, and getting updates:
161 |
162 | [[./screenshots/track.png]]
163 |
164 | Commands history:
165 |
166 | You can use UP arrow key to get old commands, or use Ctrl+r to do reverse search (not tested in windows).
167 |
168 | [[./screenshots/history.png]]
169 |
170 | help command:
171 |
172 | [[./screenshots/help1.png]]
173 |
174 | [[./screenshots/help2.png]]
175 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | """Command Line Interface for anime available in gogoanime website.
2 |
3 | Usage:
4 | - One time usage:
5 | ggshell.py COMMAND [ANIME-NAME] [RANGE]
6 | - Shell usage:
7 | COMMAND [ANIME-NAME] [RANGE]
8 |
9 | Launching with no arguments will launch an interactive interface.
10 |
11 | COMMAND - Command to execute, see details below for available commands.
12 | ANIME-NAME - Name of the anime or url or choice number.
13 | It must be same as the name on gogoanime address bar unless
14 | you are searching anime, or using the results from search.
15 | If you exclude this argument, the first choice from last
16 | listed animes or the anime last played/downloaded will
17 | be used. (first line of anime cachefile)
18 | You can put a choice number starting from 0 if you want to
19 | choose any anime from last anime lists. Like from results
20 | of 'search' command.
21 | RANGE - Range of the episodes; defaults to all episodes if not
22 | specified.
23 | For 'continue' command, defaults to unwatched episodes.
24 |
25 | AVAILABLE COMMANDS:
26 | help - Display this message.
27 | debug - Launch the debug shell.
28 | url - Download the video from provided URL.
29 | download - Download specified anime(episodes).
30 | check - Check if specified anime(episodes) has missing episodes files.
31 | Do not use this when simple commands like tree or ls can give
32 | you information as this command checks the files online.
33 | list - Just list the available episodes range.
34 | play - Play the episodes in mpv.
35 | continue - Continue playing given anime from your last watch.
36 | search - Search the anime list from given name/keywords.
37 | info - Get the information about the anime.
38 | log - print the log. Regex for filtering the log can be given as an
39 | argument.
40 | watched - Add the episodes as watched in log, if you watched them elsewhere.
41 | track - Put the anime on track list .
42 | updates - See if any anime on the track list have updates on new episodes.
43 | notify - Get the updates in notification, good for scheduled check.
44 |
45 | Example Usage:
46 | check one-piece 1-10
47 | download one-piece 1-2,5
48 | info one-piece
49 | search "One Piece Movie"
50 | list https://gogoanime.so/category/one-piece
51 | url https://gogoanime.so/one-piece-episode-1
52 | """
53 |
--------------------------------------------------------------------------------
/cfiles/Makefile:
--------------------------------------------------------------------------------
1 | # I'm just learning Makefiles so I don't know if I'm doing the things
2 | # as per standards/best practices. Suggestions will be appreciated.
3 | CC = gcc
4 | CFLAGS = -Wall
5 | LIBS = -lmpv
6 | PLUGFLAGS = -shared -fPIC
7 | OBJ = readstatus.o
8 | CONFIG = --cflags mpv --libs libnotify
9 |
10 | all: mpvstatus plugin
11 |
12 | %.o: %.c $(DEPS)
13 | $(CC) $(CFLAGS) $(LIBS) -c -o $@ $<
14 |
15 | mpvstatus: $(OBJ)
16 | gcc $(CFLAGS) -o $@ $^
17 |
18 | clean:
19 | -rm *.o *.so mpvstatus
20 |
21 | plugin: plugin.c
22 | $(CC) -o $@.so $< `pkg-config $(CONFIG)` $(PLUGFLAGS)
23 |
24 | install:
25 | -sudo cp mpvstatus /usr/local/bin/
26 | -cp plugin.so ~/.config/mpv/scripts
27 |
28 | uninstall:
29 | -sudo rm /usr/local/bin/mpvstatus
30 | -rm ~/.config/mpv/scripts/plugin.so
31 |
--------------------------------------------------------------------------------
/cfiles/plugin.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | #include
7 | #include
8 | #include
9 |
10 | #include
11 | #include
12 | #include
13 |
14 | #define INFO_DIR "/tmp/mpvinfo/"
15 | #define LOGGING_OFF 0 /* change it to 1 to turn off logging */
16 | #define LOG_FILE "/home/gaurav/.log/mpv.log"
17 |
18 | #define MAX_CHAR 50
19 |
20 | struct status {
21 | char *fname;
22 | double cur, dur, perc;
23 | } st = {.fname=NULL};
24 |
25 |
26 | void write_time(FILE *fp, int time_sec){
27 | if (time_sec < 60*60){
28 | fprintf(fp, "%02d:%02d", time_sec/60, time_sec % 60);
29 | }else{
30 | fprintf(fp, "%d:%02d:%02d", time_sec/3600 ,(time_sec%3600)/60, time_sec % 60);
31 | }
32 | }
33 |
34 | void shorten_string(char *str, int len){
35 | int total;
36 | total = strlen(str);
37 | if(total < len){
38 | return;
39 | }
40 | int i, pre, post;
41 | pre = len * 3 / 4;
42 | post = len - pre - 3;
43 | for(i=0; i<3; i++){
44 | *(str+pre+i)= '.';
45 | }
46 | strcpy(str+pre+3,str+total-post);
47 | }
48 |
49 | void info_filename(int number, char *dest){
50 | strcpy(dest, INFO_DIR);
51 | /* Max Pid for 64bit = 4194304 */
52 | char count[8];
53 | int i;
54 | count[7] = '\0';
55 | for(i=6;i>=0;i--){
56 | count[i] = number % 10 + '0';
57 | number /= 10;
58 | }
59 | int l = strlen(dest);
60 | if (*(dest+l-1) == '/'){
61 | strcpy(dest+l,count);
62 | }else{
63 | *(dest+l) = '/';
64 | strcpy(dest+l+1, count);
65 | }
66 | }
67 |
68 | void new_info_file(char *filename){
69 | info_filename(getpid(), filename);
70 | return;
71 |
72 | /* This used to set filenames on increasing number. */
73 | /* int i = 1; */
74 | /* while (1){ */
75 | /* info_filename(i++, filename); */
76 | /* if (access(filename, F_OK) == 0){ */
77 | /* continue; */
78 | /* } */
79 | /* return; */
80 | /* } */
81 | }
82 |
83 |
84 | void read_status(mpv_handle * handle){
85 | if (st.fname != NULL) mpv_free(st.fname);
86 | mpv_get_property(handle, "media-title", MPV_FORMAT_STRING, &(st.fname));
87 | mpv_get_property(handle, "time-pos", MPV_FORMAT_DOUBLE, &(st.cur));
88 | mpv_get_property(handle, "duration", MPV_FORMAT_DOUBLE, &(st.dur));
89 | mpv_get_property(handle, "percent-pos", MPV_FORMAT_DOUBLE, &(st.perc));
90 | }
91 |
92 |
93 | void write_status(char *filename, mpv_handle *handle){
94 | FILE *fp;
95 | /* char fname[MAX_CHAR+1]; */
96 | /* shorten_string(st.fname, MAX_CHAR); */
97 | fp = fopen(filename, "w");
98 | fprintf(fp,"%s\n TIME:",st.fname);
99 | write_time(fp, (int)st.cur);
100 | fprintf(fp," of ");
101 | write_time(fp, (int)st.dur);
102 | fprintf(fp,"(%.2f%%)\n", st.perc);
103 | fclose(fp);
104 | }
105 |
106 | void send_notification(NotifyNotification *n){
107 | notify_notification_update(n, "New Media Start", st.fname, NULL);
108 | notify_notification_show(n, NULL);
109 | }
110 |
111 | void clear_status(char *filename) {
112 | remove(filename);
113 | }
114 |
115 | void write_log(const char *action){
116 | if (LOGGING_OFF) return;
117 | FILE *fp;
118 | time_t t1;
119 | t1 = time(NULL);
120 | fp = fopen(LOG_FILE, "a");
121 | fprintf(fp, "%ld %s ",t1,action);
122 | write_time(fp, (int)st.cur);
123 | fprintf(fp, " ");
124 | write_time(fp, (int)st.dur);
125 | fprintf(fp," %s\n",st.fname);
126 | fclose(fp);
127 | }
128 |
129 | void init_plugin(mpv_handle *handle, char *filename, NotifyNotification **n){
130 | mkdir(INFO_DIR, 0700);
131 | new_info_file(filename);
132 | printf("Status Update file: %s\n", filename);
133 | if (!LOGGING_OFF) printf("Log file: %s\n", LOG_FILE);
134 | mpv_observe_property(handle, 0, "playback-time", MPV_FORMAT_DOUBLE);
135 | mpv_observe_property(handle, 0, "pause", MPV_FORMAT_FLAG);
136 | notify_init("MPV");
137 | *n = notify_notification_new("Init", NULL, NULL);
138 | notify_notification_set_urgency(*n, NOTIFY_URGENCY_LOW);
139 | }
140 |
141 | void exit_plugin(mpv_handle *handle, char *filename, NotifyNotification *n) {
142 | clear_status(filename);
143 | g_object_unref(G_OBJECT(n));
144 | notify_uninit();
145 | }
146 |
147 | int handle_event(mpv_handle *handle, mpv_event *event, char *filename, NotifyNotification *n, int *started, int *on_seek){
148 | mpv_event_property *prop;
149 | switch (event->event_id){
150 | case MPV_EVENT_SHUTDOWN:
151 | return 0;
152 | break;
153 | case MPV_EVENT_FILE_LOADED:
154 | *started = 1;
155 | read_status(handle);
156 | send_notification(n);
157 | write_log(mpv_event_name(event->event_id));
158 | break;
159 | case MPV_EVENT_END_FILE:
160 | if (*started==0) return 1;
161 | *started = 0;
162 | write_log(mpv_event_name(event->event_id));
163 | break;
164 | case MPV_EVENT_SEEK:
165 | if (*on_seek) return 1;
166 | *on_seek = 1;
167 | write_log(mpv_event_name(event->event_id));
168 | break;
169 | case MPV_EVENT_PLAYBACK_RESTART:
170 | if (*on_seek == 0) return 1;
171 | *on_seek = 0;
172 | read_status(handle);
173 | write_log(mpv_event_name(event->event_id));
174 | break;
175 | case MPV_EVENT_PROPERTY_CHANGE:
176 | prop = (mpv_event_property *)event->data;
177 | if (strcmp(prop->name, "playback-time") == 0) {
178 | read_status(handle);
179 | write_status(filename, handle);
180 | }else if (strcmp(prop->name, "pause") == 0) {
181 | if (*started) write_log(*(int*)prop->data ? "pause":"unpause");
182 | }
183 | break;
184 | default:
185 | break;
186 | }
187 | return 1;
188 | }
189 |
190 |
191 | int mpv_open_cplugin(mpv_handle *handle)
192 | {
193 | char filename[128];
194 | int flag;
195 | int on_seek = 0, started = 0;
196 | NotifyNotification *n;
197 | init_plugin(handle, filename, &n);
198 | do{
199 | mpv_event *event = mpv_wait_event(handle, -1);
200 | flag = handle_event(handle, event, filename, n, &started, &on_seek);
201 | }while (flag);
202 | exit_plugin(handle, filename, n);
203 | return 0;
204 | }
205 |
206 |
--------------------------------------------------------------------------------
/cfiles/readstatus.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #define INFO_DIR "/tmp/mpvinfo/"
9 | #define MAX_COL 50
10 |
11 | void join_path(parent, child, dest)
12 | char *parent, *child, *dest;{
13 | strcpy(dest, parent);
14 | int l = strlen(dest);
15 | if (*(dest+l-1) == '/'){
16 | strcpy(dest+l, child);
17 | }else{
18 | *(dest+l) = '/';
19 | strcpy(dest+l+1, child);
20 | }
21 | }
22 |
23 | int main(int argc, char *argv[])
24 | {
25 | DIR *dir;
26 | FILE *fp;
27 | char fullpath[128], c;
28 | struct dirent *file;
29 | if (access(INFO_DIR, F_OK)!=0){
30 | printf("No MPV instances.\n");
31 | return 0;
32 | }
33 | int count = 0, col, pid;
34 | dir = opendir(INFO_DIR);
35 | while ((file = readdir(dir)) != NULL){
36 | if(file->d_name[0]=='.'){
37 | continue;
38 | }
39 | join_path(INFO_DIR, file->d_name, fullpath);
40 |
41 | /* check if the instance is still running. */
42 | pid = atoi(file->d_name);
43 | if (kill(pid, 0)){
44 | remove(fullpath);
45 | continue;
46 | }
47 | count++;
48 | fp = fopen(fullpath, "r");
49 | printf("(%d) ", pid);
50 | col=0;
51 | while ((c=getc(fp))!=EOF){
52 | col++;
53 | if (c=='\n') col=0;
54 | if (col > MAX_COL){
55 | fputc('\n', stdout);
56 | fputc('\t', stdout);
57 | col = 0;
58 | }
59 | fputc(c, stdout);
60 | }
61 | }
62 | if (count==0){
63 | printf("No MPV instances.\n");
64 | }
65 | return 0;
66 | }
67 |
--------------------------------------------------------------------------------
/commands.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import re
4 | import time
5 | import html2text
6 | import webbrowser
7 |
8 | import config
9 | import utils
10 | import outputs
11 | import notification
12 |
13 | import players
14 | import sources
15 |
16 |
17 | player_module = getattr(players, config.ext_player)
18 | player_module.compile_command(
19 | flags=config.ext_player_flags,
20 | fullscreen=config.ext_player_fullscreen
21 | )
22 | anime_source_module = getattr(sources, config.anime_source)
23 |
24 |
25 | def set_quality(quality):
26 | if quality.isnumeric():
27 | config.video_quality = int(quality)
28 | elif quality.isalnum():
29 | if re.match(r"[0-9]+p", quality):
30 | config.video_quality = int(quality[:-1])
31 | else:
32 | outputs.prompt_val("Invalid quality format", quality, "error")
33 | else:
34 | outputs.normal_info(f"Current quality: {quality}")
35 |
36 |
37 | def toggle_fullscreen(value):
38 | if value.lower() in ["on", "yes", "true"]:
39 | config.ext_player_fullscreen = True
40 | player_module.compile_command(
41 | flags=config.ext_player_flags,
42 | fullscreen=True
43 | )
44 | elif value.lower() in ["off", "no", "false"]:
45 | config.ext_player_fullscreen = False
46 | player_module.compile_command(
47 | flags=config.ext_player_flags,
48 | fullscreen=False
49 | )
50 | else:
51 | outputs.prompt_val("Incorrect Argument", value, "error")
52 | outputs.prompt_val("External Player command",
53 | player_module.get_player_command())
54 |
55 |
56 | def set_geometry(value):
57 | if re.match(r"^([0-9]+-?)+$", value):
58 | player_module.set_geometry(value)
59 | player_module.compile_command(
60 | flags=config.ext_player_flags,
61 | fullscreen=config.ext_player_fullscreen
62 | )
63 | else:
64 | outputs.prompt_val("Incorrect Argument", value, "error")
65 | outputs.prompt_val("External Player command",
66 | player_module.get_player_command())
67 |
68 |
69 | def anime_log(args):
70 | log_args = dict()
71 | if len(args) == 0:
72 | pass
73 | elif args[0].isnumeric():
74 | log_args["number"] = int(args[0])
75 | else:
76 | log_args["pattern"] = re.compile(args[0])
77 | if len(args) == 2:
78 | log_args["number"] = int(args[1])
79 | logs = utils.read_log(**log_args)
80 | ongoing = utils.read_log(logfile=config.ongoingfile)
81 | if len(logs) == 0:
82 | if len(args) == 0:
83 | outputs.warning_info("No log entries found.")
84 | else:
85 | outputs.prompt_val("Log entries not found for arguments", args[0],
86 | "error")
87 | return
88 | outputs.bold_info("Watched\t\tAnime Name")
89 | for k, log in logs.items():
90 | outputs.normal_info(utils.Log(log).show(), end=" ")
91 | if k in ongoing:
92 | outputs.warning_tag("TRACKED", end="")
93 | outputs.normal_info()
94 |
95 |
96 | def check_canon(args):
97 | name, episodes = read_args(args, episodes=False)
98 | eps = utils.canon_episodes(name, episodes)
99 | outputs.normal_info(eps)
100 |
101 |
102 | def play_anime(args):
103 | name, episodes = read_args(args)
104 | for e in episodes:
105 | url = anime_source_module.get_episode_url(name, e)
106 | stream_from_url(url, name, e)
107 |
108 |
109 | def play_local_anime(args):
110 | name, episodes = read_args(args)
111 | for e in episodes:
112 | path = utils.get_episode_path(name, e, check=True)
113 | if not path:
114 | outputs.prompt_val("File not found locally", f"{name}:ep-{e}",
115 | "error")
116 | continue
117 | stream_from_url(path, name, e, local=True)
118 |
119 |
120 | def watch_episode_in_web(args):
121 | name, episodes = read_args(args, episodes=None)
122 | if not episodes:
123 | url = anime_source_module.get_anime_url(name)
124 | webbrowser.open_new_tab(url)
125 | return
126 | for e in episodes:
127 | url = anime_source_module.get_episode_url(name, e)
128 | webbrowser.open_new_tab(url)
129 | choice = input(f"did you watch the episode {e}? ")
130 | if not choice.strip() or choice.strip() in 'Yy':
131 | utils.write_log(name, e)
132 | utils.update_tracklist(name, e)
133 | utils.write_cache(name)
134 | utils.update_watchlater(name, e)
135 |
136 |
137 | def update_log(args):
138 | anime_name, episodes = read_args(args)
139 | episodes = utils.compress_range(episodes)
140 | utils.write_log(anime_name, episodes)
141 | utils.update_tracklist(anime_name, episodes)
142 | utils.write_cache(anime_name)
143 | utils.update_watchlater(anime_name, episodes)
144 |
145 |
146 | def edit_log(args):
147 | anime_name, episodes = read_args(args)
148 | utils.write_log(anime_name, utils.compress_range(episodes), append=False)
149 |
150 |
151 | def continue_play(args, play_func=play_anime):
152 | name, _ = read_args(args, episodes=False)
153 | log = utils.Log(utils.read_log().get(name))
154 | watch_later = utils.read_log(name, logfile=config.watchlaterfile)
155 | if watch_later:
156 | episodes = utils.extract_range(utils.Log(watch_later).eps)
157 | else:
158 | _, episodes = read_args(args)
159 | outputs.prompt_val("Watched",
160 | log._eps, "success", end='\t')
161 | outputs.normal_info(log.last_updated_fmt)
162 | if not log.eps:
163 | last = 0
164 | else:
165 | last = int(re.split('-|,', log.eps)[-1])
166 | to_play = utils.compress_range(filter(lambda e: e > last, episodes))
167 | if to_play.strip():
168 | play_func([name, to_play])
169 | else:
170 | unsave_anime(name)
171 |
172 |
173 | def download_anime(args):
174 | name, episodes = read_args(args)
175 | for e in episodes:
176 | url = anime_source_module.get_episode_url(name, e)
177 | download_from_url(url, name, e)
178 |
179 |
180 | def check_anime(args):
181 | name, episodes = read_args(args)
182 | unavail_eps = []
183 | for e in episodes:
184 | url = anime_source_module.get_episode_url(name, e)
185 | outputs.normal_info("Testing:", url)
186 | durl, ext = anime_source_module.get_direct_video_url(url)
187 | if not durl:
188 | raise SystemExit("Url for the file not found")
189 | if not os.path.exists(
190 | os.path.join(config.anime_dir, f"./{name}/ep{e:02d}.{ext}")):
191 | unavail_eps.append(e)
192 | if len(unavail_eps) == 0:
193 | outputs.success_info(
194 | "All episodes in given range are locally available")
195 | else:
196 | outputs.prompt_val("Missing episodes",
197 | utils.compress_range(unavail_eps), "warning")
198 |
199 |
200 | def read_args(args, episodes=True, verbose=True):
201 | if len(args) == 0:
202 | name = utils.read_cache()
203 | elif len(args) == 1 and args[0].isnumeric():
204 | name = utils.read_cache(int(args[0]))
205 | if verbose:
206 | outputs.prompt_val("Name", name)
207 | elif "/" in args[0]:
208 | name = args[0].strip("/").split("/")[-1]
209 | else:
210 | name = anime_source_module.process_anime_name(args[0].strip('"'))
211 | if not anime_source_module.verify_anime_exists(name):
212 | outputs.prompt_val("Anime with the name doesn't exist", args[0],
213 | "error")
214 | raise SystemExit
215 |
216 | if not name:
217 | outputs.error_info("Numbers choice invalid, or invalid context.")
218 | raise SystemExit
219 |
220 | if len(args) <= 1:
221 | if episodes:
222 | if verbose:
223 | outputs.warning_info("Episodes range not given defaulting to all")
224 | available_rng = anime_source_module.get_episodes_range(
225 | anime_source_module.get_anime_url(name))
226 | if verbose:
227 | outputs.prompt_val("Available episodes", available_rng)
228 | eps = utils.extract_range(available_rng)
229 | else:
230 | eps = None
231 | elif len(args) == 2:
232 | eps = utils.extract_range(args[1])
233 | else:
234 | outputs.error_info("Too many arguments.\n")
235 | outputs.normal_info(__doc__)
236 | raise SystemExit
237 | return name, eps
238 |
239 |
240 | def list_episodes(args):
241 | name, _ = read_args(args, episodes=False)
242 | available_rng = anime_source_module.get_episodes_range(anime_source_module.get_anime_url(name))
243 | if len(args) == 2:
244 | _, episodes = read_args(args)
245 | eps = set(episodes)
246 | avl_eps = set(utils.extract_range(available_rng))
247 | res = eps.intersection(avl_eps)
248 | available_rng = utils.compress_range(res)
249 | outputs.prompt_val("Available episodes", available_rng)
250 | log = utils.Log(utils.read_log(name))
251 | outputs.prompt_val("Watched episodes", log.eps, "success", end=' ')
252 | outputs.normal_info(log.last_updated_fmt)
253 | utils.write_cache(name)
254 |
255 |
256 | def list_local_episodes(args):
257 | in_dict = utils.get_local_episodes(*args)
258 | out_dict = dict()
259 | for anime, eps in in_dict.items():
260 | new_eps = utils.compress_range(utils.extract_range(eps))
261 | if new_eps != "":
262 | out_dict[anime] = new_eps
263 | empties = set(in_dict).difference(set(out_dict))
264 | if len(out_dict) == 0:
265 | outputs.warning_info("No local entries found.")
266 | else:
267 | outputs.bold_info("Episodes\tAnime Name")
268 | for k, v in out_dict.items():
269 | outputs.normal_info(f"{v}\t\t{k}")
270 | if len(empties) > 0:
271 | outputs.warning_info("Directories without Episodes:")
272 | outputs.warning_info(", ".join(empties))
273 |
274 |
275 | def search_anime(args):
276 | name = " ".join(args)
277 | anime_source_module.search_anime(name)
278 |
279 |
280 | def latest():
281 | utils.display_anime_eps_list(anime_source_module.home_page())
282 |
283 |
284 | def new():
285 | utils.display_anime_eps_list(anime_source_module.new_page())
286 |
287 |
288 | def import_from_mal(username):
289 | # TODO : use MAL username to import his completed and other lists.
290 | pass
291 |
292 |
293 | def anime_info(args):
294 | name, _ = read_args(args, episodes=False)
295 | soup = utils.get_soup(anime_source_module.get_anime_url(name))
296 | info = soup.find("div", {"class": "anime_info_body"})
297 | h = html2text.HTML2Text()
298 | h.ignore_links = True
299 | for t in info.find_all("p", {"class": "type"}):
300 | outputs.normal_info(h.handle(t.decode_contents()), end="")
301 |
302 |
303 | def download_from_url(url, anime_name=None, episode=None):
304 | if not anime_name or not episode:
305 | anime_name, episode = anime_source_module.parse_url(url)
306 | os.makedirs(os.path.join(config.anime_dir, f"./{anime_name}"),
307 | exist_ok=True)
308 | outputs.prompt_val("Downloading", url)
309 | durl, ext = anime_source_module.get_direct_video_url(url)
310 | if not durl:
311 | outputs.error_info("Url for the file not found")
312 | raise SystemExit
313 | if ext == ".m3u8":
314 | utils.download_m3u8(
315 | durl, utils.get_episode_path(anime_name, episode, make=True))
316 | else:
317 | utils.download_file(
318 | durl,
319 | utils.get_episode_path(anime_name, episode, ext=ext, make=True))
320 |
321 |
322 | def stream_from_url(url, anime_name=None, episode=None, *, local=False):
323 | if not anime_name or not episode:
324 | anime_name, episode = anime_source_module.parse_url(url)
325 | if local:
326 | durl = url
327 | _, ext = os.path.splitext(durl)
328 | else:
329 | outputs.normal_info("Getting Streaming Link:", url)
330 | durl, ext = anime_source_module.get_direct_video_url(url)
331 | if not durl:
332 | outputs.error_info("Url for the file not found")
333 | raise SystemExit
334 | outputs.prompt_val("Stream link", durl, "success")
335 | try:
336 | if config.ext_player_confirm:
337 | choice = input(f"Open {config.ext_player} Player? ")
338 | if choice == "" or choice.lower() == "y":
339 | pass
340 | else:
341 | raise SystemExit
342 | else:
343 | for i in range(11):
344 | outputs.normal_info(
345 | f"\rOpening External Player in: {1-i/10:1.1f} sec.",
346 | end="")
347 | time.sleep(0.1)
348 | outputs.normal_info()
349 | retval = player_module.play_media(
350 | durl, title=f"Ganime:{anime_name}:ep-{episode}{ext}")
351 | if retval:
352 | utils.write_log(anime_name, episode)
353 | utils.update_tracklist(anime_name, episode)
354 | utils.write_cache(anime_name)
355 | utils.update_watchlater(anime_name, episode)
356 | return
357 | except KeyboardInterrupt:
358 | outputs.warning_info("\nInturrupted, Exiting...")
359 | raise SystemExit
360 | outputs.normal_info()
361 |
362 |
363 | def save_anime(args):
364 | """Put the anime into watch later list."""
365 | anime_name, eps = read_args(args)
366 | watched = utils.read_log(anime_name)
367 | if watched:
368 | watched_eps = utils.extract_range(utils.Log(watched).eps)
369 | else:
370 | watched_eps = []
371 | save_eps = set(eps).difference(set(watched_eps))
372 | if not save_eps:
373 | outputs.warning_info('Already watched the provided episodes.')
374 | return
375 | utils.write_log(anime_name,
376 | utils.compress_range(save_eps),
377 | append=True,
378 | logfile=config.watchlaterfile)
379 |
380 |
381 | def track_anime(args):
382 | """Put an anime into the track list"""
383 | anime_name, episodes = read_args(args, episodes=False)
384 | log = utils.read_log(anime_name)
385 | if log is None:
386 | outputs.warning_info(
387 | "Log entry not found.")
388 | if not episodes:
389 | _, episodes = read_args(args)
390 | episodes = utils.compress_range(episodes)
391 | else:
392 | episodes = utils.Log(log).eps
393 | outputs.prompt_val("Watched", episodes, "success")
394 | utils.write_log(anime_name,
395 | episodes,
396 | append=False,
397 | logfile=config.ongoingfile)
398 |
399 |
400 | def untrack_anime(anime_name):
401 | """Remove an anime from the track list"""
402 | utils.remove_anime_from_log(anime_name, logfile=config.ongoingfile)
403 |
404 |
405 | def unsave_anime(anime_name):
406 | """Remove an anime from the saved list"""
407 | utils.remove_anime_from_log(anime_name, logfile=config.watchlaterfile)
408 |
409 |
410 | def unlog_anime(anime_name):
411 | utils.remove_anime_from_log(anime_name)
412 |
413 |
414 | def list_tracked():
415 | anime_list = utils.read_log(logfile=config.ongoingfile)
416 | for anime, log in anime_list.items():
417 | outputs.normal_info(utils.Log(log).show())
418 |
419 |
420 | def list_saved_anime():
421 | anime_list = utils.read_log(logfile=config.watchlaterfile)
422 | for anime, log in anime_list.items():
423 | outputs.normal_info(utils.Log(log).show())
424 |
425 |
426 | def anime_updates(anime_name=""):
427 | """Check and display the updates on the tracked anime list."""
428 | if anime_name == "":
429 | anime_list = utils.read_log(logfile=config.ongoingfile)
430 | else:
431 | anime_list = {
432 | anime_name:
433 | utils.read_log(anime_name=anime_name, logfile=config.ongoingfile)
434 | }
435 | updates = {}
436 | for anime, log in anime_list.items():
437 | episodes = log.split()[2] # FIX: use log object
438 | new_episodes = anime_source_module.get_episodes_range(
439 | anime_source_module.get_anime_url(anime))
440 | new = set(utils.extract_range(new_episodes)).difference(
441 | set(utils.extract_range(episodes)))
442 | if len(new) > 0:
443 | updates[anime] = new
444 | return updates
445 |
446 |
447 | def get_updates(anime_name=""):
448 | """Check and display the updates on the tracked anime list."""
449 | updates = anime_updates(anime_name)
450 | if len(updates) == 0:
451 | outputs.normal_info("No new episodes released.")
452 | return
453 | if anime_name == "":
454 | outputs.prompt_val(
455 | "anime(s) has new episodes.",
456 | len(updates),
457 | "success",
458 | sep=" ",
459 | reverse=True,
460 | )
461 | outputs.normal_info("-" * 50)
462 | for anime, episodes in updates.items():
463 | outputs.normal_info(anime, end="\n\t")
464 | outputs.success_tag(len(episodes), end=" ")
465 | outputs.prompt_val("new episodes", utils.compress_range(episodes),
466 | "success")
467 |
468 |
469 | def notify_update(anime_name=""):
470 | updates = anime_updates(anime_name)
471 | notification.episodes_update(updates)
472 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | anime_dir = os.path.expanduser('~/anime')
5 | os.makedirs(anime_dir, exist_ok=True)
6 |
7 | cachefile = os.path.join(anime_dir, ".cachefile")
8 | historyfile = os.path.join(anime_dir, ".shell_history")
9 | logfile = os.path.join(anime_dir, ".anime_history")
10 | ongoingfile = os.path.join(anime_dir, ".ongoing")
11 | watchlaterfile = os.path.join(anime_dir, ".watch_later")
12 |
13 | configfile = os.path.join(anime_dir, "shell.conf")
14 | if not os.path.exists(configfile):
15 | print(f"Config file doesn't exist in {configfile}")
16 | exit(0)
17 |
18 |
19 | project_dir = os.path.abspath(os.path.dirname(__file__))
20 |
21 |
22 | def is_config_line(line):
23 | line = line.strip()
24 | if not line:
25 | return False
26 | if line[0] == '#':
27 | return False
28 | return True
29 |
30 |
31 | with open(configfile, "r") as r:
32 | lines = filter(is_config_line, r)
33 | configs = dict()
34 | for line in lines:
35 | key, val = line.split("=", 1)
36 | configs[key.strip()] = val.strip(' "\n')
37 |
38 |
39 | ext_player = configs["ext_player"]
40 | ext_player_flags = configs["ext_player_flags"]
41 | anime_source = configs["anime_source"]
42 | video_quality = int(configs["video_quality"])
43 |
44 | ext_player_confirm = configs["ext_player_confirm"].lower() in [
45 | 'true', 'yes', 'on']
46 |
47 | ext_player_fullscreen = configs["ext_player_fullscreen"].lower() in [
48 | 'true', 'yes', 'on']
49 |
50 |
51 | req_headers = {
52 | "User-Agent":
53 | "Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/2010010 Firefox/84.0",
54 | "Accept":
55 | "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
56 | "Accept-Language": "en-US,en;q=0.5",
57 | "Upgrade-Insecure-Requests": "1"
58 | }
59 |
60 | down_headers = {
61 | "User-Agent":
62 | "Mozilla/5.0 (X11; Linux x86_64; rv:82.0) Gecko/20100102 Firefox/82.0",
63 | "Accept":
64 | "video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5",
65 | "Accept-Language": "en-US,en;q=0.5",
66 | "referer":"https://gogoanime.dk/"
67 | }
68 |
--------------------------------------------------------------------------------
/debug_shell.py:
--------------------------------------------------------------------------------
1 | """Prototype module for debugging.
2 |
3 | Got bored of sending line to python REPL and importing everything everytime.
4 |
5 | So here goes the debug REPL just like Python REPL.
6 | """
7 | import re
8 | import cmd
9 | import traceback
10 | import itertools
11 | import importlib
12 |
13 | import commands
14 | import config
15 | import outputs
16 | import utils
17 | import notification
18 |
19 | shell_commands = {
20 | "anime_src": commands.anime_source_module,
21 | "player": commands.player_module,
22 | "commands": commands,
23 | "config": config,
24 | "utils": utils,
25 | "notification": notification,
26 | "outputs": outputs,
27 | }
28 |
29 |
30 | class DebugShell(cmd.Cmd):
31 | identchars = cmd.IDENTCHARS + '.-'
32 | prompt = "\x1b[44mDEBUG $\x1b[0m"
33 |
34 | def __init__(self, ggshell, *args, **kwargs):
35 | super(DebugShell, self).__init__(*args, **kwargs)
36 | self.parent = ggshell
37 |
38 | def do_shell(self, inp):
39 | try:
40 | self.parent.onecmd(inp)
41 | except Exception as e:
42 | print(e)
43 |
44 | def import_mod(self, inp):
45 | """Import python modules.
46 | Supported commands:
47 | - import module
48 | - import module as alias
49 | - from module import something
50 |
51 | doesn't work if there is . in name but no alias.
52 | like: import os.path
53 | but import os.path as path works.
54 | """
55 | m = re.match(r'^import ([\w.]+)\s*$', inp)
56 | if m:
57 | shell_commands[m.group(1)] = importlib.import_module(m.group(1))
58 | return
59 | m = re.match(r'^import ([\w.]+) +as +(\w+)\s*$', inp)
60 | if m:
61 | shell_commands[m.group(2)] = importlib.import_module(m.group(1))
62 | return
63 | m = re.match(r'^from ([\w.]+) +import +(\w+)\s*$', inp)
64 | if m:
65 | shell_commands[m.group(2)] = getattr(
66 | importlib.import_module(m.group(1)), m.group(2))
67 |
68 | def default(self, inp):
69 | try:
70 | if 'import' in inp:
71 | return self.import_mod(inp)
72 | if '=' in inp:
73 | exec(inp, {}, shell_commands)
74 | else:
75 | retval = eval(inp, {}, shell_commands)
76 | outputs.success_tag('RET:', end=' ')
77 | outputs.normal_info(retval)
78 | except Exception as e:
79 | outputs.error_tag('ERR:', end=' ')
80 | outputs.normal_info(e)
81 | traceback.print_exc(chain=False)
82 |
83 | def completedefault(self, text, line, *args):
84 | if len(line) > 0 and line[0] == '!':
85 | if ' ' in line:
86 | lls = line.split(' ', 2)
87 | try:
88 | compfunc = getattr(self.parent, 'complete_' + lls[0])
89 | except AttributeError:
90 | compfunc = self.parent.completedefault
91 | return compfunc(text, line[1:], *args)
92 | else:
93 | return self.parent.completenames(text, line[1:], *args)
94 | if '.' in text:
95 | texts = text.split('.', 1)
96 | if texts[0] in shell_commands:
97 | possible = utils.recursive_getattr(shell_commands[texts[0]],
98 | texts[1])
99 | match = filter(lambda a: a.startswith(texts[1]), possible)
100 | completion = map(lambda m: f'{texts[0]}.{m}', match)
101 | return list(completion)
102 | else:
103 | return []
104 |
105 | commands = filter(lambda a: 'Error' not in a and not a.startswith('_'),
106 | __builtins__)
107 | possible = itertools.chain(shell_commands, commands)
108 | match = filter(lambda a: a.startswith(text), possible)
109 | return list(match)
110 |
111 | completenames = completedefault
112 |
113 | def do_exit(self, inp):
114 | return True
115 |
--------------------------------------------------------------------------------
/extras/plot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/extras/plot.png
--------------------------------------------------------------------------------
/extras/process.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import os
3 | import datetime as dt
4 |
5 | log_file = os.path.expanduser("~/.log/mpv.log")
6 |
7 | df = pd.DataFrame(
8 | columns=['timestamp', 'action', 'current_time',
9 | 'total_time', 'filename'])
10 | with open(log_file) as r:
11 | for i, line in enumerate(r):
12 | row = line.strip().split(" ", 4)
13 | df.loc[i, :] = row
14 |
15 | df.loc[:, 'isanime'] = df.filename.map(lambda fn: fn.startswith("Ganime:"))
16 |
17 | dfanime = df[df.isanime]
18 | dfanime.to_csv("/tmp/anime.csv", index=False)
19 | df = pd.read_csv("/tmp/anime.csv")
20 | animename = df.filename.map(lambda fn: fn[7:])
21 | df.loc[:, 'anime'] = animename.map(lambda x: x.split(':')[0])
22 | df.loc[:, 'episode'] = animename.map(
23 | lambda x: x.split(':')[1].split(".")[0][3:])
24 |
25 |
26 | def time_in_seconds(tms):
27 | data = tms.split(":")
28 | val = 0
29 | for d in data:
30 | val = val*60 + int(d)
31 | return val
32 |
33 |
34 | def play_categorize(action):
35 | if action in ['file-loaded', 'pause', 'seek']:
36 | return -1
37 | return 1
38 |
39 |
40 | df.current_time = df.current_time.map(time_in_seconds)
41 | df.total_time = df.total_time.map(time_in_seconds)
42 | df.loc[:, 'temp'] = df.action.map(play_categorize)
43 | df.temp = df.temp * df.current_time
44 | processed = df.groupby(['anime', 'episode']).agg(
45 | watchtime=('temp', 'sum'),
46 | totaltime=('total_time', 'mean'),
47 | timestamp=('timestamp', 'mean')
48 | )
49 | processed.loc[:, 'percentage'] = (
50 | processed.watchtime * 100 / processed.totaltime)
51 | dates = processed.timestamp.map(dt.datetime.fromtimestamp)
52 | processed.loc[:, 'year'] = dates.map(lambda t: t.year)
53 | processed.loc[:, 'month'] = dates.map(lambda t: t.month)
54 | processed.loc[:, 'day'] = dates.map(lambda t: t.day)
55 | processed.loc[:, 'dayofweek'] = dates.map(lambda t: t.strftime("%A"))
56 | processed.loc[:, 'hour'] = dates.map(
57 | lambda t: t.hour + t.minute/60 + t.second/3600)
58 |
59 | processed.to_csv("./extras/log_anime.csv")
60 |
--------------------------------------------------------------------------------
/extras/visualize.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | from matplotlib import gridspec
3 | from matplotlib.dates import DateFormatter
4 | import datetime as dt
5 | import pandas as pd
6 | import calendar
7 |
8 | df = pd.read_csv("./extras/log_anime.csv")
9 |
10 | daily = df.groupby(['year', 'month', 'day']).agg(
11 | watchtime=('watchtime', 'sum'),
12 | dayofweek=('dayofweek', 'first'),
13 | )
14 |
15 | daily.loc[:, 'date'] = daily.apply(
16 | lambda row: dt.datetime(row.name[0], row.name[1], row.name[2]), axis=1)
17 |
18 | day = daily.date.min()
19 | while day <= daily.date.max():
20 | if (day.year, day.month, day.day) not in daily.index:
21 | daily.loc[(day.year,
22 | day.month,
23 | day.day), :] = [0, calendar.day_name[day.dayofweek], day]
24 | day += dt.timedelta(days=1)
25 |
26 | daily.sort_index(inplace=True)
27 | filt_index = (daily.watchtime > 0).to_list()
28 |
29 | i = 1
30 | while i < len(filt_index)-1:
31 | if filt_index[i] is True:
32 | if filt_index[i-1] is False:
33 | filt_index[i-1] = True
34 | if filt_index[i+1] is False:
35 | filt_index[i+1] = True
36 | i += 1
37 | i += 1
38 |
39 | daily = daily[filt_index]
40 |
41 | weekdays = daily[daily.watchtime > 0].groupby('dayofweek').watchtime.mean() / 3600
42 | days_dict = {d: i for i, d in enumerate(calendar.day_name)}
43 | colors = [
44 | 'tab:blue', 'tab:pink', 'tab:gray', 'tab:orange', 'tab:purple',
45 | 'tab:olive', 'tab:green'
46 | ]
47 | days_color = {d: c for d, c in zip(calendar.day_name, colors)}
48 | weekdays.sort_index(key=lambda x: x.map(lambda v: days_dict[v]), inplace=True)
49 |
50 | all_animes = pd.pivot_table(df,
51 | columns=['dayofweek'],
52 | index='anime',
53 | values='watchtime',
54 | aggfunc='sum').fillna(0)
55 |
56 | animes = all_animes[all_animes.apply(sum, axis=1) > 3600*4] # At least 4 hours of watchtime
57 | other_animes = all_animes[all_animes.apply(sum, axis=1) <= 1800] # remaining
58 | others = other_animes.sum() / 3600
59 | animes /= 3600
60 | # animes = df.groupby(['anime', 'dayofweek']).episode.count()
61 | animes.index = animes.index.map(lambda x: x
62 | if len(x) < 30 else x[:17] + '...' + x[-10:])
63 | animes = animes.sort_index()
64 | animes.loc['others', :] = others
65 |
66 | # watchtime = df.groupby('anime').watchtime.sum()
67 | # watchtime.index = animes.index
68 | # total = watchtime.sum()
69 | # name = watchtime.map(lambda x: x * 100 / total > 2)
70 | # for_pi = watchtime[name]
71 | # for_pi.loc['others'] = watchtime[name == False].sum()
72 |
73 | with plt.style.context("ggplot"):
74 | fig = plt.figure(constrained_layout=True, figsize=(16, 9))
75 | specs = gridspec.GridSpec(ncols=2, nrows=2, figure=fig)
76 |
77 | top = fig.add_subplot(specs[0, :])
78 | bleft = fig.add_subplot(specs[1, 0])
79 | bright = fig.add_subplot(specs[1, 1])
80 |
81 | bottoms = pd.Series(0, index=animes.index)
82 | top_bars = []
83 | for col in calendar.day_name:
84 | tb = top.bar(animes.index,
85 | animes[col],
86 | color=days_color[col],
87 | bottom=bottoms)
88 | bottoms += animes[col]
89 | top_bars.append(tb)
90 | top.tick_params(labelbottom=False, bottom=False)
91 | top.set_xlabel('Animes watched since 2021-Jan-15')
92 | top.set_ylabel('Hours spent')
93 | mean_h = bottoms.max()/2
94 | for i, bar in enumerate(top_bars[0]):
95 | h = sum((top_bars[j][i].get_height() for j in range(len(top_bars))))
96 | if h > mean_h:
97 | h = 0
98 | top.annotate(
99 | animes.index[i],
100 | xy=(bar.get_x() + bar.get_width() / 2, h),
101 | xytext=(0, 3), # 3 points vertical offset
102 | textcoords="offset points",
103 | rotation=90,
104 | ha='center',
105 | va='bottom')
106 |
107 | bleft_bar = bleft.bar(weekdays.index, weekdays, color=colors)
108 | bleft.set_ylabel('Hours')
109 | bleft.set_xlabel('Average Time Spent on Anime')
110 |
111 | # bright_pie = bright.pie(for_pi, labels=for_pi.index)
112 | # bright.set_xlabel(f'Total time spent on anime={total/3600:.2f}hr')
113 | bright.plot_date(daily.date, daily.watchtime / 3600, fmt='--',
114 | linewidth=0.7)
115 | # bright.plot_date(daily.date, daily.watchtime/3600, fmt='o',
116 | # color=[days_color[d] for d in daily.dayofweek])
117 | bright.scatter(daily.date,
118 | daily.watchtime / 3600,
119 | c=daily.dayofweek.map(days_color))
120 | bright.xaxis.set_major_formatter(DateFormatter("Y%yM%m"))
121 |
122 | # plt.show()
123 | plt.savefig("/tmp/test.png")
124 | print("/tmp/test.png")
125 |
--------------------------------------------------------------------------------
/ggshell.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import cmd
3 | import sys
4 | import os
5 | import subprocess
6 | import re
7 |
8 | from requests.exceptions import ConnectionError, ConnectTimeout
9 |
10 | import commands
11 | import utils
12 | import config
13 | import outputs
14 | from debug_shell import DebugShell
15 |
16 |
17 | class GGshell(cmd.Cmd):
18 | # These are overriden from cmd.Cmd
19 | # ANSII scapes for orage bg
20 | prompt = "\x1b[43mGanime >>\x1b[0m"
21 | # to have '-' character in my commands
22 | identchars = cmd.Cmd.identchars + '-'
23 | ruler = '-'
24 | misc_header = 'Other Help Topics'
25 |
26 | def __init__(self, *args, **kwargs):
27 | super().__init__(*args, **kwargs)
28 | self.in_cmdloop = False
29 |
30 | def onecmd(self, ind):
31 | if ind == 'EOF':
32 | outputs.normal_info()
33 | return
34 | try:
35 | return super().onecmd(ind)
36 | except (SystemExit, KeyboardInterrupt):
37 | outputs.normal_info()
38 | except (ConnectionError, ConnectTimeout):
39 | outputs.error_info('Slow or no Internet connection. Try again.')
40 |
41 | def cmdloop(self, intro=None):
42 | """Repeatedly issue a prompt, accept input, parse an initial prefix
43 | off the received input, and dispatch to action methods, passing them
44 | the remainder of the line as argument.
45 |
46 | """
47 |
48 | self.in_cmdloop = True
49 | self.preloop()
50 | if self.use_rawinput and self.completekey:
51 | try:
52 | import readline
53 | self.old_completer = readline.get_completer()
54 | readline.set_completer(self.complete)
55 | readline.parse_and_bind(self.completekey + ": complete")
56 | except ImportError:
57 | pass
58 | try:
59 | if intro is not None:
60 | self.intro = intro
61 | if self.intro:
62 | self.stdout.write(str(self.intro) + "\n")
63 | stop = None
64 | while not stop:
65 | if self.cmdqueue:
66 | line = self.cmdqueue.pop(0)
67 | else:
68 | try:
69 | if self.use_rawinput:
70 | try:
71 | line = input(self.prompt)
72 | except EOFError:
73 | line = 'EOF'
74 | else:
75 | self.stdout.write(self.prompt)
76 | self.stdout.flush()
77 | line = self.stdin.readline()
78 | if not len(line):
79 | line = 'EOF'
80 | else:
81 | line = line.rstrip('\r\n')
82 | except KeyboardInterrupt:
83 | self.stdout.write('\n^C\n')
84 | continue
85 | line = self.precmd(line)
86 | stop = self.onecmd(line)
87 | stop = self.postcmd(stop, line)
88 | self.postloop()
89 | finally:
90 | if self.use_rawinput and self.completekey:
91 | try:
92 | import readline
93 | readline.set_completer(self.old_completer)
94 | except ImportError:
95 | pass
96 | self.in_cmdloop = False
97 |
98 | def preloop(self):
99 | try:
100 | import readline
101 | readline.clear_history()
102 | if os.path.exists(config.historyfile):
103 | readline.read_history_file(config.historyfile)
104 | self.old_completers = readline.get_completer_delims()
105 | readline.set_completer_delims(
106 | re.sub(r'-|:|/', '', self.old_completers))
107 | except ImportError:
108 | pass
109 |
110 | def postloop(self):
111 | try:
112 | import readline
113 | readline.set_history_length(1000)
114 | readline.write_history_file(config.historyfile)
115 | readline.set_completer_delims(self.old_completers)
116 | except ImportError:
117 | pass
118 |
119 | def emptyline(self):
120 | pass
121 |
122 | def completedefault(self, text, line, start, end):
123 | if re.match(r'([a-z-]+ +){2,}', line):
124 | return []
125 | lists = set(utils.read_log().keys()).union(
126 | set(utils.read_cache(complete=True)))
127 | match = filter(lambda t: t.startswith(text), lists)
128 | return utils.completion_list(match)
129 |
130 | def do_help(self, topic):
131 | if len(topic) == 0:
132 | import __init__
133 | outputs.normal_info(__init__.__doc__)
134 | super().do_help(topic)
135 |
136 | # From here my commands start
137 |
138 | def do_exit(self, inp):
139 | """Exit this interactive shell."""
140 | return True
141 |
142 | def do_debug(self, inp):
143 | """Launch the debug shell.
144 |
145 | You can tweak the config variables and other functions without having
146 | to edit the config.py and reloading the app and so on. Use this to see
147 | the effect of configurations which won't be saved.
148 |
149 | """
150 | if self.in_cmdloop:
151 | self.postloop()
152 | DebugShell(self).cmdloop(
153 | "Debug Shell for Ganime shell.\n" +
154 | "try `dir()` to see available context variables. " +
155 | "This shell is same as python shell but has" +
156 | " Ganime context.")
157 | self.preloop()
158 | else:
159 | DebugShell(self).cmdloop()
160 |
161 | def do_history(self, inp):
162 | """show the history of the commands.
163 | """
164 | if not self.in_cmdloop:
165 | for j, h in enumerate(open(config.historyfile), start=1):
166 | h = h.strip()
167 | if re.match(inp, h):
168 | outputs.normal_info(f'{j:3d}: {h}')
169 | return
170 | try:
171 | import readline
172 | for j in range(1, readline.get_current_history_length() + 1):
173 | h = readline.get_history_item(j)
174 | if re.match(inp, h):
175 | outputs.normal_info(f'{j:3d}: {h}')
176 | except ImportError:
177 | pass
178 |
179 | def do_shell(self, inp):
180 | """Execute shell commands
181 | """
182 | subprocess.call(inp, shell=True)
183 |
184 | def do_quality(self, inp):
185 | """Sets the quality for the anime.
186 | """
187 | commands.set_quality(inp)
188 |
189 | def complete_quality(self, text, *ignored):
190 | possibilities = ['360p', '480p', '720p', '1080p']
191 | match = filter(lambda t: t.startswith(text), possibilities)
192 | return list(match)
193 |
194 | def do_geometry(self, inp):
195 | """Sets the geometry for the external player.
196 | """
197 | commands.set_geometry(inp)
198 |
199 | def complete_geometry(self, *ignored):
200 | return utils.completion_list([config.geometry])
201 |
202 | def do_canon(self, inp):
203 | """Available list of Canon Episodes.
204 | """
205 | commands.check_canon(inp.split())
206 |
207 | def do_fullscreen(self, inp):
208 | """Toggles the fullscreen setting for external player.
209 | """
210 | commands.toggle_fullscreen(inp)
211 |
212 | def complete_fullscreen(self, text, *ignored):
213 | possibilities = ['yes', 'no', 'on', 'off']
214 | match = filter(lambda t: t.startswith(text), possibilities)
215 | return utils.completion_list(match)
216 |
217 | def do_unlog(self, inp):
218 | """Remove the log entry for the given anime.
219 |
220 | USAGE: unlog [ANIME-NAME]
221 | ANIME-NAME : Name of the anime
222 | """
223 | commands.unlog_anime(inp)
224 |
225 | def do_untrack(self, inp):
226 | """Remove the given anime from the active track list.
227 |
228 | USAGE: untrack [ANIME-NAME]
229 | ANIME-NAME : Name of the anime
230 | """
231 | commands.untrack_anime(inp)
232 |
233 | def complete_untrack(self, text, line, start, end):
234 | if re.match(r'([a-z-]+ +){2,}', line):
235 | return []
236 | lists = utils.read_log(logfile=config.ongoingfile).keys()
237 | match = filter(lambda t: t.startswith(text), lists)
238 | return utils.completion_list(match)
239 |
240 | def do_track(self, inp):
241 | """Put the given anime into the active track list.
242 |
243 | USAGE: track [ANIME-NAME] [EPISODES-RANGE]
244 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
245 | EPISODES-RANGE : Range of the episodes, defaults to all
246 | """
247 | commands.track_anime(inp.split())
248 |
249 | def do_tracklist(self, inp):
250 | """Lists all the animes on the track list.
251 |
252 | USAGE: tracklist
253 | """
254 | commands.list_tracked()
255 |
256 | def do_latest(self, inp):
257 | """Get the latest updates from the home page.
258 |
259 | USAGE: latest
260 | """
261 | commands.latest()
262 |
263 | def do_new(self, inp):
264 | """Get the new animes from the new page.
265 |
266 | USAGE: new
267 | """
268 | commands.new()
269 |
270 | def do_updates(self, inp):
271 | """Get the updates for new episode releases.
272 |
273 | USAGE: updates [ANIME-NAME]
274 | ANIME-NAME : Name of the anime
275 | """
276 | commands.get_updates(inp.strip())
277 |
278 | complete_updates = complete_untrack
279 |
280 | def do_notify(self, inp):
281 | """Get the updates for new episode releases in notification.
282 |
283 | USAGE: notify [ANIME-NAME]
284 | ANIME-NAME : Name of the anime
285 | """
286 | commands.notify_update(inp.strip())
287 |
288 | complete_notify = complete_untrack
289 |
290 | def do_downloadurl(self, inp):
291 | """Downloads the anime episode from given gogoanime url
292 | USAGE: downloadurl [GOGOANIME-URL]
293 | GOGOANIME-URL : Url of the episode from gogoanime website.
294 |
295 | related commands: download, streamurl
296 | """
297 | commands.download_from_url(inp)
298 |
299 | def do_streamurl(self, inp):
300 | """Streams the anime episode from given gogoanime url
301 | USAGE: streamurl [GOGOANIME-URL]
302 | GOGOANIME-URL : Url of the episode from gogoanime website.
303 |
304 | related commands: play, continue
305 | """
306 | commands.stream_from_url(inp)
307 |
308 | def complete_downloadurl(self, text, line, *ignored):
309 | lists = set(utils.read_log().keys()).union(
310 | set(utils.read_cache(complete=True)))
311 | urls = map(lambda name: commands.anime_source_module.get_episode_url(name, ''), lists)
312 | match = filter(lambda t: t.startswith(text), urls)
313 | return utils.completion_list(match)
314 |
315 | complete_streamurl = complete_downloadurl
316 |
317 | def do_download(self, inp):
318 | """Download the anime episodes in given range
319 |
320 | USAGE: download [ANIME-NAME] [EPISODES-RANGE]
321 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
322 | EPISODES-RANGE : Range of the episodes, defaults to all
323 |
324 | related commands: play, continue, streamurl
325 | """
326 | commands.download_anime(inp.split())
327 |
328 | def do_list(self, inp):
329 | """List the episodes available for the given anime.
330 |
331 | USAGE: list [ANIME-NAME] [EPISODES-RANGE]
332 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
333 | EPISODES-RANGE : Range of the episodes, defaults to all
334 |
335 | related commands: info, local
336 | """
337 | commands.list_episodes(inp.split())
338 |
339 | def do_web(self, inp):
340 | """Play the given episodes of the given anime in browser.
341 |
342 | USAGE: web [ANIME-NAME] [EPISODES-RANGE]
343 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
344 | EPISODES-RANGE : Range of the episodes, defaults to all
345 |
346 | related commands: play, continue, webcontinue
347 | """
348 | commands.watch_episode_in_web(inp.split())
349 |
350 | def do_webcontinue(self, inp):
351 | """Continue playing the given anime in browser.
352 |
353 | USAGE: webcontinue [ANIME-NAME]
354 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
355 | """
356 | commands.continue_play(inp.split(),
357 | play_func=commands.watch_episode_in_web)
358 |
359 | def do_play(self, inp):
360 | """Play the given episodes of the given anime.
361 |
362 | USAGE: play [ANIME-NAME] [EPISODES-RANGE]
363 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
364 | EPISODES-RANGE : Range of the episodes, defaults to all
365 |
366 | related commands: continue, web, streamurl
367 | """
368 | commands.play_anime(inp.split())
369 |
370 | def complete_play(self, text, line, *ignored):
371 | m = re.match(r'[a-z-]+ +([0-9a-z-]+) +', line)
372 | if m:
373 | name = m.group(1)
374 | log = utils.read_log(name)
375 | if not log:
376 | return ["1"]
377 | ep = re.split("[-,]", utils.Log(log).eps)[-1]
378 | return [str(int(ep) + 1)]
379 | return self.completedefault(text, line, *ignored)
380 |
381 | complete_web = complete_play
382 | complete_watched = complete_play
383 |
384 | def do_savelist(self, inp):
385 | """List the animes saved for watching later. The continue command will
386 | use this list to decide which episode to watch next. Useful for
387 | skipping fillers.
388 |
389 | USAGE: savelist
390 |
391 | related commands: save, unsave
392 | """
393 | commands.list_saved_anime()
394 |
395 | def do_unsave(self, inp):
396 | """Play the given episodes of the given anime.
397 |
398 | USAGE: unsave [ANIME-NAME]
399 | ANIME-NAME : Name of the anime
400 |
401 | related commands: savelist, save
402 | """
403 | commands.unsave_anime(inp.strip())
404 |
405 | def complete_unsave(self, text, line, *ignored):
406 | return utils.completion_list(filter(lambda x: re.match(text,x), utils.read_log(logfile=config.watchlaterfile).keys()))
407 |
408 | def do_listlocal(self, inp):
409 | """List the animes available in local storage.
410 |
411 | USAGE: listlocal [KEYWORDS]
412 | KEYWORDS : Name of the anime, or regex to filter the list.
413 | """
414 | commands.list_local_episodes(inp.split())
415 |
416 | do_locallist = do_listlocal
417 |
418 | def complete_listlocal(self, text, line, *ignored):
419 | animes = utils.get_local_episodes()
420 | match = filter(lambda t: t.startswith(text), animes.keys())
421 | return utils.completion_list(match)
422 |
423 | complete_locallist = complete_listlocal
424 |
425 | def do_local(self, inp):
426 | """Play the given episodes of the given anime from local storage.
427 |
428 | USAGE: local [ANIME-NAME] [EPISODES-RANGE]
429 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
430 | EPISODES-RANGE : Range of the episodes, defaults to all
431 | """
432 | if inp.strip() == '':
433 | self.do_listlocal(inp)
434 | return
435 | commands.play_local_anime(inp.split())
436 |
437 | def complete_local(self, text, line, *ignored):
438 | m = re.match(r'local +([0-9a-z-]+) +', line)
439 | if m:
440 | name = m.group(1)
441 | eps = utils.get_local_episodes(name)[name]
442 | return [utils.compress_range(utils.extract_range(eps))]
443 | return self.complete_listlocal(text, line, *ignored)
444 |
445 | def do_watched(self, inp):
446 | """Update the log so that the given anime (& episodes) are deemed
447 | watched.
448 |
449 | USAGE: watched [ANIME-NAME] [EPISODES-RANGE]
450 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
451 | EPISODES-RANGE : Range of the episodes, defaults to all
452 | """
453 | commands.update_log(inp.split())
454 |
455 | def do_edit(self, inp):
456 | """Edit the log so that the given anime (& episodes) replace the
457 | previous log information with new.
458 |
459 | USAGE: edit [ANIME-NAME] [EPISODES-RANGE]
460 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
461 | EPISODES-RANGE : Range of the episodes, defaults to all
462 | """
463 | commands.edit_log(inp.split())
464 |
465 | def do_save(self, inp):
466 | """Save the anime or episodes to watch later list. `continue` command
467 | will use this list to decide what to play next, great for skipping
468 | filler episodes.
469 |
470 | USAGE: save [ANIME-NAME] [EPISODES-RANGE]
471 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
472 | EPISODES-RANGE : Range of the episodes, defaults to all,
473 | can be copied from the list of episodes in websites like:
474 | https://www.animefillerlist.com
475 |
476 | """
477 | commands.save_anime(inp.split(maxsplit=1))
478 |
479 | def do_continue(self, inp):
480 | """Play the given anime's unwatched episodes from the start.
481 |
482 | USAGE: continue [ANIME-NAME]
483 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
484 | """
485 | commands.continue_play(inp.split())
486 |
487 | def do_search(self, inp):
488 | """Search the given keywords in the gogoanime anime list.
489 |
490 | USAGE: search [KEYWORDS]
491 | KEYWORDS : Name of the anime, in english or japanese.
492 | You can use this search result as choice number in
493 | next command. first choice is 1.
494 | """
495 | commands.search_anime(inp.split())
496 |
497 | def do_log(self, inp):
498 | """Display the log information.
499 | Pass Anime name or keywords to filter the log. (supports python regex)
500 |
501 | USAGE: log [KEYWORDS] [NUMBER]
502 | KEYWORDS : Name of the anime, or regex to filter the log.
503 | NUMBER : Number of log items to be shown.
504 | """
505 | commands.anime_log(inp.split())
506 |
507 | def do_info(self, inp):
508 | """Show the information of the anime, if you have just searched
509 | something, you can see their info to test if that's what you are searching
510 | for.
511 |
512 | USAGE: info [ANIME-NAME]
513 | ANIME-NAME : Name of the anime, or choice number; defaults to 0
514 | """
515 | commands.anime_info(inp.split())
516 |
517 | def do_check(self, inp):
518 | """Check if the given episodes range are downloaded and available
519 | offline.
520 | Do not use this when simple commands like ls and tree are enough, as it
521 | also checks the file online to make sure extensions match.
522 | """
523 | commands.check_anime(inp.split())
524 |
525 | # Aliases
526 | do_la = do_latest
527 | do_ls = do_locallist
528 | # do_co = do_continue
529 | do_s = do_search
530 | # do_pl = do_play
531 | do_q = do_exit
532 |
533 |
534 | if __name__ == '__main__':
535 | if len(sys.argv) == 1:
536 | gshell = GGshell()
537 | gshell.cmdloop("""Welcome, This is the CLI interactive for gogoanime.
538 | Type help for more.""")
539 | else:
540 | GGshell().onecmd(" ".join(sys.argv[1:]))
541 |
--------------------------------------------------------------------------------
/notification.py:
--------------------------------------------------------------------------------
1 | import utils
2 | import outputs
3 | try:
4 | import notify2
5 |
6 | def send_notification(summary, body):
7 | notify2.init('Gogoanime CLI')
8 | n = notify2.Notification(summary, message=body)
9 | n.show()
10 | except ImportError:
11 |
12 | def send_notification(summary, body):
13 | outputs.error_info('Notification system is not setup properly')
14 |
15 |
16 | def episodes_update(updates):
17 | if len(updates) == 0:
18 | return
19 | if len(updates) == 1:
20 | anime_name = list(updates)[0]
21 | epl = len(updates[anime_name])
22 | eps = utils.compress_range(updates[anime_name])
23 | summary = f'{epl} New episode(s)'
24 | msg = f'{anime_name} has {epl} new episodes ({eps})'
25 | send_notification(summary, msg)
26 | else:
27 | summary = f'{len(updates)} anime updates'
28 | msg = ''
29 | for anime_name, ep in updates.items():
30 | epl = len(updates[anime_name])
31 | eps = utils.compress_range(updates[anime_name])
32 | msg += f'{epl} new ({eps}) : {anime_name}\n'
33 | send_notification(summary, msg)
34 |
--------------------------------------------------------------------------------
/outputs.py:
--------------------------------------------------------------------------------
1 | from colorama import init, Fore, Back, Style
2 |
3 | init()
4 |
5 |
6 | def normal_info(*args, **kwargs):
7 | print(*args, **kwargs)
8 |
9 |
10 | def bold_info(*args, **kwargs):
11 | print(Style.BRIGHT, end='')
12 | print(*args, **kwargs)
13 | print(Style.RESET_ALL, end='')
14 |
15 |
16 | def success_info(*args, **kwargs):
17 | print(Fore.GREEN, end='')
18 | print(*args, **kwargs)
19 | print(Fore.RESET, end='')
20 |
21 |
22 | def error_info(*args, **kwargs):
23 | print(Fore.RED, end='')
24 | print(*args, **kwargs)
25 | print(Fore.RESET, end='')
26 |
27 |
28 | def warning_info(*args, **kwargs):
29 | print(Fore.YELLOW, end='')
30 | print(*args, **kwargs)
31 | print(Fore.RESET, end='')
32 |
33 |
34 | def error_tag(*args, end='\n', **kwargs):
35 | print(Back.RED + Fore.BLACK, end='')
36 | print(*args, **kwargs, end='')
37 | print(Back.RESET + Fore.RESET, end=end)
38 |
39 |
40 | def warning_tag(*args, end='\n', **kwargs):
41 | print(Back.YELLOW + Fore.BLACK, end='')
42 | print(*args, **kwargs, end='')
43 | print(Back.RESET + Fore.RESET, end=end)
44 |
45 |
46 | def success_tag(*args, end='\n', **kwargs):
47 | print(Back.GREEN + Fore.BLACK, end='')
48 | print(*args, **kwargs, end='')
49 | print(Back.RESET + Fore.RESET, end=end)
50 |
51 | def normal_tag(*args, end='\n', **kwargs):
52 | print(Back.WHITE + Fore.BLACK, end='')
53 | print(*args, **kwargs, end='')
54 | print(Back.RESET + Fore.RESET, end=end)
55 |
56 |
57 | def prompt_val(prompt='', val='', output='normal', sep=": ", reverse=False, end='\n'):
58 | if reverse:
59 | globals()[f'{output}_tag'](val, end='')
60 | globals()[f'{output}_info'](sep+prompt, end=end)
61 | else:
62 | globals()[f'{output}_info'](prompt+sep, end='')
63 | globals()[f'{output}_tag'](val, end=end)
64 |
65 |
--------------------------------------------------------------------------------
/players/README.org:
--------------------------------------------------------------------------------
1 | * Player modules
2 | The modules in this path are used to play the media, choose one among these from ~shell.conf~ in your anime directory.
3 |
4 |
5 | * Currently Available
6 |
7 | ** mpv
8 | mpv player is the only one currently available.
9 |
10 |
11 | * Adding new ones
12 | To add a new module make a new .py file in this directory and make a pull request.
13 |
14 | the module should have following functions and variables.
15 |
16 | ** compile_command
17 | Should change player command using the latest config or arguments.
18 |
19 | arguments: ~(flags='', fullscreen=False)~
20 |
21 | ** get_player_command
22 | Should return current player command.
23 |
24 | ** set_geometry
25 | should set the geometry in the module or/and player command.
26 |
27 | ** play_media
28 | Should be able to play the media in the player.
29 |
30 | Arguments: ~(link, title=None)~
31 |
32 | link can be both streamable link or local file path.
33 |
34 | * Plans to add
35 | Would prefer to add the followings, contributions are welcome.
36 |
37 |
38 | ** Termux
39 | A termux option that would open the player from android.
40 |
41 | ** vlc
42 | Since many people use it, would be nice to be added.
43 |
--------------------------------------------------------------------------------
/players/__init__.py:
--------------------------------------------------------------------------------
1 | import players.mpv as mpv
2 |
--------------------------------------------------------------------------------
/players/mpv.py:
--------------------------------------------------------------------------------
1 | import time
2 | import subprocess
3 | import outputs
4 |
5 | geometry = ''
6 |
7 | player_command = ''
8 |
9 |
10 | def set_geometry(geom):
11 | global geometry
12 | geometry = geom
13 | compile_command()
14 |
15 |
16 | def compile_command(flags='', fullscreen=False):
17 | global player_command
18 | com = [f'mpv {flags}']
19 | if geometry:
20 | com += [f'--geometry={geometry}']
21 | if fullscreen:
22 | com += ['--fs']
23 | player_command = com + [flags]
24 | return com
25 |
26 |
27 | def get_player_command():
28 | return " ".join(player_command)
29 |
30 |
31 | def get_command(path, title=None, flags=''):
32 | com = " ".join(player_command)
33 | if title:
34 | com += f' --force-media-title={title}'
35 | com += flags + f' "{path}"'
36 | return com
37 |
38 |
39 | def play_media(link, title=None):
40 | while True:
41 | t1 = time.time()
42 | ret_val = subprocess.call(get_command(link, title),
43 | shell=True)
44 | if ret_val == 2: # mpv error code
45 | outputs.error_info('Couldn\'t open the stream.')
46 | if input("retry?") == '':
47 | continue
48 | else:
49 | raise SystemExit
50 | return (time.time() - t1) > (5 * 60)
51 | # 5 minutes watchtime at least, otherwise consider it unwatched.
52 | # TODO: use direct communication with mpv to know if episode was
53 | # watched.
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pycurl
2 | m3u8
3 | requests
4 | beautifulsoup4
5 | html2text
6 | notify2
7 | colorama
8 |
--------------------------------------------------------------------------------
/screenshots/help1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/help1.png
--------------------------------------------------------------------------------
/screenshots/help2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/help2.png
--------------------------------------------------------------------------------
/screenshots/history.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/history.png
--------------------------------------------------------------------------------
/screenshots/info.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/info.png
--------------------------------------------------------------------------------
/screenshots/log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/log.png
--------------------------------------------------------------------------------
/screenshots/number.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/number.png
--------------------------------------------------------------------------------
/screenshots/others.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/others.png
--------------------------------------------------------------------------------
/screenshots/recent.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/recent.png
--------------------------------------------------------------------------------
/screenshots/track.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/track.png
--------------------------------------------------------------------------------
/screenshots/watch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Atreyagaurav/anime-helper-shell/27f27cf031c47bedec3e427ed18edf2d6f10198c/screenshots/watch.png
--------------------------------------------------------------------------------
/shell.conf:
--------------------------------------------------------------------------------
1 | # preferred external media player. Needs to be among the ones available in players directory.
2 | ext_player=mpv
3 | # do not remove referrer, it will break the script
4 | ext_player_flags="--no-config --referrer=https://gogoanime.film/"
5 | ext_player_fullscreen=True
6 | ext_player_confirm=False
7 |
8 | # Source for the anime. Needs to be among the ones available in sources directory.
9 | anime_source=gogoanime
10 | video_quality=1080
11 |
--------------------------------------------------------------------------------
/sources/README.org:
--------------------------------------------------------------------------------
1 | * Sources modules
2 |
3 | These are used by the shell to communicate with whichever source you choose in your config file (~shell.conf~ in your anime dir).
4 |
5 |
6 | * Currently available ones
7 |
8 | ** gogoanime
9 | This source uses gogoanime website to get the episodes informations and all.
10 |
11 |
12 | * Adding new source
13 | You can add new sources by putting more modules in this directory.
14 |
15 | The module you define needs the following functions
16 |
17 | ** get_anime_url
18 | should be able to provide url for that anime based on parameters ~(anime_name)~.
19 |
20 | ** get_direct_video_url
21 | should be able to reuturn a stream-able video url & it's extension in tuple ~(url, ext)~ from parameter ~anime_episode_url~.
22 |
23 | ** get_episode_url
24 | should be able to provide the url where we can watch the episode from a browser based on parameters ~(anime_name, episode)~.
25 |
26 | ** get_episodes_range
27 | should be able to provide the available episodes range in human readable format from parameter ~anime_url~.
28 |
29 | ** home_page
30 | List of anime episodes in home page (latest updated episodes).
31 |
32 | ** new_page
33 | List of animes in current season.
34 |
35 | ** parse_url
36 | Should be able to return tuple ~(anime_name, episode)~ from given episode url.
37 |
38 | ** process_anime_name
39 | Should be able to process raw human readable anime name into anime name used by the source website.
40 |
41 | ** search_anime
42 | Should be able to print out all the anime names matching the search terms.
43 |
44 | ** verify_anime_exists
45 | Should be able to check if a anime with given name exists with parameter ~anime_name~. Optional parameter ~verbose~ for debugging purposes which shows where the information was obtained from (like was the anime name in logs, in cache, downloaded locally or from online source).
46 |
47 |
48 | * Plans to add
49 | Prefer to add more sources in future. I don't have a list right now, but more sub sources or some raw sources with jp subs would be nice.
50 |
--------------------------------------------------------------------------------
/sources/__init__.py:
--------------------------------------------------------------------------------
1 | import sources.gogoanime as gogoanime
2 |
--------------------------------------------------------------------------------
/sources/gogoanime.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | from urllib.parse import urljoin, urlparse
4 | from string import Template
5 |
6 | import subprocess
7 |
8 | import utils
9 | import outputs
10 | import config
11 |
12 |
13 | gogoanime_url = 'https://gogoanime.dk/'
14 | new_page_url = urljoin(gogoanime_url, "new-season.html")
15 |
16 | # ajax_t = Template('https://gogoplay.fi/encrypt-ajax.php?id=${id}')
17 | episode_t = Template("${anime}-episode-${ep}")
18 | anime_t = Template("category/${anime}")
19 | resume_t = Template("Range: bytes=${size}-")
20 | search_t = Template(gogoanime_url + "//search.html?keyword=${name}")
21 | search_page_t = Template(
22 | gogoanime_url + "//search.html?keyword=${name}&page=${page}")
23 |
24 | script_path = os.path.join(config.project_dir, 'sources/url-to-videos.sh')
25 |
26 |
27 | def get_anime_url(anime_name):
28 | return urljoin(
29 | gogoanime_url,
30 | anime_t.substitute(anime=anime_name.lower().replace(' ', '-')))
31 |
32 |
33 | def get_episode_url(anime_name, episode):
34 | return urljoin(
35 | gogoanime_url,
36 | episode_t.substitute(
37 | anime=anime_name.lower().replace(' ', '-'),
38 | ep=episode))
39 |
40 |
41 | def process_anime_name(name):
42 | name = name.lower().replace(' ', '-')
43 | name = re.sub(r'\(|\)|:', '', name)
44 | return name
45 |
46 |
47 | def get_episode_stream_url(url):
48 | soup = utils.get_soup(url)
49 | if not soup:
50 | outputs.error_info("The video doesn't exist.")
51 | raise SystemExit
52 | iframe = soup.find('iframe')
53 | if not iframe:
54 | outputs.error_info("The video doesn't exist.")
55 | raise SystemExit
56 | link = iframe['src']
57 | if not link.startswith('http'):
58 | link = 'https:' + link
59 | return link
60 |
61 |
62 | def select_quality(urls):
63 | req_quality = f'{config.video_quality}p'
64 | for url in urls:
65 | if req_quality in url:
66 | break
67 | return url
68 |
69 |
70 | def get_direct_video_url(gogo_url):
71 | url = get_episode_stream_url(gogo_url)
72 |
73 | # got this from ani-cli program since mine broke.
74 | process = subprocess.Popen(f'bash {script_path} {url}',
75 | shell=True,
76 | stdout=subprocess.PIPE,
77 | stderr=subprocess.PIPE)
78 | out, err = process.communicate()
79 | vids = out.decode().strip().split('\n')
80 |
81 | link = select_quality(vids)
82 | _, ext = os.path.splitext(urlparse(link).path)
83 | if ext == '.m3u8':
84 | link = utils.get_m3u8_stream(link)
85 | return link, ext
86 |
87 |
88 | def get_episodes_range(anime_url):
89 | soup = utils.get_soup(anime_url)
90 | if not soup:
91 | return []
92 | rngs_obj = soup.find_all('a', ep_end=True, ep_start=True)
93 | total_rng = []
94 | for r in rngs_obj:
95 | rng = r.text
96 | rngs = rng.split('-')
97 | if rngs[0] == '0' and len(rngs) == 2:
98 | rngs[0] = '1'
99 | total_rng.append('-'.join(rngs))
100 | text = ','.join(total_rng)
101 | parsed_rng = utils.compress_range(utils.extract_range(text))
102 | return parsed_rng
103 |
104 |
105 | def get_page(url=gogoanime_url):
106 | soup = utils.get_soup(url)
107 | div = soup.find('div', {'class': 'last_episodes'})
108 | eps = []
109 | for li in div.find_all('li'):
110 | try:
111 | link = li.find('a')['href']
112 | eps.append(parse_url(link))
113 | except SystemExit:
114 | continue
115 | return eps
116 |
117 |
118 | def home_page():
119 | return get_page()
120 |
121 |
122 | def new_page():
123 | return get_page(new_page_url)
124 |
125 |
126 | def parse_url(url):
127 | whole_name = url.split('/')[-1]
128 | match = re.match(r'(.+)-episode-([0-9]+)', whole_name)
129 | if match:
130 | anime_name = match.group(1)
131 | episode = match.group(2)
132 | elif "category" in url:
133 | anime_name = whole_name
134 | episode = None
135 | else:
136 | outputs.error_info("URL couldn't be parsed.")
137 | raise SystemExit
138 | return anime_name, episode
139 |
140 |
141 | def verify_anime_exists(anime_name, verbose=False):
142 | if utils.read_log(anime_name) is not None:
143 | if verbose:
144 | outputs.normal_info(anime_name, 'LOG', reverse=True)
145 | return True
146 | elif anime_name in utils.read_cache(complete=True):
147 | if verbose:
148 | outputs.normal_info(anime_name, 'CACHE', reverse=True)
149 | return True
150 | elif utils.get_anime_path(anime_name, check=True)[0]:
151 | if verbose:
152 | outputs.normal_info(anime_name, 'LOCAL', reverse=True)
153 | return True
154 | elif utils.get_soup(get_anime_url(anime_name)) is not None:
155 | if verbose:
156 | outputs.normal_info(anime_name, 'SITE', reverse=True)
157 | return True
158 | else:
159 | return False
160 |
161 |
162 | def search_anime(keywords):
163 | url = search_t.substitute(name=keywords)
164 | soup = utils.get_soup(url)
165 | plist = soup.find("ul", {"class": "pagination-list"})
166 | utils.clear_cache()
167 |
168 | def search_results(s):
169 | all_res = s.find("ul", {"class": "items"})
170 | for list_item in all_res.find_all("li"):
171 | an = list_item.p.a["href"].split("/")[-1]
172 | utils.write_cache(an, append=True)
173 | outputs.normal_info(an, end=" \t")
174 | outputs.normal_info(list_item.p.a.text)
175 |
176 | search_results(soup)
177 | if plist:
178 | for list_item in plist.find_all("li", {"class": None}):
179 | url = search_page_t.substitute(name=keywords,
180 | page=list_item.a.text)
181 | soup = utils.get_soup(url)
182 | search_results(soup)
183 |
--------------------------------------------------------------------------------
/sources/url-to-videos.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # made from a function in:
4 | # https://github.com/pystardust/ani-cli/blob/master/ani-cli
5 |
6 | gogohd_url="https://gogohd.net/"
7 | agent="Mozilla/5.0 (X11; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/100.0"
8 | refr="$gogohd_url"
9 | dpage_url=$1
10 | id=$(printf "%s" "$dpage_url" | sed -nE 's/.*id=([^&]*).*/\1/p')
11 | resp="$(curl -A "$agent" -sL "${gogohd_url}streaming.php?id=$id" |
12 | sed -nE 's/.*class="container-(.*)">/\1/p ;
13 | s/.*class="wrapper container-(.*)">/\1/p ;
14 | s/.*class=".*videocontent-(.*)">/\1/p ;
15 | s/.*data-value="(.*)">.*/\1/p ;
16 | s/.*data-status="1".*data-video="(.*)">.*/\1/p')"
17 | secret_key=$(printf "%s" "$resp" | sed -n '2p' | tr -d "\n" | od -A n -t x1 | tr -d " |\n")
18 | iv=$(printf "%s" "$resp" | sed -n '3p' | tr -d "\n" | od -A n -t x1 | tr -d " |\n")
19 | second_key=$(printf "%s" "$resp" | sed -n '4p' | tr -d "\n" | od -A n -t x1 | tr -d " |\n")
20 | token=$(printf "%s" "$resp" | head -1 | base64 -d | openssl enc -d -aes256 -K "$secret_key" -iv "$iv" | sed -nE 's/.*&(token.*)/\1/p')
21 | ajax=$(printf '%s' "$id" | openssl enc -e -aes256 -K "$secret_key" -iv "$iv" -a)
22 | data=$(curl -A "$agent" -sL -H "X-Requested-With:XMLHttpRequest" "${gogohd_url}encrypt-ajax.php?id=${ajax}&alias=${id}&${token}" | sed -e 's/{"data":"//' -e 's/"}/\n/' -e 's/\\//g')
23 | result_links="$(printf '%s' "$data" | base64 -d 2>/dev/null | openssl enc -d -aes256 -K "$second_key" -iv "$iv" 2>/dev/null | sed -e 's/\].*/\]/' -e 's/\\//g' | grep -Eo 'https://[-a-zA-Z0-9@:%._\+~#=][a-zA-Z0-9][-a-zA-Z0-9@:%_\+.~#?&\/\/=]*')"
24 | printf "%s\n" $result_links
25 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import math
4 | import datetime as dt
5 | import pycurl
6 | import m3u8
7 | import requests
8 |
9 | from bs4 import BeautifulSoup
10 |
11 | import config
12 | import outputs
13 |
14 |
15 | class Log:
16 | def __init__(self, logline, eps=None):
17 | if not logline:
18 | self.anime = ''
19 | self.source = config.anime_source
20 | self.eps = ''
21 | self.last_updated = None
22 | return
23 | data = logline.split()
24 | if len(data) == 1: # only anime name
25 | self.anime = data[0]
26 | self.source = config.anime_source
27 | else:
28 | self.source = data[0]
29 | self.anime = data[1]
30 | if eps:
31 | self.eps = eps
32 | self.last_updated = dt.datetime.now()
33 | else:
34 | self.eps = data[2]
35 | if len(data) > 3:
36 | self.last_updated = dt.datetime.fromtimestamp(int(data[3]))
37 | else:
38 | self.last_updated = None
39 |
40 | @property
41 | def last_updated_fmt(self):
42 | if self.last_updated:
43 | return self.last_updated.strftime("%Y-%m-%d %H:%M %A")
44 | return ''
45 |
46 | def add(self, eps):
47 | self.eps = compress_range(extract_range(f'{self.eps},{eps}'))
48 |
49 | self.last_updated = dt.datetime.now()
50 | return self
51 |
52 | def edit(self, eps):
53 | self.eps = eps
54 | self.last_updated = dt.datetime.now()
55 | return self
56 |
57 | def __str__(self):
58 | rep = (f'{self.source} {self.anime} {self.eps}')
59 | if self.last_updated:
60 | rep += f' {int(self.last_updated.timestamp())}'
61 | return rep
62 |
63 | @property
64 | def _eps(self):
65 | if len(self.eps) > 10:
66 | data = re.split(',|-', self.eps)
67 | return f'{data[0]}...{data[-1]}'
68 | else:
69 | return self.eps
70 |
71 | def show(self):
72 | rep = f'{outputs.Fore.BLUE}{self.source}{outputs.Fore.RESET}'
73 | rep += f' {self._eps}\t\t{self.anime}'
74 | if self.last_updated:
75 | rep += f' ({self.last_updated_fmt})'
76 | return rep
77 |
78 |
79 | def get_soup(url):
80 | r = requests.get(url, headers=config.req_headers)
81 | if r.status_code != 200:
82 | outputs.error_info(f"Request Failed: {url}")
83 | raise SystemExit
84 | return BeautifulSoup(r.text, 'html.parser')
85 |
86 |
87 | def download_file(url, filepath, replace=False):
88 | if os.path.exists(filepath) and not replace:
89 | outputs.warning_info('File already downloaded, skipping.')
90 | return
91 | part_file = f'{filepath}.part'
92 |
93 | c = pycurl.Curl()
94 | c.setopt(pycurl.URL, url)
95 | c.setopt(pycurl.NOPROGRESS, 0)
96 |
97 | curl_header = [f'{k}: {v}' for k, v in config.down_headers.items()]
98 |
99 | if os.path.exists(part_file) and not replace:
100 | outputs.normal_info('Previously Downloaded part found.')
101 | wmode = 'ab'
102 | curl_header.append(
103 | config.resume_t.substitute(size=os.path.getsize(part_file)))
104 | else:
105 | wmode = 'wb'
106 | c.setopt(pycurl.HTTPHEADER, curl_header)
107 | try:
108 | with open(part_file, wmode) as writer:
109 | c.setopt(pycurl.WRITEDATA, writer)
110 | c.perform()
111 | c.close()
112 | except (KeyboardInterrupt, pycurl.error) as e:
113 | c.close()
114 | outputs.error_info(f"Download Failed {e}")
115 | raise SystemExit
116 |
117 | os.rename(part_file, filepath)
118 |
119 |
120 | def download_m3u8(url, filepath, replace=False):
121 | if os.path.exists(filepath) and not replace:
122 | outputs.warning_info('File already downloaded, skipping.')
123 | return
124 | part_file = f'{filepath}.part'
125 | if os.path.exists(part_file) and not replace:
126 | outputs.normal_info('Previously Downloaded part found.')
127 | # TODO: resume download
128 | media = m3u8.load(url)
129 | total = len(media.segments)
130 | with open(part_file, 'wb') as writer:
131 | c = pycurl.Curl()
132 | curl_header = [f'{k}: {v}' for k, v in config.down_headers.items()]
133 | c.setopt(pycurl.HTTPHEADER, curl_header)
134 | c.setopt(pycurl.WRITEDATA, writer)
135 | try:
136 | for i, f in enumerate(media.segments):
137 | uri = f.absolute_uri
138 | c.setopt(pycurl.URL, uri)
139 | c.perform()
140 | outputs.normal_info('\rDownloaded :',
141 | '#' * (((i + 1) * 40) // total),
142 | f'{(i+1)*100//total}% ({i+1} of {total})',
143 | end="")
144 | c.close()
145 | except (KeyboardInterrupt, pycurl.error) as e:
146 | c.close()
147 | raise SystemExit(f"Download Failed {e}")
148 | outputs.normal_info()
149 | os.rename(part_file, filepath)
150 |
151 |
152 | def get_m3u8_stream(m3u8_url):
153 | media = m3u8.load(m3u8_url)
154 | if media.data['is_variant']:
155 | res = sorted(((i, p.stream_info.resolution[1])
156 | for i, p in enumerate(media.playlists)),
157 | key=lambda x: x[1])
158 | res_high = list(filter(lambda r: r[1] >= config.video_quality, res))
159 | if len(res_high) == 0:
160 | # if higher than config not available choose best
161 | ind = res[-1][0]
162 | else:
163 | # choose the closest but > the config
164 | ind = res_high[0][0]
165 | return media.playlists[ind].absolute_uri
166 | return m3u8_url
167 |
168 |
169 | def read_cache(num=1, complete=False):
170 | if not os.path.exists(config.cachefile):
171 | return list() if complete else None
172 | else:
173 | with open(config.cachefile, 'r') as r:
174 | lines = r.readlines()
175 | if complete:
176 | return list(map(lambda l: l.strip(), lines))
177 | else:
178 | try:
179 | return lines[num - 1].strip()
180 | except IndexError:
181 | outputs.error_info("The choice number is too large.")
182 | outputs.prompt_val("Total items in cache", len(lines), 'error')
183 | raise SystemExit
184 |
185 |
186 | def write_cache(anime, append=False):
187 | with open(config.cachefile, 'a' if append else 'w') as w:
188 | w.write(f'{anime}\n')
189 |
190 |
191 | def clear_cache():
192 | if os.path.exists(config.cachefile):
193 | os.remove(config.cachefile)
194 |
195 |
196 | def read_log(anime_name=None,
197 | number=math.inf,
198 | pattern=re.compile(r'.*'),
199 | logfile=config.logfile):
200 | if not os.path.exists(logfile):
201 | log = dict()
202 | else:
203 | # TODO need to rewrite this to use Log class
204 | log = {
205 | line[1]: " ".join(line)
206 | for i, line in enumerate(li.strip().split()
207 | for li in open(logfile, 'r')
208 | if pattern.match(li.split()[1]))
209 | if i < number
210 | }
211 | if not anime_name:
212 | return log
213 | return log.get(anime_name)
214 |
215 |
216 | def write_log(anime_name, episodes, append=True, logfile=config.logfile):
217 | log = read_log(logfile=logfile)
218 | if anime_name in log and append:
219 | log[anime_name] = str(Log(log[anime_name]).add(episodes))
220 | else:
221 | log[anime_name] = str(Log(anime_name, episodes))
222 | with open(logfile, 'w') as w:
223 | w.writelines((f'{v}\n' for v in log.values()))
224 |
225 |
226 | def remove_anime_from_log(anime_name, logfile=config.logfile):
227 | anime_list = read_log(logfile=logfile)
228 | if anime_name in anime_list:
229 | anime_list.pop(anime_name)
230 | else:
231 | return
232 | logs = sorted(
233 | map(Log, anime_list.values()),
234 | key=lambda l: ((
235 | int(l.last_updated.timestamp())
236 | if l.last_updated else 0) +
237 | (ord(l.anime[0])-ord('a'))/26),
238 | reverse=False)
239 | with open(logfile, "w") as w:
240 | for log in logs:
241 | w.write(f"{str(log)}\n")
242 |
243 |
244 | def update_tracklist(anime_name, episodes, append=True):
245 | log = read_log(anime_name, logfile=config.ongoingfile)
246 | if log:
247 | write_log(anime_name,
248 | episodes,
249 | append=append,
250 | logfile=config.ongoingfile)
251 |
252 |
253 | def update_watchlater(anime_name, episode=None):
254 | log = read_log(anime_name, logfile=config.watchlaterfile)
255 | if log:
256 | eps = set(extract_range(Log(log).eps)).difference(
257 | set([episode])
258 | )
259 | if not eps:
260 | remove_anime_from_log(anime_name, logfile=config.watchlaterfile)
261 | else:
262 | write_log(anime_name,
263 | compress_range(eps),
264 | append=True,
265 | logfile=config.watchlaterfile)
266 |
267 |
268 | def compress_range(range_list):
269 | range_list = sorted(range_list)
270 | if len(range_list) == 0:
271 | return ''
272 | rng_str = f'{range_list[0]}'
273 | prev = range_list[0]
274 | rng = False
275 | for r in range_list[1:]:
276 | if r == prev:
277 | continue
278 | if r == (prev + 1):
279 | if not rng:
280 | rng_str += '-'
281 | rng = True
282 | else:
283 | if rng:
284 | rng_str += f'{prev},{r}'
285 | else:
286 | rng_str += f',{r}'
287 | rng = False
288 | prev = r
289 |
290 | if rng:
291 | rng_str += f'{prev}'
292 | return rng_str
293 |
294 |
295 | def extract_range(range_str):
296 | if range_str is None or range_str.strip() == '':
297 | return
298 | ranges = range_str.replace(" ", "").split(',')
299 | try:
300 | for r in ranges:
301 | if r.strip() == '':
302 | continue
303 | if '-' in r:
304 | rng = r.split('-')
305 | if len(rng) > 2:
306 | outputs.prompt_val('Incorrect formatting', r, 'error')
307 | raise SystemExit
308 | yield from range(int(rng[0]), int(rng[1]) + 1)
309 | else:
310 | yield int(r)
311 | except ValueError as e:
312 | outputs.error_info('Incorrect formatting: use integers for episodes')
313 | outputs.error_tag(e)
314 | raise SystemExit
315 |
316 |
317 | def recursive_getattr(obj, attr=None):
318 | if attr is None or '.' not in attr:
319 | return dir(obj)
320 | else:
321 | attrs = attr.split('.', 1)
322 | try:
323 | return map(lambda s: f'{attrs[0]}.{s}',
324 | recursive_getattr(getattr(obj, attrs[0]), attrs[1]))
325 | except AttributeError:
326 | return []
327 |
328 |
329 | def get_anime_path(anime_name, *, make=False, check=False):
330 | """returns tuple (anime path, existed before)
331 | """
332 | anime_dir = os.path.join(config.anime_dir, anime_name)
333 | if not os.path.isdir(anime_dir):
334 | if make:
335 | os.mkdir(anime_dir)
336 | return anime_dir, False
337 | elif check:
338 | return None, False
339 | else:
340 | return anime_dir, False
341 | return anime_dir, True
342 |
343 |
344 | def get_local_episodes(pattrn=r'^[0-9a-z-]+$'):
345 | animes = dict()
346 | for folder in os.listdir(config.anime_dir):
347 | if not os.path.isdir(os.path.join(config.anime_dir, folder)) or \
348 | not re.match(pattrn, folder):
349 | continue
350 | animes[folder] = ''
351 | for f in os.listdir(os.path.join(config.anime_dir, folder)):
352 | m = re.match(r'^ep([0-9]+)\.[a-z0-9]+$', f)
353 | if m:
354 | animes[folder] += f',{m.group(1)}'
355 | return animes
356 |
357 |
358 | def get_episode_path(anime_name,
359 | episode,
360 | *,
361 | ext='.mp4',
362 | make=False,
363 | check=False):
364 | anime_dir, existed = get_anime_path(anime_name, make=make, check=check)
365 | if anime_dir is None:
366 | return None
367 | ep_path = os.path.join(anime_dir, f'ep{episode:02d}{ext}')
368 | if check and not os.path.isfile(ep_path):
369 | return None
370 | return ep_path
371 |
372 |
373 | def display_anime_eps_list(animes_dict):
374 | tracklist = read_log(logfile=config.ongoingfile)
375 | log = read_log()
376 | clear_cache()
377 | for name, ep in animes_dict:
378 | outputs.normal_info(f"{name} : ep-{ep}" if ep else name, end=" ")
379 | write_cache(name, append=True)
380 | if name in tracklist:
381 | watched = extract_range(Log(tracklist[name]).eps)
382 | if not ep:
383 | outputs.warning_tag("TRACKED", end="")
384 | elif int(ep) in watched:
385 | outputs.warning_tag("WATCHED", end="")
386 | else:
387 | outputs.success_tag("NEW", end="")
388 | elif name in log:
389 | outputs.normal_tag("LOGGED", end="")
390 |
391 | outputs.normal_info()
392 | return
393 |
394 |
395 | def canon_episodes(anime_name, episodes=None):
396 | url = f"https://www.animefillerlist.com/shows/{anime_name}"
397 | soup = get_soup(url)
398 | eps_str = soup.find("div", {"class": "manga_canon"}).text.split(":")[-1]
399 | rng = extract_range(eps_str)
400 | if episodes:
401 | episodes = set(episodes)
402 | rng = filter(lambda x: x in episodes, rng)
403 | return compress_range(rng)
404 |
405 |
406 | def completion_list(iterator):
407 | return [f'{s} ' for s in iterator]
408 |
--------------------------------------------------------------------------------