commit 21bfbfb13959b16dd1437a46ab57b855c1923c6f Author: Finnley Somdahl <87634197+rebelonion@users.noreply.github.com> Date: Tue Oct 17 18:42:43 2023 -0500 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dfe07704 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a68e5b57 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Log/OS Files +*.log + +# Android Studio generated files and folders +captures/ +.externalNativeBuild/ +.cxx/ +*.apk +output.json + +# IntelliJ +*.iml +.idea/ + +# Keystore files +*.jks +*.keystore + +# Google Services (e.g. APIs or Firebase) +google-services.json + +# Android Profiling +*.hprof diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 00000000..4299de36 --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# **Dantotsu** +

+ + +

+Dantotsu is crafted from the ashes of Saikou and based on simplistic yet state-of-the-art elegance. It is an [Anilist](https://anilist.co/) only client, which also lets you stream-download Anime & Manga through extensions. +

+Dantotsu (断トツ; Dan-totsu) literally means the best of the best in Japanese. Well, we would like to say this is the best open source app for anime and manga on Android, but hey, try it out yourself & judge! + +
+
+ +
+### 🌟STAR THIS REPOSITORY TO SUPPORT THE DEVELOPER AND ENCOURAGE THE DEVELOPMENT OF THE APPLICATION! + +> **Warning** +> +> Please do not attempt to upload Dantotsu or any of it's forks on Playstore or any other Android appstores on the internet. Doing so, may infringe their terms and conditions. This may result to legal action or immediate take-down of the app. + + + + +## APP FEATURES + +- Easy and functional way to both, watch anime and read manga, ad-free. + +- A completely open source app with a nice UI & Animations :) + +- Aniyomi extension support built right into the app. + +- Synchronize anime and manga real-time with AniList and MyAnimeList. Easily categorise anime and manga based on your current status. (Powered by AniList) + +- Find all shows using thoroughly and frequently updated list of all trending, popular and ongoing anime based on scores. + +- View extensive details about anime shows, movies and manga titles. It also features ability to countdown to the next episode of airing anime. (Powered by AniList & MyAnimeList) + +- Get notified when new episodes/chapters are released! + + +* **Available Anime sources:-** +NONE BUILT IN! +add your own extensions in the settings menu (Dantotsu has affiliation with any of the extensions) + + +* **Available Manga sources:-** + NONE BUILT IN! + add your own extensions in the settings menu (Dantotsu has affiliation with any of the extensions) + +## Planned Stuff + +- get app out of alpha + +- Accent Color Change (RIP Hot Pink Supremacy.) + + +## Rejected Stuff (still rejected) + +- Sources of any language except English + +- News Section in the App + +- Comment Section + + +## WANT TO CONTRIBUTE? + +- All contributions are welcome, from code to documentation to graphics to design suggestions to bug reports. Please use GitHub to its fullest; contribute Pull Requests, contribute tutorials or other content- whatever you have to offer, we can use it! + +- You can come hang out with our awesome community and request new features and report any bugs or issue at our discord server too. + +### Official Discord Server + +

+ + + +

+ + +### VISIT FOR MORE INFORMATION:- + +https://saikou.me/ + +## DISCLAIMER + +* Dantotsu by itself only provides an anime and manga tracker and does not provide any anime or manga streaming or downloading capabilities. + +* Dantotsu or any of its developer/staff don't host any of the content found inside Dantotsu. Any and all images and anime/manga information found in the app are taken from various public APIs (AniList, MyAnimeList, Kitsu). + +* Furthermore, all of the anime/manga links found in Dantotsu are taken from various 3rd party plugins and have no affiliation with Dantotsu or its staff. + +* Dantotsu or it's owners aren't liable for any misuse of any of the contents found inside or outside of the app and cannot be held accountable for the distribution of any of the contents found inside the app. + +* By using Dantotsu, you comply to the fact that the developer of the app is not responsible for any of the contents found in the app. You also agree to the fact that you may not use Dantotsu to download or stream any copyrighted content. + +* If the internet infringement issues are involved, please contact the source website. The developer does not assume any legal responsibility. + +## License + +Dantotsu is licensed under the [GNU General Public License v3.0](LICENSE.md) diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 00000000..92118fcd --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,4 @@ +/build +/debug +/debug/output-metadata.json +/release \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 00000000..e1fa4462 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,119 @@ +plugins { + id 'com.android.application' + id 'com.google.gms.google-services' + id 'com.google.firebase.crashlytics' + id 'kotlin-android' + id 'kotlinx-serialization' + id 'org.jetbrains.kotlin.android' + id 'com.google.devtools.ksp' + +} + +def gitCommitHash = providers.exec { + commandLine("git", "rev-parse", "--verify", "--short", "HEAD") +}.standardOutput.asText.get().trim() + +android { + compileSdk 34 + + defaultConfig { + applicationId "ani.dantotsu" + minSdk 23 + targetSdk 34 + versionCode ((System.currentTimeMillis() / 60000).toInteger()) + versionName "0.0.1" + signingConfig signingConfigs.debug + } + + buildTypes { + debug { + //applicationIdSuffix ".beta" + debuggable true + versionNameSuffix "." + gitCommitHash + } + release { + debuggable false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + buildFeatures { + viewBinding true + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' + freeCompilerArgs = ["-Xcontext-receivers", "-Xmulti-platform"] + } + namespace 'ani.dantotsu' +} + +dependencies { +// Core + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'androidx.browser:browser:1.6.0' + implementation 'androidx.core:core-ktx:1.12.0' + implementation 'androidx.fragment:fragment-ktx:1.6.1' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation 'androidx.multidex:multidex:2.0.1' + implementation "androidx.work:work-runtime-ktx:2.8.1" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + + implementation 'com.github.Blatzar:NiceHttp:0.4.3' + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0' + +// Glide + ext.glide_version = '4.16.0' + api "com.github.bumptech.glide:glide:$glide_version" + implementation "com.github.bumptech.glide:glide:$glide_version" + ksp "com.github.bumptech.glide:ksp:$glide_version" + implementation "com.github.bumptech.glide:okhttp3-integration:$glide_version" + implementation 'jp.wasabeef:glide-transformations:4.3.0' + +// FireBase + implementation platform('com.google.firebase:firebase-bom:32.2.3') + implementation 'com.google.firebase:firebase-analytics-ktx:21.3.0' + implementation 'com.google.firebase:firebase-crashlytics-ktx:18.4.3' + +// Exoplayer + ext.exo_version = '1.1.1' + implementation "androidx.media3:media3-exoplayer:$exo_version" + implementation "androidx.media3:media3-ui:$exo_version" + implementation "androidx.media3:media3-exoplayer-hls:$exo_version" + implementation "androidx.media3:media3-exoplayer-dash:$exo_version" + implementation "androidx.media3:media3-datasource-okhttp:$exo_version" + implementation "androidx.media3:media3-session:$exo_version" + +// UI + implementation 'com.google.android.material:material:1.10.0' + implementation 'nl.joery.animatedbottombar:library:1.1.0' + implementation 'io.noties.markwon:core:4.6.2' + implementation 'com.flaviofaria:kenburnsview:1.0.7' + implementation 'com.davemorrissey.labs:subsampling-scale-image-view-androidx:3.10.0' + implementation 'com.alexvasilkov:gesture-views:2.8.3' + implementation 'com.github.VipulOG:ebook-reader:0.1.6' + +// Aniyomi + implementation 'io.reactivex:rxjava:1.3.8' + implementation 'io.reactivex:rxandroid:1.2.1' + implementation 'ru.beryukhov:flowreactivenetwork:1.0.4' + implementation 'ca.gosyer:voyager-navigator:1.0.0-rc07' + implementation 'com.squareup.logcat:logcat:0.1' + implementation 'com.github.inorichi.injekt:injekt-core:65b0440' + implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.11' + implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.11' + implementation 'com.squareup.okhttp3:okhttp-dnsoverhttps' + implementation 'com.squareup.okio:okio:3.3.0' + implementation 'ch.acra:acra-http:5.9.7' + implementation 'org.jsoup:jsoup:1.15.4' + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json-okio:1.5.0' + implementation 'com.jakewharton.rxrelay:rxrelay:1.2.0' + implementation 'com.github.tachiyomiorg:unifile:17bec43' + implementation 'com.github.gpanther:java-nat-sort:natural-comparator-1.1' + implementation 'androidx.preference:preference-ktx:1.2.0' + +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 00000000..8d6bcddf --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,61 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle.kts. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + +# Keep `Companion` object fields of serializable classes. +# This avoids serializer lookup through `getDeclaredClasses` as done for named companion objects. +-if @kotlinx.serialization.Serializable class ** +-keepclassmembers class <1> { + static <1>$Companion Companion; +} + +# Keep `serializer()` on companion objects (both default and named) of serializable classes. +-if @kotlinx.serialization.Serializable class ** { + static **$* *; +} +-keepclassmembers class <2>$<3> { + kotlinx.serialization.KSerializer serializer(...); +} + +# Keep `INSTANCE.serializer()` of serializable objects. +-if @kotlinx.serialization.Serializable class ** { + public static ** INSTANCE; +} +-keepclassmembers class <1> { + public static <1> INSTANCE; + kotlinx.serialization.KSerializer serializer(...); +} + +# @Serializable and @Polymorphic are used at runtime for polymorphic serialization. +-keepattributes RuntimeVisibleAnnotations,AnnotationDefault + +# Serializer for classes with named companion objects are retrieved using `getDeclaredClasses`. +# If you have any, uncomment and replace classes with those containing named companion objects. +#-keepattributes InnerClasses # Needed for `getDeclaredClasses`. +#-if @kotlinx.serialization.Serializable class +#com.example.myapplication.HasNamedCompanion, # <-- List serializable classes with named companions. +#com.example.myapplication.HasNamedCompanion2 +#{ +# static **$* *; +#} +#-keepnames class <1>$$serializer { # -keepnames suffices; class is kept when serializer() is kept. +# static <1>$$serializer INSTANCE; +#} \ No newline at end of file diff --git a/app/src/debug/res/values/strings.xml b/app/src/debug/res/values/strings.xml new file mode 100644 index 00000000..3c0d72af --- /dev/null +++ b/app/src/debug/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Dantotsu α + \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..a39a2788 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/App.kt b/app/src/main/java/ani/dantotsu/App.kt new file mode 100644 index 00000000..9b57909c --- /dev/null +++ b/app/src/main/java/ani/dantotsu/App.kt @@ -0,0 +1,87 @@ +package ani.dantotsu + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Context +import android.os.Bundle +import androidx.multidex.MultiDex +import androidx.multidex.MultiDexApplication +import ani.dantotsu.aniyomi.anime.custom.AppModule +import ani.dantotsu.aniyomi.anime.custom.PreferenceModule +import ani.dantotsu.aniyomi.data.Notifications +import ani.dantotsu.aniyomi.util.logcat +import ani.dantotsu.others.DisabledReports +import com.google.firebase.crashlytics.ktx.crashlytics +import com.google.firebase.ktx.Firebase +import logcat.AndroidLogcatLogger +import logcat.LogPriority +import logcat.LogcatLogger +import uy.kohesive.injekt.Injekt + +@SuppressLint("StaticFieldLeak") +class App : MultiDexApplication() { + override fun attachBaseContext(base: Context?) { + super.attachBaseContext(base) + MultiDex.install(this) + } + + init { + instance = this + } + + val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks() + + override fun onCreate() { + super.onCreate() + registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks) + + Firebase.crashlytics.setCrashlyticsCollectionEnabled(!DisabledReports) + initializeNetwork(baseContext) + + Injekt.importModule(AppModule(this)) + Injekt.importModule(PreferenceModule(this)) + + setupNotificationChannels() + if (!LogcatLogger.isInstalled) { + LogcatLogger.install(AndroidLogcatLogger(LogPriority.VERBOSE)) + } + + } + + private fun setupNotificationChannels() { + try { + Notifications.createChannels(this) + } catch (e: Exception) { + logcat(LogPriority.ERROR, e) { "Failed to modify notification channels" } + } + } + + inner class FTActivityLifecycleCallbacks : ActivityLifecycleCallbacks { + var currentActivity: Activity? = null + override fun onActivityCreated(p0: Activity, p1: Bundle?) {} + override fun onActivityStarted(p0: Activity) { + currentActivity = p0 + } + + override fun onActivityResumed(p0: Activity) { + currentActivity = p0 + } + + override fun onActivityPaused(p0: Activity) {} + override fun onActivityStopped(p0: Activity) {} + override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {} + override fun onActivityDestroyed(p0: Activity) {} + } + + companion object { + private var instance: App? = null + var context : Context? = null + fun currentContext(): Context? { + return instance?.mFTActivityLifecycleCallbacks?.currentActivity ?: context + } + + fun currentActivity(): Activity? { + return instance?.mFTActivityLifecycleCallbacks?.currentActivity + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/Functions.kt b/app/src/main/java/ani/dantotsu/Functions.kt new file mode 100644 index 00000000..f175ff5c --- /dev/null +++ b/app/src/main/java/ani/dantotsu/Functions.kt @@ -0,0 +1,873 @@ +package ani.dantotsu + +import android.animation.ObjectAnimator +import android.annotation.SuppressLint +import android.app.Activity +import android.app.DatePickerDialog +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.DialogInterface +import android.content.Intent +import android.content.res.Configuration +import android.content.res.Resources.getSystem +import android.graphics.Bitmap +import android.graphics.Color +import android.media.MediaScannerConnection +import android.net.ConnectivityManager +import android.net.NetworkCapabilities.* +import android.net.Uri +import android.os.* +import android.provider.Settings +import android.telephony.TelephonyManager +import android.text.InputFilter +import android.text.Spanned +import android.util.AttributeSet +import android.view.* +import android.view.ViewGroup.LayoutParams.WRAP_CONTENT +import android.view.animation.* +import android.widget.* +import androidx.appcompat.app.AppCompatDelegate +import androidx.core.content.ContextCompat.getSystemService +import androidx.core.content.FileProvider +import androidx.core.math.MathUtils.clamp +import androidx.core.view.* +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.MutableLiveData +import androidx.recyclerview.widget.RecyclerView +import androidx.viewpager2.widget.ViewPager2 +import ani.dantotsu.BuildConfig.APPLICATION_ID +import ani.dantotsu.connections.anilist.Genre +import ani.dantotsu.connections.anilist.api.FuzzyDate +import ani.dantotsu.databinding.ItemCountDownBinding +import ani.dantotsu.media.Media +import ani.dantotsu.parsers.ShowResponse +import ani.dantotsu.settings.UserInterfaceSettings +import com.bumptech.glide.Glide +import com.bumptech.glide.load.model.GlideUrl +import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade +import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView +import com.google.android.material.bottomnavigation.BottomNavigationView +import com.google.android.material.bottomsheet.BottomSheetBehavior +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import com.google.android.material.internal.ViewUtils +import com.google.android.material.snackbar.Snackbar +import kotlinx.coroutines.* +import nl.joery.animatedbottombar.AnimatedBottomBar +import java.io.* +import java.lang.Runnable +import java.lang.reflect.Field +import java.util.* +import kotlin.math.* + + +var statusBarHeight = 0 +var navBarHeight = 0 +val Int.dp: Float get() = (this / getSystem().displayMetrics.density) +val Float.px: Int get() = (this * getSystem().displayMetrics.density).toInt() + +lateinit var bottomBar: AnimatedBottomBar +var selectedOption = 1 + +object Refresh { + fun all() { + for (i in activity) { + activity[i.key]!!.postValue(true) + } + } + + val activity = mutableMapOf>() +} + +fun currContext(): Context? { + return App.currentContext() +} + +fun currActivity(): Activity? { + return App.currentActivity() +} + +var loadMedia: Int? = null +var loadIsMAL = false + +fun logger(e: Any?, print: Boolean = true) { + if (print) + println(e) +} + +fun saveData(fileName: String, data: Any?, context: Context? = null) { + tryWith { + val a = context ?: currContext() + if (a != null) { + val fos: FileOutputStream = a.openFileOutput(fileName, Context.MODE_PRIVATE) + val os = ObjectOutputStream(fos) + os.writeObject(data) + os.close() + fos.close() + } + } +} + +@Suppress("UNCHECKED_CAST") +fun loadData(fileName: String, context: Context? = null, toast: Boolean = true): T? { + val a = context ?: currContext() + try { + if (a?.fileList() != null) + if (fileName in a.fileList()) { + val fileIS: FileInputStream = a.openFileInput(fileName) + val objIS = ObjectInputStream(fileIS) + val data = objIS.readObject() as T + objIS.close() + fileIS.close() + return data + } + } catch (e: Exception) { + if (toast) snackString(a?.getString(R.string.error_loading_data, fileName)) + e.printStackTrace() + } + return null +} + +fun initActivity(a: Activity) { + val window = a.window + WindowCompat.setDecorFitsSystemWindows(window, false) + val uiSettings = loadData("ui_settings", toast = false) ?: UserInterfaceSettings().apply { + saveData("ui_settings", this) + } + uiSettings.darkMode.apply { + AppCompatDelegate.setDefaultNightMode( + when (this) { + true -> AppCompatDelegate.MODE_NIGHT_YES + false -> AppCompatDelegate.MODE_NIGHT_NO + else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM + } + ) + } + if (uiSettings.immersiveMode) { + if (navBarHeight == 0) { + ViewCompat.getRootWindowInsets(window.decorView.findViewById(android.R.id.content))?.apply { + navBarHeight = this.getInsets(WindowInsetsCompat.Type.systemBars()).bottom + } + } + a.hideStatusBar() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && statusBarHeight == 0 && a.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { + window.decorView.rootWindowInsets?.displayCutout?.apply { + if (boundingRects.size > 0) { + statusBarHeight = min(boundingRects[0].width(), boundingRects[0].height()) + } + } + } + } else + if (statusBarHeight == 0) { + val windowInsets = ViewCompat.getRootWindowInsets(window.decorView.findViewById(android.R.id.content)) + if (windowInsets != null) { + val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + statusBarHeight = insets.top + navBarHeight = insets.bottom + } + } +} + +@Suppress("DEPRECATION") +fun Activity.hideSystemBars() { + window.decorView.systemUiVisibility = ( + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + or View.SYSTEM_UI_FLAG_FULLSCREEN + or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + ) +} + +@Suppress("DEPRECATION") +fun Activity.hideStatusBar() { + window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) +} + +open class BottomSheetDialogFragment : BottomSheetDialogFragment() { + override fun onStart() { + super.onStart() + if (this.resources.configuration.orientation != Configuration.ORIENTATION_PORTRAIT) { + val behavior = BottomSheetBehavior.from(requireView().parent as View) + behavior.state = BottomSheetBehavior.STATE_EXPANDED + } + } + + override fun show(manager: FragmentManager, tag: String?) { + val ft = manager.beginTransaction() + ft.add(this, tag) + ft.commitAllowingStateLoss() + } +} + +fun isOnline(context: Context): Boolean { + val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + return tryWith { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + val cap = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) + return@tryWith if (cap != null) { + when { + cap.hasTransport(TRANSPORT_BLUETOOTH) || + cap.hasTransport(TRANSPORT_CELLULAR) || + cap.hasTransport(TRANSPORT_ETHERNET) || + cap.hasTransport(TRANSPORT_LOWPAN) || + cap.hasTransport(TRANSPORT_USB) || + cap.hasTransport(TRANSPORT_VPN) || + cap.hasTransport(TRANSPORT_WIFI) || + cap.hasTransport(TRANSPORT_WIFI_AWARE) -> true + + else -> false + } + } else false + } else true + } ?: false +} + +fun startMainActivity(activity: Activity, bundle: Bundle? = null) { + activity.finishAffinity() + activity.startActivity( + Intent( + activity, + MainActivity::class.java + ).apply { + addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) + if (bundle != null) putExtras(bundle) + } + ) +} + + +class DatePickerFragment(activity: Activity, var date: FuzzyDate = FuzzyDate().getToday()) : DialogFragment(), + DatePickerDialog.OnDateSetListener { + var dialog: DatePickerDialog + + init { + val c = Calendar.getInstance() + val year = date.year ?: c.get(Calendar.YEAR) + val month = if (date.month != null) date.month!! - 1 else c.get(Calendar.MONTH) + val day = date.day ?: c.get(Calendar.DAY_OF_MONTH) + dialog = DatePickerDialog(activity, this, year, month, day) + dialog.setButton( + DialogInterface.BUTTON_NEUTRAL, + activity.getString(R.string.remove) + ) { dialog, which -> + if (which == DialogInterface.BUTTON_NEUTRAL) { + date = FuzzyDate() + } + } + } + + override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) { + date = FuzzyDate(year, month + 1, day) + } +} + +class InputFilterMinMax(private val min: Double, private val max: Double, private val status: AutoCompleteTextView? = null) : + InputFilter { + override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { + try { + val input = (dest.toString() + source.toString()).toDouble() + if (isInRange(min, max, input)) return null + } catch (nfe: NumberFormatException) { + logger(nfe.stackTraceToString()) + } + return "" + } + + @SuppressLint("SetTextI18n") + private fun isInRange(a: Double, b: Double, c: Double): Boolean { + val statusStrings = currContext()!!.resources.getStringArray(R.array.status_manga)[2] + + if (c == b) { + status?.setText(statusStrings, false) + status?.parent?.requestLayout() + } + return if (b > a) c in a..b else c in b..a + } +} + + +class ZoomOutPageTransformer(private val uiSettings: UserInterfaceSettings) : ViewPager2.PageTransformer { + override fun transformPage(view: View, position: Float) { + if (position == 0.0f && uiSettings.layoutAnimations) { + setAnimation(view.context, view, uiSettings, 300, floatArrayOf(1.3f, 1f, 1.3f, 1f), 0.5f to 0f) + ObjectAnimator.ofFloat(view, "alpha", 0f, 1.0f).setDuration((200 * uiSettings.animationSpeed).toLong()).start() + } + } +} + +fun setAnimation( + context: Context, + viewToAnimate: View, + uiSettings: UserInterfaceSettings, + duration: Long = 150, + list: FloatArray = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f), + pivot: Pair = 0.5f to 0.5f +) { + if (uiSettings.layoutAnimations) { + val anim = ScaleAnimation( + list[0], + list[1], + list[2], + list[3], + Animation.RELATIVE_TO_SELF, + pivot.first, + Animation.RELATIVE_TO_SELF, + pivot.second + ) + anim.duration = (duration * uiSettings.animationSpeed).toLong() + anim.setInterpolator(context, R.anim.over_shoot) + viewToAnimate.startAnimation(anim) + } +} + + +class FadingEdgeRecyclerView : RecyclerView { + + constructor(context: Context) : super(context) + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) + constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) + + override fun isPaddingOffsetRequired(): Boolean { + return !clipToPadding + } + + override fun getLeftPaddingOffset(): Int { + return if (clipToPadding) 0 else -paddingLeft + } + + override fun getTopPaddingOffset(): Int { + return if (clipToPadding) 0 else -paddingTop + } + + override fun getRightPaddingOffset(): Int { + return if (clipToPadding) 0 else paddingRight + } + + override fun getBottomPaddingOffset(): Int { + return if (clipToPadding) 0 else paddingBottom + } +} + +fun levenshtein(lhs: CharSequence, rhs: CharSequence): Int { + if (lhs == rhs) { + return 0 + } + if (lhs.isEmpty()) { + return rhs.length + } + if (rhs.isEmpty()) { + return lhs.length + } + + val lhsLength = lhs.length + 1 + val rhsLength = rhs.length + 1 + + var cost = Array(lhsLength) { it } + var newCost = Array(lhsLength) { 0 } + + for (i in 1 until rhsLength) { + newCost[0] = i + + for (j in 1 until lhsLength) { + val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1 + + val costReplace = cost[j - 1] + match + val costInsert = cost[j] + 1 + val costDelete = newCost[j - 1] + 1 + + newCost[j] = min(min(costInsert, costDelete), costReplace) + } + + val swap = cost + cost = newCost + newCost = swap + } + + return cost[lhsLength - 1] +} + +fun List.sortByTitle(string: String): List { + val list = this.toMutableList() + list.sortByTitle(string) + return list +} + +fun MutableList.sortByTitle(string: String) { + val temp: MutableMap = mutableMapOf() + for (i in 0 until this.size) { + temp[i] = levenshtein(string.lowercase(), this[i].name.lowercase()) + } + val c = temp.toList().sortedBy { (_, value) -> value }.toMap() + val a = ArrayList(c.keys.toList().subList(0, min(this.size, 25))) + val b = c.values.toList().subList(0, min(this.size, 25)) + for (i in b.indices.reversed()) { + if (b[i] > 18 && i < a.size) a.removeAt(i) + } + val temp2 = this.toMutableList() + this.clear() + for (i in a.indices) { + this.add(temp2[a[i]]) + } +} + +fun String.findBetween(a: String, b: String): String? { + val string = substringAfter(a, "").substringBefore(b,"") + return string.ifEmpty { null } +} + +fun ImageView.loadImage(url: String?, size: Int = 0) { + if (!url.isNullOrEmpty()) { + loadImage(FileUrl(url), size) + } +} + +fun ImageView.loadImage(file: FileUrl?, size: Int = 0) { + if (file?.url?.isNotEmpty() == true) { + tryWith { + val glideUrl = GlideUrl(file.url) { file.headers } + Glide.with(this.context).load(glideUrl).transition(withCrossFade()).override(size).into(this) + } + } +} + +class SafeClickListener( + private var defaultInterval: Int = 1000, + private val onSafeCLick: (View) -> Unit +) : View.OnClickListener { + + private var lastTimeClicked: Long = 0 + + override fun onClick(v: View) { + if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) { + return + } + lastTimeClicked = SystemClock.elapsedRealtime() + onSafeCLick(v) + } +} + +fun View.setSafeOnClickListener(onSafeClick: (View) -> Unit) { + val safeClickListener = SafeClickListener { + onSafeClick(it) + } + setOnClickListener(safeClickListener) +} + +suspend fun getSize(file: FileUrl): Double? { + return tryWithSuspend { + client.head(file.url, file.headers, timeout = 1000).size?.toDouble()?.div(1024 * 1024) + } +} + +suspend fun getSize(file: String): Double? { + return getSize(FileUrl(file)) +} + + +abstract class GesturesListener : GestureDetector.SimpleOnGestureListener() { + private var timer: Timer? = null //at class level; + private val delay: Long = 200 + + override fun onSingleTapUp(e: MotionEvent): Boolean { + processSingleClickEvent(e) + return super.onSingleTapUp(e) + } + + override fun onLongPress(e: MotionEvent) { + processLongClickEvent(e) + super.onLongPress(e) + } + + override fun onDoubleTap(e: MotionEvent): Boolean { + processDoubleClickEvent(e) + return super.onDoubleTap(e) + } + + override fun onScroll(e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { + onScrollYClick(distanceY) + onScrollXClick(distanceX) + return super.onScroll(e1, e2, distanceX, distanceY) + } + + private fun processSingleClickEvent(e: MotionEvent) { + val handler = Handler(Looper.getMainLooper()) + val mRunnable = Runnable { + onSingleClick(e) + } + timer = Timer().apply { + schedule(object : TimerTask() { + override fun run() { + handler.post(mRunnable) + } + }, delay) + } + } + + private fun processDoubleClickEvent(e: MotionEvent) { + timer?.apply { + cancel() + purge() + } + onDoubleClick(e) + } + + private fun processLongClickEvent(e: MotionEvent) { + timer?.apply { + cancel() + purge() + } + onLongClick(e) + } + + open fun onSingleClick(event: MotionEvent) {} + open fun onDoubleClick(event: MotionEvent) {} + open fun onScrollYClick(y: Float) {} + open fun onScrollXClick(y: Float) {} + open fun onLongClick(event: MotionEvent) {} +} + +fun View.circularReveal(ex: Int, ey: Int, subX: Boolean, time: Long) { + ViewAnimationUtils.createCircularReveal( + this, + if (subX) (ex - x.toInt()) else ex, + ey - y.toInt(), + 0f, + max(height, width).toFloat() + ).setDuration(time).start() +} + +fun openLinkInBrowser(link: String?) { + tryWith { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) + currContext()?.startActivity(intent) + } +} + +fun saveImageToDownloads(title: String, bitmap: Bitmap, context: Context) { + FileProvider.getUriForFile( + context, + "$APPLICATION_ID.provider", + saveImage( + bitmap, + Environment.getExternalStorageDirectory().absolutePath + "/" + Environment.DIRECTORY_DOWNLOADS, + title + ) ?: return + ) +} + +fun shareImage(title: String, bitmap: Bitmap, context: Context) { + + val contentUri = FileProvider.getUriForFile( + context, + "$APPLICATION_ID.provider", + saveImage(bitmap, context.cacheDir.absolutePath, title) ?: return + ) + + val intent = Intent(Intent.ACTION_SEND) + intent.type = "image/png" + intent.putExtra(Intent.EXTRA_TEXT, title) + intent.putExtra(Intent.EXTRA_STREAM, contentUri) + context.startActivity(Intent.createChooser(intent, "Share $title")) +} + +fun saveImage(image: Bitmap, path: String, imageFileName: String): File? { + val imageFile = File(path, "$imageFileName.png") + return tryWith { + val fOut: OutputStream = FileOutputStream(imageFile) + image.compress(Bitmap.CompressFormat.PNG, 0, fOut) + fOut.close() + scanFile(imageFile.absolutePath, currContext()!!) + toast(String.format(currContext()!!.getString(R.string.saved_to_path, path))) + imageFile + } +} + +private fun scanFile(path: String, context: Context) { + MediaScannerConnection.scanFile(context, arrayOf(path), null) { p, _ -> + logger("Finished scanning $p") + } +} + +class MediaPageTransformer : ViewPager2.PageTransformer { + private fun parallax(view: View, position: Float) { + if (position > -1 && position < 1) { + val width = view.width.toFloat() + view.translationX = -(position * width * 0.8f) + } + } + + override fun transformPage(view: View, position: Float) { + + val bannerContainer = view.findViewById(R.id.itemCompactBanner) + parallax(bannerContainer, position) + } +} + +class NoGestureSubsamplingImageView(context: Context?, attr: AttributeSet?) : + SubsamplingScaleImageView(context, attr) { + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + return false + } +} + +fun copyToClipboard(string: String, toast: Boolean = true) { + val activity = currContext() ?: return + val clipboard = getSystemService(activity, ClipboardManager::class.java) + val clip = ClipData.newPlainText("label", string) + clipboard?.setPrimaryClip(clip) + if (toast) snackString(activity.getString(R.string.copied_text, string)) +} + +@SuppressLint("SetTextI18n") +fun countDown(media: Media, view: ViewGroup) { + if (media.anime?.nextAiringEpisode != null && media.anime.nextAiringEpisodeTime != null && (media.anime.nextAiringEpisodeTime!! - System.currentTimeMillis() / 1000) <= 86400 * 7.toLong()) { + val v = ItemCountDownBinding.inflate(LayoutInflater.from(view.context), view, false) + view.addView(v.root, 0) + v.mediaCountdownText.text = + currActivity()?.getString(R.string.episode_release_countdown, media.anime.nextAiringEpisode!! + 1) + + object : CountDownTimer((media.anime.nextAiringEpisodeTime!! + 10000) * 1000 - System.currentTimeMillis(), 1000) { + override fun onTick(millisUntilFinished: Long) { + val a = millisUntilFinished / 1000 + v.mediaCountdown.text = currActivity()?.getString( + R.string.time_format, + a / 86400, + a % 86400 / 3600, + a % 86400 % 3600 / 60, + a % 86400 % 3600 % 60 + ) + } + + override fun onFinish() { + v.mediaCountdownContainer.visibility = View.GONE + snackString(currContext()?.getString(R.string.congrats_vro)) + } + }.start() + } +} + +fun MutableMap.checkId(id: Int): Boolean { + this.forEach { + if (it.value.id == id) { + return false + } + } + return true +} + +fun MutableMap.checkGenreTime(genre: String): Boolean { + if (containsKey(genre)) + return (System.currentTimeMillis() - get(genre)!!.time) >= (1000 * 60 * 60 * 24 * 7) + return true +} + +fun setSlideIn(uiSettings: UserInterfaceSettings) = AnimationSet(false).apply { + if (uiSettings.layoutAnimations) { + var animation: Animation = AlphaAnimation(0.0f, 1.0f) + animation.duration = (500 * uiSettings.animationSpeed).toLong() + animation.interpolator = AccelerateDecelerateInterpolator() + addAnimation(animation) + + animation = TranslateAnimation( + Animation.RELATIVE_TO_SELF, 1.0f, + Animation.RELATIVE_TO_SELF, 0f, + Animation.RELATIVE_TO_SELF, 0.0f, + Animation.RELATIVE_TO_SELF, 0f + ) + + animation.duration = (750 * uiSettings.animationSpeed).toLong() + animation.interpolator = OvershootInterpolator(1.1f) + addAnimation(animation) + } +} + +fun setSlideUp(uiSettings: UserInterfaceSettings) = AnimationSet(false).apply { + if (uiSettings.layoutAnimations) { + var animation: Animation = AlphaAnimation(0.0f, 1.0f) + animation.duration = (500 * uiSettings.animationSpeed).toLong() + animation.interpolator = AccelerateDecelerateInterpolator() + addAnimation(animation) + + animation = TranslateAnimation( + Animation.RELATIVE_TO_SELF, 0.0f, + Animation.RELATIVE_TO_SELF, 0f, + Animation.RELATIVE_TO_SELF, 1.0f, + Animation.RELATIVE_TO_SELF, 0f + ) + + animation.duration = (750 * uiSettings.animationSpeed).toLong() + animation.interpolator = OvershootInterpolator(1.1f) + addAnimation(animation) + } +} + +class EmptyAdapter(private val count: Int) : RecyclerView.Adapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + return EmptyViewHolder(View(parent.context)) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {} + + override fun getItemCount(): Int = count + + inner class EmptyViewHolder(view: View) : RecyclerView.ViewHolder(view) +} + +fun toast(string: String?) { + if (string != null) { + logger(string) + MainScope().launch { + Toast.makeText(currActivity()?.application ?: return@launch, string, Toast.LENGTH_SHORT).show() + } + } +} + +fun snackString(s: String?, activity: Activity? = null, clipboard: String? = null) { + if (s != null) { + (activity ?: currActivity())?.apply { + runOnUiThread { + val snackBar = Snackbar.make(window.decorView.findViewById(android.R.id.content), s, Snackbar.LENGTH_LONG) + snackBar.view.apply { + updateLayoutParams { + gravity = (Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM) + width = WRAP_CONTENT + } + translationY = -(navBarHeight.dp + 32f) + translationZ = 32f + updatePadding(16f.px, right = 16f.px) + setOnClickListener { + snackBar.dismiss() + } + setOnLongClickListener { + copyToClipboard(clipboard ?: s, false) + toast(getString(R.string.copied_to_clipboard)) + true + } + } + snackBar.show() + } + } + logger(s) + } +} + +open class NoPaddingArrayAdapter(context: Context, layoutId: Int, items: List) : ArrayAdapter(context, layoutId, items) { + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + val view = super.getView(position, convertView, parent) + view.setPadding(0, view.paddingTop, view.paddingRight, view.paddingBottom) + (view as TextView).setTextColor(Color.WHITE) + return view + } +} + +@SuppressLint("ClickableViewAccessibility") +class SpinnerNoSwipe : androidx.appcompat.widget.AppCompatSpinner { + private var mGestureDetector: GestureDetector? = null + + constructor(context: Context) : super(context) { + setup() + } + + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { + setup() + } + + constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { + setup() + } + + private fun setup() { + mGestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { + override fun onSingleTapUp(e: MotionEvent): Boolean { + return performClick() + } + }) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + mGestureDetector!!.onTouchEvent(event) + return true + } +} + +@SuppressLint("RestrictedApi") +class CustomBottomNavBar @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null +) : BottomNavigationView(context, attrs) { + init { + ViewUtils.doOnApplyWindowInsets( + this + ) { view, insets, initialPadding -> + initialPadding.bottom = 0 + updateLayoutParams { bottomMargin = navBarHeight } + initialPadding.applyToView(view) + insets + } + } +} + +fun getCurrentBrightnessValue(context: Context): Float { + fun getMax(): Int { + val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager + + val fields: Array = powerManager.javaClass.declaredFields + for (field in fields) { + if (field.name.equals("BRIGHTNESS_ON")) { + field.isAccessible = true + return try { + field.get(powerManager)?.toString()?.toInt() ?: 255 + } catch (e: IllegalAccessException) { + 255 + } + } + } + return 255 + } + + fun getCur(): Float { + return Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 127).toFloat() + } + + return brightnessConverter(getCur() / getMax(), true) +} + +fun brightnessConverter(it: Float, fromLog: Boolean) = + clamp( + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) + if (fromLog) log2((it * 256f)) * 12.5f / 100f else 2f.pow(it * 100f / 12.5f) / 256f + else it, 0.001f, 1f + ) + + +fun checkCountry(context: Context): Boolean { + val telMgr = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + return when (telMgr.simState) { + TelephonyManager.SIM_STATE_ABSENT -> { + val tz = TimeZone.getDefault().id + tz.equals("Asia/Kolkata", ignoreCase = true) + } + + TelephonyManager.SIM_STATE_READY -> { + val countryCodeValue = telMgr.networkCountryIso + countryCodeValue.equals("in", ignoreCase = true) + } + + else -> false + } +} + +suspend fun View.pop() { + currActivity()?.runOnUiThread { + ObjectAnimator.ofFloat(this@pop, "scaleX", 1f, 1.25f).setDuration(120).start() + ObjectAnimator.ofFloat(this@pop, "scaleY", 1f, 1.25f).setDuration(120).start() + } + delay(120) + currActivity()?.runOnUiThread { + ObjectAnimator.ofFloat(this@pop, "scaleX", 1.25f, 1f).setDuration(100).start() + ObjectAnimator.ofFloat(this@pop, "scaleY", 1.25f, 1f).setDuration(100).start() + } + delay(100) +} diff --git a/app/src/main/java/ani/dantotsu/MainActivity.kt b/app/src/main/java/ani/dantotsu/MainActivity.kt new file mode 100644 index 00000000..edbf4dcc --- /dev/null +++ b/app/src/main/java/ani/dantotsu/MainActivity.kt @@ -0,0 +1,233 @@ +package ani.dantotsu + +import android.animation.ObjectAnimator +import android.content.Intent +import android.graphics.drawable.Animatable +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.view.View +import android.view.ViewGroup +import android.view.animation.AnticipateInterpolator +import android.widget.TextView +import androidx.activity.addCallback +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.core.animation.doOnEnd +import androidx.core.view.doOnAttach +import androidx.core.view.updateLayoutParams +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.viewpager2.adapter.FragmentStateAdapter +import ani.dantotsu.aniyomi.anime.AnimeExtensionManager +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.AnilistHomeViewModel +import ani.dantotsu.databinding.ActivityMainBinding +import ani.dantotsu.databinding.SplashScreenBinding +import ani.dantotsu.home.AnimeFragment +import ani.dantotsu.home.HomeFragment +import ani.dantotsu.home.LoginFragment +import ani.dantotsu.home.MangaFragment +import ani.dantotsu.home.NoInternet +import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.others.CustomBottomDialog +import ani.dantotsu.parsers.AnimeSources +import ani.dantotsu.settings.UserInterfaceSettings +import ani.dantotsu.subcriptions.Subscription.Companion.startSubscription +import io.noties.markwon.Markwon +import io.noties.markwon.SoftBreakAddsNewLinePlugin +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import nl.joery.animatedbottombar.AnimatedBottomBar +import uy.kohesive.injekt.injectLazy +import java.io.Serializable + + +class MainActivity : AppCompatActivity() { + private lateinit var binding: ActivityMainBinding + private val scope = lifecycleScope + private var load = false + + private var uiSettings = UserInterfaceSettings() + private val animeExtensionManager: AnimeExtensionManager by injectLazy() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + val myScope = CoroutineScope(Dispatchers.Default) + myScope.launch { + animeExtensionManager.findAvailableExtensions() + AnimeSources.init(animeExtensionManager.installedExtensionsFlow) + + } + + var doubleBackToExitPressedOnce = false + onBackPressedDispatcher.addCallback(this) { + if (doubleBackToExitPressedOnce) { + finish() + } + doubleBackToExitPressedOnce = true + snackString(this@MainActivity.getString(R.string.back_to_exit)) + Handler(Looper.getMainLooper()).postDelayed( + { doubleBackToExitPressedOnce = false }, + 2000 + ) + } + + binding.root.isMotionEventSplittingEnabled = false + + lifecycleScope.launch { + val splash = SplashScreenBinding.inflate(layoutInflater) + binding.root.addView(splash.root) + (splash.splashImage.drawable as Animatable).start() + + // Wait for 2 seconds (2000 milliseconds) + delay(2000) + + // Now perform the animation + ObjectAnimator.ofFloat( + splash.root, + View.TRANSLATION_Y, + 0f, + -splash.root.height.toFloat() + ).apply { + interpolator = AnticipateInterpolator() + duration = 200L + doOnEnd { binding.root.removeView(splash.root) } + start() + } + } + + + binding.root.doOnAttach { + initActivity(this) + uiSettings = loadData("ui_settings") ?: uiSettings + selectedOption = uiSettings.defaultStartUpTab + binding.navbarContainer.updateLayoutParams { + bottomMargin = navBarHeight + } + } + + if (!isOnline(this)) { + snackString(this@MainActivity.getString(R.string.no_internet_connection)) + startActivity(Intent(this, NoInternet::class.java)) + } else { + val model: AnilistHomeViewModel by viewModels() + model.genres.observe(this) { + if (it != null) { + if (it) { + val navbar = binding.navbar + bottomBar = navbar + navbar.visibility = View.VISIBLE + binding.mainProgressBar.visibility = View.GONE + val mainViewPager = binding.viewpager + mainViewPager.isUserInputEnabled = false + mainViewPager.adapter = ViewPagerAdapter(supportFragmentManager, lifecycle) + mainViewPager.setPageTransformer(ZoomOutPageTransformer(uiSettings)) + navbar.setOnTabSelectListener(object : + AnimatedBottomBar.OnTabSelectListener { + override fun onTabSelected( + lastIndex: Int, + lastTab: AnimatedBottomBar.Tab?, + newIndex: Int, + newTab: AnimatedBottomBar.Tab + ) { + navbar.animate().translationZ(12f).setDuration(200).start() + selectedOption = newIndex + mainViewPager.setCurrentItem(newIndex, false) + } + }) + navbar.selectTabAt(selectedOption) + mainViewPager.post { mainViewPager.setCurrentItem(selectedOption, false) } + } else { + binding.mainProgressBar.visibility = View.GONE + } + } + } + //Load Data + if (!load) { + scope.launch(Dispatchers.IO) { + model.loadMain(this@MainActivity) + val id = intent.extras?.getInt("mediaId", 0) + val isMAL = intent.extras?.getBoolean("mal") ?: false + val cont = intent.extras?.getBoolean("continue") ?: false + if (id != null && id != 0) { + val media = withContext(Dispatchers.IO) { + Anilist.query.getMedia(id, isMAL) + } + if (media != null) { + media.cameFromContinue = cont + startActivity( + Intent(this@MainActivity, MediaDetailsActivity::class.java) + .putExtra("media", media as Serializable) + ) + } else { + snackString(this@MainActivity.getString(R.string.anilist_not_found)) + } + } + delay(500) + startSubscription() + } + load = true + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + if (loadData("allow_opening_links", this) != true) { + CustomBottomDialog.newInstance().apply { + title = "Allow Dantotsu to automatically open Anilist & MAL Links?" + val md = "Open settings & click +Add Links & select Anilist & Mal urls" + addView(TextView(this@MainActivity).apply { + val markWon = + Markwon.builder(this@MainActivity) + .usePlugin(SoftBreakAddsNewLinePlugin.create()).build() + markWon.setMarkdown(this, md) + }) + + setNegativeButton(this@MainActivity.getString(R.string.no)) { + saveData("allow_opening_links", true, this@MainActivity) + dismiss() + } + + setPositiveButton(this@MainActivity.getString(R.string.yes)) { + saveData("allow_opening_links", true, this@MainActivity) + tryWith(true) { + startActivity( + Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS) + .setData(Uri.parse("package:$packageName")) + ) + } + } + }.show(supportFragmentManager, "dialog") + } + } + } + } + + //ViewPager + private class ViewPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) : + FragmentStateAdapter(fragmentManager, lifecycle) { + + override fun getItemCount(): Int = 3 + + override fun createFragment(position: Int): Fragment { + when (position) { + 0 -> return AnimeFragment() + 1 -> return if (Anilist.token != null) HomeFragment() else LoginFragment() + 2 -> return MangaFragment() + } + return LoginFragment() + } + } + +} diff --git a/app/src/main/java/ani/dantotsu/Network.kt b/app/src/main/java/ani/dantotsu/Network.kt new file mode 100644 index 00000000..58c9d6fc --- /dev/null +++ b/app/src/main/java/ani/dantotsu/Network.kt @@ -0,0 +1,229 @@ +package ani.dantotsu + +import android.content.Context +import android.os.Build +import androidx.fragment.app.FragmentActivity +import ani.dantotsu.others.webview.CloudFlare +import ani.dantotsu.others.webview.WebViewBottomDialog +import com.lagradost.nicehttp.Requests +import com.lagradost.nicehttp.ResponseParser +import com.lagradost.nicehttp.addGenericDns +import kotlinx.coroutines.* +import kotlinx.coroutines.CancellationException +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.InternalSerializationApi +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import kotlinx.serialization.serializer +import okhttp3.Cache +import okhttp3.OkHttpClient +import java.io.File +import java.io.PrintWriter +import java.io.Serializable +import java.io.StringWriter +import java.util.concurrent.* +import kotlin.reflect.KClass +import kotlin.reflect.KFunction + +val defaultHeaders = mapOf( + "User-Agent" to + "Mozilla/5.0 (Linux; Android %s; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Mobile Safari/537.36" + .format(Build.VERSION.RELEASE, Build.MODEL) +) +lateinit var cache: Cache + +lateinit var okHttpClient: OkHttpClient +lateinit var client: Requests + +fun initializeNetwork(context: Context) { + val dns = loadData("settings_dns") + cache = Cache( + File(context.cacheDir, "http_cache"), + 5 * 1024L * 1024L // 5 MiB + ) + okHttpClient = OkHttpClient.Builder() + .followRedirects(true) + .followSslRedirects(true) + .cache(cache) + .apply { + when (dns) { + 1 -> addGoogleDns() + 2 -> addCloudFlareDns() + 3 -> addAdGuardDns() + } + } + .build() + client = Requests( + okHttpClient, + defaultHeaders, + defaultCacheTime = 6, + defaultCacheTimeUnit = TimeUnit.HOURS, + responseParser = Mapper + ) +} + +object Mapper : ResponseParser { + + @OptIn(ExperimentalSerializationApi::class) + val json = Json { + isLenient = true + ignoreUnknownKeys = true + explicitNulls = false + } + + @OptIn(InternalSerializationApi::class) + override fun parse(text: String, kClass: KClass): T { + return json.decodeFromString(kClass.serializer(), text) + } + + override fun parseSafe(text: String, kClass: KClass): T? { + return tryWith { + parse(text, kClass) + } + } + + override fun writeValueAsString(obj: Any): String { + return json.encodeToString(obj) + } + + inline fun parse(text: String): T { + return json.decodeFromString(text) + } +} + +fun Collection.asyncMap(f: suspend (A) -> B): List = runBlocking { + map { async { f(it) } }.map { it.await() } +} + +fun Collection.asyncMapNotNull(f: suspend (A) -> B?): List = runBlocking { + map { async { f(it) } }.mapNotNull { it.await() } +} + +fun logError(e: Throwable, post: Boolean = true, snackbar: Boolean = true) { + val sw = StringWriter() + val pw = PrintWriter(sw) + e.printStackTrace(pw) + val stackTrace: String = sw.toString() + if (post) { + if (snackbar) + snackString(e.localizedMessage, null, stackTrace) + else + toast(e.localizedMessage) + } + e.printStackTrace() +} + +fun tryWith(post: Boolean = false, snackbar: Boolean = true, call: () -> T): T? { + return try { + call.invoke() + } catch (e: Throwable) { + logError(e, post, snackbar) + null + } +} + +suspend fun tryWithSuspend(post: Boolean = false, snackbar: Boolean = true, call: suspend () -> T): T? { + return try { + call.invoke() + } catch (e: Throwable) { + logError(e, post, snackbar) + null + } catch (e: CancellationException) { + null + } +} + +/** + * A url, which can also have headers + * **/ +data class FileUrl( + val url: String, + val headers: Map = mapOf() +) : Serializable { + companion object { + operator fun get(url: String?, headers: Map = mapOf()): FileUrl? { + return FileUrl(url ?: return null, headers) + } + } +} + +//Credits to leg +data class Lazier( + val factory: () -> T, + val name: String, + val lClass: KFunction? = null +) { + val get = lazy { factory() ?: lClass?.call() } +} + + +fun lazyList(vararg objects: Pair T>): List> { + return objects.map { + Lazier(it.second, it.first) + } +} + + +fun T.printIt(pre: String = ""): T { + println("$pre$this") + return this +} + + +fun OkHttpClient.Builder.addGoogleDns() = ( + addGenericDns( + "https://dns.google/dns-query", + listOf( + "8.8.4.4", + "8.8.8.8" + ) + )) + +fun OkHttpClient.Builder.addCloudFlareDns() = ( + addGenericDns( + "https://cloudflare-dns.com/dns-query", + listOf( + "1.1.1.1", + "1.0.0.1", + "2606:4700:4700::1111", + "2606:4700:4700::1001" + ) + )) + +fun OkHttpClient.Builder.addAdGuardDns() = ( + addGenericDns( + "https://dns.adguard.com/dns-query", + listOf( + // "Non-filtering" + "94.140.14.140", + "94.140.14.141", + ) + )) + +@Suppress("BlockingMethodInNonBlockingContext") +suspend fun webViewInterface(webViewDialog: WebViewBottomDialog): Map? { + var map : Map? = null + + val latch = CountDownLatch(1) + webViewDialog.callback = { + map = it + latch.countDown() + } + val fragmentManager = (currContext() as FragmentActivity?)?.supportFragmentManager ?: return null + webViewDialog.show(fragmentManager, "web-view") + delay(0) + latch.await(2,TimeUnit.MINUTES) + return map +} + +suspend fun webViewInterface(type: String, url: FileUrl): Map? { + val webViewDialog: WebViewBottomDialog = when (type) { + "Cloudflare" -> CloudFlare.newInstance(url) + else -> return null + } + return webViewInterface(webViewDialog) +} + +suspend fun webViewInterface(type: String, url: String): Map? { + return webViewInterface(type,FileUrl(url)) +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/aniyomi/LICENSE b/app/src/main/java/ani/dantotsu/aniyomi/LICENSE new file mode 100644 index 00000000..2bb9ad24 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/aniyomi/NOTICE.md b/app/src/main/java/ani/dantotsu/aniyomi/NOTICE.md new file mode 100644 index 00000000..5a81820b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/NOTICE.md @@ -0,0 +1,3 @@ +NOTICE + +This software includes code modified from Aniyomi, available at https://github.com/aniyomiorg/aniyomi/. \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/aniyomi/PreferenceScreen.kt b/app/src/main/java/ani/dantotsu/aniyomi/PreferenceScreen.kt new file mode 100644 index 00000000..0eb65a07 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/PreferenceScreen.kt @@ -0,0 +1,3 @@ +package ani.dantotsu.aniyomi + +typealias PreferenceScreen = androidx.preference.PreferenceScreen diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/AnimeExtensionManager.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/AnimeExtensionManager.kt new file mode 100644 index 00000000..7435a711 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/AnimeExtensionManager.kt @@ -0,0 +1,394 @@ +package ani.dantotsu.aniyomi.anime + +import android.content.Context +import android.graphics.drawable.Drawable +import ani.dantotsu.aniyomi.domain.source.anime.model.AnimeSourceData +import ani.dantotsu.aniyomi.util.extension.InstallStep +import ani.dantotsu.aniyomi.util.launchNow +import ani.dantotsu.aniyomi.anime.api.AnimeExtensionGithubApi +import ani.dantotsu.aniyomi.anime.model.AnimeExtension +import ani.dantotsu.aniyomi.anime.model.AnimeLoadResult +import ani.dantotsu.aniyomi.anime.util.AnimeExtensionInstallReceiver +import ani.dantotsu.aniyomi.anime.util.AnimeExtensionInstaller +import ani.dantotsu.aniyomi.anime.util.AnimeExtensionLoader +import ani.dantotsu.aniyomi.animesource.AnimeCatalogueSource +//import eu.kanade.tachiyomi.util.preference.plusAssign +import ani.dantotsu.aniyomi.util.toast +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import logcat.LogPriority +import rx.Observable +import ani.dantotsu.aniyomi.util.logcat +import ani.dantotsu.aniyomi.util.withUIContext + +/** + * The manager of anime extensions installed as another apk which extend the available sources. It handles + * the retrieval of remotely available anime extensions as well as installing, updating and removing them. + * To avoid malicious distribution, every anime extension must be signed and it will only be loaded if its + * signature is trusted, otherwise the user will be prompted with a warning to trust it before being + * loaded. + * + * @param context The application context. + * @param preferences The application preferences. + */ +class AnimeExtensionManager( + private val context: Context, +) { + + var isInitialized = false + private set + + /** + * API where all the available anime extensions can be found. + */ + private val api = AnimeExtensionGithubApi() + + /** + * The installer which installs, updates and uninstalls the anime extensions. + */ + private val installer by lazy { AnimeExtensionInstaller(context) } + + private val iconMap = mutableMapOf() + + private val _installedAnimeExtensionsFlow = MutableStateFlow(emptyList()) + val installedExtensionsFlow = _installedAnimeExtensionsFlow.asStateFlow() + + private var subLanguagesEnabledOnFirstRun = false + + fun getAppIconForSource(sourceId: Long): Drawable? { + val pkgName = _installedAnimeExtensionsFlow.value.find { ext -> ext.sources.any { it.id == sourceId } }?.pkgName + if (pkgName != null) { + return iconMap[pkgName] ?: iconMap.getOrPut(pkgName) { context.packageManager.getApplicationIcon(pkgName) } + } + return null + } + + private val _availableAnimeExtensionsFlow = MutableStateFlow(emptyList()) + val availableExtensionsFlow = _availableAnimeExtensionsFlow.asStateFlow() + + private var availableAnimeExtensionsSourcesData: Map = emptyMap() + + private fun setupAvailableAnimeExtensionsSourcesDataMap(animeextensions: List) { + if (animeextensions.isEmpty()) return + availableAnimeExtensionsSourcesData = animeextensions + .flatMap { ext -> ext.sources.map { it.toAnimeSourceData() } } + .associateBy { it.id } + } + + fun getSourceData(id: Long) = availableAnimeExtensionsSourcesData[id] + + private val _untrustedAnimeExtensionsFlow = MutableStateFlow(emptyList()) + val untrustedExtensionsFlow = _untrustedAnimeExtensionsFlow.asStateFlow() + + init { + initAnimeExtensions() + AnimeExtensionInstallReceiver(AnimeInstallationListener()).register(context) + } + + /** + * Loads and registers the installed animeextensions. + */ + private fun initAnimeExtensions() { + val animeextensions = AnimeExtensionLoader.loadExtensions(context) + logcat { "Loaded ${animeextensions.size} anime extensions" } + for (result in animeextensions) { + when (result) { + is AnimeLoadResult.Success -> { + logcat { "Loaded: ${result.extension.pkgName}" } + for(source in result.extension.sources) { + logcat { "Loaded: ${source.name}" } + } + val sc = result.extension.sources.first() + if (sc is AnimeCatalogueSource) { + //val res = sc.fetchSearchAnime(1, "spy x family", AnimeFilterList()).toBlocking().first() + /*val newScope = CoroutineScope(Dispatchers.IO) + newScope.launch { + println("fetching popular anime") + try { + val res = sc.fetchPopularAnime(1).toBlocking().first() + println("res111: $res") + } + catch (e: Exception) { + println("Exception111: $e") + } + + }*/ + + + } + } + + else -> { + logcat(LogPriority.ERROR) { "Error loading anime extension: $result" } + } + } + } + + _installedAnimeExtensionsFlow.value = animeextensions + .filterIsInstance() + .map { it.extension } + + _untrustedAnimeExtensionsFlow.value = animeextensions + .filterIsInstance() + .map { it.extension } + + isInitialized = true + } + + /** + * Finds the available anime extensions in the [api] and updates [availableExtensions]. + */ + suspend fun findAvailableExtensions() { + val extensions: List = try { + api.findExtensions() + } catch (e: Exception) { + logcat(LogPriority.ERROR, e) + withUIContext { context.toast("Could not update anime extensions") } + emptyList() + } + + enableAdditionalSubLanguages(extensions) + + _availableAnimeExtensionsFlow.value = extensions + println("AnimeExtensions: $extensions") + updatedInstalledAnimeExtensionsStatuses(extensions) + setupAvailableAnimeExtensionsSourcesDataMap(extensions) + } + + /** + * Enables the additional sub-languages in the app first run. This addresses + * the issue where users still need to enable some specific languages even when + * the device language is inside that major group. As an example, if a user + * has a zh device language, the app will also enable zh-Hans and zh-Hant. + * + * If the user have already changed the enabledLanguages preference value once, + * the new languages will not be added to respect the user enabled choices. + */ + private fun enableAdditionalSubLanguages(animeextensions: List) { + if (subLanguagesEnabledOnFirstRun || animeextensions.isEmpty()) { + return + } + + // Use the source lang as some aren't present on the animeextension level. + /*val availableLanguages = animeextensions + .flatMap(AnimeExtension.Available::sources) + .distinctBy(AvailableAnimeSources::lang) + .map(AvailableAnimeSources::lang) + + val deviceLanguage = Locale.getDefault().language + val defaultLanguages = preferences.enabledLanguages().defaultValue() + val languagesToEnable = availableLanguages.filter { + it != deviceLanguage && it.startsWith(deviceLanguage) + } + + preferences.enabledLanguages().set(defaultLanguages + languagesToEnable)*/ + subLanguagesEnabledOnFirstRun = true + } + + /** + * Sets the update field of the installed animeextensions with the given [availableAnimeExtensions]. + * + * @param availableAnimeExtensions The list of animeextensions given by the [api]. + */ + private fun updatedInstalledAnimeExtensionsStatuses(availableAnimeExtensions: List) { + if (availableAnimeExtensions.isEmpty()) { + //preferences.animeExtensionUpdatesCount().set(0) + return + } + + val mutInstalledAnimeExtensions = _installedAnimeExtensionsFlow.value.toMutableList() + var changed = false + + for ((index, installedExt) in mutInstalledAnimeExtensions.withIndex()) { + val pkgName = installedExt.pkgName + val availableExt = availableAnimeExtensions.find { it.pkgName == pkgName } + + if (!installedExt.isUnofficial && availableExt == null && !installedExt.isObsolete) { + mutInstalledAnimeExtensions[index] = installedExt.copy(isObsolete = true) + changed = true + } else if (availableExt != null) { + val hasUpdate = installedExt.updateExists(availableExt) + + if (installedExt.hasUpdate != hasUpdate) { + mutInstalledAnimeExtensions[index] = installedExt.copy(hasUpdate = hasUpdate) + changed = true + } + } + } + if (changed) { + _installedAnimeExtensionsFlow.value = mutInstalledAnimeExtensions + } + updatePendingUpdatesCount() + } + + /** + * Returns an observable of the installation process for the given anime extension. It will complete + * once the anime extension is installed or throws an error. The process will be canceled if + * unsubscribed before its completion. + * + * @param extension The anime extension to be installed. + */ + fun installExtension(extension: AnimeExtension.Available): Observable { + return installer.downloadAndInstall(api.getApkUrl(extension), extension) + } + + /** + * Returns an observable of the installation process for the given anime extension. It will complete + * once the anime extension is updated or throws an error. The process will be canceled if + * unsubscribed before its completion. + * + * @param extension The anime extension to be updated. + */ + fun updateExtension(extension: AnimeExtension.Installed): Observable { + val availableExt = _availableAnimeExtensionsFlow.value.find { it.pkgName == extension.pkgName } + ?: return Observable.empty() + return installExtension(availableExt) + } + + fun cancelInstallUpdateExtension(extension: AnimeExtension) { + installer.cancelInstall(extension.pkgName) + } + + /** + * Sets to "installing" status of an anime extension installation. + * + * @param downloadId The id of the download. + */ + fun setInstalling(downloadId: Long) { + installer.updateInstallStep(downloadId, InstallStep.Installing) + } + + fun updateInstallStep(downloadId: Long, step: InstallStep) { + installer.updateInstallStep(downloadId, step) + } + + /** + * Uninstalls the anime extension that matches the given package name. + * + * @param pkgName The package name of the application to uninstall. + */ + fun uninstallExtension(pkgName: String) { + installer.uninstallApk(pkgName) + } + + /** + * Adds the given signature to the list of trusted signatures. It also loads in background the + * anime extensions that match this signature. + * + * @param signature The signature to whitelist. + */ + fun trustSignature(signature: String) { + val untrustedSignatures = _untrustedAnimeExtensionsFlow.value.map { it.signatureHash }.toSet() + if (signature !in untrustedSignatures) return + + AnimeExtensionLoader.trustedSignatures += signature + //preferences.trustedSignatures() += signature + + val nowTrustedAnimeExtensions = _untrustedAnimeExtensionsFlow.value.filter { it.signatureHash == signature } + _untrustedAnimeExtensionsFlow.value -= nowTrustedAnimeExtensions + + val ctx = context + launchNow { + nowTrustedAnimeExtensions + .map { animeextension -> + async { AnimeExtensionLoader.loadExtensionFromPkgName(ctx, animeextension.pkgName) } + } + .map { it.await() } + .forEach { result -> + if (result is AnimeLoadResult.Success) { + registerNewExtension(result.extension) + } + } + } + } + + /** + * Registers the given anime extension in this and the source managers. + * + * @param extension The anime extension to be registered. + */ + private fun registerNewExtension(extension: AnimeExtension.Installed) { + _installedAnimeExtensionsFlow.value += extension + } + + /** + * Registers the given updated anime extension in this and the source managers previously removing + * the outdated ones. + * + * @param extension The anime extension to be registered. + */ + private fun registerUpdatedExtension(extension: AnimeExtension.Installed) { + val mutInstalledAnimeExtensions = _installedAnimeExtensionsFlow.value.toMutableList() + val oldAnimeExtension = mutInstalledAnimeExtensions.find { it.pkgName == extension.pkgName } + if (oldAnimeExtension != null) { + mutInstalledAnimeExtensions -= oldAnimeExtension + } + mutInstalledAnimeExtensions += extension + _installedAnimeExtensionsFlow.value = mutInstalledAnimeExtensions + } + + /** + * Unregisters the animeextension in this and the source managers given its package name. Note this + * method is called for every uninstalled application in the system. + * + * @param pkgName The package name of the uninstalled application. + */ + private fun unregisterAnimeExtension(pkgName: String) { + val installedAnimeExtension = _installedAnimeExtensionsFlow.value.find { it.pkgName == pkgName } + if (installedAnimeExtension != null) { + _installedAnimeExtensionsFlow.value -= installedAnimeExtension + } + val untrustedAnimeExtension = _untrustedAnimeExtensionsFlow.value.find { it.pkgName == pkgName } + if (untrustedAnimeExtension != null) { + _untrustedAnimeExtensionsFlow.value -= untrustedAnimeExtension + } + } + + /** + * Listener which receives events of the anime extensions being installed, updated or removed. + */ + private inner class AnimeInstallationListener : AnimeExtensionInstallReceiver.Listener { + + override fun onExtensionInstalled(extension: AnimeExtension.Installed) { + registerNewExtension(extension.withUpdateCheck()) + updatePendingUpdatesCount() + } + + override fun onExtensionUpdated(extension: AnimeExtension.Installed) { + registerUpdatedExtension(extension.withUpdateCheck()) + updatePendingUpdatesCount() + } + + override fun onExtensionUntrusted(extension: AnimeExtension.Untrusted) { + _untrustedAnimeExtensionsFlow.value += extension + } + + override fun onPackageUninstalled(pkgName: String) { + unregisterAnimeExtension(pkgName) + updatePendingUpdatesCount() + } + } + + /** + * AnimeExtension method to set the update field of an installed anime extension. + */ + private fun AnimeExtension.Installed.withUpdateCheck(): AnimeExtension.Installed { + return if (updateExists()) { + copy(hasUpdate = true) + } else { + this + } + } + + private fun AnimeExtension.Installed.updateExists(availableAnimeExtension: AnimeExtension.Available? = null): Boolean { + val availableExt = availableAnimeExtension ?: _availableAnimeExtensionsFlow.value.find { it.pkgName == pkgName } + if (isUnofficial || availableExt == null) return false + + return (availableExt.versionCode > versionCode || availableExt.libVersion > libVersion) + } + + private fun updatePendingUpdatesCount() { + //preferences.animeExtensionUpdatesCount().set(_installedAnimeExtensionsFlow.value.count { it.hasUpdate }) + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/api/AnimeExtensionGithubApi.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/api/AnimeExtensionGithubApi.kt new file mode 100644 index 00000000..83925bcf --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/api/AnimeExtensionGithubApi.kt @@ -0,0 +1,187 @@ +package ani.dantotsu.aniyomi.anime.api + +import android.content.Context +import ani.dantotsu.aniyomi.util.extension.ExtensionUpdateNotifier +import ani.dantotsu.aniyomi.anime.AnimeExtensionManager +import ani.dantotsu.aniyomi.anime.model.AnimeExtension +import ani.dantotsu.aniyomi.anime.model.AnimeLoadResult +import ani.dantotsu.aniyomi.anime.model.AvailableAnimeSources +import ani.dantotsu.aniyomi.anime.util.AnimeExtensionLoader +import ani.dantotsu.aniyomi.core.preference.PreferenceStore +import eu.kanade.tachiyomi.network.GET +import eu.kanade.tachiyomi.network.NetworkHelper +import eu.kanade.tachiyomi.network.awaitSuccess +import eu.kanade.tachiyomi.network.parseAs +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import logcat.LogPriority +//import ani.dantotsu.aniyomi.core.preference.Preference +//import ani.dantotsu.aniyomi.core.preference.PreferenceStore +import ani.dantotsu.aniyomi.util.withIOContext +import ani.dantotsu.aniyomi.util.logcat +import uy.kohesive.injekt.injectLazy + +internal class AnimeExtensionGithubApi { + + private val networkService: NetworkHelper by injectLazy() + private val preferenceStore: PreferenceStore by injectLazy() + private val animeExtensionManager: AnimeExtensionManager by injectLazy() + private val json: Json by injectLazy() + + //private val lastExtCheck: Preference by lazy { + // preferenceStore.getLong("last_ext_check", 0) + //} + private val lastExtCheck: Long = 0 + + private var requiresFallbackSource = false + + suspend fun findExtensions(): List { + return withIOContext { + val githubResponse = if (requiresFallbackSource) { + null + } else { + try { + networkService.client + .newCall(GET("${REPO_URL_PREFIX}index.min.json")) + .awaitSuccess() + } catch (e: Throwable) { + logcat(LogPriority.ERROR, e) { "Failed to get extensions from GitHub" } + requiresFallbackSource = true + null + } + } + + val response = githubResponse ?: run { + networkService.client + .newCall(GET("${FALLBACK_REPO_URL_PREFIX}index.min.json")) + .awaitSuccess() + } + + val extensions = with(json) { + response + .parseAs>() + .toExtensions() + } + + // Sanity check - a small number of extensions probably means something broke + // with the repo generator + if (extensions.size < 10) { + throw Exception() + } + + extensions + } + } + + suspend fun checkForUpdates(context: Context, fromAvailableExtensionList: Boolean = false): List? { + // Limit checks to once a day at most + //if (fromAvailableExtensionList && Date().time < lastExtCheck.get() + 1.days.inWholeMilliseconds) { + // return null + //} + + val extensions = if (fromAvailableExtensionList) { + animeExtensionManager.availableExtensionsFlow.value + } else { + findExtensions().also { }//lastExtCheck.set(Date().time) } + } + + val installedExtensions = AnimeExtensionLoader.loadExtensions(context) + .filterIsInstance() + .map { it.extension } + + val extensionsWithUpdate = mutableListOf() + for (installedExt in installedExtensions) { + val pkgName = installedExt.pkgName + val availableExt = extensions.find { it.pkgName == pkgName } ?: continue + + val hasUpdatedVer = availableExt.versionCode > installedExt.versionCode + val hasUpdatedLib = availableExt.libVersion > installedExt.libVersion + val hasUpdate = installedExt.isUnofficial.not() && (hasUpdatedVer || hasUpdatedLib) + if (hasUpdate) { + extensionsWithUpdate.add(installedExt) + } + } + + if (extensionsWithUpdate.isNotEmpty()) { + ExtensionUpdateNotifier(context).promptUpdates(extensionsWithUpdate.map { it.name }) + } + + return extensionsWithUpdate + } + + private fun List.toExtensions(): List { + return this + .filter { + val libVersion = it.extractLibVersion() + libVersion >= AnimeExtensionLoader.LIB_VERSION_MIN && libVersion <= AnimeExtensionLoader.LIB_VERSION_MAX + } + .map { + AnimeExtension.Available( + name = it.name.substringAfter("Aniyomi: "), + pkgName = it.pkg, + versionName = it.version, + versionCode = it.code, + libVersion = it.extractLibVersion(), + lang = it.lang, + isNsfw = it.nsfw == 1, + hasReadme = it.hasReadme == 1, + hasChangelog = it.hasChangelog == 1, + sources = it.sources?.toAnimeExtensionSources().orEmpty(), + apkName = it.apk, + iconUrl = "${getUrlPrefix()}icon/${it.apk.replace(".apk", ".png")}", + ) + } + } + + private fun List.toAnimeExtensionSources(): List { + return this.map { + AvailableAnimeSources( + id = it.id, + lang = it.lang, + name = it.name, + baseUrl = it.baseUrl, + ) + } + } + + fun getApkUrl(extension: AnimeExtension.Available): String { + return "${getUrlPrefix()}apk/${extension.apkName}" + } + + private fun getUrlPrefix(): String { + return if (requiresFallbackSource) { + FALLBACK_REPO_URL_PREFIX + } else { + REPO_URL_PREFIX + } + } +} + +private fun AnimeExtensionJsonObject.extractLibVersion(): Double { + return version.substringBeforeLast('.').toDouble() +} + +private const val REPO_URL_PREFIX = "https://raw.githubusercontent.com/aniyomiorg/aniyomi-extensions/repo/" +private const val FALLBACK_REPO_URL_PREFIX = "https://gcore.jsdelivr.net/gh/aniyomiorg/aniyomi-extensions@repo/" + +@Serializable +private data class AnimeExtensionJsonObject( + val name: String, + val pkg: String, + val apk: String, + val lang: String, + val code: Long, + val version: String, + val nsfw: Int, + val hasReadme: Int = 0, + val hasChangelog: Int = 0, + val sources: List?, +) + +@Serializable +private data class AnimeExtensionSourceJsonObject( + val id: Long, + val lang: String, + val name: String, + val baseUrl: String, +) diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/App.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/App.kt new file mode 100644 index 00000000..876e20c7 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/App.kt @@ -0,0 +1,30 @@ +package ani.dantotsu.aniyomi.anime.custom +/* +import android.app.Application +import ani.dantotsu.aniyomi.data.Notifications +import ani.dantotsu.aniyomi.util.logcat +import logcat.AndroidLogcatLogger +import logcat.LogPriority +import logcat.LogcatLogger +import uy.kohesive.injekt.Injekt + +class App : Application() { + override fun onCreate() { + super.onCreate() + Injekt.importModule(AppModule(this)) + Injekt.importModule(PreferenceModule(this)) + + setupNotificationChannels() + if (!LogcatLogger.isInstalled) { + LogcatLogger.install(AndroidLogcatLogger(LogPriority.VERBOSE)) + } + } + + private fun setupNotificationChannels() { + try { + Notifications.createChannels(this) + } catch (e: Exception) { + logcat(LogPriority.ERROR, e) { "Failed to modify notification channels" } + } + } +}*/ \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/InjektModules.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/InjektModules.kt new file mode 100644 index 00000000..e4b3e8eb --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/InjektModules.kt @@ -0,0 +1,48 @@ +package ani.dantotsu.aniyomi.anime.custom + +import android.app.Application +import ani.dantotsu.aniyomi.anime.AnimeExtensionManager +import ani.dantotsu.aniyomi.core.preference.PreferenceStore +import ani.dantotsu.aniyomi.domain.base.BasePreferences +import ani.dantotsu.aniyomi.domain.source.service.SourcePreferences +import ani.dantotsu.aniyomi.core.preference.AndroidPreferenceStore +import eu.kanade.tachiyomi.network.NetworkHelper +import kotlinx.serialization.json.Json +import uy.kohesive.injekt.api.InjektModule +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addSingleton +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get + +class AppModule(val app: Application) : InjektModule { + override fun InjektRegistrar.registerInjectables() { + addSingleton(app) + + addSingletonFactory { NetworkHelper(app) } + + addSingletonFactory { AnimeExtensionManager(app) } + + addSingletonFactory { + Json { + ignoreUnknownKeys = true + explicitNulls = false + } + } + } +} + +class PreferenceModule(val application: Application) : InjektModule { + override fun InjektRegistrar.registerInjectables() { + addSingletonFactory { + AndroidPreferenceStore(application) + } + + addSingletonFactory { + SourcePreferences(get()) + } + + addSingletonFactory { + BasePreferences(application, get()) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/InstallerAnime.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/InstallerAnime.kt new file mode 100644 index 00000000..e41d5261 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/InstallerAnime.kt @@ -0,0 +1,170 @@ +package ani.dantotsu.aniyomi.anime.installer + +import android.app.Service +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.Uri +import androidx.annotation.CallSuper +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import ani.dantotsu.aniyomi.util.extension.InstallStep +import ani.dantotsu.aniyomi.anime.AnimeExtensionManager +import uy.kohesive.injekt.injectLazy +import java.util.Collections +import java.util.concurrent.atomic.AtomicReference + +/** + * Base implementation class for extension installer. To be used inside a foreground [Service]. + */ +abstract class InstallerAnime(private val service: Service) { + + private val extensionManager: AnimeExtensionManager by injectLazy() + + private var waitingInstall = AtomicReference(null) + private val queue = Collections.synchronizedList(mutableListOf()) + + private val cancelReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val downloadId = intent.getLongExtra(EXTRA_DOWNLOAD_ID, -1).takeIf { it >= 0 } ?: return + cancelQueue(downloadId) + } + } + + /** + * Installer readiness. If false, queue check will not run. + * + * @see checkQueue + */ + abstract var ready: Boolean + + /** + * Add an item to install queue. + * + * @param downloadId Download ID as known by [ExtensionManager] + * @param uri Uri of APK to install + */ + fun addToQueue(downloadId: Long, uri: Uri) { + queue.add(Entry(downloadId, uri)) + checkQueue() + } + + /** + * Proceeds to install the APK of this entry inside this method. Call [continueQueue] + * when the install process for this entry is finished to continue the queue. + * + * @param entry The [Entry] of item to process + * @see continueQueue + */ + @CallSuper + open fun processEntry(entry: Entry) { + extensionManager.setInstalling(entry.downloadId) + } + + /** + * Called before queue continues. Override this to handle when the removed entry is + * currently being processed. + * + * @return true if this entry can be removed from queue. + */ + open fun cancelEntry(entry: Entry): Boolean { + return true + } + + /** + * Tells the queue to continue processing the next entry and updates the install step + * of the completed entry ([waitingInstall]) to [ExtensionManager]. + * + * @param resultStep new install step for the processed entry. + * @see waitingInstall + */ + fun continueQueue(resultStep: InstallStep) { + val completedEntry = waitingInstall.getAndSet(null) + if (completedEntry != null) { + extensionManager.updateInstallStep(completedEntry.downloadId, resultStep) + checkQueue() + } + } + + /** + * Checks the queue. The provided service will be stopped if the queue is empty. + * Will not be run when not ready. + * + * @see ready + */ + fun checkQueue() { + if (!ready) { + return + } + if (queue.isEmpty()) { + service.stopSelf() + return + } + val nextEntry = queue.first() + if (waitingInstall.compareAndSet(null, nextEntry)) { + queue.removeFirst() + processEntry(nextEntry) + } + } + + /** + * Call this method when the provided service is destroyed. + */ + @CallSuper + open fun onDestroy() { + LocalBroadcastManager.getInstance(service).unregisterReceiver(cancelReceiver) + queue.forEach { extensionManager.updateInstallStep(it.downloadId, InstallStep.Error) } + queue.clear() + waitingInstall.set(null) + } + + protected fun getActiveEntry(): Entry? = waitingInstall.get() + + /** + * Cancels queue for the provided download ID if exists. + * + * @param downloadId Download ID as known by [ExtensionManager] + */ + private fun cancelQueue(downloadId: Long) { + val waitingInstall = this.waitingInstall.get() + val toCancel = queue.find { it.downloadId == downloadId } ?: waitingInstall ?: return + if (cancelEntry(toCancel)) { + queue.remove(toCancel) + if (waitingInstall == toCancel) { + // Currently processing removed entry, continue queue + this.waitingInstall.set(null) + checkQueue() + } + extensionManager.updateInstallStep(downloadId, InstallStep.Idle) + } + } + + /** + * Install item to queue. + * + * @param downloadId Download ID as known by [ExtensionManager] + * @param uri Uri of APK to install + */ + data class Entry(val downloadId: Long, val uri: Uri) + + init { + val filter = IntentFilter(ACTION_CANCEL_QUEUE) + LocalBroadcastManager.getInstance(service).registerReceiver(cancelReceiver, filter) + } + + companion object { + private const val ACTION_CANCEL_QUEUE = "InstallerAnime.action.CANCEL_QUEUE" + private const val EXTRA_DOWNLOAD_ID = "InstallerAnime.extra.DOWNLOAD_ID" + + /** + * Attempts to cancel the installation entry for the provided download ID. + * + * @param downloadId Download ID as known by [ExtensionManager] + */ + fun cancelInstallQueue(context: Context, downloadId: Long) { + val intent = Intent(ACTION_CANCEL_QUEUE) + intent.putExtra(EXTRA_DOWNLOAD_ID, downloadId) + LocalBroadcastManager.getInstance(context).sendBroadcast(intent) + } + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/PackageInstallerInstallerAnime.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/PackageInstallerInstallerAnime.kt new file mode 100644 index 00000000..9141129a --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/installer/PackageInstallerInstallerAnime.kt @@ -0,0 +1,107 @@ +package ani.dantotsu.aniyomi.anime.installer + +import android.app.PendingIntent +import android.app.Service +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageInstaller +import android.os.Build +import ani.dantotsu.aniyomi.util.extension.InstallStep +import ani.dantotsu.aniyomi.util.lang.use +import ani.dantotsu.aniyomi.util.system.getParcelableExtraCompat +import ani.dantotsu.aniyomi.util.system.getUriSize +import logcat.LogPriority +import ani.dantotsu.aniyomi.util.logcat + +class PackageInstallerInstallerAnime(private val service: Service) : InstallerAnime(service) { + + private val packageInstaller = service.packageManager.packageInstaller + + private val packageActionReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) { + PackageInstaller.STATUS_PENDING_USER_ACTION -> { + val userAction = intent.getParcelableExtraCompat(Intent.EXTRA_INTENT) + if (userAction == null) { + logcat(LogPriority.ERROR) { "Fatal error for $intent" } + continueQueue(InstallStep.Error) + return + } + userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + service.startActivity(userAction) + } + PackageInstaller.STATUS_FAILURE_ABORTED -> { + continueQueue(InstallStep.Idle) + } + PackageInstaller.STATUS_SUCCESS -> continueQueue(InstallStep.Installed) + else -> continueQueue(InstallStep.Error) + } + } + } + + private var activeSession: Pair? = null + + // Always ready + override var ready = true + + override fun processEntry(entry: Entry) { + super.processEntry(entry) + activeSession = null + try { + val installParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + installParams.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } + activeSession = entry to packageInstaller.createSession(installParams) + val fileSize = service.getUriSize(entry.uri) ?: throw IllegalStateException() + installParams.setSize(fileSize) + + val inputStream = service.contentResolver.openInputStream(entry.uri) ?: throw IllegalStateException() + val session = packageInstaller.openSession(activeSession!!.second) + val outputStream = session.openWrite(entry.downloadId.toString(), 0, fileSize) + session.use { + arrayOf(inputStream, outputStream).use { + inputStream.copyTo(outputStream) + session.fsync(outputStream) + } + + val intentSender = PendingIntent.getBroadcast( + service, + activeSession!!.second, + Intent(INSTALL_ACTION), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0, + ).intentSender + session.commit(intentSender) + } + } catch (e: Exception) { + logcat(LogPriority.ERROR, e) { "Failed to install extension ${entry.downloadId} ${entry.uri}" } + activeSession?.let { (_, sessionId) -> + packageInstaller.abandonSession(sessionId) + } + continueQueue(InstallStep.Error) + } + } + + override fun cancelEntry(entry: Entry): Boolean { + activeSession?.let { (activeEntry, sessionId) -> + if (activeEntry == entry) { + packageInstaller.abandonSession(sessionId) + return false + } + } + return true + } + + override fun onDestroy() { + service.unregisterReceiver(packageActionReceiver) + super.onDestroy() + } + + init { + service.registerReceiver(packageActionReceiver, IntentFilter(INSTALL_ACTION)) + } +} + +private const val INSTALL_ACTION = "PackageInstallerInstaller.INSTALL_ACTION" diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeExtension.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeExtension.kt new file mode 100644 index 00000000..a0446979 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeExtension.kt @@ -0,0 +1,79 @@ +package ani.dantotsu.aniyomi.anime.model + +import android.graphics.drawable.Drawable +import ani.dantotsu.aniyomi.animesource.AnimeSource +import ani.dantotsu.aniyomi.domain.source.anime.model.AnimeSourceData + +sealed class AnimeExtension { + + abstract val name: String + abstract val pkgName: String + abstract val versionName: String + abstract val versionCode: Long + abstract val libVersion: Double + abstract val lang: String? + abstract val isNsfw: Boolean + abstract val hasReadme: Boolean + abstract val hasChangelog: Boolean + + data class Installed( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + override val libVersion: Double, + override val lang: String, + override val isNsfw: Boolean, + override val hasReadme: Boolean, + override val hasChangelog: Boolean, + val pkgFactory: String?, + val sources: List, + val icon: Drawable?, + val hasUpdate: Boolean = false, + val isObsolete: Boolean = false, + val isUnofficial: Boolean = false, + ) : AnimeExtension() + + data class Available( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + override val libVersion: Double, + override val lang: String, + override val isNsfw: Boolean, + override val hasReadme: Boolean, + override val hasChangelog: Boolean, + val sources: List, + val apkName: String, + val iconUrl: String, + ) : AnimeExtension() + + data class Untrusted( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + override val libVersion: Double, + val signatureHash: String, + override val lang: String? = null, + override val isNsfw: Boolean = false, + override val hasReadme: Boolean = false, + override val hasChangelog: Boolean = false, + ) : AnimeExtension() +} + +data class AvailableAnimeSources( + val id: Long, + val lang: String, + val name: String, + val baseUrl: String, +) { + fun toAnimeSourceData(): AnimeSourceData { + return AnimeSourceData( + id = this.id, + lang = this.lang, + name = this.name, + ) + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeLoadResult.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeLoadResult.kt new file mode 100644 index 00000000..ad1090bd --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/model/AnimeLoadResult.kt @@ -0,0 +1,7 @@ +package ani.dantotsu.aniyomi.anime.model + +sealed class AnimeLoadResult { + class Success(val extension: AnimeExtension.Installed) : AnimeLoadResult() + class Untrusted(val extension: AnimeExtension.Untrusted) : AnimeLoadResult() + object Error : AnimeLoadResult() +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallActivity.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallActivity.kt new file mode 100644 index 00000000..26a50483 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallActivity.kt @@ -0,0 +1,78 @@ +package ani.dantotsu.aniyomi.anime.util + +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import ani.dantotsu.aniyomi.util.extension.InstallStep +import ani.dantotsu.aniyomi.anime.AnimeExtensionManager +import ani.dantotsu.aniyomi.util.system.hasMiuiPackageInstaller +import ani.dantotsu.aniyomi.util.toast +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get +import kotlin.time.Duration.Companion.seconds + +/** + * Activity used to install extensions, because we can only receive the result of the installation + * with [startActivityForResult], which we need to update the UI. + */ +class AnimeExtensionInstallActivity : Activity() { + + // MIUI package installer bug workaround + private var ignoreUntil = 0L + private var ignoreResult = false + private var hasIgnoredResult = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) + .setDataAndType(intent.data, intent.type) + .putExtra(Intent.EXTRA_RETURN_RESULT, true) + .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + + if (hasMiuiPackageInstaller) { + ignoreResult = true + ignoreUntil = System.nanoTime() + 1.seconds.inWholeNanoseconds + } + + try { + startActivityForResult(installIntent, INSTALL_REQUEST_CODE) + } catch (error: Exception) { + // Either install package can't be found (probably bots) or there's a security exception + // with the download manager. Nothing we can workaround. + toast(error.message) + } + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (ignoreResult && System.nanoTime() < ignoreUntil) { + hasIgnoredResult = true + return + } + if (requestCode == INSTALL_REQUEST_CODE) { + checkInstallationResult(resultCode) + } + finish() + } + + override fun onStart() { + super.onStart() + if (hasIgnoredResult) { + checkInstallationResult(RESULT_CANCELED) + finish() + } + } + + private fun checkInstallationResult(resultCode: Int) { + val downloadId = intent.extras!!.getLong(AnimeExtensionInstaller.EXTRA_DOWNLOAD_ID) + val extensionManager = Injekt.get() + val newStep = when (resultCode) { + RESULT_OK -> InstallStep.Installed + RESULT_CANCELED -> InstallStep.Idle + else -> InstallStep.Error + } + extensionManager.updateInstallStep(downloadId, newStep) + } +} + +private const val INSTALL_REQUEST_CODE = 500 diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallReceiver.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallReceiver.kt new file mode 100644 index 00000000..66c3d72d --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallReceiver.kt @@ -0,0 +1,130 @@ +package ani.dantotsu.aniyomi.anime.util + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import ani.dantotsu.aniyomi.anime.model.AnimeExtension +import ani.dantotsu.aniyomi.anime.model.AnimeLoadResult +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import logcat.LogPriority +import ani.dantotsu.aniyomi.util.launchNow +import ani.dantotsu.aniyomi.util.logcat + +/** + * Broadcast receiver that listens for the system's packages installed, updated or removed, and only + * notifies the given [listener] when the package is an extension. + * + * @param listener The listener that should be notified of extension installation events. + */ +internal class AnimeExtensionInstallReceiver(private val listener: Listener) : + BroadcastReceiver() { + + /** + * Registers this broadcast receiver + */ + fun register(context: Context) { + context.registerReceiver(this, filter) + } + + /** + * Returns the intent filter this receiver should subscribe to. + */ + private val filter + get() = IntentFilter().apply { + addAction(Intent.ACTION_PACKAGE_ADDED) + addAction(Intent.ACTION_PACKAGE_REPLACED) + addAction(Intent.ACTION_PACKAGE_REMOVED) + addDataScheme("package") + } + + /** + * Called when one of the events of the [filter] is received. When the package is an extension, + * it's loaded in background and it notifies the [listener] when finished. + */ + override fun onReceive(context: Context, intent: Intent?) { + if (intent == null) return + + when (intent.action) { + Intent.ACTION_PACKAGE_ADDED -> { + if (isReplacing(intent)) return + + launchNow { + when (val result = getExtensionFromIntent(context, intent)) { + is AnimeLoadResult.Success -> listener.onExtensionInstalled(result.extension) + + is AnimeLoadResult.Untrusted -> listener.onExtensionUntrusted(result.extension) + else -> {} + } + } + } + Intent.ACTION_PACKAGE_REPLACED -> { + launchNow { + when (val result = getExtensionFromIntent(context, intent)) { + is AnimeLoadResult.Success -> listener.onExtensionUpdated(result.extension) + // Not needed as a package can't be upgraded if the signature is different + // is LoadResult.Untrusted -> {} + else -> {} + } + } + } + Intent.ACTION_PACKAGE_REMOVED -> { + if (isReplacing(intent)) return + + val pkgName = getPackageNameFromIntent(intent) + if (pkgName != null) { + listener.onPackageUninstalled(pkgName) + } + } + } + } + + /** + * Returns true if this package is performing an update. + * + * @param intent The intent that triggered the event. + */ + private fun isReplacing(intent: Intent): Boolean { + return intent.getBooleanExtra(Intent.EXTRA_REPLACING, false) + } + + /** + * Returns the extension triggered by the given intent. + * + * @param context The application context. + * @param intent The intent containing the package name of the extension. + */ + private suspend fun getExtensionFromIntent(context: Context, intent: Intent?): AnimeLoadResult { + val pkgName = getPackageNameFromIntent(intent) + if (pkgName == null) { + logcat(LogPriority.WARN) { "Package name not found" } + return AnimeLoadResult.Error + } + return GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) { + AnimeExtensionLoader.loadExtensionFromPkgName( + context, + pkgName, + ) + }.await() + } + + /** + * Returns the package name of the installed, updated or removed application. + */ + private fun getPackageNameFromIntent(intent: Intent?): String? { + return intent?.data?.encodedSchemeSpecificPart ?: return null + } + + /** + * Listener that receives extension installation events. + */ + interface Listener { + fun onExtensionInstalled(extension: AnimeExtension.Installed) + fun onExtensionUpdated(extension: AnimeExtension.Installed) + fun onExtensionUntrusted(extension: AnimeExtension.Untrusted) + fun onPackageUninstalled(pkgName: String) + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallService.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallService.kt new file mode 100644 index 00000000..0f9d4584 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstallService.kt @@ -0,0 +1,82 @@ +package ani.dantotsu.aniyomi.anime.util + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.IBinder +import ani.dantotsu.R +import ani.dantotsu.aniyomi.domain.base.BasePreferences +import ani.dantotsu.aniyomi.data.Notifications +import ani.dantotsu.aniyomi.anime.installer.InstallerAnime +import ani.dantotsu.aniyomi.anime.installer.PackageInstallerInstallerAnime +import ani.dantotsu.aniyomi.anime.util.AnimeExtensionInstaller.Companion.EXTRA_DOWNLOAD_ID +import ani.dantotsu.aniyomi.util.system.getSerializableExtraCompat +import ani.dantotsu.aniyomi.util.system.notificationBuilder +import logcat.LogPriority +import ani.dantotsu.aniyomi.util.logcat + +class AnimeExtensionInstallService : Service() { + + private var installer: InstallerAnime? = null + + override fun onCreate() { + val notification = notificationBuilder(Notifications.CHANNEL_EXTENSIONS_UPDATE) { + setSmallIcon(R.drawable.spinner_icon) + setAutoCancel(false) + setOngoing(true) + setShowWhen(false) + setContentTitle("Installing Anime Extension...") + setProgress(100, 100, true) + }.build() + startForeground(Notifications.ID_EXTENSION_INSTALLER, notification) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val uri = intent?.data + val id = intent?.getLongExtra(EXTRA_DOWNLOAD_ID, -1)?.takeIf { it != -1L } + val installerUsed = intent?.getSerializableExtraCompat( + EXTRA_INSTALLER, + ) + if (uri == null || id == null || installerUsed == null) { + stopSelf() + return START_NOT_STICKY + } + + if (installer == null) { + installer = when (installerUsed) { + BasePreferences.ExtensionInstaller.PACKAGEINSTALLER -> PackageInstallerInstallerAnime(this) + else -> { + logcat(LogPriority.ERROR) { "Not implemented for installer $installerUsed" } + stopSelf() + return START_NOT_STICKY + } + } + } + installer!!.addToQueue(id, uri) + return START_NOT_STICKY + } + + override fun onDestroy() { + installer?.onDestroy() + installer = null + } + + override fun onBind(i: Intent?): IBinder? = null + + companion object { + private const val EXTRA_INSTALLER = "EXTRA_INSTALLER" + + fun getIntent( + context: Context, + downloadId: Long, + uri: Uri, + installer: BasePreferences.ExtensionInstaller, + ): Intent { + return Intent(context, AnimeExtensionInstallService::class.java) + .setDataAndType(uri, AnimeExtensionInstaller.APK_MIME) + .putExtra(EXTRA_DOWNLOAD_ID, downloadId) + .putExtra(EXTRA_INSTALLER, installer) + } + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstaller.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstaller.kt new file mode 100644 index 00000000..bc6372dd --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionInstaller.kt @@ -0,0 +1,266 @@ +package ani.dantotsu.aniyomi.anime.util + +import android.app.DownloadManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.Uri +import android.os.Environment +import androidx.core.content.ContextCompat +import androidx.core.content.getSystemService +import androidx.core.net.toUri +import com.jakewharton.rxrelay.PublishRelay +import ani.dantotsu.aniyomi.util.extension.InstallStep +import ani.dantotsu.aniyomi.anime.installer.InstallerAnime +import ani.dantotsu.aniyomi.anime.model.AnimeExtension +import ani.dantotsu.aniyomi.domain.base.BasePreferences +import ani.dantotsu.aniyomi.util.storage.getUriCompat +import logcat.LogPriority +import rx.Observable +import rx.android.schedulers.AndroidSchedulers +import ani.dantotsu.aniyomi.util.logcat +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get +import java.io.File +import java.util.concurrent.TimeUnit + +/** + * The installer which installs, updates and uninstalls the extensions. + * + * @param context The application context. + */ +internal class AnimeExtensionInstaller(private val context: Context) { + + /** + * The system's download manager + */ + private val downloadManager = context.getSystemService()!! + + /** + * The broadcast receiver which listens to download completion events. + */ + private val downloadReceiver = DownloadCompletionReceiver() + + /** + * The currently requested downloads, with the package name (unique id) as key, and the id + * returned by the download manager. + */ + private val activeDownloads = hashMapOf() + + /** + * Relay used to notify the installation step of every download. + */ + private val downloadsRelay = PublishRelay.create>() + + private val extensionInstaller = Injekt.get().extensionInstaller() + + /** + * Adds the given extension to the downloads queue and returns an observable containing its + * step in the installation process. + * + * @param url The url of the apk. + * @param extension The extension to install. + */ + fun downloadAndInstall(url: String, extension: AnimeExtension) = Observable.defer { + val pkgName = extension.pkgName + + val oldDownload = activeDownloads[pkgName] + if (oldDownload != null) { + deleteDownload(pkgName) + } + + // Register the receiver after removing (and unregistering) the previous download + downloadReceiver.register() + + val downloadUri = url.toUri() + val request = DownloadManager.Request(downloadUri) + .setTitle(extension.name) + .setMimeType(APK_MIME) + .setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, downloadUri.lastPathSegment) + .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) + + val id = downloadManager.enqueue(request) + activeDownloads[pkgName] = id + + downloadsRelay.filter { it.first == id } + .map { it.second } + // Poll download status + .mergeWith(pollStatus(id)) + // Stop when the application is installed or errors + .takeUntil { it.isCompleted() } + // Always notify on main thread + .observeOn(AndroidSchedulers.mainThread()) + // Always remove the download when unsubscribed + .doOnUnsubscribe { deleteDownload(pkgName) } + } + + /** + * Returns an observable that polls the given download id for its status every second, as the + * manager doesn't have any notification system. It'll stop once the download finishes. + * + * @param id The id of the download to poll. + */ + private fun pollStatus(id: Long): Observable { + val query = DownloadManager.Query().setFilterById(id) + + return Observable.interval(0, 1, TimeUnit.SECONDS) + // Get the current download status + .map { + downloadManager.query(query).use { cursor -> + cursor.moveToFirst() + cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)) + } + } + // Ignore duplicate results + .distinctUntilChanged() + // Stop polling when the download fails or finishes + .takeUntil { it == DownloadManager.STATUS_SUCCESSFUL || it == DownloadManager.STATUS_FAILED } + // Map to our model + .flatMap { status -> + when (status) { + DownloadManager.STATUS_PENDING -> Observable.just(InstallStep.Pending) + DownloadManager.STATUS_RUNNING -> Observable.just(InstallStep.Downloading) + else -> Observable.empty() + } + } + } + + /** + * Starts an intent to install the extension at the given uri. + * + * @param uri The uri of the extension to install. + */ + fun installApk(downloadId: Long, uri: Uri) { + when (val installer = extensionInstaller.get()) { + BasePreferences.ExtensionInstaller.LEGACY -> { + val intent = Intent(context, AnimeExtensionInstallActivity::class.java) + .setDataAndType(uri, APK_MIME) + .putExtra(EXTRA_DOWNLOAD_ID, downloadId) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION) + + context.startActivity(intent) + } + else -> { + val intent = + AnimeExtensionInstallService.getIntent(context, downloadId, uri, installer) + ContextCompat.startForegroundService(context, intent) + } + } + } + + /** + * Cancels extension install and remove from download manager and installer. + */ + fun cancelInstall(pkgName: String) { + val downloadId = activeDownloads.remove(pkgName) ?: return + downloadManager.remove(downloadId) + InstallerAnime.cancelInstallQueue(context, downloadId) + } + + /** + * Starts an intent to uninstall the extension by the given package name. + * + * @param pkgName The package name of the extension to uninstall + */ + fun uninstallApk(pkgName: String) { + val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, "package:$pkgName".toUri()) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + context.startActivity(intent) + } + + /** + * Sets the step of the installation of an extension. + * + * @param downloadId The id of the download. + * @param step New install step. + */ + fun updateInstallStep(downloadId: Long, step: InstallStep) { + downloadsRelay.call(downloadId to step) + } + + /** + * Deletes the download for the given package name. + * + * @param pkgName The package name of the download to delete. + */ + private fun deleteDownload(pkgName: String) { + val downloadId = activeDownloads.remove(pkgName) + if (downloadId != null) { + downloadManager.remove(downloadId) + } + if (activeDownloads.isEmpty()) { + downloadReceiver.unregister() + } + } + + /** + * Receiver that listens to download status events. + */ + private inner class DownloadCompletionReceiver : BroadcastReceiver() { + + /** + * Whether this receiver is currently registered. + */ + private var isRegistered = false + + /** + * Registers this receiver if it's not already. + */ + fun register() { + if (isRegistered) return + isRegistered = true + + val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) + context.registerReceiver(this, filter) + } + + /** + * Unregisters this receiver if it's not already. + */ + fun unregister() { + if (!isRegistered) return + isRegistered = false + + context.unregisterReceiver(this) + } + + /** + * Called when a download event is received. It looks for the download in the current active + * downloads and notifies its installation step. + */ + override fun onReceive(context: Context, intent: Intent?) { + val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0) ?: return + + // Avoid events for downloads we didn't request + if (id !in activeDownloads.values) return + + val uri = downloadManager.getUriForDownloadedFile(id) + + // Set next installation step + if (uri == null) { + logcat(LogPriority.ERROR) { "Couldn't locate downloaded APK" } + downloadsRelay.call(id to InstallStep.Error) + return + } + + val query = DownloadManager.Query().setFilterById(id) + downloadManager.query(query).use { cursor -> + if (cursor.moveToFirst()) { + val localUri = cursor.getString( + cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI), + ).removePrefix(FILE_SCHEME) + + installApk(id, File(localUri).getUriCompat(context)) + } + } + } + } + + companion object { + const val APK_MIME = "application/vnd.android.package-archive" + const val EXTRA_DOWNLOAD_ID = "AnimeExtensionInstaller.extra.DOWNLOAD_ID" + const val FILE_SCHEME = "file://" + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionLoader.kt b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionLoader.kt new file mode 100644 index 00000000..1356860b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/util/AnimeExtensionLoader.kt @@ -0,0 +1,232 @@ +package ani.dantotsu.aniyomi.anime.util + +import android.annotation.SuppressLint +import android.content.Context +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.content.pm.PackageInfoCompat +import dalvik.system.PathClassLoader +import ani.dantotsu.aniyomi.domain.source.service.SourcePreferences +import ani.dantotsu.aniyomi.animesource.AnimeCatalogueSource +import ani.dantotsu.aniyomi.animesource.AnimeSource +import ani.dantotsu.aniyomi.animesource.AnimeSourceFactory +import ani.dantotsu.aniyomi.anime.model.AnimeExtension +import ani.dantotsu.aniyomi.anime.model.AnimeLoadResult +import ani.dantotsu.aniyomi.util.lang.Hash +import ani.dantotsu.aniyomi.util.system.getApplicationIcon +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import logcat.LogPriority +import ani.dantotsu.aniyomi.util.logcat +import uy.kohesive.injekt.injectLazy + +/** + * Class that handles the loading of the extensions installed in the system. + */ +@SuppressLint("PackageManagerGetSignatures") +internal object AnimeExtensionLoader { + + private val preferences: SourcePreferences by injectLazy() + private val loadNsfwSource by lazy { + preferences.showNsfwSource().get() + } + + private const val EXTENSION_FEATURE = "tachiyomi.animeextension" + private const val METADATA_SOURCE_CLASS = "tachiyomi.animeextension.class" + private const val METADATA_SOURCE_FACTORY = "tachiyomi.animeextension.factory" + private const val METADATA_NSFW = "tachiyomi.animeextension.nsfw" + private const val METADATA_HAS_README = "tachiyomi.animeextension.hasReadme" + private const val METADATA_HAS_CHANGELOG = "tachiyomi.animeextension.hasChangelog" + const val LIB_VERSION_MIN = 12 + const val LIB_VERSION_MAX = 15 + + private const val PACKAGE_FLAGS = PackageManager.GET_CONFIGURATIONS or PackageManager.GET_SIGNATURES + + // jmir1's key + private const val officialSignature = "50ab1d1e3a20d204d0ad6d334c7691c632e41b98dfa132bf385695fdfa63839c" + + /** + * List of the trusted signatures. + */ + var trustedSignatures = mutableSetOf() + preferences.trustedSignatures().get() + officialSignature + + /** + * Return a list of all the installed extensions initialized concurrently. + * + * @param context The application context. + */ + fun loadExtensions(context: Context): List { + val pkgManager = context.packageManager + + @Suppress("DEPRECATION") + val installedPkgs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + pkgManager.getInstalledPackages(PackageManager.PackageInfoFlags.of(PACKAGE_FLAGS.toLong())) + } else { + pkgManager.getInstalledPackages(PACKAGE_FLAGS) + } + + val extPkgs = installedPkgs.filter { isPackageAnExtension(it) } + + if (extPkgs.isEmpty()) return emptyList() + + // Load each extension concurrently and wait for completion + return runBlocking { + val deferred = extPkgs.map { + async { loadExtension(context, it.packageName, it) } + } + deferred.map { it.await() } + } + } + + /** + * Attempts to load an extension from the given package name. It checks if the extension + * contains the required feature flag before trying to load it. + */ + fun loadExtensionFromPkgName(context: Context, pkgName: String): AnimeLoadResult { + val pkgInfo = try { + context.packageManager.getPackageInfo(pkgName, PACKAGE_FLAGS) + } catch (error: PackageManager.NameNotFoundException) { + // Unlikely, but the package may have been uninstalled at this point + logcat(LogPriority.ERROR, error) + return AnimeLoadResult.Error + } + if (!isPackageAnExtension(pkgInfo)) { + logcat(LogPriority.WARN) { "Tried to load a package that wasn't a extension ($pkgName)" } + return AnimeLoadResult.Error + } + return loadExtension(context, pkgName, pkgInfo) + } + + /** + * Loads an extension given its package name. + * + * @param context The application context. + * @param pkgName The package name of the extension to load. + * @param pkgInfo The package info of the extension. + */ + private fun loadExtension(context: Context, pkgName: String, pkgInfo: PackageInfo): AnimeLoadResult { + val pkgManager = context.packageManager + + val appInfo = try { + pkgManager.getApplicationInfo(pkgName, PackageManager.GET_META_DATA) + } catch (error: PackageManager.NameNotFoundException) { + // Unlikely, but the package may have been uninstalled at this point + logcat(LogPriority.ERROR, error) + return AnimeLoadResult.Error + } + + val extName = pkgManager.getApplicationLabel(appInfo).toString().substringAfter("Aniyomi: ") + val versionName = pkgInfo.versionName + val versionCode = PackageInfoCompat.getLongVersionCode(pkgInfo) + + if (versionName.isNullOrEmpty()) { + logcat(LogPriority.WARN) { "Missing versionName for extension $extName" } + return AnimeLoadResult.Error + } + + // Validate lib version + val libVersion = versionName.substringBeforeLast('.').toDoubleOrNull() + if (libVersion == null || libVersion < LIB_VERSION_MIN || libVersion > LIB_VERSION_MAX) { + logcat(LogPriority.WARN) { + "Lib version is $libVersion, while only versions " + + "$LIB_VERSION_MIN to $LIB_VERSION_MAX are allowed" + } + return AnimeLoadResult.Error + } + + val signatureHash = getSignatureHash(pkgInfo) + + if (signatureHash == null) { + logcat(LogPriority.WARN) { "Package $pkgName isn't signed" } + return AnimeLoadResult.Error + } else if (signatureHash !in trustedSignatures) { + val extension = AnimeExtension.Untrusted(extName, pkgName, versionName, versionCode, libVersion, signatureHash) + logcat(LogPriority.WARN, message = { "Extension $pkgName isn't trusted" }) + return AnimeLoadResult.Untrusted(extension) + } + + val isNsfw = appInfo.metaData.getInt(METADATA_NSFW) == 1 + if (!loadNsfwSource && isNsfw) { + logcat(LogPriority.WARN) { "NSFW extension $pkgName not allowed" } + return AnimeLoadResult.Error + } + + val hasReadme = appInfo.metaData.getInt(METADATA_HAS_README, 0) == 1 + val hasChangelog = appInfo.metaData.getInt(METADATA_HAS_CHANGELOG, 0) == 1 + + val classLoader = PathClassLoader(appInfo.sourceDir, null, context.classLoader) + + val sources = appInfo.metaData.getString(METADATA_SOURCE_CLASS)!! + .split(";") + .map { + val sourceClass = it.trim() + if (sourceClass.startsWith(".")) { + pkgInfo.packageName + sourceClass + } else { + sourceClass + } + } + .flatMap { + try { + when (val obj = Class.forName(it, false, classLoader).newInstance()) { + is AnimeSource -> listOf(obj) + is AnimeSourceFactory -> obj.createSources() + else -> throw Exception("Unknown source class type! ${obj.javaClass}") + } + } catch (e: Throwable) { + logcat(LogPriority.ERROR, e) { "Extension load error: $extName ($it)" } + return AnimeLoadResult.Error + } + } + + val langs = sources.filterIsInstance() + .map { it.lang } + .toSet() + val lang = when (langs.size) { + 0 -> "" + 1 -> langs.first() + else -> "all" + } + + val extension = AnimeExtension.Installed( + name = extName, + pkgName = pkgName, + versionName = versionName, + versionCode = versionCode, + libVersion = libVersion, + lang = lang, + isNsfw = isNsfw, + hasReadme = hasReadme, + hasChangelog = hasChangelog, + sources = sources, + pkgFactory = appInfo.metaData.getString(METADATA_SOURCE_FACTORY), + isUnofficial = signatureHash != officialSignature, + icon = context.getApplicationIcon(pkgName), + ) + return AnimeLoadResult.Success(extension) + } + + /** + * Returns true if the given package is an extension. + * + * @param pkgInfo The package info of the application. + */ + private fun isPackageAnExtension(pkgInfo: PackageInfo): Boolean { + return pkgInfo.reqFeatures.orEmpty().any { it.name == EXTENSION_FEATURE } + } + + /** + * Returns the signature hash of the package or null if it's not signed. + * + * @param pkgInfo The package info of the application. + */ + private fun getSignatureHash(pkgInfo: PackageInfo): String? { + val signatures = pkgInfo.signatures + return if (signatures != null && signatures.isNotEmpty()) { + Hash.sha256(signatures.first().toByteArray()) + } else { + null + } + } +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeCatalogueSource.kt b/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeCatalogueSource.kt new file mode 100644 index 00000000..412bce7b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeCatalogueSource.kt @@ -0,0 +1,46 @@ +package ani.dantotsu.aniyomi.animesource + +import eu.kanade.tachiyomi.animesource.model.AnimeFilterList +import eu.kanade.tachiyomi.animesource.model.AnimesPage +import rx.Observable + +interface AnimeCatalogueSource : AnimeSource { + + /** + * An ISO 639-1 compliant language code (two letters in lower case). + */ + override val lang: String + + /** + * Whether the source has support for latest updates. + */ + val supportsLatest: Boolean + + /** + * Returns an observable containing a page with a list of anime. + * + * @param page the page number to retrieve. + */ + fun fetchPopularAnime(page: Int): Observable + + /** + * Returns an observable containing a page with a list of anime. + * + * @param page the page number to retrieve. + * @param query the search query. + * @param filters the list of filters to apply. + */ + fun fetchSearchAnime(page: Int, query: String, filters: AnimeFilterList): Observable + + /** + * Returns an observable containing a page with a list of latest anime updates. + * + * @param page the page number to retrieve. + */ + fun fetchLatestUpdates(page: Int): Observable + + /** + * Returns the list of filters for the source. + */ + fun getFilterList(): AnimeFilterList +} diff --git a/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeSource.kt b/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeSource.kt new file mode 100644 index 00000000..c422c411 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/aniyomi/animesource/AnimeSource.kt @@ -0,0 +1,86 @@ +package ani.dantotsu.aniyomi.animesource + +import eu.kanade.tachiyomi.animesource.model.SAnime +import eu.kanade.tachiyomi.animesource.model.SEpisode +import eu.kanade.tachiyomi.animesource.model.Video +//import ani.dantotsu.aniyomi.util.awaitSingle +import ani.dantotsu.aniyomi.util.lang.awaitSingle +import rx.Observable + +/** + * A basic interface for creating a source. It could be an online source, a local source, etc. + */ +interface AnimeSource { + + /** + * ID for the source. Must be unique. + */ + val id: Long + + /** + * Name of the source. + */ + val name: String + + val lang: String + get() = "" + + /** + * Returns an observable with the updated details for a anime. + * + * @param anime the anime to update. + */ + @Deprecated( + "Use the 1.x API instead", + ReplaceWith("getAnimeDetails"), + ) + fun fetchAnimeDetails(anime: SAnime): Observable = throw IllegalStateException("Not used") + + /** + * Returns an observable with all the available episodes for a anime. + * + * @param anime the anime to update. + */ + @Deprecated( + "Use the 1.x API instead", + ReplaceWith("getEpisodeList"), + ) + fun fetchEpisodeList(anime: SAnime): Observable> = throw IllegalStateException("Not used") + + /** + * Returns an observable with the list of videos a episode has. Videos should be returned + * in the expected order; the index is ignored. + * + * @param episode the episode. + */ + @Deprecated( + "Use the 1.x API instead", + ReplaceWith("getVideoList"), + ) + fun fetchVideoList(episode: SEpisode): Observable> = Observable.empty() + + /** + * [1.x API] Get the updated details for a anime. + */ + @Suppress("DEPRECATION") + suspend fun getAnimeDetails(anime: SAnime): SAnime { + return fetchAnimeDetails(anime).awaitSingle() + } + + /** + * [1.x API] Get all the available episodes for a anime. + */ + @Suppress("DEPRECATION") + suspend fun getEpisodeList(anime: SAnime): List { + return fetchEpisodeList(anime).awaitSingle() + } + + /** + * [1.x API] Get the list of videos a episode has. Videos should be returned + * in the expected order; the index is ignored. + */ + @Suppress("DEPRECATION") + suspend fun getVideoList(episode: SEpisode): List tag linking to the next page, or null if + * there's no next page. + */ + protected abstract fun popularAnimeNextPageSelector(): String? + + /** + * Parses the response from the site and returns a [AnimesPage] object. + * + * @param response the response from the site. + */ + override fun searchAnimeParse(response: Response): AnimesPage { + val document = response.asJsoup() + + val animes = document.select(searchAnimeSelector()).map { element -> + searchAnimeFromElement(element) + } + + val hasNextPage = searchAnimeNextPageSelector()?.let { selector -> + document.select(selector).first() + } != null + + return AnimesPage(animes, hasNextPage) + } + + /** + * Returns the Jsoup selector that returns a list of [Element] corresponding to each anime. + */ + protected abstract fun searchAnimeSelector(): String + + /** + * Returns an anime from the given [element]. Most sites only show the title and the url, it's + * totally fine to fill only those two values. + * + * @param element an element obtained from [searchAnimeSelector]. + */ + protected abstract fun searchAnimeFromElement(element: Element): SAnime + + /** + * Returns the Jsoup selector that returns the tag linking to the next page, or null if + * there's no next page. + */ + protected abstract fun searchAnimeNextPageSelector(): String? + + /** + * Parses the response from the site and returns a [AnimesPage] object. + * + * @param response the response from the site. + */ + override fun latestUpdatesParse(response: Response): AnimesPage { + val document = response.asJsoup() + + val animes = document.select(latestUpdatesSelector()).map { element -> + latestUpdatesFromElement(element) + } + + val hasNextPage = latestUpdatesNextPageSelector()?.let { selector -> + document.select(selector).first() + } != null + + return AnimesPage(animes, hasNextPage) + } + + /** + * Returns the Jsoup selector that returns a list of [Element] corresponding to each anime. + */ + protected abstract fun latestUpdatesSelector(): String + + /** + * Returns an anime from the given [element]. Most sites only show the title and the url, it's + * totally fine to fill only those two values. + * + * @param element an element obtained from [latestUpdatesSelector]. + */ + protected abstract fun latestUpdatesFromElement(element: Element): SAnime + + /** + * Returns the Jsoup selector that returns the tag linking to the next page, or null if + * there's no next page. + */ + protected abstract fun latestUpdatesNextPageSelector(): String? + + /** + * Parses the response from the site and returns the details of an anime. + * + * @param response the response from the site. + */ + override fun animeDetailsParse(response: Response): SAnime { + return animeDetailsParse(response.asJsoup()) + } + + /** + * Returns the details of the anime from the given [document]. + * + * @param document the parsed document. + */ + protected abstract fun animeDetailsParse(document: Document): SAnime + + /** + * Parses the response from the site and returns a list of episodes. + * + * @param response the response from the site. + */ + override fun episodeListParse(response: Response): List { + val document = response.asJsoup() + return document.select(episodeListSelector()).map { episodeFromElement(it) } + } + + /** + * Returns the Jsoup selector that returns a list of [Element] corresponding to each episode. + */ + protected abstract fun episodeListSelector(): String + + /** + * Returns an episode from the given element. + * + * @param element an element obtained from [episodeListSelector]. + */ + protected abstract fun episodeFromElement(element: Element): SEpisode + + /** + * Parses the response from the site and returns the page list. + * + * @param response the response from the site. + */ + override fun videoListParse(response: Response): List