diff --git a/.github/workflows/beta.yml b/.github/workflows/beta.yml index ef708935..558fb658 100644 --- a/.github/workflows/beta.yml +++ b/.github/workflows/beta.yml @@ -48,9 +48,11 @@ jobs: echo "COMMIT_LOG=${COMMIT_LOGS}" >> $GITHUB_ENV # Debugging: Print the variable to check its content echo "$COMMIT_LOGS" + echo "$COMMIT_LOGS" > commit_log.txt shell: /usr/bin/bash -e {0} env: CI: true + continue-on-error: true - name: Save Current SHA for Next Run run: echo ${{ github.sha }} > last_sha.txt @@ -82,13 +84,13 @@ jobs: - name: Build with Gradle run: ./gradlew assembleGoogleAlpha -Pandroid.injected.signing.store.file=$GITHUB_WORKSPACE/key.keystore -Pandroid.injected.signing.store.password=${{ secrets.KEYSTORE_PASSWORD }} -Pandroid.injected.signing.key.alias=${{ secrets.KEY_ALIAS }} -Pandroid.injected.signing.key.password=${{ secrets.KEY_PASSWORD }} - - name: Upload Build Artifacts - uses: actions/upload-artifact@v4.3.1 + - name: Upload a Build Artifact + uses: actions/upload-artifact@v4 with: - name: APKs - path: | - app/build/outputs/apk/google/alpha/*/*.apk - app/build/outputs/apk/google/alpha/*/*/*.apk + name: Dantotsu + retention-days: 5 + compression-level: 9 + path: "app/build/outputs/apk/google/alpha/app-google-alpha.apk" - name: Upload APK to Discord and Telegram if: ${{ github.repository == 'rebelonion/Dantotsu' }} @@ -102,7 +104,7 @@ jobs: commit_messages="${commit_messages:0:$max_length}... (truncated)" fi contentbody=$( jq -nc --arg msg "Alpha-Build: <@&1225347048321191996> **$VERSION**:" --arg commits "$commit_messages" '{"content": ($msg + "\n" + $commits)}' ) - curl -F "payload_json=${contentbody}" -F "dantotsu_debug=@app/build/outputs/apk/google/alpha/app-google-universal-alpha.apk" ${{ secrets.DISCORD_WEBHOOK }} + curl -F "payload_json=${contentbody}" -F "dantotsu_debug=@app/build/outputs/apk/google/alpha/app-google-alpha.apk" ${{ secrets.DISCORD_WEBHOOK }} #Telegram curl -F "chat_id=${{ secrets.TELEGRAM_CHANNEL_ID }}" \ @@ -115,18 +117,13 @@ jobs: VERSION: ${{ env.VERSION }} - name: Upload Current SHA as Artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: last-sha path: last_sha.txt - - - name: Delete Old Pre-Releases - id: delete-pre-releases - uses: sgpublic/delete-release-action@master + - name: Upload Commit log as Artifact + uses: actions/upload-artifact@v4 with: - pre-release-drop: true - pre-release-keep-count: 3 - pre-release-drop-tag: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + name: commit-log + path: commit_log.txt diff --git a/.gitignore b/.gitignore index 6cc9cdea..2ccc322f 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,6 @@ output.json #other scripts/ + +#crowdin +crowdin.yml \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md index f288702d..8f34e383 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,674 +1,17 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +## Unabandon Public License (UPL) - 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** - Preamble +This Unabandon Public License (UPL) is designed to ensure the continued development and public availability of source code based on works released under the GNU General Public License Version 3 (GPLv3) while upholding the core principles of GPLv3. This license extends GPLv3 by mandating public accessibility of source code for any derivative works. - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +**Body** - 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. +1. **Incorporation of GPLv3:** This UPL incorporates all terms and conditions of the GNU General Public License Version 3 (GPLv3) as published by the Free Software Foundation. You can find the complete text of GPLv3 at [https://www.gnu.org/licenses/licenses.en.html](https://www.gnu.org/licenses/licenses.en.html). - 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. +2. **Public Source Requirement:** In addition to the terms of GPLv3, the source code for any software distributed under this license, including modifications and derivative works, must be publicly available. Public availability means the source code must be accessible to anyone through a publicly accessible repository or download link without any access restrictions or fees. - 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. +3. **Source Code Availability:** The source code must be made publicly available using a recognized open-source hosting platform (e.g., GitHub, GitLab) or be downloadable from a publicly accessible website. The chosen method must clearly identify the source code and its corresponding licensed work. - 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. +**Termination** - 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 -. +This UPL terminates automatically if the terms and conditions are not followed by the licensee. diff --git a/app/build.gradle b/app/build.gradle index f7a04f77..811cab90 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,6 +6,10 @@ plugins { id 'com.google.devtools.ksp' } +def gitCommitHash = providers.exec { + commandLine("git", "rev-parse", "--verify", "--short", "HEAD") +}.standardOutput.asText.get().trim() + android { compileSdk 34 @@ -14,9 +18,10 @@ android { minSdk 21 targetSdk 34 versionCode((System.currentTimeMillis() / 60000).toInteger()) - versionName "3.0.0" - versionCode 300000000 + versionName "3.1.0" + versionCode 300100000 signingConfig signingConfigs.debug + } flavorDimensions += "store" @@ -38,7 +43,7 @@ android { buildTypes { alpha { applicationIdSuffix ".beta" // keep as beta by popular request - versionNameSuffix "-alpha01" + versionNameSuffix "-alpha01-" + gitCommitHash manifestPlaceholders.icon_placeholder = "@mipmap/ic_launcher_alpha" manifestPlaceholders.icon_placeholder_round = "@mipmap/ic_launcher_alpha_round" debuggable System.getenv("CI") == null @@ -75,14 +80,14 @@ android { dependencies { - // FireBase - googleImplementation platform('com.google.firebase:firebase-bom:32.7.4') - googleImplementation 'com.google.firebase:firebase-analytics-ktx:21.5.1' - googleImplementation 'com.google.firebase:firebase-crashlytics-ktx:18.6.2' -// Core +// FireBase + googleImplementation platform('com.google.firebase:firebase-bom:33.0.0') + googleImplementation 'com.google.firebase:firebase-analytics-ktx:22.0.0' + googleImplementation 'com.google.firebase:firebase-crashlytics-ktx:19.0.0' +// Core implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'androidx.browser:browser:1.8.0' - implementation 'androidx.core:core-ktx:1.12.0' + implementation 'androidx.core:core-ktx:1.13.1' implementation 'androidx.fragment:fragment-ktx:1.6.2' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' @@ -94,9 +99,10 @@ dependencies { implementation 'com.github.Blatzar:NiceHttp:0.4.4' implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3' implementation 'androidx.preference:preference-ktx:1.2.1' - implementation 'androidx.webkit:webkit:1.10.0' + implementation 'androidx.webkit:webkit:1.11.0' + implementation "com.anggrayudi:storage:1.5.5" -// Glide +// Glide ext.glide_version = '4.16.0' api "com.github.bumptech.glide:glide:$glide_version" implementation "com.github.bumptech.glide:glide:$glide_version" @@ -104,49 +110,48 @@ dependencies { implementation "com.github.bumptech.glide:okhttp3-integration:$glide_version" implementation 'jp.wasabeef:glide-transformations:4.3.0' -// Exoplayer - ext.exo_version = '1.3.0' +// Exoplayer + ext.exo_version = '1.3.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" - //media3 casting +// Media3 Casting implementation "androidx.media3:media3-cast:$exo_version" - implementation "androidx.mediarouter:mediarouter:1.6.0" + implementation "androidx.mediarouter:mediarouter:1.7.0" -// UI - implementation 'com.google.android.material:material:1.11.0' - //implementation 'nl.joery.animatedbottombar:library:1.1.0' - implementation 'com.github.rebelonion:AnimatedBottomBar:v1.1.0' +// UI + implementation 'com.google.android.material:material:1.12.0' + implementation 'com.github.RepoDevil:AnimatedBottomBar:7fcb9af' 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' implementation 'androidx.paging:paging-runtime-ktx:3.2.1' implementation 'com.github.eltos:simpledialogfragments:v3.7' - implementation 'com.github.AAChartModel:AAChartCore-Kotlin:93972bc' + implementation 'com.github.AAChartModel:AAChartCore-Kotlin:7.2.1' - // Markwon +// Markwon ext.markwon_version = '4.6.2' - implementation "io.noties.markwon:core:$markwon_version" - implementation "io.noties.markwon:editor:$markwon_version" - implementation "io.noties.markwon:ext-strikethrough:$markwon_version" - implementation "io.noties.markwon:ext-tables:$markwon_version" - implementation "io.noties.markwon:ext-tasklist:$markwon_version" - implementation "io.noties.markwon:html:$markwon_version" - implementation "io.noties.markwon:image-glide:$markwon_version" + implementation "io.noties.markwon:core:$markwon_version" + implementation "io.noties.markwon:editor:$markwon_version" + implementation "io.noties.markwon:ext-strikethrough:$markwon_version" + implementation "io.noties.markwon:ext-tables:$markwon_version" + implementation "io.noties.markwon:ext-tasklist:$markwon_version" + implementation "io.noties.markwon:html:$markwon_version" + implementation "io.noties.markwon:image-glide:$markwon_version" -// Groupie +// Groupie ext.groupie_version = '2.10.1' implementation "com.github.lisawray.groupie:groupie:$groupie_version" implementation "com.github.lisawray.groupie:groupie-viewbinding:$groupie_version" -// string matching +// String Matching implementation 'me.xdrop:fuzzywuzzy:1.4.0' -// Aniyomi +// Aniyomi implementation 'io.reactivex:rxjava:1.3.8' implementation 'io.reactivex:rxandroid:1.2.1' implementation 'ru.beryukhov:flowreactivenetwork:1.0.4' diff --git a/app/src/google/java/ani/dantotsu/connections/crashlytics/FirebaseCrashlytics.kt b/app/src/google/java/ani/dantotsu/connections/crashlytics/FirebaseCrashlytics.kt index 64ab524f..105bcbf0 100644 --- a/app/src/google/java/ani/dantotsu/connections/crashlytics/FirebaseCrashlytics.kt +++ b/app/src/google/java/ani/dantotsu/connections/crashlytics/FirebaseCrashlytics.kt @@ -5,12 +5,12 @@ import com.google.firebase.FirebaseApp import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase -import com.google.firebase.ktx.app class FirebaseCrashlytics : CrashlyticsInterface { override fun initialize(context: Context) { FirebaseApp.initializeApp(context) } + override fun logException(e: Throwable) { FirebaseCrashlytics.getInstance().recordException(e) } diff --git a/app/src/google/java/ani/dantotsu/others/AppUpdater.kt b/app/src/google/java/ani/dantotsu/others/AppUpdater.kt index c368ff68..67b7ce43 100644 --- a/app/src/google/java/ani/dantotsu/others/AppUpdater.kt +++ b/app/src/google/java/ani/dantotsu/others/AppUpdater.kt @@ -85,13 +85,18 @@ object AppUpdater { setPositiveButton(currContext()!!.getString(R.string.lets_go)) { MainScope().launch(Dispatchers.IO) { try { - client.get("https://api.github.com/repos/$repo/releases/tags/v$version") - .parsed().assets?.find { - it.browserDownloadURL.endsWith("apk") - }?.browserDownloadURL.apply { - if (this != null) activity.downloadUpdate(version, this) - else openLinkInBrowser("https://github.com/repos/$repo/releases/tag/v$version") - } + val apks = + client.get("https://api.github.com/repos/$repo/releases/tags/v$version") + .parsed().assets?.filter { + it.browserDownloadURL.endsWith( + ".apk" + ) + } + val apkToDownload = apks?.first() + apkToDownload?.browserDownloadURL.apply { + if (this != null) activity.downloadUpdate(version, this) + else openLinkInBrowser("https://github.com/repos/$repo/releases/tag/v$version") + } } catch (e: Exception) { logError(e) } @@ -111,24 +116,25 @@ object AppUpdater { } private fun compareVersion(version: String): Boolean { + return when (BuildConfig.BUILD_TYPE) { + "debug" -> BuildConfig.VERSION_NAME != version + "alpha" -> false + else -> { + fun toDouble(list: List): Double { + return list.mapIndexed { i: Int, s: String -> + when (i) { + 0 -> s.toDouble() * 100 + 1 -> s.toDouble() * 10 + 2 -> s.toDouble() + else -> s.toDoubleOrNull() ?: 0.0 + } + }.sum() + } - if (BuildConfig.DEBUG) { - return BuildConfig.VERSION_NAME != version - } else { - fun toDouble(list: List): Double { - return list.mapIndexed { i: Int, s: String -> - when (i) { - 0 -> s.toDouble() * 100 - 1 -> s.toDouble() * 10 - 2 -> s.toDouble() - else -> s.toDoubleOrNull() ?: 0.0 - } - }.sum() + val new = toDouble(version.split(".")) + val curr = toDouble(BuildConfig.VERSION_NAME.split(".")) + new > curr } - - val new = toDouble(version.split(".")) - val curr = toDouble(BuildConfig.VERSION_NAME.split(".")) - return new > curr } } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index cf650323..43c9c29f 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ + + @@ -19,7 +21,7 @@ + android:maxSdkVersion="29" /> @@ -38,6 +40,17 @@ android:name="android.permission.READ_APP_SPECIFIC_LOCALES" tools:ignore="ProtectedPermissions" /> + + + + + + + @@ -49,6 +62,7 @@ android:name=".App" android:allowBackup="true" android:banner="@mipmap/ic_banner_foreground" + android:enableOnBackInvokedCallback="true" android:icon="${icon_placeholder}" android:label="@string/app_name" android:largeHeap="true" @@ -57,9 +71,30 @@ android:supportsRtl="true" android:theme="@style/Theme.Dantotsu" android:usesCleartextTraffic="true" - tools:ignore="AllowBackup"> + tools:ignore="AllowBackup" + tools:targetApi="tiramisu"> + + + + + + + + + + + + + + @@ -67,11 +102,10 @@ + android:resource="@xml/statistics_widget_info" /> - + @@ -103,30 +139,76 @@ android:name=".settings.SettingsActivity" android:parentActivityName=".MainActivity" /> + + + + + + + + + + + + + + + + + android:parentActivityName=".MainActivity" + android:windowSoftInputMode="adjustResize|stateHidden" /> + android:parentActivityName=".MainActivity" + android:windowSoftInputMode="adjustResize|stateHidden" /> - + android:parentActivityName=".MainActivity" /> - + android:parentActivityName=".MainActivity" /> + + + + @@ -136,8 +218,9 @@ android:name=".media.CalendarActivity" android:parentActivityName=".MainActivity" /> - + + + android:windowSoftInputMode="adjustResize|stateHidden" /> + - + + @@ -299,30 +391,27 @@ - + android:theme="@style/Theme.AppCompat" /> - - - - - - + + + - - - - - - - - + { crashlytics } + crashlytics.initialize(this) + Logger.init(this) + Thread.setDefaultUncaughtExceptionHandler(FinalExceptionHandler()) + Logger.log(Log.WARN, "App: Logging started") + Injekt.importModule(AppModule(this)) Injekt.importModule(PreferenceModule(this)) - val crashlytics = Injekt.get() - crashlytics.initialize(this) val useMaterialYou: Boolean = PrefManager.getVal(PrefName.UseMaterialYou) if (useMaterialYou) { @@ -82,46 +98,47 @@ class App : MultiDexApplication() { } crashlytics.setCustomKey("device Info", SettingsActivity.getDeviceInfo()) - Logger.init(this) - Thread.setDefaultUncaughtExceptionHandler(FinalExceptionHandler()) - Logger.log("App: Logging started") - - initializeNetwork(baseContext) + initializeNetwork() setupNotificationChannels() if (!LogcatLogger.isInstalled) { LogcatLogger.install(AndroidLogcatLogger(LogPriority.VERBOSE)) } - animeExtensionManager = Injekt.get() - mangaExtensionManager = Injekt.get() - novelExtensionManager = Injekt.get() - - val animeScope = CoroutineScope(Dispatchers.Default) - animeScope.launch { + CoroutineScope(Dispatchers.IO).launch { + animeExtensionManager = Injekt.get() animeExtensionManager.findAvailableExtensions() Logger.log("Anime Extensions: ${animeExtensionManager.installedExtensionsFlow.first()}") AnimeSources.init(animeExtensionManager.installedExtensionsFlow) } - val mangaScope = CoroutineScope(Dispatchers.Default) - mangaScope.launch { + CoroutineScope(Dispatchers.IO).launch { + mangaExtensionManager = Injekt.get() mangaExtensionManager.findAvailableExtensions() Logger.log("Manga Extensions: ${mangaExtensionManager.installedExtensionsFlow.first()}") MangaSources.init(mangaExtensionManager.installedExtensionsFlow) } - val novelScope = CoroutineScope(Dispatchers.Default) - novelScope.launch { + CoroutineScope(Dispatchers.IO).launch { + novelExtensionManager = Injekt.get() novelExtensionManager.findAvailableExtensions() Logger.log("Novel Extensions: ${novelExtensionManager.installedExtensionsFlow.first()}") NovelSources.init(novelExtensionManager.installedExtensionsFlow) } - val commentsScope = CoroutineScope(Dispatchers.Default) - commentsScope.launch { - CommentsAPI.fetchAuthToken() - } + GlobalScope.launch { + torrentAddonManager = Injekt.get() + downloadAddonManager = Injekt.get() + torrentAddonManager.init() + downloadAddonManager.init() + CommentsAPI.fetchAuthToken(this@App) - val useAlarmManager = PrefManager.getVal(PrefName.UseAlarmManager) - TaskScheduler.create(this, useAlarmManager).scheduleAllTasks(this) + val useAlarmManager = PrefManager.getVal(PrefName.UseAlarmManager) + val scheduler = TaskScheduler.create(this@App, useAlarmManager) + try { + scheduler.scheduleAllTasks(this@App) + } catch (e: IllegalStateException) { + Logger.log("Failed to schedule tasks") + Logger.log(e) + } + } } private fun setupNotificationChannels() { @@ -135,7 +152,11 @@ class App : MultiDexApplication() { inner class FTActivityLifecycleCallbacks : ActivityLifecycleCallbacks { var currentActivity: Activity? = null - override fun onActivityCreated(p0: Activity, p1: Bundle?) {} + var lastActivity: String? = null + override fun onActivityCreated(p0: Activity, p1: Bundle?) { + lastActivity = p0.javaClass.simpleName + } + override fun onActivityStarted(p0: Activity) { currentActivity = p0 } @@ -151,7 +172,11 @@ class App : MultiDexApplication() { } companion object { - private var instance: App? = null + var instance: App? = null + + /** Reference to the application context. + * + * USE WITH EXTREME CAUTION!**/ var context: Context? = null fun currentContext(): Context? { return instance?.mFTActivityLifecycleCallbacks?.currentActivity ?: context diff --git a/app/src/main/java/ani/dantotsu/Functions.kt b/app/src/main/java/ani/dantotsu/Functions.kt index f51b28ff..04b83f52 100644 --- a/app/src/main/java/ani/dantotsu/Functions.kt +++ b/app/src/main/java/ani/dantotsu/Functions.kt @@ -10,6 +10,7 @@ import android.app.PendingIntent import android.content.ActivityNotFoundException import android.content.ClipData import android.content.ClipboardManager +import android.content.ComponentName import android.content.Context import android.content.DialogInterface import android.content.Intent @@ -66,9 +67,9 @@ import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import android.widget.Toast -import androidx.appcompat.app.AppCompatActivity +import androidx.annotation.AttrRes +import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatDelegate -import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat @@ -83,6 +84,7 @@ import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.RecyclerView @@ -90,16 +92,21 @@ 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.connections.bakaupdates.MangaUpdates import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.databinding.ItemCountDownBinding import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaDetailsActivity import ani.dantotsu.notifications.IncognitoNotificationClickReceiver +import ani.dantotsu.others.ImageViewDialog import ani.dantotsu.others.SpoilerPlugin import ani.dantotsu.parsers.ShowResponse +import ani.dantotsu.profile.ProfileActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.internal.PreferenceKeystore import ani.dantotsu.settings.saving.internal.PreferenceKeystore.Companion.generateSalt +import ani.dantotsu.util.CountUpTimer import ani.dantotsu.util.Logger import com.bumptech.glide.Glide import com.bumptech.glide.RequestBuilder @@ -113,6 +120,7 @@ import com.bumptech.glide.load.resource.gif.GifDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target +import com.bumptech.glide.request.target.ViewTarget import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomsheet.BottomSheetBehavior @@ -132,9 +140,12 @@ import io.noties.markwon.html.TagHandlerNoOp import io.noties.markwon.image.AsyncDrawable import io.noties.markwon.image.glide.GlideImagesPlugin import jp.wasabeef.glide.transformations.BlurTransformation +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import nl.joery.animatedbottombar.AnimatedBottomBar import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get @@ -182,6 +193,11 @@ fun currActivity(): Activity? { var loadMedia: Int? = null var loadIsMAL = false +val Int.toPx + get() = TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), getSystem().displayMetrics + ).toInt() + fun initActivity(a: Activity) { val window = a.window WindowCompat.setDecorFitsSystemWindows(window, false) @@ -201,13 +217,16 @@ fun initActivity(a: Activity) { ViewCompat.getRootWindowInsets(window.decorView.findViewById(android.R.id.content)) ?.apply { navBarHeight = this.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) navBarHeight += 48.toPx } } WindowInsetsControllerCompat( window, window.decorView ).hide(WindowInsetsCompat.Type.statusBars()) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && statusBarHeight == 0 && a.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { + 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()) @@ -222,6 +241,7 @@ fun initActivity(a: Activity) { statusBarHeight = windowInsets.getInsets(WindowInsetsCompat.Type.statusBars()).top navBarHeight = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) navBarHeight += 48.toPx } } if (a !is MainActivity) a.setNavigationTheme() @@ -262,6 +282,56 @@ fun Activity.setNavigationTheme() { } } +/** + * Sets clipToPadding false and sets the combined height of navigation bars as bottom padding. + * + * When nesting multiple scrolling views, only call this method on the inner most scrolling view. + */ +fun ViewGroup.setBaseline(navBar: AnimatedBottomBar) { + navBar.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) + clipToPadding = false + setPadding(paddingLeft, paddingTop, paddingRight, navBarHeight + navBar.measuredHeight) +} + +/** + * Sets clipToPadding false and sets the combined height of navigation bars as bottom padding. + * + * When nesting multiple scrolling views, only call this method on the inner most scrolling view. + */ +fun ViewGroup.setBaseline(navBar: AnimatedBottomBar, overlayView: View) { + navBar.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) + overlayView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) + clipToPadding = false + setPadding( + paddingLeft, + paddingTop, + paddingRight, + navBarHeight + navBar.measuredHeight + overlayView.measuredHeight + ) +} + +fun Activity.reloadActivity() { + Refresh.all() + finish() + startActivity(Intent(this, this::class.java)) + initActivity(this) +} + +fun Activity.restartApp() { + val mainIntent = Intent.makeRestartActivityTask( + packageManager.getLaunchIntentForPackage(this.packageName)!!.component + ) + val component = + ComponentName(this@restartApp.packageName, this@restartApp::class.qualifiedName!!) + try { + startActivity(Intent().setComponent(component)) + } catch (e: Exception) { + startActivity(mainIntent) + } + finishAndRemoveTask() + PrefManager.setCustomVal("reload", true) +} + open class BottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onStart() { super.onStart() @@ -277,14 +347,8 @@ open class BottomSheetDialogFragment : BottomSheetDialogFragment() { val behavior = BottomSheetBehavior.from(requireView().parent as View) behavior.state = BottomSheetBehavior.STATE_EXPANDED } - val typedValue = TypedValue() - val theme = requireContext().theme - theme.resolveAttribute( - com.google.android.material.R.attr.colorSurface, - typedValue, - true - ) - window.navigationBarColor = typedValue.data + window.navigationBarColor = + requireContext().getThemeColor(com.google.android.material.R.attr.colorSurface) } } @@ -359,7 +423,7 @@ class DatePickerFragment(activity: Activity, var date: FuzzyDate = FuzzyDate().g dialog.setButton( DialogInterface.BUTTON_NEUTRAL, activity.getString(R.string.remove) - ) { dialog, which -> + ) { _, which -> if (which == DialogInterface.BUTTON_NEUTRAL) { date = FuzzyDate() } @@ -394,7 +458,6 @@ class InputFilterMinMax( return "" } - @SuppressLint("SetTextI18n") private fun isInRange(a: Double, b: Double, c: Double): Boolean { val statusStrings = currContext()!!.resources.getStringArray(R.array.status_manga)[2] @@ -407,7 +470,7 @@ class InputFilterMinMax( } -class ZoomOutPageTransformer() : +class ZoomOutPageTransformer : ViewPager2.PageTransformer { override fun transformPage(view: View, position: Float) { if (position == 0.0f && PrefManager.getVal(PrefName.LayoutAnimations)) { @@ -563,13 +626,36 @@ fun ImageView.loadImage(file: FileUrl?, size: Int = 0) { file?.url = PrefManager.getVal(PrefName.ImageUrl).ifEmpty { file?.url ?: "" } 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) + if (file.url.startsWith("content://")) { + Glide.with(this.context).load(Uri.parse(file.url)).transition(withCrossFade()) + .override(size).into(this) + } else { + val glideUrl = GlideUrl(file.url) { file.headers } + Glide.with(this.context).load(glideUrl).transition(withCrossFade()).override(size) + .into(this) + } } } } +fun ImageView.loadImage(file: FileUrl?, width: Int = 0, height: Int = 0) { + file?.url = PrefManager.getVal(PrefName.ImageUrl).ifEmpty { file?.url ?: "" } + if (file?.url?.isNotEmpty() == true) { + tryWith { + if (file.url.startsWith("content://")) { + Glide.with(this.context).load(Uri.parse(file.url)).transition(withCrossFade()) + .override(width, height).into(this) + } else { + val glideUrl = GlideUrl(file.url) { file.headers } + Glide.with(this.context).load(glideUrl).transition(withCrossFade()) + .override(width, height) + .into(this) + } + } + } +} + + fun ImageView.loadLocalImage(file: File?, size: Int = 0) { if (file?.exists() == true) { tryWith { @@ -712,6 +798,23 @@ fun openLinkInBrowser(link: String?) { } } +fun openLinkInYouTube(link: String?) { + link?.let { + try { + val videoIntent = Intent(Intent.ACTION_VIEW).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + data = Uri.parse(link) + setPackage("com.google.android.youtube") + } + currContext()!!.startActivity(videoIntent) + } catch (e: ActivityNotFoundException) { + openLinkInBrowser(link) + } catch (e: Exception) { + Logger.log(e) + } + } +} + fun saveImageToDownloads(title: String, bitmap: Bitmap, context: Activity) { FileProvider.getUriForFile( context, @@ -803,31 +906,6 @@ fun savePrefs( } } -fun downloadsPermission(activity: AppCompatActivity): Boolean { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) return true - val permissions = arrayOf( - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Manifest.permission.READ_EXTERNAL_STORAGE - ) - - val requiredPermissions = permissions.filter { - ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED - }.toTypedArray() - - return if (requiredPermissions.isNotEmpty()) { - ActivityCompat.requestPermissions( - activity, - requiredPermissions, - DOWNLOADS_PERMISSION_REQUEST_CODE - ) - false - } else { - true - } -} - -private const val DOWNLOADS_PERMISSION_REQUEST_CODE = 100 - fun shareImage(title: String, bitmap: Bitmap, context: Context) { val contentUri = FileProvider.getUriForFile( @@ -897,9 +975,10 @@ fun copyToClipboard(string: String, toast: Boolean = true) { } } -@SuppressLint("SetTextI18n") fun countDown(media: Media, view: ViewGroup) { - if (media.anime?.nextAiringEpisode != null && media.anime.nextAiringEpisodeTime != null && (media.anime.nextAiringEpisodeTime!! - System.currentTimeMillis() / 1000) <= 86400 * 28.toLong()) { + if (media.anime?.nextAiringEpisode != null && media.anime.nextAiringEpisodeTime != null + && (media.anime.nextAiringEpisodeTime!! - System.currentTimeMillis() / 1000) <= 86400 * 28.toLong() + ) { val v = ItemCountDownBinding.inflate(LayoutInflater.from(view.context), view, false) view.addView(v.root, 0) v.mediaCountdownText.text = @@ -931,6 +1010,50 @@ fun countDown(media: Media, view: ViewGroup) { } } +fun sinceWhen(media: Media, view: ViewGroup) { + if (media.status != "RELEASING" && media.status != "HIATUS") return + CoroutineScope(Dispatchers.IO).launch { + MangaUpdates().search(media.mangaName(), media.startDate)?.let { + val latestChapter = MangaUpdates.getLatestChapter(view.context, it) + val timeSince = (System.currentTimeMillis() - + (it.metadata.series.lastUpdated!!.timestamp * 1000)) / 1000 + + withContext(Dispatchers.Main) { + val v = + ItemCountDownBinding.inflate(LayoutInflater.from(view.context), view, false) + view.addView(v.root, 0) + v.mediaCountdownText.text = + currActivity()?.getString(R.string.chapter_release_timeout, latestChapter) + + object : CountUpTimer(86400000) { + override fun onTick(second: Int) { + val a = second + timeSince + 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() { + // The legend will never die. + } + }.start() + } + } + } +} + +fun displayTimer(media: Media, view: ViewGroup) { + when { + media.anime != null -> countDown(media, view) + media.format == "MANGA" || media.format == "ONE_SHOT" -> sinceWhen(media, view) + else -> {} // No timer yet + } +} + fun MutableMap.checkId(id: Int): Boolean { this.forEach { if (it.value.id == id) { @@ -1000,6 +1123,10 @@ class EmptyAdapter(private val count: Int) : RecyclerView.Adapter(context: Context, layoutId: Int, items: List) : ArrayAdapter(context, layoutId, items) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { @@ -1230,24 +1365,93 @@ fun blurImage(imageView: ImageView, banner: String?) { if (banner != null) { val radius = PrefManager.getVal(PrefName.BlurRadius).toInt() val sampling = PrefManager.getVal(PrefName.BlurSampling).toInt() - if (PrefManager.getVal(PrefName.BlurBanners)) { - val context = imageView.context - if (!(context as Activity).isDestroyed) { - val url = PrefManager.getVal(PrefName.ImageUrl).ifEmpty { banner } + val context = imageView.context + if (!(context as Activity).isDestroyed) { + val url = PrefManager.getVal(PrefName.ImageUrl).ifEmpty { banner } + if (PrefManager.getVal(PrefName.BlurBanners)) { Glide.with(context as Context) - .load(GlideUrl(url)) - .diskCacheStrategy(DiskCacheStrategy.ALL).override(400) + .load( + if (banner.startsWith("http")) GlideUrl(url) else if (banner.startsWith("content://")) Uri.parse( + url + ) else File(url) + ) + .diskCacheStrategy(DiskCacheStrategy.RESOURCE).override(400) .apply(RequestOptions.bitmapTransform(BlurTransformation(radius, sampling))) .into(imageView) + + } else { + Glide.with(context as Context) + .load( + if (banner.startsWith("http")) GlideUrl(url) else if (banner.startsWith("content://")) Uri.parse( + url + ) else File(url) + ) + .diskCacheStrategy(DiskCacheStrategy.RESOURCE).override(400) + .into(imageView) } - } else { - imageView.loadImage(banner) } } else { imageView.setImageResource(R.drawable.linear_gradient_bg) } } +fun Context.getThemeColor(@AttrRes attribute: Int): Int { + val typedValue = TypedValue() + theme.resolveAttribute(attribute, typedValue, true) + return typedValue.data +} + +fun ImageView.openImage(title: String, image: String) { + setOnLongClickListener { + ImageViewDialog.newInstance( + context as FragmentActivity, title, image + ) + } +} + +/** + * Attempts to open the link in the app, otherwise copies it to the clipboard + * @param link the link to open + */ +fun openOrCopyAnilistLink(link: String) { + if (link.startsWith("https://anilist.co/anime/") || link.startsWith("https://anilist.co/manga/")) { + val mangaAnime = link.substringAfter("https://anilist.co/").substringBefore("/") + val id = + link.substringAfter("https://anilist.co/$mangaAnime/").substringBefore("/") + .toIntOrNull() + if (id != null && currContext() != null) { + ContextCompat.startActivity( + currContext()!!, + Intent(currContext()!!, MediaDetailsActivity::class.java) + .putExtra("mediaId", id), + null + ) + } else { + copyToClipboard(link, true) + } + } else if (link.startsWith("https://anilist.co/user/")) { + val username = link.substringAfter("https://anilist.co/user/").substringBefore("/") + val id = username.toIntOrNull() + if (currContext() != null) { + val intent = Intent(currContext()!!, ProfileActivity::class.java) + if (id != null) { + intent.putExtra("userId", id) + } else { + intent.putExtra("username", username) + } + ContextCompat.startActivity( + currContext()!!, + intent, + null + ) + } else { + copyToClipboard(link, true) + } + } else { + copyToClipboard(link, true) + } +} + /** * Builds the markwon instance with all the plugins * @return the markwon instance @@ -1255,14 +1459,15 @@ fun blurImage(imageView: ImageView, banner: String?) { fun buildMarkwon( activity: Context, userInputContent: Boolean = true, - fragment: Fragment? = null + fragment: Fragment? = null, + anilist: Boolean = false ): Markwon { val glideContext = fragment?.let { Glide.with(it) } ?: Glide.with(activity) val markwon = Markwon.builder(activity) .usePlugin(object : AbstractMarkwonPlugin() { override fun configureConfiguration(builder: MarkwonConfiguration.Builder) { builder.linkResolver { _, link -> - copyToClipboard(link, true) + openOrCopyAnilistLink(link) } } }) @@ -1271,7 +1476,7 @@ fun buildMarkwon( .usePlugin(StrikethroughPlugin.create()) .usePlugin(TablePlugin.create(activity)) .usePlugin(TaskListPlugin.create(activity)) - .usePlugin(SpoilerPlugin()) + .usePlugin(SpoilerPlugin(anilist)) .usePlugin(HtmlPlugin.create { plugin -> if (userInputContent) { plugin.addHandler( @@ -1321,4 +1526,4 @@ fun buildMarkwon( })) .build() return markwon -} \ No newline at end of file +} diff --git a/app/src/main/java/ani/dantotsu/MainActivity.kt b/app/src/main/java/ani/dantotsu/MainActivity.kt index 23d8e508..f9740533 100644 --- a/app/src/main/java/ani/dantotsu/MainActivity.kt +++ b/app/src/main/java/ani/dantotsu/MainActivity.kt @@ -5,7 +5,6 @@ import android.annotation.SuppressLint import android.app.AlertDialog import android.content.Intent import android.content.res.Configuration -import android.content.res.Resources import android.graphics.drawable.Animatable import android.graphics.drawable.GradientDrawable import android.net.Uri @@ -14,13 +13,10 @@ import android.os.Bundle import android.os.Handler import android.os.Looper import android.provider.Settings -import android.util.TypedValue -import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnticipateInterpolator import android.widget.TextView -import android.widget.Toast import androidx.activity.addCallback import androidx.activity.viewModels import androidx.annotation.OptIn @@ -36,26 +32,27 @@ import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.media3.common.util.UnstableApi -import androidx.media3.exoplayer.offline.Download import androidx.viewpager2.adapter.FragmentStateAdapter -import androidx.work.OneTimeWorkRequest +import ani.dantotsu.addons.torrent.TorrentAddonManager +import ani.dantotsu.addons.torrent.TorrentServerService import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.AnilistHomeViewModel import ani.dantotsu.databinding.ActivityMainBinding +import ani.dantotsu.databinding.DialogUserAgentBinding import ani.dantotsu.databinding.SplashScreenBinding -import ani.dantotsu.download.video.Helper 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.notifications.anilist.AnilistNotificationWorker -import ani.dantotsu.notifications.comment.CommentNotificationWorker +import ani.dantotsu.notifications.TaskScheduler import ani.dantotsu.others.CustomBottomDialog +import ani.dantotsu.others.calc.CalcActivity import ani.dantotsu.profile.ProfileActivity import ani.dantotsu.profile.activity.FeedActivity import ani.dantotsu.profile.activity.NotificationActivity +import ani.dantotsu.settings.ExtensionsActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager.asLiveBool import ani.dantotsu.settings.saving.PrefName @@ -70,11 +67,13 @@ import com.google.android.material.textfield.TextInputEditText import eu.kanade.domain.source.service.SourcePreferences import io.noties.markwon.Markwon import io.noties.markwon.SoftBreakAddsNewLinePlugin +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import nl.joery.animatedbottombar.AnimatedBottomBar +import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.Serializable @@ -87,6 +86,7 @@ class MainActivity : AppCompatActivity() { private var load = false + @kotlin.OptIn(DelicateCoroutinesApi::class) @SuppressLint("InternalInsetResource", "DiscouragedApi") @OptIn(UnstableApi::class) override fun onCreate(savedInstanceState: Bundle?) { @@ -100,12 +100,21 @@ class MainActivity : AppCompatActivity() { binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) - - androidx.work.WorkManager.getInstance(this) - .enqueue(OneTimeWorkRequest.Companion.from(CommentNotificationWorker::class.java)) - - androidx.work.WorkManager.getInstance(this) - .enqueue(OneTimeWorkRequest.Companion.from(AnilistNotificationWorker::class.java)) + TaskScheduler.scheduleSingleWork(this) + if (!CalcActivity.hasPermission) { + val pin: String = PrefManager.getVal(PrefName.AppPassword) + if (pin.isNotEmpty()) { + ContextCompat.startActivity( + this@MainActivity, + Intent(this@MainActivity, CalcActivity::class.java) + .putExtra("code", pin) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK), + null + ) + finish() + return + } + } val action = intent.action val type = intent.type @@ -161,16 +170,16 @@ class MainActivity : AppCompatActivity() { } } - val _bottomBar = findViewById(R.id.navbar) + val bottomNavBar = findViewById(R.id.navbar) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - val backgroundDrawable = _bottomBar.background as GradientDrawable + val backgroundDrawable = bottomNavBar.background as GradientDrawable val currentColor = backgroundDrawable.color?.defaultColor ?: 0 val semiTransparentColor = (currentColor and 0x00FFFFFF) or 0xF9000000.toInt() backgroundDrawable.setColor(semiTransparentColor) - _bottomBar.background = backgroundDrawable + bottomNavBar.background = backgroundDrawable } - _bottomBar.background = ContextCompat.getDrawable(this, R.drawable.bottom_nav_gray) + bottomNavBar.background = ContextCompat.getDrawable(this, R.drawable.bottom_nav_gray) val offset = try { val statusBarHeightId = resources.getIdentifier("status_bar_height", "dimen", "android") @@ -230,17 +239,6 @@ class MainActivity : AppCompatActivity() { } } - val preferences: SourcePreferences = Injekt.get() - if (preferences.animeExtensionUpdatesCount() - .get() > 0 || preferences.mangaExtensionUpdatesCount().get() > 0 - ) { - Toast.makeText( - this, - "You have extension updates available!", - Toast.LENGTH_LONG - ).show() - } - binding.root.isMotionEventSplittingEnabled = false lifecycleScope.launch { @@ -284,6 +282,16 @@ class MainActivity : AppCompatActivity() { binding.root.doOnAttach { initActivity(this) + val preferences: SourcePreferences = Injekt.get() + if (preferences.animeExtensionUpdatesCount() + .get() > 0 || preferences.mangaExtensionUpdatesCount().get() > 0 + ) { + snackString(R.string.extension_updates_available) + ?.setDuration(Snackbar.LENGTH_LONG) + ?.setAction(R.string.review) { + startActivity(Intent(this, ExtensionsActivity::class.java)) + } + } window.navigationBarColor = ContextCompat.getColor(this, android.R.color.transparent) selectedOption = if (fragment != null) { when (fragment) { @@ -295,11 +303,43 @@ class MainActivity : AppCompatActivity() { } else { PrefManager.getVal(PrefName.DefaultStartUpTab) } + val navbar = binding.includedNavbar.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()) + navbar.selectTabAt(selectedOption) + 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) + } + }) + if (mainViewPager.currentItem != selectedOption) { + mainViewPager.post { + mainViewPager.setCurrentItem( + selectedOption, + false + ) + } + } binding.includedNavbar.navbarContainer.updateLayoutParams { bottomMargin = navBarHeight } } + var launched = false intent.extras?.let { extras -> val fragmentToLoad = extras.getString("FRAGMENT_TO_LOAD") val mediaId = extras.getInt("mediaId", -1) @@ -312,6 +352,7 @@ class MainActivity : AppCompatActivity() { putExtra("mediaId", mediaId) putExtra("commentId", commentId) } + launched = true startActivity(detailIntent) } else if (fragmentToLoad == "FEED" && activityId != -1) { val feedIntent = Intent(this, FeedActivity::class.java).apply { @@ -319,6 +360,7 @@ class MainActivity : AppCompatActivity() { putExtra("activityId", activityId) } + launched = true startActivity(feedIntent) } else if (fragmentToLoad == "NOTIFICATIONS" && activityId != -1) { Logger.log("MainActivity, onCreate: $activityId") @@ -326,6 +368,7 @@ class MainActivity : AppCompatActivity() { putExtra("FRAGMENT_TO_LOAD", "NOTIFICATIONS") putExtra("activityId", activityId) } + launched = true startActivity(notificationIntent) } } @@ -339,47 +382,9 @@ class MainActivity : AppCompatActivity() { startActivity(Intent(this, NoInternet::class.java)) } else { val model: AnilistHomeViewModel by viewModels() - model.genres.observe(this) { it -> - if (it != null) { - if (it) { - val navbar = binding.includedNavbar.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()) - 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) - } - }) - if (mainViewPager.getCurrentItem() != selectedOption) { - navbar.selectTabAt(selectedOption) - mainViewPager.post { - mainViewPager.setCurrentItem( - selectedOption, - false - ) - } - } - } else { - binding.mainProgressBar.visibility = View.GONE - } - } - } + //Load Data - if (!load) { + if (!load && !launched) { scope.launch(Dispatchers.IO) { model.loadMain(this@MainActivity) val id = intent.extras?.getInt("mediaId", 0) @@ -450,16 +455,26 @@ class MainActivity : AppCompatActivity() { } } } - lifecycleScope.launch(Dispatchers.IO) { //simple cleanup - val index = Helper.downloadManager(this@MainActivity).downloadIndex - val downloadCursor = index.getDownloads() - while (downloadCursor.moveToNext()) { - val download = downloadCursor.download - if (download.state == Download.STATE_FAILED) { - Helper.downloadManager(this@MainActivity).removeDownload(download.request.id) + + val torrentManager = Injekt.get() + fun startTorrent() { + if (torrentManager.isAvailable() && PrefManager.getVal(PrefName.TorrentEnabled)) { + launchIO { + if (!TorrentServerService.isRunning()) { + TorrentServerService.start() + } } } } + if (torrentManager.isInitialized.value == false) { + torrentManager.isInitialized.observe(this) { + if (it) { + startTorrent() + } + } + } else { + startTorrent() + } } override fun onRestart() { @@ -467,34 +482,26 @@ class MainActivity : AppCompatActivity() { window.navigationBarColor = ContextCompat.getColor(this, android.R.color.transparent) } - private val Int.toPx get() = TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), Resources.getSystem().displayMetrics - ).toInt() - override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) - val params : ViewGroup.MarginLayoutParams = + val margin = if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) 8 else 32 + val params: ViewGroup.MarginLayoutParams = binding.includedNavbar.navbar.layoutParams as ViewGroup.MarginLayoutParams - if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) - params.updateMargins(bottom = 8.toPx) - else - params.updateMargins(bottom = 32.toPx) + params.updateMargins(bottom = margin.toPx) } private fun passwordAlertDialog(callback: (CharArray?) -> Unit) { val password = CharArray(16).apply { fill('0') } // Inflate the dialog layout - val dialogView = - LayoutInflater.from(this).inflate(R.layout.dialog_user_agent, null) - dialogView.findViewById(R.id.userAgentTextBox)?.hint = "Password" - val subtitleTextView = dialogView.findViewById(R.id.subtitle) - subtitleTextView?.visibility = View.VISIBLE - subtitleTextView?.text = "Enter your password to decrypt the file" + val dialogView = DialogUserAgentBinding.inflate(layoutInflater) + dialogView.userAgentTextBox.hint = "Password" + dialogView.subtitle.visibility = View.VISIBLE + dialogView.subtitle.text = getString(R.string.enter_password_to_decrypt_file) val dialog = AlertDialog.Builder(this, R.style.MyPopup) .setTitle("Enter Password") - .setView(dialogView) + .setView(dialogView.root) .setPositiveButton("OK", null) .setNegativeButton("Cancel") { dialog, _ -> password.fill('0') diff --git a/app/src/main/java/ani/dantotsu/Network.kt b/app/src/main/java/ani/dantotsu/Network.kt index aa71cb48..ce536e8d 100644 --- a/app/src/main/java/ani/dantotsu/Network.kt +++ b/app/src/main/java/ani/dantotsu/Network.kt @@ -1,6 +1,5 @@ package ani.dantotsu -import android.content.Context import android.os.Build import androidx.fragment.app.FragmentActivity import ani.dantotsu.others.webview.CloudFlare @@ -10,6 +9,7 @@ import com.lagradost.nicehttp.Requests import com.lagradost.nicehttp.ResponseParser import com.lagradost.nicehttp.addGenericDns import eu.kanade.tachiyomi.network.NetworkHelper +import eu.kanade.tachiyomi.network.NetworkHelper.Companion.defaultUserAgentProvider import kotlinx.coroutines.CancellationException import kotlinx.coroutines.async import kotlinx.coroutines.delay @@ -35,13 +35,13 @@ lateinit var defaultHeaders: Map lateinit var okHttpClient: OkHttpClient lateinit var client: Requests -fun initializeNetwork(context: Context) { +fun initializeNetwork() { val networkHelper = Injekt.get() defaultHeaders = mapOf( "User-Agent" to - Injekt.get().defaultUserAgentProvider() + defaultUserAgentProvider() .format(Build.VERSION.RELEASE, Build.MODEL) ) @@ -137,12 +137,14 @@ suspend fun tryWithSuspend( * **/ data class FileUrl( var url: String, - val headers: Map = mapOf() + var headers: Map = mapOf() ) : Serializable { companion object { operator fun get(url: String?, headers: Map = mapOf()): FileUrl? { return FileUrl(url ?: return null, headers) } + + private const val serialVersionUID = 1L } } diff --git a/app/src/main/java/ani/dantotsu/addons/Addon.kt b/app/src/main/java/ani/dantotsu/addons/Addon.kt new file mode 100644 index 00000000..e7b1a1d7 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/Addon.kt @@ -0,0 +1,15 @@ +package ani.dantotsu.addons + +abstract class Addon { + abstract val name: String + abstract val pkgName: String + abstract val versionName: String + abstract val versionCode: Long + + abstract class Installed( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + ) : Addon() +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/AddonDownloader.kt b/app/src/main/java/ani/dantotsu/addons/AddonDownloader.kt new file mode 100644 index 00000000..4ab1876f --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/AddonDownloader.kt @@ -0,0 +1,128 @@ +package ani.dantotsu.addons + +import android.app.Activity +import android.app.NotificationManager +import android.content.Context +import android.os.Build +import ani.dantotsu.Mapper +import ani.dantotsu.R +import ani.dantotsu.client +import ani.dantotsu.logError +import ani.dantotsu.openLinkInBrowser +import ani.dantotsu.others.AppUpdater +import ani.dantotsu.settings.InstallerSteps +import ani.dantotsu.toast +import ani.dantotsu.util.Logger +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.decodeFromJsonElement +import rx.android.schedulers.AndroidSchedulers + +class AddonDownloader { + companion object { + private suspend fun check(repo: String): Pair { + return try { + val res = client.get("https://api.github.com/repos/$repo/releases") + .parsed().map { + Mapper.json.decodeFromJsonElement(it) + } + val r = res.maxByOrNull { + it.timeStamp() + } ?: throw Exception("No Pre Release Found") + val v = r.tagName.substringAfter("v", "") + val md = r.body ?: "" + val version = v.ifEmpty { throw Exception("Weird Version : ${r.tagName}") } + + Logger.log("Git Version for $repo: $version") + Pair(md, version) + } catch (e: Exception) { + Logger.log("Error checking for update") + Logger.log(e) + Pair("", "") + } + } + + suspend fun hasUpdate(repo: String, currentVersion: String): Boolean { + val (_, version) = check(repo) + return compareVersion(version, currentVersion) + } + + suspend fun update( + activity: Activity, + manager: AddonManager<*>, + repo: String, + currentVersion: String + ) { + val (_, version) = check(repo) + if (!compareVersion(version, currentVersion)) { + toast(activity.getString(R.string.no_update_found)) + return + } + MainScope().launch(Dispatchers.IO) { + try { + val apks = + client.get("https://api.github.com/repos/$repo/releases/tags/v$version") + .parsed().assets?.filter { + it.browserDownloadURL.endsWith( + ".apk" + ) + } + val apkToDownload = + apks?.find { it.browserDownloadURL.contains(getCurrentABI()) } + ?: apks?.find { it.browserDownloadURL.contains("universal") } + ?: apks?.first() + apkToDownload?.browserDownloadURL.apply { + if (this != null) { + val notificationManager = + activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val installerSteps = InstallerSteps(notificationManager, activity) + manager.install(this) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe( + { installStep -> installerSteps.onInstallStep(installStep) {} }, + { error -> installerSteps.onError(error) {} }, + { installerSteps.onComplete {} } + ) + } else openLinkInBrowser("https://github.com/repos/$repo/releases/tag/v$version") + } + } catch (e: Exception) { + logError(e) + } + } + } + + /** + * Returns the ABI that the app is most likely running on. + * @return The primary ABI for the device. + */ + private fun getCurrentABI(): String { + return if (Build.SUPPORTED_ABIS.isNotEmpty()) { + Build.SUPPORTED_ABIS[0] + } else "Unknown" + } + + private fun compareVersion(newVersion: String, oldVersion: String): Boolean { + fun toDouble(list: List): Double { + return try { + list.mapIndexed { i: Int, s: String -> + when (i) { + 0 -> s.toDouble() * 100 + 1 -> s.toDouble() * 10 + 2 -> s.toDouble() + else -> s.toDoubleOrNull() ?: 0.0 + } + }.sum() + } catch (e: NumberFormatException) { + 0.0 + } + } + + val new = toDouble(newVersion.split(".")) + val curr = toDouble(oldVersion.split(".")) + return new > curr + } + + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/AddonInstallReceiver.kt b/app/src/main/java/ani/dantotsu/addons/AddonInstallReceiver.kt new file mode 100644 index 00000000..decc4d30 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/AddonInstallReceiver.kt @@ -0,0 +1,131 @@ +package ani.dantotsu.addons + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.core.content.ContextCompat +import ani.dantotsu.addons.download.DownloadAddonManager +import ani.dantotsu.addons.torrent.TorrentAddonManager +import ani.dantotsu.media.AddonType +import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver +import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver.Companion.filter +import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver.Companion.getPackageNameFromIntent +import kotlinx.coroutines.DelicateCoroutinesApi +import tachiyomi.core.util.lang.launchNow + +internal class AddonInstallReceiver : BroadcastReceiver() { + private var listener: AddonListener? = null + private var type: AddonType? = null + + /** + * Registers this broadcast receiver + */ + fun register(context: Context) { + ContextCompat.registerReceiver(context, this, filter, ContextCompat.RECEIVER_EXPORTED) + } + + fun setListener(listener: AddonListener, type: AddonType): AddonInstallReceiver { + this.listener = listener + this.type = type + return this + } + + /** + * 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. + */ + @OptIn(DelicateCoroutinesApi::class) + override fun onReceive(context: Context, intent: Intent?) { + if (intent == null) return + + when (intent.action) { + Intent.ACTION_PACKAGE_ADDED -> { + if (ExtensionInstallReceiver.isReplacing(intent)) return + launchNow { + when (type) { + AddonType.DOWNLOAD -> { + getPackageNameFromIntent(intent)?.let { packageName -> + if (packageName != DownloadAddonManager.DOWNLOAD_PACKAGE) return@launchNow + listener?.onAddonInstalled( + AddonLoader.loadFromPkgName( + context, + packageName, + AddonType.DOWNLOAD + ) + ) + } + } + + AddonType.TORRENT -> { + getPackageNameFromIntent(intent)?.let { packageName -> + if (packageName != TorrentAddonManager.TORRENT_PACKAGE) return@launchNow + listener?.onAddonInstalled( + AddonLoader.loadFromPkgName( + context, + packageName, + AddonType.TORRENT + ) + ) + } + } + + else -> {} + } + } + } + + Intent.ACTION_PACKAGE_REPLACED -> { + launchNow { + when (type) { + AddonType.DOWNLOAD -> { + getPackageNameFromIntent(intent)?.let { packageName -> + if (packageName != DownloadAddonManager.DOWNLOAD_PACKAGE) return@launchNow + listener?.onAddonUpdated( + AddonLoader.loadFromPkgName( + context, + packageName, + AddonType.DOWNLOAD + ) + ) + } + } + + AddonType.TORRENT -> { + getPackageNameFromIntent(intent)?.let { packageName -> + if (packageName != TorrentAddonManager.TORRENT_PACKAGE) return@launchNow + listener?.onAddonUpdated( + AddonLoader.loadFromPkgName( + context, + packageName, + AddonType.TORRENT + ) + ) + } + } + + else -> {} + } + } + } + + Intent.ACTION_PACKAGE_REMOVED -> { + if (ExtensionInstallReceiver.isReplacing(intent)) return + getPackageNameFromIntent(intent)?.let { packageName -> + when (type) { + AddonType.DOWNLOAD -> { + if (packageName != DownloadAddonManager.DOWNLOAD_PACKAGE) return + listener?.onAddonUninstalled(packageName) + } + + AddonType.TORRENT -> { + if (packageName != TorrentAddonManager.TORRENT_PACKAGE) return + listener?.onAddonUninstalled(packageName) + } + + else -> {} + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/AddonListener.kt b/app/src/main/java/ani/dantotsu/addons/AddonListener.kt new file mode 100644 index 00000000..7fdd4786 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/AddonListener.kt @@ -0,0 +1,11 @@ +package ani.dantotsu.addons + +interface AddonListener { + fun onAddonInstalled(result: LoadResult?) + fun onAddonUpdated(result: LoadResult?) + fun onAddonUninstalled(pkgName: String) + + enum class ListenerAction { + INSTALL, UPDATE, UNINSTALL + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/AddonLoader.kt b/app/src/main/java/ani/dantotsu/addons/AddonLoader.kt new file mode 100644 index 00000000..f2dc4488 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/AddonLoader.kt @@ -0,0 +1,176 @@ +package ani.dantotsu.addons + +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 ani.dantotsu.addons.download.DownloadAddon +import ani.dantotsu.addons.download.DownloadAddonApiV2 +import ani.dantotsu.addons.download.DownloadAddonManager +import ani.dantotsu.addons.download.DownloadLoadResult +import ani.dantotsu.addons.torrent.TorrentAddon +import ani.dantotsu.addons.torrent.TorrentAddonApi +import ani.dantotsu.addons.torrent.TorrentAddonManager +import ani.dantotsu.addons.torrent.TorrentLoadResult +import ani.dantotsu.media.AddonType +import ani.dantotsu.util.Logger +import dalvik.system.PathClassLoader +import eu.kanade.tachiyomi.extension.util.ExtensionLoader +import eu.kanade.tachiyomi.util.system.getApplicationIcon + +class AddonLoader { + companion object { + + /** + * Load an extension from a package name with a specific class name + * @param context the context + * @param packageName the package name of the extension + * @param type the type of extension + * @return the loaded extension + * @throws IllegalStateException if the extension is not of the correct type + * @throws ClassNotFoundException if the extension class is not found + * @throws NoClassDefFoundError if the extension class is not found + * @throws Exception if any other error occurs + * @throws PackageManager.NameNotFoundException if the package is not found + * @throws IllegalStateException if the extension is not found + */ + fun loadExtension( + context: Context, + packageName: String, + className: String, + type: AddonType + ): LoadResult? { + val pkgManager = context.packageManager + + val installedPkgs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + pkgManager.getInstalledPackages(PackageManager.PackageInfoFlags.of(ExtensionLoader.PACKAGE_FLAGS.toLong())) + } else { + pkgManager.getInstalledPackages(ExtensionLoader.PACKAGE_FLAGS) + } + + val extPkgs = installedPkgs.filter { + isPackageAnExtension( + packageName, + it + ) + } + + if (extPkgs.isEmpty()) return null + if (extPkgs.size > 1) throw IllegalStateException("Multiple extensions with the same package name found") + + val pkgName = extPkgs.first().packageName + val pkgInfo = extPkgs.first() + + 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 + Logger.log(error) + throw error + } + + val extName = + pkgManager.getApplicationLabel(appInfo).toString().substringAfter("Dantotsu: ") + val versionName = pkgInfo.versionName + val versionCode = PackageInfoCompat.getLongVersionCode(pkgInfo) + + if (versionName.isNullOrEmpty()) { + Logger.log("Missing versionName for extension $extName") + throw IllegalStateException("Missing versionName for extension $extName") + } + val classLoader = + PathClassLoader(appInfo.sourceDir, appInfo.nativeLibraryDir, context.classLoader) + val loadedClass = try { + Class.forName(className, false, classLoader) + } catch (e: ClassNotFoundException) { + Logger.log("ClassNotFoundException load error: $extName ($className)") + Logger.log(e) + throw e + } catch (e: NoClassDefFoundError) { + Logger.log("NoClassDefFoundError load error: $extName ($className)") + Logger.log(e) + throw e + } catch (e: Exception) { + Logger.log("Extension load error: $extName ($className)") + Logger.log(e) + throw e + } + val instance = loadedClass.getDeclaredConstructor().newInstance() + + return when (type) { + AddonType.TORRENT -> { + val extension = instance as? TorrentAddonApi + ?: throw IllegalStateException("Extension is not a TorrentAddonApi") + TorrentLoadResult.Success( + TorrentAddon.Installed( + name = extName, + pkgName = pkgName, + versionName = versionName, + versionCode = versionCode, + extension = extension, + icon = context.getApplicationIcon(pkgName), + ) + ) + } + + AddonType.DOWNLOAD -> { + val extension = instance as? DownloadAddonApiV2 + ?: throw IllegalStateException("Extension is not a DownloadAddonApiV2") + DownloadLoadResult.Success( + DownloadAddon.Installed( + name = extName, + pkgName = pkgName, + versionName = versionName, + versionCode = versionCode, + extension = extension, + icon = context.getApplicationIcon(pkgName), + ) + ) + } + } + } + + /** + * Load an extension from a package name (class is determined by type) + * @param context the context + * @param packageName the package name of the extension + * @param type the type of extension + * @return the loaded extension + */ + fun loadFromPkgName(context: Context, packageName: String, type: AddonType): LoadResult? { + return try { + when (type) { + AddonType.TORRENT -> loadExtension( + context, + packageName, + TorrentAddonManager.TORRENT_CLASS, + type + ) + + AddonType.DOWNLOAD -> loadExtension( + context, + packageName, + DownloadAddonManager.DOWNLOAD_CLASS, + type + ) + } + } catch (e: Exception) { + Logger.log("Error loading extension from package name: $packageName") + Logger.log(e) + null + } + } + + /** + * Check if a package is an extension by comparing the package name + * @param type the type of extension + * @param pkgInfo the package info + * @return true if the package is an extension + */ + private fun isPackageAnExtension(type: String, pkgInfo: PackageInfo): Boolean { + return pkgInfo.packageName.equals(type) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/AddonManager.kt b/app/src/main/java/ani/dantotsu/addons/AddonManager.kt new file mode 100644 index 00000000..edf92dee --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/AddonManager.kt @@ -0,0 +1,46 @@ +package ani.dantotsu.addons + +import android.content.Context +import ani.dantotsu.media.AddonType +import eu.kanade.tachiyomi.extension.InstallStep +import eu.kanade.tachiyomi.extension.util.ExtensionInstaller +import rx.Observable + +abstract class AddonManager( + private val context: Context +) { + abstract var extension: T? + abstract var name: String + abstract var type: AddonType + protected val installer by lazy { ExtensionInstaller(context) } + var hasUpdate: Boolean = false + protected set + + protected var onListenerAction: ((AddonListener.ListenerAction) -> Unit)? = null + + abstract suspend fun init() + abstract fun isAvailable(andEnabled: Boolean = true): Boolean + abstract fun getVersion(): String? + abstract fun getPackageName(): String? + abstract fun hadError(context: Context): String? + abstract fun updateInstallStep(id: Long, step: InstallStep) + abstract fun setInstalling(id: Long) + + fun uninstall() { + getPackageName()?.let { + installer.uninstallApk(it) + } + } + + fun addListenerAction(action: (AddonListener.ListenerAction) -> Unit) { + onListenerAction = action + } + + fun removeListenerAction() { + onListenerAction = null + } + + fun install(url: String): Observable { + return installer.downloadAndInstall(url, getPackageName() ?: "", name, type) + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/LoadResult.kt b/app/src/main/java/ani/dantotsu/addons/LoadResult.kt new file mode 100644 index 00000000..e59288c8 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/LoadResult.kt @@ -0,0 +1,8 @@ +package ani.dantotsu.addons + +abstract class LoadResult { + + abstract class Success : LoadResult() + + +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/download/DownloadAddon.kt b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddon.kt new file mode 100644 index 00000000..ee89d7c5 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddon.kt @@ -0,0 +1,18 @@ +package ani.dantotsu.addons.download + +import android.graphics.drawable.Drawable +import ani.dantotsu.addons.Addon + +sealed class DownloadAddon : Addon() { + + data class Installed( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + val extension: DownloadAddonApiV2, + val icon: Drawable?, + val hasUpdate: Boolean = false, + ) : Addon.Installed(name, pkgName, versionName, versionCode) + +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonApiV2.kt b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonApiV2.kt new file mode 100644 index 00000000..ee82acba --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonApiV2.kt @@ -0,0 +1,40 @@ +package ani.dantotsu.addons.download + +import android.content.Context +import android.net.Uri + +interface DownloadAddonApiV2 { + + fun cancelDownload(sessionId: Long) + + fun setDownloadPath(context: Context, uri: Uri): String + + fun getReadPath(context: Context, uri: Uri): String + + suspend fun executeFFProbe( + videoUrl: String, + headers: Map = emptyMap(), + logCallback: (String) -> Unit + ) + + suspend fun executeFFMpeg( + videoUrl: String, + downloadPath: String, + headers: Map = emptyMap(), + subtitleUrls: List> = emptyList(), + audioUrls: List> = emptyList(), + statCallback: (Double) -> Unit + ): Long + + suspend fun customFFMpeg(command: String, videoUrls: List, logCallback: (String) -> Unit): Long + + suspend fun customFFProbe(command: String, videoUrls: List, logCallback: (String) -> Unit) + + fun getState(sessionId: Long): String + + fun getStackTrace(sessionId: Long): String? + + fun hadError(sessionId: Long): Boolean + + fun getFileExtension(): Pair = Pair("mkv", "video/x-matroska") +} diff --git a/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonManager.kt b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonManager.kt new file mode 100644 index 00000000..6fb4695a --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/download/DownloadAddonManager.kt @@ -0,0 +1,135 @@ +package ani.dantotsu.addons.download + +import android.content.Context +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import ani.dantotsu.R +import ani.dantotsu.addons.AddonDownloader +import ani.dantotsu.addons.AddonInstallReceiver +import ani.dantotsu.addons.AddonListener +import ani.dantotsu.addons.AddonLoader +import ani.dantotsu.addons.AddonManager +import ani.dantotsu.addons.LoadResult +import ani.dantotsu.media.AddonType +import ani.dantotsu.util.Logger +import eu.kanade.tachiyomi.extension.InstallStep +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class DownloadAddonManager( + private val context: Context +) : AddonManager(context) { + + override var extension: DownloadAddon.Installed? = null + override var name: String = "Download Addon" + override var type = AddonType.DOWNLOAD + + private val _isInitialized = MutableLiveData(false) + val isInitialized: LiveData = _isInitialized + + private var error: String? = null + + override suspend fun init() { + extension = null + error = null + hasUpdate = false + withContext(Dispatchers.Main) { + _isInitialized.value = false + } + + AddonInstallReceiver() + .setListener(InstallationListener(), type) + .register(context) + try { + val result = AddonLoader.loadExtension( + context, + DOWNLOAD_PACKAGE, + DOWNLOAD_CLASS, + AddonType.DOWNLOAD + ) as? DownloadLoadResult + result?.let { + if (it is DownloadLoadResult.Success) { + extension = it.extension + hasUpdate = AddonDownloader.hasUpdate(REPO, it.extension.versionName) + } + } + Logger.log("Download addon initialized successfully") + withContext(Dispatchers.Main) { + _isInitialized.value = true + } + } catch (e: Exception) { + Logger.log("Error initializing Download addon") + Logger.log(e) + error = e.message + } + } + + override fun isAvailable(andEnabled: Boolean): Boolean { + return extension?.extension != null + } + + override fun getVersion(): String? { + return extension?.versionName + } + + override fun getPackageName(): String? { + return extension?.pkgName + } + + override fun hadError(context: Context): String? { + return if (isInitialized.value == true) { + if (error != null) { + error + } else if (extension != null) { + context.getString(R.string.loaded_successfully) + } else { + null + } + } else { + null + } + } + + private inner class InstallationListener : AddonListener { + override fun onAddonInstalled(result: LoadResult?) { + if (result is DownloadLoadResult.Success) { + extension = result.extension + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.INSTALL) + } + } + + override fun onAddonUpdated(result: LoadResult?) { + if (result is DownloadLoadResult.Success) { + extension = result.extension + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.UPDATE) + } + } + + override fun onAddonUninstalled(pkgName: String) { + if (extension?.pkgName == pkgName) { + extension = null + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.UNINSTALL) + } + } + + } + + override fun updateInstallStep(id: Long, step: InstallStep) { + installer.updateInstallStep(id, step) + } + + override fun setInstalling(id: Long) { + installer.updateInstallStep(id, InstallStep.Installing) + } + + + companion object { + + const val DOWNLOAD_PACKAGE = "dantotsu.downloadAddon" + const val DOWNLOAD_CLASS = "ani.dantotsu.downloadAddon.DownloadAddon" + const val REPO = "rebelonion/Dantotsu-Download-Addon" + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/download/DownloadLoadResult.kt b/app/src/main/java/ani/dantotsu/addons/download/DownloadLoadResult.kt new file mode 100644 index 00000000..da8e7cdd --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/download/DownloadLoadResult.kt @@ -0,0 +1,7 @@ +package ani.dantotsu.addons.download + +import ani.dantotsu.addons.LoadResult + +open class DownloadLoadResult : LoadResult() { + class Success(val extension: DownloadAddon.Installed) : DownloadLoadResult() +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddon.kt b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddon.kt new file mode 100644 index 00000000..ebb369f6 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddon.kt @@ -0,0 +1,16 @@ +package ani.dantotsu.addons.torrent + +import android.graphics.drawable.Drawable +import ani.dantotsu.addons.Addon + +sealed class TorrentAddon : Addon() { + data class Installed( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Long, + val extension: TorrentAddonApi, + val icon: Drawable?, + val hasUpdate: Boolean = false, + ) : Addon.Installed(name, pkgName, versionName, versionCode) +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonApi.kt b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonApi.kt new file mode 100644 index 00000000..956e5c21 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonApi.kt @@ -0,0 +1,24 @@ +package ani.dantotsu.addons.torrent + +import eu.kanade.tachiyomi.data.torrentServer.model.Torrent + +interface TorrentAddonApi { + + fun startServer(path: String) + + fun stopServer() + + fun echo(): String + + fun removeTorrent(torrent: String) + + fun addTorrent( + link: String, + title: String, + poster: String, + data: String, + save: Boolean, + ): Torrent + + fun getLink(torrent: Torrent, index: Int): String +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonManager.kt b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonManager.kt new file mode 100644 index 00000000..1d71d45d --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentAddonManager.kt @@ -0,0 +1,142 @@ +package ani.dantotsu.addons.torrent + +import android.content.Context +import android.os.Build +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import ani.dantotsu.R +import ani.dantotsu.addons.AddonDownloader.Companion.hasUpdate +import ani.dantotsu.addons.AddonListener +import ani.dantotsu.addons.AddonLoader +import ani.dantotsu.addons.AddonManager +import ani.dantotsu.addons.LoadResult +import ani.dantotsu.addons.AddonInstallReceiver +import ani.dantotsu.media.AddonType +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.util.Logger +import eu.kanade.tachiyomi.extension.InstallStep +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class TorrentAddonManager( + private val context: Context +) : AddonManager(context) { + override var extension: TorrentAddon.Installed? = null + override var name: String = "Torrent Addon" + override var type: AddonType = AddonType.TORRENT + var torrentHash: String? = null + + private val _isInitialized = MutableLiveData(false) + val isInitialized: LiveData = _isInitialized + + private var error: String? = null + + override suspend fun init() { + extension = null + error = null + hasUpdate = false + withContext(Dispatchers.Main) { + _isInitialized.value = false + } + if (Build.VERSION.SDK_INT < 23) { + Logger.log("Torrent extension is not supported on this device.") + error = context.getString(R.string.torrent_extension_not_supported) + return + } + + AddonInstallReceiver() + .setListener(InstallationListener(), type) + .register(context) + try { + val result = AddonLoader.loadExtension( + context, + TORRENT_PACKAGE, + TORRENT_CLASS, + type + ) as TorrentLoadResult? + result?.let { + if (it is TorrentLoadResult.Success) { + extension = it.extension + hasUpdate = hasUpdate(REPO, it.extension.versionName) + } + } + Logger.log("Torrent addon initialized successfully") + withContext(Dispatchers.Main) { + _isInitialized.value = true + } + } catch (e: Exception) { + Logger.log("Error initializing torrent addon") + Logger.log(e) + error = e.message + } + } + + override fun isAvailable(andEnabled: Boolean): Boolean { + return extension?.extension != null && if (andEnabled) { + PrefManager.getVal(PrefName.TorrentEnabled) + } else true + } + + override fun getVersion(): String? { + return extension?.versionName + } + + override fun getPackageName(): String? { + return extension?.pkgName + } + + override fun hadError(context: Context): String? { + return if (isInitialized.value == true) { + if (error != null) { + error + } else if (extension != null) { + context.getString(R.string.loaded_successfully) + } else { + null + } + } else { + null + } + } + + private inner class InstallationListener : AddonListener { + override fun onAddonInstalled(result: LoadResult?) { + if (result is TorrentLoadResult.Success) { + extension = result.extension + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.INSTALL) + } + } + + override fun onAddonUpdated(result: LoadResult?) { + if (result is TorrentLoadResult.Success) { + extension = result.extension + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.UPDATE) + } + } + + override fun onAddonUninstalled(pkgName: String) { + if (pkgName == TORRENT_PACKAGE) { + extension = null + hasUpdate = false + onListenerAction?.invoke(AddonListener.ListenerAction.UNINSTALL) + } + } + } + + override fun updateInstallStep(id: Long, step: InstallStep) { + installer.updateInstallStep(id, step) + } + + override fun setInstalling(id: Long) { + installer.updateInstallStep(id, InstallStep.Installing) + } + + companion object { + const val TORRENT_PACKAGE = "dantotsu.torrentAddon" + const val TORRENT_CLASS = "ani.dantotsu.torrentAddon.TorrentAddon" + const val REPO = "rebelonion/Dantotsu-Torrent-Addon" + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/torrent/TorrentLoadResult.kt b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentLoadResult.kt new file mode 100644 index 00000000..dfba2009 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentLoadResult.kt @@ -0,0 +1,7 @@ +package ani.dantotsu.addons.torrent + +import ani.dantotsu.addons.LoadResult + +open class TorrentLoadResult : LoadResult() { + class Success(val extension: TorrentAddon.Installed) : TorrentLoadResult() +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/addons/torrent/TorrentService.kt b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentService.kt new file mode 100644 index 00000000..295ae176 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/addons/torrent/TorrentService.kt @@ -0,0 +1,179 @@ +/** + * modified source from + * https://github.com/rebelonion/Dantotsu/pull/305 + * and https://github.com/LuftVerbot/kuukiyomi + * all credits to the original authors + */ + +package ani.dantotsu.addons.torrent + +import android.app.ActivityManager +import android.app.Application +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import ani.dantotsu.R +import ani.dantotsu.util.Logger +import eu.kanade.tachiyomi.data.notification.Notifications.CHANNEL_TORRENT_SERVER +import eu.kanade.tachiyomi.data.notification.Notifications.ID_TORRENT_SERVER +import eu.kanade.tachiyomi.util.system.cancelNotification +import eu.kanade.tachiyomi.util.system.notificationBuilder +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get +import kotlin.coroutines.EmptyCoroutineContext + + +class TorrentServerService : Service() { + private val serviceScope = CoroutineScope(EmptyCoroutineContext) + private val applicationContext = Injekt.get() + private lateinit var extension: TorrentAddonApi + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand( + intent: Intent?, + flags: Int, + startId: Int, + ): Int { + extension = Injekt.get().extension?.extension ?: return START_NOT_STICKY + intent?.let { + if (it.action != null) { + when (it.action) { + ACTION_START -> { + startServer() + notification(applicationContext) + return START_STICKY + } + + ACTION_STOP -> { + stopServer() + return START_NOT_STICKY + } + } + } + } + return START_NOT_STICKY + } + + private fun startServer() { + serviceScope.launch { + val echo = extension.echo() + if (echo == "") { + extension.startServer(filesDir.absolutePath) + } + } + } + + private fun stopServer() { + serviceScope.launch { + extension.stopServer() + applicationContext.cancelNotification(ID_TORRENT_SERVER) + stopSelf() + } + } + + private fun notification(context: Context) { + val exitPendingIntent = + PendingIntent.getService( + applicationContext, + 0, + Intent(applicationContext, TorrentServerService::class.java).apply { + action = ACTION_STOP + }, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val builder = context.notificationBuilder(CHANNEL_TORRENT_SERVER) { + setSmallIcon(R.drawable.notification_icon) + setContentText("Torrent Server") + setContentTitle("Server is running…") + setAutoCancel(false) + setOngoing(true) + setUsesChronometer(true) + addAction( + R.drawable.ic_circle_cancel, + "Stop", + exitPendingIntent, + ) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + startForeground( + ID_TORRENT_SERVER, + builder.build(), + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, + ) + } else { + startForeground(ID_TORRENT_SERVER, builder.build()) + } + } + + companion object { + const val ACTION_START = "start_torrent_server" + const val ACTION_STOP = "stop_torrent_server" + + fun isRunning(): Boolean { + with(Injekt.get().getSystemService(ACTIVITY_SERVICE) as ActivityManager) { + @Suppress("DEPRECATION") // We only need our services + getRunningServices(Int.MAX_VALUE).forEach { + if (TorrentServerService::class.java.name.equals(it.service.className)) { + return true + } + } + } + return false + } + + fun start() { + if (Injekt.get().extension?.extension == null) { + return + } + try { + val intent = + Intent(Injekt.get(), TorrentServerService::class.java).apply { + action = ACTION_START + } + Injekt.get().startService(intent) + } catch (e: Exception) { + e.printStackTrace() + } + } + + + fun stop() { + try { + val intent = + Intent(Injekt.get(), TorrentServerService::class.java).apply { + action = ACTION_STOP + } + Injekt.get().startService(intent) + } catch (e: Exception) { + e.printStackTrace() + } + } + + fun wait(timeout: Int = -1): Boolean { + var count = 0 + if (timeout < 0) { + count = -20 + } + var echo = Injekt.get().extension?.extension?.echo() + while (echo == "") { + Thread.sleep(1000) + count++ + if (count > timeout) { + return false + } + echo = Injekt.get().extension?.extension?.echo() + } + Logger.log("ServerService: Server started: $echo") + return true + } + + } +} \ 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 index c3a19008..8f8c4bda 100644 --- a/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/InjektModules.kt +++ b/app/src/main/java/ani/dantotsu/aniyomi/anime/custom/InjektModules.kt @@ -6,6 +6,8 @@ import androidx.annotation.OptIn import androidx.core.content.ContextCompat import androidx.media3.common.util.UnstableApi import androidx.media3.database.StandaloneDatabaseProvider +import ani.dantotsu.addons.download.DownloadAddonManager +import ani.dantotsu.addons.torrent.TorrentAddonManager import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.download.DownloadsManager import ani.dantotsu.media.manga.MangaCache @@ -18,6 +20,7 @@ import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.source.anime.AndroidAnimeSourceManager import eu.kanade.tachiyomi.source.manga.AndroidMangaSourceManager +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import tachiyomi.core.preference.PreferenceStore import tachiyomi.domain.source.anime.service.AnimeSourceManager @@ -29,6 +32,7 @@ import uy.kohesive.injekt.api.addSingletonFactory import uy.kohesive.injekt.api.get class AppModule(val app: Application) : InjektModule { + @kotlin.OptIn(ExperimentalSerializationApi::class) @OptIn(UnstableApi::class) override fun InjektRegistrar.registerInjectables() { addSingleton(app) @@ -36,10 +40,13 @@ class AppModule(val app: Application) : InjektModule { addSingletonFactory { DownloadsManager(app) } addSingletonFactory { NetworkHelper(app) } + addSingletonFactory { NetworkHelper(app).client } addSingletonFactory { AnimeExtensionManager(app) } addSingletonFactory { MangaExtensionManager(app) } addSingletonFactory { NovelExtensionManager(app) } + addSingletonFactory { TorrentAddonManager(app) } + addSingletonFactory { DownloadAddonManager(app) } addSingletonFactory { AndroidAnimeSourceManager(app, get()) } addSingletonFactory { AndroidMangaSourceManager(app, get()) } @@ -53,10 +60,6 @@ class AppModule(val app: Application) : InjektModule { addSingletonFactory { StandaloneDatabaseProvider(app) } - addSingletonFactory { - ani.dantotsu.connections.crashlytics.CrashlyticsFactory.createCrashlytics() - } - addSingletonFactory { MangaCache() } ContextCompat.getMainExecutor(app).execute { diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/Anilist.kt b/app/src/main/java/ani/dantotsu/connections/anilist/Anilist.kt index 804343f6..51f3bc9d 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/Anilist.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/Anilist.kt @@ -3,17 +3,16 @@ package ani.dantotsu.connections.anilist import android.content.ActivityNotFoundException import android.content.Context import android.net.Uri -import android.util.Log import androidx.browser.customtabs.CustomTabsIntent import ani.dantotsu.R import ani.dantotsu.client +import ani.dantotsu.connections.comments.CommentsAPI import ani.dantotsu.currContext import ani.dantotsu.openLinkInBrowser import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.toast -import ani.dantotsu.tryWithSuspend import ani.dantotsu.util.Logger import java.util.Calendar @@ -36,24 +35,60 @@ object Anilist { var rateLimitReset: Long = 0 + var initialized = false + val sortBy = listOf( "SCORE_DESC", "POPULARITY_DESC", "TRENDING_DESC", + "START_DATE_DESC", "TITLE_ENGLISH", "TITLE_ENGLISH_DESC", "SCORE" ) + val source = listOf( + "ORIGINAL", + "MANGA", + "LIGHT NOVEL", + "VISUAL NOVEL", + "VIDEO GAME", + "OTHER", + "NOVEL", + "DOUJINSHI", + "ANIME", + "WEB NOVEL", + "LIVE ACTION", + "GAME", + "COMIC", + "MULTIMEDIA PROJECT", + "PICTURE BOOK" + ) + + val animeStatus = listOf( + "FINISHED", + "RELEASING", + "NOT YET RELEASED", + "CANCELLED" + ) + + val mangaStatus = listOf( + "FINISHED", + "RELEASING", + "NOT YET RELEASED", + "HIATUS", + "CANCELLED" + ) + val seasons = listOf( "WINTER", "SPRING", "SUMMER", "FALL" ) - val anime_formats = listOf( + val animeFormats = listOf( "TV", "TV SHORT", "MOVIE", "SPECIAL", "OVA", "ONA", "MUSIC" ) - val manga_formats = listOf( + val mangaFormats = listOf( "MANGA", "NOVEL", "ONE SHOT" ) @@ -117,6 +152,9 @@ object Anilist { episodesWatched = null chapterRead = null PrefManager.removeVal(PrefName.AnilistToken) + //logout from comments api + CommentsAPI.logout() + } suspend inline fun executeQuery( @@ -138,7 +176,7 @@ object Anilist { "variables" to variables ) val headers = mutableMapOf( - "Content-Type" to "application/json", + "Content-Type" to "application/json; charset=utf-8", "Accept" to "application/json" ) @@ -163,8 +201,9 @@ object Anilist { toast("Rate limited. Try after $retry seconds") throw Exception("Rate limited after $retry seconds") } - if (!json.text.startsWith("{")) {throw Exception(currContext()?.getString(R.string.anilist_down))} - if (show) Logger.log("Anilist Response: ${json.text}") + if (!json.text.startsWith("{")) { + throw Exception(currContext()?.getString(R.string.anilist_down)) + } json.parsed() } else null } catch (e: Exception) { diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistMutations.kt b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistMutations.kt index c2b8eb24..a8bd8904 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistMutations.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistMutations.kt @@ -2,6 +2,10 @@ package ani.dantotsu.connections.anilist import ani.dantotsu.connections.anilist.Anilist.executeQuery import ani.dantotsu.connections.anilist.api.FuzzyDate +import ani.dantotsu.connections.anilist.api.Query +import ani.dantotsu.currContext +import com.google.gson.Gson +import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject class AnilistMutations { @@ -69,4 +73,54 @@ class AnilistMutations { val variables = """{"id":"$listId"}""" executeQuery(query, variables) } + + + suspend fun rateReview(reviewId: Int, rating: String): Query.RateReviewResponse? { + val query = "mutation{RateReview(reviewId:$reviewId,rating:$rating){id mediaId mediaType summary body(asHtml:true)rating ratingAmount userRating score private siteUrl createdAt updatedAt user{id name bannerImage avatar{medium large}}}}" + return executeQuery(query) + } + + suspend fun postActivity(text:String): String { + val encodedText = text.stringSanitizer() + val query = "mutation{SaveTextActivity(text:$encodedText){siteUrl}}" + val result = executeQuery(query) + val errors = result?.get("errors") + return errors?.toString() + ?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success") + } + + suspend fun postReview(summary: String, body: String, mediaId: Int, score: Int): String { + val encodedSummary = summary.stringSanitizer() + val encodedBody = body.stringSanitizer() + val query = "mutation{SaveReview(mediaId:$mediaId,summary:$encodedSummary,body:$encodedBody,score:$score){siteUrl}}" + val result = executeQuery(query) + val errors = result?.get("errors") + return errors?.toString() + ?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success") + } + + suspend fun postReply(activityId: Int, text: String): String { + val encodedText = text.stringSanitizer() + val query = "mutation{SaveActivityReply(activityId:$activityId,text:$encodedText){id}}" + val result = executeQuery(query) + val errors = result?.get("errors") + return errors?.toString() + ?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success") + } + + private fun String.stringSanitizer(): String { + val sb = StringBuilder() + var i = 0 + while (i < this.length) { + val codePoint = this.codePointAt(i) + if (codePoint > 0xFFFF) { + sb.append("&#").append(codePoint).append(";") + i += 2 + } else { + sb.append(this[i]) + i++ + } + } + return Gson().toJson(sb.toString()) + } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistQueries.kt b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistQueries.kt index c9ff694d..4315ad13 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistQueries.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistQueries.kt @@ -11,6 +11,7 @@ import ani.dantotsu.connections.anilist.api.FuzzyDate import ani.dantotsu.connections.anilist.api.NotificationResponse import ani.dantotsu.connections.anilist.api.Page import ani.dantotsu.connections.anilist.api.Query +import ani.dantotsu.connections.anilist.api.ReplyResponse import ani.dantotsu.connections.anilist.api.ToggleLike import ani.dantotsu.currContext import ani.dantotsu.isOnline @@ -20,10 +21,10 @@ import ani.dantotsu.media.Character import ani.dantotsu.media.Media import ani.dantotsu.media.Studio import ani.dantotsu.others.MalScraper +import ani.dantotsu.profile.User import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString -import ani.dantotsu.util.Logger import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking @@ -32,6 +33,7 @@ import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable +import java.util.Calendar import kotlin.system.measureTimeMillis class AnilistQueries { @@ -56,6 +58,7 @@ class AnilistQueries { Anilist.unreadNotificationCount = user.unreadNotificationCount ?: 0 val unread = PrefManager.getVal(PrefName.UnreadCommentNotifications) Anilist.unreadNotificationCount += unread + Anilist.initialized = true return true } @@ -72,18 +75,19 @@ class AnilistQueries { media.cameFromContinue = false val query = - """{Media(id:${media.id}){id mediaListEntry{id status score(format:POINT_100)progress private notes repeat customLists updatedAt startedAt{year month day}completedAt{year month day}}isFavourite siteUrl idMal nextAiringEpisode{episode airingAt}source countryOfOrigin format duration season seasonYear startDate{year month day}endDate{year month day}genres studios(isMain:true){nodes{id name siteUrl}}description trailer{site id}synonyms tags{name rank isMediaSpoiler}characters(sort:[ROLE,FAVOURITES_DESC],perPage:25,page:1){edges{role node{id image{medium}name{userPreferred}isFavourite}}}relations{edges{relationType(version:2)node{id idMal mediaListEntry{progress private score(format:POINT_100)status}episodes chapters nextAiringEpisode{episode}popularity meanScore isAdult isFavourite format title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}staffPreview:staff(perPage:8,sort:[RELEVANCE,ID]){edges{role node{id image{large medium}name{userPreferred}}}}recommendations(sort:RATING_DESC){nodes{mediaRecommendation{id idMal mediaListEntry{progress private score(format:POINT_100)status}episodes chapters nextAiringEpisode{episode}meanScore isAdult isFavourite format title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}externalLinks{url site}}}""" + """{Media(id:${media.id}){id favourites popularity episodes chapters mediaListEntry{id status score(format:POINT_100)progress private notes repeat customLists updatedAt startedAt{year month day}completedAt{year month day}}reviews(perPage:3, sort:SCORE_DESC){nodes{id mediaId mediaType summary body(asHtml:true) rating ratingAmount userRating score private siteUrl createdAt updatedAt user{id name bannerImage avatar{medium large}}}}isFavourite siteUrl idMal nextAiringEpisode{episode airingAt}source countryOfOrigin format duration season seasonYear startDate{year month day}endDate{year month day}genres studios(isMain:true){nodes{id name siteUrl}}description trailer{site id}synonyms tags{name rank isMediaSpoiler}characters(sort:[ROLE,FAVOURITES_DESC],perPage:25,page:1){edges{role voiceActors { id name { first middle last full native userPreferred } image { large medium } languageV2 } node{id image{medium}name{userPreferred}isFavourite}}}relations{edges{relationType(version:2)node{id idMal mediaListEntry{progress private score(format:POINT_100)status}episodes chapters nextAiringEpisode{episode}popularity meanScore isAdult isFavourite format title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}staffPreview:staff(perPage:8,sort:[RELEVANCE,ID]){edges{role node{id image{large medium}name{userPreferred}}}}recommendations(sort:RATING_DESC){nodes{mediaRecommendation{id idMal mediaListEntry{progress private score(format:POINT_100)status}episodes chapters nextAiringEpisode{episode}meanScore isAdult isFavourite format title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}externalLinks{url site}}Page(page:1){pageInfo{total perPage currentPage lastPage hasNextPage}mediaList(isFollowing:true,sort:[STATUS],mediaId:${media.id}){id status score(format: POINT_100) progress progressVolumes user{id name avatar{large medium}}}}}""" runBlocking { val anilist = async { - var response = executeQuery(query, force = true, show = true) + var response = executeQuery(query, force = true) if (response != null) { fun parse() { val fetchedMedia = response?.data?.media ?: return - + val user = response?.data?.page media.source = fetchedMedia.source?.toString() media.countryOfOrigin = fetchedMedia.countryOfOrigin media.format = fetchedMedia.format?.toString() - + media.favourites = fetchedMedia.favourites + media.popularity = fetchedMedia.popularity media.startDate = fetchedMedia.startDate media.endDate = fetchedMedia.endDate @@ -138,7 +142,15 @@ class AnilistQueries { ?: "SUPPORTING" else -> i.role.toString() - } + }, + voiceActor = i.voiceActors?.map { + Author( + id = it.id, + name = it.name?.userPreferred, + image = it.image?.large, + role = it.languageV2 + ) + } as ArrayList ) ) } @@ -152,7 +164,7 @@ class AnilistQueries { Author( id = id, name = i.node?.name?.userPreferred, - image = i.node?.image?.medium, + image = i.node?.image?.large, role = when (i.role.toString()) { "MAIN" -> currContext()?.getString(R.string.main_role) ?: "MAIN" @@ -199,7 +211,27 @@ class AnilistQueries { } } } - + if (fetchedMedia.reviews?.nodes != null){ + media.review = fetchedMedia.reviews!!.nodes as ArrayList + } + if (user?.mediaList?.isNotEmpty() == true) { + media.users = user.mediaList?.mapNotNull { + it.user?.let { user -> + if (user.id != Anilist.userid) { + User( + user.id, + user.name ?: "Unknown", + user.avatar?.large, + "", + it.status?.toString(), + it.score, + it.progress, + fetchedMedia.episodes ?: fetchedMedia.chapters, + ) + } else null + } + }?.toCollection(arrayListOf()) ?: arrayListOf() + } if (fetchedMedia.mediaListEntry != null) { fetchedMedia.mediaListEntry?.apply { media.userProgress = progress @@ -344,69 +376,11 @@ class AnilistQueries { } return media } - - suspend fun continueMedia(type: String, planned: Boolean = false): ArrayList { - val returnArray = arrayListOf() - val map = mutableMapOf() - val query = if (planned) { - """{ planned: ${continueMediaQuery(type, "PLANNING")} }""" - } else { - """{ - current: ${continueMediaQuery(type, "CURRENT")}, - repeating: ${continueMediaQuery(type, "REPEATING")} - }""" - } - - val response = executeQuery(query) - if (planned) { - response?.data?.planned?.lists?.forEach { li -> - li.entries?.reversed()?.forEach { - val m = Media(it) - m.cameFromContinue = true - map[m.id] = m - } - } - } else { - response?.data?.current?.lists?.forEach { li -> - li.entries?.reversed()?.forEach { - val m = Media(it) - m.cameFromContinue = true - map[m.id] = m - } - } - response?.data?.repeating?.lists?.forEach { li -> - li.entries?.reversed()?.forEach { - val m = Media(it) - m.cameFromContinue = true - map[m.id] = m - } - } - } - if (type != "ANIME") { - returnArray.addAll(map.values) - return returnArray - } - val list = PrefManager.getNullableCustomVal( - "continueAnimeList", - listOf(), - List::class.java - ) as List - if (list.isNotEmpty()) { - list.reversed().forEach { - if (map.containsKey(it)) returnArray.add(map[it]!!) - } - for (i in map) { - if (i.value !in returnArray) returnArray.add(i.value) - } - } else returnArray.addAll(map.values) - return returnArray - } - private fun continueMediaQuery(type: String, status: String): String { return """ MediaListCollection(userId: ${Anilist.userid}, type: $type, status: $status , sort: UPDATED_TIME ) { lists { entries { progress private score(format:POINT_100) status media { id idMal type isAdult status chapters episodes nextAiringEpisode {episode} meanScore isFavourite format bannerImage coverImage{large} title { english romaji userPreferred } } } } } """ } - suspend fun favMedia(anime: Boolean, id: Int? = Anilist.userid): ArrayList { + private suspend fun favMedia(anime: Boolean, id: Int? = Anilist.userid): ArrayList { var hasNextPage = true var page = 0 @@ -434,41 +408,6 @@ class AnilistQueries { return """User(id:${id}){id favourites{${if (anime) "anime" else "manga"}(page:$page){pageInfo{hasNextPage}edges{favouriteOrder node{id idMal isAdult mediaListEntry{ progress private score(format:POINT_100) status } chapters isFavourite format episodes nextAiringEpisode{episode}meanScore isFavourite format startDate{year month day} title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}}}""" } - suspend fun recommendations(): ArrayList { - val response = executeQuery("""{${recommendationQuery()}}""") - val map = mutableMapOf() - response?.data?.page?.apply { - recommendations?.onEach { - val json = it.mediaRecommendation - if (json != null) { - val m = Media(json) - m.relation = json.type?.toString() - map[m.id] = m - } - } - } - - val types = arrayOf("ANIME", "MANGA") - suspend fun repeat(type: String) { - val res = - executeQuery("""{${recommendationPlannedQuery(type)}}""") - res?.data?.mediaListCollection?.lists?.forEach { li -> - li.entries?.forEach { - val m = Media(it) - if (m.status == "RELEASING" || m.status == "FINISHED") { - m.relation = it.media?.type?.toString() - map[m.id] = m - } - } - } - } - types.forEach { repeat(it) } - - val list = ArrayList(map.values.toList()) - list.sortByDescending { it.meanScore } - return list - } - private fun recommendationQuery(): String { return """ Page(page: 1, perPage:30) { pageInfo { total currentPage hasNextPage } recommendations(sort: RATING_DESC, onList: true) { rating userRating mediaRecommendation { id idMal isAdult mediaListEntry { progress private score(format:POINT_100) status } chapters isFavourite format episodes nextAiringEpisode {episode} popularity meanScore isFavourite format title {english romaji userPreferred } type status(version: 2) bannerImage coverImage { large } } } } """ } @@ -477,9 +416,11 @@ class AnilistQueries { return """ MediaListCollection(userId: ${Anilist.userid}, type: $type, status: PLANNING${if (type == "ANIME") ", sort: MEDIA_POPULARITY_DESC" else ""} ) { lists { entries { media { id mediaListEntry { progress private score(format:POINT_100) status } idMal type isAdult popularity status(version: 2) chapters episodes nextAiringEpisode {episode} meanScore isFavourite format bannerImage coverImage{large} title { english romaji userPreferred } } } } }""" } - suspend fun initHomePage(): Map> { + suspend fun initHomePage(): Map> { + val removeList = PrefManager.getCustomVal("removeList", setOf()) + val removedMedia = ArrayList() val toShow: List = - PrefManager.getVal(PrefName.HomeLayoutShow) // anime continue, anime fav, anime planned, manga continue, manga fav, manga planned, recommendations + PrefManager.getVal(PrefName.HomeLayout) // anime continue, anime fav, anime planned, manga continue, manga fav, manga planned, recommendations var query = """{""" if (toShow.getOrNull(0) == true) query += """currentAnime: ${ continueMediaQuery( @@ -512,11 +453,11 @@ class AnilistQueries { "ANIME" ) }, recommendationPlannedQueryManga: ${recommendationPlannedQuery("MANGA")}""" + if (toShow.getOrNull(7) == true) query += "Page1:${status(1)}Page2:${status(2)}" query += """}""".trimEnd(',') val response = executeQuery(query, show = true) - Logger.log(response.toString()) - val returnMap = mutableMapOf>() + val returnMap = mutableMapOf>() fun current(type: String) { val subMap = mutableMapOf() val returnArray = arrayListOf() @@ -527,15 +468,24 @@ class AnilistQueries { current?.lists?.forEach { li -> li.entries?.reversed()?.forEach { val m = Media(it) - m.cameFromContinue = true - subMap[m.id] = m + if (m.id !in removeList) { + m.cameFromContinue = true + subMap[m.id] = m + } else { + removedMedia.add(m) + } } } + repeating?.lists?.forEach { li -> li.entries?.reversed()?.forEach { val m = Media(it) - m.cameFromContinue = true - subMap[m.id] = m + if (m.id !in removeList) { + m.cameFromContinue = true + subMap[m.id] = m + } else { + removedMedia.add(m) + } } } if (type != "Anime") { @@ -543,6 +493,7 @@ class AnilistQueries { returnMap["current$type"] = returnArray return } + @Suppress("UNCHECKED_CAST") val list = PrefManager.getNullableCustomVal( "continueAnimeList", listOf(), @@ -568,10 +519,15 @@ class AnilistQueries { current?.lists?.forEach { li -> li.entries?.reversed()?.forEach { val m = Media(it) - m.cameFromContinue = true - subMap[m.id] = m + if (m.id !in removeList) { + m.cameFromContinue = true + subMap[m.id] = m + } else { + removedMedia.add(m) + } } } + @Suppress("UNCHECKED_CAST") val list = PrefManager.getNullableCustomVal( "continueAnimeList", listOf(), @@ -595,7 +551,12 @@ class AnilistQueries { val returnArray = arrayListOf() apiMediaList?.edges?.forEach { it.node?.let { i -> - returnArray.add(Media(i).apply { isFav = true }) + val m = Media(i).apply { isFav = true } + if (m.id !in removeList) { + returnArray.add(m) + } else { + removedMedia.add(m) + } } } returnMap["favorite$type"] = returnArray @@ -657,6 +618,47 @@ class AnilistQueries { list.sortByDescending { it.meanScore } returnMap["recommendations"] = list } + if (toShow.getOrNull(7) == true) { + val list = mutableListOf() + val threeDaysAgo = Calendar.getInstance().apply { + add(Calendar.DAY_OF_MONTH, -3) + }.timeInMillis + if (response?.data?.page1 != null && response.data.page2 != null) { + val activities = listOf( + response.data.page1.activities, + response.data.page2.activities + ).asSequence().flatten() + .filter { it.typename != "MessageActivity" } + .filter { if (Anilist.adult) true else it.media?.isAdult == false } + .filter { it.createdAt * 1000L > threeDaysAgo }.toList() + .sortedByDescending { it.createdAt } + val anilistActivities = mutableListOf() + val groupedActivities = activities.groupBy { it.userId } + + groupedActivities.forEach { (_, userActivities) -> + val user = userActivities.firstOrNull()?.user + if (user != null) { + val userToAdd = User( + user.id, + user.name ?: "", + user.avatar?.medium, + user.bannerImage, + activity = userActivities.sortedBy { it.createdAt }.toList() + ) + if (user.id == Anilist.userid) { + anilistActivities.add(0, userToAdd) + } else { + list.add(userToAdd) + } + } + } + + + list.addAll(0, anilistActivities) + returnMap["status"] = ArrayList(list) + } + returnMap["hidden"] = removedMedia.distinctBy { it.id } as ArrayList + } return returnMap } @@ -733,7 +735,7 @@ class AnilistQueries { } sorted["All"] = all - val listSort: String = if (anime) PrefManager.getVal(PrefName.AnimeListSortOrder) + val listSort: String? = if (anime) PrefManager.getVal(PrefName.AnimeListSortOrder) else PrefManager.getVal(PrefName.MangaListSortOrder) val sort = listSort ?: sortOrder ?: options?.rowOrder for (i in sorted.keys) { @@ -881,18 +883,23 @@ class AnilistQueries { sort: String? = null, genres: MutableList? = null, tags: MutableList? = null, + status: String? = null, + source: String? = null, format: String? = null, + countryOfOrigin: String? = null, isAdult: Boolean = false, onList: Boolean? = null, excludedGenres: MutableList? = null, excludedTags: MutableList? = null, + startYear: Int? = null, seasonYear: Int? = null, season: String? = null, id: Int? = null, hd: Boolean = false, + adultOnly: Boolean = false ): SearchResults? { val query = """ -query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: Boolean = false, ${"$"}search: String, ${"$"}format: [MediaFormat], ${"$"}status: MediaStatus, ${"$"}countryOfOrigin: CountryCode, ${"$"}source: MediaSource, ${"$"}season: MediaSeason, ${"$"}seasonYear: Int, ${"$"}year: String, ${"$"}onList: Boolean, ${"$"}yearLesser: FuzzyDateInt, ${"$"}yearGreater: FuzzyDateInt, ${"$"}episodeLesser: Int, ${"$"}episodeGreater: Int, ${"$"}durationLesser: Int, ${"$"}durationGreater: Int, ${"$"}chapterLesser: Int, ${"$"}chapterGreater: Int, ${"$"}volumeLesser: Int, ${"$"}volumeGreater: Int, ${"$"}licensedBy: [String], ${"$"}isLicensed: Boolean, ${"$"}genres: [String], ${"$"}excludedGenres: [String], ${"$"}tags: [String], ${"$"}excludedTags: [String], ${"$"}minimumTagRank: Int, ${"$"}sort: [MediaSort] = [POPULARITY_DESC, SCORE_DESC]) { +query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: Boolean = false, ${"$"}search: String, ${"$"}format: [MediaFormat], ${"$"}status: MediaStatus, ${"$"}countryOfOrigin: CountryCode, ${"$"}source: MediaSource, ${"$"}season: MediaSeason, ${"$"}seasonYear: Int, ${"$"}year: String, ${"$"}onList: Boolean, ${"$"}yearLesser: FuzzyDateInt, ${"$"}yearGreater: FuzzyDateInt, ${"$"}episodeLesser: Int, ${"$"}episodeGreater: Int, ${"$"}durationLesser: Int, ${"$"}durationGreater: Int, ${"$"}chapterLesser: Int, ${"$"}chapterGreater: Int, ${"$"}volumeLesser: Int, ${"$"}volumeGreater: Int, ${"$"}licensedBy: [String], ${"$"}isLicensed: Boolean, ${"$"}genres: [String], ${"$"}excludedGenres: [String], ${"$"}tags: [String], ${"$"}excludedTags: [String], ${"$"}minimumTagRank: Int, ${"$"}sort: [MediaSort] = [POPULARITY_DESC, SCORE_DESC, START_DATE_DESC]) { Page(page: ${"$"}page, perPage: ${perPage ?: 50}) { pageInfo { total @@ -937,14 +944,19 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: } """.replace("\n", " ").replace(""" """, "") val variables = """{"type":"$type","isAdult":$isAdult + ${if (adultOnly) ""","isAdult":true""" else ""} ${if (onList != null) ""","onList":$onList""" else ""} ${if (page != null) ""","page":"$page"""" else ""} ${if (id != null) ""","id":"$id"""" else ""} - ${if (seasonYear != null) ""","seasonYear":"$seasonYear"""" else ""} + ${if (type == "ANIME" && seasonYear != null) ""","seasonYear":"$seasonYear"""" else ""} + ${if (type == "MANGA" && startYear != null) ""","yearGreater":${startYear}0000,"yearLesser":${startYear + 1}0000""" else ""} ${if (season != null) ""","season":"$season"""" else ""} ${if (search != null) ""","search":"$search"""" else ""} + ${if (source != null) ""","source":"$source"""" else ""} ${if (sort != null) ""","sort":"$sort"""" else ""} + ${if (status != null) ""","status":"$status"""" else ""} ${if (format != null) ""","format":"${format.replace(" ", "_")}"""" else ""} + ${if (countryOfOrigin != null) ""","countryOfOrigin":"$countryOfOrigin"""" else ""} ${if (genres?.isNotEmpty() == true) ""","genres":[${genres.joinToString { "\"$it\"" }}]""" else ""} ${ if (excludedGenres?.isNotEmpty() == true) @@ -976,7 +988,6 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: else "" } }""".replace("\n", " ").replace(""" """, "") - val response = executeQuery(query, variables, true)?.data?.page if (response?.media != null) { val responseArray = arrayListOf() @@ -1008,7 +1019,11 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: excludedGenres = excludedGenres, tags = tags, excludedTags = excludedTags, + status = status, + source = source, format = format, + countryOfOrigin = countryOfOrigin, + startYear = startYear, seasonYear = seasonYear, season = season, results = responseArray, @@ -1019,11 +1034,157 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult: return null } + private val onListAnime = + (if (PrefManager.getVal(PrefName.IncludeAnimeList)) "" else "onList:false").replace( + "\"", + "" + ) + private val isAdult = + (if (PrefManager.getVal(PrefName.AdultOnly)) "isAdult:true" else "").replace("\"", "") + + private fun recentAnimeUpdates(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}airingSchedules(airingAt_greater:0 airingAt_lesser:${System.currentTimeMillis() / 1000 - 10000} sort:TIME_DESC){episode airingAt media{id idMal status chapters episodes nextAiringEpisode{episode} isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large} title{english romaji userPreferred} mediaListEntry{progress private score(format:POINT_100) status}}}}""" + } + + private fun trendingMovies(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: ANIME, format: MOVIE, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun topRatedAnime(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun mostFavAnime(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + suspend fun loadAnimeList(): Map> { + val list = mutableMapOf>() + fun query(): String { + return """{ + recentUpdates:${recentAnimeUpdates(1)} + recentUpdates2:${recentAnimeUpdates(2)} + trendingMovies:${trendingMovies(1)} + trendingMovies2:${trendingMovies(2)} + topRated:${topRatedAnime(1)} + topRated2:${topRatedAnime(2)} + mostFav:${mostFavAnime(1)} + mostFav2:${mostFavAnime(2)} + }""".trimIndent() + } + executeQuery(query(), force = true)?.data?.apply { + val listOnly: Boolean = PrefManager.getVal(PrefName.RecentlyListOnly) + val adultOnly: Boolean = PrefManager.getVal(PrefName.AdultOnly) + val idArr = mutableListOf() + list["recentUpdates"] = recentUpdates?.airingSchedules?.mapNotNull { i -> + i.media?.let { + if (!idArr.contains(it.id)) + if (!listOnly && it.countryOfOrigin == "JP" && Anilist.adult && adultOnly && it.isAdult == true) { + idArr.add(it.id) + Media(it) + } else if (!listOnly && !adultOnly && (it.countryOfOrigin == "JP" && it.isAdult == false)) { + idArr.add(it.id) + Media(it) + } else if ((listOnly && it.mediaListEntry != null)) { + idArr.add(it.id) + Media(it) + } else null + else null + } + }?.toCollection(ArrayList()) ?: arrayListOf() + + list["trendingMovies"] = trendingMovies?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["topRated"] = topRated?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["mostFav"] = mostFav?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + + list["recentUpdates"]?.addAll(recentUpdates2?.airingSchedules?.mapNotNull { i -> + i.media?.let { + if (!idArr.contains(it.id)) + if (!listOnly && it.countryOfOrigin == "JP" && Anilist.adult && adultOnly && it.isAdult == true) { + idArr.add(it.id) + Media(it) + } else if (!listOnly && !adultOnly && (it.countryOfOrigin == "JP" && it.isAdult == false)) { + idArr.add(it.id) + Media(it) + } else if ((listOnly && it.mediaListEntry != null)) { + idArr.add(it.id) + Media(it) + } else null + else null + } + }?.toCollection(ArrayList()) ?: arrayListOf()) + list["trendingMovies"]?.addAll(trendingMovies2?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf()) + list["topRated"]?.addAll(topRated2?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf()) + list["mostFav"]?.addAll(mostFav2?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf()) + } + return list + } + + private val onListManga = + (if (PrefManager.getVal(PrefName.IncludeMangaList)) "" else "onList:false").replace( + "\"", + "" + ) + + private fun trendingManga(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA,countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun trendingManhwa(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, countryOfOrigin:KR, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun trendingNovel(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, format: NOVEL, countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun topRatedManga(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + private fun mostFavManga(page: Int): String { + return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" + } + + suspend fun loadMangaList(): Map> { + val list = mutableMapOf>() + fun query(): String { + return """{ + trendingManga:${trendingManga(1)} + trendingManga2:${trendingManga(2)} + trendingManhwa:${trendingManhwa(1)} + trendingManhwa2:${trendingManhwa(2)} + trendingNovel:${trendingNovel(1)} + trendingNovel2:${trendingNovel(2)} + topRated:${topRatedManga(1)} + topRated2:${topRatedManga(2)} + mostFav:${mostFavManga(1)} + mostFav2:${mostFavManga(2)} + }""".trimIndent() + } + + executeQuery(query(), force = true)?.data?.apply { + list["trendingManga"] = trendingManga?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["trendingManhwa"] = trendingManhwa?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["trendingNovel"] = trendingNovel?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["topRated"] = topRated?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + list["mostFav"] = mostFav?.media?.map { Media(it) }?.toCollection(ArrayList()) ?: arrayListOf() + + list["trendingManga"]?.addAll(trendingManga2?.media?.map { Media(it) }?.toList() ?: arrayListOf()) + list["trendingManhwa"]?.addAll(trendingManhwa2?.media?.map { Media(it) }?.toList() ?: arrayListOf()) + list["trendingNovel"]?.addAll(trendingNovel2?.media?.map { Media(it) }?.toList() ?: arrayListOf()) + list["topRated"]?.addAll(topRated2?.media?.map { Media(it) }?.toList() ?: arrayListOf()) + list["mostFav"]?.addAll(mostFav2?.media?.map { Media(it) }?.toList() ?: arrayListOf()) + } + + + return list + } + suspend fun recentlyUpdated( - smaller: Boolean = true, greater: Long = 0, lesser: Long = System.currentTimeMillis() / 1000 - 10000 - ): MutableList? { + ): MutableList { suspend fun execute(page: Int = 1): Page? { val query = """{ Page(page:$page,perPage:50) { @@ -1070,41 +1231,26 @@ Page(page:$page,perPage:50) { }""".replace("\n", " ").replace(""" """, "") return executeQuery(query, force = true)?.data?.page } - if (smaller) { - val response = execute()?.airingSchedules ?: return null - val idArr = mutableListOf() - val listOnly: Boolean = PrefManager.getVal(PrefName.RecentlyListOnly) - return response.mapNotNull { i -> - i.media?.let { - if (!idArr.contains(it.id)) - if (!listOnly && (it.countryOfOrigin == "JP" && (if (!Anilist.adult) it.isAdult == false else true)) || (listOnly && it.mediaListEntry != null)) { - idArr.add(it.id) - Media(it) - } else null - else null + + var i = 1 + val list = mutableListOf() + var res: Page? = null + suspend fun next() { + res = execute(i) + list.addAll(res?.airingSchedules?.mapNotNull { j -> + j.media?.let { + if (it.countryOfOrigin == "JP" && (if (!Anilist.adult) it.isAdult == false else true)) { + Media(it).apply { relation = "${j.episode},${j.airingAt}" } + } else null } - }.toMutableList() - } else { - var i = 1 - val list = mutableListOf() - var res: Page? = null - suspend fun next() { - res = execute(i) - list.addAll(res?.airingSchedules?.mapNotNull { j -> - j.media?.let { - if (it.countryOfOrigin == "JP" && (if (!Anilist.adult) it.isAdult == false else true)) { - Media(it).apply { relation = "${j.episode},${j.airingAt}" } - } else null - } - } ?: listOf()) - } - next() - while (res?.pageInfo?.hasNextPage == true) { - next() - i++ - } - return list.reversed().toMutableList() + } ?: listOf()) } + next() + while (res?.pageInfo?.hasNextPage == true) { + next() + i++ + } + return list.reversed().toMutableList() } suspend fun getCharacterDetails(character: Character): Character { @@ -1290,19 +1436,39 @@ Page(page:$page,perPage:50) { } } } + characters(page: $page,sort:FAVOURITES_DESC) { + pageInfo{ + hasNextPage + } + nodes{ + id + name { + first + middle + last + full + native + userPreferred + } + image { + large + medium + } + } + } } }""".replace("\n", " ").replace(""" """, "") var hasNextPage = true val yearMedia = mutableMapOf>() var page = 0 - + val characters = arrayListOf() while (hasNextPage) { page++ - hasNextPage = executeQuery( - query(page), - force = true - )?.data?.author?.staffMedia?.let { + val query = executeQuery( + query(page), force = true + )?.data?.author + hasNextPage = query?.staffMedia?.let { it.edges?.forEach { i -> i.node?.apply { val status = status.toString() @@ -1317,6 +1483,20 @@ Page(page:$page,perPage:50) { } it.pageInfo?.hasNextPage == true } ?: false + query?.characters?.let { + it.nodes?.forEach { i -> + characters.add( + Character( + i.id, + i.name?.userPreferred, + i.image?.large, + i.image?.medium, + "", + false + ) + ) + } + } } if (yearMedia.contains("CANCELLED")) { @@ -1324,10 +1504,18 @@ Page(page:$page,perPage:50) { yearMedia.remove("CANCELLED") yearMedia["CANCELLED"] = a } + author.character = characters author.yearMedia = yearMedia return author } + suspend fun getReviews(mediaId: Int, page: Int = 1, sort: String = "SCORE_DESC"): Query.ReviewsResponse? { + return executeQuery( + """{Page(page:$page,perPage:10){pageInfo{currentPage,hasNextPage,total}reviews(mediaId:$mediaId,sort:$sort){id,mediaId,mediaType,summary,body(asHtml:true)rating,ratingAmount,userRating,score,private,siteUrl,createdAt,updatedAt,user{id,name,bannerImage avatar{medium,large}}}}}""", + force = true + ) + } + suspend fun toggleFollow(id: Int): Query.ToggleFollow? { return executeQuery( """mutation{ToggleFollow(userId:$id){id, isFollowing, isFollower}}""" @@ -1352,7 +1540,7 @@ Page(page:$page,perPage:50) { return getUserProfile(id) } - suspend fun getUserId(username: String): Int? { + private suspend fun getUserId(username: String): Int? { return executeQuery( """{User(name:"$username"){id}}""", force = true @@ -1367,8 +1555,8 @@ Page(page:$page,perPage:50) { ) } - private fun userFavMediaQuery(anime: Boolean, page: Int, id: Int): String { - return """User(id:${id}){id favourites{${if (anime) "anime" else "manga"}(page:$page){pageInfo{hasNextPage}edges{favouriteOrder node{id idMal isAdult mediaListEntry{ progress private score(format:POINT_100) status } chapters isFavourite format episodes nextAiringEpisode{episode}meanScore isFavourite format startDate{year month day} title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}}}""" + private fun userFavMediaQuery(anime: Boolean, id: Int): String { + return """User(id:${id}){id favourites{${if (anime) "anime" else "manga"}(page:1){pageInfo{hasNextPage}edges{favouriteOrder node{id idMal isAdult mediaListEntry{ progress private score(format:POINT_100) status } chapters isFavourite format episodes nextAiringEpisode{episode}meanScore isFavourite format startDate{year month day} title{english romaji userPreferred}type status(version:2)bannerImage coverImage{large}}}}}}""" } suspend fun userFollowing(id: Int): Query.Following? { @@ -1388,19 +1576,18 @@ Page(page:$page,perPage:50) { suspend fun initProfilePage(id: Int): Query.ProfilePageMedia? { return executeQuery( """{ - favoriteAnime:${userFavMediaQuery(true, 1, id)} - favoriteManga:${userFavMediaQuery(false, 1, id)} - animeMediaList:${bannerImageQuery("ANIME", id)} - mangaMediaList:${bannerImageQuery("MANGA", id)} + favoriteAnime:${userFavMediaQuery(true, id)} + favoriteManga:${userFavMediaQuery(false, id)} }""".trimIndent(), force = true ) } - private fun bannerImageQuery(type: String, id: Int?): String { - return """MediaListCollection(userId: ${id}, type: $type, chunk:1,perChunk:25, sort: [SCORE_DESC,UPDATED_TIME_DESC]) { lists { entries{ media { id bannerImage } } } }""" - } - suspend fun getNotifications(id: Int, page: Int = 1, resetNotification: Boolean = true): NotificationResponse? { + suspend fun getNotifications( + id: Int, + page: Int = 1, + resetNotification: Boolean = true + ): NotificationResponse? { val reset = if (resetNotification) "true" else "false" val res = executeQuery( """{User(id:$id){unreadNotificationCount}Page(page:$page,perPage:$ITEMS_PER_PAGE){pageInfo{currentPage,hasNextPage}notifications(resetNotificationCount:$reset){__typename...on AiringNotification{id,type,animeId,episode,contexts,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}},}...on FollowingNotification{id,userId,type,context,createdAt,user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMessageNotification{id,userId,type,activityId,context,createdAt,message{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMentionNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplySubscribedNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentMentionNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentReplyNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentSubscribedNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentLikeNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadLikeNotification{id,userId,type,threadId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on RelatedMediaAdditionNotification{id,type,context,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDataChangeNotification{id,type,mediaId,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaMergeNotification{id,type,mediaId,deletedMediaTitles,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDeletionNotification{id,type,deletedMediaTitle,context,reason,createdAt,}}}}""", @@ -1415,25 +1602,72 @@ Page(page:$page,perPage:50) { return res } - suspend fun getFeed(userId: Int?, global: Boolean = false, page: Int = 1, activityId: Int? = null): FeedResponse? { + suspend fun getFeed( + userId: Int?, + global: Boolean = false, + page: Int = 1, + activityId: Int? = null + ): FeedResponse? { val filter = if (activityId != null) "id:$activityId," else if (userId != null) "userId:$userId," else if (global) "isFollowing:false,hasRepliesOrTypeText:true," - else "isFollowing:true,type_not:MESSAGE," + else "isFollowing:true," return executeQuery( - """{Page(page:$page,perPage:$ITEMS_PER_PAGE){activities(${filter}sort:ID_DESC){__typename ... on TextActivity{id userId type replyCount text(asHtml:true)siteUrl isLocked isSubscribed likeCount isLiked isPinned createdAt user{id name bannerImage avatar{medium large}}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}... on ListActivity{id userId type replyCount status progress siteUrl isLocked isSubscribed likeCount isLiked isPinned createdAt user{id name bannerImage avatar{medium large}}media{id title{english romaji native userPreferred}bannerImage coverImage{medium large}}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}... on MessageActivity{id recipientId messengerId type replyCount likeCount message(asHtml:true)isLocked isSubscribed isLiked isPrivate siteUrl createdAt recipient{id name bannerImage avatar{medium large}}messenger{id name bannerImage avatar{medium large}}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}}}}""", + """{Page(page:$page,perPage:$ITEMS_PER_PAGE){activities(${filter}sort:ID_DESC){__typename ... on TextActivity{id userId type replyCount text(asHtml:true)siteUrl isLocked isSubscribed likeCount isLiked isPinned createdAt user{id name bannerImage avatar{medium large}}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}... on ListActivity{id userId type replyCount status progress siteUrl isLocked isSubscribed likeCount isLiked isPinned createdAt user{id name bannerImage avatar{medium large}}media{id title{english romaji native userPreferred}bannerImage coverImage{medium large}isAdult}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}... on MessageActivity{id recipientId messengerId type replyCount likeCount message(asHtml:true)isLocked isSubscribed isLiked isPrivate siteUrl createdAt recipient{id name bannerImage avatar{medium large}}messenger{id name bannerImage avatar{medium large}}replies{id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}likes{id name bannerImage avatar{medium large}}}}}}""", force = true ) } - suspend fun isUserFav(favType: AnilistMutations.FavType, id: Int): Boolean { //anilist isFavourite is broken, so we need to check it manually - val res = getUserProfile(Anilist.userid?: return false) + suspend fun getReplies( + activityId: Int, + page: Int = 1 + ) : ReplyResponse? { + val query = """{Page(page:$page,perPage:50){activityReplies(activityId:$activityId){id userId activityId text(asHtml:true)likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}}}""" + return executeQuery(query, force = true) + } + + private fun status(page: Int = 1): String { + return """Page(page:$page,perPage:50){activities(isFollowing: true,sort:ID_DESC){__typename ... on TextActivity{id userId type replyCount text(asHtml:true)siteUrl isLocked isSubscribed replyCount likeCount isLiked createdAt user{id name bannerImage avatar{medium large}}likes{id name bannerImage avatar{medium large}}}... on ListActivity{id userId type replyCount status progress siteUrl isLocked isSubscribed replyCount likeCount isLiked isPinned createdAt user{id name bannerImage avatar{medium large}}media{id isAdult title{english romaji native userPreferred}bannerImage coverImage{extraLarge medium large}}likes{id name bannerImage avatar{medium large}}}... on MessageActivity{id type createdAt}}}""" + } + + suspend fun getUpcomingAnime(id: String): List { + val res = executeQuery( + """{MediaListCollection(userId:$id,type:ANIME){lists{name entries{media{id,isFavourite,title{userPreferred,romaji}coverImage{medium}nextAiringEpisode{timeUntilAiring}}}}}}""", + force = true + ) + val list = mutableListOf() + res?.data?.mediaListCollection?.lists?.forEach { listEntry -> + listEntry.entries?.forEach { entry -> + entry.media?.nextAiringEpisode?.timeUntilAiring?.let { + list.add(Media(entry.media!!)) + } + } + } + return list.sortedBy { it.timeUntilAiring } + .distinctBy { it.id } + .filter { it.timeUntilAiring != null } + } + + suspend fun isUserFav( + favType: AnilistMutations.FavType, + id: Int + ): Boolean { //anilist isFavourite is broken, so we need to check it manually + val res = getUserProfile(Anilist.userid ?: return false) return when (favType) { - AnilistMutations.FavType.ANIME -> res?.data?.user?.favourites?.anime?.nodes?.any { it.id == id } ?: false - AnilistMutations.FavType.MANGA -> res?.data?.user?.favourites?.manga?.nodes?.any { it.id == id } ?: false - AnilistMutations.FavType.CHARACTER -> res?.data?.user?.favourites?.characters?.nodes?.any { it.id == id } ?: false - AnilistMutations.FavType.STAFF -> res?.data?.user?.favourites?.staff?.nodes?.any { it.id == id } ?: false - AnilistMutations.FavType.STUDIO -> res?.data?.user?.favourites?.studios?.nodes?.any { it.id == id } ?: false + AnilistMutations.FavType.ANIME -> res?.data?.user?.favourites?.anime?.nodes?.any { it.id == id } + ?: false + + AnilistMutations.FavType.MANGA -> res?.data?.user?.favourites?.manga?.nodes?.any { it.id == id } + ?: false + + AnilistMutations.FavType.CHARACTER -> res?.data?.user?.favourites?.characters?.nodes?.any { it.id == id } + ?: false + + AnilistMutations.FavType.STAFF -> res?.data?.user?.favourites?.staff?.nodes?.any { it.id == id } + ?: false + + AnilistMutations.FavType.STUDIO -> res?.data?.user?.favourites?.studios?.nodes?.any { it.id == id } + ?: false } } diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistViewModel.kt b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistViewModel.kt index 5eb28a79..6cda8e7a 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/AnilistViewModel.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/AnilistViewModel.kt @@ -5,46 +5,34 @@ import androidx.fragment.app.FragmentActivity import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel +import androidx.lifecycle.lifecycleScope import ani.dantotsu.BuildConfig import ani.dantotsu.R import ani.dantotsu.connections.discord.Discord import ani.dantotsu.connections.mal.MAL import ani.dantotsu.media.Media import ani.dantotsu.others.AppUpdater +import ani.dantotsu.profile.User import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.tryWithSuspend -import ani.dantotsu.util.Logger -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext suspend fun getUserId(context: Context, block: () -> Unit) { - CoroutineScope(Dispatchers.IO).launch { - val token = PrefManager.getVal(PrefName.DiscordToken, null as String?) - val userid = PrefManager.getVal(PrefName.DiscordId, null as String?) - if (userid == null && token != null) { - /*if (!Discord.getUserData()) - snackString(context.getString(R.string.error_loading_discord_user_data))*/ - //TODO: Discord.getUserData() - } - } - - val anilist = if (Anilist.userid == null && Anilist.token != null) { + if (!Anilist.initialized) { if (Anilist.query.getUserData()) { tryWithSuspend { if (MAL.token != null && !MAL.query.getUserData()) snackString(context.getString(R.string.error_loading_mal_user_data)) } - true } else { snackString(context.getString(R.string.error_loading_anilist_user_data)) - false } - } else true - - if (anilist) block.invoke() + } + block.invoke() } class AnilistHomeViewModel : ViewModel() { @@ -58,66 +46,75 @@ class AnilistHomeViewModel : ViewModel() { MutableLiveData>(null) fun getAnimeContinue(): LiveData> = animeContinue - suspend fun setAnimeContinue() = animeContinue.postValue(Anilist.query.continueMedia("ANIME")) private val animeFav: MutableLiveData> = MutableLiveData>(null) fun getAnimeFav(): LiveData> = animeFav - suspend fun setAnimeFav() = animeFav.postValue(Anilist.query.favMedia(true)) private val animePlanned: MutableLiveData> = MutableLiveData>(null) fun getAnimePlanned(): LiveData> = animePlanned - suspend fun setAnimePlanned() = - animePlanned.postValue(Anilist.query.continueMedia("ANIME", true)) private val mangaContinue: MutableLiveData> = MutableLiveData>(null) fun getMangaContinue(): LiveData> = mangaContinue - suspend fun setMangaContinue() = mangaContinue.postValue(Anilist.query.continueMedia("MANGA")) private val mangaFav: MutableLiveData> = MutableLiveData>(null) fun getMangaFav(): LiveData> = mangaFav - suspend fun setMangaFav() = mangaFav.postValue(Anilist.query.favMedia(false)) private val mangaPlanned: MutableLiveData> = MutableLiveData>(null) fun getMangaPlanned(): LiveData> = mangaPlanned - suspend fun setMangaPlanned() = - mangaPlanned.postValue(Anilist.query.continueMedia("MANGA", true)) private val recommendation: MutableLiveData> = MutableLiveData>(null) fun getRecommendation(): LiveData> = recommendation - suspend fun setRecommendation() = recommendation.postValue(Anilist.query.recommendations()) + private val userStatus: MutableLiveData> = + MutableLiveData>(null) + + fun getUserStatus(): LiveData> = userStatus + + private val hidden: MutableLiveData> = + MutableLiveData>(null) + + fun getHidden(): LiveData> = hidden + + @Suppress("UNCHECKED_CAST") suspend fun initHomePage() { val res = Anilist.query.initHomePage() - Logger.log("AnilistHomeViewModel : res=$res") - res["currentAnime"]?.let { animeContinue.postValue(it) } - res["favoriteAnime"]?.let { animeFav.postValue(it) } - res["plannedAnime"]?.let { animePlanned.postValue(it) } - res["currentManga"]?.let { mangaContinue.postValue(it) } - res["favoriteManga"]?.let { mangaFav.postValue(it) } - res["plannedManga"]?.let { mangaPlanned.postValue(it) } - res["recommendations"]?.let { recommendation.postValue(it) } + res["currentAnime"]?.let { animeContinue.postValue(it as ArrayList?) } + res["favoriteAnime"]?.let { animeFav.postValue(it as ArrayList?) } + res["plannedAnime"]?.let { animePlanned.postValue(it as ArrayList?) } + res["currentManga"]?.let { mangaContinue.postValue(it as ArrayList?) } + res["favoriteManga"]?.let { mangaFav.postValue(it as ArrayList?) } + res["plannedManga"]?.let { mangaPlanned.postValue(it as ArrayList?) } + res["recommendations"]?.let { recommendation.postValue(it as ArrayList?) } + res["hidden"]?.let { hidden.postValue(it as ArrayList?) } + res["status"]?.let { userStatus.postValue(it as ArrayList?) } } suspend fun loadMain(context: FragmentActivity) { Anilist.getSavedToken() - MAL.getSavedToken(context) - Discord.getSavedToken(context) + MAL.getSavedToken() + Discord.getSavedToken() if (!BuildConfig.FLAVOR.contains("fdroid")) { - if (PrefManager.getVal(PrefName.CheckUpdate)) AppUpdater.check(context) + if (PrefManager.getVal(PrefName.CheckUpdate)) + context.lifecycleScope.launch(Dispatchers.IO) { + AppUpdater.check(context, false) + } + } + val ret = Anilist.query.getGenresAndTags() + withContext(Dispatchers.Main) { + genres.value = ret } - genres.postValue(Anilist.query.getGenresAndTags()) } val empty = MutableLiveData(null) @@ -144,22 +141,19 @@ class AnilistAnimeViewModel : ViewModel() { sort = Anilist.sortBy[2], season = season, seasonYear = year, - hd = true + hd = true, + adultOnly = PrefManager.getVal(PrefName.AdultOnly) )?.results ) } - private val updated: MutableLiveData> = - MutableLiveData>(null) - - fun getUpdated(): LiveData> = updated - suspend fun loadUpdated() = updated.postValue(Anilist.query.recentlyUpdated()) private val animePopular = MutableLiveData(null) + fun getPopular(): LiveData = animePopular suspend fun loadPopular( type: String, - search_val: String? = null, + searchVal: String? = null, genres: ArrayList? = null, sort: String = Anilist.sortBy[1], onList: Boolean = true, @@ -167,10 +161,11 @@ class AnilistAnimeViewModel : ViewModel() { animePopular.postValue( Anilist.query.search( type, - search = search_val, + search = searchVal, onList = if (onList) null else false, sort = sort, - genres = genres + genres = genres, + adultOnly = PrefManager.getVal(PrefName.AdultOnly) ) ) } @@ -185,13 +180,43 @@ class AnilistAnimeViewModel : ViewModel() { r.sort, r.genres, r.tags, + r.status, + r.source, r.format, + r.countryOfOrigin, r.isAdult, - r.onList + r.onList, + adultOnly = PrefManager.getVal(PrefName.AdultOnly), ) ) var loaded: Boolean = false + private val updated: MutableLiveData> = + MutableLiveData>(null) + + fun getUpdated(): LiveData> = updated + + private val popularMovies: MutableLiveData> = + MutableLiveData>(null) + + fun getMovies(): LiveData> = popularMovies + + private val topRatedAnime: MutableLiveData> = + MutableLiveData>(null) + + fun getTopRated(): LiveData> = topRatedAnime + + private val mostFavAnime: MutableLiveData> = + MutableLiveData>(null) + + fun getMostFav(): LiveData> = mostFavAnime + suspend fun loadAll() { + val list = Anilist.query.loadAnimeList() + updated.postValue(list["recentUpdates"]) + popularMovies.postValue(list["trendingMovies"]) + topRatedAnime.postValue(list["topRated"]) + mostFavAnime.postValue(list["mostFav"]) + } } class AnilistMangaViewModel : ViewModel() { @@ -209,29 +234,17 @@ class AnilistMangaViewModel : ViewModel() { type, perPage = 10, sort = Anilist.sortBy[2], - hd = true + hd = true, + adultOnly = PrefManager.getVal(PrefName.AdultOnly) )?.results ) - private val updated: MutableLiveData> = - MutableLiveData>(null) - - fun getTrendingNovel(): LiveData> = updated - suspend fun loadTrendingNovel() = - updated.postValue( - Anilist.query.search( - type, - perPage = 10, - sort = Anilist.sortBy[2], - format = "NOVEL" - )?.results - ) private val mangaPopular = MutableLiveData(null) fun getPopular(): LiveData = mangaPopular suspend fun loadPopular( type: String, - search_val: String? = null, + searchVal: String? = null, genres: ArrayList? = null, sort: String = Anilist.sortBy[1], onList: Boolean = true, @@ -239,10 +252,11 @@ class AnilistMangaViewModel : ViewModel() { mangaPopular.postValue( Anilist.query.search( type, - search = search_val, + search = searchVal, onList = if (onList) null else false, sort = sort, - genres = genres + genres = genres, + adultOnly = PrefManager.getVal(PrefName.AdultOnly) ) ) } @@ -257,17 +271,55 @@ class AnilistMangaViewModel : ViewModel() { r.sort, r.genres, r.tags, + r.status, + r.source, r.format, + r.countryOfOrigin, r.isAdult, r.onList, r.excludedGenres, r.excludedTags, + r.startYear, r.seasonYear, - r.season + r.season, + adultOnly = PrefManager.getVal(PrefName.AdultOnly) ) ) var loaded: Boolean = false + + private val popularManga: MutableLiveData> = + MutableLiveData>(null) + + fun getPopularManga(): LiveData> = popularManga + + private val popularManhwa: MutableLiveData> = + MutableLiveData>(null) + + fun getPopularManhwa(): LiveData> = popularManhwa + + private val popularNovel: MutableLiveData> = + MutableLiveData>(null) + + fun getPopularNovel(): LiveData> = popularNovel + + private val topRatedManga: MutableLiveData> = + MutableLiveData>(null) + + fun getTopRated(): LiveData> = topRatedManga + + private val mostFavManga: MutableLiveData> = + MutableLiveData>(null) + + fun getMostFav(): LiveData> = mostFavManga + suspend fun loadAll() { + val list = Anilist.query.loadMangaList() + popularManga.postValue(list["trendingManga"]) + popularManhwa.postValue(list["trendingManhwa"]) + popularNovel.postValue(list["trendingNovel"]) + topRatedManga.postValue(list["topRated"]) + mostFavManga.postValue(list["mostFav"]) + } } class AnilistSearch : ViewModel() { @@ -286,13 +338,17 @@ class AnilistSearch : ViewModel() { r.sort, r.genres, r.tags, + r.status, + r.source, r.format, + r.countryOfOrigin, r.isAdult, r.onList, r.excludedGenres, r.excludedTags, + r.startYear, r.seasonYear, - r.season + r.season, ) ) @@ -305,11 +361,15 @@ class AnilistSearch : ViewModel() { r.sort, r.genres, r.tags, + r.status, + r.source, r.format, + r.countryOfOrigin, r.isAdult, r.onList, r.excludedGenres, r.excludedTags, + r.startYear, r.seasonYear, r.season ) @@ -347,11 +407,6 @@ class ProfileViewModel : ViewModel() { fun getAnimeFav(): LiveData> = animeFav - private val listImages: MutableLiveData> = - MutableLiveData>(arrayListOf()) - - fun getListImages(): LiveData> = listImages - suspend fun setData(id: Int) { val res = Anilist.query.initProfilePage(id) val mangaList = res?.data?.favoriteManga?.favourites?.manga?.edges?.mapNotNull { @@ -367,30 +422,11 @@ class ProfileViewModel : ViewModel() { } animeFav.postValue(ArrayList(animeList ?: arrayListOf())) - val bannerImages = arrayListOf(null, null) - val animeRandom = res?.data?.animeMediaList?.lists?.mapNotNull { - it.entries?.mapNotNull { entry -> - val imageUrl = entry.media?.bannerImage - if (imageUrl != null && imageUrl != "null") imageUrl - else null - } - }?.flatten()?.randomOrNull() - bannerImages[0] = animeRandom - val mangaRandom = res?.data?.mangaMediaList?.lists?.mapNotNull { - it.entries?.mapNotNull { entry -> - val imageUrl = entry.media?.bannerImage - if (imageUrl != null && imageUrl != "null") imageUrl - else null - } - }?.flatten()?.randomOrNull() - bannerImages[1] = mangaRandom - listImages.postValue(bannerImages) - } fun refresh() { mangaFav.postValue(mangaFav.value) animeFav.postValue(animeFav.value) - listImages.postValue(listImages.value) + } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/Login.kt b/app/src/main/java/ani/dantotsu/connections/anilist/Login.kt index 0ec87efb..c9e148a2 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/Login.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/Login.kt @@ -4,7 +4,6 @@ import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import ani.dantotsu.logError -import ani.dantotsu.util.Logger import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.startMainActivity diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/SearchResults.kt b/app/src/main/java/ani/dantotsu/connections/anilist/SearchResults.kt index 32bc1757..6c2ca504 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/SearchResults.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/SearchResults.kt @@ -11,13 +11,17 @@ data class SearchResults( var onList: Boolean? = null, var perPage: Int? = null, var search: String? = null, + var countryOfOrigin: String? = null, var sort: String? = null, var genres: MutableList? = null, var excludedGenres: MutableList? = null, var tags: MutableList? = null, var excludedTags: MutableList? = null, + var status: String? = null, + var source: String? = null, var format: String? = null, var seasonYear: Int? = null, + var startYear: Int? = null, var season: String? = null, var page: Int = 1, var results: MutableList, @@ -37,12 +41,24 @@ data class SearchResults( ) ) } + status?.let { + list.add(SearchChip("STATUS", currContext()!!.getString(R.string.filter_status, it))) + } + source?.let { + list.add(SearchChip("SOURCE", currContext()!!.getString(R.string.filter_source, it))) + } format?.let { list.add(SearchChip("FORMAT", currContext()!!.getString(R.string.filter_format, it))) } + countryOfOrigin?.let { + list.add(SearchChip("COUNTRY", currContext()!!.getString(R.string.filter_country, it))) + } season?.let { list.add(SearchChip("SEASON", it)) } + startYear?.let { + list.add(SearchChip("START_YEAR", it.toString())) + } seasonYear?.let { list.add(SearchChip("SEASON_YEAR", it.toString())) } @@ -74,8 +90,12 @@ data class SearchResults( fun removeChip(chip: SearchChip) { when (chip.type) { "SORT" -> sort = null + "STATUS" -> status = null + "SOURCE" -> source = null "FORMAT" -> format = null + "COUNTRY" -> countryOfOrigin = null "SEASON" -> season = null + "START_YEAR" -> startYear = null "SEASON_YEAR" -> seasonYear = null "GENRE" -> genres?.remove(chip.text) "EXCLUDED_GENRE" -> excludedGenres?.remove(chip.text) diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Character.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Character.kt index e0539085..ec5a9ef4 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Character.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Character.kt @@ -55,7 +55,7 @@ data class CharacterConnection( @SerialName("nodes") var nodes: List?, // The pagination information - // @SerialName("pageInfo") var pageInfo: PageInfo?, + @SerialName("pageInfo") var pageInfo: PageInfo?, ) : java.io.Serializable @Serializable @@ -72,7 +72,7 @@ data class CharacterEdge( @SerialName("name") var name: String?, // The voice actors of the character - // @SerialName("voiceActors") var voiceActors: List?, + @SerialName("voiceActors") var voiceActors: List?, // The voice actors of the character with role date // @SerialName("voiceActorRoles") var voiceActorRoles: List?, diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Data.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Data.kt index 58445406..e6635b9a 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Data.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Data.kt @@ -24,7 +24,9 @@ class Query { @Serializable data class Data( @SerialName("Media") - val media: ani.dantotsu.connections.anilist.api.Media? + val media: ani.dantotsu.connections.anilist.api.Media?, + @SerialName("Page") + val page: ani.dantotsu.connections.anilist.api.Page? ) } @@ -136,6 +138,8 @@ class Query { @SerialName("recommendationQuery") val recommendationQuery: ani.dantotsu.connections.anilist.api.Page?, @SerialName("recommendationPlannedQueryAnime") val recommendationPlannedQueryAnime: ani.dantotsu.connections.anilist.api.MediaListCollection?, @SerialName("recommendationPlannedQueryManga") val recommendationPlannedQueryManga: ani.dantotsu.connections.anilist.api.MediaListCollection?, + @SerialName("Page1") val page1: ActivityPage?, + @SerialName("Page2") val page2: ActivityPage? ) } @@ -147,9 +151,45 @@ class Query { @Serializable data class Data( @SerialName("favoriteAnime") val favoriteAnime: ani.dantotsu.connections.anilist.api.User?, - @SerialName("favoriteManga") val favoriteManga: ani.dantotsu.connections.anilist.api.User?, - @SerialName("animeMediaList") val animeMediaList: ani.dantotsu.connections.anilist.api.MediaListCollection?, - @SerialName("mangaMediaList") val mangaMediaList: ani.dantotsu.connections.anilist.api.MediaListCollection? + @SerialName("favoriteManga") val favoriteManga: ani.dantotsu.connections.anilist.api.User? + ) + } + + @Serializable + data class AnimeList( + @SerialName("data") + val data: Data? + ) { + @Serializable + data class Data( + @SerialName("recentUpdates") val recentUpdates: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("recentUpdates2") val recentUpdates2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingMovies") val trendingMovies: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingMovies2") val trendingMovies2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("topRated") val topRated: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("topRated2") val topRated2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("mostFav") val mostFav: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?, + ) + } + + @Serializable + data class MangaList( + @SerialName("data") + val data: Data? + ) { + @Serializable + data class Data( + @SerialName("trendingManga") val trendingManga: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingManga2") val trendingManga2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingManhwa") val trendingManhwa: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingManhwa2") val trendingManhwa2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingNovel") val trendingNovel: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("trendingNovel2") val trendingNovel2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("topRated") val topRated: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("topRated2") val topRated2: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("mostFav") val mostFav: ani.dantotsu.connections.anilist.api.Page?, + @SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?, ) } @@ -259,6 +299,70 @@ class Query { val following: List? ) : java.io.Serializable + @Serializable + data class ReviewsResponse( + @SerialName("data") + val data: Data + ) : java.io.Serializable { + @Serializable + data class Data( + @SerialName("Page") + val page: ReviewPage? + ) : java.io.Serializable + } + + @Serializable + data class ReviewPage( + @SerialName("pageInfo") + val pageInfo: PageInfo, + @SerialName("reviews") + val reviews: List? + ) : java.io.Serializable + + @Serializable + data class RateReviewResponse( + @SerialName("data") + val data: Data + ) : java.io.Serializable { + @Serializable + data class Data( + @SerialName("RateReview") + val rateReview: Review + ) : java.io.Serializable + } + + @Serializable + data class Review( + @SerialName("id") + val id: Int, + @SerialName("mediaId") + val mediaId: Int, + @SerialName("mediaType") + val mediaType: String, + @SerialName("summary") + val summary: String, + @SerialName("body") + val body: String, + @SerialName("rating") + var rating: Int, + @SerialName("ratingAmount") + var ratingAmount: Int, + @SerialName("userRating") + var userRating: String, + @SerialName("score") + val score: Int, + @SerialName("private") + val private: Boolean, + @SerialName("siteUrl") + val siteUrl: String, + @SerialName("createdAt") + val createdAt: Int, + @SerialName("updatedAt") + val updatedAt: Int?, + @SerialName("user") + val user: ani.dantotsu.connections.anilist.api.User?, + ) : java.io.Serializable + @Serializable data class UserProfile( @SerialName("id") @@ -283,13 +387,13 @@ class Query { val statistics: NNUserStatisticTypes, @SerialName("siteUrl") val siteUrl: String, - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class NNUserStatisticTypes( @SerialName("anime") var anime: NNUserStatistics, @SerialName("manga") var manga: NNUserStatistics - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class NNUserStatistics( @@ -300,9 +404,9 @@ class Query { @SerialName("episodesWatched") var episodesWatched: Int, @SerialName("chaptersRead") var chaptersRead: Int, @SerialName("volumesRead") var volumesRead: Int, - ): java.io.Serializable + ) : java.io.Serializable - @Serializable + @Serializable data class UserFavourites( @SerialName("anime") val anime: UserMediaFavouritesCollection, @@ -314,13 +418,13 @@ class Query { val staff: UserStaffFavouritesCollection, @SerialName("studios") val studios: UserStudioFavouritesCollection, - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserMediaFavouritesCollection( @SerialName("nodes") val nodes: List, - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserMediaImageFavorite( @@ -328,13 +432,13 @@ class Query { val id: Int, @SerialName("coverImage") val coverImage: MediaCoverImage - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserCharacterFavouritesCollection( @SerialName("nodes") val nodes: List, - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserCharacterImageFavorite( @@ -346,19 +450,19 @@ class Query { val image: CharacterImage, @SerialName("isFavourite") val isFavourite: Boolean - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserStaffFavouritesCollection( @SerialName("nodes") val nodes: List, //downstream it's the same as character - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserStudioFavouritesCollection( @SerialName("nodes") val nodes: List, - ): java.io.Serializable + ) : java.io.Serializable @Serializable data class UserStudioFavorite( @@ -366,7 +470,7 @@ class Query { val id: Int, @SerialName("name") val name: String, - ): java.io.Serializable + ) : java.io.Serializable //---------------------------------------- // Statistics @@ -375,12 +479,12 @@ class Query { data class StatisticsResponse( @SerialName("data") val data: Data - ): java.io.Serializable { + ) : java.io.Serializable { @Serializable data class Data( @SerialName("User") val user: StatisticsUser? - ): java.io.Serializable + ) : java.io.Serializable } @Serializable diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Feed.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Feed.kt index 5f0af956..03ec0c46 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Feed.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Feed.kt @@ -14,7 +14,6 @@ data class FeedResponse( val page: ActivityPage ) : java.io.Serializable } - @Serializable data class ActivityPage( @SerialName("activities") @@ -36,7 +35,7 @@ data class Activity( @SerialName("type") val type: String, @SerialName("replyCount") - val replyCount: Int, + val replyCount: Int = 0, @SerialName("status") val status: String?, @SerialName("progress") @@ -48,9 +47,9 @@ data class Activity( @SerialName("siteUrl") val siteUrl: String?, @SerialName("isLocked") - val isLocked: Boolean, + val isLocked: Boolean?, @SerialName("isSubscribed") - val isSubscribed: Boolean, + val isSubscribed: Boolean?, @SerialName("likeCount") var likeCount: Int?, @SerialName("isLiked") @@ -75,6 +74,24 @@ data class Activity( val likes: List?, ) : java.io.Serializable +@Serializable +data class ReplyResponse( + @SerialName("data") + val data: Data +) : java.io.Serializable { + @Serializable + data class Data( + @SerialName("Page") + val page: ReplyPage + ) : java.io.Serializable +} + +@Serializable +data class ReplyPage( + @SerialName("activityReplies") + val activityReplies: List +) : java.io.Serializable + @Serializable data class ActivityReply( @SerialName("id") @@ -84,9 +101,9 @@ data class ActivityReply( @SerialName("text") val text: String, @SerialName("likeCount") - val likeCount: Int, + var likeCount: Int, @SerialName("isLiked") - val isLiked: Boolean, + var isLiked: Boolean, @SerialName("createdAt") val createdAt: Int, @SerialName("user") diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Media.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Media.kt index da2a989e..23c79045 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Media.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Media.kt @@ -152,7 +152,7 @@ data class Media( @SerialName("mediaListEntry") var mediaListEntry: MediaList?, // User reviews of the media - // @SerialName("reviews") var reviews: ReviewConnection?, + @SerialName("reviews") var reviews: ReviewConnection?, // User recommendations for similar media @SerialName("recommendations") var recommendations: RecommendationConnection?, @@ -174,7 +174,7 @@ data class Media( // Notes for site moderators @SerialName("modNotes") var modNotes: String?, -) +) : java.io.Serializable @Serializable data class MediaTitle( @@ -189,7 +189,7 @@ data class MediaTitle( // The currently authenticated users preferred title language. Default romaji for non-authenticated @SerialName("userPreferred") var userPreferred: String, -) +): java.io.Serializable @Serializable enum class MediaType { @@ -205,15 +205,17 @@ enum class MediaStatus { FINISHED, RELEASING, NOT_YET_RELEASED, CANCELLED, HIATUS; override fun toString(): String { - return when (super.toString()) { - "FINISHED" -> currContext()!!.getString(R.string.status_finished) - "RELEASING" -> currContext()!!.getString(R.string.status_releasing) - "NOT_YET_RELEASED" -> currContext()!!.getString(R.string.status_not_yet_released) - "CANCELLED" -> currContext()!!.getString(R.string.status_cancelled) - "HIATUS" -> currContext()!!.getString(R.string.status_hiatus) - else -> "" + currContext()?.let { + return when (super.toString()) { + "FINISHED" -> it.getString(R.string.status_finished) + "RELEASING" -> it.getString(R.string.status_releasing) + "NOT_YET_RELEASED" -> it.getString(R.string.status_not_yet_released) + "CANCELLED" -> it.getString(R.string.status_cancelled) + "HIATUS" -> it.getString(R.string.status_hiatus) + else -> "" + } } - + return super.toString().replace("_", " ") } } @@ -445,17 +447,20 @@ enum class MediaRelation { ADAPTATION, PREQUEL, SEQUEL, PARENT, SIDE_STORY, CHARACTER, SUMMARY, ALTERNATIVE, SPIN_OFF, OTHER, SOURCE, COMPILATION, CONTAINS; override fun toString(): String { - return when (super.toString()) { - "ADAPTATION" -> currContext()!!.getString(R.string.type_adaptation) - "PARENT" -> currContext()!!.getString(R.string.type_parent) - "CHARACTER" -> currContext()!!.getString(R.string.type_character) - "SUMMARY" -> currContext()!!.getString(R.string.type_summary) - "ALTERNATIVE" -> currContext()!!.getString(R.string.type_alternative) - "OTHER" -> currContext()!!.getString(R.string.type_other) - "SOURCE" -> currContext()!!.getString(R.string.type_source) - "CONTAINS" -> currContext()!!.getString(R.string.type_contains) - else -> super.toString().replace("_", " ") + currContext()?.let { + return when (super.toString()) { + "ADAPTATION" -> it.getString(R.string.type_adaptation) + "PARENT" -> it.getString(R.string.type_parent) + "CHARACTER" -> it.getString(R.string.type_character) + "SUMMARY" -> it.getString(R.string.type_summary) + "ALTERNATIVE" -> it.getString(R.string.type_alternative) + "OTHER" -> it.getString(R.string.type_other) + "SOURCE" -> it.getString(R.string.type_source) + "CONTAINS" -> it.getString(R.string.type_contains) + else -> super.toString().replace("_", " ") + } } + return super.toString().replace("_", " ") } } @@ -532,4 +537,9 @@ data class MediaListGroup( @SerialName("isSplitCompletedList") var isSplitCompletedList: Boolean?, @SerialName("status") var status: MediaListStatus?, -) : java.io.Serializable \ No newline at end of file +) : java.io.Serializable + +@Serializable +data class ReviewConnection( + @SerialName("nodes") var nodes: List?, +) \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Notification.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Notification.kt index b7d1cf0c..3928cf86 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Notification.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Notification.kt @@ -2,6 +2,7 @@ package ani.dantotsu.connections.anilist.api import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import java.util.Locale enum class NotificationType(val value: String) { ACTIVITY_MESSAGE("ACTIVITY_MESSAGE"), @@ -21,8 +22,23 @@ enum class NotificationType(val value: String) { MEDIA_DATA_CHANGE("MEDIA_DATA_CHANGE"), MEDIA_MERGE("MEDIA_MERGE"), MEDIA_DELETION("MEDIA_DELETION"), + //custom COMMENT_REPLY("COMMENT_REPLY"), + COMMENT_WARNING("COMMENT_WARNING"), + DANTOTSU_UPDATE("DANTOTSU_UPDATE"), + SUBSCRIPTION("SUBSCRIPTION"); + + fun toFormattedString(): String { + return this.value.replace("_", " ").lowercase(Locale.ROOT) + .replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } + } + + companion object { + fun String.fromFormattedString(): String { + return this.replace(" ", "_").uppercase(Locale.ROOT) + } + } } @Serializable @@ -84,9 +100,9 @@ data class Notification( @SerialName("createdAt") val createdAt: Int, @SerialName("media") - val media: ani.dantotsu.connections.anilist.api.Media? = null, + val media: Media? = null, @SerialName("user") - val user: ani.dantotsu.connections.anilist.api.User? = null, + val user: User? = null, @SerialName("message") val message: MessageActivity? = null, @SerialName("activity") @@ -95,6 +111,8 @@ data class Notification( val thread: Thread? = null, @SerialName("comment") val comment: ThreadComment? = null, + val image: String? = null, + val banner: String? = null, ) : java.io.Serializable @Serializable diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/Staff.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/Staff.kt index 7b56f693..7c9cafe1 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/Staff.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/Staff.kt @@ -93,6 +93,7 @@ data class StaffConnection( // The pagination information // @SerialName("pageInfo") var pageInfo: PageInfo?, ) + @Serializable data class StaffImage( // The character's image of media at its largest size @@ -101,6 +102,7 @@ data class StaffImage( // The character's image of media at medium size @SerialName("medium") var medium: String?, ) : java.io.Serializable + @Serializable data class StaffEdge( var role: String?, diff --git a/app/src/main/java/ani/dantotsu/connections/anilist/api/User.kt b/app/src/main/java/ani/dantotsu/connections/anilist/api/User.kt index b1ec8862..9117c144 100644 --- a/app/src/main/java/ani/dantotsu/connections/anilist/api/User.kt +++ b/app/src/main/java/ani/dantotsu/connections/anilist/api/User.kt @@ -69,7 +69,7 @@ data class User( // The user's previously used names. // @SerialName("previousNames") var previousNames: List?, -) +): java.io.Serializable @Serializable data class UserOptions( @@ -111,7 +111,7 @@ data class UserAvatar( // The avatar of user at medium size @SerialName("medium") var medium: String?, -): java.io.Serializable +) : java.io.Serializable @Serializable data class UserStatisticTypes( diff --git a/app/src/main/java/ani/dantotsu/connections/bakaupdates/MangaUpdates.kt b/app/src/main/java/ani/dantotsu/connections/bakaupdates/MangaUpdates.kt new file mode 100644 index 00000000..53a88815 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/connections/bakaupdates/MangaUpdates.kt @@ -0,0 +1,133 @@ +package ani.dantotsu.connections.bakaupdates + +import android.content.Context +import ani.dantotsu.R +import ani.dantotsu.client +import ani.dantotsu.connections.anilist.api.FuzzyDate +import ani.dantotsu.tryWithSuspend +import ani.dantotsu.util.Logger +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import okio.ByteString.Companion.encode +import org.json.JSONException +import org.json.JSONObject +import java.nio.charset.Charset + + +class MangaUpdates { + + private val Int?.dateFormat get() = String.format("%02d", this) + + private val apiUrl = "https://api.mangaupdates.com/v1/releases/search" + + suspend fun search(title: String, startDate: FuzzyDate?): MangaUpdatesResponse.Results? { + return tryWithSuspend { + val query = JSONObject().apply { + try { + put("search", title.encode(Charset.forName("UTF-8"))) + startDate?.let { + put( + "start_date", + "${it.year}-${it.month.dateFormat}-${it.day.dateFormat}" + ) + } + put("include_metadata", true) + } catch (e: JSONException) { + e.printStackTrace() + } + } + val res = try { + client.post(apiUrl, json = query).parsed() + } catch (e: Exception) { + Logger.log(e.toString()) + return@tryWithSuspend null + } + coroutineScope { + res.results?.map { + async(Dispatchers.IO) { + Logger.log(it.toString()) + } + } + }?.awaitAll() + res.results?.first { + it.metadata.series.lastUpdated?.timestamp != null + && (it.metadata.series.latestChapter != null + || (it.record.volume.isNullOrBlank() && it.record.chapter != null)) + } + } + } + + companion object { + fun getLatestChapter(context: Context, results: MangaUpdatesResponse.Results): String { + return results.metadata.series.latestChapter?.let { + context.getString(R.string.chapter_number, it) + } ?: results.record.chapter!!.substringAfterLast("-").trim().let { chapter -> + chapter.takeIf { + it.toIntOrNull() == null + } ?: context.getString(R.string.chapter_number, chapter.toInt()) + } + } + } + + @Serializable + data class MangaUpdatesResponse( + @SerialName("total_hits") + val totalHits: Int?, + @SerialName("page") + val page: Int?, + @SerialName("per_page") + val perPage: Int?, + val results: List? = null + ) { + @Serializable + data class Results( + val record: Record, + val metadata: MetaData + ) { + @Serializable + data class Record( + @SerialName("id") + val id: Int, + @SerialName("title") + val title: String, + @SerialName("volume") + val volume: String?, + @SerialName("chapter") + val chapter: String?, + @SerialName("release_date") + val releaseDate: String + ) + + @Serializable + data class MetaData( + val series: Series + ) { + @Serializable + data class Series( + @SerialName("series_id") + val seriesId: Long?, + @SerialName("title") + val title: String?, + @SerialName("latest_chapter") + val latestChapter: Int?, + @SerialName("last_updated") + val lastUpdated: LastUpdated? + ) { + @Serializable + data class LastUpdated( + @SerialName("timestamp") + val timestamp: Long, + @SerialName("as_rfc3339") + val asRfc3339: String, + @SerialName("as_string") + val asString: String + ) + } + } + } + } +} diff --git a/app/src/main/java/ani/dantotsu/connections/comments/CommentsAPI.kt b/app/src/main/java/ani/dantotsu/connections/comments/CommentsAPI.kt index defb5bad..57d08531 100644 --- a/app/src/main/java/ani/dantotsu/connections/comments/CommentsAPI.kt +++ b/app/src/main/java/ani/dantotsu/connections/comments/CommentsAPI.kt @@ -1,10 +1,13 @@ package ani.dantotsu.connections.comments +import android.content.Context import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.isOnline import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.toast +import ani.dantotsu.util.Logger import com.lagradost.nicehttp.NiceResponse import com.lagradost.nicehttp.Requests import eu.kanade.tachiyomi.network.NetworkHelper @@ -24,7 +27,8 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get object CommentsAPI { - val address: String = "https://1224665.xyz:443" + private const val ADDRESS: String = "https://api.dantotsu.app" + private var isOnline: Boolean = true var authToken: String? = null var userId: String? = null var isBanned: Boolean = false @@ -32,8 +36,13 @@ object CommentsAPI { var isMod: Boolean = false var totalVotes: Int = 0 - suspend fun getCommentsForId(id: Int, page: Int = 1, tag: Int?, sort: String?): CommentResponse? { - var url = "$address/comments/$id/$page" + suspend fun getCommentsForId( + id: Int, + page: Int = 1, + tag: Int?, + sort: String? + ): CommentResponse? { + var url = "$ADDRESS/comments/$id/$page" val request = requestBuilder() tag?.let { url += "?tag=$it" @@ -44,7 +53,8 @@ object CommentsAPI { val json = try { request.get(url) } catch (e: IOException) { - snackString("Failed to fetch comments") + Logger.log(e) + errorMessage("Failed to fetch comments") return null } if (!json.text.startsWith("{")) return null @@ -61,12 +71,13 @@ object CommentsAPI { } suspend fun getRepliesFromId(id: Int, page: Int = 1): CommentResponse? { - val url = "$address/comments/parent/$id/$page" + val url = "$ADDRESS/comments/parent/$id/$page" val request = requestBuilder() val json = try { request.get(url) } catch (e: IOException) { - snackString("Failed to fetch comments") + Logger.log(e) + errorMessage("Failed to fetch comments") return null } if (!json.text.startsWith("{")) return null @@ -83,12 +94,13 @@ object CommentsAPI { } suspend fun getSingleComment(id: Int): Comment? { - val url = "$address/comments/$id" + val url = "$ADDRESS/comments/$id" val request = requestBuilder() val json = try { request.get(url) } catch (e: IOException) { - snackString("Failed to fetch comment") + Logger.log(e) + errorMessage("Failed to fetch comment") return null } if (!json.text.startsWith("{")) return null @@ -105,12 +117,13 @@ object CommentsAPI { } suspend fun vote(commentId: Int, voteType: Int): Boolean { - val url = "$address/comments/vote/$commentId/$voteType" + val url = "$ADDRESS/comments/vote/$commentId/$voteType" val request = requestBuilder() val json = try { request.post(url) } catch (e: IOException) { - snackString("Failed to vote") + Logger.log(e) + errorMessage("Failed to vote") return false } val res = json.code == 200 @@ -121,7 +134,7 @@ object CommentsAPI { } suspend fun comment(mediaId: Int, parentCommentId: Int?, content: String, tag: Int?): Comment? { - val url = "$address/comments" + val url = "$ADDRESS/comments" val body = FormBody.Builder() .add("user_id", userId ?: return null) .add("media_id", mediaId.toString()) @@ -136,7 +149,8 @@ object CommentsAPI { val json = try { request.post(url, requestBody = body.build()) } catch (e: IOException) { - snackString("Failed to comment") + Logger.log(e) + errorMessage("Failed to comment") return null } val res = json.code == 200 @@ -147,7 +161,8 @@ object CommentsAPI { val parsed = try { Json.decodeFromString(json.text) } catch (e: Exception) { - snackString("Failed to parse comment") + Logger.log(e) + errorMessage("Failed to parse comment") return null } return Comment( @@ -169,12 +184,13 @@ object CommentsAPI { } suspend fun deleteComment(commentId: Int): Boolean { - val url = "$address/comments/$commentId" + val url = "$ADDRESS/comments/$commentId" val request = requestBuilder() val json = try { request.delete(url) } catch (e: IOException) { - snackString("Failed to delete comment") + Logger.log(e) + errorMessage("Failed to delete comment") return false } val res = json.code == 200 @@ -185,7 +201,7 @@ object CommentsAPI { } suspend fun editComment(commentId: Int, content: String): Boolean { - val url = "$address/comments/$commentId" + val url = "$ADDRESS/comments/$commentId" val body = FormBody.Builder() .add("content", content) .build() @@ -193,7 +209,8 @@ object CommentsAPI { val json = try { request.put(url, requestBody = body) } catch (e: IOException) { - snackString("Failed to edit comment") + Logger.log(e) + errorMessage("Failed to edit comment") return false } val res = json.code == 200 @@ -204,12 +221,13 @@ object CommentsAPI { } suspend fun banUser(userId: String): Boolean { - val url = "$address/ban/$userId" + val url = "$ADDRESS/ban/$userId" val request = requestBuilder() val json = try { request.post(url) } catch (e: IOException) { - snackString("Failed to ban user") + Logger.log(e) + errorMessage("Failed to ban user") return false } val res = json.code == 200 @@ -225,7 +243,7 @@ object CommentsAPI { mediaTitle: String, reportedId: String ): Boolean { - val url = "$address/report/$commentId" + val url = "$ADDRESS/report/$commentId" val body = FormBody.Builder() .add("username", username) .add("mediaName", mediaTitle) @@ -236,7 +254,8 @@ object CommentsAPI { val json = try { request.post(url, requestBody = body) } catch (e: IOException) { - snackString("Failed to report comment") + Logger.log(e) + errorMessage("Failed to report comment") return false } val res = json.code == 200 @@ -247,7 +266,7 @@ object CommentsAPI { } suspend fun getNotifications(client: OkHttpClient): NotificationResponse? { - val url = "$address/notification/reply" + val url = "$ADDRESS/notification/reply" val request = requestBuilder(client) val json = try { request.get(url) @@ -268,7 +287,7 @@ object CommentsAPI { } private suspend fun getUserDetails(client: OkHttpClient? = null): User? { - val url = "$address/user" + val url = "$ADDRESS/user" val request = if (client != null) requestBuilder(client) else requestBuilder() val json = try { request.get(url) @@ -291,7 +310,8 @@ object CommentsAPI { return null } - suspend fun fetchAuthToken(client: OkHttpClient? = null) { + suspend fun fetchAuthToken(context: Context, client: OkHttpClient? = null) { + isOnline = isOnline(context) if (authToken != null) return val MAX_RETRIES = 5 val tokenLifetime: Long = 1000 * 60 * 60 * 24 * 6 // 6 days @@ -310,7 +330,7 @@ object CommentsAPI { } } - val url = "$address/authenticate" + val url = "$ADDRESS/authenticate" val token = PrefManager.getVal(PrefName.AnilistToken, null as String?) ?: return repeat(MAX_RETRIES) { try { @@ -320,7 +340,8 @@ object CommentsAPI { val parsed = try { Json.decodeFromString(json.text) } catch (e: Exception) { - snackString("Failed to login to comments API: ${e.printStackTrace()}") + Logger.log(e) + errorMessage("Failed to login to comments API: ${e.printStackTrace()}") return } PrefManager.setVal(PrefName.CommentAuthResponse, parsed) @@ -340,12 +361,29 @@ object CommentsAPI { return } } catch (e: IOException) { - snackString("Failed to login to comments API") + Logger.log(e) + errorMessage("Failed to login to comments API") return } kotlinx.coroutines.delay(60000) } - snackString("Failed to login after multiple attempts") + errorMessage("Failed to login after multiple attempts") + } + + private fun errorMessage(reason: String) { + Logger.log(reason) + if (isOnline) snackString(reason) + } + + fun logout() { + PrefManager.removeVal(PrefName.CommentAuthResponse) + PrefManager.removeVal(PrefName.CommentTokenExpiry) + authToken = null + userId = null + isBanned = false + isAdmin = false + isMod = false + totalVotes = 0 } private suspend fun authRequest( @@ -388,7 +426,7 @@ object CommentsAPI { null } val message = parsed?.message ?: reason ?: error - val fullMessage = if(code == 500) message else "$code: $message" + val fullMessage = if (code == 500) message else "$code: $message" toast(fullMessage) } diff --git a/app/src/main/java/ani/dantotsu/connections/crashlytics/CrashlyticsStub.kt b/app/src/main/java/ani/dantotsu/connections/crashlytics/CrashlyticsStub.kt index 6c4e988a..76c072e1 100644 --- a/app/src/main/java/ani/dantotsu/connections/crashlytics/CrashlyticsStub.kt +++ b/app/src/main/java/ani/dantotsu/connections/crashlytics/CrashlyticsStub.kt @@ -7,6 +7,7 @@ class CrashlyticsStub : CrashlyticsInterface { override fun initialize(context: Context) { //no-op } + override fun logException(e: Throwable) { Logger.log(e) } diff --git a/app/src/main/java/ani/dantotsu/connections/discord/Discord.kt b/app/src/main/java/ani/dantotsu/connections/discord/Discord.kt index ea34f1bf..9318e5e6 100644 --- a/app/src/main/java/ani/dantotsu/connections/discord/Discord.kt +++ b/app/src/main/java/ani/dantotsu/connections/discord/Discord.kt @@ -20,14 +20,14 @@ object Discord { var avatar: String? = null - fun getSavedToken(context: Context): Boolean { + fun getSavedToken(): Boolean { token = PrefManager.getVal( PrefName.DiscordToken, null as String? ) return token != null } - fun saveToken(context: Context, token: String) { + fun saveToken(token: String) { PrefManager.setVal(PrefName.DiscordToken, token) } @@ -71,4 +71,6 @@ object Discord { const val application_Id = "1163925779692912771" const val small_Image: String = "mp:external/GJEe4hKzr8w56IW6ZKQz43HFVEo8pOtA_C-dJiWwxKo/https/cdn.discordapp.com/app-icons/1163925779692912771/f6b42d41dfdf0b56fcc79d4a12d2ac66.png" + const val small_Image_AniList: String = + "mp:external/rHOIjjChluqQtGyL_UHk6Z4oAqiVYlo_B7HSGPLSoUg/%3Fsize%3D128/https/cdn.discordapp.com/icons/210521487378087947/a_f54f910e2add364a3da3bb2f2fce0c72.webp" } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/connections/discord/DiscordService.kt b/app/src/main/java/ani/dantotsu/connections/discord/DiscordService.kt index 0a29ab60..9b6d19a1 100644 --- a/app/src/main/java/ani/dantotsu/connections/discord/DiscordService.kt +++ b/app/src/main/java/ani/dantotsu/connections/discord/DiscordService.kt @@ -5,16 +5,12 @@ import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service -import android.content.ContentValues import android.content.Context import android.content.Intent import android.content.pm.PackageManager -import android.net.Uri import android.os.Build -import android.os.Environment import android.os.IBinder import android.os.PowerManager -import android.provider.MediaStore import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat @@ -37,7 +33,6 @@ import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import java.io.File -import java.io.OutputStreamWriter class DiscordService : Service() { private var heartbeat: Int = 0 @@ -49,6 +44,7 @@ class DiscordService : Service() { private lateinit var heartbeatThread: Thread private lateinit var client: OkHttpClient private lateinit var wakeLock: PowerManager.WakeLock + private val shouldLog = false var presenceStore = "" val json = Json { encodeDefaults = true @@ -67,7 +63,7 @@ class DiscordService : Service() { PowerManager.PARTIAL_WAKE_LOCK, "discordRPC:backgroundPresence" ) - wakeLock.acquire() + wakeLock.acquire(30 * 60 * 1000L /*30 minutes*/) log("WakeLock Acquired") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val serviceChannel = NotificationChannel( @@ -162,8 +158,8 @@ class DiscordService : Service() { inner class DiscordWebSocketListener : WebSocketListener() { - var retryAttempts = 0 - val maxRetryAttempts = 10 + private var retryAttempts = 0 + private val maxRetryAttempts = 10 override fun onOpen(webSocket: WebSocket, response: Response) { super.onOpen(webSocket, response) this@DiscordService.webSocket = webSocket @@ -232,7 +228,7 @@ class DiscordService : Service() { resume() resume = false } else { - identify(webSocket, baseContext) + identify(webSocket) log("WebSocket: Identified") } } @@ -245,13 +241,13 @@ class DiscordService : Service() { } } - fun identify(webSocket: WebSocket, context: Context) { + private fun identify(webSocket: WebSocket) { val properties = JsonObject() properties.addProperty("os", "linux") properties.addProperty("browser", "unknown") properties.addProperty("device", "unknown") val d = JsonObject() - d.addProperty("token", getToken(context)) + d.addProperty("token", getToken()) d.addProperty("intents", 0) d.add("properties", properties) val payload = JsonObject() @@ -270,7 +266,7 @@ class DiscordService : Service() { retryAttempts++ if (retryAttempts >= maxRetryAttempts) { log("WebSocket: Error, onFailure() reason: Max Retry Attempts") - errorNotification("Could not set the presence", "Max Retry Attempts") + errorNotification("Timeout setting presence", "Max Retry Attempts") return } } @@ -311,7 +307,7 @@ class DiscordService : Service() { } } - fun getToken(context: Context): String { + fun getToken(): String { val token = PrefManager.getVal(PrefName.DiscordToken, null as String?) return if (token == null) { log("WebSocket: Token not found") @@ -349,13 +345,13 @@ class DiscordService : Service() { Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { - //TODO: Request permission return } notificationManager.notify(2, builder.build()) log("Error Notified") } + @Suppress("unused") fun saveSimpleTestPresence() { val file = File(baseContext.cacheDir, "payload") //fill with test payload @@ -375,20 +371,22 @@ class DiscordService : Service() { log("WebSocket: Simple Test Presence Saved") } - fun setPresence(String: String) { + fun setPresence(string: String) { log("WebSocket: Sending Presence payload") - log(String) - webSocket.send(String) + log(string) + webSocket.send(string) } fun log(string: String) { - //Logger.log(string) + if (shouldLog) { + Logger.log(string) + } } fun resume() { log("Sending Resume payload") val d = JsonObject() - d.addProperty("token", getToken(baseContext)) + d.addProperty("token", getToken()) d.addProperty("session_id", sessionId) d.addProperty("seq", sequence) val json = JsonObject() @@ -404,7 +402,7 @@ class DiscordService : Service() { Thread.sleep(heartbeat.toLong()) heartbeatSend(webSocket, sequence) log("WebSocket: Heartbeat Sent") - } catch (e: InterruptedException) { + } catch (ignored: InterruptedException) { } } } diff --git a/app/src/main/java/ani/dantotsu/connections/discord/Login.kt b/app/src/main/java/ani/dantotsu/connections/discord/Login.kt index 676f11e2..513da55b 100644 --- a/app/src/main/java/ani/dantotsu/connections/discord/Login.kt +++ b/app/src/main/java/ani/dantotsu/connections/discord/Login.kt @@ -75,7 +75,7 @@ class Login : AppCompatActivity() { } Toast.makeText(this, "Logged in successfully", Toast.LENGTH_SHORT).show() finish() - saveToken(this, token) + saveToken(token) startMainActivity(this@Login) } diff --git a/app/src/main/java/ani/dantotsu/connections/discord/RPC.kt b/app/src/main/java/ani/dantotsu/connections/discord/RPC.kt index 8a4f314b..f46dd63d 100644 --- a/app/src/main/java/ani/dantotsu/connections/discord/RPC.kt +++ b/app/src/main/java/ani/dantotsu/connections/discord/RPC.kt @@ -71,8 +71,8 @@ open class RPC(val token: String, val coroutineContext: CoroutineContext) { assets = Activity.Assets( largeImage = data.largeImage?.url?.discordUrl(), largeText = data.largeImage?.label, - smallImage = data.smallImage?.url?.discordUrl(), - smallText = data.smallImage?.label + smallImage = if (PrefManager.getVal(PrefName.ShowAniListIcon)) Discord.small_Image_AniList.discordUrl() else Discord.small_Image.discordUrl(), + smallText = if (PrefManager.getVal(PrefName.ShowAniListIcon)) "Anilist" else "Dantotsu", ), buttons = data.buttons.map { it.label }, metadata = Activity.Metadata( diff --git a/app/src/main/java/ani/dantotsu/connections/github/Contributors.kt b/app/src/main/java/ani/dantotsu/connections/github/Contributors.kt new file mode 100644 index 00000000..337e4c49 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/connections/github/Contributors.kt @@ -0,0 +1,114 @@ +package ani.dantotsu.connections.github + +import ani.dantotsu.Mapper +import ani.dantotsu.R +import ani.dantotsu.client +import ani.dantotsu.getAppString +import ani.dantotsu.settings.Developer +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.decodeFromJsonElement + +class Contributors { + + fun getContributors(): Array { + var developers = arrayOf() + runBlocking(Dispatchers.IO) { + val repo = getAppString(R.string.repo) + val res = client.get("https://api.github.com/repos/$repo/contributors") + .parsed().map { + Mapper.json.decodeFromJsonElement(it) + } + res.forEach { + if (it.login == "SunglassJerry") return@forEach + val role = when (it.login) { + "rebelonion" -> "Owner & Maintainer" + "sneazy-ibo" -> "Contributor & Comment Moderator" + "WaiWhat" -> "Icon Designer" + else -> "Contributor" + } + developers = developers.plus( + Developer( + it.login, + it.avatarUrl, + role, + it.htmlUrl + ) + ) + } + developers = developers.plus( + arrayOf( + Developer( + "MarshMeadow", + "https://avatars.githubusercontent.com/u/88599122?v=4", + "Beta Icon Designer & Website Maintainer", + "https://github.com/MarshMeadow?tab=repositories" + ), + Developer( + "Zaxx69", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6342562-kxE8m4i7KUMK.png", + "Telegram Admin", + "https://anilist.co/user/6342562" + ), + Developer( + "Arif Alam", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6011177-2n994qtayiR9.jpg", + "Discord & Comment Moderator", + "https://anilist.co/user/6011177" + ), + Developer( + "SunglassJeery", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b5804776-FEKfP5wbz2xv.png", + "Head Discord & Comment Moderator", + "https://anilist.co/user/5804776" + ), + Developer( + "Excited", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6131921-toSoGWmKbRA1.png", + "Comment Moderator", + "https://anilist.co/user/6131921" + ), + Developer( + "Gurjshan", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6363228-rWQ3Pl3WuxzL.png", + "Comment Moderator", + "https://anilist.co/user/6363228" + ), + Developer( + "NekoMimi", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6244220-HOpImMGMQAxW.jpg", + "Comment Moderator", + "https://anilist.co/user/6244220" + ), + Developer( + "Ziadsenior", + "https://s4.anilist.co/file/anilistcdn/user/avatar/large/b6049773-8cjYeUOFUguv.jpg", + "Comment Moderator and Arabic Translator", + "https://anilist.co/user/6049773" + ), + Developer( + "hastsu", + "https://cdn.discordapp.com/avatars/602422545077108749/20b4a6efa4314550e4ed51cdbe4fef3d.webp?size=160", + "Comment Moderator and Arabic Translator", + "https://anilist.co/user/6183359" + ), + ) + ) + } + return developers + } + + + @Serializable + data class GithubResponse( + @SerialName("login") + val login: String, + @SerialName("avatar_url") + val avatarUrl: String, + @SerialName("html_url") + val htmlUrl: String + ) +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/connections/mal/MAL.kt b/app/src/main/java/ani/dantotsu/connections/mal/MAL.kt index 9eaffdca..770d0e05 100644 --- a/app/src/main/java/ani/dantotsu/connections/mal/MAL.kt +++ b/app/src/main/java/ani/dantotsu/connections/mal/MAL.kt @@ -5,7 +5,6 @@ import android.content.Context import android.net.Uri import android.util.Base64 import androidx.browser.customtabs.CustomTabsIntent -import androidx.fragment.app.FragmentActivity import ani.dantotsu.R import ani.dantotsu.client import ani.dantotsu.currContext @@ -64,7 +63,7 @@ object MAL { } - suspend fun getSavedToken(context: FragmentActivity): Boolean { + suspend fun getSavedToken(): Boolean { return tryWithSuspend(false) { var res: ResponseToken = PrefManager.getNullableVal(PrefName.MALToken, null) @@ -77,7 +76,7 @@ object MAL { } ?: false } - fun removeSavedToken(context: Context) { + fun removeSavedToken() { token = null username = null userid = null diff --git a/app/src/main/java/ani/dantotsu/download/DownloadCompat.kt b/app/src/main/java/ani/dantotsu/download/DownloadCompat.kt new file mode 100644 index 00000000..892c6521 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/download/DownloadCompat.kt @@ -0,0 +1,384 @@ +package ani.dantotsu.download + +import android.content.Context +import android.net.Uri +import android.os.Environment +import android.widget.Toast +import ani.dantotsu.R +import ani.dantotsu.connections.crashlytics.CrashlyticsInterface +import ani.dantotsu.currActivity +import ani.dantotsu.currContext +import ani.dantotsu.download.anime.OfflineAnimeModel +import ani.dantotsu.download.manga.OfflineMangaModel +import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType +import ani.dantotsu.parsers.Episode +import ani.dantotsu.parsers.MangaChapter +import ani.dantotsu.parsers.MangaImage +import ani.dantotsu.parsers.Subtitle +import ani.dantotsu.parsers.SubtitleType +import ani.dantotsu.util.Logger +import com.google.gson.GsonBuilder +import com.google.gson.InstanceCreator +import eu.kanade.tachiyomi.animesource.model.SAnime +import eu.kanade.tachiyomi.animesource.model.SAnimeImpl +import eu.kanade.tachiyomi.animesource.model.SEpisode +import eu.kanade.tachiyomi.animesource.model.SEpisodeImpl +import eu.kanade.tachiyomi.source.model.SChapter +import eu.kanade.tachiyomi.source.model.SChapterImpl +import eu.kanade.tachiyomi.source.model.SManga +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get +import java.io.File +import java.util.Locale + +@Deprecated("external storage is deprecated, use SAF instead") +class DownloadCompat { + companion object { + @Deprecated("external storage is deprecated, use SAF instead") + fun loadMediaCompat(downloadedType: DownloadedType): Media? { + val type = when (downloadedType.type) { + MediaType.MANGA -> "Manga" + MediaType.ANIME -> "Anime" + else -> "Novel" + } + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/$type/${downloadedType.titleName}" + ) + //load media.json and convert to media class with gson + return try { + val gson = GsonBuilder() + .registerTypeAdapter(SChapter::class.java, InstanceCreator { + SChapterImpl() // Provide an instance of SChapterImpl + }) + .registerTypeAdapter(SAnime::class.java, InstanceCreator { + SAnimeImpl() // Provide an instance of SAnimeImpl + }) + .registerTypeAdapter(SEpisode::class.java, InstanceCreator { + SEpisodeImpl() // Provide an instance of SEpisodeImpl + }) + .create() + val media = File(directory, "media.json") + val mediaJson = media.readText() + gson.fromJson(mediaJson, Media::class.java) + } catch (e: Exception) { + Logger.log("Error loading media.json: ${e.message}") + Logger.log(e) + Injekt.get().logException(e) + null + } + } + + @Deprecated("external storage is deprecated, use SAF instead") + fun loadOfflineAnimeModelCompat(downloadedType: DownloadedType): OfflineAnimeModel { + val type = when (downloadedType.type) { + MediaType.MANGA -> "Manga" + MediaType.ANIME -> "Anime" + else -> "Novel" + } + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/$type/${downloadedType.titleName}" + ) + //load media.json and convert to media class with gson + try { + val mediaModel = loadMediaCompat(downloadedType)!! + val cover = File(directory, "cover.jpg") + val coverUri: Uri? = if (cover.exists()) { + Uri.fromFile(cover) + } else null + val banner = File(directory, "banner.jpg") + val bannerUri: Uri? = if (banner.exists()) { + Uri.fromFile(banner) + } else null + val title = mediaModel.mainName() + val score = ((if (mediaModel.userScore == 0) (mediaModel.meanScore + ?: 0) else mediaModel.userScore) / 10.0).toString() + val isOngoing = + mediaModel.status == currActivity()!!.getString(R.string.status_releasing) + val isUserScored = mediaModel.userScore != 0 + val watchedEpisodes = (mediaModel.userProgress ?: "~").toString() + val totalEpisode = + if (mediaModel.anime?.nextAiringEpisode != null) (mediaModel.anime.nextAiringEpisode.toString() + " | " + (mediaModel.anime.totalEpisodes + ?: "~").toString()) else (mediaModel.anime?.totalEpisodes ?: "~").toString() + val chapters = " Chapters" + val totalEpisodesList = + if (mediaModel.anime?.nextAiringEpisode != null) (mediaModel.anime.nextAiringEpisode.toString()) else (mediaModel.anime?.totalEpisodes + ?: "~").toString() + return OfflineAnimeModel( + title, + score, + totalEpisode, + totalEpisodesList, + watchedEpisodes, + type, + chapters, + isOngoing, + isUserScored, + coverUri, + bannerUri + ) + } catch (e: Exception) { + Logger.log("Error loading media.json: ${e.message}") + Logger.log(e) + Injekt.get().logException(e) + return OfflineAnimeModel( + "unknown", + "0", + "??", + "??", + "??", + "movie", + "hmm", + isOngoing = false, + isUserScored = false, + null, + null + ) + } + } + + @Deprecated("external storage is deprecated, use SAF instead") + fun loadOfflineMangaModelCompat(downloadedType: DownloadedType): OfflineMangaModel { + val type = when (downloadedType.type) { + MediaType.MANGA -> "Manga" + MediaType.ANIME -> "Anime" + else -> "Novel" + } + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/$type/${downloadedType.titleName}" + ) + //load media.json and convert to media class with gson + try { + val mediaModel = loadMediaCompat(downloadedType)!! + val cover = File(directory, "cover.jpg") + val coverUri: Uri? = if (cover.exists()) { + Uri.fromFile(cover) + } else null + val banner = File(directory, "banner.jpg") + val bannerUri: Uri? = if (banner.exists()) { + Uri.fromFile(banner) + } else null + val title = mediaModel.mainName() + val score = ((if (mediaModel.userScore == 0) (mediaModel.meanScore + ?: 0) else mediaModel.userScore) / 10.0).toString() + val isOngoing = + mediaModel.status == currActivity()!!.getString(R.string.status_releasing) + val isUserScored = mediaModel.userScore != 0 + val readchapter = (mediaModel.userProgress ?: "~").toString() + val totalchapter = "${mediaModel.manga?.totalChapters ?: "??"}" + val chapters = " Chapters" + return OfflineMangaModel( + title, + score, + totalchapter, + readchapter, + type, + chapters, + isOngoing, + isUserScored, + coverUri, + bannerUri + ) + } catch (e: Exception) { + Logger.log("Error loading media.json: ${e.message}") + Logger.log(e) + Injekt.get().logException(e) + return OfflineMangaModel( + "unknown", + "0", + "??", + "??", + "movie", + "hmm", + isOngoing = false, + isUserScored = false, + null, + null + ) + } + } + + @Deprecated("external storage is deprecated, use SAF instead") + suspend fun loadEpisodesCompat( + animeLink: String, + extra: Map?, + sAnime: SAnime + ): List { + + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "${animeLocation}/$animeLink" + ) + //get all of the folder names and add them to the list + val episodes = mutableListOf() + if (directory.exists()) { + directory.listFiles()?.forEach { + //put the title and episdode number in the extra data + val extraData = mutableMapOf() + extraData["title"] = animeLink + extraData["episode"] = it.name + if (it.isDirectory) { + val episode = Episode( + it.name, + "$animeLink - ${it.name}", + it.name, + null, + null, + extra = extraData, + sEpisode = SEpisodeImpl() + ) + episodes.add(episode) + } + } + episodes.sortBy { MediaNameAdapter.findEpisodeNumber(it.number) } + return episodes + } + return emptyList() + } + + @Deprecated("external storage is deprecated, use SAF instead") + suspend fun loadChaptersCompat( + mangaLink: String, + extra: Map?, + sManga: SManga + ): List { + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/Manga/$mangaLink" + ) + //get all of the folder names and add them to the list + val chapters = mutableListOf() + if (directory.exists()) { + directory.listFiles()?.forEach { + if (it.isDirectory) { + val chapter = MangaChapter( + it.name, + "$mangaLink/${it.name}", + it.name, + null, + null, + SChapter.create() + ) + chapters.add(chapter) + } + } + chapters.sortBy { MediaNameAdapter.findChapterNumber(it.number) } + return chapters + } + return emptyList() + } + + @Deprecated("external storage is deprecated, use SAF instead") + suspend fun loadImagesCompat(chapterLink: String, sChapter: SChapter): List { + val directory = File( + currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/Manga/$chapterLink" + ) + val images = mutableListOf() + val imageNumberRegex = Regex("""(\d+)\.jpg$""") + if (directory.exists()) { + directory.listFiles()?.forEach { + if (it.isFile) { + val image = MangaImage(it.absolutePath, false, null) + images.add(image) + } + } + images.sortBy { image -> + val matchResult = imageNumberRegex.find(image.url.url) + matchResult?.groups?.get(1)?.value?.toIntOrNull() ?: Int.MAX_VALUE + } + for (image in images) { + Logger.log("imageNumber: ${image.url.url}") + } + return images + } + return emptyList() + } + + @Deprecated("external storage is deprecated, use SAF instead") + fun loadSubtitleCompat(title: String, episode: String): List? { + currContext()?.let { + File( + it.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "$animeLocation/$title/$episode" + ).listFiles()?.forEach { + if (it.name.contains("subtitle")) { + return listOf( + Subtitle( + "Downloaded Subtitle", + Uri.fromFile(it).toString(), + determineSubtitletype(it.absolutePath) + ) + ) + } + } + } + return null + } + + private fun determineSubtitletype(url: String): SubtitleType { + return when { + url.lowercase(Locale.ROOT).endsWith("ass") -> SubtitleType.ASS + url.lowercase(Locale.ROOT).endsWith("vtt") -> SubtitleType.VTT + else -> SubtitleType.SRT + } + } + + @Deprecated("external storage is deprecated, use SAF instead") + fun removeMediaCompat(context: Context, title: String, type: MediaType) { + val subDirectory = if (type == MediaType.MANGA) { + "Manga" + } else if (type == MediaType.ANIME) { + "Anime" + } else { + "Novel" + } + val directory = File( + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/$subDirectory/$title" + ) + if (directory.exists()) { + directory.deleteRecursively() + } + } + + @Deprecated("external storage is deprecated, use SAF instead") + fun removeDownloadCompat(context: Context, downloadedType: DownloadedType, toast: Boolean) { + val directory = if (downloadedType.type == MediaType.MANGA) { + File( + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/Manga/${downloadedType.titleName}/${downloadedType.chapterName}" + ) + } else if (downloadedType.type == MediaType.ANIME) { + File( + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/Anime/${downloadedType.titleName}/${downloadedType.chapterName}" + ) + } else { + File( + context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), + "Dantotsu/Novel/${downloadedType.titleName}/${downloadedType.chapterName}" + ) + } + + // Check if the directory exists and delete it recursively + if (directory.exists()) { + val deleted = directory.deleteRecursively() + if (toast) { + if (deleted) { + Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT) + .show() + } + } + } + } + + private val animeLocation = "Dantotsu/Anime" + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/download/DownloadsManager.kt b/app/src/main/java/ani/dantotsu/download/DownloadsManager.kt index 0cbfa1bc..3b44e66d 100644 --- a/app/src/main/java/ani/dantotsu/download/DownloadsManager.kt +++ b/app/src/main/java/ani/dantotsu/download/DownloadsManager.kt @@ -1,13 +1,27 @@ package ani.dantotsu.download import android.content.Context -import android.os.Environment -import android.widget.Toast +import android.net.Uri +import androidx.documentfile.provider.DocumentFile +import ani.dantotsu.download.DownloadCompat.Companion.removeDownloadCompat +import ani.dantotsu.download.DownloadCompat.Companion.removeMediaCompat +import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaType import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.callback.FolderCallback +import com.anggrayudi.storage.file.deleteRecursively +import com.anggrayudi.storage.file.findFolder +import com.anggrayudi.storage.file.moveFolderTo import com.google.gson.Gson import com.google.gson.reflect.TypeToken -import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import me.xdrop.fuzzywuzzy.FuzzySearch import java.io.Serializable class DownloadsManager(private val context: Context) { @@ -15,11 +29,11 @@ class DownloadsManager(private val context: Context) { private val downloadsList = loadDownloads().toMutableList() val mangaDownloadedTypes: List - get() = downloadsList.filter { it.type == DownloadedType.Type.MANGA } + get() = downloadsList.filter { it.type == MediaType.MANGA } val animeDownloadedTypes: List - get() = downloadsList.filter { it.type == DownloadedType.Type.ANIME } + get() = downloadsList.filter { it.type == MediaType.ANIME } val novelDownloadedTypes: List - get() = downloadsList.filter { it.type == DownloadedType.Type.NOVEL } + get() = downloadsList.filter { it.type == MediaType.NOVEL } private fun saveDownloads() { val jsonString = gson.toJson(downloadsList) @@ -41,84 +55,72 @@ class DownloadsManager(private val context: Context) { saveDownloads() } - fun removeDownload(downloadedType: DownloadedType) { + fun removeDownload( + downloadedType: DownloadedType, + toast: Boolean = true, + onFinished: () -> Unit + ) { + removeDownloadCompat(context, downloadedType, toast) downloadsList.remove(downloadedType) - removeDirectory(downloadedType) + CoroutineScope(Dispatchers.IO).launch { + removeDirectory(downloadedType, toast) + withContext(Dispatchers.Main) { + onFinished() + } + } saveDownloads() } - fun removeMedia(title: String, type: DownloadedType.Type) { - val subDirectory = if (type == DownloadedType.Type.MANGA) { - "Manga" - } else if (type == DownloadedType.Type.ANIME) { - "Anime" - } else { - "Novel" - } - val directory = File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$subDirectory/$title" - ) - if (directory.exists()) { - val deleted = directory.deleteRecursively() + fun removeMedia(title: String, type: MediaType) { + removeMediaCompat(context, title, type) + val baseDirectory = getBaseDirectory(context, type) + val directory = baseDirectory?.findFolder(title) + if (directory?.exists() == true) { + val deleted = directory.deleteRecursively(context, false) if (deleted) { - Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show() + snackString("Successfully deleted") } else { - Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT).show() + snackString("Failed to delete directory") } } else { - Toast.makeText(context, "Directory does not exist", Toast.LENGTH_SHORT).show() + snackString("Directory does not exist") cleanDownloads() } when (type) { - DownloadedType.Type.MANGA -> { - downloadsList.removeAll { it.title == title && it.type == DownloadedType.Type.MANGA } + MediaType.MANGA -> { + downloadsList.removeAll { it.titleName == title && it.type == MediaType.MANGA } } - DownloadedType.Type.ANIME -> { - downloadsList.removeAll { it.title == title && it.type == DownloadedType.Type.ANIME } + MediaType.ANIME -> { + downloadsList.removeAll { it.titleName == title && it.type == MediaType.ANIME } } - DownloadedType.Type.NOVEL -> { - downloadsList.removeAll { it.title == title && it.type == DownloadedType.Type.NOVEL } + MediaType.NOVEL -> { + downloadsList.removeAll { it.titleName == title && it.type == MediaType.NOVEL } } } saveDownloads() } private fun cleanDownloads() { - cleanDownload(DownloadedType.Type.MANGA) - cleanDownload(DownloadedType.Type.ANIME) - cleanDownload(DownloadedType.Type.NOVEL) + cleanDownload(MediaType.MANGA) + cleanDownload(MediaType.ANIME) + cleanDownload(MediaType.NOVEL) } - private fun cleanDownload(type: DownloadedType.Type) { + private fun cleanDownload(type: MediaType) { // remove all folders that are not in the downloads list - val subDirectory = if (type == DownloadedType.Type.MANGA) { - "Manga" - } else if (type == DownloadedType.Type.ANIME) { - "Anime" - } else { - "Novel" + val directory = getBaseDirectory(context, type) + val downloadsSubLists = when (type) { + MediaType.MANGA -> mangaDownloadedTypes + MediaType.ANIME -> animeDownloadedTypes + else -> novelDownloadedTypes } - val directory = File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$subDirectory" - ) - val downloadsSubLists = if (type == DownloadedType.Type.MANGA) { - mangaDownloadedTypes - } else if (type == DownloadedType.Type.ANIME) { - animeDownloadedTypes - } else { - novelDownloadedTypes - } - if (directory.exists()) { + if (directory?.exists() == true && directory.isDirectory) { val files = directory.listFiles() - if (files != null) { - for (file in files) { - if (!downloadsSubLists.any { it.title == file.name }) { - val deleted = file.deleteRecursively() - } + for (file in files) { + if (!downloadsSubLists.any { it.titleName == file.name }) { + file.deleteRecursively(context, false) } } } @@ -126,122 +128,138 @@ class DownloadsManager(private val context: Context) { val iterator = downloadsList.iterator() while (iterator.hasNext()) { val download = iterator.next() - val downloadDir = File(directory, download.title) - if ((!downloadDir.exists() && download.type == type) || download.title.isBlank()) { + val downloadDir = directory?.findFolder(download.titleName) + if ((downloadDir?.exists() == false && download.type == type) || download.titleName.isBlank()) { iterator.remove() } } } - fun saveDownloadsListToJSONFileInDownloadsFolder(downloadsList: List) //for debugging - { - val jsonString = gson.toJson(downloadsList) - val file = File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/downloads.json" - ) - if (file.parentFile?.exists() == false) { - file.parentFile?.mkdirs() + fun moveDownloadsDir( + context: Context, + oldUri: Uri, + newUri: Uri, + finished: (Boolean, String) -> Unit + ) { + if (oldUri == newUri) { + Logger.log("Source and destination are the same") + finished(false, "Source and destination are the same") + return } - if (!file.exists()) { - file.createNewFile() + if (oldUri == Uri.EMPTY) { + Logger.log("Old Uri is empty") + finished(true, "Old Uri is empty") + return + } + CoroutineScope(Dispatchers.IO).launch { + try { + val oldBase = + DocumentFile.fromTreeUri(context, oldUri) ?: throw Exception("Old base is null") + val newBase = + DocumentFile.fromTreeUri(context, newUri) ?: throw Exception("New base is null") + val folder = + oldBase.findFolder(BASE_LOCATION) ?: throw Exception("Base folder not found") + folder.moveFolderTo(context, newBase, false, BASE_LOCATION, object : + FolderCallback() { + override fun onFailed(errorCode: ErrorCode) { + when (errorCode) { + ErrorCode.CANCELED -> finished(false, "Move canceled") + ErrorCode.CANNOT_CREATE_FILE_IN_TARGET -> finished( + false, + "Cannot create file in target" + ) + + ErrorCode.INVALID_TARGET_FOLDER -> finished( + true, + "Invalid target folder" + ) // seems to still work + ErrorCode.NO_SPACE_LEFT_ON_TARGET_PATH -> finished( + false, + "No space left on target path" + ) + + ErrorCode.UNKNOWN_IO_ERROR -> finished(false, "Unknown IO error") + ErrorCode.SOURCE_FOLDER_NOT_FOUND -> finished( + false, + "Source folder not found" + ) + + ErrorCode.STORAGE_PERMISSION_DENIED -> finished( + false, + "Storage permission denied" + ) + + ErrorCode.TARGET_FOLDER_CANNOT_HAVE_SAME_PATH_WITH_SOURCE_FOLDER -> finished( + false, + "Target folder cannot have same path with source folder" + ) + + else -> finished(false, "Failed to move downloads: $errorCode") + } + Logger.log("Failed to move downloads: $errorCode") + super.onFailed(errorCode) + } + + override fun onCompleted(result: Result) { + finished(true, "Successfully moved downloads") + super.onCompleted(result) + } + + }) + + } catch (e: Exception) { + snackString("Error: ${e.message}") + Logger.log("Failed to move downloads: ${e.message}") + Logger.log(e) + Logger.log("oldUri: $oldUri, newUri: $newUri") + finished(false, "Failed to move downloads: ${e.message}") + return@launch + } } - file.writeText(jsonString) } fun queryDownload(downloadedType: DownloadedType): Boolean { return downloadsList.contains(downloadedType) } - fun queryDownload(title: String, chapter: String, type: DownloadedType.Type? = null): Boolean { + fun queryDownload(title: String, chapter: String, type: MediaType? = null): Boolean { return if (type == null) { - downloadsList.any { it.title == title && it.chapter == chapter } + downloadsList.any { it.titleName == title && it.chapterName == chapter } } else { - downloadsList.any { it.title == title && it.chapter == chapter && it.type == type } + downloadsList.any { it.titleName == title && it.chapterName == chapter && it.type == type } } } - private fun removeDirectory(downloadedType: DownloadedType) { - val directory = if (downloadedType.type == DownloadedType.Type.MANGA) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/${downloadedType.title}/${downloadedType.chapter}" - ) - } else if (downloadedType.type == DownloadedType.Type.ANIME) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Anime/${downloadedType.title}/${downloadedType.chapter}" - ) - } else { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/${downloadedType.title}/${downloadedType.chapter}" - ) - } - + private fun removeDirectory(downloadedType: DownloadedType, toast: Boolean) { + val baseDirectory = getBaseDirectory(context, downloadedType.type) + val directory = + baseDirectory?.findFolder(downloadedType.titleName) + ?.findFolder(downloadedType.chapterName) + downloadsList.remove(downloadedType) // Check if the directory exists and delete it recursively - if (directory.exists()) { - val deleted = directory.deleteRecursively() + if (directory?.exists() == true) { + val deleted = directory.deleteRecursively(context, false) if (deleted) { - Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show() + if (toast) snackString("Successfully deleted") } else { - Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT).show() + snackString("Failed to delete directory") } } else { - Toast.makeText(context, "Directory does not exist", Toast.LENGTH_SHORT).show() + snackString("Directory does not exist") } } - fun exportDownloads(downloadedType: DownloadedType) { //copies to the downloads folder available to the user - val directory = if (downloadedType.type == DownloadedType.Type.MANGA) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/${downloadedType.title}/${downloadedType.chapter}" - ) - } else if (downloadedType.type == DownloadedType.Type.ANIME) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Anime/${downloadedType.title}/${downloadedType.chapter}" - ) - } else { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/${downloadedType.title}/${downloadedType.chapter}" - ) - } - val destination = File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/${downloadedType.title}/${downloadedType.chapter}" - ) - if (directory.exists()) { - val copied = directory.copyRecursively(destination, true) - if (copied) { - Toast.makeText(context, "Successfully copied", Toast.LENGTH_SHORT).show() - } else { - Toast.makeText(context, "Failed to copy directory", Toast.LENGTH_SHORT).show() - } - } else { - Toast.makeText(context, "Directory does not exist", Toast.LENGTH_SHORT).show() - } - } - - fun purgeDownloads(type: DownloadedType.Type) { - val directory = if (type == DownloadedType.Type.MANGA) { - File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Dantotsu/Manga") - } else if (type == DownloadedType.Type.ANIME) { - File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Dantotsu/Anime") - } else { - File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Dantotsu/Novel") - } - if (directory.exists()) { - val deleted = directory.deleteRecursively() + fun purgeDownloads(type: MediaType) { + val directory = getBaseDirectory(context, type) + if (directory?.exists() == true) { + val deleted = directory.deleteRecursively(context, false) if (deleted) { - Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show() + snackString("Successfully deleted") } else { - Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT).show() + snackString("Failed to delete directory") } } else { - Toast.makeText(context, "Directory does not exist", Toast.LENGTH_SHORT).show() + snackString("Directory does not exist") } downloadsList.removeAll { it.type == type } @@ -249,62 +267,132 @@ class DownloadsManager(private val context: Context) { } companion object { - const val novelLocation = "Dantotsu/Novel" - const val mangaLocation = "Dantotsu/Manga" - const val animeLocation = "Dantotsu/Anime" + private const val BASE_LOCATION = "Dantotsu" + private const val MANGA_SUB_LOCATION = "Manga" + private const val ANIME_SUB_LOCATION = "Anime" + private const val NOVEL_SUB_LOCATION = "Novel" - fun getDirectory( - context: Context, - type: DownloadedType.Type, - title: String, - chapter: String? = null - ): File { - return if (type == DownloadedType.Type.MANGA) { - if (chapter != null) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$mangaLocation/$title/$chapter" - ) - } else { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$mangaLocation/$title" - ) + + /** + * Get and create a base directory for the given type + * @param context the context + * @param type the type of media + * @return the base directory + */ + private fun getBaseDirectory(context: Context, type: MediaType): DocumentFile? { + val baseDirectory = Uri.parse(PrefManager.getVal(PrefName.DownloadsDir)) + if (baseDirectory == Uri.EMPTY) return null + var base = DocumentFile.fromTreeUri(context, baseDirectory) ?: return null + base = base.findOrCreateFolder(BASE_LOCATION, false) ?: return null + return when (type) { + MediaType.MANGA -> { + base.findOrCreateFolder(MANGA_SUB_LOCATION, false) } - } else if (type == DownloadedType.Type.ANIME) { - if (chapter != null) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$animeLocation/$title/$chapter" - ) - } else { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$animeLocation/$title" - ) + + MediaType.ANIME -> { + base.findOrCreateFolder(ANIME_SUB_LOCATION, false) } - } else { - if (chapter != null) { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$novelLocation/$title/$chapter" - ) - } else { - File( - context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "$novelLocation/$title" - ) + + else -> { + base.findOrCreateFolder(NOVEL_SUB_LOCATION, false) } } } - } -} + /** + * Get and create a subdirectory for the given type + * @param context the context + * @param type the type of media + * @param title the title of the media + * @param chapter the chapter of the media + * @return the subdirectory + */ + fun getSubDirectory( + context: Context, + type: MediaType, + overwrite: Boolean, + title: String, + chapter: String? = null + ): DocumentFile? { + val baseDirectory = getBaseDirectory(context, type) ?: return null + return if (chapter != null) { + baseDirectory.findOrCreateFolder(title, false) + ?.findOrCreateFolder(chapter, overwrite) + } else { + baseDirectory.findOrCreateFolder(title, overwrite) + } + } -data class DownloadedType(val title: String, val chapter: String, val type: Type) : Serializable { - enum class Type { - MANGA, - ANIME, - NOVEL + fun getDirSize( + context: Context, + type: MediaType, + title: String, + chapter: String? = null + ): Long { + val directory = getSubDirectory(context, type, false, title, chapter) ?: return 0 + var size = 0L + directory.listFiles().forEach { + size += it.length() + } + return size + } + + fun addNoMedia(context: Context) { + val baseDirectory = getBaseDirectory(context) ?: return + if (baseDirectory.findFile(".nomedia") == null) { + baseDirectory.createFile("application/octet-stream", ".nomedia") + } + } + + private fun getBaseDirectory(context: Context): DocumentFile? { + val baseDirectory = Uri.parse(PrefManager.getVal(PrefName.DownloadsDir)) + if (baseDirectory == Uri.EMPTY) return null + return DocumentFile.fromTreeUri(context, baseDirectory) + } + + private fun DocumentFile.findOrCreateFolder( + name: String, overwrite: Boolean + ): DocumentFile? { + return if (overwrite) { + findFolder(name.findValidName())?.delete() + createDirectory(name.findValidName()) + } else { + findFolder(name.findValidName()) ?: createDirectory(name.findValidName()) + } + } + + private const val RATIO_THRESHOLD = 95 + fun Media.compareName(name: String): Boolean { + val mainName = mainName().findValidName().lowercase() + val ratio = FuzzySearch.ratio(mainName, name.lowercase()) + return ratio > RATIO_THRESHOLD + } + + fun String.compareName(name: String): Boolean { + val mainName = findValidName().lowercase() + val compareName = name.findValidName().lowercase() + val ratio = FuzzySearch.ratio(mainName, compareName) + return ratio > RATIO_THRESHOLD + } } } + +private const val RESERVED_CHARS = "|\\?*<\":>+[]/'" +fun String?.findValidName(): String { + return this?.replace("/","_")?.filterNot { RESERVED_CHARS.contains(it) } ?: "" +} + +data class DownloadedType( + private val pTitle: String?, + private val pChapter: String?, + val type: MediaType, + @Deprecated("use pTitle instead") + private val title: String? = null, + @Deprecated("use pChapter instead") + private val chapter: String? = null +) : Serializable { + val titleName: String + get() = title ?: pTitle.findValidName() + val chapterName: String + get() = chapter ?: pChapter.findValidName() +} diff --git a/app/src/main/java/ani/dantotsu/download/anime/AnimeDownloaderService.kt b/app/src/main/java/ani/dantotsu/download/anime/AnimeDownloaderService.kt index 22b20dcb..ebeb17b4 100644 --- a/app/src/main/java/ani/dantotsu/download/anime/AnimeDownloaderService.kt +++ b/app/src/main/java/ani/dantotsu/download/anime/AnimeDownloaderService.kt @@ -9,32 +9,34 @@ import android.content.IntentFilter import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.os.Build -import android.os.Environment import android.os.IBinder import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat +import androidx.documentfile.provider.DocumentFile import androidx.media3.common.util.UnstableApi -import androidx.media3.exoplayer.offline.DownloadManager -import androidx.media3.exoplayer.offline.DownloadService import ani.dantotsu.FileUrl import ani.dantotsu.R +import ani.dantotsu.addons.download.DownloadAddonManager import ani.dantotsu.connections.crashlytics.CrashlyticsInterface -import ani.dantotsu.currActivity +import ani.dantotsu.defaultHeaders import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager -import ani.dantotsu.download.video.ExoplayerDownloadService -import ani.dantotsu.download.video.Helper -import ani.dantotsu.util.Logger +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory +import ani.dantotsu.download.anime.AnimeDownloaderService.AnimeDownloadTask.Companion.getTaskName +import ani.dantotsu.download.findValidName import ani.dantotsu.media.Media -import ani.dantotsu.media.SubtitleDownloader +import ani.dantotsu.media.MediaType import ani.dantotsu.media.anime.AnimeWatchFragment -import ani.dantotsu.parsers.Subtitle import ani.dantotsu.parsers.Video import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.snackString +import ani.dantotsu.toast +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.forceDelete +import com.anggrayudi.storage.file.openOutputStream import com.google.gson.GsonBuilder import com.google.gson.InstanceCreator import eu.kanade.tachiyomi.animesource.model.SAnime @@ -45,25 +47,21 @@ import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SChapterImpl import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext -import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.util.Queue import java.util.concurrent.ConcurrentLinkedQueue + class AnimeDownloaderService : Service() { private lateinit var notificationManager: NotificationManagerCompat @@ -74,6 +72,7 @@ class AnimeDownloaderService : Service() { private val mutex = Mutex() private var isCurrentlyProcessing = false private var currentTasks: MutableList = mutableListOf() + private val ffExtension = Injekt.get().extension?.extension override fun onBind(intent: Intent?): IBinder? { // This is only required for bound services. @@ -82,6 +81,11 @@ class AnimeDownloaderService : Service() { override fun onCreate() { super.onCreate() + if (ffExtension == null) { + toast(getString(R.string.download_addon_not_found)) + stopSelf() + return + } notificationManager = NotificationManagerCompat.from(this) builder = NotificationCompat.Builder(this, Notifications.CHANNEL_DOWNLOADER_PROGRESS).apply { @@ -89,6 +93,7 @@ class AnimeDownloaderService : Service() { setSmallIcon(R.drawable.ic_download_24) priority = NotificationCompat.PRIORITY_DEFAULT setOnlyAlertOnce(true) + setProgress(100, 0, false) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground( @@ -157,27 +162,14 @@ class AnimeDownloaderService : Service() { @UnstableApi fun cancelDownload(taskName: String) { - val url = - AnimeServiceDataSingleton.downloadQueue.find { it.getTaskName() == taskName }?.video?.file?.url - ?: currentTasks.find { it.getTaskName() == taskName }?.video?.file?.url ?: "" - if (url.isEmpty()) { - snackString("Failed to cancel download") - return + val sessionIds = + AnimeServiceDataSingleton.downloadQueue.filter { it.getTaskName() == taskName } + .map { it.sessionId }.toMutableList() + sessionIds.addAll(currentTasks.filter { it.getTaskName() == taskName }.map { it.sessionId }) + sessionIds.forEach { + ffExtension!!.cancelDownload(it) } currentTasks.removeAll { it.getTaskName() == taskName } - DownloadService.sendSetStopReason( - this@AnimeDownloaderService, - ExoplayerDownloadService::class.java, - url, - androidx.media3.exoplayer.offline.Download.STATE_STOPPED, - false - ) - DownloadService.sendRemoveDownload( - this@AnimeDownloaderService, - ExoplayerDownloadService::class.java, - url, - false - ) CoroutineScope(Dispatchers.Default).launch { mutex.withLock { downloadJobs[taskName]?.cancel() @@ -210,7 +202,6 @@ class AnimeDownloaderService : Service() { @androidx.annotation.OptIn(UnstableApi::class) suspend fun download(task: AnimeDownloadTask) { try { - val downloadManager = Helper.downloadManager(this@AnimeDownloaderService) withContext(Dispatchers.Main) { val notifi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ContextCompat.checkSelfPermission( @@ -221,111 +212,179 @@ class AnimeDownloaderService : Service() { true } - builder.setContentText("Downloading ${task.title} - ${task.episode}") + builder.setContentText("Downloading ${getTaskName(task.title, task.episode)}") if (notifi) { notificationManager.notify(NOTIFICATION_ID, builder.build()) } - currActivity()?.let { - Helper.downloadVideo( - it, - task.video, - task.subtitle - ) + val outputDir = getSubDirectory( + this@AnimeDownloaderService, + MediaType.ANIME, + false, + task.title, + task.episode + ) ?: throw Exception("Failed to create output directory") + + val extension = ffExtension!!.getFileExtension() + outputDir.findFile("${task.getTaskName().findValidName()}.${extension.first}")?.delete() + + val outputFile = + outputDir.createFile(extension.second, "${task.getTaskName()}.${extension.first}") + ?: throw Exception("Failed to create output file") + + var percent = 0 + var totalLength = 0.0 + val path = ffExtension.setDownloadPath( + this@AnimeDownloaderService, + outputFile.uri + ) + if (!task.video.file.headers.containsKey("User-Agent") + && !task.video.file.headers.containsKey("user-agent") + ) { + val newHeaders = task.video.file.headers.toMutableMap() + newHeaders["User-Agent"] = defaultHeaders["User-Agent"]!! + task.video.file.headers = newHeaders } + ffExtension.executeFFProbe( + task.video.file.url, + task.video.file.headers + ) { + if (it.toDoubleOrNull() != null) { + totalLength = it.toDouble() + } + } + val ffTask = + ffExtension.executeFFMpeg( + task.video.file.url, + path, + task.video.file.headers, + task.subtitle, + task.audio, + ) { + // CALLED WHEN SESSION GENERATES STATISTICS + val timeInMilliseconds = it + if (timeInMilliseconds > 0 && totalLength > 0) { + percent = ((it / 1000) / totalLength * 100).toInt() + } + Logger.log("Statistics: $it") + } + task.sessionId = ffTask + currentTasks.find { it.getTaskName() == task.getTaskName() }?.sessionId = + ffTask + saveMediaInfo(task) - task.subtitle?.let { - SubtitleDownloader.downloadSubtitle( - this@AnimeDownloaderService, - it.file.url, - DownloadedType( - task.title, - task.episode, - DownloadedType.Type.ANIME, - ) - ) - } - val downloadStarted = - hasDownloadStarted(downloadManager, task, 30000) // 30 seconds timeout - - if (!downloadStarted) { - Logger.log("Download failed to start") - builder.setContentText("${task.title} - ${task.episode} Download failed to start") - notificationManager.notify(NOTIFICATION_ID, builder.build()) - snackString("${task.title} - ${task.episode} Download failed to start") - broadcastDownloadFailed(task.episode) - return@withContext - } - // periodically check if the download is complete - while (downloadManager.downloadIndex.getDownload(task.video.file.url) != null) { - val download = downloadManager.downloadIndex.getDownload(task.video.file.url) - if (download != null) { - if (download.state == androidx.media3.exoplayer.offline.Download.STATE_FAILED) { - Logger.log("Download failed") - builder.setContentText("${task.title} - ${task.episode} Download failed") - notificationManager.notify(NOTIFICATION_ID, builder.build()) - snackString("${task.title} - ${task.episode} Download failed") - Logger.log("Download failed: ${download.failureReason}") - downloadsManager.removeDownload( - DownloadedType( + while (ffExtension.getState(ffTask) != "COMPLETED") { + if (ffExtension.getState(ffTask) == "FAILED") { + Logger.log("Download failed") + builder.setContentText( + "${ + getTaskName( task.title, - task.episode, - DownloadedType.Type.ANIME, + task.episode ) - ) - Injekt.get().logException( - Exception( - "Anime Download failed:" + - " ${download.failureReason}" + - " url: ${task.video.file.url}" + - " title: ${task.title}" + - " episode: ${task.episode}" - ) - ) - currentTasks.removeAll { it.getTaskName() == task.getTaskName() } - broadcastDownloadFailed(task.episode) - break - } - if (download.state == androidx.media3.exoplayer.offline.Download.STATE_COMPLETED) { - Logger.log("Download completed") - builder.setContentText("${task.title} - ${task.episode} Download completed") - notificationManager.notify(NOTIFICATION_ID, builder.build()) - snackString("${task.title} - ${task.episode} Download completed") - PrefManager.getAnimeDownloadPreferences().edit().putString( - task.getTaskName(), - task.video.file.url - ).apply() - downloadsManager.addDownload( - DownloadedType( - task.title, - task.episode, - DownloadedType.Type.ANIME, - ) - ) - currentTasks.removeAll { it.getTaskName() == task.getTaskName() } - broadcastDownloadFinished(task.episode) - break - } - if (download.state == androidx.media3.exoplayer.offline.Download.STATE_STOPPED) { - Logger.log("Download stopped") - builder.setContentText("${task.title} - ${task.episode} Download stopped") - notificationManager.notify(NOTIFICATION_ID, builder.build()) - snackString("${task.title} - ${task.episode} Download stopped") - break - } - broadcastDownloadProgress( - task.episode, - download.percentDownloaded.toInt() + } Download failed" ) - if (notifi) { - notificationManager.notify(NOTIFICATION_ID, builder.build()) - } + notificationManager.notify(NOTIFICATION_ID, builder.build()) + toast("${getTaskName(task.title, task.episode)} Download failed") + Logger.log("Download failed: ${ffExtension.getStackTrace(ffTask)}") + downloadsManager.removeDownload( + DownloadedType( + task.title, + task.episode, + MediaType.ANIME, + ), + false + ) {} + Injekt.get().logException( + Exception( + "Anime Download failed:" + + " ${getTaskName(task.title, task.episode)}" + + " url: ${task.video.file.url}" + + " title: ${task.title}" + + " episode: ${task.episode}" + ) + ) + currentTasks.removeAll { it.getTaskName() == task.getTaskName() } + broadcastDownloadFailed(task.episode) + break + } + builder.setProgress( + 100, percent.coerceAtMost(99), + false + ) + broadcastDownloadProgress( + task.episode, + percent.coerceAtMost(99) + ) + if (notifi) { + notificationManager.notify(NOTIFICATION_ID, builder.build()) } kotlinx.coroutines.delay(2000) } + if (ffExtension.getState(ffTask) == "COMPLETED") { + if (ffExtension.hadError(ffTask)) { + Logger.log("Download failed") + builder.setContentText( + "${ + getTaskName( + task.title, + task.episode + ) + } Download failed" + ) + notificationManager.notify(NOTIFICATION_ID, builder.build()) + snackString("${getTaskName(task.title, task.episode)} Download failed") + downloadsManager.removeDownload( + DownloadedType( + task.title, + task.episode, + MediaType.ANIME + ), + false + ) {} + Injekt.get().logException( + Exception( + "Anime Download failed:" + + " ${getTaskName(task.title, task.episode)}" + + " url: ${task.video.file.url}" + + " title: ${task.title}" + + " episode: ${task.episode}" + ) + ) + currentTasks.removeAll { it.getTaskName() == task.getTaskName() } + broadcastDownloadFailed(task.episode) + return@withContext + } + Logger.log("Download completed") + builder.setContentText( + "${ + getTaskName( + task.title, + task.episode + ) + } Download completed" + ) + notificationManager.notify(NOTIFICATION_ID, builder.build()) + snackString("${getTaskName(task.title, task.episode)} Download completed") + PrefManager.getAnimeDownloadPreferences().edit().putString( + task.getTaskName(), + task.video.file.url + ).apply() + downloadsManager.addDownload( + DownloadedType( + task.title, + task.episode, + MediaType.ANIME, + ) + ) + + currentTasks.removeAll { it.getTaskName() == task.getTaskName() } + broadcastDownloadFinished(task.episode) + } else throw Exception("Download failed") + } } catch (e: Exception) { if (e.message?.contains("Coroutine was cancelled") == false) { //wut @@ -338,34 +397,24 @@ class AnimeDownloaderService : Service() { } } - @androidx.annotation.OptIn(UnstableApi::class) - suspend fun hasDownloadStarted( - downloadManager: DownloadManager, - task: AnimeDownloadTask, - timeout: Long - ): Boolean { - val startTime = System.currentTimeMillis() - while (System.currentTimeMillis() - startTime < timeout) { - val download = downloadManager.downloadIndex.getDownload(task.video.file.url) - if (download != null) { - return true - } - // Delay between each poll - kotlinx.coroutines.delay(500) - } - return false - } - private fun saveMediaInfo(task: AnimeDownloadTask) { - launchIO { - val directory = File( - getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "${DownloadsManager.animeLocation}/${task.title}" - ) - val episodeDirectory = File(directory, task.episode) - if (!episodeDirectory.exists()) episodeDirectory.mkdirs() + CoroutineScope(Dispatchers.IO).launch { + val directory = + getSubDirectory(this@AnimeDownloaderService, MediaType.ANIME, false, task.title) + ?: throw Exception("Directory not found") + directory.findFile("media.json")?.forceDelete(this@AnimeDownloaderService) + val file = directory.createFile("application/json", "media.json") + ?: throw Exception("File not created") + val episodeDirectory = + getSubDirectory( + this@AnimeDownloaderService, + MediaType.ANIME, + false, + task.title, + task.episode + ) + ?: throw Exception("Directory not found") - val file = File(directory, "media.json") val gson = GsonBuilder() .registerTypeAdapter(SChapter::class.java, InstanceCreator { SChapterImpl() // Provide an instance of SChapterImpl @@ -399,14 +448,25 @@ class AnimeDownloaderService : Service() { val jsonString = gson.toJson(media) withContext(Dispatchers.Main) { - file.writeText(jsonString) + try { + file.openOutputStream(this@AnimeDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") + output.write(jsonString.toByteArray()) + } + } catch (e: android.system.ErrnoException) { + e.printStackTrace() + Toast.makeText( + this@AnimeDownloaderService, + "Error while saving: ${e.localizedMessage}", + Toast.LENGTH_LONG + ).show() + } } } } } - - private suspend fun downloadImage(url: String, directory: File, name: String): String? = + private suspend fun downloadImage(url: String, directory: DocumentFile, name: String): String? = withContext(Dispatchers.IO) { var connection: HttpURLConnection? = null println("Downloading url $url") @@ -417,13 +477,16 @@ class AnimeDownloaderService : Service() { throw Exception("Server returned HTTP ${connection.responseCode} ${connection.responseMessage}") } - val file = File(directory, name) - FileOutputStream(file).use { output -> + directory.findFile(name)?.forceDelete(this@AnimeDownloaderService) + val file = + directory.createFile("image/jpeg", name) ?: throw Exception("File not created") + file.openOutputStream(this@AnimeDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") connection.inputStream.use { input -> input.copyTo(output) } } - return@withContext file.absolutePath + return@withContext file.uri.toString() } catch (e: Exception) { e.printStackTrace() withContext(Dispatchers.Main) { @@ -485,19 +548,21 @@ class AnimeDownloaderService : Service() { val title: String, val episode: String, val video: Video, - val subtitle: Subtitle? = null, + val subtitle: List> = emptyList(), + val audio: List> = emptyList(), val sourceMedia: Media? = null, val episodeImage: String? = null, val retries: Int = 2, val simultaneousDownloads: Int = 2, + var sessionId: Long = -1 ) { fun getTaskName(): String { - return "$title - $episode" + return "${title.replace("/", "")}/${episode.replace("/", "")}" } companion object { fun getTaskName(title: String, episode: String): String { - return "$title - $episode" + return "${title.replace("/", "")}/${episode.replace("/", "")}" } } } @@ -511,7 +576,6 @@ class AnimeDownloaderService : Service() { object AnimeServiceDataSingleton { var video: Video? = null - var sourceMedia: Media? = null var downloadQueue: Queue = ConcurrentLinkedQueue() @Volatile diff --git a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeAdapter.kt b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeAdapter.kt index ef0c4148..a4f03cf7 100644 --- a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeAdapter.kt +++ b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeAdapter.kt @@ -1,7 +1,6 @@ package ani.dantotsu.download.anime -import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View @@ -38,7 +37,6 @@ class OfflineAnimeAdapter( return position.toLong() } - @SuppressLint("SetTextI18n") override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view: View = convertView ?: when (style) { @@ -51,28 +49,28 @@ class OfflineAnimeAdapter( val imageView = view.findViewById(R.id.itemCompactImage) val titleTextView = view.findViewById(R.id.itemCompactTitle) val itemScore = view.findViewById(R.id.itemCompactScore) - val itemScoreBG = view.findViewById(R.id.itemCompactScoreBG) val ongoing = view.findViewById(R.id.itemCompactOngoing) - val totalepisodes = view.findViewById(R.id.itemCompactTotal) - val typeimage = view.findViewById(R.id.itemCompactTypeImage) + val totalEpisodes = view.findViewById(R.id.itemCompactTotal) + val typeImage = view.findViewById(R.id.itemCompactTypeImage) val type = view.findViewById(R.id.itemCompactRelation) val typeView = view.findViewById(R.id.itemCompactType) if (style == 0) { val bannerView = view.findViewById(R.id.itemCompactBanner) // for large view val episodes = view.findViewById(R.id.itemTotal) - episodes.text = " Episodes" - bannerView.setImageURI(item.banner) - totalepisodes.text = item.totalEpisodeList + val text = " ${context.getString(R.string.episodes)}" + episodes.text = text + bannerView.setImageURI(item.banner ?: item.image) + totalEpisodes.text = item.totalEpisodeList } else if (style == 1) { val watchedEpisodes = view.findViewById(R.id.itemCompactUserProgress) // for compact view watchedEpisodes.text = item.watchedEpisode - totalepisodes.text = " | " + item.totalEpisode + totalEpisodes.text = context.getString(R.string.total_divider, item.totalEpisode) } // Bind item data to the views - typeimage.setImageResource(R.drawable.ic_round_movie_filter_24) + typeImage.setImageResource(R.drawable.ic_round_movie_filter_24) type.text = item.type typeView.visibility = View.VISIBLE imageView.setImageURI(item.image) diff --git a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeFragment.kt b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeFragment.kt index 4ff5497c..cdf7e993 100644 --- a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeFragment.kt +++ b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeFragment.kt @@ -4,10 +4,8 @@ package ani.dantotsu.download.anime import android.content.Intent import android.net.Uri import android.os.Bundle -import android.os.Environment import android.text.Editable import android.text.TextWatcher -import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -22,26 +20,35 @@ import androidx.annotation.OptIn import androidx.appcompat.app.AppCompatActivity import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.marginBottom import androidx.fragment.app.Fragment +import androidx.lifecycle.lifecycleScope import androidx.media3.common.util.UnstableApi import ani.dantotsu.R import ani.dantotsu.bottomBar import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.currActivity import ani.dantotsu.currContext +import ani.dantotsu.download.DownloadCompat.Companion.loadMediaCompat +import ani.dantotsu.download.DownloadCompat.Companion.loadOfflineAnimeModelCompat import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager +import ani.dantotsu.download.DownloadsManager.Companion.compareName +import ani.dantotsu.download.findValidName +import ani.dantotsu.getThemeColor import ani.dantotsu.initActivity -import ani.dantotsu.util.Logger import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.media.MediaType import ani.dantotsu.navBarHeight import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.settings.SettingsDialogFragment import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.openInputStream import com.google.android.material.card.MaterialCardView import com.google.android.material.imageview.ShapeableImageView import com.google.android.material.textfield.TextInputLayout @@ -53,9 +60,13 @@ import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.SEpisodeImpl import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SChapterImpl +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { @@ -64,6 +75,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { private lateinit var gridView: GridView private lateinit var adapter: OfflineAnimeAdapter private lateinit var total: TextView + private var downloadsJob: Job = Job() override fun onCreateView( inflater: LayoutInflater, @@ -79,9 +91,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { textInputLayout.boxBackgroundColor = semiTransparentColor val materialCardView = view.findViewById(R.id.offlineMangaAvatarContainer) materialCardView.setCardBackgroundColor(semiTransparentColor) - val typedValue = TypedValue() - requireContext().theme?.resolveAttribute(android.R.attr.windowBackground, typedValue, true) - val color = typedValue.data + val color = requireContext().getThemeColor(android.R.attr.windowBackground) val animeUserAvatar = view.findViewById(R.id.offlineMangaUserAvatar) animeUserAvatar.setSafeOnClickListener { @@ -110,10 +120,10 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { }) var style: Int = PrefManager.getVal(PrefName.OfflineView) val layoutList = view.findViewById(R.id.downloadedList) - val layoutcompact = view.findViewById(R.id.downloadedGrid) + val layoutCompact = view.findViewById(R.id.downloadedGrid) var selected = when (style) { 0 -> layoutList - 1 -> layoutcompact + 1 -> layoutCompact else -> layoutList } selected.alpha = 1f @@ -134,7 +144,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { grid() } - layoutcompact.setOnClickListener { + layoutCompact.setOnClickListener { selected(it as ImageView) style = 1 PrefManager.setVal(PrefName.OfflineView, style) @@ -154,11 +164,11 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { @OptIn(UnstableApi::class) private fun grid() { gridView.visibility = View.VISIBLE - getDownloads() val fadeIn = AlphaAnimation(0f, 1f) fadeIn.duration = 300 // animations pog gridView.layoutAnimation = LayoutAnimationController(fadeIn) adapter = OfflineAnimeAdapter(requireContext(), downloads, this) + getDownloads() gridView.adapter = adapter gridView.scheduleLayoutAnimation() total.text = if (gridView.count > 0) "Anime (${gridView.count})" else "Empty List" @@ -166,20 +176,22 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { // Get the OfflineAnimeModel that was clicked val item = adapter.getItem(position) as OfflineAnimeModel val media = - downloadManager.animeDownloadedTypes.firstOrNull { it.title == item.title } + downloadManager.animeDownloadedTypes.firstOrNull { it.titleName.compareName(item.title) } media?.let { - val mediaModel = getMedia(it) - if (mediaModel == null) { - snackString("Error loading media.json") - return@let + lifecycleScope.launch { + val mediaModel = getMedia(it) + if (mediaModel == null) { + snackString("Error loading media.json") + return@launch + } + MediaDetailsActivity.mediaSingleton = mediaModel + ContextCompat.startActivity( + requireActivity(), + Intent(requireContext(), MediaDetailsActivity::class.java) + .putExtra("download", true), + null + ) } - MediaDetailsActivity.mediaSingleton = mediaModel - ContextCompat.startActivity( - requireActivity(), - Intent(requireContext(), MediaDetailsActivity::class.java) - .putExtra("download", true), - null - ) } ?: run { snackString("no media found") } @@ -187,8 +199,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { gridView.setOnItemLongClickListener { _, _, position, _ -> // Get the OfflineAnimeModel that was clicked val item = adapter.getItem(position) as OfflineAnimeModel - val type: DownloadedType.Type = - DownloadedType.Type.ANIME + val type: MediaType = MediaType.ANIME // Alert dialog to confirm deletion val builder = @@ -203,13 +214,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { if (mediaIds.isEmpty()) { snackString("No media found") // if this happens, terrible things have happened } - for (mediaId in mediaIds) { - ani.dantotsu.download.video.Helper.downloadManager(requireContext()) - .removeDownload(mediaId.toString()) - } getDownloads() - adapter.setItems(downloads) - total.text = if (gridView.count > 0) "Anime (${gridView.count})" else "Empty List" } builder.setNegativeButton("No") { _, _ -> // Do nothing @@ -237,7 +242,6 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { gridView.setOnScrollListener(object : AbsListView.OnScrollListener { override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { - // Implement behavior for different scroll states if needed } override fun onScroll( @@ -250,7 +254,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { val visibility = first != null && first.top < 0 scrollTop.translationY = -(navBarHeight + bottomBar.height + bottomBar.marginBottom).toFloat() - scrollTop.visibility = if (visibility) View.VISIBLE else View.GONE + scrollTop.isVisible = visibility } }) initActivity(requireActivity()) @@ -260,7 +264,6 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { override fun onResume() { super.onResume() getDownloads() - adapter.notifyDataSetChanged() } override fun onPause() { @@ -280,29 +283,40 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { private fun getDownloads() { downloads = listOf() - val animeTitles = downloadManager.animeDownloadedTypes.map { it.title }.distinct() - val newAnimeDownloads = mutableListOf() - for (title in animeTitles) { - val tDownloads = downloadManager.animeDownloadedTypes.filter { it.title == title } - val download = tDownloads.first() - val offlineAnimeModel = loadOfflineAnimeModel(download) - newAnimeDownloads += offlineAnimeModel + if (downloadsJob.isActive) { + downloadsJob.cancel() + } + downloadsJob = Job() + CoroutineScope(Dispatchers.IO + downloadsJob).launch { + val animeTitles = downloadManager.animeDownloadedTypes.map { it.titleName.findValidName() }.distinct() + val newAnimeDownloads = mutableListOf() + for (title in animeTitles) { + val tDownloads = downloadManager.animeDownloadedTypes.filter { it.titleName.findValidName() == title } + val download = tDownloads.firstOrNull() ?: continue + val offlineAnimeModel = loadOfflineAnimeModel(download) + if (offlineAnimeModel.title == "unknown") offlineAnimeModel.title = title + newAnimeDownloads += offlineAnimeModel + } + downloads = newAnimeDownloads + withContext(Dispatchers.Main) { + adapter.setItems(downloads) + total.text = if (gridView.count > 0) "Anime (${gridView.count})" else "Empty List" + adapter.notifyDataSetChanged() + } } - downloads = newAnimeDownloads } - private fun getMedia(downloadedType: DownloadedType): Media? { - val type = when (downloadedType.type) { - DownloadedType.Type.MANGA -> "Manga" - DownloadedType.Type.ANIME -> "Anime" - else -> "Novel" - } - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$type/${downloadedType.title}" - ) - //load media.json and convert to media class with gson + /** + * Load media.json file from the directory and convert it to Media class + * @param downloadedType DownloadedType object + * @return Media object + */ + private suspend fun getMedia(downloadedType: DownloadedType): Media? { return try { + val directory = DownloadsManager.getSubDirectory( + context ?: currContext()!!, downloadedType.type, + false, downloadedType.titleName + ) val gson = GsonBuilder() .registerTypeAdapter(SChapter::class.java, InstanceCreator { SChapterImpl() // Provide an instance of SChapterImpl @@ -314,8 +328,13 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { SEpisodeImpl() // Provide an instance of SEpisodeImpl }) .create() - val media = File(directory, "media.json") - val mediaJson = media.readText() + val media = directory?.findFile("media.json") + ?: return loadMediaCompat(downloadedType) + val mediaJson = + media.openInputStream(context ?: currContext()!!)?.bufferedReader().use { + it?.readText() + } + ?: return null gson.fromJson(mediaJson, Media::class.java) } catch (e: Exception) { Logger.log("Error loading media.json: ${e.message}") @@ -325,27 +344,28 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { } } - private fun loadOfflineAnimeModel(downloadedType: DownloadedType): OfflineAnimeModel { - val type = when (downloadedType.type) { - DownloadedType.Type.MANGA -> "Manga" - DownloadedType.Type.ANIME -> "Anime" - else -> "Novel" - } - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$type/${downloadedType.title}" - ) - //load media.json and convert to media class with gson + /** + * Load OfflineAnimeModel from the directory + * @param downloadedType DownloadedType object + * @return OfflineAnimeModel object + */ + private suspend fun loadOfflineAnimeModel(downloadedType: DownloadedType): OfflineAnimeModel { + val type = downloadedType.type.asText() try { + val directory = DownloadsManager.getSubDirectory( + context ?: currContext()!!, downloadedType.type, + false, downloadedType.titleName + ) val mediaModel = getMedia(downloadedType)!! - val cover = File(directory, "cover.jpg") - val coverUri: Uri? = if (cover.exists()) { - Uri.fromFile(cover) + val cover = directory?.findFile("cover.jpg") + val coverUri: Uri? = if (cover?.exists() == true) { + cover.uri } else null - val banner = File(directory, "banner.jpg") - val bannerUri: Uri? = if (banner.exists()) { - Uri.fromFile(banner) + val banner = directory?.findFile("banner.jpg") + val bannerUri: Uri? = if (banner?.exists() == true) { + banner.uri } else null + if (coverUri == null && bannerUri == null) throw Exception("No cover or banner found, probably compat") val title = mediaModel.mainName() val score = ((if (mediaModel.userScore == 0) (mediaModel.meanScore ?: 0) else mediaModel.userScore) / 10.0).toString() @@ -374,22 +394,26 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener { bannerUri ) } catch (e: Exception) { - Logger.log("Error loading media.json: ${e.message}") - Logger.log(e) - Injekt.get().logException(e) - return OfflineAnimeModel( - "unknown", - "0", - "??", - "??", - "??", - "movie", - "hmm", - isOngoing = false, - isUserScored = false, - null, - null - ) + return try { + loadOfflineAnimeModelCompat(downloadedType) + } catch (e: Exception) { + Logger.log("Error loading media.json: ${e.message}") + Logger.log(e) + Injekt.get().logException(e) + OfflineAnimeModel( + "unknown", + "0", + "??", + "??", + "??", + "movie", + "hmm", + isOngoing = false, + isUserScored = false, + null, + null + ) + } } } } diff --git a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeModel.kt b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeModel.kt index 4823e2af..5e936b83 100644 --- a/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeModel.kt +++ b/app/src/main/java/ani/dantotsu/download/anime/OfflineAnimeModel.kt @@ -3,7 +3,7 @@ package ani.dantotsu.download.anime import android.net.Uri data class OfflineAnimeModel( - val title: String, + var title: String, val score: String, val totalEpisode: String, val totalEpisodeList: String, diff --git a/app/src/main/java/ani/dantotsu/download/manga/MangaDownloaderService.kt b/app/src/main/java/ani/dantotsu/download/manga/MangaDownloaderService.kt index 188c9dc3..08ddb3a7 100644 --- a/app/src/main/java/ani/dantotsu/download/manga/MangaDownloaderService.kt +++ b/app/src/main/java/ani/dantotsu/download/manga/MangaDownloaderService.kt @@ -10,19 +10,20 @@ import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.graphics.Bitmap import android.os.Build -import android.os.Environment import android.os.IBinder import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat +import androidx.documentfile.provider.DocumentFile import ani.dantotsu.R import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager -import ani.dantotsu.util.Logger +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaType import ani.dantotsu.media.manga.ImageData import ani.dantotsu.media.manga.MangaReadFragment.Companion.ACTION_DOWNLOAD_FAILED import ani.dantotsu.media.manga.MangaReadFragment.Companion.ACTION_DOWNLOAD_FINISHED @@ -30,6 +31,10 @@ import ani.dantotsu.media.manga.MangaReadFragment.Companion.ACTION_DOWNLOAD_PROG import ani.dantotsu.media.manga.MangaReadFragment.Companion.ACTION_DOWNLOAD_STARTED import ani.dantotsu.media.manga.MangaReadFragment.Companion.EXTRA_CHAPTER_NUMBER import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.deleteRecursively +import com.anggrayudi.storage.file.forceDelete +import com.anggrayudi.storage.file.openOutputStream import com.google.gson.GsonBuilder import com.google.gson.InstanceCreator import eu.kanade.tachiyomi.data.notification.Notifications.CHANNEL_DOWNLOADER_PROGRESS @@ -39,7 +44,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async @@ -51,8 +55,6 @@ import kotlinx.coroutines.withContext import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.util.Queue @@ -189,13 +191,20 @@ class MangaDownloaderService : Service() { true } - //val deferredList = mutableListOf>() val deferredMap = mutableMapOf>() builder.setContentText("Downloading ${task.title} - ${task.chapter}") if (notifi) { notificationManager.notify(NOTIFICATION_ID, builder.build()) } + getSubDirectory( + this@MangaDownloaderService, + MediaType.MANGA, + false, + task.title, + task.chapter + )?.deleteRecursively(this@MangaDownloaderService) + // Loop through each ImageData object from the task var farthest = 0 for ((index, image) in task.imageData.withIndex()) { @@ -211,8 +220,7 @@ class MangaDownloaderService : Service() { while (bitmap == null && retryCount < task.retries) { bitmap = image.fetchAndProcessImage( image.page, - image.source, - this@MangaDownloaderService + image.source ) retryCount++ } @@ -246,7 +254,7 @@ class MangaDownloaderService : Service() { DownloadedType( task.title, task.chapter, - DownloadedType.Type.MANGA + MediaType.MANGA ) ) broadcastDownloadFinished(task.chapter) @@ -264,24 +272,18 @@ class MangaDownloaderService : Service() { private fun saveToDisk(fileName: String, bitmap: Bitmap, title: String, chapter: String) { try { // Define the directory within the private external storage space - val directory = File( - this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/$title/$chapter" - ) - - if (!directory.exists()) { - directory.mkdirs() - } - - // Create a file reference within that directory for your image - val file = File(directory, fileName) + val directory = getSubDirectory(this, MediaType.MANGA, false, title, chapter) + ?: throw Exception("Directory not found") + directory.findFile(fileName)?.forceDelete(this) + // Create a file reference within that directory for the image + val file = + directory.createFile("image/jpeg", fileName) ?: throw Exception("File not created") // Use a FileOutputStream to write the bitmap to the file - FileOutputStream(file).use { outputStream -> + file.openOutputStream(this, false).use { outputStream -> + if (outputStream == null) throw Exception("Output stream is null") bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) } - - } catch (e: Exception) { println("Exception while saving image: ${e.message}") snackString("Exception while saving image: ${e.message}") @@ -292,13 +294,12 @@ class MangaDownloaderService : Service() { @OptIn(DelicateCoroutinesApi::class) private fun saveMediaInfo(task: DownloadTask) { launchIO { - val directory = File( - getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/${task.title}" - ) - if (!directory.exists()) directory.mkdirs() - - val file = File(directory, "media.json") + val directory = + getSubDirectory(this@MangaDownloaderService, MediaType.MANGA, false, task.title) + ?: throw Exception("Directory not found") + directory.findFile("media.json")?.forceDelete(this@MangaDownloaderService) + val file = directory.createFile("application/json", "media.json") + ?: throw Exception("File not created") val gson = GsonBuilder() .registerTypeAdapter(SChapter::class.java, InstanceCreator { SChapterImpl() // Provide an instance of SChapterImpl @@ -313,7 +314,10 @@ class MangaDownloaderService : Service() { val jsonString = gson.toJson(media) withContext(Dispatchers.Main) { try { - file.writeText(jsonString) + file.openOutputStream(this@MangaDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") + output.write(jsonString.toByteArray()) + } } catch (e: android.system.ErrnoException) { e.printStackTrace() Toast.makeText( @@ -328,7 +332,7 @@ class MangaDownloaderService : Service() { } - private suspend fun downloadImage(url: String, directory: File, name: String): String? = + private suspend fun downloadImage(url: String, directory: DocumentFile, name: String): String? = withContext(Dispatchers.IO) { var connection: HttpURLConnection? = null println("Downloading url $url") @@ -338,14 +342,16 @@ class MangaDownloaderService : Service() { if (connection.responseCode != HttpURLConnection.HTTP_OK) { throw Exception("Server returned HTTP ${connection.responseCode} ${connection.responseMessage}") } - - val file = File(directory, name) - FileOutputStream(file).use { output -> + directory.findFile(name)?.forceDelete(this@MangaDownloaderService) + val file = + directory.createFile("image/jpeg", name) ?: throw Exception("File not created") + file.openOutputStream(this@MangaDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") connection.inputStream.use { input -> input.copyTo(output) } } - return@withContext file.absolutePath + return@withContext file.uri.toString() } catch (e: Exception) { e.printStackTrace() withContext(Dispatchers.Main) { diff --git a/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaAdapter.kt b/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaAdapter.kt index 4ef12c03..612f81e0 100644 --- a/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaAdapter.kt +++ b/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaAdapter.kt @@ -1,6 +1,5 @@ package ani.dantotsu.download.manga -import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View @@ -37,7 +36,6 @@ class OfflineMangaAdapter( return position.toLong() } - @SuppressLint("SetTextI18n") override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view: View = convertView ?: when (style) { @@ -50,7 +48,6 @@ class OfflineMangaAdapter( val imageView = view.findViewById(R.id.itemCompactImage) val titleTextView = view.findViewById(R.id.itemCompactTitle) val itemScore = view.findViewById(R.id.itemCompactScore) - val itemScoreBG = view.findViewById(R.id.itemCompactScoreBG) val ongoing = view.findViewById(R.id.itemCompactOngoing) val totalChapter = view.findViewById(R.id.itemCompactTotal) val typeImage = view.findViewById(R.id.itemCompactTypeImage) @@ -60,14 +57,15 @@ class OfflineMangaAdapter( if (style == 0) { val bannerView = view.findViewById(R.id.itemCompactBanner) // for large view val chapters = view.findViewById(R.id.itemTotal) - chapters.text = " Chapters" - bannerView.setImageURI(item.banner) + val text = " ${context.getString(R.string.chapters)}" + chapters.text = text + bannerView.setImageURI(item.banner ?: item.image) totalChapter.text = item.totalChapter } else if (style == 1) { val readChapter = view.findViewById(R.id.itemCompactUserProgress) // for compact view readChapter.text = item.readChapter - totalChapter.text = " | " + item.totalChapter + totalChapter.text = context.getString(R.string.total_divider, item.totalChapter) } // Bind item data to the views diff --git a/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaFragment.kt b/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaFragment.kt index 0c97a8df..36e90e60 100644 --- a/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaFragment.kt +++ b/app/src/main/java/ani/dantotsu/download/manga/OfflineMangaFragment.kt @@ -3,10 +3,8 @@ package ani.dantotsu.download.manga import android.content.Intent import android.net.Uri import android.os.Bundle -import android.os.Environment import android.text.Editable import android.text.TextWatcher -import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -20,25 +18,35 @@ import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.marginBottom import androidx.fragment.app.Fragment +import androidx.lifecycle.lifecycleScope import ani.dantotsu.R import ani.dantotsu.bottomBar import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.currActivity import ani.dantotsu.currContext +import ani.dantotsu.download.DownloadCompat +import ani.dantotsu.download.DownloadCompat.Companion.loadOfflineMangaModelCompat import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager +import ani.dantotsu.download.DownloadsManager.Companion.compareName +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory +import ani.dantotsu.download.findValidName +import ani.dantotsu.getThemeColor import ani.dantotsu.initActivity -import ani.dantotsu.util.Logger import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.media.MediaType import ani.dantotsu.navBarHeight import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.settings.SettingsDialogFragment import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.openInputStream import com.google.android.material.card.MaterialCardView import com.google.android.material.imageview.ShapeableImageView import com.google.android.material.textfield.TextInputLayout @@ -46,9 +54,13 @@ import com.google.gson.GsonBuilder import com.google.gson.InstanceCreator import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SChapterImpl +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { @@ -57,6 +69,7 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { private lateinit var gridView: GridView private lateinit var adapter: OfflineMangaAdapter private lateinit var total: TextView + private var downloadsJob: Job = Job() override fun onCreateView( inflater: LayoutInflater, @@ -72,9 +85,7 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { textInputLayout.boxBackgroundColor = semiTransparentColor val materialCardView = view.findViewById(R.id.offlineMangaAvatarContainer) materialCardView.setCardBackgroundColor(semiTransparentColor) - val typedValue = TypedValue() - requireContext().theme?.resolveAttribute(android.R.attr.windowBackground, typedValue, true) - val color = typedValue.data + val color = requireContext().getThemeColor(android.R.attr.windowBackground) val animeUserAvatar = view.findViewById(R.id.offlineMangaUserAvatar) animeUserAvatar.setSafeOnClickListener { @@ -146,11 +157,11 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { private fun grid() { gridView.visibility = View.VISIBLE - getDownloads() val fadeIn = AlphaAnimation(0f, 1f) fadeIn.duration = 300 // animations pog gridView.layoutAnimation = LayoutAnimationController(fadeIn) adapter = OfflineMangaAdapter(requireContext(), downloads, this) + getDownloads() gridView.adapter = adapter gridView.scheduleLayoutAnimation() total.text = @@ -159,17 +170,18 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { // Get the OfflineMangaModel that was clicked val item = adapter.getItem(position) as OfflineMangaModel val media = - downloadManager.mangaDownloadedTypes.firstOrNull { it.title == item.title } - ?: downloadManager.novelDownloadedTypes.firstOrNull { it.title == item.title } + downloadManager.mangaDownloadedTypes.firstOrNull { it.titleName.compareName(item.title) } + ?: downloadManager.novelDownloadedTypes.firstOrNull { it.titleName.compareName(item.title) } media?.let { - - ContextCompat.startActivity( - requireActivity(), - Intent(requireContext(), MediaDetailsActivity::class.java) - .putExtra("media", getMedia(it)) - .putExtra("download", true), - null - ) + lifecycleScope.launch { + ContextCompat.startActivity( + requireActivity(), + Intent(requireContext(), MediaDetailsActivity::class.java) + .putExtra("media", getMedia(it)) + .putExtra("download", true), + null + ) + } } ?: run { snackString("no media found") } @@ -178,11 +190,11 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { gridView.setOnItemLongClickListener { _, _, position, _ -> // Get the OfflineMangaModel that was clicked val item = adapter.getItem(position) as OfflineMangaModel - val type: DownloadedType.Type = - if (downloadManager.mangaDownloadedTypes.any { it.title == item.title }) { - DownloadedType.Type.MANGA + val type: MediaType = + if (downloadManager.mangaDownloadedTypes.any { it.titleName == item.title }) { + MediaType.MANGA } else { - DownloadedType.Type.NOVEL + MediaType.NOVEL } // Alert dialog to confirm deletion val builder = @@ -192,9 +204,6 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { builder.setPositiveButton("Yes") { _, _ -> downloadManager.removeMedia(item.title, type) getDownloads() - adapter.setItems(downloads) - total.text = - if (gridView.count > 0) "Manga and Novels (${gridView.count})" else "Empty List" } builder.setNegativeButton("No") { _, _ -> // Do nothing @@ -223,7 +232,6 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { gridView.setOnScrollListener(object : AbsListView.OnScrollListener { override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { - // Implement behavior for different scroll states if needed } override fun onScroll( @@ -234,7 +242,7 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { ) { val first = view.getChildAt(0) val visibility = first != null && first.top < 0 - scrollTop.visibility = if (visibility) View.VISIBLE else View.GONE + scrollTop.isVisible = visibility scrollTop.translationY = -(navBarHeight + bottomBar.height + bottomBar.marginBottom).toFloat() } @@ -246,7 +254,6 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { override fun onResume() { super.onResume() getDownloads() - adapter.notifyDataSetChanged() } override fun onPause() { @@ -266,46 +273,62 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { private fun getDownloads() { downloads = listOf() - val mangaTitles = downloadManager.mangaDownloadedTypes.map { it.title }.distinct() - val newMangaDownloads = mutableListOf() - for (title in mangaTitles) { - val tDownloads = downloadManager.mangaDownloadedTypes.filter { it.title == title } - val download = tDownloads.first() - val offlineMangaModel = loadOfflineMangaModel(download) - newMangaDownloads += offlineMangaModel + if (downloadsJob.isActive) { + downloadsJob.cancel() } - downloads = newMangaDownloads - val novelTitles = downloadManager.novelDownloadedTypes.map { it.title }.distinct() - val newNovelDownloads = mutableListOf() - for (title in novelTitles) { - val tDownloads = downloadManager.novelDownloadedTypes.filter { it.title == title } - val download = tDownloads.first() - val offlineMangaModel = loadOfflineMangaModel(download) - newNovelDownloads += offlineMangaModel + downloads = listOf() + downloadsJob = Job() + CoroutineScope(Dispatchers.IO + downloadsJob).launch { + val mangaTitles = downloadManager.mangaDownloadedTypes.map { it.titleName.findValidName() }.distinct() + val newMangaDownloads = mutableListOf() + for (title in mangaTitles) { + val tDownloads = downloadManager.mangaDownloadedTypes.filter { it.titleName.findValidName() == title } + val download = tDownloads.firstOrNull() ?: continue + val offlineMangaModel = loadOfflineMangaModel(download) + newMangaDownloads += offlineMangaModel + } + downloads = newMangaDownloads + val novelTitles = downloadManager.novelDownloadedTypes.map { it.titleName }.distinct() + val newNovelDownloads = mutableListOf() + for (title in novelTitles) { + val tDownloads = downloadManager.novelDownloadedTypes.filter { it.titleName.findValidName() == title } + val download = tDownloads.firstOrNull() ?: continue + val offlineMangaModel = loadOfflineMangaModel(download) + newNovelDownloads += offlineMangaModel + } + downloads += newNovelDownloads + withContext(Dispatchers.Main) { + adapter.setItems(downloads) + total.text = + if (gridView.count > 0) "Manga and Novels (${gridView.count})" else "Empty List" + adapter.notifyDataSetChanged() + } } - downloads += newNovelDownloads } - private fun getMedia(downloadedType: DownloadedType): Media? { - val type = when (downloadedType.type) { - DownloadedType.Type.MANGA -> "Manga" - DownloadedType.Type.ANIME -> "Anime" - else -> "Novel" - } - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$type/${downloadedType.title}" - ) - //load media.json and convert to media class with gson + /** + * Load media.json file from the directory and convert it to Media class + * @param downloadedType DownloadedType object + * @return Media object + */ + private suspend fun getMedia(downloadedType: DownloadedType): Media? { return try { + val directory = getSubDirectory( + context ?: currContext()!!, downloadedType.type, + false, downloadedType.titleName + ) val gson = GsonBuilder() .registerTypeAdapter(SChapter::class.java, InstanceCreator { SChapterImpl() // Provide an instance of SChapterImpl }) .create() - val media = File(directory, "media.json") - val mediaJson = media.readText() + val media = directory?.findFile("media.json") + ?: return DownloadCompat.loadMediaCompat(downloadedType) + val mediaJson = + media.openInputStream(context ?: currContext()!!)?.bufferedReader().use { + it?.readText() + } gson.fromJson(mediaJson, Media::class.java) } catch (e: Exception) { Logger.log("Error loading media.json: ${e.message}") @@ -315,41 +338,38 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { } } - private fun loadOfflineMangaModel(downloadedType: DownloadedType): OfflineMangaModel { - val type = when (downloadedType.type) { - DownloadedType.Type.MANGA -> "Manga" - DownloadedType.Type.ANIME -> "Anime" - else -> "Novel" - } - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/$type/${downloadedType.title}" - ) + private suspend fun loadOfflineMangaModel(downloadedType: DownloadedType): OfflineMangaModel { + val type = downloadedType.type.asText() //load media.json and convert to media class with gson try { + val directory = getSubDirectory( + context ?: currContext()!!, downloadedType.type, + false, downloadedType.titleName + ) val mediaModel = getMedia(downloadedType)!! - val cover = File(directory, "cover.jpg") - val coverUri: Uri? = if (cover.exists()) { - Uri.fromFile(cover) + val cover = directory?.findFile("cover.jpg") + val coverUri: Uri? = if (cover?.exists() == true) { + cover.uri } else null - val banner = File(directory, "banner.jpg") - val bannerUri: Uri? = if (banner.exists()) { - Uri.fromFile(banner) + val banner = directory?.findFile("banner.jpg") + val bannerUri: Uri? = if (banner?.exists() == true) { + banner.uri } else null + if (coverUri == null && bannerUri == null) throw Exception("No cover or banner found, probably compat") val title = mediaModel.mainName() val score = ((if (mediaModel.userScore == 0) (mediaModel.meanScore ?: 0) else mediaModel.userScore) / 10.0).toString() val isOngoing = mediaModel.status == currActivity()!!.getString(R.string.status_releasing) val isUserScored = mediaModel.userScore != 0 - val readchapter = (mediaModel.userProgress ?: "~").toString() - val totalchapter = "${mediaModel.manga?.totalChapters ?: "??"}" + val readChapter = (mediaModel.userProgress ?: "~").toString() + val totalChapter = "${mediaModel.manga?.totalChapters ?: "??"}" val chapters = " Chapters" return OfflineMangaModel( title, score, - totalchapter, - readchapter, + totalChapter, + readChapter, type, chapters, isOngoing, @@ -358,21 +378,25 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener { bannerUri ) } catch (e: Exception) { - Logger.log("Error loading media.json: ${e.message}") - Logger.log(e) - Injekt.get().logException(e) - return OfflineMangaModel( - "unknown", - "0", - "??", - "??", - "movie", - "hmm", - isOngoing = false, - isUserScored = false, - null, - null - ) + return try { + loadOfflineMangaModelCompat(downloadedType) + } catch (e: Exception) { + Logger.log("Error loading media.json: ${e.message}") + Logger.log(e) + Injekt.get().logException(e) + return OfflineMangaModel( + "unknown", + "0", + "??", + "??", + "movie", + "hmm", + isOngoing = false, + isUserScored = false, + null, + null + ) + } } } } diff --git a/app/src/main/java/ani/dantotsu/download/novel/NovelDownloaderService.kt b/app/src/main/java/ani/dantotsu/download/novel/NovelDownloaderService.kt index 0c3575a3..bc1d8e31 100644 --- a/app/src/main/java/ani/dantotsu/download/novel/NovelDownloaderService.kt +++ b/app/src/main/java/ani/dantotsu/download/novel/NovelDownloaderService.kt @@ -9,21 +9,25 @@ import android.content.IntentFilter import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.os.Build -import android.os.Environment import android.os.IBinder import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat +import androidx.documentfile.provider.DocumentFile import ani.dantotsu.R import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager -import ani.dantotsu.util.Logger +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaType import ani.dantotsu.media.novel.NovelReadFragment import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.forceDelete +import com.anggrayudi.storage.file.openOutputStream import com.google.gson.GsonBuilder import com.google.gson.InstanceCreator import eu.kanade.tachiyomi.data.notification.Notifications @@ -33,7 +37,6 @@ import eu.kanade.tachiyomi.source.model.SChapterImpl import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch @@ -46,8 +49,6 @@ import okio.sink import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.io.FileOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.URL @@ -64,7 +65,7 @@ class NovelDownloaderService : Service() { private val mutex = Mutex() private var isCurrentlyProcessing = false - val networkHelper = Injekt.get() + private val networkHelper = Injekt.get() override fun onBind(intent: Intent?): IBinder? { // This is only required for bound services. @@ -247,27 +248,30 @@ class NovelDownloaderService : Service() { networkHelper.downloadClient.newCall(request).execute().use { response -> // Ensure the response is successful and has a body - if (!response.isSuccessful || response.body == null) { + if (!response.isSuccessful) { throw IOException("Failed to download file: ${response.message}") } + val directory = getSubDirectory( + this@NovelDownloaderService, + MediaType.NOVEL, + false, + task.title, + task.chapter + ) ?: throw Exception("Directory not found") + directory.findFile("0.epub")?.forceDelete(this@NovelDownloaderService) - val file = File( - this@NovelDownloaderService.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/${task.title}/${task.chapter}/0.epub" - ) - - // Create directories if they don't exist - file.parentFile?.takeIf { !it.exists() }?.mkdirs() - - // Overwrite existing file - if (file.exists()) file.delete() + val file = directory.createFile("application/epub+zip", "0.epub") + ?: throw Exception("File not created") //download cover task.coverUrl?.let { file.parentFile?.let { it1 -> downloadImage(it, it1, "cover.jpg") } } + val outputStream = + this@NovelDownloaderService.contentResolver.openOutputStream(file.uri) + ?: throw Exception("Could not open OutputStream") - val sink = file.sink().buffer() + val sink = outputStream.sink().buffer() val responseBody = response.body val totalBytes = responseBody.contentLength() var downloadedBytes = 0L @@ -335,7 +339,7 @@ class NovelDownloaderService : Service() { DownloadedType( task.title, task.chapter, - DownloadedType.Type.NOVEL + MediaType.NOVEL ) ) broadcastDownloadFinished(task.originalLink) @@ -352,13 +356,16 @@ class NovelDownloaderService : Service() { @OptIn(DelicateCoroutinesApi::class) private fun saveMediaInfo(task: DownloadTask) { launchIO { - val directory = File( - getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/${task.title}" - ) - if (!directory.exists()) directory.mkdirs() - - val file = File(directory, "media.json") + val directory = + getSubDirectory( + this@NovelDownloaderService, + MediaType.NOVEL, + false, + task.title + ) ?: throw Exception("Directory not found") + directory.findFile("media.json")?.forceDelete(this@NovelDownloaderService) + val file = directory.createFile("application/json", "media.json") + ?: throw Exception("File not created") val gson = GsonBuilder() .registerTypeAdapter(SChapter::class.java, InstanceCreator { SChapterImpl() // Provide an instance of SChapterImpl @@ -372,33 +379,47 @@ class NovelDownloaderService : Service() { val jsonString = gson.toJson(media) withContext(Dispatchers.Main) { - file.writeText(jsonString) + try { + file.openOutputStream(this@NovelDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") + output.write(jsonString.toByteArray()) + } + } catch (e: android.system.ErrnoException) { + e.printStackTrace() + Toast.makeText( + this@NovelDownloaderService, + "Error while saving: ${e.localizedMessage}", + Toast.LENGTH_LONG + ).show() + } } } } } - private suspend fun downloadImage(url: String, directory: File, name: String): String? = + private suspend fun downloadImage(url: String, directory: DocumentFile, name: String): String? = withContext( Dispatchers.IO ) { var connection: HttpURLConnection? = null - println("Downloading url $url") + Logger.log("Downloading url $url") try { connection = URL(url).openConnection() as HttpURLConnection connection.connect() if (connection.responseCode != HttpURLConnection.HTTP_OK) { throw Exception("Server returned HTTP ${connection.responseCode} ${connection.responseMessage}") } - - val file = File(directory, name) - FileOutputStream(file).use { output -> + directory.findFile(name)?.forceDelete(this@NovelDownloaderService) + val file = + directory.createFile("image/jpeg", name) ?: throw Exception("File not created") + file.openOutputStream(this@NovelDownloaderService, false).use { output -> + if (output == null) throw Exception("Output stream is null") connection.inputStream.use { input -> input.copyTo(output) } } - return@withContext file.absolutePath + return@withContext file.uri.toString() } catch (e: Exception) { e.printStackTrace() withContext(Dispatchers.Main) { @@ -473,7 +494,6 @@ class NovelDownloaderService : Service() { } object NovelServiceDataSingleton { - var sourceMedia: Media? = null var downloadQueue: Queue = ConcurrentLinkedQueue() @Volatile diff --git a/app/src/main/java/ani/dantotsu/download/video/ExoplayerDownloadService.kt b/app/src/main/java/ani/dantotsu/download/video/ExoplayerDownloadService.kt deleted file mode 100644 index 4add998c..00000000 --- a/app/src/main/java/ani/dantotsu/download/video/ExoplayerDownloadService.kt +++ /dev/null @@ -1,37 +0,0 @@ -package ani.dantotsu.download.video - -import android.app.Notification -import androidx.media3.common.util.UnstableApi -import androidx.media3.exoplayer.offline.Download -import androidx.media3.exoplayer.offline.DownloadManager -import androidx.media3.exoplayer.offline.DownloadNotificationHelper -import androidx.media3.exoplayer.offline.DownloadService -import androidx.media3.exoplayer.scheduler.PlatformScheduler -import androidx.media3.exoplayer.scheduler.Scheduler -import ani.dantotsu.R - -@UnstableApi -class ExoplayerDownloadService : - DownloadService(1, 2000, "download_service", R.string.downloads, 0) { - companion object { - private const val JOB_ID = 1 - private const val FOREGROUND_NOTIFICATION_ID = 1 - } - - override fun getDownloadManager(): DownloadManager = Helper.downloadManager(this) - - override fun getScheduler(): Scheduler = PlatformScheduler(this, JOB_ID) - - override fun getForegroundNotification( - downloads: MutableList, - notMetRequirements: Int - ): Notification = - DownloadNotificationHelper(this, "download_service").buildProgressNotification( - this, - R.drawable.mono, - null, - null, - downloads, - notMetRequirements - ) -} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/download/video/Helper.kt b/app/src/main/java/ani/dantotsu/download/video/Helper.kt index 4e82e76c..b207d634 100644 --- a/app/src/main/java/ani/dantotsu/download/video/Helper.kt +++ b/app/src/main/java/ani/dantotsu/download/video/Helper.kt @@ -7,15 +7,10 @@ import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager -import android.net.Uri import android.os.Build -import android.util.Log import androidx.annotation.OptIn import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat -import androidx.media3.common.C -import androidx.media3.common.MediaItem -import androidx.media3.common.MimeTypes import androidx.media3.common.util.UnstableApi import androidx.media3.database.StandaloneDatabaseProvider import androidx.media3.datasource.DataSource @@ -23,11 +18,8 @@ import androidx.media3.datasource.HttpDataSource import androidx.media3.datasource.cache.NoOpCacheEvictor import androidx.media3.datasource.cache.SimpleCache import androidx.media3.datasource.okhttp.OkHttpDataSource -import androidx.media3.exoplayer.DefaultRenderersFactory import androidx.media3.exoplayer.offline.Download -import androidx.media3.exoplayer.offline.DownloadHelper import androidx.media3.exoplayer.offline.DownloadManager -import androidx.media3.exoplayer.offline.DownloadService import androidx.media3.exoplayer.scheduler.Requirements import ani.dantotsu.R import ani.dantotsu.defaultHeaders @@ -35,93 +27,103 @@ import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager import ani.dantotsu.download.anime.AnimeDownloaderService import ani.dantotsu.download.anime.AnimeServiceDataSingleton -import ani.dantotsu.logError import ani.dantotsu.media.Media -import ani.dantotsu.okHttpClient +import ani.dantotsu.media.MediaType import ani.dantotsu.parsers.Subtitle -import ani.dantotsu.parsers.SubtitleType import ani.dantotsu.parsers.Video -import ani.dantotsu.parsers.VideoType import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.network.NetworkHelper import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.File -import java.io.IOException -import java.util.concurrent.* +import java.util.concurrent.Executors +@SuppressLint("UnsafeOptInUsageError") object Helper { - - private var simpleCache: SimpleCache? = null - - @SuppressLint("UnsafeOptInUsageError") - fun downloadVideo(context: Context, video: Video, subtitle: Subtitle?) { - val dataSourceFactory = DataSource.Factory { - val dataSource: HttpDataSource = - OkHttpDataSource.Factory(okHttpClient).createDataSource() - defaultHeaders.forEach { - dataSource.setRequestProperty(it.key, it.value) - } - video.file.headers.forEach { - dataSource.setRequestProperty(it.key, it.value) - } - dataSource - } - val mimeType = when (video.format) { - VideoType.M3U8 -> MimeTypes.APPLICATION_M3U8 - VideoType.DASH -> MimeTypes.APPLICATION_MPD - else -> MimeTypes.APPLICATION_MP4 - } - - val builder = MediaItem.Builder().setUri(video.file.url).setMimeType(mimeType) - var sub: MediaItem.SubtitleConfiguration? = null - if (subtitle != null) { - sub = MediaItem.SubtitleConfiguration - .Builder(Uri.parse(subtitle.file.url)) - .setSelectionFlags(C.SELECTION_FLAG_FORCED) - .setMimeType( - when (subtitle.type) { - SubtitleType.VTT -> MimeTypes.TEXT_VTT - SubtitleType.ASS -> MimeTypes.TEXT_SSA - SubtitleType.SRT -> MimeTypes.APPLICATION_SUBRIP - SubtitleType.UNKNOWN -> MimeTypes.TEXT_SSA - } + @OptIn(UnstableApi::class) + fun startAnimeDownloadService( + context: Context, + title: String, + episode: String, + video: Video, + subtitle: List> = emptyList(), + audio: List> = emptyList(), + sourceMedia: Media? = null, + episodeImage: String? = null + ) { + if (!isNotificationPermissionGranted(context)) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + ActivityCompat.requestPermissions( + context as Activity, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + 1 ) - .build() + } } - if (sub != null) builder.setSubtitleConfigurations(mutableListOf(sub)) - val mediaItem = builder.build() - val downloadHelper = DownloadHelper.forMediaItem( - context, - mediaItem, - DefaultRenderersFactory(context), - dataSourceFactory - ) - downloadHelper.prepare(object : DownloadHelper.Callback { - override fun onPrepared(helper: DownloadHelper) { - helper.getDownloadRequest(null).let { - DownloadService.sendAddDownload( - context, - ExoplayerDownloadService::class.java, - it, - false - ) - } - } - override fun onPrepareError(helper: DownloadHelper, e: IOException) { - logError(e) + val animeDownloadTask = AnimeDownloaderService.AnimeDownloadTask( + title, + episode, + video, + subtitle, + audio, + sourceMedia, + episodeImage + ) + + val downloadsManger = Injekt.get() + val downloadCheck = downloadsManger + .queryDownload(title, episode, MediaType.ANIME) + + if (downloadCheck) { + AlertDialog.Builder(context, R.style.MyPopup) + .setTitle("Download Exists") + .setMessage("A download for this episode already exists. Do you want to overwrite it?") + .setPositiveButton("Yes") { _, _ -> + PrefManager.getAnimeDownloadPreferences().edit() + .remove(animeDownloadTask.getTaskName()) + .apply() + downloadsManger.removeDownload( + DownloadedType( + title, + episode, + MediaType.ANIME + ) + ) { + AnimeServiceDataSingleton.downloadQueue.offer(animeDownloadTask) + if (!AnimeServiceDataSingleton.isServiceRunning) { + val intent = Intent(context, AnimeDownloaderService::class.java) + ContextCompat.startForegroundService(context, intent) + AnimeServiceDataSingleton.isServiceRunning = true + } + } + } + .setNegativeButton("No") { _, _ -> } + .show() + } else { + AnimeServiceDataSingleton.downloadQueue.offer(animeDownloadTask) + if (!AnimeServiceDataSingleton.isServiceRunning) { + val intent = Intent(context, AnimeDownloaderService::class.java) + ContextCompat.startForegroundService(context, intent) + AnimeServiceDataSingleton.isServiceRunning = true } - }) + } } - - private var download: DownloadManager? = null - private const val DOWNLOAD_CONTENT_DIRECTORY = "Anime_Downloads" + private fun isNotificationPermissionGranted(context: Context): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + return ActivityCompat.checkSelfPermission( + context, + Manifest.permission.POST_NOTIFICATIONS + ) == PackageManager.PERMISSION_GRANTED + } + return true + } @Synchronized @UnstableApi + @Deprecated("exoplayer download manager is no longer used") fun downloadManager(context: Context): DownloadManager { return download ?: let { val database = Injekt.get() @@ -175,96 +177,7 @@ object Helper { downloadManager } } - - private var downloadDirectory: File? = null - - @Synchronized - private fun getDownloadDirectory(context: Context): File { - if (downloadDirectory == null) { - downloadDirectory = context.getExternalFilesDir(null) - if (downloadDirectory == null) { - downloadDirectory = context.filesDir - } - } - return downloadDirectory!! - } - - @OptIn(UnstableApi::class) - fun startAnimeDownloadService( - context: Context, - title: String, - episode: String, - video: Video, - subtitle: Subtitle? = null, - sourceMedia: Media? = null, - episodeImage: String? = null - ) { - if (!isNotificationPermissionGranted(context)) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - ActivityCompat.requestPermissions( - context as Activity, - arrayOf(Manifest.permission.POST_NOTIFICATIONS), - 1 - ) - } - } - - val animeDownloadTask = AnimeDownloaderService.AnimeDownloadTask( - title, - episode, - video, - subtitle, - sourceMedia, - episodeImage - ) - - val downloadsManger = Injekt.get() - val downloadCheck = downloadsManger - .queryDownload(title, episode, DownloadedType.Type.ANIME) - - if (downloadCheck) { - AlertDialog.Builder(context, R.style.MyPopup) - .setTitle("Download Exists") - .setMessage("A download for this episode already exists. Do you want to overwrite it?") - .setPositiveButton("Yes") { _, _ -> - DownloadService.sendRemoveDownload( - context, - ExoplayerDownloadService::class.java, - PrefManager.getAnimeDownloadPreferences().getString( - animeDownloadTask.getTaskName(), - "" - ) ?: "", - false - ) - PrefManager.getAnimeDownloadPreferences().edit() - .remove(animeDownloadTask.getTaskName()) - .apply() - downloadsManger.removeDownload( - DownloadedType( - title, - episode, - DownloadedType.Type.ANIME - ) - ) - AnimeServiceDataSingleton.downloadQueue.offer(animeDownloadTask) - if (!AnimeServiceDataSingleton.isServiceRunning) { - val intent = Intent(context, AnimeDownloaderService::class.java) - ContextCompat.startForegroundService(context, intent) - AnimeServiceDataSingleton.isServiceRunning = true - } - } - .setNegativeButton("No") { _, _ -> } - .show() - } else { - AnimeServiceDataSingleton.downloadQueue.offer(animeDownloadTask) - if (!AnimeServiceDataSingleton.isServiceRunning) { - val intent = Intent(context, AnimeDownloaderService::class.java) - ContextCompat.startForegroundService(context, intent) - AnimeServiceDataSingleton.isServiceRunning = true - } - } - } - + @Deprecated("exoplayer download manager is no longer used") @OptIn(UnstableApi::class) fun getSimpleCache(context: Context): SimpleCache { return if (simpleCache == null) { @@ -276,14 +189,23 @@ object Helper { simpleCache!! } } - - private fun isNotificationPermissionGranted(context: Context): Boolean { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - return ActivityCompat.checkSelfPermission( - context, - Manifest.permission.POST_NOTIFICATIONS - ) == PackageManager.PERMISSION_GRANTED + @Synchronized + @Deprecated("exoplayer download manager is no longer used") + private fun getDownloadDirectory(context: Context): File { + if (downloadDirectory == null) { + downloadDirectory = context.getExternalFilesDir(null) + if (downloadDirectory == null) { + downloadDirectory = context.filesDir + } } - return true + return downloadDirectory!! } + @Deprecated("exoplayer download manager is no longer used") + private var download: DownloadManager? = null + @Deprecated("exoplayer download manager is no longer used") + private const val DOWNLOAD_CONTENT_DIRECTORY = "Anime_Downloads" + @Deprecated("exoplayer download manager is no longer used") + private var simpleCache: SimpleCache? = null + @Deprecated("exoplayer download manager is no longer used") + private var downloadDirectory: File? = null } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/home/AnimeFragment.kt b/app/src/main/java/ani/dantotsu/home/AnimeFragment.kt index c7434c96..f9a9f596 100644 --- a/app/src/main/java/ani/dantotsu/home/AnimeFragment.kt +++ b/app/src/main/java/ani/dantotsu/home/AnimeFragment.kt @@ -36,6 +36,7 @@ import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.statusBarHeight +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -204,7 +205,22 @@ class AnimeFragment : Fragment() { if (i) { model.getUpdated().observe(viewLifecycleOwner) { if (it != null) { - animePageAdapter.updateRecent(MediaAdaptor(0, it, requireActivity())) + animePageAdapter.updateRecent(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getMovies().observe(viewLifecycleOwner) { + if (it != null) { + animePageAdapter.updateMovies(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getTopRated().observe(viewLifecycleOwner) { + if (it != null) { + animePageAdapter.updateTopRated(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getMostFav().observe(viewLifecycleOwner) { + if (it != null) { + animePageAdapter.updateMostFav(MediaAdaptor(0, it, requireActivity()), it) } } if (animePageAdapter.trendingViewPager != null) { @@ -253,17 +269,29 @@ class AnimeFragment : Fragment() { true } + var running = false val live = Refresh.activity.getOrPut(this.hashCode()) { MutableLiveData(false) } live.observe(viewLifecycleOwner) { - if (it) { + if (it && !running) { + running = true scope.launch { withContext(Dispatchers.IO) { - getUserId(requireContext()) { - load() + Anilist.userid = PrefManager.getNullableVal(PrefName.AnilistUserId, null) + ?.toIntOrNull() + if (Anilist.userid == null) { + getUserId(requireContext()) { + load() + } + } else { + CoroutineScope(Dispatchers.IO).launch { + getUserId(requireContext()) { + load() + } + } } model.loaded = true model.loadTrending(1) - model.loadUpdated() + model.loadAll() model.loadPopular( "ANIME", sort = Anilist.sortBy[1], onList = PrefManager.getVal( PrefName.PopularAnimeList @@ -272,6 +300,7 @@ class AnimeFragment : Fragment() { } live.postValue(false) _binding?.animeRefresh?.isRefreshing = false + running = false } } } diff --git a/app/src/main/java/ani/dantotsu/home/AnimePageAdapter.kt b/app/src/main/java/ani/dantotsu/home/AnimePageAdapter.kt index 2c60b3ac..df0e0939 100644 --- a/app/src/main/java/ani/dantotsu/home/AnimePageAdapter.kt +++ b/app/src/main/java/ani/dantotsu/home/AnimePageAdapter.kt @@ -3,15 +3,17 @@ package ani.dantotsu.home import android.content.Intent import android.os.Handler import android.os.Looper -import android.util.TypedValue +import android.view.HapticFeedbackConstants import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LayoutAnimationController import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding +import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView @@ -21,10 +23,15 @@ import ani.dantotsu.R import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.currContext import ani.dantotsu.databinding.ItemAnimePageBinding +import ani.dantotsu.databinding.LayoutTrendingBinding +import ani.dantotsu.getAppString +import ani.dantotsu.getThemeColor import ani.dantotsu.loadImage import ani.dantotsu.media.CalendarActivity import ani.dantotsu.media.GenreActivity +import ani.dantotsu.media.Media import ani.dantotsu.media.MediaAdaptor +import ani.dantotsu.media.MediaListViewActivity import ani.dantotsu.media.SearchActivity import ani.dantotsu.profile.ProfileActivity import ani.dantotsu.px @@ -41,6 +48,7 @@ import com.google.android.material.textfield.TextInputLayout class AnimePageAdapter : RecyclerView.Adapter() { val ready = MutableLiveData(false) lateinit var binding: ItemAnimePageBinding + private lateinit var trendingBinding: LayoutTrendingBinding private var trendHandler: Handler? = null private lateinit var trendRun: Runnable var trendingViewPager: ViewPager2? = null @@ -53,32 +61,30 @@ class AnimePageAdapter : RecyclerView.Adapter(R.id.animeSearchBar) + val textInputLayout = holder.itemView.findViewById(R.id.searchBar) val currentColor = textInputLayout.boxBackgroundColor val semiTransparentColor = (currentColor and 0x00FFFFFF) or 0xA8000000.toInt() textInputLayout.boxBackgroundColor = semiTransparentColor val materialCardView = - holder.itemView.findViewById(R.id.animeUserAvatarContainer) + holder.itemView.findViewById(R.id.userAvatarContainer) materialCardView.setCardBackgroundColor(semiTransparentColor) - val typedValue = TypedValue() - currContext()?.theme?.resolveAttribute(android.R.attr.windowBackground, typedValue, true) - val color = typedValue.data - + val color = binding.root.context.getThemeColor(android.R.attr.windowBackground) textInputLayout.boxBackgroundColor = (color and 0x00FFFFFF) or 0x28000000 materialCardView.setCardBackgroundColor((color and 0x00FFFFFF) or 0x28000000) - binding.animeTitleContainer.updatePadding(top = statusBarHeight) + trendingBinding.titleContainer.updatePadding(top = statusBarHeight) - if (PrefManager.getVal(PrefName.SmallView)) binding.animeTrendingContainer.updateLayoutParams { + if (PrefManager.getVal(PrefName.SmallView)) trendingBinding.trendingContainer.updateLayoutParams { bottomMargin = (-108f).px } updateAvatar() - binding.animeSearchBar.hint = "ANIME" - binding.animeSearchBarText.setOnClickListener { + trendingBinding.searchBar.hint = "ANIME" + trendingBinding.searchBarText.setOnClickListener { ContextCompat.startActivity( it.context, Intent(it.context, SearchActivity::class.java).putExtra("type", "ANIME"), @@ -86,26 +92,28 @@ class AnimePageAdapter : RecyclerView.Adapter + trendingBinding.userAvatar.setOnLongClickListener { view -> + view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) ContextCompat.startActivity( view.context, Intent(view.context, ProfileActivity::class.java) - .putExtra("userId", Anilist.userid),null + .putExtra("userId", Anilist.userid), null ) false } - binding.animeNotificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE - binding.animeNotificationCount.text = Anilist.unreadNotificationCount.toString() + trendingBinding.searchBar.setEndIconOnClickListener { + trendingBinding.searchBar.performClick() + } + + trendingBinding.notificationCount.visibility = + if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE + trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString() listOf( binding.animePreviousSeason, @@ -134,8 +142,7 @@ class AnimePageAdapter : RecyclerView.Adapter) { + binding.apply { + init( + adaptor, + animeUpdatedRecyclerView, + animeUpdatedProgressBar, + animeRecently, + animeRecentlyMore, + getAppString(R.string.updated), + media + ) + animePopular.visibility = View.VISIBLE + animePopular.startAnimation(setSlideUp()) + if (adaptor.itemCount == 0) { + animeRecentlyContainer.visibility = View.GONE + } + } + + } + + fun updateMovies(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + animeMoviesRecyclerView, + animeMoviesProgressBar, + animeMovies, + animeMoviesMore, + getAppString(R.string.trending_movies), + media + ) + } + } + + fun updateTopRated(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + animeTopRatedRecyclerView, + animeTopRatedProgressBar, + animeTopRated, + animeTopRatedMore, + getAppString(R.string.top_rated), + media + ) + } + } + + fun updateMostFav(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + animeMostFavRecyclerView, + animeMostFavProgressBar, + animeMostFav, + animeMostFavMore, + getAppString(R.string.most_favourite), + media + ) + } + } + + fun init(adaptor: MediaAdaptor, recyclerView: RecyclerView, progress: View, title: View , more: View , string: String, media : MutableList) { + progress.visibility = View.GONE + recyclerView.adapter = adaptor + recyclerView.layoutManager = LinearLayoutManager( - binding.animeUpdatedRecyclerView.context, + recyclerView.context, LinearLayoutManager.HORIZONTAL, false ) - binding.animeUpdatedRecyclerView.visibility = View.VISIBLE - - binding.animeRecently.visibility = View.VISIBLE - binding.animeRecently.startAnimation(setSlideUp()) - binding.animeUpdatedRecyclerView.layoutAnimation = + MediaListViewActivity.passedMedia = media.toCollection(ArrayList()) + more.setOnClickListener { + ContextCompat.startActivity( + it.context, Intent(it.context, MediaListViewActivity::class.java) + .putExtra("title", string), + null + ) + } + recyclerView.visibility = View.VISIBLE + title.visibility = View.VISIBLE + more.visibility = View.VISIBLE + title.startAnimation(setSlideUp()) + more.startAnimation(setSlideUp()) + recyclerView.layoutAnimation = LayoutAnimationController(setSlideIn(), 0.25f) - binding.animePopular.visibility = View.VISIBLE - binding.animePopular.startAnimation(setSlideUp()) } fun updateAvatar() { if (Anilist.avatar != null && ready.value == true) { - binding.animeUserAvatar.loadImage(Anilist.avatar) - binding.animeUserAvatar.imageTintList = null + trendingBinding.userAvatar.loadImage(Anilist.avatar) + trendingBinding.userAvatar.imageTintList = null } } fun updateNotificationCount() { if (this::binding.isInitialized) { - binding.animeNotificationCount.visibility = + trendingBinding.notificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE - binding.animeNotificationCount.text = Anilist.unreadNotificationCount.toString() + trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString() } } diff --git a/app/src/main/java/ani/dantotsu/home/HomeFragment.kt b/app/src/main/java/ani/dantotsu/home/HomeFragment.kt index fae3fedf..fc729b9d 100644 --- a/app/src/main/java/ani/dantotsu/home/HomeFragment.kt +++ b/app/src/main/java/ani/dantotsu/home/HomeFragment.kt @@ -5,11 +5,13 @@ import android.content.Intent import android.graphics.drawable.Animatable import android.os.Build import android.os.Bundle +import android.view.HapticFeedbackConstants import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LayoutAnimationController import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.fragment.app.Fragment @@ -28,9 +30,11 @@ import ani.dantotsu.connections.anilist.AnilistHomeViewModel import ani.dantotsu.connections.anilist.getUserId import ani.dantotsu.currContext import ani.dantotsu.databinding.FragmentHomeBinding +import ani.dantotsu.home.status.UserStatusAdapter import ani.dantotsu.loadImage import ani.dantotsu.media.Media import ani.dantotsu.media.MediaAdaptor +import ani.dantotsu.media.MediaListViewActivity import ani.dantotsu.media.user.ListActivity import ani.dantotsu.navBarHeight import ani.dantotsu.profile.ProfileActivity @@ -39,12 +43,14 @@ import ani.dantotsu.setSlideIn import ani.dantotsu.setSlideUp import ani.dantotsu.settings.SettingsDialogFragment import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.settings.saving.PrefManager.asLiveBool import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.statusBarHeight +import ani.dantotsu.util.Logger +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlin.math.max import kotlin.math.min @@ -53,7 +59,6 @@ import kotlin.math.min class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! - override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, @@ -72,16 +77,21 @@ class HomeFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val scope = lifecycleScope + Logger.log("HomeFragment") fun load() { + Logger.log("Loading HomeFragment") if (activity != null && _binding != null) lifecycleScope.launch(Dispatchers.Main) { binding.homeUserName.text = Anilist.username binding.homeUserEpisodesWatched.text = Anilist.episodesWatched.toString() binding.homeUserChaptersRead.text = Anilist.chapterRead.toString() binding.homeUserAvatar.loadImage(Anilist.avatar) - if (!(PrefManager.getVal(PrefName.BannerAnimations) as Boolean)) binding.homeUserBg.pause() - blurImage(binding.homeUserBg, Anilist.bg) + val bannerAnimations: Boolean = PrefManager.getVal(PrefName.BannerAnimations) + blurImage( + if (bannerAnimations) binding.homeUserBg else binding.homeUserBgNoKen, + Anilist.bg + ) binding.homeUserDataProgressBar.visibility = View.GONE - binding.homeNotificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE + binding.homeNotificationCount.isVisible = Anilist.unreadNotificationCount > 0 binding.homeNotificationCount.text = Anilist.unreadNotificationCount.toString() binding.homeAnimeList.setOnClickListener { @@ -123,9 +133,10 @@ class HomeFragment : Fragment() { ) } binding.homeUserAvatarContainer.setOnLongClickListener { + it.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) ContextCompat.startActivity( requireContext(), Intent(requireContext(), ProfileActivity::class.java) - .putExtra("userId", Anilist.userid),null + .putExtra("userId", Anilist.userid), null ) false } @@ -134,6 +145,7 @@ class HomeFragment : Fragment() { bottomMargin = navBarHeight } binding.homeUserBg.updateLayoutParams { height += statusBarHeight } + binding.homeUserBgNoKen.updateLayoutParams { height += statusBarHeight } binding.homeTopContainer.updatePadding(top = statusBarHeight) var reached = false @@ -198,13 +210,16 @@ class HomeFragment : Fragment() { recyclerView: RecyclerView, progress: View, empty: View, - title: View + title: View, + more: View, + string: String ) { container.visibility = View.VISIBLE progress.visibility = View.VISIBLE recyclerView.visibility = View.GONE empty.visibility = View.GONE title.visibility = View.INVISIBLE + more.visibility = View.INVISIBLE mode.observe(viewLifecycleOwner) { recyclerView.visibility = View.GONE @@ -217,6 +232,14 @@ class HomeFragment : Fragment() { LinearLayoutManager.HORIZONTAL, false ) + more.setOnClickListener { i -> + MediaListViewActivity.passedMedia = it + ContextCompat.startActivity( + i.context, Intent(i.context, MediaListViewActivity::class.java) + .putExtra("title", string), + null + ) + } recyclerView.visibility = View.VISIBLE recyclerView.layoutAnimation = LayoutAnimationController(setSlideIn(), 0.25f) @@ -224,7 +247,9 @@ class HomeFragment : Fragment() { } else { empty.visibility = View.VISIBLE } + more.visibility = View.VISIBLE title.visibility = View.VISIBLE + more.startAnimation(setSlideUp()) title.startAnimation(setSlideUp()) progress.visibility = View.GONE } @@ -239,7 +264,9 @@ class HomeFragment : Fragment() { binding.homeWatchingRecyclerView, binding.homeWatchingProgressBar, binding.homeWatchingEmpty, - binding.homeContinueWatch + binding.homeContinueWatch, + binding.homeContinueWatchMore, + getString(R.string.continue_watching) ) binding.homeWatchingBrowseButton.setOnClickListener { bottomBar.selectTabAt(0) @@ -251,7 +278,9 @@ class HomeFragment : Fragment() { binding.homeFavAnimeRecyclerView, binding.homeFavAnimeProgressBar, binding.homeFavAnimeEmpty, - binding.homeFavAnime + binding.homeFavAnime, + binding.homeFavAnimeMore, + getString(R.string.fav_anime) ) initRecyclerView( @@ -260,7 +289,9 @@ class HomeFragment : Fragment() { binding.homePlannedAnimeRecyclerView, binding.homePlannedAnimeProgressBar, binding.homePlannedAnimeEmpty, - binding.homePlannedAnime + binding.homePlannedAnime, + binding.homePlannedAnimeMore, + getString(R.string.planned_anime) ) binding.homePlannedAnimeBrowseButton.setOnClickListener { bottomBar.selectTabAt(0) @@ -272,7 +303,9 @@ class HomeFragment : Fragment() { binding.homeReadingRecyclerView, binding.homeReadingProgressBar, binding.homeReadingEmpty, - binding.homeContinueRead + binding.homeContinueRead, + binding.homeContinueReadMore, + getString(R.string.continue_reading) ) binding.homeReadingBrowseButton.setOnClickListener { bottomBar.selectTabAt(2) @@ -284,7 +317,9 @@ class HomeFragment : Fragment() { binding.homeFavMangaRecyclerView, binding.homeFavMangaProgressBar, binding.homeFavMangaEmpty, - binding.homeFavManga + binding.homeFavManga, + binding.homeFavMangaMore, + getString(R.string.fav_manga) ) initRecyclerView( @@ -293,7 +328,9 @@ class HomeFragment : Fragment() { binding.homePlannedMangaRecyclerView, binding.homePlannedMangaProgressBar, binding.homePlannedMangaEmpty, - binding.homePlannedManga + binding.homePlannedManga, + binding.homePlannedMangaMore, + getString(R.string.planned_manga) ) binding.homePlannedMangaBrowseButton.setOnClickListener { bottomBar.selectTabAt(2) @@ -305,12 +342,87 @@ class HomeFragment : Fragment() { binding.homeRecommendedRecyclerView, binding.homeRecommendedProgressBar, binding.homeRecommendedEmpty, - binding.homeRecommended + binding.homeRecommended, + binding.homeRecommendedMore, + getString(R.string.recommended) ) + binding.homeUserStatusContainer.visibility = View.VISIBLE + binding.homeUserStatusProgressBar.visibility = View.VISIBLE + binding.homeUserStatusRecyclerView.visibility = View.GONE + model.getUserStatus().observe(viewLifecycleOwner) { + binding.homeUserStatusRecyclerView.visibility = View.GONE + if (it != null) { + if (it.isNotEmpty()) { + PrefManager.getLiveVal(PrefName.RefreshStatus, false).apply { + asLiveBool() + observe(viewLifecycleOwner) { _ -> + binding.homeUserStatusRecyclerView.adapter = UserStatusAdapter(it) + } + } + binding.homeUserStatusRecyclerView.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + binding.homeUserStatusRecyclerView.visibility = View.VISIBLE + binding.homeUserStatusRecyclerView.layoutAnimation = + LayoutAnimationController(setSlideIn(), 0.25f) + + } else { + binding.homeUserStatusContainer.visibility = View.GONE + } + binding.homeUserStatusProgressBar.visibility = View.GONE + } + + } + binding.homeHiddenItemsContainer.visibility = View.GONE + model.getHidden().observe(viewLifecycleOwner) { + if (it != null) { + if (it.isNotEmpty()) { + binding.homeHiddenItemsRecyclerView.adapter = + MediaAdaptor(0, it, requireActivity()) + binding.homeHiddenItemsRecyclerView.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + binding.homeContinueWatch.setOnLongClickListener { + binding.homeHiddenItemsContainer.visibility = View.VISIBLE + binding.homeHiddenItemsRecyclerView.layoutAnimation = + LayoutAnimationController(setSlideIn(), 0.25f) + true + } + binding.homeHiddenItemsMore.setSafeOnClickListener { _ -> + MediaListViewActivity.passedMedia = it + ContextCompat.startActivity( + requireActivity(), + Intent(requireActivity(), MediaListViewActivity::class.java) + .putExtra("title", getString(R.string.hidden)), + null + ) + } + binding.homeHiddenItemsTitle.setOnLongClickListener { + binding.homeHiddenItemsContainer.visibility = View.GONE + true + } + } else { + binding.homeContinueWatch.setOnLongClickListener { + snackString(getString(R.string.no_hidden_items)) + true + } + } + } else { + binding.homeContinueWatch.setOnLongClickListener { + snackString(getString(R.string.no_hidden_items)) + true + } + } + } binding.homeUserAvatarContainer.startAnimation(setSlideUp()) - model.empty.observe(viewLifecycleOwner) { + model.empty.observe(viewLifecycleOwner) + { binding.homeDantotsuContainer.visibility = if (it == true) View.VISIBLE else View.GONE (binding.homeDantotsuIcon.drawable as Animatable).start() binding.homeDantotsuContainer.startAnimation(setSlideUp()) @@ -327,7 +439,8 @@ class HomeFragment : Fragment() { "MangaContinue", "MangaFav", "MangaPlanned", - "Recommendation" + "Recommendation", + "UserStatus", ) val containers = arrayOf( @@ -337,26 +450,41 @@ class HomeFragment : Fragment() { binding.homeContinueReadingContainer, binding.homeFavMangaContainer, binding.homePlannedMangaContainer, - binding.homeRecommendedContainer + binding.homeRecommendedContainer, + binding.homeUserStatusContainer, ) - val live = Refresh.activity.getOrPut(1) { MutableLiveData(false) } - live.observe(viewLifecycleOwner) { - if (it) { + var running = false + val live = Refresh.activity.getOrPut(1) { MutableLiveData(true) } + live.observe(viewLifecycleOwner) + { + if (!running && it) { + running = true scope.launch { withContext(Dispatchers.IO) { //Get userData First - getUserId(requireContext()) { - load() + Anilist.userid = + PrefManager.getNullableVal(PrefName.AnilistUserId, null) + ?.toIntOrNull() + if (Anilist.userid == null) { + getUserId(requireContext()) { + load() + } + } else { + CoroutineScope(Dispatchers.IO).launch { + getUserId(requireContext()) { + load() + } + } } model.loaded = true - model.setListImages() + CoroutineScope(Dispatchers.IO).launch { + model.setListImages() + } var empty = true val homeLayoutShow: List = - PrefManager.getVal(PrefName.HomeLayoutShow) - runBlocking { - model.initHomePage() - } + PrefManager.getVal(PrefName.HomeLayout) + model.initHomePage() (array.indices).forEach { i -> if (homeLayoutShow.elementAt(i)) { empty = false @@ -368,14 +496,18 @@ class HomeFragment : Fragment() { } live.postValue(false) _binding?.homeRefresh?.isRefreshing = false + running = false } + binding.homeHiddenItemsContainer.visibility = View.GONE } + } } + override fun onResume() { if (!model.loaded) Refresh.activity[1]!!.postValue(true) if (_binding != null) { - binding.homeNotificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE + binding.homeNotificationCount.isVisible = Anilist.unreadNotificationCount > 0 binding.homeNotificationCount.text = Anilist.unreadNotificationCount.toString() } super.onResume() diff --git a/app/src/main/java/ani/dantotsu/home/MangaFragment.kt b/app/src/main/java/ani/dantotsu/home/MangaFragment.kt index 24eedc27..c878c584 100644 --- a/app/src/main/java/ani/dantotsu/home/MangaFragment.kt +++ b/app/src/main/java/ani/dantotsu/home/MangaFragment.kt @@ -33,6 +33,7 @@ import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.statusBarHeight +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -160,9 +161,35 @@ class MangaFragment : Fragment() { }) mangaPageAdapter.ready.observe(viewLifecycleOwner) { i -> if (i == true) { - model.getTrendingNovel().observe(viewLifecycleOwner) { + model.getPopularNovel().observe(viewLifecycleOwner) { if (it != null) { - mangaPageAdapter.updateNovel(MediaAdaptor(0, it, requireActivity())) + mangaPageAdapter.updateNovel(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getPopularManga().observe(viewLifecycleOwner) { + if (it != null) { + mangaPageAdapter.updateTrendingManga(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getPopularManhwa().observe(viewLifecycleOwner) { + if (it != null) { + mangaPageAdapter.updateTrendingManhwa( + MediaAdaptor( + 0, + it, + requireActivity() + ), it + ) + } + } + model.getTopRated().observe(viewLifecycleOwner) { + if (it != null) { + mangaPageAdapter.updateTopRated(MediaAdaptor(0, it, requireActivity()), it) + } + } + model.getMostFav().observe(viewLifecycleOwner) { + if (it != null) { + mangaPageAdapter.updateMostFav(MediaAdaptor(0, it, requireActivity()), it) } } if (mangaPageAdapter.trendingViewPager != null) { @@ -227,17 +254,29 @@ class MangaFragment : Fragment() { mangaPageAdapter.updateAvatar() } - val live = Refresh.activity.getOrPut(this.hashCode()) { MutableLiveData(false) } + var running = false + val live = Refresh.activity.getOrPut(this.hashCode()) { MutableLiveData(true) } live.observe(viewLifecycleOwner) { - if (it) { + if (!running && it) { + running = true scope.launch { withContext(Dispatchers.IO) { - getUserId(requireContext()) { - load() + Anilist.userid = PrefManager.getNullableVal(PrefName.AnilistUserId, null) + ?.toIntOrNull() + if (Anilist.userid == null) { + getUserId(requireContext()) { + load() + } + } else { + CoroutineScope(Dispatchers.IO).launch { + getUserId(requireContext()) { + load() + } + } } model.loaded = true model.loadTrending() - model.loadTrendingNovel() + model.loadAll() model.loadPopular( "MANGA", sort = Anilist.sortBy[1], onList = PrefManager.getVal( PrefName.PopularMangaList @@ -246,6 +285,7 @@ class MangaFragment : Fragment() { } live.postValue(false) _binding?.mangaRefresh?.isRefreshing = false + running = false } } } diff --git a/app/src/main/java/ani/dantotsu/home/MangaPageAdapter.kt b/app/src/main/java/ani/dantotsu/home/MangaPageAdapter.kt index 2aef3b6b..2e3e6a8c 100644 --- a/app/src/main/java/ani/dantotsu/home/MangaPageAdapter.kt +++ b/app/src/main/java/ani/dantotsu/home/MangaPageAdapter.kt @@ -3,13 +3,14 @@ package ani.dantotsu.home import android.content.Intent import android.os.Handler import android.os.Looper -import android.util.TypedValue +import android.view.HapticFeedbackConstants import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LayoutAnimationController import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.lifecycle.MutableLiveData @@ -19,11 +20,15 @@ import androidx.viewpager2.widget.ViewPager2 import ani.dantotsu.MediaPageTransformer import ani.dantotsu.R import ani.dantotsu.connections.anilist.Anilist -import ani.dantotsu.currContext import ani.dantotsu.databinding.ItemMangaPageBinding +import ani.dantotsu.databinding.LayoutTrendingBinding +import ani.dantotsu.getAppString +import ani.dantotsu.getThemeColor import ani.dantotsu.loadImage import ani.dantotsu.media.GenreActivity +import ani.dantotsu.media.Media import ani.dantotsu.media.MediaAdaptor +import ani.dantotsu.media.MediaListViewActivity import ani.dantotsu.media.SearchActivity import ani.dantotsu.profile.ProfileActivity import ani.dantotsu.px @@ -40,6 +45,7 @@ import com.google.android.material.textfield.TextInputLayout class MangaPageAdapter : RecyclerView.Adapter() { val ready = MutableLiveData(false) lateinit var binding: ItemMangaPageBinding + private lateinit var trendingBinding: LayoutTrendingBinding private var trendHandler: Handler? = null private lateinit var trendRun: Runnable var trendingViewPager: ViewPager2? = null @@ -52,33 +58,31 @@ class MangaPageAdapter : RecyclerView.Adapter(R.id.mangaSearchBar) + val textInputLayout = holder.itemView.findViewById(R.id.searchBar) val currentColor = textInputLayout.boxBackgroundColor val semiTransparentColor = (currentColor and 0x00FFFFFF) or 0xA8000000.toInt() textInputLayout.boxBackgroundColor = semiTransparentColor val materialCardView = - holder.itemView.findViewById(R.id.mangaUserAvatarContainer) + holder.itemView.findViewById(R.id.userAvatarContainer) materialCardView.setCardBackgroundColor(semiTransparentColor) - val typedValue = TypedValue() - currContext()?.theme?.resolveAttribute(android.R.attr.windowBackground, typedValue, true) - val color = typedValue.data + val color = binding.root.context.getThemeColor(android.R.attr.windowBackground) + textInputLayout.boxBackgroundColor = (color and 0x00FFFFFF) or 0x28000000 + materialCardView.setCardBackgroundColor((color and 0x00FFFFFF) or 0x28000000) - textInputLayout.boxBackgroundColor = (color and 0x00FFFFFF) or 0x28000000.toInt() - materialCardView.setCardBackgroundColor((color and 0x00FFFFFF) or 0x28000000.toInt()) + trendingBinding.titleContainer.updatePadding(top = statusBarHeight) - binding.mangaTitleContainer.updatePadding(top = statusBarHeight) - - if (PrefManager.getVal(PrefName.SmallView)) binding.mangaTrendingContainer.updateLayoutParams { + if (PrefManager.getVal(PrefName.SmallView)) trendingBinding.trendingContainer.updateLayoutParams { bottomMargin = (-108f).px } updateAvatar() - binding.mangaNotificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE - binding.mangaNotificationCount.text = Anilist.unreadNotificationCount.toString() - binding.mangaSearchBar.hint = "MANGA" - binding.mangaSearchBarText.setOnClickListener { + trendingBinding.notificationCount.isVisible = Anilist.unreadNotificationCount > 0 + trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString() + trendingBinding.searchBar.hint = "MANGA" + trendingBinding.searchBarText.setOnClickListener { ContextCompat.startActivity( it.context, Intent(it.context, SearchActivity::class.java).putExtra("type", "MANGA"), @@ -86,22 +90,23 @@ class MangaPageAdapter : RecyclerView.Adapter + trendingBinding.userAvatar.setOnLongClickListener { view -> + view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) ContextCompat.startActivity( view.context, Intent(view.context, ProfileActivity::class.java) - .putExtra("userId", Anilist.userid),null + .putExtra("userId", Anilist.userid), null ) false } - binding.mangaSearchBar.setEndIconOnClickListener { - binding.mangaSearchBarText.performClick() + trendingBinding.searchBar.setEndIconOnClickListener { + trendingBinding.searchBarText.performClick() } binding.mangaGenreImage.loadImage("https://s4.anilist.co/file/anilistcdn/media/manga/banner/105778-wk5qQ7zAaTGl.jpg") @@ -125,8 +130,7 @@ class MangaPageAdapter : RecyclerView.Adapter) { + binding.apply { + init( + adaptor, + mangaTrendingMangaRecyclerView, + mangaTrendingMangaProgressBar, + mangaTrendingManga, + mangaTrendingMangaMore, + getAppString(R.string.trending_manga), + media + ) + } + } + + fun updateTrendingManhwa(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + mangaTrendingManhwaRecyclerView, + mangaTrendingManhwaProgressBar, + mangaTrendingManhwa, + mangaTrendingManhwaMore, + getAppString(R.string.trending_manhwa), + media + ) + } + } + + fun updateNovel(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + mangaNovelRecyclerView, + mangaNovelProgressBar, + mangaNovel, + mangaNovelMore, + getAppString(R.string.trending_novel), + media + ) + } + } + + fun updateTopRated(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + mangaTopRatedRecyclerView, + mangaTopRatedProgressBar, + mangaTopRated, + mangaTopRatedMore, + getAppString(R.string.top_rated), + media + ) + } + } + + fun updateMostFav(adaptor: MediaAdaptor, media: MutableList) { + binding.apply { + init( + adaptor, + mangaMostFavRecyclerView, + mangaMostFavProgressBar, + mangaMostFav, + mangaMostFavMore, + getAppString(R.string.most_favourite), + media + ) + mangaPopular.visibility = View.VISIBLE + mangaPopular.startAnimation(setSlideUp()) + } + } + + fun init( + adaptor: MediaAdaptor, + recyclerView: RecyclerView, + progress: View, + title: View , + more: View , + string: String, + media : MutableList + ) { + progress.visibility = View.GONE + recyclerView.adapter = adaptor + recyclerView.layoutManager = LinearLayoutManager( - binding.mangaNovelRecyclerView.context, + recyclerView.context, LinearLayoutManager.HORIZONTAL, false ) - binding.mangaNovelRecyclerView.visibility = View.VISIBLE - - binding.mangaNovel.visibility = View.VISIBLE - binding.mangaNovel.startAnimation(setSlideUp()) - binding.mangaNovelRecyclerView.layoutAnimation = + more.setOnClickListener { + MediaListViewActivity.passedMedia = media.toCollection(ArrayList()) + ContextCompat.startActivity( + it.context, Intent(it.context, MediaListViewActivity::class.java) + .putExtra("title", string), + null + ) + } + recyclerView.visibility = View.VISIBLE + title.visibility = View.VISIBLE + more.visibility = View.VISIBLE + title.startAnimation(setSlideUp()) + more.startAnimation(setSlideUp()) + recyclerView.layoutAnimation = LayoutAnimationController(setSlideIn(), 0.25f) - binding.mangaPopular.visibility = View.VISIBLE - binding.mangaPopular.startAnimation(setSlideUp()) } fun updateAvatar() { if (Anilist.avatar != null && ready.value == true) { - binding.mangaUserAvatar.loadImage(Anilist.avatar) - binding.mangaUserAvatar.imageTintList = null + trendingBinding.userAvatar.loadImage(Anilist.avatar) + trendingBinding.userAvatar.imageTintList = null } } fun updateNotificationCount() { if (this::binding.isInitialized) { - binding.mangaNotificationCount.visibility = + trendingBinding.notificationCount.visibility = if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE - binding.mangaNotificationCount.text = Anilist.unreadNotificationCount.toString() + trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString() } } diff --git a/app/src/main/java/ani/dantotsu/home/status/CircleView.kt b/app/src/main/java/ani/dantotsu/home/status/CircleView.kt new file mode 100644 index 00000000..63986d83 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/CircleView.kt @@ -0,0 +1,83 @@ +package ani.dantotsu.home.status + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.util.AttributeSet +import android.view.View +import ani.dantotsu.getThemeColor + +class CircleView(context: Context, attrs: AttributeSet?) : View(context, attrs) { + private var parts: Int = 3 + private var gapAngle: Float = 12f + private val path = Path() + private var isUser = false + private var booleanList = listOf() + private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = 6f + strokeCap = Paint.Cap.ROUND + } + + @SuppressLint("DrawAllocation") + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val centerX = width / 2f + val centerY = height / 2f + val radius = centerX.coerceAtMost(centerY) - paint.strokeWidth / 2 + + val totalGapAngle = gapAngle * (parts) + val totalAngle = 360f - totalGapAngle + + + val primaryColor = context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + val secondColor = context.getThemeColor(com.google.android.material.R.attr.colorOnPrimary) + + fun setColor(int: Int) { + paint.color = if (int < booleanList.size && booleanList[int]) { + Color.GRAY + } else { + if (isUser) secondColor else primaryColor + } + canvas.drawPath(path, paint) + } + + if (parts == 1) { + path.addArc( + centerX - radius, + centerY - radius, + centerX + radius, + centerY + radius, + 0f, + 360f + ) + setColor(0) + } else { + val effectiveAngle = totalAngle / parts + for (i in 0 until parts) { + val startAngle = i * (effectiveAngle + gapAngle) -90f + path.reset() + path.addArc( + centerX - radius, + centerY - radius, + centerX + radius, + centerY + radius, + startAngle, + effectiveAngle + ) + setColor(i) + } + } + + } + + fun setParts(parts: Int, list : List = mutableListOf(), isUser: Boolean) { + this.parts = parts + this.booleanList = list + this.isUser = isUser + invalidate() + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/home/status/RepliesBottomDialog.kt b/app/src/main/java/ani/dantotsu/home/status/RepliesBottomDialog.kt new file mode 100644 index 00000000..1927384a --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/RepliesBottomDialog.kt @@ -0,0 +1,113 @@ +package ani.dantotsu.home.status + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import androidx.core.view.isVisible +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.LinearLayoutManager +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.api.ActivityReply +import ani.dantotsu.databinding.BottomSheetRecyclerBinding +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.activity.ActivityReplyItem +import ani.dantotsu.snackString +import ani.dantotsu.util.MarkdownCreatorActivity +import com.xwray.groupie.GroupieAdapter +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class RepliesBottomDialog : BottomSheetDialogFragment() { + private var _binding: BottomSheetRecyclerBinding? = null + private val binding get() = _binding!! + private val adapter: GroupieAdapter = GroupieAdapter() + private val replies: MutableList = mutableListOf() + private var activityId: Int = -1 + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + _binding = BottomSheetRecyclerBinding.inflate(inflater, container, false) + return _binding?.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + binding.repliesRecyclerView.adapter = adapter + binding.repliesRecyclerView.layoutManager = LinearLayoutManager( + context, + LinearLayoutManager.VERTICAL, + false + ) + val context = requireContext() + binding.replyButton.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, MarkdownCreatorActivity::class.java) + .putExtra("type", "replyActivity") + .putExtra("parentId", activityId), + null + ) + } + activityId = requireArguments().getInt("activityId") + loading(true) + lifecycleScope.launch(Dispatchers.IO) { + val response = Anilist.query.getReplies(activityId) + withContext(Dispatchers.Main) { + loading(false) + if (response != null) { + replies.clear() + replies.addAll(response.data.page.activityReplies) + adapter.update( + replies.map { + ActivityReplyItem( + it, + requireActivity(), + clickCallback = { int, _ -> + onClick(int) + } + ) + } + ) + } else { + snackString("Failed to load replies") + } + } + } + + } + + private fun onClick(int: Int) { + ContextCompat.startActivity( + requireContext(), + Intent(requireContext(), ProfileActivity::class.java).putExtra("userId", int), + null + ) + } + + private fun loading(load: Boolean) { + binding.repliesRefresh.isVisible = load + binding.repliesRecyclerView.isVisible = !load + } + + override fun onDestroyView() { + _binding = null + super.onDestroyView() + } + + companion object { + fun newInstance(activityId: Int): RepliesBottomDialog { + return RepliesBottomDialog().apply { + arguments = Bundle().apply { + putInt("activityId", activityId) + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/home/status/StatusActivity.kt b/app/src/main/java/ani/dantotsu/home/status/StatusActivity.kt new file mode 100644 index 00000000..43b2cb55 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/StatusActivity.kt @@ -0,0 +1,110 @@ +package ani.dantotsu.home.status + +import android.os.Bundle +import android.view.ViewGroup +import android.view.animation.Animation +import android.view.animation.AnimationUtils +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.updateLayoutParams +import ani.dantotsu.R +import ani.dantotsu.connections.anilist.api.Activity +import ani.dantotsu.databinding.ActivityStatusBinding +import ani.dantotsu.initActivity +import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.home.status.listener.StoriesCallback +import ani.dantotsu.navBarHeight +import ani.dantotsu.profile.User +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.statusBarHeight + +class StatusActivity : AppCompatActivity(), StoriesCallback { + private lateinit var activity: ArrayList + private lateinit var binding: ActivityStatusBinding + private var position: Int = -1 + private lateinit var slideInLeft: Animation + private lateinit var slideOutRight: Animation + private lateinit var slideOutLeft: Animation + private lateinit var slideInRight: Animation + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + initActivity(this) + binding = ActivityStatusBinding.inflate(layoutInflater) + setContentView(binding.root) + activity = user + position = intent.getIntExtra("position", -1) + binding.root.updateLayoutParams { + topMargin = statusBarHeight + bottomMargin = navBarHeight + } + slideInLeft = AnimationUtils.loadAnimation(this, R.anim.slide_in_left) + slideOutRight = AnimationUtils.loadAnimation(this, R.anim.slide_out_right) + slideOutLeft = AnimationUtils.loadAnimation(this, R.anim.slide_out_left) + slideInRight = AnimationUtils.loadAnimation(this, R.anim.slide_in_right) + + val key = "activities" + val watchedActivity = PrefManager.getCustomVal>(key, setOf()) + val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity ) + val startIndex = if ( startFrom > 0) startFrom else 0 + binding.stories.setStoriesList(activity[position].activity, this, startIndex + 1) + + + } + private fun findFirstNonMatch(watchedActivity: Set, activity: List): Int { + for (activityItem in activity) { + if (activityItem.id !in watchedActivity) { + return activity.indexOf(activityItem) + } + } + return -1 + } + override fun onPause() { + super.onPause() + binding.stories.pause() + } + override fun onResume() { + super.onResume() + binding.stories.resume() + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) { + binding.stories.resume() + } else { + binding.stories.pause() + } + } + override fun onStoriesEnd() { + position += 1 + if (position < activity.size) { + val key = "activities" + val watchedActivity = PrefManager.getCustomVal>(key, setOf()) + val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity ) + val startIndex= if ( startFrom > 0) startFrom else 0 + binding.stories.startAnimation(slideOutLeft) + binding.stories.setStoriesList(activity[position].activity, this, startIndex + 1) + binding.stories.startAnimation(slideInRight) + } else { + finish() + } + } + + override fun onStoriesStart() { + position -= 1 + if (position >= 0) { + val key = "activities" + val watchedActivity = PrefManager.getCustomVal>(key, setOf()) + val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity ) + val startIndex = if ( startFrom > 0) startFrom else 0 + binding.stories.startAnimation(slideOutRight) + binding.stories.setStoriesList(activity[position].activity, this, startIndex + 1) + binding.stories.startAnimation(slideInLeft) + } else { + finish() + } + } + companion object { + var user: ArrayList = arrayListOf() + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/home/status/Stories.kt b/app/src/main/java/ani/dantotsu/home/status/Stories.kt new file mode 100644 index 00000000..7f2c60ec --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/Stories.kt @@ -0,0 +1,505 @@ +package ani.dantotsu.home.status + +import android.annotation.SuppressLint +import android.content.Context +import android.content.Intent +import android.content.res.ColorStateList +import android.util.AttributeSet +import android.view.LayoutInflater +import android.view.MotionEvent +import android.view.View +import android.widget.ProgressBar +import androidx.constraintlayout.widget.ConstraintLayout +import androidx.constraintlayout.widget.ConstraintSet +import androidx.core.app.ActivityOptionsCompat +import androidx.core.content.ContextCompat +import androidx.core.view.ViewCompat +import androidx.core.view.isVisible +import androidx.fragment.app.FragmentActivity +import ani.dantotsu.R +import ani.dantotsu.blurImage +import ani.dantotsu.buildMarkwon +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.api.Activity +import ani.dantotsu.databinding.FragmentStatusBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.home.status.listener.StoriesCallback +import ani.dantotsu.loadImage +import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.User +import ani.dantotsu.profile.UsersDialogFragment +import ani.dantotsu.profile.activity.ActivityItemBuilder +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.snackString +import ani.dantotsu.util.AniMarkdown +import ani.dantotsu.util.Logger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.Calendar +import java.util.Locale +import kotlin.math.abs + + +class Stories @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 +) : ConstraintLayout(context, attrs, defStyleAttr), View.OnTouchListener { + private lateinit var activity: FragmentActivity + private lateinit var binding: FragmentStatusBinding + private lateinit var activityList: List + private lateinit var storiesListener: StoriesCallback + private var userClicked: Boolean = false + private var storyIndex: Int = 1 + private var primaryColor: Int = 0 + private var onPrimaryColor: Int = 0 + private var storyDuration: Int = 6 + private val timer: StoryTimer = StoryTimer(secondsToMillis(storyDuration)) + + init { + initLayout() + } + + @SuppressLint("ClickableViewAccessibility") + fun initLayout() { + val inflater: LayoutInflater = LayoutInflater.from(context) + binding = FragmentStatusBinding.inflate(inflater, this, false) + addView(binding.root) + + primaryColor = context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + onPrimaryColor = context.getThemeColor(com.google.android.material.R.attr.colorOnPrimary) + + if (context is StoriesCallback) storiesListener = context as StoriesCallback + + binding.leftTouchPanel.setOnTouchListener(this) + binding.rightTouchPanel.setOnTouchListener(this) + } + + + fun setStoriesList( + activityList: List, activity: FragmentActivity, startIndex: Int = 1 + ) { + this.activityList = activityList + this.activity = activity + this.storyIndex = startIndex + addLoadingViews(activityList) + } + + private fun addLoadingViews(storiesList: List) { + var idCounter = 1 + for (story in storiesList) { + binding.progressBarContainer.removeView(findViewWithTag("story${idCounter}")) + val progressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal) + progressBar.visibility = View.VISIBLE + progressBar.id = idCounter + progressBar.tag = "story${idCounter++}" + progressBar.progressBackgroundTintList = ColorStateList.valueOf(primaryColor) + progressBar.progressTintList = ColorStateList.valueOf(onPrimaryColor) + val params = LayoutParams(0, LayoutParams.WRAP_CONTENT) + params.marginEnd = 5 + params.marginStart = 5 + binding.progressBarContainer.addView(progressBar, params) + } + + val constraintSet = ConstraintSet() + constraintSet.clone(binding.progressBarContainer) + + var counter = storiesList.size + for (story in storiesList) { + val progressBar = findViewWithTag("story${counter}") + if (progressBar != null) { + if (storiesList.size > 1) { + when (counter) { + storiesList.size -> { + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.END, + LayoutParams.PARENT_ID, + ConstraintSet.END + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.TOP, + LayoutParams.PARENT_ID, + ConstraintSet.TOP + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.START, + getId("story${counter - 1}"), + ConstraintSet.END + ) + } + + 1 -> { + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.TOP, + LayoutParams.PARENT_ID, + ConstraintSet.TOP + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.START, + LayoutParams.PARENT_ID, + ConstraintSet.START + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.END, + getId("story${counter + 1}"), + ConstraintSet.START + ) + } + + else -> { + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.TOP, + LayoutParams.PARENT_ID, + ConstraintSet.TOP + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.START, + getId("story${counter - 1}"), + ConstraintSet.END + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.END, + getId("story${counter + 1}"), + ConstraintSet.START + ) + } + } + } else { + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.END, + LayoutParams.PARENT_ID, + ConstraintSet.END + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.TOP, + LayoutParams.PARENT_ID, + ConstraintSet.TOP + ) + constraintSet.connect( + getId("story${counter}"), + ConstraintSet.START, + LayoutParams.PARENT_ID, + ConstraintSet.START + ) + } + } + counter-- + } + constraintSet.applyTo(binding.progressBarContainer) + startShowContent() + } + + private fun startShowContent() { + showStory() + } + + private fun showStory() { + if (storyIndex > 1) { + completeProgressBar(storyIndex - 1) + } + val progressBar = findViewWithTag("story${storyIndex}") + binding.androidStoriesLoadingView.visibility = View.VISIBLE + timer.setOnTimerCompletedListener { + Logger.log("onAnimationEnd: $storyIndex") + if (storyIndex - 1 <= activityList.size) { + Logger.log("userNotClicked: $storyIndex") + if (storyIndex < activityList.size) { + storyIndex += 1 + showStory() + } else { + // on stories end + binding.androidStoriesLoadingView.visibility = View.GONE + onStoriesCompleted() + } + } else { + // on stories end + binding.androidStoriesLoadingView.visibility = View.GONE + onStoriesCompleted() + } + } + timer.setOnPercentTickListener { + progressBar.progress = it + } + loadStory(activityList[storyIndex - 1]) + } + + private fun getId(tag: String): Int { + return findViewWithTag(tag).id + } + + private fun secondsToMillis(seconds: Int): Long { + return (seconds.toLong()).times(1000) + } + + private fun resetProgressBar(storyIndex: Int) { + for (i in storyIndex until activityList.size + 1) { + val progressBar = findViewWithTag("story${i}") + progressBar?.let { + it.progress = 0 + } + } + } + + private fun completeProgressBar(storyIndex: Int) { + for (i in 1 until storyIndex + 1) { + val progressBar = findViewWithTag("story${i}") + progressBar?.let { + it.progress = 100 + } + } + } + + + private var startClickTime = 0L + private var startX = 0f + private var startY = 0f + private var isLongPress = false + private val swipeThreshold = 100 + override fun onTouch(view: View?, event: MotionEvent?): Boolean { + val maxClickDuration = 200 + when (event?.action) { + MotionEvent.ACTION_DOWN -> { + startX = event.x + startY = event.y + startClickTime = Calendar.getInstance().timeInMillis + pause() + isLongPress = false + } + + MotionEvent.ACTION_MOVE -> { + val deltaX = event.x - startX + val deltaY = event.y - startY + if (!isLongPress && (abs(deltaX) > swipeThreshold || abs(deltaY) > swipeThreshold)) { + isLongPress = true + } + } + + MotionEvent.ACTION_UP -> { + val clickDuration = Calendar.getInstance().timeInMillis - startClickTime + if (clickDuration < maxClickDuration && !isLongPress) { + when (view?.id) { + R.id.leftTouchPanel -> leftPanelTouch() + R.id.rightTouchPanel -> rightPanelTouch() + } + } else { + resume() + } + val deltaX = event.x - startX + if (abs(deltaX) > swipeThreshold) { + if (deltaX > 0) onStoriesPrevious() + else onStoriesCompleted() + } + } + } + return true + } + + private fun rightPanelTouch() { + Logger.log("rightPanelTouch: $storyIndex") + if (storyIndex == activityList.size) { + completeProgressBar(storyIndex) + onStoriesCompleted() + return + } + userClicked = true + timer.cancel() + if (storyIndex <= activityList.size) storyIndex += 1 + showStory() + } + + private fun leftPanelTouch() { + Logger.log("leftPanelTouch: $storyIndex") + if (storyIndex == 1) { + onStoriesPrevious() + return + } + userClicked = true + timer.cancel() + resetProgressBar(storyIndex) + if (storyIndex > 1) storyIndex -= 1 + showStory() + } + + private fun onStoriesCompleted() { + Logger.log("onStoriesCompleted") + if (::storiesListener.isInitialized) { + storyIndex = 1 + storiesListener.onStoriesEnd() + resetProgressBar(storyIndex) + } + } + + private fun onStoriesPrevious() { + if (::storiesListener.isInitialized) { + storyIndex = 1 + storiesListener.onStoriesStart() + resetProgressBar(storyIndex) + } + } + + fun pause() { + timer.pause() + } + + fun resume() { + timer.resume() + } + + private fun loadStory(story: Activity) { + val key = "activities" + val set = PrefManager.getCustomVal>(key, setOf()).plus((story.id)) + val newList = set.sorted().takeLast(200).toSet() + PrefManager.setCustomVal(key, newList) + binding.statusUserAvatar.loadImage(story.user?.avatar?.large) + binding.statusUserName.text = story.user?.name + binding.statusUserTime.text = ActivityItemBuilder.getDateTime(story.createdAt) + binding.statusUserContainer.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, ProfileActivity::class.java).putExtra("userId", story.userId), + null + ) + } + fun visible(isList: Boolean) { + binding.textActivity.isVisible = !isList + binding.textActivityContainer.isVisible = !isList + binding.infoText.isVisible = isList + binding.coverImage.isVisible = isList + binding.infoText.visibility = if (isList) View.VISIBLE else View.INVISIBLE + binding.infoText.text = "" + binding.contentImageViewKen.isVisible = isList + binding.contentImageView.isVisible = isList + } + + when (story.typename) { + "ListActivity" -> { + visible(true) + val text = "${ + story.status?.replaceFirstChar { + if (it.isLowerCase()) { + it.titlecase(Locale.ROOT) + } else { + it.toString() + } + } + } ${story.progress ?: story.media?.title?.userPreferred} " + + if ( + story.status?.contains("completed") == false && + !story.status.contains("plans") && + !story.status.contains("repeating") + ) { + "of ${story.media?.title?.userPreferred}" + } else { + "" + } + binding.infoText.text = text + val bannerAnimations: Boolean = PrefManager.getVal(PrefName.BannerAnimations) + blurImage( + if (bannerAnimations) binding.contentImageViewKen else binding.contentImageView, + story.media?.bannerImage ?: story.media?.coverImage?.extraLarge + ) + binding.coverImage.loadImage(story.media?.coverImage?.extraLarge) + binding.coverImage.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, MediaDetailsActivity::class.java).putExtra( + "mediaId", + story.media?.id + ), + ActivityOptionsCompat.makeSceneTransitionAnimation( + activity, + binding.coverImage, + ViewCompat.getTransitionName(binding.coverImage)!! + ).toBundle() + ) + } + } + + "TextActivity" -> { + visible(false) + if (!(context as android.app.Activity).isDestroyed) { + val markwon = buildMarkwon(context, false) + markwon.setMarkdown( + binding.textActivity, AniMarkdown.getBasicAniHTML(story.text ?: "") + ) + } + } + + "MessageActivity" -> { + visible(false) + if (!(context as android.app.Activity).isDestroyed) { + val markwon = buildMarkwon(context, false) + markwon.setMarkdown( + binding.textActivity, AniMarkdown.getBasicAniHTML(story.message ?: "") + ) + } + } + } + val userList = arrayListOf() + story.likes?.forEach { i -> + userList.add(User(i.id, i.name.toString(), i.avatar?.medium, i.bannerImage)) + } + val likeColor = ContextCompat.getColor(context, R.color.yt_red) + val notLikeColor = ContextCompat.getColor(context, R.color.bg_opp) + binding.activityRepliesContainer.setOnClickListener { + RepliesBottomDialog.newInstance(story.id) + .show(activity.supportFragmentManager, "replies") + } + binding.activityLike.setColorFilter(if (story.isLiked == true) likeColor else notLikeColor) + binding.replyCount.text = story.replyCount.toString() + binding.activityLikeCount.text = story.likeCount.toString() + binding.activityReplies.setColorFilter(ContextCompat.getColor(context, R.color.bg_opp)) + binding.activityLikeContainer.setOnClickListener { + like() + } + binding.activityLikeContainer.setOnLongClickListener { + val context = activity + UsersDialogFragment().apply { + userList(userList) + show(context.supportFragmentManager, "dialog") + } + true + } + binding.androidStoriesLoadingView.visibility = View.GONE + timer.start() + } + + fun like() { + val story = activityList[storyIndex - 1] + val likeColor = ContextCompat.getColor(context, R.color.yt_red) + val notLikeColor = ContextCompat.getColor(context, R.color.bg_opp) + val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + scope.launch { + val res = Anilist.query.toggleLike(story.id, "ACTIVITY") + withContext(Dispatchers.Main) { + if (res != null) { + if (story.isLiked == true) { + story.likeCount = story.likeCount?.minus(1) + } else { + story.likeCount = story.likeCount?.plus(1) + } + binding.activityLikeCount.text = (story.likeCount ?: 0).toString() + story.isLiked = !story.isLiked!! + binding.activityLike.setColorFilter(if (story.isLiked == true) likeColor else notLikeColor) + + } else { + snackString("Failed to like activity") + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/home/status/StoryTimer.kt b/app/src/main/java/ani/dantotsu/home/status/StoryTimer.kt new file mode 100644 index 00000000..137d7d4b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/StoryTimer.kt @@ -0,0 +1,64 @@ +package ani.dantotsu.home.status + +import android.os.CountDownTimer + +class StoryTimer( + private val updateInterval: Long +) { + private lateinit var timer: CountDownTimer + private var prevVal = 0 + private var pauseLength = 0L + var onTimerCompleted: () -> Unit = {} + var percentTick: (Int) -> Unit = {} + var timeLeft: Long = 0 + private set + + fun start(durationInMillis: Long = updateInterval) { + cancel() + timer = object : CountDownTimer(durationInMillis, 1) { + override fun onTick(millisUntilFinished: Long) { + timeLeft = millisUntilFinished + val percent = + ((pauseLength + durationInMillis - millisUntilFinished) * 100 / (pauseLength + durationInMillis)).toInt() + if (percent != prevVal) { + percentTick.invoke(percent) + prevVal = percent + } + } + + override fun onFinish() { + onTimerCompleted.invoke() + pauseLength = 0 + } + } + timer.start() + } + + fun cancel() { + if (::timer.isInitialized) { + timer.cancel() + } + } + + fun pause() { + if (::timer.isInitialized) { + timer.cancel() + pauseLength = updateInterval - timeLeft + } + } + + fun resume() { + if (::timer.isInitialized && timeLeft > 0) { + start(timeLeft) + timer.start() + } + } + + fun setOnTimerCompletedListener(onTimerCompleted: () -> Unit) { + this.onTimerCompleted = onTimerCompleted + } + + fun setOnPercentTickListener(percentTick: (Int) -> Unit) { + this.percentTick = percentTick + } +} diff --git a/app/src/main/java/ani/dantotsu/home/status/UserStatusAdapter.kt b/app/src/main/java/ani/dantotsu/home/status/UserStatusAdapter.kt new file mode 100644 index 00000000..5daebcd9 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/UserStatusAdapter.kt @@ -0,0 +1,73 @@ +package ani.dantotsu.home.status + +import android.content.Context +import android.content.Intent +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView +import ani.dantotsu.R +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.databinding.ItemUserStatusBinding +import ani.dantotsu.getAppString +import ani.dantotsu.loadImage +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.User +import ani.dantotsu.setAnimation +import ani.dantotsu.settings.saving.PrefManager + +class UserStatusAdapter(private val user: ArrayList) : + RecyclerView.Adapter() { + + inner class UsersViewHolder(val binding: ItemUserStatusBinding) : + RecyclerView.ViewHolder(binding.root) { + init { + itemView.setOnClickListener { + StatusActivity.user = user + ContextCompat.startActivity( + itemView.context, + Intent( + itemView.context, + StatusActivity::class.java + ).putExtra("position", bindingAdapterPosition), + null + ) + } + itemView.setOnLongClickListener { + ContextCompat.startActivity( + itemView.context, + Intent( + itemView.context, + ProfileActivity::class.java + ).putExtra("userId", user[bindingAdapterPosition].id), + null + ) + true + } + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsersViewHolder { + return UsersViewHolder( + ItemUserStatusBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + } + + override fun onBindViewHolder(holder: UsersViewHolder, position: Int) { + val b = holder.binding + setAnimation(b.root.context, b.root) + val user = user[position] + b.profileUserAvatar.loadImage(user.pfp) + b.profileUserName.text = if (Anilist.userid == user.id) getAppString(R.string.your_story) else user.name + val watchedActivity = PrefManager.getCustomVal>("activities", setOf()) + val booleanList = user.activity.map { watchedActivity.contains(it.id) } + b.profileUserStatusIndicator.setParts(user.activity.size, booleanList, user.id == Anilist.userid) + + } + + override fun getItemCount(): Int = user.size +} diff --git a/app/src/main/java/ani/dantotsu/home/status/listener/StoriesCallback.kt b/app/src/main/java/ani/dantotsu/home/status/listener/StoriesCallback.kt new file mode 100644 index 00000000..9a2b684c --- /dev/null +++ b/app/src/main/java/ani/dantotsu/home/status/listener/StoriesCallback.kt @@ -0,0 +1,6 @@ +package ani.dantotsu.home.status.listener + +interface StoriesCallback { + fun onStoriesEnd() + fun onStoriesStart() +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/Author.kt b/app/src/main/java/ani/dantotsu/media/Author.kt index 9ab3c169..803ef989 100644 --- a/app/src/main/java/ani/dantotsu/media/Author.kt +++ b/app/src/main/java/ani/dantotsu/media/Author.kt @@ -3,9 +3,10 @@ package ani.dantotsu.media import java.io.Serializable data class Author( - val id: Int, - val name: String?, - val image: String?, - val role: String?, - var yearMedia: MutableMap>? = null + var id: Int, + var name: String?, + var image: String?, + var role: String?, + var yearMedia: MutableMap>? = null, + var character: ArrayList? = null ) : Serializable diff --git a/app/src/main/java/ani/dantotsu/media/AuthorActivity.kt b/app/src/main/java/ani/dantotsu/media/AuthorActivity.kt index 22bc54f1..e30d6049 100644 --- a/app/src/main/java/ani/dantotsu/media/AuthorActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/AuthorActivity.kt @@ -12,6 +12,7 @@ import androidx.lifecycle.MutableLiveData import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager import ani.dantotsu.EmptyAdapter import ani.dantotsu.R import ani.dantotsu.Refresh @@ -32,7 +33,6 @@ class AuthorActivity : AppCompatActivity() { private val model: OtherDetailsViewModel by viewModels() private var author: Author? = null private var loaded = false - override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -55,14 +55,15 @@ class AuthorActivity : AppCompatActivity() { binding.studioClose.setOnClickListener { onBackPressedDispatcher.onBackPressed() } - model.getAuthor().observe(this) { if (it != null) { author = it loaded = true binding.studioProgressBar.visibility = View.GONE binding.studioRecycler.visibility = View.VISIBLE - + if (author!!.yearMedia.isNullOrEmpty()) { + binding.studioRecycler.visibility = View.GONE + } val titlePosition = arrayListOf() val concatAdapter = ConcatAdapter() val map = author!!.yearMedia ?: return@observe @@ -89,9 +90,19 @@ class AuthorActivity : AppCompatActivity() { concatAdapter.addAdapter(MediaAdaptor(0, medias, this, true)) concatAdapter.addAdapter(EmptyAdapter(empty)) } - binding.studioRecycler.adapter = concatAdapter binding.studioRecycler.layoutManager = gridLayoutManager + + binding.charactersRecycler.visibility = View.VISIBLE + binding.charactersText.visibility = View.VISIBLE + binding.charactersRecycler.adapter = + CharacterAdapter(author!!.character ?: arrayListOf()) + binding.charactersRecycler.layoutManager = + LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) + if (author!!.character.isNullOrEmpty()) { + binding.charactersRecycler.visibility = View.GONE + binding.charactersText.visibility = View.GONE + } } } val live = Refresh.activity.getOrPut(this.hashCode()) { MutableLiveData(true) } diff --git a/app/src/main/java/ani/dantotsu/media/AuthorAdapter.kt b/app/src/main/java/ani/dantotsu/media/AuthorAdapter.kt index 35195960..7b0953fc 100644 --- a/app/src/main/java/ani/dantotsu/media/AuthorAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/AuthorAdapter.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.view.LayoutInflater @@ -16,7 +15,7 @@ import ani.dantotsu.setAnimation import java.io.Serializable class AuthorAdapter( - private val authorList: ArrayList + private val authorList: ArrayList, ) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AuthorViewHolder { val binding = @@ -24,8 +23,7 @@ class AuthorAdapter( return AuthorViewHolder(binding) } - @SuppressLint("SetTextI18n") - override fun onBindViewHolder(holder:AuthorViewHolder, position: Int) { + override fun onBindViewHolder(holder: AuthorViewHolder, position: Int) { val binding = holder.binding setAnimation(binding.root.context, holder.binding.root) val author = authorList[position] diff --git a/app/src/main/java/ani/dantotsu/media/CalendarActivity.kt b/app/src/main/java/ani/dantotsu/media/CalendarActivity.kt index bbe66477..66cec7e4 100644 --- a/app/src/main/java/ani/dantotsu/media/CalendarActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/CalendarActivity.kt @@ -1,12 +1,9 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.os.Bundle -import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.view.Window -import android.view.WindowManager import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat @@ -16,8 +13,9 @@ import androidx.lifecycle.lifecycleScope import ani.dantotsu.R import ani.dantotsu.Refresh import ani.dantotsu.databinding.ActivityListBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.hideSystemBarsExtendView import ani.dantotsu.media.user.ListViewPagerAdapter -import ani.dantotsu.navBarHeight import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.statusBarHeight @@ -34,7 +32,6 @@ class CalendarActivity : AppCompatActivity() { private var selectedTabIdx = 1 private val model: OtherDetailsViewModel by viewModels() - @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -42,22 +39,10 @@ class CalendarActivity : AppCompatActivity() { binding = ActivityListBinding.inflate(layoutInflater) - val typedValue = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorSurface, typedValue, true) - val primaryColor = typedValue.data - val typedValue2 = TypedValue() - theme.resolveAttribute( - com.google.android.material.R.attr.colorOnBackground, - typedValue2, - true - ) - val titleTextColor = typedValue2.data - val typedValue3 = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue3, true) - val primaryTextColor = typedValue3.data - val typedValue4 = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorOutline, typedValue4, true) - val secondaryTextColor = typedValue4.data + + val primaryColor = getThemeColor(com.google.android.material.R.attr.colorSurface) + val primaryTextColor = getThemeColor(com.google.android.material.R.attr.colorPrimary) + val secondaryTextColor = getThemeColor(com.google.android.material.R.attr.colorOutline) window.statusBarColor = primaryColor window.navigationBarColor = primaryColor @@ -74,10 +59,7 @@ class CalendarActivity : AppCompatActivity() { } else { binding.root.fitsSystemWindows = false requestWindowFeature(Window.FEATURE_NO_TITLE) - window.setFlags( - WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN - ) + hideSystemBarsExtendView() binding.settingsContainer.updateLayoutParams { topMargin = statusBarHeight } @@ -87,6 +69,7 @@ class CalendarActivity : AppCompatActivity() { binding.listTitle.setText(R.string.release_calendar) binding.listSort.visibility = View.GONE binding.random.visibility = View.GONE + binding.search.visibility = View.GONE binding.listTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab?) { this@CalendarActivity.selectedTabIdx = tab?.position ?: 1 diff --git a/app/src/main/java/ani/dantotsu/media/Character.kt b/app/src/main/java/ani/dantotsu/media/Character.kt index e774ed30..77242884 100644 --- a/app/src/main/java/ani/dantotsu/media/Character.kt +++ b/app/src/main/java/ani/dantotsu/media/Character.kt @@ -14,5 +14,6 @@ data class Character( var age: String? = null, var gender: String? = null, var dateOfBirth: FuzzyDate? = null, - var roles: ArrayList? = null + var roles: ArrayList? = null, + val voiceActor: ArrayList? = null, ) : Serializable \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/CharacterAdapter.kt b/app/src/main/java/ani/dantotsu/media/CharacterAdapter.kt index d8c4961c..d97e138d 100644 --- a/app/src/main/java/ani/dantotsu/media/CharacterAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/CharacterAdapter.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.view.LayoutInflater @@ -24,12 +23,13 @@ class CharacterAdapter( return CharacterViewHolder(binding) } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: CharacterViewHolder, position: Int) { val binding = holder.binding setAnimation(binding.root.context, holder.binding.root) val character = characterList[position] - binding.itemCompactRelation.text = character.role + " " + val whitespace = "${character.role} " + character.voiceActor + binding.itemCompactRelation.text = whitespace binding.itemCompactImage.loadImage(character.image) binding.itemCompactTitle.text = character.name } diff --git a/app/src/main/java/ani/dantotsu/media/CharacterDetailsActivity.kt b/app/src/main/java/ani/dantotsu/media/CharacterDetailsActivity.kt index 4778f708..323b689e 100644 --- a/app/src/main/java/ani/dantotsu/media/CharacterDetailsActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/CharacterDetailsActivity.kt @@ -8,6 +8,7 @@ import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.math.MathUtils.clamp +import androidx.core.view.isGone import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.lifecycle.MutableLiveData @@ -94,7 +95,8 @@ class CharacterDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChang } lifecycleScope.launch { withContext(Dispatchers.IO) { - character.isFav = Anilist.query.isUserFav(AnilistMutations.FavType.CHARACTER, character.id) + character.isFav = + Anilist.query.isUserFav(AnilistMutations.FavType.CHARACTER, character.id) } withContext(Dispatchers.Main) { binding.characterFav.setImageResource( @@ -152,7 +154,7 @@ class CharacterDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChang } override fun onResume() { - binding.characterProgress.visibility = if (!loaded) View.VISIBLE else View.GONE + binding.characterProgress.isGone = loaded super.onResume() } diff --git a/app/src/main/java/ani/dantotsu/media/CharacterDetailsAdapter.kt b/app/src/main/java/ani/dantotsu/media/CharacterDetailsAdapter.kt index 2e419492..86ac6d68 100644 --- a/app/src/main/java/ani/dantotsu/media/CharacterDetailsAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/CharacterDetailsAdapter.kt @@ -1,9 +1,10 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.app.Activity import android.view.LayoutInflater +import android.view.View import android.view.ViewGroup +import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ani.dantotsu.R import ani.dantotsu.currActivity @@ -20,23 +21,36 @@ class CharacterDetailsAdapter(private val character: Character, private val acti return GenreViewHolder(binding) } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: GenreViewHolder, position: Int) { val binding = holder.binding val desc = - (if (character.age != "null") currActivity()!!.getString(R.string.age) + " " + character.age else "") + - (if (character.dateOfBirth.toString() != "") currActivity()!!.getString(R.string.birthday) + " " + character.dateOfBirth.toString() else "") + - (if (character.gender != "null") currActivity()!!.getString(R.string.gender) + " " + when (character.gender) { - "Male" -> currActivity()!!.getString(R.string.male) - "Female" -> currActivity()!!.getString(R.string.female) - else -> character.gender - } else "") + "\n" + character.description + (if (character.age != "null") "${currActivity()!!.getString(R.string.age)} ${character.age}" else "") + + (if (character.dateOfBirth.toString() != "") + "${currActivity()!!.getString(R.string.birthday)} ${character.dateOfBirth.toString()}" else "") + + (if (character.gender != "null") + currActivity()!!.getString(R.string.gender) + " " + when (character.gender) { + currActivity()!!.getString(R.string.male) -> currActivity()!!.getString( + R.string.male + ) + + currActivity()!!.getString(R.string.female) -> currActivity()!!.getString( + R.string.female + ) + + else -> character.gender + } else "") + "\n" + character.description binding.characterDesc.isTextSelectable val markWon = Markwon.builder(activity).usePlugin(SoftBreakAddsNewLinePlugin.create()) .usePlugin(SpoilerPlugin()).build() markWon.setMarkdown(binding.characterDesc, desc.replace("~!", "||").replace("!~", "||")) - + binding.voiceActorRecycler.adapter = AuthorAdapter(character.voiceActor ?: arrayListOf()) + binding.voiceActorRecycler.layoutManager = LinearLayoutManager( + activity, LinearLayoutManager.HORIZONTAL, false + ) + if (binding.voiceActorRecycler.adapter!!.itemCount == 0) { + binding.voiceActorContainer.visibility = View.GONE + } } override fun getItemCount(): Int = 1 diff --git a/app/src/main/java/ani/dantotsu/media/Media.kt b/app/src/main/java/ani/dantotsu/media/Media.kt index d26a5048..a935dd4a 100644 --- a/app/src/main/java/ani/dantotsu/media/Media.kt +++ b/app/src/main/java/ani/dantotsu/media/Media.kt @@ -5,8 +5,10 @@ import ani.dantotsu.connections.anilist.api.FuzzyDate import ani.dantotsu.connections.anilist.api.MediaEdge import ani.dantotsu.connections.anilist.api.MediaList import ani.dantotsu.connections.anilist.api.MediaType +import ani.dantotsu.connections.anilist.api.Query import ani.dantotsu.media.anime.Anime import ani.dantotsu.media.manga.Manga +import ani.dantotsu.profile.User import java.io.Serializable import ani.dantotsu.connections.anilist.api.Media as ApiMedia @@ -25,7 +27,7 @@ data class Media( var cover: String? = null, var banner: String? = null, var relation: String? = null, - var popularity: Int? = null, + var favourites: Int? = null, var isAdult: Boolean, var isFav: Boolean = false, @@ -56,14 +58,18 @@ data class Media( var trailer: String? = null, var startDate: FuzzyDate? = null, var endDate: FuzzyDate? = null, + var popularity: Int? = null, + + var timeUntilAiring: Long? = null, var characters: ArrayList? = null, + var review: ArrayList? = null, var staff: ArrayList? = null, var prequel: Media? = null, var sequel: Media? = null, var relations: ArrayList? = null, var recommendations: ArrayList? = null, - + var users: ArrayList? = null, var vrvId: String? = null, var crunchySlug: String? = null, @@ -83,7 +89,7 @@ data class Media( name = apiMedia.title!!.english, nameRomaji = apiMedia.title!!.romaji, userPreferredName = apiMedia.title!!.userPreferred, - cover = apiMedia.coverImage?.large, + cover = apiMedia.coverImage?.large ?: apiMedia.coverImage?.medium, banner = apiMedia.bannerImage, status = apiMedia.status.toString(), isFav = apiMedia.isFavourite!!, @@ -95,6 +101,8 @@ data class Media( meanScore = apiMedia.meanScore, startDate = apiMedia.startDate, endDate = apiMedia.endDate, + favourites = apiMedia.favourites, + timeUntilAiring = apiMedia.nextAiringEpisode?.timeUntilAiring?.let { it.toLong() * 1000 }, anime = if (apiMedia.type == MediaType.ANIME) Anime( totalEpisodes = apiMedia.episodes, nextAiringEpisode = apiMedia.nextAiringEpisode?.episode?.minus(1) @@ -109,7 +117,8 @@ data class Media( this.userScore = mediaList.score?.toInt() ?: 0 this.userStatus = mediaList.status?.toString() this.userUpdatedAt = mediaList.updatedAt?.toLong() - this.genres = mediaList.media?.genres?.toMutableList() as? ArrayList? ?: arrayListOf() + this.genres = + mediaList.media?.genres?.toMutableList() as? ArrayList? ?: arrayListOf() } constructor(mediaEdge: MediaEdge) : this(mediaEdge.node!!) { diff --git a/app/src/main/java/ani/dantotsu/media/MediaAdaptor.kt b/app/src/main/java/ani/dantotsu/media/MediaAdaptor.kt index 8c415e2d..d31473c6 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaAdaptor.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaAdaptor.kt @@ -1,8 +1,6 @@ package ani.dantotsu.media import android.annotation.SuppressLint -import android.app.Activity -import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas @@ -15,25 +13,25 @@ import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources import androidx.core.app.ActivityOptionsCompat import androidx.core.content.ContextCompat -import androidx.core.util.Pair import androidx.core.view.ViewCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 -import ani.dantotsu.* +import ani.dantotsu.R +import ani.dantotsu.blurImage +import ani.dantotsu.currActivity import ani.dantotsu.databinding.ItemMediaCompactBinding import ani.dantotsu.databinding.ItemMediaLargeBinding import ani.dantotsu.databinding.ItemMediaPageBinding import ani.dantotsu.databinding.ItemMediaPageSmallBinding +import ani.dantotsu.loadImage +import ani.dantotsu.setAnimation +import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName -import com.bumptech.glide.Glide -import com.bumptech.glide.load.engine.DiskCacheStrategy -import com.bumptech.glide.load.model.GlideUrl -import com.bumptech.glide.request.RequestOptions import com.flaviofaria.kenburnsview.RandomTransitionGenerator -import jp.wasabeef.glide.transformations.BlurTransformation import java.io.Serializable @@ -85,7 +83,7 @@ class MediaAdaptor( } - @SuppressLint("SetTextI18n", "ClickableViewAccessibility") + @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (type) { 0 -> { @@ -94,8 +92,8 @@ class MediaAdaptor( val media = mediaList?.getOrNull(position) if (media != null) { b.itemCompactImage.loadImage(media.cover) - b.itemCompactOngoing.visibility = - if (media.status == currActivity()!!.getString(R.string.status_releasing)) View.VISIBLE else View.GONE + b.itemCompactOngoing.isVisible = + media.status == currActivity()!!.getString(R.string.status_releasing) b.itemCompactTitle.text = media.userPreferredName b.itemCompactScore.text = ((if (media.userScore == 0) (media.meanScore @@ -140,8 +138,8 @@ class MediaAdaptor( if (media != null) { b.itemCompactImage.loadImage(media.cover) blurImage(b.itemCompactBanner, media.banner ?: media.cover) - b.itemCompactOngoing.visibility = - if (media.status == currActivity()!!.getString(R.string.status_releasing)) View.VISIBLE else View.GONE + b.itemCompactOngoing.isVisible = + media.status == currActivity()!!.getString(R.string.status_releasing) b.itemCompactTitle.text = media.userPreferredName b.itemCompactScore.text = ((if (media.userScore == 0) (media.meanScore @@ -151,25 +149,30 @@ class MediaAdaptor( (if (media.userScore != 0) R.drawable.item_user_score else R.drawable.item_score) ) if (media.anime != null) { - b.itemTotal.text = " " + if ((media.anime.totalEpisodes + val itemTotal = " " + if ((media.anime.totalEpisodes ?: 0) != 1 - ) currActivity()!!.getString(R.string.episode_plural) - else currActivity()!!.getString(R.string.episode_singular) + ) currActivity()!!.getString(R.string.episode_plural) else currActivity()!!.getString( + R.string.episode_singular + ) + b.itemTotal.text = itemTotal b.itemCompactTotal.text = if (media.anime.nextAiringEpisode != null) (media.anime.nextAiringEpisode.toString() + " / " + (media.anime.totalEpisodes ?: "??").toString()) else (media.anime.totalEpisodes ?: "??").toString() } else if (media.manga != null) { - b.itemTotal.text = " " + if ((media.manga.totalChapters + val itemTotal = " " + if ((media.manga.totalChapters ?: 0) != 1 - ) currActivity()!!.getString(R.string.chapter_plural) - else currActivity()!!.getString(R.string.chapter_singular) + ) currActivity()!!.getString(R.string.chapter_plural) else currActivity()!!.getString( + R.string.chapter_singular + ) + b.itemTotal.text = itemTotal b.itemCompactTotal.text = "${media.manga.totalChapters ?: "??"}" } - @SuppressLint("NotifyDataSetChanged") if (position == mediaList!!.size - 2 && viewPager != null) viewPager.post { + val start = mediaList.size mediaList.addAll(mediaList) - notifyDataSetChanged() + val end = mediaList.size - start + notifyItemRangeInserted(start, end) } } } @@ -178,6 +181,7 @@ class MediaAdaptor( val b = (holder as MediaPageViewHolder).binding val media = mediaList?.get(position) if (media != null) { + val bannerAnimations: Boolean = PrefManager.getVal(PrefName.BannerAnimations) b.itemCompactImage.loadImage(media.cover) if (bannerAnimations) @@ -187,9 +191,12 @@ class MediaAdaptor( AccelerateDecelerateInterpolator() ) ) - blurImage(b.itemCompactBanner, media.banner ?: media.cover) - b.itemCompactOngoing.visibility = - if (media.status == currActivity()!!.getString(R.string.status_releasing)) View.VISIBLE else View.GONE + blurImage( + if (bannerAnimations) b.itemCompactBanner else b.itemCompactBannerNoKen, + media.banner ?: media.cover + ) + b.itemCompactOngoing.isVisible = + media.status == currActivity()!!.getString(R.string.status_releasing) b.itemCompactTitle.text = media.userPreferredName b.itemCompactScore.text = ((if (media.userScore == 0) (media.meanScore @@ -236,9 +243,12 @@ class MediaAdaptor( AccelerateDecelerateInterpolator() ) ) - blurImage(b.itemCompactBanner, media.banner ?: media.cover) - b.itemCompactOngoing.visibility = - if (media.status == currActivity()!!.getString(R.string.status_releasing)) View.VISIBLE else View.GONE + blurImage( + if (bannerAnimations) b.itemCompactBanner else b.itemCompactBannerNoKen, + media.banner ?: media.cover + ) + b.itemCompactOngoing.isVisible = + media.status == currActivity()!!.getString(R.string.status_releasing) b.itemCompactTitle.text = media.userPreferredName b.itemCompactScore.text = ((if (media.userScore == 0) (media.meanScore diff --git a/app/src/main/java/ani/dantotsu/media/MediaDetailsActivity.kt b/app/src/main/java/ani/dantotsu/media/MediaDetailsActivity.kt index 9a528b80..44b04457 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaDetailsActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaDetailsActivity.kt @@ -2,28 +2,27 @@ package ani.dantotsu.media import android.animation.ObjectAnimator import android.annotation.SuppressLint -import android.app.Activity import android.content.Intent -import android.graphics.Rect +import android.content.res.Configuration import android.os.Bundle import android.text.SpannableStringBuilder -import android.util.TypedValue import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.view.ViewGroup -import android.view.WindowManager import android.view.animation.AccelerateDecelerateInterpolator -import android.widget.FrameLayout import android.widget.ImageView +import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import androidx.core.text.bold import androidx.core.text.color +import androidx.core.view.isVisible import androidx.core.view.marginBottom import androidx.core.view.updateLayoutParams +import androidx.core.view.updateMargins import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle @@ -38,6 +37,7 @@ import ani.dantotsu.blurImage import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.copyToClipboard import ani.dantotsu.databinding.ActivityMediaBinding +import ani.dantotsu.getThemeColor import ani.dantotsu.initActivity import ani.dantotsu.loadImage import ani.dantotsu.media.anime.AnimeWatchFragment @@ -54,6 +54,7 @@ import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.statusBarHeight import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.util.LauncherWrapper import com.flaviofaria.kenburnsview.RandomTransitionGenerator import com.google.android.material.appbar.AppBarLayout import kotlinx.coroutines.CoroutineScope @@ -62,20 +63,21 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext +import nl.joery.animatedbottombar.AnimatedBottomBar import kotlin.math.abs class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListener { - + lateinit var launcher: LauncherWrapper lateinit var binding: ActivityMediaBinding private val scope = lifecycleScope private val model: MediaDetailsViewModel by viewModels() - lateinit var tabLayout: TripleNavAdapter var selected = 0 + lateinit var navBar: AnimatedBottomBar var anime = true private var adult = false - @SuppressLint("SetTextI18n", "ClickableViewAccessibility") + @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var media: Media = intent.getSerialized("media") ?: mediaSingleton ?: emptyMedia() @@ -83,8 +85,7 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi if (id != -1) { runBlocking { withContext(Dispatchers.IO) { - media = - Anilist.query.getMedia(id, false) ?: emptyMedia() + media = Anilist.query.getMedia(id, false) ?: emptyMedia() } } } @@ -93,6 +94,9 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi onBackPressedDispatcher.onBackPressed() return } + val contract = ActivityResultContracts.OpenDocumentTree() + launcher = LauncherWrapper(this, contract) + mediaSingleton = null ThemeManager(this).applyTheme(MediaSingleton.bitmap) MediaSingleton.bitmap = null @@ -100,26 +104,38 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi binding = ActivityMediaBinding.inflate(layoutInflater) setContentView(binding.root) screenWidth = resources.displayMetrics.widthPixels.toFloat() + navBar = binding.mediaBottomBar - val isVertical = resources.configuration.orientation - //Ui init + // Ui init initActivity(this) - binding.mediaViewPager.updateLayoutParams { bottomMargin += navBarHeight } + binding.mediaViewPager.updateLayoutParams { + bottomMargin = navBarHeight + } val oldMargin = binding.mediaViewPager.marginBottom AndroidBug5497Workaround.assistActivity(this) { if (it) { binding.mediaViewPager.updateLayoutParams { bottomMargin = 0 } - binding.mediaTabContainer.visibility = View.GONE + navBar.visibility = View.GONE } else { binding.mediaViewPager.updateLayoutParams { bottomMargin = oldMargin } - binding.mediaTabContainer.visibility = View.VISIBLE + navBar.visibility = View.VISIBLE } } + val navBarRightMargin = if (resources.configuration.orientation == + Configuration.ORIENTATION_LANDSCAPE + ) navBarHeight else 0 + val navBarBottomMargin = if (resources.configuration.orientation == + Configuration.ORIENTATION_LANDSCAPE + ) 0 else navBarHeight + navBar.updateLayoutParams { + rightMargin = navBarRightMargin + bottomMargin = navBarBottomMargin + } binding.mediaBanner.updateLayoutParams { height += statusBarHeight } binding.mediaBannerNoKen.updateLayoutParams { height += statusBarHeight } binding.mediaClose.updateLayoutParams { topMargin += statusBarHeight } @@ -147,7 +163,6 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi val banner = if (bannerAnimations) binding.mediaBanner else binding.mediaBannerNoKen val viewPager = binding.mediaViewPager - //tabLayout = binding.mediaTab as AnimatedBottomBar viewPager.isUserInputEnabled = false viewPager.setPageTransformer(ZoomOutPageTransformer()) @@ -157,9 +172,10 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi binding.mediaCoverImage.loadImage(media.cover) binding.mediaCoverImage.setOnLongClickListener { + val coverTitle = getString(R.string.cover, media.userPreferredName) ImageViewDialog.newInstance( this, - media.userPreferredName + "[Cover]", + coverTitle, media.cover ) } @@ -176,9 +192,10 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi } override fun onLongClick(event: MotionEvent) { + val bannerTitle = getString(R.string.banner, media.userPreferredName) ImageViewDialog.newInstance( this@MediaDetailsActivity, - media.userPreferredName + "[Banner]", + bannerTitle, media.banner ?: media.cover ) banner.performClick() @@ -186,7 +203,8 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi }) banner.setOnTouchListener { _, motionEvent -> gestureDetector.onTouchEvent(motionEvent);true } if (PrefManager.getVal(PrefName.Incognito)) { - binding.mediaTitle.text = " ${media.userPreferredName}" + val mediaTitle = " ${media.userPreferredName}" + binding.mediaTitle.text = mediaTitle binding.incognito.visibility = View.VISIBLE } else { binding.mediaTitle.text = media.userPreferredName @@ -210,20 +228,6 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi R.drawable.ic_round_favorite_24 ) ) - val typedValue = TypedValue() - this.theme.resolveAttribute( - com.google.android.material.R.attr.colorSecondary, - typedValue, - true - ) - val color = typedValue.data - val typedValue2 = TypedValue() - this.theme.resolveAttribute( - com.google.android.material.R.attr.colorSecondary, - typedValue2, - true - ) - val color2 = typedValue.data PopImageButton( scope, @@ -231,7 +235,7 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi R.drawable.ic_round_favorite_24, R.drawable.ic_round_favorite_border_24, R.color.bg_opp, - R.color.violet_400,//TODO: Change to colorSecondary + R.color.violet_400, media.isFav ) { media.isFav = it @@ -246,22 +250,12 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi @SuppressLint("ResourceType") fun total() { val text = SpannableStringBuilder().apply { - val typedValue = TypedValue() - this@MediaDetailsActivity.theme.resolveAttribute( - com.google.android.material.R.attr.colorOnBackground, - typedValue, - true - ) - val white = typedValue.data + + val white = this@MediaDetailsActivity.getThemeColor(com.google.android.material.R.attr.colorOnBackground) if (media.userStatus != null) { append(if (media.anime != null) getString(R.string.watched_num) else getString(R.string.read_num)) - val typedValue = TypedValue() - theme.resolveAttribute( - com.google.android.material.R.attr.colorSecondary, - typedValue, - true - ) - bold { color(typedValue.data) { append("${media.userProgress}") } } + val colorSecondary = getThemeColor(com.google.android.material.R.attr.colorSecondary) + bold { color(colorSecondary) { append("${media.userProgress}") } } append( if (media.anime != null) getString(R.string.episodes_out_of) else getString( R.string.chapters_out_of @@ -342,18 +336,16 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi progress() } } - tabLayout = TripleNavAdapter( - binding.mediaTab1, - binding.mediaTab2, - binding.mediaTab3, - media.anime != null, - media.format ?: "", - isVertical == 1 - ) adult = media.isAdult if (media.anime != null) { viewPager.adapter = - ViewPagerAdapter(supportFragmentManager, lifecycle, SupportedMedia.ANIME, media, intent.getIntExtra("commentId", -1)) + ViewPagerAdapter( + supportFragmentManager, + lifecycle, + SupportedMedia.ANIME, + media, + intent.getIntExtra("commentId", -1) + ) } else if (media.manga != null) { viewPager.adapter = ViewPagerAdapter( supportFragmentManager, @@ -365,31 +357,47 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi anime = false } - selected = media.selected!!.window binding.mediaTitle.translationX = -screenWidth - tabLayout.selectionListener = { selected, newId -> - binding.commentInputLayout.visibility = if (selected == 2) View.VISIBLE else View.GONE - this.selected = selected - selectFromID(newId) - viewPager.setCurrentItem(selected, false) - val sel = model.loadSelected(media, isDownload) - sel.window = selected - model.saveSelected(media.id, sel) + val infoTab = navBar.createTab(R.drawable.ic_round_info_24, R.string.info, R.id.info) + val watchTab = if (anime) { + navBar.createTab(R.drawable.ic_round_movie_filter_24, R.string.watch, R.id.watch) + } else if (media.format == "NOVEL") { + navBar.createTab(R.drawable.ic_round_book_24, R.string.read, R.id.read) + } else { + navBar.createTab(R.drawable.ic_round_import_contacts_24, R.string.read, R.id.read) } - tabLayout.selectTab(selected) - selectFromID(tabLayout.selected) - viewPager.setCurrentItem(selected, false) - + val commentTab = + navBar.createTab(R.drawable.ic_round_comment_24, R.string.comments, R.id.comment) + navBar.addTab(infoTab) + navBar.addTab(watchTab) + navBar.addTab(commentTab) if (model.continueMedia == null && media.cameFromContinue) { model.continueMedia = PrefManager.getVal(PrefName.ContinueMedia) selected = 1 } - val frag = intent.getStringExtra("FRAGMENT_TO_LOAD") - if (frag != null) { - selected = 2 + if (intent.getStringExtra("FRAGMENT_TO_LOAD") != null) selected = 2 + if (viewPager.currentItem != selected) viewPager.post { + viewPager.setCurrentItem(selected, false) } + binding.commentInputLayout.isVisible = selected == 2 + navBar.selectTabAt(selected) + navBar.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener { + override fun onTabSelected( + lastIndex: Int, + lastTab: AnimatedBottomBar.Tab?, + newIndex: Int, + newTab: AnimatedBottomBar.Tab + ) { + selected = newIndex + binding.commentInputLayout.isVisible = selected == 2 + viewPager.setCurrentItem(selected, true) + val sel = model.loadSelected(media, isDownload) + sel.window = selected + model.saveSelected(media.id, sel) + } + }) val live = Refresh.activity.getOrPut(this.hashCode()) { MutableLiveData(true) } live.observe(this) { @@ -402,40 +410,21 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi } } - private fun selectFromID(id: Int) { - when (id) { - R.id.info -> { - selected = 0 - } - - R.id.watch, R.id.read -> { - selected = 1 - } - - R.id.comment -> { - selected = 2 - } - } - } - - private fun idFromSelect(): Int { - if (anime) when (selected) { - 0 -> return R.id.info - 1 -> return R.id.watch - 2 -> return R.id.comment - } - else when (selected) { - 0 -> return R.id.info - 1 -> return R.id.read - 2 -> return R.id.comment - } - return R.id.info + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + val rightMargin = if (resources.configuration.orientation == + Configuration.ORIENTATION_LANDSCAPE + ) navBarHeight else 0 + val bottomMargin = if (resources.configuration.orientation == + Configuration.ORIENTATION_LANDSCAPE + ) 0 else navBarHeight + val params: ViewGroup.MarginLayoutParams = + navBar.layoutParams as ViewGroup.MarginLayoutParams + params.updateMargins(right = rightMargin, bottom = bottomMargin) } override fun onResume() { - if (this::tabLayout.isInitialized) { - tabLayout.selectTab(selected) - } + navBar.selectTabAt(selected) super.onResume() } @@ -443,7 +432,7 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi ANIME, MANGA, NOVEL } - //ViewPager + // ViewPager private class ViewPagerAdapter( fragmentManager: FragmentManager, lifecycle: Lifecycle, @@ -462,6 +451,7 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi SupportedMedia.MANGA -> MangaReadFragment() SupportedMedia.NOVEL -> NovelReadFragment() } + 2 -> { val fragment = CommentsFragment() val bundle = Bundle() @@ -489,13 +479,6 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi binding.mediaCover.visibility = if (binding.mediaCover.scaleX == 0f) View.GONE else View.VISIBLE val duration = (200 * (PrefManager.getVal(PrefName.AnimationSpeed) as Float)).toLong() - val typedValue = TypedValue() - this@MediaDetailsActivity.theme.resolveAttribute( - com.google.android.material.R.attr.colorSecondary, - typedValue, - true - ) - val color = typedValue.data if (percentage >= percent && !isCollapsed) { isCollapsed = true ObjectAnimator.ofFloat(binding.mediaTitle, "translationX", 0f).setDuration(duration) diff --git a/app/src/main/java/ani/dantotsu/media/MediaDetailsViewModel.kt b/app/src/main/java/ani/dantotsu/media/MediaDetailsViewModel.kt index 650e722d..cfd9c736 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaDetailsViewModel.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaDetailsViewModel.kt @@ -9,7 +9,6 @@ import androidx.lifecycle.ViewModel import ani.dantotsu.R import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.currContext -import ani.dantotsu.util.Logger import ani.dantotsu.media.anime.Episode import ani.dantotsu.media.anime.SelectorDialogFragment import ani.dantotsu.media.manga.MangaChapter @@ -29,6 +28,7 @@ import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString import ani.dantotsu.tryWithSuspend +import ani.dantotsu.util.Logger import com.bumptech.glide.load.resource.bitmap.BitmapTransformation import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope @@ -52,26 +52,23 @@ class MediaDetailsViewModel : ViewModel() { it } if (isDownload) { - data.sourceIndex = if (media.anime != null) { - AnimeSources.list.size - 1 - } else if (media.format == "MANGA" || media.format == "ONE_SHOT") { - MangaSources.list.size - 1 - } else { - NovelSources.list.size - 1 + data.sourceIndex = when { + media.anime != null -> { + AnimeSources.list.size - 1 + } + + media.format == "MANGA" || media.format == "ONE_SHOT" -> { + MangaSources.list.size - 1 + } + + else -> { + NovelSources.list.size - 1 + } } } return data } - fun loadSelectedStringLocation(sourceName: String): Int { - //find the location of the source in the list - var location = watchSources?.list?.indexOfFirst { it.name == sourceName } ?: 0 - if (location == -1) { - location = 0 - } - return location - } - var continueMedia: Boolean? = null private var loading = false @@ -152,10 +149,10 @@ class MediaDetailsViewModel : ViewModel() { watchSources?.get(i)?.apply { if (!post && !allowsPreloading) return@apply ep.sEpisode?.let { - loadByVideoServers(link, ep.extra, it) { - if (it.videos.isNotEmpty()) { - list.add(it) - ep.extractorCallback?.invoke(it) + loadByVideoServers(link, ep.extra, it) { extractor -> + if (extractor.videos.isNotEmpty()) { + list.add(extractor) + ep.extractorCallback?.invoke(extractor) } } } @@ -291,7 +288,6 @@ class MediaDetailsViewModel : ViewModel() { suspend fun loadMangaChapterImages( chapter: MangaChapter, selected: Selected, - series: String, post: Boolean = true ): Boolean { diff --git a/app/src/main/java/ani/dantotsu/media/MediaInfoFragment.kt b/app/src/main/java/ani/dantotsu/media/MediaInfoFragment.kt index 06fb3aa9..216c937f 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaInfoFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaInfoFragment.kt @@ -3,7 +3,6 @@ package ani.dantotsu.media import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Intent -import android.net.Uri import android.os.Build import android.os.Bundle import android.os.CountDownTimer @@ -16,18 +15,37 @@ import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import androidx.core.text.HtmlCompat +import androidx.core.view.isGone +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager -import ani.dantotsu.* +import ani.dantotsu.R import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.GenresViewModel -import ani.dantotsu.databinding.* +import ani.dantotsu.copyToClipboard +import ani.dantotsu.currActivity +import ani.dantotsu.databinding.ActivityGenreBinding +import ani.dantotsu.databinding.FragmentMediaInfoBinding +import ani.dantotsu.databinding.ItemChipBinding +import ani.dantotsu.databinding.ItemQuelsBinding +import ani.dantotsu.databinding.ItemTitleChipgroupBinding +import ani.dantotsu.databinding.ItemTitleRecyclerBinding +import ani.dantotsu.databinding.ItemTitleTextBinding +import ani.dantotsu.databinding.ItemTitleTrailerBinding +import ani.dantotsu.displayTimer +import ani.dantotsu.isOnline +import ani.dantotsu.loadImage +import ani.dantotsu.navBarHeight +import ani.dantotsu.profile.User +import ani.dantotsu.px +import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import com.xwray.groupie.GroupieAdapter import io.noties.markwon.Markwon import io.noties.markwon.SoftBreakAddsNewLinePlugin import kotlinx.coroutines.Dispatchers @@ -37,7 +55,6 @@ import java.io.Serializable import java.net.URLEncoder -@SuppressLint("SetTextI18n") class MediaInfoFragment : Fragment() { private var _binding: FragmentMediaInfoBinding? = null private val binding get() = _binding!! @@ -46,6 +63,8 @@ class MediaInfoFragment : Fragment() { private var type = "ANIME" private val genreModel: GenresViewModel by activityViewModels() + private val tripleTab = "\t\t\t" + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, @@ -62,9 +81,10 @@ class MediaInfoFragment : Fragment() { @SuppressLint("SetJavaScriptEnabled") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val model: MediaDetailsViewModel by activityViewModels() - val offline: Boolean = PrefManager.getVal(PrefName.OfflineMode) - binding.mediaInfoProgressBar.visibility = if (!loaded) View.VISIBLE else View.GONE - binding.mediaInfoContainer.visibility = if (loaded) View.VISIBLE else View.GONE + val offline: Boolean = + PrefManager.getVal(PrefName.OfflineMode) || !isOnline(requireContext()) + binding.mediaInfoProgressBar.isGone = loaded + binding.mediaInfoContainer.isVisible = loaded binding.mediaInfoContainer.updateLayoutParams { bottomMargin += 128f.px + navBarHeight } model.scrolledToTop.observe(viewLifecycleOwner) { @@ -75,17 +95,18 @@ class MediaInfoFragment : Fragment() { if (media != null && !loaded) { loaded = true - binding.mediaInfoProgressBar.visibility = View.GONE binding.mediaInfoContainer.visibility = View.VISIBLE - binding.mediaInfoName.text = "\t\t\t" + (media.name ?: media.nameRomaji) + val infoName = tripleTab + (media.name ?: media.nameRomaji) + binding.mediaInfoName.text = infoName binding.mediaInfoName.setOnLongClickListener { copyToClipboard(media.name ?: media.nameRomaji) true } if (media.name != null) binding.mediaInfoNameRomajiContainer.visibility = View.VISIBLE - binding.mediaInfoNameRomaji.text = "\t\t\t" + media.nameRomaji + val infoNameRomanji = tripleTab + media.nameRomaji + binding.mediaInfoNameRomaji.text = infoNameRomanji binding.mediaInfoNameRomaji.setOnLongClickListener { copyToClipboard(media.nameRomaji) true @@ -97,6 +118,8 @@ class MediaInfoFragment : Fragment() { binding.mediaInfoSource.text = media.source binding.mediaInfoStart.text = media.startDate?.toString() ?: "??" binding.mediaInfoEnd.text = media.endDate?.toString() ?: "??" + binding.mediaInfoPopularity.text = media.popularity.toString() + binding.mediaInfoFavorites.text = media.favourites.toString() if (media.anime != null) { val episodeDuration = media.anime.episodeDuration @@ -125,8 +148,10 @@ class MediaInfoFragment : Fragment() { } binding.mediaInfoDurationContainer.visibility = View.VISIBLE binding.mediaInfoSeasonContainer.visibility = View.VISIBLE - binding.mediaInfoSeason.text = - (media.anime.season ?: "??") + " " + (media.anime.seasonYear ?: "??") + val seasonInfo = + "${(media.anime.season ?: "??")} ${(media.anime.seasonYear ?: "??")}" + binding.mediaInfoSeason.text = seasonInfo + if (media.anime.mainStudio != null) { binding.mediaInfoStudioContainer.visibility = View.VISIBLE binding.mediaInfoStudio.text = media.anime.mainStudio!!.name @@ -160,9 +185,12 @@ class MediaInfoFragment : Fragment() { } } binding.mediaInfoTotalTitle.setText(R.string.total_eps) - binding.mediaInfoTotal.text = - if (media.anime.nextAiringEpisode != null) (media.anime.nextAiringEpisode.toString() + " | " + (media.anime.totalEpisodes - ?: "~").toString()) else (media.anime.totalEpisodes ?: "~").toString() + val infoTotal = if (media.anime.nextAiringEpisode != null) + "${media.anime.nextAiringEpisode} | ${media.anime.totalEpisodes ?: "~"}" + else + (media.anime.totalEpisodes ?: "~").toString() + binding.mediaInfoTotal.text = infoTotal + } else if (media.manga != null) { type = "MANGA" binding.mediaInfoTotalTitle.setText(R.string.total_chaps) @@ -189,8 +217,10 @@ class MediaInfoFragment : Fragment() { (media.description ?: "null").replace("\\n", "
").replace("\\\"", "\""), HtmlCompat.FROM_HTML_MODE_LEGACY ) - binding.mediaInfoDescription.text = - "\t\t\t" + if (desc.toString() != "null") desc else getString(R.string.no_description_available) + val infoDesc = + tripleTab + if (desc.toString() != "null") desc else getString(R.string.no_description_available) + binding.mediaInfoDescription.text = infoDesc + binding.mediaInfoDescription.setOnClickListener { if (binding.mediaInfoDescription.maxLines == 5) { ObjectAnimator.ofInt(binding.mediaInfoDescription, "maxLines", 100) @@ -200,8 +230,7 @@ class MediaInfoFragment : Fragment() { .setDuration(400).start() } } - - countDown(media, binding.mediaInfoContainer) + displayTimer(media, binding.mediaInfoContainer) val parent = _binding?.mediaInfoContainer!! val screenWidth = resources.displayMetrics.run { widthPixels / density } @@ -223,7 +252,41 @@ class MediaInfoFragment : Fragment() { } parent.addView(bind.root) } - + if (!media.users.isNullOrEmpty() && !offline) { + val users: ArrayList = media.users ?: arrayListOf() + if (Anilist.token != null && media.userStatus != null) { + users.add( + 0, + User( + id = Anilist.userid!!, + name = getString(R.string.you), + pfp = Anilist.avatar, + banner = "", + status = media.userStatus, + score = media.userScore.toFloat(), + progress = media.userProgress, + totalEpisodes = media.anime?.totalEpisodes + ?: media.manga?.totalChapters, + nextAiringEpisode = media.anime?.nextAiringEpisode + ) + ) + } + ItemTitleRecyclerBinding.inflate( + LayoutInflater.from(context), + parent, + false + ).apply { + itemTitle.visibility = View.GONE + itemRecycler.adapter = + MediaSocialAdapter(users, type, requireActivity()) + itemRecycler.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + parent.addView(root) + } + } if (media.trailer != null && !offline) { @Suppress("DEPRECATION") class MyChrome : WebChromeClient() { @@ -413,113 +476,140 @@ class MediaInfoFragment : Fragment() { if (!media.relations.isNullOrEmpty() && !offline) { if (media.sequel != null || media.prequel != null) { - val bind = ItemQuelsBinding.inflate( + ItemQuelsBinding.inflate( LayoutInflater.from(context), parent, false - ) + ).apply { - if (media.sequel != null) { - bind.mediaInfoSequel.visibility = View.VISIBLE - bind.mediaInfoSequelImage.loadImage( - media.sequel!!.banner ?: media.sequel!!.cover - ) - bind.mediaInfoSequel.setSafeOnClickListener { - ContextCompat.startActivity( - requireContext(), - Intent( - requireContext(), - MediaDetailsActivity::class.java - ).putExtra( - "media", - media.sequel as Serializable - ), null + if (media.sequel != null) { + mediaInfoSequel.visibility = View.VISIBLE + mediaInfoSequelImage.loadImage( + media.sequel!!.banner ?: media.sequel!!.cover ) - } - } - if (media.prequel != null) { - bind.mediaInfoPrequel.visibility = View.VISIBLE - bind.mediaInfoPrequelImage.loadImage( - media.prequel!!.banner ?: media.prequel!!.cover - ) - bind.mediaInfoPrequel.setSafeOnClickListener { - ContextCompat.startActivity( - requireContext(), - Intent( + mediaInfoSequel.setSafeOnClickListener { + ContextCompat.startActivity( requireContext(), - MediaDetailsActivity::class.java - ).putExtra( - "media", - media.prequel as Serializable - ), null - ) + Intent( + requireContext(), + MediaDetailsActivity::class.java + ).putExtra( + "media", + media.sequel as Serializable + ), null + ) + } } + if (media.prequel != null) { + mediaInfoPrequel.visibility = View.VISIBLE + mediaInfoPrequelImage.loadImage( + media.prequel!!.banner ?: media.prequel!!.cover + ) + mediaInfoPrequel.setSafeOnClickListener { + ContextCompat.startActivity( + requireContext(), + Intent( + requireContext(), + MediaDetailsActivity::class.java + ).putExtra( + "media", + media.prequel as Serializable + ), null + ) + } + } + parent.addView(root) } - parent.addView(bind.root) } - val bindi = ItemTitleRecyclerBinding.inflate( + if (!media.review.isNullOrEmpty()) { + ItemTitleRecyclerBinding.inflate( + LayoutInflater.from(context), + parent, + false + ).apply { + val adapter = GroupieAdapter() + media.review!!.forEach { adapter.add(ReviewAdapter(it)) } + itemTitle.setText(R.string.reviews) + itemRecycler.adapter = adapter + itemRecycler.layoutManager = LinearLayoutManager(requireContext()) + itemMore.visibility = View.VISIBLE + itemMore.setSafeOnClickListener { + startActivity( + Intent(requireContext(), ReviewActivity::class.java) + .putExtra("mediaId", media.id) + ) + } + parent.addView(root) + } + } + + ItemTitleRecyclerBinding.inflate( LayoutInflater.from(context), parent, false - ) + ).apply { - bindi.itemRecycler.adapter = - MediaAdaptor(0, media.relations!!, requireActivity()) - bindi.itemRecycler.layoutManager = LinearLayoutManager( - requireContext(), - LinearLayoutManager.HORIZONTAL, - false - ) - parent.addView(bindi.root) + itemRecycler.adapter = + MediaAdaptor(0, media.relations!!, requireActivity()) + itemRecycler.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + parent.addView(root) + } } if (!media.characters.isNullOrEmpty() && !offline) { - val bind = ItemTitleRecyclerBinding.inflate( + ItemTitleRecyclerBinding.inflate( LayoutInflater.from(context), parent, false - ) - bind.itemTitle.setText(R.string.characters) - bind.itemRecycler.adapter = - CharacterAdapter(media.characters!!) - bind.itemRecycler.layoutManager = LinearLayoutManager( - requireContext(), - LinearLayoutManager.HORIZONTAL, - false - ) - parent.addView(bind.root) + ).apply { + itemTitle.setText(R.string.characters) + itemRecycler.adapter = + CharacterAdapter(media.characters!!) + itemRecycler.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + parent.addView(root) + } } if (!media.staff.isNullOrEmpty() && !offline) { - val bind = ItemTitleRecyclerBinding.inflate( + ItemTitleRecyclerBinding.inflate( LayoutInflater.from(context), parent, false - ) - bind.itemTitle.setText(R.string.staff) - bind.itemRecycler.adapter = - AuthorAdapter(media.staff!!) - bind.itemRecycler.layoutManager = LinearLayoutManager( - requireContext(), - LinearLayoutManager.HORIZONTAL, - false - ) - parent.addView(bind.root) + ).apply { + itemTitle.setText(R.string.staff) + itemRecycler.adapter = + AuthorAdapter(media.staff!!) + itemRecycler.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + parent.addView(root) + } } if (!media.recommendations.isNullOrEmpty() && !offline) { - val bind = ItemTitleRecyclerBinding.inflate( + ItemTitleRecyclerBinding.inflate( LayoutInflater.from(context), parent, false - ) - bind.itemTitle.setText(R.string.recommended) - bind.itemRecycler.adapter = - MediaAdaptor(0, media.recommendations!!, requireActivity()) - bind.itemRecycler.layoutManager = LinearLayoutManager( - requireContext(), - LinearLayoutManager.HORIZONTAL, - false - ) - parent.addView(bind.root) + ).apply { + itemTitle.setText(R.string.recommended) + itemRecycler.adapter = + MediaAdaptor(0, media.recommendations!!, requireActivity()) + itemRecycler.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.HORIZONTAL, + false + ) + parent.addView(root) + } } } } @@ -544,11 +634,12 @@ class MediaInfoFragment : Fragment() { } } } + super.onViewCreated(view, null) } override fun onResume() { - binding.mediaInfoProgressBar.visibility = if (!loaded) View.VISIBLE else View.GONE + binding.mediaInfoProgressBar.isGone = loaded super.onResume() } diff --git a/app/src/main/java/ani/dantotsu/media/MediaListDialogFragment.kt b/app/src/main/java/ani/dantotsu/media/MediaListDialogFragment.kt index 0430709b..1117f342 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaListDialogFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaListDialogFragment.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.os.Bundle import android.text.InputFilter.LengthFilter import android.view.Gravity @@ -11,11 +10,19 @@ import android.widget.ArrayAdapter import androidx.core.view.updateLayoutParams import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope -import ani.dantotsu.* +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.DatePickerFragment +import ani.dantotsu.InputFilterMinMax +import ani.dantotsu.R +import ani.dantotsu.Refresh import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.api.FuzzyDate import ani.dantotsu.connections.mal.MAL import ani.dantotsu.databinding.BottomSheetMediaListBinding +import ani.dantotsu.navBarHeight +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.snackString +import ani.dantotsu.tryWith import com.google.android.material.materialswitch.MaterialSwitch import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -36,7 +43,6 @@ class MediaListDialogFragment : BottomSheetDialogFragment() { return binding.root } - @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.mediaListContainer.updateLayoutParams { bottomMargin += navBarHeight } var media: Media? @@ -168,9 +174,10 @@ class MediaListDialogFragment : BottomSheetDialogFragment() { val init = if (binding.mediaListProgress.text.toString() != "") binding.mediaListProgress.text.toString() .toInt() else 0 - if (init < (total - ?: 5000) - ) binding.mediaListProgress.setText((init + 1).toString()) + if (init < (total ?: 5000)) { + val progressText = "${init + 1}" + binding.mediaListProgress.setText(progressText) + } if (init + 1 == (total ?: 5000)) { binding.mediaListStatus.setText(statusStrings[2], false) onComplete() @@ -181,7 +188,12 @@ class MediaListDialogFragment : BottomSheetDialogFragment() { binding.mediaListPrivate.setOnCheckedChangeListener { _, checked -> media?.isListPrivate = checked } - + val removeList = PrefManager.getCustomVal("removeList", setOf()) + var remove: Boolean? = null + binding.mediaListShow.isChecked = media?.id in removeList + binding.mediaListShow.setOnCheckedChangeListener { _, checked -> + remove = checked + } media?.userRepeat?.apply { binding.mediaListRewatch.setText(this.toString()) } @@ -247,6 +259,11 @@ class MediaListDialogFragment : BottomSheetDialogFragment() { ) } } + if (remove == true) { + PrefManager.setCustomVal("removeList", removeList.plus(media!!.id)) + } else if (remove == false) { + PrefManager.setCustomVal("removeList", removeList.minus(media!!.id)) + } Refresh.all() snackString(getString(R.string.list_updated)) dismissAllowingStateLoss() @@ -269,6 +286,7 @@ class MediaListDialogFragment : BottomSheetDialogFragment() { } } } + PrefManager.setCustomVal("removeList", removeList.minus(media?.id)) } if (id != null) { Refresh.all() diff --git a/app/src/main/java/ani/dantotsu/media/MediaListDialogSmallFragment.kt b/app/src/main/java/ani/dantotsu/media/MediaListDialogSmallFragment.kt index 982eca8e..caf882e6 100644 --- a/app/src/main/java/ani/dantotsu/media/MediaListDialogSmallFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/MediaListDialogSmallFragment.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.os.Bundle import android.text.InputFilter.LengthFilter import android.view.Gravity @@ -10,11 +9,17 @@ import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.core.view.updateLayoutParams import androidx.lifecycle.lifecycleScope -import ani.dantotsu.* +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.InputFilterMinMax +import ani.dantotsu.R +import ani.dantotsu.Refresh import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.mal.MAL import ani.dantotsu.databinding.BottomSheetMediaListSmallBinding +import ani.dantotsu.navBarHeight import ani.dantotsu.others.getSerialized +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.snackString import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -54,7 +59,6 @@ class MediaListDialogSmallFragment : BottomSheetDialogFragment() { } - @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.mediaListContainer.updateLayoutParams { bottomMargin += navBarHeight } val scope = viewLifecycleOwner.lifecycleScope @@ -68,7 +72,7 @@ class MediaListDialogSmallFragment : BottomSheetDialogFragment() { MAL.query.deleteList(media.anime != null, media.idMAL) } catch (e: Exception) { withContext(Dispatchers.Main) { - snackString("Failed to delete because of... ${e.message}") + snackString(getString(R.string.delete_fail_reason, e.message)) } return@withContext } @@ -154,7 +158,10 @@ class MediaListDialogSmallFragment : BottomSheetDialogFragment() { val init = if (binding.mediaListProgress.text.toString() != "") binding.mediaListProgress.text.toString() .toInt() else 0 - if (init < (total ?: 5000)) binding.mediaListProgress.setText((init + 1).toString()) + if (init < (total ?: 5000)) { + val progressText = "${init + 1}" + binding.mediaListProgress.setText(progressText) + } if (init + 1 == (total ?: 5000)) { binding.mediaListStatus.setText(statusStrings[2], false) } @@ -164,7 +171,12 @@ class MediaListDialogSmallFragment : BottomSheetDialogFragment() { binding.mediaListPrivate.setOnCheckedChangeListener { _, checked -> media.isListPrivate = checked } - + val removeList = PrefManager.getCustomVal("removeList", setOf()) + var remove: Boolean? = null + binding.mediaListShow.isChecked = media.id in removeList + binding.mediaListShow.setOnCheckedChangeListener { _, checked -> + remove = checked + } binding.mediaListSave.setOnClickListener { scope.launch { withContext(Dispatchers.IO) { @@ -192,6 +204,11 @@ class MediaListDialogSmallFragment : BottomSheetDialogFragment() { ) } } + if (remove == true) { + PrefManager.setCustomVal("removeList", removeList.plus(media.id)) + } else if (remove == false) { + PrefManager.setCustomVal("removeList", removeList.minus(media.id)) + } Refresh.all() snackString(getString(R.string.list_updated)) dismissAllowingStateLoss() diff --git a/app/src/main/java/ani/dantotsu/media/MediaListViewActivity.kt b/app/src/main/java/ani/dantotsu/media/MediaListViewActivity.kt new file mode 100644 index 00000000..60a9e898 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/MediaListViewActivity.kt @@ -0,0 +1,93 @@ +package ani.dantotsu.media + +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import android.view.Window +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.updateLayoutParams +import androidx.recyclerview.widget.GridLayoutManager +import ani.dantotsu.R +import ani.dantotsu.databinding.ActivityMediaListViewBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.hideSystemBarsExtendView +import ani.dantotsu.initActivity +import ani.dantotsu.others.getSerialized +import ani.dantotsu.settings.saving.PrefManager +import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import java.util.ArrayList + +class MediaListViewActivity: AppCompatActivity() { + private lateinit var binding: ActivityMediaListViewBinding + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMediaListViewBinding.inflate(layoutInflater) + ThemeManager(this).applyTheme() + initActivity(this) + if (!PrefManager.getVal(PrefName.ImmersiveMode)) { + this.window.statusBarColor = + ContextCompat.getColor(this, R.color.nav_bg_inv) + binding.root.fitsSystemWindows = true + + } else { + binding.root.fitsSystemWindows = false + requestWindowFeature(Window.FEATURE_NO_TITLE) + hideSystemBarsExtendView() + binding.settingsContainer.updateLayoutParams { + topMargin = statusBarHeight + } + } + + setContentView(binding.root) + + val primaryColor = getThemeColor(com.google.android.material.R.attr.colorSurface) + val primaryTextColor = getThemeColor(com.google.android.material.R.attr.colorPrimary) + val secondaryTextColor = getThemeColor(com.google.android.material.R.attr.colorOutline) + + window.statusBarColor = primaryColor + window.navigationBarColor = primaryColor + binding.listAppBar.setBackgroundColor(primaryColor) + binding.listTitle.setTextColor(primaryTextColor) + val screenWidth = resources.displayMetrics.run { widthPixels / density } + val mediaList = passedMedia ?: intent.getSerialized("media") as? ArrayList ?: ArrayList() + if (passedMedia != null) passedMedia = null + val view = PrefManager.getCustomVal("mediaView", 0) + var mediaView: View = when (view) { + 1 -> binding.mediaList + 0 -> binding.mediaGrid + else -> binding.mediaGrid + } + mediaView.alpha = 1f + fun changeView(mode: Int, current: View) { + mediaView.alpha = 0.33f + mediaView = current + current.alpha = 1f + PrefManager.setCustomVal("mediaView", mode) + binding.mediaRecyclerView.adapter = MediaAdaptor(mode, mediaList, this) + binding.mediaRecyclerView.layoutManager = GridLayoutManager( + this, + if (mode == 1) 1 else (screenWidth / 120f).toInt() + ) + } + binding.mediaList.setOnClickListener { + changeView(1, binding.mediaList) + } + binding.mediaGrid.setOnClickListener { + changeView(0, binding.mediaGrid) + } + val text = "${intent.getStringExtra("title")} (${mediaList.count()})" + binding.listTitle.text = text + binding.mediaRecyclerView.adapter = MediaAdaptor(view, mediaList, this) + binding.mediaRecyclerView.layoutManager = GridLayoutManager( + this, + if (view == 1) 1 else (screenWidth / 120f).toInt() + ) + } + + companion object { + var passedMedia: ArrayList? = null + } +} diff --git a/app/src/main/java/ani/dantotsu/media/MediaNameAdapter.kt b/app/src/main/java/ani/dantotsu/media/MediaNameAdapter.kt new file mode 100644 index 00000000..a28bc018 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/MediaNameAdapter.kt @@ -0,0 +1,146 @@ +package ani.dantotsu.media + +import java.util.Locale +import java.util.regex.Matcher +import java.util.regex.Pattern + +object MediaNameAdapter { + + private const val REGEX_ITEM = "[\\s:.\\-]*(\\d+\\.?\\d*)[\\s:.\\-]*" + private const val REGEX_PART_NUMBER = "(? "sub" + SubDubType.DUB -> "dub" + SubDubType.NULL -> "" + } + val toggledCasePreserved = + if (subdub?.get(0)?.isUpperCase() == true || soft?.get(0) + ?.isUpperCase() == true + ) toggled.replaceFirstChar { + if (it.isLowerCase()) it.titlecase( + Locale.ROOT + ) else it.toString() + } else toggled + + subdubMatcher.replaceFirst(toggledCasePreserved + bed) + } else { + null + } + } + + fun getSubDub(text: String): SubDubType { + val subdubPattern: Pattern = Pattern.compile(REGEX_SUBDUB, Pattern.CASE_INSENSITIVE) + val subdubMatcher: Matcher = subdubPattern.matcher(text) + + return if (subdubMatcher.find()) { + val subdub = subdubMatcher.group(2)?.lowercase(Locale.ROOT) + when (subdub) { + "sub" -> SubDubType.SUB + "dub" -> SubDubType.DUB + else -> SubDubType.NULL + } + } else { + SubDubType.NULL + } + } + + enum class SubDubType { + SUB, DUB, NULL + } + + fun findSeasonNumber(text: String): Int? { + val seasonPattern: Pattern = Pattern.compile(REGEX_SEASON, Pattern.CASE_INSENSITIVE) + val seasonMatcher: Matcher = seasonPattern.matcher(text) + + return if (seasonMatcher.find()) { + seasonMatcher.group(2)?.toInt() + } else { + text.toIntOrNull() + } + } + + fun findEpisodeNumber(text: String): Float? { + val episodePattern: Pattern = Pattern.compile(REGEX_EPISODE, Pattern.CASE_INSENSITIVE) + val episodeMatcher: Matcher = episodePattern.matcher(text) + + return if (episodeMatcher.find()) { + if (episodeMatcher.group(2) != null) { + episodeMatcher.group(2)?.toFloat() + } else { + val failedEpisodeNumberPattern: Pattern = + Pattern.compile(REGEX_PART_NUMBER, Pattern.CASE_INSENSITIVE) + val failedEpisodeNumberMatcher: Matcher = + failedEpisodeNumberPattern.matcher(text) + if (failedEpisodeNumberMatcher.find()) { + failedEpisodeNumberMatcher.group(1)?.toFloat() + } else { + null + } + } + } else { + text.toFloatOrNull() + } + } + + fun removeEpisodeNumber(text: String): String { + val regexPattern = Regex(REGEX_EPISODE, RegexOption.IGNORE_CASE) + val removedNumber = text.replace(regexPattern, "").ifEmpty { + text + } + val letterPattern = Regex("[a-zA-Z]") + return if (letterPattern.containsMatchIn(removedNumber)) { + removedNumber + } else { + text + } + } + + + fun removeEpisodeNumberCompletely(text: String): String { + val regexPattern = Regex(REGEX_EPISODE, RegexOption.IGNORE_CASE) + val removedNumber = text.replace(regexPattern, "") + return if (removedNumber.equals(text, true)) { // if nothing was removed + val failedEpisodeNumberPattern = + Regex(REGEX_PART_NUMBER, RegexOption.IGNORE_CASE) + failedEpisodeNumberPattern.replace(removedNumber) { mr -> + mr.value.replaceFirst(mr.groupValues[1], "") + } + } else { + removedNumber + } + } + + fun findChapterNumber(text: String): Float? { + val pattern: Pattern = Pattern.compile(REGEX_CHAPTER, Pattern.CASE_INSENSITIVE) + val matcher: Matcher = pattern.matcher(text) + + return if (matcher.find()) { + matcher.group(2)?.toFloat() + } else { + val failedChapterNumberPattern: Pattern = + Pattern.compile(REGEX_PART_NUMBER, Pattern.CASE_INSENSITIVE) + val failedChapterNumberMatcher: Matcher = + failedChapterNumberPattern.matcher(text) + if (failedChapterNumberMatcher.find()) { + failedChapterNumberMatcher.group(1)?.toFloat() + } else { + text.toFloatOrNull() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/MediaSocialAdapter.kt b/app/src/main/java/ani/dantotsu/media/MediaSocialAdapter.kt new file mode 100644 index 00000000..a267cd6b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/MediaSocialAdapter.kt @@ -0,0 +1,82 @@ +package ani.dantotsu.media + +import android.content.Intent +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import androidx.fragment.app.FragmentActivity +import androidx.recyclerview.widget.RecyclerView +import ani.dantotsu.R +import ani.dantotsu.databinding.ItemFollowerGridBinding +import ani.dantotsu.getAppString +import ani.dantotsu.loadImage +import ani.dantotsu.others.ImageViewDialog +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.User +import ani.dantotsu.setAnimation + +class MediaSocialAdapter( + val user: ArrayList, + val type: String, + val activity: FragmentActivity +) : RecyclerView.Adapter() { + + inner class FollowerGridViewHolder(val binding: ItemFollowerGridBinding) : + RecyclerView.ViewHolder(binding.root) + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FollowerGridViewHolder { + return FollowerGridViewHolder( + ItemFollowerGridBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + } + + + override fun onBindViewHolder(holder: FollowerGridViewHolder, position: Int) { + holder.binding.apply { + val user = user[position] + val score = user.score?.div(10.0) ?: 0.0 + setAnimation(root.context, root) + profileUserName.text = user.name + profileInfo.apply { + text = when (user.status) { + "CURRENT" -> if (type == "ANIME") getAppString(R.string.watching) else getAppString(R.string.reading) + else -> user.status ?: "" + } + visibility = View.VISIBLE + } + profileCompactUserProgress.text = user.progress.toString() + profileCompactScore.text = score.toString() + " | ${user.totalEpisodes ?: "~"}".also { profileCompactTotal.text = it } + profileUserAvatar.loadImage(user.pfp) + + val scoreDrawable = if (score == 0.0) R.drawable.score else R.drawable.user_score + profileCompactScoreBG.apply { + visibility = View.VISIBLE + background = ContextCompat.getDrawable(root.context, scoreDrawable) + } + + profileCompactProgressContainer.visibility = View.VISIBLE + + profileUserAvatar.setOnClickListener { + ContextCompat.startActivity(root.context, + Intent(root.context, ProfileActivity::class.java) + .putExtra("userId", user.id), + null) + } + profileUserAvatarContainer.setOnLongClickListener { + ImageViewDialog.newInstance( + activity, + activity.getString(R.string.avatar, user.name), + user.pfp + ) + } + } + } + + override fun getItemCount(): Int = user.size +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/MediaType.kt b/app/src/main/java/ani/dantotsu/media/MediaType.kt new file mode 100644 index 00000000..61cb2239 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/MediaType.kt @@ -0,0 +1,56 @@ +package ani.dantotsu.media + +interface Type { + fun asText(): String +} + +enum class MediaType : Type { + ANIME, + MANGA, + NOVEL; + + override fun asText(): String { + return when (this) { + ANIME -> "Anime" + MANGA -> "Manga" + NOVEL -> "Novel" + } + } + + companion object { + fun fromText(string: String): MediaType? { + return when (string) { + "Anime" -> ANIME + "Manga" -> MANGA + "Novel" -> NOVEL + else -> { + null + } + } + } + } +} + +enum class AddonType : Type { + TORRENT, + DOWNLOAD; + + override fun asText(): String { + return when (this) { + TORRENT -> "Torrent" + DOWNLOAD -> "Download" + } + } + + companion object { + fun fromText(string: String): AddonType? { + return when (string) { + "Torrent" -> TORRENT + "Download" -> DOWNLOAD + else -> { + null + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/OtherDetailsViewModel.kt b/app/src/main/java/ani/dantotsu/media/OtherDetailsViewModel.kt index 677d700f..0be0fc22 100644 --- a/app/src/main/java/ani/dantotsu/media/OtherDetailsViewModel.kt +++ b/app/src/main/java/ani/dantotsu/media/OtherDetailsViewModel.kt @@ -30,7 +30,7 @@ class OtherDetailsViewModel : ViewModel() { fun getCalendar(): LiveData>> = calendar suspend fun loadCalendar() { val curr = System.currentTimeMillis() / 1000 - val res = Anilist.query.recentlyUpdated(false, curr - 86400, curr + (86400 * 6)) + val res = Anilist.query.recentlyUpdated(curr - 86400, curr + (86400 * 6)) val df = DateFormat.getDateInstance(DateFormat.FULL) val map = mutableMapOf>() val idMap = mutableMapOf>() diff --git a/app/src/main/java/ani/dantotsu/media/ProgressAdapter.kt b/app/src/main/java/ani/dantotsu/media/ProgressAdapter.kt index 081d47fc..eb11c29f 100644 --- a/app/src/main/java/ani/dantotsu/media/ProgressAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/ProgressAdapter.kt @@ -27,7 +27,7 @@ class ProgressAdapter(private val horizontal: Boolean = true, searched: Boolean) return ProgressViewHolder(binding) } - @SuppressLint("SetTextI18n", "ClickableViewAccessibility") + @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: ProgressViewHolder, position: Int) { val progressBar = holder.binding.root bar = progressBar diff --git a/app/src/main/java/ani/dantotsu/media/ReviewActivity.kt b/app/src/main/java/ani/dantotsu/media/ReviewActivity.kt new file mode 100644 index 00000000..6b08734c --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/ReviewActivity.kt @@ -0,0 +1,127 @@ +package ani.dantotsu.media + +import android.annotation.SuppressLint +import android.content.Intent +import android.os.Bundle +import android.text.SpannableString +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.isVisible +import androidx.core.view.updateLayoutParams +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.LinearLayoutManager +import ani.dantotsu.R +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.api.Query +import ani.dantotsu.databinding.ActivityFollowBinding +import ani.dantotsu.initActivity +import ani.dantotsu.navBarHeight +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.util.MarkdownCreatorActivity +import com.xwray.groupie.GroupieAdapter +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class ReviewActivity : AppCompatActivity() { + private lateinit var binding: ActivityFollowBinding + val adapter = GroupieAdapter() + private val reviews = mutableListOf() + var mediaId = 0 + private var currentPage: Int = 1 + private var hasNextPage: Boolean = true + + @SuppressLint("ClickableViewAccessibility") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + initActivity(this) + binding = ActivityFollowBinding.inflate(layoutInflater) + binding.listToolbar.updateLayoutParams { + topMargin = statusBarHeight + } + binding.listFrameLayout.updateLayoutParams { + bottomMargin = navBarHeight + } + setContentView(binding.root) + mediaId = intent.getIntExtra("mediaId", -1) + if (mediaId == -1) { + finish() + return + } + binding.followerGrid.visibility = View.GONE + binding.followerList.visibility = View.GONE + binding.followFilterButton.setImageResource(R.drawable.ic_add) + binding.followFilterButton.setOnClickListener { + ContextCompat.startActivity( + this, + Intent(this, MarkdownCreatorActivity::class.java) + .putExtra("type", "review"), + null + ) + } + binding.followFilterButton.visibility = View.GONE + binding.listTitle.text = getString(R.string.reviews) + binding.listRecyclerView.adapter = adapter + binding.listRecyclerView.layoutManager = LinearLayoutManager( + this, + LinearLayoutManager.VERTICAL, + false + ) + binding.listProgressBar.visibility = View.VISIBLE + binding.listBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() } + + lifecycleScope.launch(Dispatchers.IO) { + val response = Anilist.query.getReviews(mediaId)?.data?.page + withContext(Dispatchers.Main) { + binding.listProgressBar.visibility = View.GONE + binding.listRecyclerView.setOnTouchListener { _, event -> + if (event?.action == MotionEvent.ACTION_UP) { + if (hasNextPage && !binding.listRecyclerView.canScrollVertically(1) && !binding.followRefresh.isVisible + && binding.listRecyclerView.adapter!!.itemCount != 0 && + (binding.listRecyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() == (binding.listRecyclerView.adapter!!.itemCount - 1) + ) { + binding.followRefresh.visibility = ViewGroup.VISIBLE + loadPage(++currentPage) { + binding.followRefresh.visibility = ViewGroup.GONE + } + } + } + false + } + currentPage = response?.pageInfo?.currentPage ?: 1 + hasNextPage = response?.pageInfo?.hasNextPage ?: false + response?.reviews?.let { + reviews.addAll(it) + fillList() + } + } + } + } + + private fun loadPage(page: Int, callback: () -> Unit) { + lifecycleScope.launch(Dispatchers.IO) { + val response = Anilist.query.getReviews(mediaId, page) + currentPage = response?.data?.page?.pageInfo?.currentPage ?: 1 + hasNextPage = response?.data?.page?.pageInfo?.hasNextPage ?: false + withContext(Dispatchers.Main) { + response?.data?.page?.reviews?.let { + reviews.addAll(it) + fillList() + } + callback() + } + } + } + + private fun fillList() { + adapter.clear() + reviews.forEach { + adapter.add(ReviewAdapter(it)) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/ReviewAdapter.kt b/app/src/main/java/ani/dantotsu/media/ReviewAdapter.kt new file mode 100644 index 00000000..8bb0a138 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/ReviewAdapter.kt @@ -0,0 +1,167 @@ +package ani.dantotsu.media + + +import android.app.Activity +import android.content.Intent +import android.view.View +import androidx.activity.ComponentActivity +import androidx.core.app.ActivityOptionsCompat +import androidx.core.content.ContextCompat +import androidx.core.util.Pair +import androidx.core.view.ViewCompat +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentActivity +import ani.dantotsu.R +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.api.Query +import ani.dantotsu.databinding.ItemReviewsBinding +import ani.dantotsu.loadImage +import ani.dantotsu.openImage +import ani.dantotsu.others.ImageViewDialog +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.activity.ActivityItemBuilder +import ani.dantotsu.toast +import com.xwray.groupie.viewbinding.BindableItem +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class ReviewAdapter( + private var review: Query.Review, +) : BindableItem() { + private lateinit var binding: ItemReviewsBinding + + override fun bind(viewBinding: ItemReviewsBinding, position: Int) { + binding = viewBinding + val context = binding.root.context + binding.reviewUserName.text = review.user?.name + binding.reviewUserAvatar.loadImage(review.user?.avatar?.medium) + binding.reviewText.text = review.summary + binding.reviewPostTime.text = ActivityItemBuilder.getDateTime(review.createdAt) + val text = "[${review.score/ 10.0f}]" + binding.reviewTag.text = text + binding.root.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, ReviewViewActivity::class.java) + .putExtra("review", review), + null + ) + } + binding.reviewUserName.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, ProfileActivity::class.java) + .putExtra("userId", review.user?.id), + null + ) + } + binding.reviewUserAvatar.setOnClickListener { + ContextCompat.startActivity( + context, + Intent(context, ProfileActivity::class.java) + .putExtra("userId", review.user?.id), + null + ) + } + binding.reviewUserAvatar.openImage( + context.getString( + R.string.avatar, + review.user?.name + ), + review.user?.avatar?.medium ?: "" + ) + userVote(review.userRating) + enableVote() + binding.reviewTotalVotes.text = review.rating.toString() + } + + override fun getLayout(): Int { + return R.layout.item_reviews + } + + override fun initializeViewBinding(view: View): ItemReviewsBinding { + return ItemReviewsBinding.bind(view) + } + private fun userVote(type: String) { + when (type) { + "NO_VOTE" -> { + binding.reviewUpVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) + binding.reviewDownVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) + binding.reviewUpVote.alpha = 0.6f + binding.reviewDownVote.alpha = 0.6f + } + + "UP_VOTE" -> { + binding.reviewUpVote.setImageResource(R.drawable.ic_round_upvote_active_24) + binding.reviewDownVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) + binding.reviewUpVote.alpha = 1f + binding.reviewDownVote.alpha = 0.6f + } + + "DOWN_VOTE" -> { + binding.reviewUpVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) + binding.reviewDownVote.setImageResource(R.drawable.ic_round_upvote_active_24) + binding.reviewDownVote.alpha = 1f + binding.reviewUpVote.alpha = 0.6f + } + } + } + + private fun rateReview(rating: String) { + disableVote() + val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + scope.launch { + val result = Anilist.mutation.rateReview(review.id, rating) + if (result != null) { + withContext(Dispatchers.Main) { + val res = result.data.rateReview + review.rating = res.rating + review.ratingAmount = res.ratingAmount + review.userRating = res.userRating + userVote(review.userRating) + binding.reviewTotalVotes.text = review.rating.toString() + userVote(review.userRating) + enableVote() + } + } else { + withContext(Dispatchers.Main) { + toast( + binding.root.context.getString(R.string.error_message, "response is null") + ) + enableVote() + } + } + } + } + + private fun disableVote() { + binding.reviewUpVote.setOnClickListener(null) + binding.reviewDownVote.setOnClickListener(null) + binding.reviewUpVote.isEnabled = false + binding.reviewDownVote.isEnabled = false + } + + private fun enableVote() { + binding.reviewUpVote.setOnClickListener { + if (review.userRating == "UP_VOTE") { + rateReview("NO_VOTE") + } else { + rateReview("UP_VOTE") + } + disableVote() + } + binding.reviewDownVote.setOnClickListener { + if (review.userRating == "DOWN_VOTE") { + rateReview("NO_VOTE") + } else { + rateReview("DOWN_VOTE") + } + disableVote() + } + binding.reviewUpVote.isEnabled = true + binding.reviewDownVote.isEnabled = true + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/ReviewViewActivity.kt b/app/src/main/java/ani/dantotsu/media/ReviewViewActivity.kt new file mode 100644 index 00000000..5e64d33c --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/ReviewViewActivity.kt @@ -0,0 +1,196 @@ +package ani.dantotsu.media + +import android.content.Intent +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.updateLayoutParams +import androidx.lifecycle.lifecycleScope +import ani.dantotsu.R +import ani.dantotsu.connections.anilist.Anilist +import ani.dantotsu.connections.anilist.api.Query +import ani.dantotsu.databinding.ActivityReviewViewBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.initActivity +import ani.dantotsu.loadImage +import ani.dantotsu.navBarHeight +import ani.dantotsu.openImage +import ani.dantotsu.others.ImageViewDialog +import ani.dantotsu.profile.ProfileActivity +import ani.dantotsu.profile.activity.ActivityItemBuilder +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.toast +import ani.dantotsu.util.AniMarkdown +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class ReviewViewActivity : AppCompatActivity() { + private lateinit var binding: ActivityReviewViewBinding + private lateinit var review: Query.Review + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + initActivity(this) + binding = ActivityReviewViewBinding.inflate(layoutInflater) + binding.userContainer.updateLayoutParams { + topMargin = statusBarHeight + } + binding.reviewContent.updateLayoutParams { + bottomMargin += navBarHeight + } + setContentView(binding.root) + review = intent.getSerializableExtra("review") as Query.Review + binding.userName.text = review.user?.name + binding.userAvatar.loadImage(review.user?.avatar?.medium) + binding.userTime.text = ActivityItemBuilder.getDateTime(review.createdAt) + binding.userContainer.setOnClickListener { + startActivity(Intent(this, ProfileActivity::class.java) + .putExtra("userId", review.user?.id) + ) + } + binding.userAvatar.openImage( + binding.root.context.getString(R.string.avatar, review.user?.name), + review.user?.avatar?.medium ?: "" + ) + binding.userAvatar.setOnClickListener { + startActivity(Intent(this, ProfileActivity::class.java) + .putExtra("userId", review.user?.id) + ) + } + binding.profileUserBio.settings.loadWithOverviewMode = true + binding.profileUserBio.settings.useWideViewPort = true + binding.profileUserBio.setInitialScale(1) + val styledHtml = AniMarkdown.getFullAniHTML( + review.body, + ContextCompat.getColor(this, R.color.bg_opp) + ) + binding.profileUserBio.loadDataWithBaseURL( + null, + styledHtml, + "text/html", + "utf-8", + null + ) + binding.profileUserBio.setBackgroundColor( + ContextCompat.getColor( + this, + android.R.color.transparent + ) + ) + binding.profileUserBio.setLayerType(View.LAYER_TYPE_HARDWARE, null) + binding.profileUserBio.webViewClient = object : WebViewClient() { + override fun onPageFinished(view: WebView?, url: String?) { + super.onPageFinished(view, url) + binding.profileUserBio.setBackgroundColor( + ContextCompat.getColor( + this@ReviewViewActivity, + android.R.color.transparent + ) + ) + } + + override fun shouldOverrideUrlLoading( + view: WebView?, + request: WebResourceRequest? + ): Boolean { + return true + } + } + userVote(review.userRating) + enableVote() + binding.voteCount.text = review.rating.toString() + binding.voteText.text = getString( + R.string.vote_out_of_total, + review.rating.toString(), + review.ratingAmount.toString() + ) + } + + private fun userVote(type: String) { + val selectedColor = getThemeColor(com.google.android.material.R.attr.colorPrimary) + val unselectedColor = getThemeColor(androidx.appcompat.R.attr.colorControlNormal) + when (type) { + "NO_VOTE" -> { + binding.upvote.setColorFilter(unselectedColor) + binding.downvote.setColorFilter(unselectedColor) + } + + "UP_VOTE" -> { + binding.upvote.setColorFilter(selectedColor) + binding.downvote.setColorFilter(unselectedColor) + } + + "DOWN_VOTE" -> { + binding.upvote.setColorFilter(unselectedColor) + binding.downvote.setColorFilter(selectedColor) + } + } + } + + private fun rateReview(rating: String) { + disableVote() + lifecycleScope.launch { + val result = Anilist.mutation.rateReview(review.id, rating) + if (result != null) { + withContext(Dispatchers.Main) { + val res = result.data.rateReview + review.rating = res.rating + review.ratingAmount = res.ratingAmount + review.userRating = res.userRating + userVote(review.userRating) + binding.voteCount.text = review.rating.toString() + binding.voteText.text = getString( + R.string.vote_out_of_total, + review.rating.toString(), + review.ratingAmount.toString() + ) + userVote(review.userRating) + enableVote() + } + } else { + withContext(Dispatchers.Main) { + toast( + getString(R.string.error_message, "response is null") + ) + enableVote() + } + } + } + } + + private fun disableVote() { + binding.upvote.setOnClickListener(null) + binding.downvote.setOnClickListener(null) + binding.upvote.isEnabled = false + binding.downvote.isEnabled = false + } + + private fun enableVote() { + binding.upvote.setOnClickListener { + if (review.userRating == "UP_VOTE") { + rateReview("NO_VOTE") + } else { + rateReview("UP_VOTE") + } + disableVote() + } + binding.downvote.setOnClickListener { + if (review.userRating == "DOWN_VOTE") { + rateReview("NO_VOTE") + } else { + rateReview("DOWN_VOTE") + } + disableVote() + } + binding.upvote.isEnabled = true + binding.downvote.isEnabled = true + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/SearchActivity.kt b/app/src/main/java/ani/dantotsu/media/SearchActivity.kt index 33403915..358c9700 100644 --- a/app/src/main/java/ani/dantotsu/media/SearchActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/SearchActivity.kt @@ -4,24 +4,30 @@ import android.annotation.SuppressLint import android.os.Bundle import android.os.Parcelable import android.view.View +import android.view.WindowManager import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible import androidx.core.view.updatePaddingRelative import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView -import ani.dantotsu.* import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.AnilistSearch import ani.dantotsu.connections.anilist.SearchResults import ani.dantotsu.databinding.ActivitySearchBinding +import ani.dantotsu.initActivity +import ani.dantotsu.navBarHeight +import ani.dantotsu.px import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.statusBarHeight import ani.dantotsu.themes.ThemeManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -import java.util.* +import java.util.Timer +import java.util.TimerTask class SearchActivity : AppCompatActivity() { private lateinit var binding: ActivitySearchBinding @@ -64,11 +70,18 @@ class SearchActivity : AppCompatActivity() { intent.getStringExtra("type") ?: "ANIME", isAdult = if (Anilist.adult) intent.getBooleanExtra("hentai", false) else false, onList = listOnly, + search = intent.getStringExtra("query"), genres = intent.getStringExtra("genre")?.let { mutableListOf(it) }, tags = intent.getStringExtra("tag")?.let { mutableListOf(it) }, sort = intent.getStringExtra("sortBy"), + status = intent.getStringExtra("status"), + source = intent.getStringExtra("source"), + countryOfOrigin = intent.getStringExtra("country"), season = intent.getStringExtra("season"), - seasonYear = intent.getStringExtra("seasonYear")?.toIntOrNull(), + seasonYear = if (intent.getStringExtra("type") == "ANIME") intent.getStringExtra("seasonYear") + ?.toIntOrNull() else null, + startYear = if (intent.getStringExtra("type") == "MANGA") intent.getStringExtra("seasonYear") + ?.toIntOrNull() else null, results = mutableListOf(), hasNextPage = false ) @@ -127,8 +140,12 @@ class SearchActivity : AppCompatActivity() { excludedTags = it.excludedTags tags = it.tags season = it.season + startYear = it.startYear seasonYear = it.seasonYear + status = it.status + source = it.source format = it.format + countryOfOrigin = it.countryOfOrigin page = it.page hasNextPage = it.hasNextPage } @@ -137,7 +154,7 @@ class SearchActivity : AppCompatActivity() { model.searchResults.results.addAll(it.results) mediaAdaptor.notifyItemRangeInserted(prev, it.results.size) - progressAdapter.bar?.visibility = if (it.hasNextPage) View.VISIBLE else View.GONE + progressAdapter.bar?.isVisible = it.hasNextPage } } @@ -151,7 +168,10 @@ class SearchActivity : AppCompatActivity() { } else headerAdaptor.requestFocus?.run() - if (intent.getBooleanExtra("search", false)) search() + if (intent.getBooleanExtra("search", false)) { + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED) + search() + } } } } diff --git a/app/src/main/java/ani/dantotsu/media/SearchAdapter.kt b/app/src/main/java/ani/dantotsu/media/SearchAdapter.kt index 2bfec418..ecf3692c 100644 --- a/app/src/main/java/ani/dantotsu/media/SearchAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/SearchAdapter.kt @@ -13,9 +13,9 @@ import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager +import android.widget.PopupMenu import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources -import androidx.core.content.ContextCompat.startActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.HORIZONTAL @@ -28,7 +28,9 @@ import ani.dantotsu.openLinkInBrowser import ani.dantotsu.others.imagesearch.ImageSearchActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName -import com.google.android.material.checkbox.MaterialCheckBox.* +import com.google.android.material.checkbox.MaterialCheckBox.STATE_CHECKED +import com.google.android.material.checkbox.MaterialCheckBox.STATE_INDETERMINATE +import com.google.android.material.checkbox.MaterialCheckBox.STATE_UNCHECKED import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -44,6 +46,20 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri private lateinit var searchHistoryAdapter: SearchHistoryAdapter private lateinit var binding: ItemSearchHeaderBinding + private fun updateFilterTextViewDrawable() { + val filterDrawable = when (activity.result.sort) { + Anilist.sortBy[0] -> R.drawable.ic_round_area_chart_24 + Anilist.sortBy[1] -> R.drawable.ic_round_filter_peak_24 + Anilist.sortBy[2] -> R.drawable.ic_round_star_graph_24 + Anilist.sortBy[3] -> R.drawable.ic_round_new_releases_24 + Anilist.sortBy[4] -> R.drawable.ic_round_filter_list_24 + Anilist.sortBy[5] -> R.drawable.ic_round_filter_list_24_reverse + Anilist.sortBy[6] -> R.drawable.ic_round_assist_walker_24 + else -> R.drawable.ic_round_filter_alt_24 + } + binding.filterTextView.setCompoundDrawablesWithIntrinsicBounds(filterDrawable, 0, 0, 0) + } + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchHeaderViewHolder { val binding = ItemSearchHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false) @@ -92,7 +108,7 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri binding.searchAdultCheck.isChecked = adult binding.searchList.isChecked = listOnly == true - binding.searchChipRecycler.adapter = SearchChipAdapter(activity).also { + binding.searchChipRecycler.adapter = SearchChipAdapter(activity, this).also { activity.updateChips = { it.update() } } @@ -102,6 +118,68 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri binding.searchFilter.setOnClickListener { SearchFilterBottomDialog.newInstance().show(activity.supportFragmentManager, "dialog") } + binding.searchFilter.setOnLongClickListener { + val popupMenu = PopupMenu(activity, binding.searchFilter) + popupMenu.menuInflater.inflate(R.menu.sortby_filter_menu, popupMenu.menu) + popupMenu.setOnMenuItemClickListener { item -> + when (item.itemId) { + R.id.sort_by_score -> { + activity.result.sort = Anilist.sortBy[0] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_popular -> { + activity.result.sort = Anilist.sortBy[1] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_trending -> { + activity.result.sort = Anilist.sortBy[2] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_recent -> { + activity.result.sort = Anilist.sortBy[3] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_a_z -> { + activity.result.sort = Anilist.sortBy[4] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_z_a -> { + activity.result.sort = Anilist.sortBy[5] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + + R.id.sort_by_pure_pain -> { + activity.result.sort = Anilist.sortBy[6] + activity.updateChips.invoke() + activity.search() + updateFilterTextViewDrawable() + } + } + true + } + popupMenu.show() + true + } + if (activity.result.type != "ANIME") { + binding.searchByImage.visibility = View.GONE + } binding.searchByImage.setOnClickListener { activity.startActivity(Intent(activity, ImageSearchActivity::class.java)) } @@ -230,20 +308,21 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri private fun fadeInAnimation(): Animation { return AlphaAnimation(0f, 1f).apply { duration = 150 - fillAfter = true } } private fun fadeOutAnimation(): Animation { return AlphaAnimation(1f, 0f).apply { duration = 150 - fillAfter = true } } fun addHistory() { - searchHistoryAdapter.add(binding.searchBarText.text.toString()) + if (::searchHistoryAdapter.isInitialized && + binding.searchBarText.text.toString().isNotBlank() + ) + searchHistoryAdapter.add(binding.searchBarText.text.toString()) } override fun getItemCount(): Int = 1 @@ -256,7 +335,10 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri } - class SearchChipAdapter(val activity: SearchActivity) : + class SearchChipAdapter( + val activity: SearchActivity, + private val searchAdapter: SearchAdapter + ) : RecyclerView.Adapter() { private var chips = activity.result.toChipList() @@ -273,11 +355,12 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri override fun onBindViewHolder(holder: SearchChipViewHolder, position: Int) { val chip = chips[position] holder.binding.root.apply { - text = chip.text + text = chip.text.replace("_", " ") setOnClickListener { activity.result.removeChip(chip) update() activity.search() + searchAdapter.updateFilterTextViewDrawable() } } } @@ -286,6 +369,7 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri fun update() { chips = activity.result.toChipList() notifyDataSetChanged() + searchAdapter.updateFilterTextViewDrawable() } override fun getItemCount(): Int = chips.size diff --git a/app/src/main/java/ani/dantotsu/media/SearchFilterBottomDialog.kt b/app/src/main/java/ani/dantotsu/media/SearchFilterBottomDialog.kt index 297f8289..6658532c 100644 --- a/app/src/main/java/ani/dantotsu/media/SearchFilterBottomDialog.kt +++ b/app/src/main/java/ani/dantotsu/media/SearchFilterBottomDialog.kt @@ -1,11 +1,15 @@ package ani.dantotsu.media +import android.animation.ObjectAnimator import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.ViewGroup +import android.view.animation.AccelerateDecelerateInterpolator +import android.view.animation.AnimationUtils import android.widget.ArrayAdapter +import android.widget.PopupMenu import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView @@ -17,6 +21,9 @@ import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.databinding.BottomSheetSearchFilterBinding import ani.dantotsu.databinding.ItemChipBinding import com.google.android.material.chip.Chip +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import java.util.Calendar class SearchFilterBottomDialog : BottomSheetDialogFragment() { @@ -38,6 +45,54 @@ class SearchFilterBottomDialog : BottomSheetDialogFragment() { private var exGenres = mutableListOf() private var selectedTags = mutableListOf() private var exTags = mutableListOf() + private fun updateChips() { + binding.searchFilterGenres.adapter?.notifyDataSetChanged() + binding.searchFilterTags.adapter?.notifyDataSetChanged() + } + + private fun startBounceZoomAnimation(view: View? = null) { + val targetView = view ?: binding.sortByFilter + val bounceZoomAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.bounce_zoom) + targetView.startAnimation(bounceZoomAnimation) + } + + private fun setSortByFilterImage() { + val filterDrawable = when (activity.result.sort) { + Anilist.sortBy[0] -> R.drawable.ic_round_area_chart_24 + Anilist.sortBy[1] -> R.drawable.ic_round_filter_peak_24 + Anilist.sortBy[2] -> R.drawable.ic_round_star_graph_24 + Anilist.sortBy[3] -> R.drawable.ic_round_new_releases_24 + Anilist.sortBy[4] -> R.drawable.ic_round_filter_list_24 + Anilist.sortBy[5] -> R.drawable.ic_round_filter_list_24_reverse + Anilist.sortBy[6] -> R.drawable.ic_round_assist_walker_24 + else -> R.drawable.ic_round_filter_alt_24 + } + binding.sortByFilter.setImageResource(filterDrawable) + } + + private fun resetSearchFilter() { + activity.result.sort = null + binding.sortByFilter.setImageResource(R.drawable.ic_round_filter_alt_24) + startBounceZoomAnimation(binding.sortByFilter) + activity.result.countryOfOrigin = null + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_search_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + + selectedGenres.clear() + exGenres.clear() + selectedTags.clear() + exTags.clear() + binding.searchStatus.setText("") + binding.searchSource.setText("") + binding.searchFormat.setText("") + binding.searchSeason.setText("") + binding.searchYear.setText("") + binding.searchStatus.clearFocus() + binding.searchFormat.clearFocus() + binding.searchSeason.clearFocus() + binding.searchYear.clearFocus() + updateChips() + } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { @@ -47,14 +102,157 @@ class SearchFilterBottomDialog : BottomSheetDialogFragment() { exGenres = activity.result.excludedGenres ?: mutableListOf() selectedTags = activity.result.tags ?: mutableListOf() exTags = activity.result.excludedTags ?: mutableListOf() + setSortByFilterImage() + + binding.resetSearchFilter.setOnClickListener { + val rotateAnimation = + ObjectAnimator.ofFloat(binding.resetSearchFilter, "rotation", 180f, 540f) + rotateAnimation.duration = 500 + rotateAnimation.interpolator = AccelerateDecelerateInterpolator() + rotateAnimation.start() + resetSearchFilter() + } + + binding.resetSearchFilter.setOnLongClickListener { + val rotateAnimation = + ObjectAnimator.ofFloat(binding.resetSearchFilter, "rotation", 180f, 540f) + rotateAnimation.duration = 500 + rotateAnimation.interpolator = AccelerateDecelerateInterpolator() + rotateAnimation.start() + val bounceAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.bounce_zoom) + + binding.resetSearchFilter.startAnimation(bounceAnimation) + binding.resetSearchFilter.postDelayed({ + resetSearchFilter() + + CoroutineScope(Dispatchers.Main).launch { + activity.result.apply { + status = + binding.searchStatus.text.toString().replace(" ", "_").ifBlank { null } + source = + binding.searchSource.text.toString().replace(" ", "_").ifBlank { null } + format = binding.searchFormat.text.toString().ifBlank { null } + season = binding.searchSeason.text.toString().ifBlank { null } + startYear = binding.searchYear.text.toString().toIntOrNull() + seasonYear = binding.searchYear.text.toString().toIntOrNull() + sort = activity.result.sort + genres = selectedGenres + tags = selectedTags + excludedGenres = exGenres + excludedTags = exTags + } + activity.updateChips.invoke() + activity.search() + dismiss() + } + }, 500) + true + } + + binding.sortByFilter.setOnClickListener { + val popupMenu = PopupMenu(requireContext(), it) + popupMenu.menuInflater.inflate(R.menu.sortby_filter_menu, popupMenu.menu) + popupMenu.setOnMenuItemClickListener { menuItem -> + when (menuItem.itemId) { + R.id.sort_by_score -> { + activity.result.sort = Anilist.sortBy[0] + binding.sortByFilter.setImageResource(R.drawable.ic_round_area_chart_24) + startBounceZoomAnimation() + } + + R.id.sort_by_popular -> { + activity.result.sort = Anilist.sortBy[1] + binding.sortByFilter.setImageResource(R.drawable.ic_round_filter_peak_24) + startBounceZoomAnimation() + } + + R.id.sort_by_trending -> { + activity.result.sort = Anilist.sortBy[2] + binding.sortByFilter.setImageResource(R.drawable.ic_round_star_graph_24) + startBounceZoomAnimation() + } + + R.id.sort_by_recent -> { + activity.result.sort = Anilist.sortBy[3] + binding.sortByFilter.setImageResource(R.drawable.ic_round_new_releases_24) + startBounceZoomAnimation() + } + + R.id.sort_by_a_z -> { + activity.result.sort = Anilist.sortBy[4] + binding.sortByFilter.setImageResource(R.drawable.ic_round_filter_list_24) + startBounceZoomAnimation() + } + + R.id.sort_by_z_a -> { + activity.result.sort = Anilist.sortBy[5] + binding.sortByFilter.setImageResource(R.drawable.ic_round_filter_list_24_reverse) + startBounceZoomAnimation() + } + + R.id.sort_by_pure_pain -> { + activity.result.sort = Anilist.sortBy[6] + binding.sortByFilter.setImageResource(R.drawable.ic_round_assist_walker_24) + startBounceZoomAnimation() + } + } + true + } + popupMenu.show() + } + + binding.countryFilter.setOnClickListener { + val popupMenu = PopupMenu(requireContext(), it) + popupMenu.menuInflater.inflate(R.menu.country_filter_menu, popupMenu.menu) + popupMenu.setOnMenuItemClickListener { menuItem -> + when (menuItem.itemId) { + R.id.country_global -> { + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_search_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + } + + R.id.country_china -> { + activity.result.countryOfOrigin = "CN" + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_china_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + } + + R.id.country_south_korea -> { + activity.result.countryOfOrigin = "KR" + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_south_korea_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + } + + R.id.country_japan -> { + activity.result.countryOfOrigin = "JP" + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_japan_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + } + + R.id.country_taiwan -> { + activity.result.countryOfOrigin = "TW" + binding.countryFilter.setImageResource(R.drawable.ic_round_globe_taiwan_googlefonts) + startBounceZoomAnimation(binding.countryFilter) + } + } + true + } + popupMenu.show() + } binding.searchFilterApply.setOnClickListener { activity.result.apply { + status = binding.searchStatus.text.toString().replace(" ", "_").ifBlank { null } + source = binding.searchSource.text.toString().replace(" ", "_").ifBlank { null } format = binding.searchFormat.text.toString().ifBlank { null } - sort = binding.searchSortBy.text.toString().ifBlank { null } - ?.let { Anilist.sortBy[resources.getStringArray(R.array.sort_by).indexOf(it)] } season = binding.searchSeason.text.toString().ifBlank { null } - seasonYear = binding.searchYear.text.toString().toIntOrNull() + if (activity.result.type == "ANIME") { + seasonYear = binding.searchYear.text.toString().toIntOrNull() + } else { + startYear = binding.searchYear.text.toString().toIntOrNull() + } + sort = activity.result.sort + countryOfOrigin = activity.result.countryOfOrigin genres = selectedGenres tags = selectedTags excludedGenres = exGenres @@ -67,15 +265,23 @@ class SearchFilterBottomDialog : BottomSheetDialogFragment() { binding.searchFilterCancel.setOnClickListener { dismiss() } - - binding.searchSortBy.setText(activity.result.sort?.let { - resources.getStringArray(R.array.sort_by)[Anilist.sortBy.indexOf(it)] - }) - binding.searchSortBy.setAdapter( + val format = + if (activity.result.type == "ANIME") Anilist.animeStatus else Anilist.mangaStatus + binding.searchStatus.setText(activity.result.status?.replace("_", " ")) + binding.searchStatus.setAdapter( ArrayAdapter( binding.root.context, R.layout.item_dropdown, - resources.getStringArray(R.array.sort_by) + format + ) + ) + + binding.searchSource.setText(activity.result.source?.replace("_", " ")) + binding.searchSource.setAdapter( + ArrayAdapter( + binding.root.context, + R.layout.item_dropdown, + Anilist.source.toTypedArray() ) ) @@ -84,11 +290,25 @@ class SearchFilterBottomDialog : BottomSheetDialogFragment() { ArrayAdapter( binding.root.context, R.layout.item_dropdown, - (if (activity.result.type == "ANIME") Anilist.anime_formats else Anilist.manga_formats).toTypedArray() + (if (activity.result.type == "ANIME") Anilist.animeFormats else Anilist.mangaFormats).toTypedArray() ) ) - if (activity.result.type == "MANGA") binding.searchSeasonYearCont.visibility = GONE + if (activity.result.type == "ANIME") { + binding.searchYear.setText(activity.result.seasonYear?.toString()) + } else { + binding.searchYear.setText(activity.result.startYear?.toString()) + } + binding.searchYear.setAdapter( + ArrayAdapter( + binding.root.context, + R.layout.item_dropdown, + (1970 until Calendar.getInstance().get(Calendar.YEAR) + 2).map { it.toString() } + .reversed().toTypedArray() + ) + ) + + if (activity.result.type == "MANGA") binding.searchSeasonCont.visibility = GONE else { binding.searchSeason.setText(activity.result.season) binding.searchSeason.setAdapter( @@ -98,16 +318,6 @@ class SearchFilterBottomDialog : BottomSheetDialogFragment() { Anilist.seasons.toTypedArray() ) ) - - binding.searchYear.setText(activity.result.seasonYear?.toString()) - binding.searchYear.setAdapter( - ArrayAdapter( - binding.root.context, - R.layout.item_dropdown, - (1970 until Calendar.getInstance().get(Calendar.YEAR) + 2).map { it.toString() } - .reversed().toTypedArray() - ) - ) } binding.searchFilterGenres.adapter = FilterChipAdapter(Anilist.genres ?: listOf()) { chip -> diff --git a/app/src/main/java/ani/dantotsu/media/SourceAdapter.kt b/app/src/main/java/ani/dantotsu/media/SourceAdapter.kt index c1dd18b2..e56adde6 100644 --- a/app/src/main/java/ani/dantotsu/media/SourceAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/SourceAdapter.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media -import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView @@ -22,7 +21,6 @@ abstract class SourceAdapter( return SourceViewHolder(binding) } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: SourceViewHolder, position: Int) { val binding = holder.binding val character = sources[position] diff --git a/app/src/main/java/ani/dantotsu/media/SourceSearchDialogFragment.kt b/app/src/main/java/ani/dantotsu/media/SourceSearchDialogFragment.kt index 3925bcce..06b784e8 100644 --- a/app/src/main/java/ani/dantotsu/media/SourceSearchDialogFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/SourceSearchDialogFragment.kt @@ -65,7 +65,7 @@ class SourceSearchDialogFragment : BottomSheetDialogFragment() { i = media!!.selected!!.sourceIndex val source = if (media!!.anime != null) { - (if (!media!!.isAdult) AnimeSources else HAnimeSources)[i!!] + (if (media!!.isAdult) HAnimeSources else AnimeSources)[i!!] } else { anime = false (if (media!!.isAdult) HMangaSources else MangaSources)[i!!] diff --git a/app/src/main/java/ani/dantotsu/media/StudioActivity.kt b/app/src/main/java/ani/dantotsu/media/StudioActivity.kt index ac28cd5f..a90caeb4 100644 --- a/app/src/main/java/ani/dantotsu/media/StudioActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/StudioActivity.kt @@ -6,6 +6,7 @@ import android.view.ViewGroup import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat +import androidx.core.view.isGone import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.lifecycle.MutableLiveData @@ -114,7 +115,7 @@ class StudioActivity : AppCompatActivity() { } override fun onResume() { - binding.studioProgressBar.visibility = if (!loaded) View.VISIBLE else View.GONE + binding.studioProgressBar.isGone = loaded super.onResume() } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/SubtitleDownloader.kt b/app/src/main/java/ani/dantotsu/media/SubtitleDownloader.kt index e5ebd81b..9d834a0c 100644 --- a/app/src/main/java/ani/dantotsu/media/SubtitleDownloader.kt +++ b/app/src/main/java/ani/dantotsu/media/SubtitleDownloader.kt @@ -5,67 +5,70 @@ import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager import ani.dantotsu.parsers.SubtitleType import ani.dantotsu.snackString +import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.openOutputStream import eu.kanade.tachiyomi.network.NetworkHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.Request import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class SubtitleDownloader { companion object { //doesn't really download the subtitles -\_(o_o)_/- - suspend fun loadSubtitleType(context: Context, url: String): SubtitleType = + suspend fun loadSubtitleType(url: String): SubtitleType = withContext(Dispatchers.IO) { - // Initialize the NetworkHelper instance. Replace this line based on how you usually initialize it - val networkHelper = Injekt.get() - val request = Request.Builder() - .url(url) - .build() + return@withContext try { + // Initialize the NetworkHelper instance. Replace this line based on how you usually initialize it + val networkHelper = Injekt.get() + val request = Request.Builder() + .url(url) + .build() - val response = networkHelper.client.newCall(request).execute() + val response = networkHelper.client.newCall(request).execute() - // Check if response is successful - if (response.isSuccessful) { - val responseBody = response.body.string() + // Check if response is successful + if (response.isSuccessful) { + val responseBody = response.body.string() - val subtitleType = when { - responseBody.contains("[Script Info]") -> SubtitleType.ASS - responseBody.contains("WEBVTT") -> SubtitleType.VTT - else -> SubtitleType.SRT + val subtitleType = when { + responseBody.contains("[Script Info]") -> SubtitleType.ASS + responseBody.contains("WEBVTT") -> SubtitleType.VTT + else -> SubtitleType.SRT + } + + subtitleType + } else { + SubtitleType.UNKNOWN } - - return@withContext subtitleType - } else { - return@withContext SubtitleType.UNKNOWN + } catch (e: Exception) { + Logger.log(e) + SubtitleType.UNKNOWN } } //actually downloads lol + @Deprecated("handled externally") suspend fun downloadSubtitle( context: Context, url: String, downloadedType: DownloadedType ) { try { - val directory = DownloadsManager.getDirectory( + val directory = DownloadsManager.getSubDirectory( context, downloadedType.type, - downloadedType.title, - downloadedType.chapter - ) - if (!directory.exists()) { //just in case - directory.mkdirs() - } - val type = loadSubtitleType(context, url) - val subtiteFile = File(directory, "subtitle.${type}") - if (subtiteFile.exists()) { - subtiteFile.delete() - } - subtiteFile.createNewFile() + false, + downloadedType.titleName, + downloadedType.chapterName + ) ?: throw Exception("Could not create directory") + val type = loadSubtitleType(url) + directory.findFile("subtitle.${type}")?.delete() + val subtitleFile = directory.createFile("*/*", "subtitle.${type}") + ?: throw Exception("Could not create subtitle file") val client = Injekt.get().client val request = Request.Builder().url(url).build() @@ -77,7 +80,8 @@ class SubtitleDownloader { } reponse.body.byteStream().use { input -> - subtiteFile.outputStream().use { output -> + subtitleFile.openOutputStream(context, false).use { output -> + if (output == null) throw Exception("Could not open output stream") input.copyTo(output) } } diff --git a/app/src/main/java/ani/dantotsu/media/TripleNavAdapter.kt b/app/src/main/java/ani/dantotsu/media/TripleNavAdapter.kt deleted file mode 100644 index b76a0dff..00000000 --- a/app/src/main/java/ani/dantotsu/media/TripleNavAdapter.kt +++ /dev/null @@ -1,136 +0,0 @@ -package ani.dantotsu.media - -import android.graphics.Color -import android.view.ViewGroup -import androidx.core.view.updateLayoutParams -import ani.dantotsu.R -import ani.dantotsu.navBarHeight -import nl.joery.animatedbottombar.AnimatedBottomBar - -class TripleNavAdapter( - private val nav1: AnimatedBottomBar, - private val nav2: AnimatedBottomBar, - private val nav3: AnimatedBottomBar, - anime: Boolean, - format: String, - private val isScreenVertical: Boolean = false -) { - var selected: Int = 0 - var selectionListener: ((Int, Int) -> Unit)? = null - init { - nav1.tabs.clear() - nav2.tabs.clear() - nav3.tabs.clear() - val infoTab = nav1.createTab(R.drawable.ic_round_info_24, R.string.info, R.id.info) - val watchTab = if (anime) { - nav2.createTab(R.drawable.ic_round_movie_filter_24, R.string.watch, R.id.watch) - } else if (format == "NOVEL") { - nav2.createTab(R.drawable.ic_round_book_24, R.string.read, R.id.read) - } else { - nav2.createTab(R.drawable.ic_round_import_contacts_24, R.string.read, R.id.read) - } - val commentTab = nav3.createTab(R.drawable.ic_round_comment_24, R.string.comments, R.id.comment) - nav1.addTab(infoTab) - nav1.visibility = ViewGroup.VISIBLE - if (isScreenVertical) { - nav2.visibility = ViewGroup.GONE - nav3.visibility = ViewGroup.GONE - nav1.addTab(watchTab) - nav1.addTab(commentTab) - nav1.updateLayoutParams { - bottomMargin = navBarHeight - } - nav2.updateLayoutParams { - bottomMargin = navBarHeight - } - nav3.updateLayoutParams { - bottomMargin = navBarHeight - } - } else { - nav1.indicatorColor = Color.TRANSPARENT - nav2.indicatorColor = Color.TRANSPARENT - nav3.indicatorColor = Color.TRANSPARENT - nav2.visibility = ViewGroup.VISIBLE - nav3.visibility = ViewGroup.VISIBLE - nav2.addTab(watchTab) - nav3.addTab(commentTab) - nav2.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener { - override fun onTabSelected( - lastIndex: Int, - lastTab: AnimatedBottomBar.Tab?, - newIndex: Int, - newTab: AnimatedBottomBar.Tab - ) { - selected = 1 - deselectOthers(selected) - selectionListener?.invoke(selected, newTab.id) - } - }) - nav3.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener { - override fun onTabSelected( - lastIndex: Int, - lastTab: AnimatedBottomBar.Tab?, - newIndex: Int, - newTab: AnimatedBottomBar.Tab - ) { - selected = 2 - deselectOthers(selected) - selectionListener?.invoke(selected, newTab.id) - } - }) - } - nav1.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener { - override fun onTabSelected( - lastIndex: Int, - lastTab: AnimatedBottomBar.Tab?, - newIndex: Int, - newTab: AnimatedBottomBar.Tab - ) { - if (!isScreenVertical) { - selected = 0 - deselectOthers(selected) - } else selected = newIndex - selectionListener?.invoke(selected, newTab.id) - } - }) - } - - private fun deselectOthers(selected: Int) { - if (selected == 0) { - nav2.clearSelection() - nav3.clearSelection() - } - if (selected == 1) { - nav1.clearSelection() - nav3.clearSelection() - } - if (selected == 2) { - nav1.clearSelection() - nav2.clearSelection() - } - } - - fun selectTab(tab: Int) { - selected = tab - if (!isScreenVertical) { - when (tab) { - 0 -> nav1.selectTabAt(0) - 1 -> nav2.selectTabAt(0) - 2 -> nav3.selectTabAt(0) - } - deselectOthers(selected) - } else { - nav1.selectTabAt(selected) - } - } - - fun setVisibility(visibility: Int) { - if (isScreenVertical) { - nav1.visibility = visibility - return - } - nav1.visibility = visibility - nav2.visibility = visibility - nav3.visibility = visibility - } -} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/anime/AnimeNameAdapter.kt b/app/src/main/java/ani/dantotsu/media/anime/AnimeNameAdapter.kt deleted file mode 100644 index ad8c378e..00000000 --- a/app/src/main/java/ani/dantotsu/media/anime/AnimeNameAdapter.kt +++ /dev/null @@ -1,127 +0,0 @@ -package ani.dantotsu.media.anime - -import java.util.Locale -import java.util.regex.Matcher -import java.util.regex.Pattern - -class AnimeNameAdapter { - companion object { - const val episodeRegex = - "(episode|episodio|ep|e)[\\s:.\\-]*([\\d]+\\.?[\\d]*)[\\s:.\\-]*\\(?\\s*(sub|subbed|dub|dubbed)*\\s*\\)?\\s*" - const val failedEpisodeNumberRegex = - "(? "sub" - SubDubType.DUB -> "dub" - SubDubType.NULL -> "" - } - val toggledCasePreserved = - if (subdub?.get(0)?.isUpperCase() == true || soft?.get(0) - ?.isUpperCase() == true - ) toggled.replaceFirstChar { - if (it.isLowerCase()) it.titlecase( - Locale.ROOT - ) else it.toString() - } else toggled - - subdubMatcher.replaceFirst(toggledCasePreserved + bed) - } else { - null - } - } - - fun getSubDub(text: String): SubDubType { - val subdubPattern: Pattern = Pattern.compile(subdubRegex, Pattern.CASE_INSENSITIVE) - val subdubMatcher: Matcher = subdubPattern.matcher(text) - - return if (subdubMatcher.find()) { - val subdub = subdubMatcher.group(2)?.lowercase(Locale.ROOT) - when (subdub) { - "sub" -> SubDubType.SUB - "dub" -> SubDubType.DUB - else -> SubDubType.NULL - } - } else { - SubDubType.NULL - } - } - - enum class SubDubType { - SUB, DUB, NULL - } - - fun findSeasonNumber(text: String): Int? { - val seasonPattern: Pattern = Pattern.compile(seasonRegex, Pattern.CASE_INSENSITIVE) - val seasonMatcher: Matcher = seasonPattern.matcher(text) - - return if (seasonMatcher.find()) { - seasonMatcher.group(2)?.toInt() - } else { - null - } - } - - fun findEpisodeNumber(text: String): Float? { - val episodePattern: Pattern = Pattern.compile(episodeRegex, Pattern.CASE_INSENSITIVE) - val episodeMatcher: Matcher = episodePattern.matcher(text) - - return if (episodeMatcher.find()) { - if (episodeMatcher.group(2) != null) { - episodeMatcher.group(2)?.toFloat() - } else { - val failedEpisodeNumberPattern: Pattern = - Pattern.compile(failedEpisodeNumberRegex, Pattern.CASE_INSENSITIVE) - val failedEpisodeNumberMatcher: Matcher = - failedEpisodeNumberPattern.matcher(text) - if (failedEpisodeNumberMatcher.find()) { - failedEpisodeNumberMatcher.group(1)?.toFloat() - } else { - null - } - } - } else { - null - } - } - - fun removeEpisodeNumber(text: String): String { - val regexPattern = Regex(episodeRegex, RegexOption.IGNORE_CASE) - val removedNumber = text.replace(regexPattern, "").ifEmpty { - text - } - val letterPattern = Regex("[a-zA-Z]") - return if (letterPattern.containsMatchIn(removedNumber)) { - removedNumber - } else { - text - } - } - - - fun removeEpisodeNumberCompletely(text: String): String { - val regexPattern = Regex(episodeRegex, RegexOption.IGNORE_CASE) - val removedNumber = text.replace(regexPattern, "") - return if (removedNumber.equals(text, true)) { // if nothing was removed - val failedEpisodeNumberPattern: Regex = - Regex(failedEpisodeNumberRegex, RegexOption.IGNORE_CASE) - failedEpisodeNumberPattern.replace(removedNumber) { mr -> - mr.value.replaceFirst(mr.groupValues[1], "") - } - } else { - removedNumber - } - } - } -} diff --git a/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchAdapter.kt b/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchAdapter.kt index 4b53fe42..a2406a21 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchAdapter.kt @@ -1,11 +1,9 @@ package ani.dantotsu.media.anime -import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.view.LayoutInflater import android.view.View -import ani.dantotsu.settings.FAQActivity import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageButton @@ -13,22 +11,34 @@ import android.widget.LinearLayout import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.startActivity +import androidx.core.view.isGone +import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.RecyclerView -import ani.dantotsu.* +import ani.dantotsu.FileUrl +import ani.dantotsu.R +import ani.dantotsu.currActivity import ani.dantotsu.databinding.DialogLayoutBinding import ani.dantotsu.databinding.ItemAnimeWatchBinding import ani.dantotsu.databinding.ItemChipBinding +import ani.dantotsu.displayTimer +import ani.dantotsu.isOnline +import ani.dantotsu.loadImage import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.media.MediaNameAdapter import ani.dantotsu.media.SourceSearchDialogFragment +import ani.dantotsu.openSettings import ani.dantotsu.others.LanguageMapper import ani.dantotsu.others.webview.CookieCatcher import ani.dantotsu.parsers.AnimeSources import ani.dantotsu.parsers.DynamicAnimeParser import ani.dantotsu.parsers.WatchSources +import ani.dantotsu.px +import ani.dantotsu.settings.FAQActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.toast import com.google.android.material.chip.Chip import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource import eu.kanade.tachiyomi.data.notification.Notifications.CHANNEL_SUBSCRIPTION_CHECK @@ -42,7 +52,7 @@ class AnimeWatchAdapter( private val fragment: AnimeWatchFragment, private val watchSources: WatchSources ) : RecyclerView.Adapter() { - + private var autoSelect = true var subscribe: MediaDetailsActivity.PopImageButton? = null private var _binding: ItemAnimeWatchBinding? = null @@ -54,7 +64,6 @@ class AnimeWatchAdapter( private var nestedDialog: AlertDialog? = null - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val binding = holder.binding _binding = binding @@ -97,15 +106,12 @@ class AnimeWatchAdapter( null ) } - val offline = if (!isOnline(binding.root.context) || PrefManager.getVal( - PrefName.OfflineMode - ) - ) View.GONE else View.VISIBLE + val offline = !isOnline(binding.root.context) || PrefManager.getVal(PrefName.OfflineMode) - binding.animeSourceNameContainer.visibility = offline - binding.animeSourceSettings.visibility = offline - binding.animeSourceSearch.visibility = offline - binding.animeSourceTitle.visibility = offline + binding.animeSourceNameContainer.isGone = offline + binding.animeSourceSettings.isGone = offline + binding.animeSourceSearch.isGone = offline + binding.animeSourceTitle.isGone = offline //Source Selection var source = @@ -117,8 +123,7 @@ class AnimeWatchAdapter( this.selectDub = media.selected!!.preferDub binding.animeSourceTitle.text = showUserText showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } } - binding.animeSourceDubbedCont.visibility = - if (isDubAvailableSeparately()) View.VISIBLE else View.GONE + binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately() } } @@ -137,8 +142,7 @@ class AnimeWatchAdapter( changing = true binding.animeSourceDubbed.isChecked = selectDub changing = false - binding.animeSourceDubbedCont.visibility = - if (isDubAvailableSeparately()) View.VISIBLE else View.GONE + binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately() source = i setLanguageList(0, i) } @@ -158,14 +162,12 @@ class AnimeWatchAdapter( changing = true binding.animeSourceDubbed.isChecked = selectDub changing = false - binding.animeSourceDubbedCont.visibility = - if (isDubAvailableSeparately()) View.VISIBLE else View.GONE + binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately() setLanguageList(i, source) } subscribeButton(false) fragment.loadEpisodes(media.selected!!.sourceIndex, true) - } ?: run { - } + } ?: run { } } //settings @@ -223,9 +225,9 @@ class AnimeWatchAdapter( else -> dialogBinding.animeSourceList } when (style) { - 0 -> dialogBinding.layoutText.text = "List" - 1 -> dialogBinding.layoutText.text = "Grid" - 2 -> dialogBinding.layoutText.text = "Compact" + 0 -> dialogBinding.layoutText.setText(R.string.list) + 1 -> dialogBinding.layoutText.setText(R.string.grid) + 2 -> dialogBinding.layoutText.setText(R.string.compact) else -> dialogBinding.animeSourceList } selected.alpha = 1f @@ -237,24 +239,24 @@ class AnimeWatchAdapter( dialogBinding.animeSourceList.setOnClickListener { selected(it as ImageButton) style = 0 - dialogBinding.layoutText.text = "List" + dialogBinding.layoutText.setText(R.string.list) run = true } dialogBinding.animeSourceGrid.setOnClickListener { selected(it as ImageButton) style = 1 - dialogBinding.layoutText.text = "Grid" + dialogBinding.layoutText.setText(R.string.grid) run = true } dialogBinding.animeSourceCompact.setOnClickListener { selected(it as ImageButton) style = 2 - dialogBinding.layoutText.text = "Compact" + dialogBinding.layoutText.setText(R.string.compact) run = true } dialogBinding.animeWebviewContainer.setOnClickListener { if (!WebViewUtil.supportsWebView(fragment.requireContext())) { - toast("WebView not installed") + toast(R.string.webview_not_installed) } //start CookieCatcher activity if (watchSources.names.isNotEmpty() && source in 0 until watchSources.names.size) { @@ -307,7 +309,6 @@ class AnimeWatchAdapter( } //Chips - @SuppressLint("SetTextI18n") fun updateChips(limit: Int, names: Array, arr: Array, selected: Int = 0) { val binding = _binding if (binding != null) { @@ -329,7 +330,9 @@ class AnimeWatchAdapter( 0 ) } - chip.text = "${names[limit * (position)]} - ${names[last - 1]}" + + val chipText = "${names[limit * (position)]} - ${names[last - 1]}" + chip.text = chipText chip.setTextColor( ContextCompat.getColorStateList( fragment.requireContext(), @@ -363,7 +366,6 @@ class AnimeWatchAdapter( _binding?.animeSourceChipGroup?.removeAllViews() } - @SuppressLint("SetTextI18n") fun handleEpisodes() { val binding = _binding if (binding != null) { @@ -371,9 +373,9 @@ class AnimeWatchAdapter( val episodes = media.anime.episodes!!.keys.toTypedArray() val anilistEp = (media.userProgress ?: 0).plus(1) - val appEp = - PrefManager.getCustomVal("${media.id}_current_ep", "")?.toIntOrNull() - ?: 1 + val appEp = PrefManager.getCustomVal( + "${media.id}_current_ep", "" + )?.toIntOrNull() ?: 1 var continueEp = (if (anilistEp > appEp) anilistEp else appEp).toString() if (episodes.contains(continueEp)) { @@ -403,21 +405,27 @@ class AnimeWatchAdapter( } val ep = media.anime.episodes!![continueEp]!! - val cleanedTitle = ep.title?.let { AnimeNameAdapter.removeEpisodeNumber(it) } + val cleanedTitle = ep.title?.let { MediaNameAdapter.removeEpisodeNumber(it) } binding.itemEpisodeImage.loadImage( ep.thumb ?: FileUrl[media.banner ?: media.cover], 0 ) if (ep.filler) binding.itemEpisodeFillerView.visibility = View.VISIBLE + binding.animeSourceContinueText.text = - currActivity()!!.getString(R.string.continue_episode) + "${ep.number}${if (ep.filler) " - Filler" else ""}${"\n$cleanedTitle"}" + currActivity()!!.getString( + R.string.continue_episode, ep.number, if (ep.filler) + currActivity()!!.getString(R.string.filler_tag) + else + "", cleanedTitle + ) binding.animeSourceContinue.setOnClickListener { fragment.onEpisodeClick(continueEp) } if (fragment.continueEp) { - if ((binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams).weight < PrefManager.getVal( - PrefName.WatchPercentage - ) + if ( + (binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams) + .weight < PrefManager.getVal(PrefName.WatchPercentage) ) { binding.animeSourceContinue.performClick() fragment.continueEp = false @@ -428,13 +436,31 @@ class AnimeWatchAdapter( } binding.animeSourceProgressBar.visibility = View.GONE - if (media.anime.episodes!!.isNotEmpty()) { - binding.animeSourceNotFound.visibility = View.GONE - binding.faqbutton.visibility = View.GONE} - else { - binding.animeSourceNotFound.visibility = View.VISIBLE - binding.faqbutton.visibility = View.VISIBLE + + val sourceFound = media.anime.episodes!!.isNotEmpty() + binding.animeSourceNotFound.isGone = sourceFound + binding.faqbutton.isGone = sourceFound + + if (!sourceFound && PrefManager.getVal(PrefName.SearchSources) && autoSelect) { + if (binding.animeSource.adapter.count > media.selected!!.sourceIndex + 1) { + val nextIndex = media.selected!!.sourceIndex + 1 + binding.animeSource.setText( + binding.animeSource.adapter + .getItem(nextIndex).toString(), false + ) + fragment.onSourceChange(nextIndex).apply { + binding.animeSourceTitle.text = showUserText + showUserTextListener = + { MainScope().launch { binding.animeSourceTitle.text = it } } + binding.animeSourceDubbed.isChecked = selectDub + binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately() + setLanguageList(0, nextIndex) + } + subscribeButton(false) + fragment.loadEpisodes(nextIndex, false) } + } + binding.animeSource.setOnClickListener { autoSelect = false } } else { binding.animeSourceContinue.visibility = View.GONE binding.animeSourceNotFound.visibility = View.GONE @@ -463,7 +489,7 @@ class AnimeWatchAdapter( val adapter = ArrayAdapter( fragment.requireContext(), R.layout.item_dropdown, - parser.extension.sources.map { LanguageMapper.mapLanguageCodeToName(it.lang) } + parser.extension.sources.map { LanguageMapper.getLanguageName(it.lang) } ) val items = adapter.count @@ -480,8 +506,7 @@ class AnimeWatchAdapter( inner class ViewHolder(val binding: ItemAnimeWatchBinding) : RecyclerView.ViewHolder(binding.root) { init { - //Timer - countDown(media, binding.animeSourceContainer) + displayTimer(media, binding.animeSourceContainer) } } } diff --git a/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchFragment.kt b/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchFragment.kt index 50eef688..32b90910 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/AnimeWatchFragment.kt @@ -17,41 +17,60 @@ import androidx.annotation.OptIn import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.core.math.MathUtils +import androidx.core.view.isGone +import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.media3.common.util.UnstableApi -import androidx.media3.exoplayer.offline.DownloadService import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 -import ani.dantotsu.* +import ani.dantotsu.FileUrl +import ani.dantotsu.R +import ani.dantotsu.addons.download.DownloadAddonManager import ani.dantotsu.databinding.FragmentAnimeWatchBinding import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager +import ani.dantotsu.download.DownloadsManager.Companion.compareName +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory import ani.dantotsu.download.anime.AnimeDownloaderService -import ani.dantotsu.download.video.ExoplayerDownloadService +import ani.dantotsu.download.findValidName +import ani.dantotsu.dp +import ani.dantotsu.isOnline import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsActivity import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType +import ani.dantotsu.navBarHeight +import ani.dantotsu.notifications.subscription.SubscriptionHelper +import ani.dantotsu.notifications.subscription.SubscriptionHelper.Companion.saveSubscription import ani.dantotsu.others.LanguageMapper import ani.dantotsu.parsers.AnimeParser import ani.dantotsu.parsers.AnimeSources import ani.dantotsu.parsers.HAnimeSources +import ani.dantotsu.setNavigationTheme import ani.dantotsu.settings.extensionprefs.AnimeSourcePreferencesFragment import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName -import ani.dantotsu.notifications.subscription.SubscriptionHelper -import ani.dantotsu.notifications.subscription.SubscriptionHelper.Companion.saveSubscription +import ani.dantotsu.snackString +import ani.dantotsu.toast +import ani.dantotsu.util.Logger +import ani.dantotsu.util.StoragePermissions.Companion.accessAlertDialog +import ani.dantotsu.util.StoragePermissions.Companion.hasDirAccess +import com.anggrayudi.storage.file.extension import com.google.android.material.appbar.AppBarLayout import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.extension.anime.model.AnimeExtension +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch +import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import kotlin.math.ceil @@ -188,10 +207,16 @@ class AnimeWatchFragment : Fragment() { ConcatAdapter(headerAdapter, episodeAdapter) lifecycleScope.launch(Dispatchers.IO) { - awaitAll( - async { model.loadKitsuEpisodes(media) }, - async { model.loadFillerEpisodes(media) } - ) + val offline = + !isOnline(binding.root.context) || PrefManager.getVal(PrefName.OfflineMode) + if (offline) { + media.selected!!.sourceIndex = model.watchSources!!.list.lastIndex + } else { + awaitAll( + async { model.loadKitsuEpisodes(media) }, + async { model.loadFillerEpisodes(media) } + ) + } model.loadEpisodes(media, media.selected!!.sourceIndex) } loaded = true @@ -216,7 +241,7 @@ class AnimeWatchFragment : Fragment() { if (media.anime!!.kitsuEpisodes!!.containsKey(i)) { episode.desc = media.anime!!.kitsuEpisodes!![i]?.desc ?: episode.desc - episode.title = if (AnimeNameAdapter.removeEpisodeNumberCompletely( + episode.title = if (MediaNameAdapter.removeEpisodeNumberCompletely( episode.title ?: "" ).isBlank() ) media.anime!!.kitsuEpisodes!![i]?.title @@ -340,16 +365,12 @@ class AnimeWatchFragment : Fragment() { val changeUIVisibility: (Boolean) -> Unit = { show -> val activity = activity if (activity is MediaDetailsActivity && isAdded) { - val visibility = if (show) View.VISIBLE else View.GONE - activity.findViewById(R.id.mediaAppBar).visibility = visibility - activity.findViewById(R.id.mediaViewPager).visibility = visibility - activity.findViewById(R.id.mediaCover).visibility = visibility - activity.findViewById(R.id.mediaClose).visibility = visibility - - activity.tabLayout.setVisibility(visibility) - - activity.findViewById(R.id.fragmentExtensionsContainer).visibility = - if (show) View.GONE else View.VISIBLE + activity.findViewById(R.id.mediaAppBar).isVisible = show + activity.findViewById(R.id.mediaViewPager).isVisible = show + activity.findViewById(R.id.mediaCover).isVisible = show + activity.findViewById(R.id.mediaClose).isVisible = show + activity.navBar.isVisible = show + activity.findViewById(R.id.fragmentExtensionsContainer).isGone = show } } var itemSelected = false @@ -358,7 +379,7 @@ class AnimeWatchFragment : Fragment() { var selectedSetting = allSettings[0] if (allSettings.size > 1) { val names = - allSettings.map { LanguageMapper.mapLanguageCodeToName(it.lang) }.toTypedArray() + allSettings.map { LanguageMapper.getLanguageName(it.lang) }.toTypedArray() val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup) .setTitle("Select a Source") .setSingleChoiceItems(names, -1) { dialog, which -> @@ -417,7 +438,29 @@ class AnimeWatchFragment : Fragment() { } fun onAnimeEpisodeDownloadClick(i: String) { - model.onEpisodeClick(media, i, requireActivity().supportFragmentManager, isDownload = true) + activity?.let { + if (!hasDirAccess(it)) { + (it as MediaDetailsActivity).accessAlertDialog(it.launcher) { success -> + if (success) { + model.onEpisodeClick( + media, + i, + requireActivity().supportFragmentManager, + isDownload = true + ) + } else { + snackString(getString(R.string.download_permission_required)) + } + } + } else { + model.onEpisodeClick( + media, + i, + requireActivity().supportFragmentManager, + isDownload = true + ) + } + } } fun onAnimeEpisodeStopDownloadClick(i: String) { @@ -435,10 +478,11 @@ class AnimeWatchFragment : Fragment() { DownloadedType( media.mainName(), i, - DownloadedType.Type.ANIME + MediaType.ANIME ) - ) - episodeAdapter.purgeDownload(i) + ) { + episodeAdapter.purgeDownload(i) + } } @OptIn(UnstableApi::class) @@ -447,22 +491,96 @@ class AnimeWatchFragment : Fragment() { DownloadedType( media.mainName(), i, - DownloadedType.Type.ANIME + MediaType.ANIME ) - ) - val taskName = AnimeDownloaderService.AnimeDownloadTask.getTaskName(media.mainName(), i) - val id = PrefManager.getAnimeDownloadPreferences().getString( - taskName, - "" - ) ?: "" - PrefManager.getAnimeDownloadPreferences().edit().remove(taskName).apply() - DownloadService.sendRemoveDownload( - requireContext(), - ExoplayerDownloadService::class.java, - id, - true - ) - episodeAdapter.deleteDownload(i) + ) { + val taskName = AnimeDownloaderService.AnimeDownloadTask.getTaskName(media.mainName(), i) + PrefManager.getAnimeDownloadPreferences().edit().remove(taskName).apply() + episodeAdapter.deleteDownload(i) + } + } + + @kotlin.OptIn(DelicateCoroutinesApi::class) + fun fixDownload(i: String) { + toast(R.string.running_fixes) + launchIO { + try { + val context = context ?: throw Exception("Context is null") + val directory = + getSubDirectory(context, MediaType.ANIME, false, media.mainName(), i) + ?: throw Exception("Directory is null") + val files = directory.listFiles() + val videoFiles = files.filter { it.extension == "mp4" || it.extension == "mkv" } + if (videoFiles.size != 1) { + val biggest = + videoFiles.filter { it.length() > 1000 }.maxByOrNull { it.length() } + ?: throw Exception("No video files found") + val newName = + AnimeDownloaderService.AnimeDownloadTask.getTaskName(media.mainName(), i) + .findValidName() + "." + biggest.extension + videoFiles.forEach { + if (it != biggest) { + it.delete() + } + } + if (newName != biggest.name) { + biggest.renameTo(newName) + } + toast(context.getString(R.string.success) + " (1)") + } else { + val ffExtension = Injekt.get().extension?.extension!! + val extension = ffExtension.getFileExtension() + val tempFile = + directory.createFile(extension.second, "temp.${extension.first}") + ?: throw Exception("Temp file is null") + val tempPath = ffExtension.setDownloadPath( + context, + tempFile.uri + ) + val videoPath = ffExtension.getReadPath( + context, + videoFiles[0].uri + ) + + val id = ffExtension.customFFMpeg( + "1", listOf(videoPath, tempPath) + ) { log -> + Logger.log(log) + } + val timeOut = System.currentTimeMillis() + 1000 * 60 * 10 + while (ffExtension.getState(id) != "COMPLETED") { + if (ffExtension.getState(id) == "FAILED") { + Logger.log("Failed to fix download") + ffExtension.getStackTrace(id)?.let { + Logger.log(it) + } + toast(R.string.failed_to_fix) + return@launchIO + } + if (System.currentTimeMillis() > timeOut) { + Logger.log("Failed to fix download: Timeout") + toast(R.string.failed_to_fix) + return@launchIO + } + } + if (ffExtension.hadError(id)) { + Logger.log("Failed to fix download: ${ffExtension.getStackTrace(id)}") + toast(R.string.failed_to_fix) + return@launchIO + } + val name = videoFiles[0].name + if (videoFiles[0].delete().not()) { + toast(R.string.delete_fail) + return@launchIO + } + tempFile.renameTo(name!!) + toast(context.getString(R.string.success) + " (2)") + } + } catch (e: Exception) { + toast(getString(R.string.error_msg, e.message)) + Logger.log(e) + } + } } private val downloadStatusReceiver = object : BroadcastReceiver() { @@ -526,8 +644,8 @@ class AnimeWatchFragment : Fragment() { episodeAdapter.updateType(style ?: PrefManager.getVal(PrefName.AnimeDefaultView)) episodeAdapter.notifyItemRangeInserted(0, arr.size) for (download in downloadManager.animeDownloadedTypes) { - if (download.title == media.mainName()) { - episodeAdapter.stopDownload(download.chapter) + if (media.compareName(download.titleName)) { + episodeAdapter.stopDownload(download.chapterName) } } } diff --git a/app/src/main/java/ani/dantotsu/media/anime/EpisodeAdapters.kt b/app/src/main/java/ani/dantotsu/media/anime/EpisodeAdapters.kt index 7a3d8aec..14be291a 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/EpisodeAdapters.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/EpisodeAdapters.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media.anime -import android.annotation.SuppressLint import android.app.AlertDialog import android.view.LayoutInflater import android.view.View @@ -8,18 +7,21 @@ import android.view.ViewGroup import android.view.animation.LinearInterpolator import android.widget.LinearLayout import androidx.annotation.OptIn +import androidx.core.view.isVisible import androidx.lifecycle.coroutineScope import androidx.media3.common.util.UnstableApi -import androidx.media3.exoplayer.offline.DownloadIndex import androidx.recyclerview.widget.RecyclerView -import ani.dantotsu.* +import ani.dantotsu.R import ani.dantotsu.connections.updateProgress +import ani.dantotsu.currContext import ani.dantotsu.databinding.ItemEpisodeCompactBinding import ani.dantotsu.databinding.ItemEpisodeGridBinding import ani.dantotsu.databinding.ItemEpisodeListBinding -import ani.dantotsu.download.anime.AnimeDownloaderService -import ani.dantotsu.download.video.Helper +import ani.dantotsu.download.DownloadsManager.Companion.getDirSize import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType +import ani.dantotsu.setAnimation import ani.dantotsu.settings.saving.PrefManager import com.bumptech.glide.Glide import com.bumptech.glide.load.model.GlideUrl @@ -53,15 +55,7 @@ class EpisodeAdapter( var arr: List = arrayListOf(), var offlineMode: Boolean ) : RecyclerView.Adapter() { - - private lateinit var index: DownloadIndex - - - init { - if (offlineMode) { - index = Helper.downloadManager(fragment.requireContext()).downloadIndex - } - } + val context = fragment.requireContext() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return (when (viewType) { @@ -97,11 +91,10 @@ class EpisodeAdapter( return type } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val ep = arr[position] val title = if (!ep.title.isNullOrEmpty() && ep.title != "null") { - ep.title?.let { AnimeNameAdapter.removeEpisodeNumber(it) } + ep.title?.let { MediaNameAdapter.removeEpisodeNumber(it) } } else { ep.number } ?: "" @@ -125,8 +118,7 @@ class EpisodeAdapter( binding.itemEpisodeFiller.visibility = View.GONE binding.itemEpisodeFillerView.visibility = View.GONE } - binding.itemEpisodeDesc.visibility = - if (ep.desc != null && ep.desc?.trim(' ') != "") View.VISIBLE else View.GONE + binding.itemEpisodeDesc.isVisible = !ep.desc.isNullOrBlank() binding.itemEpisodeDesc.text = ep.desc ?: "" holder.bind(ep.number, ep.downloadProgress, ep.desc) @@ -203,8 +195,7 @@ class EpisodeAdapter( val binding = holder.binding setAnimation(fragment.requireContext(), holder.binding.root) binding.itemEpisodeNumber.text = ep.number - binding.itemEpisodeFillerView.visibility = - if (ep.filler) View.VISIBLE else View.GONE + binding.itemEpisodeFillerView.isVisible = ep.filler if (media.userProgress != null) { if ((ep.number.toFloatOrNull() ?: 9999f) <= media.userProgress!!.toFloat()) binding.itemEpisodeViewedCover.visibility = View.VISIBLE @@ -248,17 +239,8 @@ class EpisodeAdapter( // Find the position of the chapter and notify only that item val position = arr.indexOfFirst { it.number == episodeNumber } if (position != -1) { - val taskName = AnimeDownloaderService.AnimeDownloadTask.getTaskName( - media.mainName(), - episodeNumber - ) - val id = PrefManager.getAnimeDownloadPreferences().getString( - taskName, - "" - ) ?: "" val size = try { - val download = index.getDownload(id) - bytesToHuman(download?.bytesDownloaded ?: 0) + bytesToHuman(getDirSize(context, MediaType.ANIME, media.mainName(), episodeNumber)) } catch (e: Exception) { null } @@ -352,6 +334,16 @@ class EpisodeAdapter( } } } + binding.itemDownload.setOnLongClickListener { + if (0 <= bindingAdapterPosition && bindingAdapterPosition < arr.size) { + val episodeNumber = arr[bindingAdapterPosition].number + if (downloadedEpisodes.contains(episodeNumber)) { + fragment.fixDownload(episodeNumber) + } + } + + true + } binding.itemEpisodeDesc.setOnClickListener { if (binding.itemEpisodeDesc.maxLines == 3) binding.itemEpisodeDesc.maxLines = 100 @@ -429,7 +421,7 @@ class EpisodeAdapter( if (bytes < 0) return null val unit = 1000 if (bytes < unit) return "$bytes B" - val exp = (Math.log(bytes.toDouble()) / ln(unit.toDouble())).toInt() + val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt() val pre = ("KMGTPE")[exp - 1] return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre) } diff --git a/app/src/main/java/ani/dantotsu/media/anime/ExoplayerView.kt b/app/src/main/java/ani/dantotsu/media/anime/ExoplayerView.kt index 7ae06a1a..b0bacad5 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/ExoplayerView.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/ExoplayerView.kt @@ -16,7 +16,10 @@ import android.graphics.Color import android.graphics.drawable.Animatable import android.hardware.SensorManager import android.media.AudioManager -import android.media.AudioManager.* +import android.media.AudioManager.AUDIOFOCUS_GAIN +import android.media.AudioManager.AUDIOFOCUS_LOSS +import android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT +import android.media.AudioManager.STREAM_MUSIC import android.net.Uri import android.os.Build import android.os.Bundle @@ -27,46 +30,80 @@ import android.provider.Settings.System import android.util.AttributeSet import android.util.Rational import android.util.TypedValue -import android.view.* -import android.view.KeyEvent.* +import android.view.GestureDetector +import android.view.KeyEvent +import android.view.KeyEvent.ACTION_UP +import android.view.KeyEvent.KEYCODE_B +import android.view.KeyEvent.KEYCODE_DPAD_LEFT +import android.view.KeyEvent.KEYCODE_DPAD_RIGHT +import android.view.KeyEvent.KEYCODE_N +import android.view.KeyEvent.KEYCODE_SPACE +import android.view.MotionEvent +import android.view.OrientationEventListener +import android.view.View +import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.AdapterView import android.widget.ImageButton import android.widget.Spinner import android.widget.TextView import androidx.activity.addCallback +import androidx.activity.result.ActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.content.res.ResourcesCompat import androidx.core.math.MathUtils.clamp import androidx.core.view.isVisible -import androidx.core.view.WindowCompat import androidx.core.view.updateLayoutParams import androidx.lifecycle.lifecycleScope import androidx.media3.cast.CastPlayer import androidx.media3.cast.SessionAvailabilityListener -import androidx.media3.common.* +import androidx.media3.common.C import androidx.media3.common.C.AUDIO_CONTENT_TYPE_MOVIE +import androidx.media3.common.C.TRACK_TYPE_AUDIO +import androidx.media3.common.C.TRACK_TYPE_TEXT import androidx.media3.common.C.TRACK_TYPE_VIDEO +import androidx.media3.common.Format +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.PlaybackParameters +import androidx.media3.common.Player +import androidx.media3.common.TrackGroup +import androidx.media3.common.TrackSelectionOverride +import androidx.media3.common.Tracks import androidx.media3.common.util.UnstableApi -import androidx.media3.common.util.Util import androidx.media3.datasource.DataSource -import androidx.media3.datasource.DefaultDataSourceFactory +import androidx.media3.datasource.DefaultDataSource import androidx.media3.datasource.HttpDataSource import androidx.media3.datasource.cache.CacheDataSource import androidx.media3.datasource.okhttp.OkHttpDataSource +import androidx.media3.exoplayer.DefaultLoadControl import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.hls.HlsMediaSource import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import androidx.media3.exoplayer.source.MergingMediaSource import androidx.media3.exoplayer.trackselection.DefaultTrackSelector import androidx.media3.exoplayer.util.EventLogger import androidx.media3.session.MediaSession -import androidx.media3.ui.* -import androidx.media3.ui.CaptionStyleCompat.* -import androidx.media3.exoplayer.DefaultLoadControl +import androidx.media3.ui.AspectRatioFrameLayout +import androidx.media3.ui.CaptionStyleCompat +import androidx.media3.ui.CaptionStyleCompat.EDGE_TYPE_DEPRESSED +import androidx.media3.ui.CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW +import androidx.media3.ui.CaptionStyleCompat.EDGE_TYPE_NONE +import androidx.media3.ui.CaptionStyleCompat.EDGE_TYPE_OUTLINE +import androidx.media3.ui.DefaultTimeBar +import androidx.media3.ui.PlayerView +import androidx.media3.ui.SubtitleView import androidx.mediarouter.app.MediaRouteButton -import ani.dantotsu.* +import ani.dantotsu.GesturesListener +import ani.dantotsu.NoPaddingArrayAdapter import ani.dantotsu.R +import ani.dantotsu.addons.download.DownloadAddonManager +import ani.dantotsu.brightnessConverter +import ani.dantotsu.circularReveal import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.connections.discord.Discord @@ -75,20 +112,44 @@ import ani.dantotsu.connections.discord.DiscordServiceRunningSingleton import ani.dantotsu.connections.discord.RPC import ani.dantotsu.connections.updateProgress import ani.dantotsu.databinding.ActivityExoplayerBinding +import ani.dantotsu.defaultHeaders +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory import ani.dantotsu.download.video.Helper +import ani.dantotsu.dp +import ani.dantotsu.getCurrentBrightnessValue +import ani.dantotsu.hideSystemBars +import ani.dantotsu.hideSystemBarsExtendView +import ani.dantotsu.isOnline +import ani.dantotsu.logError import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType import ani.dantotsu.media.SubtitleDownloader +import ani.dantotsu.okHttpClient import ani.dantotsu.others.AniSkip import ani.dantotsu.others.AniSkip.getType +import ani.dantotsu.others.LanguageMapper import ani.dantotsu.others.ResettableTimer import ani.dantotsu.others.getSerialized -import ani.dantotsu.parsers.* +import ani.dantotsu.parsers.AnimeSources +import ani.dantotsu.parsers.HAnimeSources +import ani.dantotsu.parsers.Subtitle +import ani.dantotsu.parsers.SubtitleType +import ani.dantotsu.parsers.Video +import ani.dantotsu.parsers.VideoExtractor +import ani.dantotsu.parsers.VideoType import ani.dantotsu.settings.PlayerSettingsActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.snackString +import ani.dantotsu.startMainActivity import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.toPx +import ani.dantotsu.toast +import ani.dantotsu.tryWithSuspend import ani.dantotsu.util.Logger +import com.anggrayudi.storage.file.extension import com.bumptech.glide.Glide import com.google.android.gms.cast.framework.CastButtonFactory import com.google.android.gms.cast.framework.CastContext @@ -103,14 +164,19 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.* -import java.util.concurrent.* +import java.util.Calendar +import java.util.Locale +import java.util.Timer +import java.util.TimerTask +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import kotlin.collections.set import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt @UnstableApi -@SuppressLint("SetTextI18n", "ClickableViewAccessibility") +@SuppressLint("ClickableViewAccessibility") class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityListener { private val resumeWindow = "resumeWindow" @@ -128,6 +194,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private lateinit var cacheFactory: CacheDataSource.Factory private lateinit var playbackParameters: PlaybackParameters private lateinit var mediaItem: MediaItem + private lateinit var mediaSource: MergingMediaSource private var mediaSession: MediaSession? = null private lateinit var binding: ActivityExoplayerBinding @@ -137,6 +204,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private lateinit var exoSettings: ImageButton private lateinit var exoSubtitle: ImageButton private lateinit var exoSubtitleView: SubtitleView + private lateinit var exoAudioTrack: ImageButton private lateinit var exoRotate: ImageButton private lateinit var exoSpeed: ImageButton private lateinit var exoScreen: ImageButton @@ -159,10 +227,17 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private var orientationListener: OrientationEventListener? = null private var downloadId: String? = null + private var hasExtSubtitles = false + private var audioLanguages = mutableListOf>() companion object { var initialized = false lateinit var media: Media + + private const val DEFAULT_MIN_BUFFER_MS = 600000 + private const val DEFAULT_MAX_BUFFER_MS = 600000 + private const val BUFFER_FOR_PLAYBACK_MS = 2500 + private const val BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS = 5000 } private lateinit var episode: Episode @@ -175,7 +250,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private var extractor: VideoExtractor? = null private var video: Video? = null private var subtitle: Subtitle? = null - private val player = "player_settings" private var notchHeight: Int = 0 private var currentWindow = 0 @@ -231,7 +305,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } } playerView.findViewById(androidx.media3.ui.R.id.exo_buffering).translationY = - (if (orientation == Configuration.ORIENTATION_LANDSCAPE) 0 else (notchHeight + 8f.px)).dp + (if (orientation == Configuration.ORIENTATION_LANDSCAPE) 0 else (notchHeight + 8.toPx)).dp exoBrightnessCont.updateLayoutParams { marginEnd = if (orientation == Configuration.ORIENTATION_LANDSCAPE) notchHeight else 0 @@ -321,16 +395,31 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL 6 -> ResourcesCompat.getFont(this, R.font.blocky) else -> ResourcesCompat.getFont(this, R.font.poppins_semi_bold) } - playerView.subtitleView?.setStyle( - CaptionStyleCompat( - primaryColor, - subBackground, - subWindow, - outline, - secondaryColor, - font + val fontSize = PrefManager.getVal(PrefName.FontSize).toFloat() + + playerView.subtitleView?.let { subtitles -> + subtitles.setApplyEmbeddedStyles(false) + subtitles.setApplyEmbeddedFontSizes(false) + + subtitles.setStyle( + CaptionStyleCompat( + primaryColor, + subBackground, + subWindow, + outline, + secondaryColor, + font + ) ) - ) + + subtitles.alpha = + when (PrefManager.getVal(PrefName.Subtitles)) { + true -> PrefManager.getVal(PrefName.SubAlpha) + false -> 0f + } + + subtitles.setFixedTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize) + } } override fun onCreate(savedInstanceState: Bundle?) { @@ -344,15 +433,15 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL isCastApiAvailable = GoogleApiAvailability.getInstance() .isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS try { - castContext = CastContext.getSharedInstance(this) + castContext = + CastContext.getSharedInstance(this, Executors.newSingleThreadExecutor()).result castPlayer = CastPlayer(castContext!!) castPlayer!!.setSessionAvailabilityListener(this) } catch (e: Exception) { isCastApiAvailable = false } - WindowCompat.setDecorFitsSystemWindows(window, false) - hideSystemBars() + hideSystemBarsExtendView() onBackPressedDispatcher.addCallback(this) { finishAndRemoveTask() @@ -363,6 +452,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL exoSource = playerView.findViewById(R.id.exo_source) exoSettings = playerView.findViewById(R.id.exo_settings) exoSubtitle = playerView.findViewById(R.id.exo_sub) + exoAudioTrack = playerView.findViewById(R.id.exo_audio) exoSubtitleView = playerView.findViewById(androidx.media3.ui.R.id.exo_subtitles) exoRotate = playerView.findViewById(R.id.exo_rotate) exoSpeed = playerView.findViewById(androidx.media3.ui.R.id.exo_playback_speed) @@ -393,47 +483,44 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL }, AUDIO_CONTENT_TYPE_MOVIE, AUDIOFOCUS_GAIN) if (System.getInt(contentResolver, System.ACCELEROMETER_ROTATION, 0) != 1) { - if (PrefManager.getVal(PrefName.RotationPlayer)) { - orientationListener = - object : OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) { - override fun onOrientationChanged(orientation: Int) { - if (orientation in 45..135) { - if (rotation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) { - exoRotate.visibility = View.VISIBLE + if (PrefManager.getVal(PrefName.RotationPlayer)) { + orientationListener = + object : OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) { + override fun onOrientationChanged(orientation: Int) { + when (orientation) { + in 45..135 -> { + if (rotation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) { + exoRotate.visibility = View.VISIBLE + } + rotation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE + } + + in 225..315 -> { + if (rotation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { + exoRotate.visibility = View.VISIBLE + } + rotation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE + } + + in 315..360, in 0..45 -> { + if (rotation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { + exoRotate.visibility = View.VISIBLE + } + rotation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT + } + } } - rotation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE - } else if (orientation in 225..315) { - if (rotation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { - exoRotate.visibility = View.VISIBLE - } - rotation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE - } else if (orientation in 315..360 || orientation in 0..45) { - if (rotation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { - exoRotate.visibility = View.VISIBLE - } - rotation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } - } + orientationListener?.enable() } - orientationListener?.enable() - } - requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE - exoRotate.setOnClickListener { - requestedOrientation = rotation - it.visibility = View.GONE - } -} - - setupSubFormatting(playerView) - - - playerView.subtitleView?.alpha = when (PrefManager.getVal(PrefName.Subtitles)) { - true -> 1f - false -> 0f + requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + exoRotate.setOnClickListener { + requestedOrientation = rotation + it.visibility = View.GONE + } } - val fontSize = PrefManager.getVal(PrefName.FontSize).toFloat() - playerView.subtitleView?.setFixedTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize) + setupSubFormatting(playerView) if (savedInstanceState != null) { currentWindow = savedInstanceState.getInt(resumeWindow) @@ -703,11 +790,13 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL fun seek(forward: Boolean, event: MotionEvent? = null) { val seekTime = PrefManager.getVal(PrefName.SeekTime) val (card, text) = if (forward) { - forwardText.text = "+${seekTime * ++seekTimesF}" + val text = "+${seekTime * ++seekTimesF}" + forwardText.text = text handler.post { exoPlayer.seekTo(exoPlayer.currentPosition + seekTime * 1000) } fastForwardCard to forwardText } else { - rewindText.text = "-${seekTime * ++seekTimesR}" + val text = "-${seekTime * ++seekTimesR}" + rewindText.text = text handler.post { exoPlayer.seekTo(exoPlayer.currentPosition - seekTime * 1000) } fastRewindCard to rewindText } @@ -844,7 +933,8 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL isFastForwarding = true exoPlayer.setPlaybackSpeed(exoPlayer.playbackParameters.speed * 2) fastForward.visibility = View.VISIBLE - fastForward.text = "${exoPlayer.playbackParameters.speed}x" + val speedText = "${exoPlayer.playbackParameters.speed}x" + fastForward.text = speedText } fun stopFastForward() { @@ -941,10 +1031,10 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL episodeArr = episodes.keys.toList() currentEpisodeIndex = episodeArr.indexOf(media.anime!!.selectedEpisode!!) - episodeTitleArr = arrayListOf() + episodeTitleArr = arrayListOf() episodes.forEach { val episode = it.value - val cleanedTitle = AnimeNameAdapter.removeEpisodeNumberCompletely(episode.title ?: "") + val cleanedTitle = MediaNameAdapter.removeEpisodeNumberCompletely(episode.title ?: "") episodeTitleArr.add("Episode ${episode.number}${if (episode.filler) " [Filler]" else ""}${if (cleanedTitle.isNotBlank() && cleanedTitle != "null") ": $cleanedTitle" else ""}") } @@ -1029,35 +1119,48 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL val incognito: Boolean = PrefManager.getVal(PrefName.Incognito) if ((isOnline(context) && !offline) && Discord.token != null && !incognito) { lifecycleScope.launch { - val presence = RPC.createPresence(RPC.Companion.RPCData( - applicationId = Discord.application_Id, - type = RPC.Type.WATCHING, - activityName = media.userPreferredName, - details = ep.title?.takeIf { it.isNotEmpty() } ?: getString( - R.string.episode_num, - ep.number - ), - state = "Episode : ${ep.number}/${media.anime?.totalEpisodes ?: "??"}", - largeImage = media.cover?.let { - RPC.Link( - media.userPreferredName, - it - ) - }, - smallImage = RPC.Link( - "Dantotsu", - Discord.small_Image - ), - buttons = mutableListOf( + val discordMode = PrefManager.getCustomVal("discord_mode", "dantotsu") + val buttons = when (discordMode) { + "nothing" -> mutableListOf( RPC.Link(getString(R.string.view_anime), media.shareLink ?: ""), - RPC.Link( - "Stream on Dantotsu", - "https://github.com/rebelonion/Dantotsu/" + ) + + "dantotsu" -> mutableListOf( + RPC.Link(getString(R.string.view_anime), media.shareLink ?: ""), + RPC.Link("Watch on Dantotsu", getString(R.string.dantotsu)) + ) + + "anilist" -> { + val userId = PrefManager.getVal(PrefName.AnilistUserId) + val anilistLink = "https://anilist.co/user/$userId/" + mutableListOf( + RPC.Link(getString(R.string.view_anime), media.shareLink ?: ""), + RPC.Link("View My AniList", anilistLink) ) + } + + else -> mutableListOf() + } + val presence = RPC.createPresence( + RPC.Companion.RPCData( + applicationId = Discord.application_Id, + type = RPC.Type.WATCHING, + activityName = media.userPreferredName, + details = ep.title?.takeIf { it.isNotEmpty() } ?: getString( + R.string.episode_num, + ep.number + ), + state = "Episode : ${ep.number}/${media.anime?.totalEpisodes ?: "??"}", + largeImage = media.cover?.let { + RPC.Link( + media.userPreferredName, + it + ) + }, + smallImage = RPC.Link("Dantotsu", Discord.small_Image), + buttons = buttons ) ) - ) - val intent = Intent(context, DiscordService::class.java).apply { putExtra("presence", presence) } @@ -1065,7 +1168,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL startService(intent) } } - updateProgress() } } @@ -1102,7 +1204,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL if (PrefManager.getVal(PrefName.Cast)) { playerView.findViewById(R.id.exo_cast).apply { visibility = View.VISIBLE - if(PrefManager.getVal(PrefName.UseInternalCast)) { + if (PrefManager.getVal(PrefName.UseInternalCast)) { try { CastButtonFactory.setUpMediaRouteButton(context, this) dialogFactory = CustomCastThemeFactory() @@ -1125,7 +1227,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL putExtra("subtitle", subtitle) } exoPlayer.pause() - startActivity(intent) + onChangeSettings.launch(intent) } //Speed @@ -1264,7 +1366,12 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL media.anime!!.selectedEpisode!! ) - val list = (PrefManager.getNullableCustomVal("continueAnimeList", listOf(), List::class.java) as List).toMutableList() + @Suppress("UNCHECKED_CAST") + val list = (PrefManager.getNullableCustomVal( + "continueAnimeList", + listOf(), + List::class.java + ) as List).toMutableList() if (list.contains(media.id)) list.remove(media.id) list.add(media.id) PrefManager.setCustomVal("continueAnimeList", list) @@ -1276,7 +1383,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL val ext = episode.extractors?.find { it.server.name == episode.selectedExtractor } ?: return extractor = ext video = ext.videos.getOrNull(episode.selectedVideo) ?: return - subtitle = intent.getSerialized("subtitle") ?: when (val subLang: String? = PrefManager.getNullableCustomVal("subLang_${media.id}", null, String::class.java)) { @@ -1293,19 +1399,23 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } //Subtitles - exoSubtitle.visibility = if (ext.subtitles.isNotEmpty()) View.VISIBLE else View.GONE - exoSubtitle.setOnClickListener { - subClick() + hasExtSubtitles = ext.subtitles.isNotEmpty() + if (hasExtSubtitles) { + exoSubtitle.isVisible = hasExtSubtitles + exoSubtitle.setOnClickListener { + subClick() + } } - var sub: MediaItem.SubtitleConfiguration? = null - if (subtitle != null) { + val sub: MutableList = + emptyList().toMutableList() + ext.subtitles.forEach { subtitle -> + val subtitleUrl = if (!hasExtSubtitles) video!!.file.url else subtitle.file.url //var localFile: String? = null - if (subtitle?.type == SubtitleType.UNKNOWN) { - val context = this + if (subtitle.type == SubtitleType.UNKNOWN) { runBlocking { - val type = SubtitleDownloader.loadSubtitleType(context, subtitle!!.file.url) - val fileUri = Uri.parse(subtitle!!.file.url) - sub = MediaItem.SubtitleConfiguration + val type = SubtitleDownloader.loadSubtitleType(subtitleUrl) + val fileUri = Uri.parse(subtitleUrl) + sub += MediaItem.SubtitleConfiguration .Builder(fileUri) .setSelectionFlags(C.SELECTION_FLAG_DEFAULT) .setMimeType( @@ -1317,16 +1427,17 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } ) .setId("69") + .setLanguage(subtitle.language) .build() } println("sub: $sub") } else { - val subUri = Uri.parse(subtitle!!.file.url) - sub = MediaItem.SubtitleConfiguration + val subUri = Uri.parse(subtitleUrl) + sub += MediaItem.SubtitleConfiguration .Builder(subUri) .setSelectionFlags(C.SELECTION_FLAG_FORCED) .setMimeType( - when (subtitle?.type) { + when (subtitle.type) { SubtitleType.VTT -> MimeTypes.TEXT_VTT SubtitleType.ASS -> MimeTypes.TEXT_SSA SubtitleType.SRT -> MimeTypes.APPLICATION_SUBRIP @@ -1334,6 +1445,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } ) .setId("69") + .setLanguage(subtitle.language) .build() } } @@ -1342,7 +1454,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL ext.onVideoPlayed(video) } - val simpleCache = VideoCache.getInstance(this) val httpClient = okHttpClient.newBuilder().apply { ignoreAllSSLErrors() followRedirects(true) @@ -1358,10 +1469,9 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } dataSource } - val dafuckDataSourceFactory = - DefaultDataSourceFactory(this, Util.getUserAgent(this, R.string.app_name.toString())) + val dafuckDataSourceFactory = DefaultDataSource.Factory(this) cacheFactory = CacheDataSource.Factory().apply { - setCache(Helper.getSimpleCache(this@ExoplayerView)) + setCache(VideoCache.getInstance(this@ExoplayerView)) if (ext.server.offline) { setUpstreamDataSourceFactory(dafuckDataSourceFactory) } else { @@ -1377,15 +1487,45 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } val downloadedMediaItem = if (ext.server.offline) { - val key = ext.server.name + val titleName = ext.server.name.split("/").first() + val episodeName = ext.server.name.split("/").last() downloadId = PrefManager.getAnimeDownloadPreferences() - .getString(key, null) - if (downloadId != null) { + .getString("$titleName - $episodeName", null) + ?: PrefManager.getAnimeDownloadPreferences() + .getString(ext.server.name, null) + val exoItem = if (downloadId != null) { Helper.downloadManager(this) .downloadIndex.getDownload(downloadId!!)?.request?.toMediaItem() + } else null + if (exoItem != null) { + exoItem } else { - snackString("Download not found") - null + + val directory = + getSubDirectory(this, MediaType.ANIME, false, titleName, episodeName) + if (directory != null) { + val files = directory.listFiles() + println(files) + val docFile = directory.listFiles().firstOrNull { + it.name?.endsWith(".mp4") == true || it.name?.endsWith(".mkv") == true + || it.name?.endsWith(".${Injekt.get().extension?.extension?.getFileExtension()?.first ?: "ts"}") == true + } + if (docFile != null) { + val uri = docFile.uri + val downloadedMimeType = when (docFile.extension) { + "mp4" -> MimeTypes.APPLICATION_MP4 + "mkv" -> MimeTypes.APPLICATION_MATROSKA + else -> MimeTypes.APPLICATION_MP4 + } + MediaItem.Builder().setUri(uri).setMimeType(downloadedMimeType).build() + } else { + snackString("File not found") + null + } + } else { + snackString("Directory not found") + null + } } } else null @@ -1393,23 +1533,46 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL val builder = MediaItem.Builder().setUri(video!!.file.url).setMimeType(mimeType) Logger.log("url: ${video!!.file.url}") Logger.log("mimeType: $mimeType") - - if (sub != null) { - val listofnotnullsubs = listOfNotNull(sub) - builder.setSubtitleConfigurations(listofnotnullsubs) - } + builder.setSubtitleConfigurations(sub) builder.build() } else { - val addedSubsDownloadedMediaItem = downloadedMediaItem.buildUpon() - if (sub != null) { - val listofnotnullsubs = listOfNotNull(sub) - val addLanguage = listofnotnullsubs[0].buildUpon().setLanguage("en").build() + if (sub.isNotEmpty()) { + val addedSubsDownloadedMediaItem = downloadedMediaItem.buildUpon() + val addLanguage = sub[0].buildUpon().setLanguage("en").build() addedSubsDownloadedMediaItem.setSubtitleConfigurations(listOf(addLanguage)) episode.selectedSubtitle = 0 + addedSubsDownloadedMediaItem.build() + } else { + downloadedMediaItem } - addedSubsDownloadedMediaItem.build() } + val audioMediaItem = mutableListOf() + audioLanguages.clear() + ext.audioTracks.forEach { + var code = LanguageMapper.getLanguageCode(it.lang) + if (code == "all") code = "un" + audioLanguages.add(Pair(it.lang, code)) + audioMediaItem.add( + MediaItem.Builder() + .setUri(it.url) + .setMimeType(MimeTypes.AUDIO_UNKNOWN) + .setTag(code) + .build() + ) + } + + val audioSources = audioMediaItem.map { mediaItem -> + if (mediaItem.localConfiguration?.uri.toString().contains(".m3u8")) { + HlsMediaSource.Factory(cacheFactory).createMediaSource(mediaItem) + } else { + DefaultMediaSourceFactory(cacheFactory).createMediaSource(mediaItem) + } + }.toTypedArray() + val videoMediaSource = DefaultMediaSourceFactory(cacheFactory) + .createMediaSource(mediaItem) + mediaSource = MergingMediaSource(videoMediaSource, *audioSources) + //Source exoSource.setOnClickListener { @@ -1418,22 +1581,22 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL //Quality Track trackSelector = DefaultTrackSelector(this) - trackSelector.setParameters( - trackSelector.buildUponParameters() - .setAllowVideoMixedMimeTypeAdaptiveness(true) - .setAllowVideoNonSeamlessAdaptiveness(true) - .setSelectUndeterminedTextLanguage(true) - .setAllowAudioMixedMimeTypeAdaptiveness(true) - .setAllowMultipleAdaptiveSelections(true) - .setPreferredTextLanguage(subtitle?.language ?: "en") - .setPreferredTextRoleFlags(C.ROLE_FLAG_SUBTITLE) - .setRendererDisabled(TRACK_TYPE_VIDEO, false) - .setRendererDisabled(C.TRACK_TYPE_AUDIO, false) - .setRendererDisabled(C.TRACK_TYPE_TEXT, false) - .setMaxVideoSize(1, 1) - //.setOverrideForType( - // TrackSelectionOverride(trackSelector, 2)) - ) + val parameters = trackSelector.buildUponParameters() + .setAllowVideoMixedMimeTypeAdaptiveness(true) + .setAllowVideoNonSeamlessAdaptiveness(true) + .setSelectUndeterminedTextLanguage(true) + .setAllowAudioMixedMimeTypeAdaptiveness(true) + .setAllowMultipleAdaptiveSelections(true) + .setPreferredTextLanguage(subtitle?.language ?: Locale.getDefault().language) + .setPreferredTextRoleFlags(C.ROLE_FLAG_SUBTITLE) + .setRendererDisabled(TRACK_TYPE_VIDEO, false) + .setRendererDisabled(TRACK_TYPE_AUDIO, false) + .setRendererDisabled(TRACK_TYPE_TEXT, false) + .setMaxVideoSize(1, 1) + // .setOverrideForType(TrackSelectionOverride(trackSelector, TRACK_TYPE_VIDEO)) + if (PrefManager.getVal(PrefName.SettingsPreferDub)) + parameters.setPreferredAudioLanguage(Locale.getDefault().language) + trackSelector.setParameters(parameters) if (playbackPosition != 0L && !changingServer && !PrefManager.getVal(PrefName.AlwaysContinue)) { val time = String.format( @@ -1468,11 +1631,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private fun buildExoplayer() { //Player - val DEFAULT_MIN_BUFFER_MS = 600000 - val DEFAULT_MAX_BUFFER_MS = 600000 - val BUFFER_FOR_PLAYBACK_MS = 2500 - val BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS = 5000 - val loadControl = DefaultLoadControl.Builder() .setBackBuffer(1000 * 60 * 2, true) .setBufferDurationsMs( @@ -1491,7 +1649,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL .build().apply { playWhenReady = true this.playbackParameters = this@ExoplayerView.playbackParameters - setMediaItem(mediaItem) + setMediaSource(mediaSource) prepare() PrefManager.getCustomVal( "${media.id}_${media.anime!!.selectedEpisode}_max", @@ -1503,7 +1661,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } playerView.player = exoPlayer - try { val rightNow = Calendar.getInstance() mediaSession = MediaSession.Builder(this, exoPlayer) @@ -1516,32 +1673,17 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL exoPlayer.addListener(this) exoPlayer.addAnalyticsListener(EventLogger()) isInitialized = true - } - /*private fun selectSubtitleTrack() { saving this for later - // Get the current track groups - val trackGroups = exoPlayer.currentTrackGroups - // Prepare a track selector parameters builder - val parametersBuilder = DefaultTrackSelector.ParametersBuilder(this) - - // Iterate through the track groups to find the subtitle tracks - for (i in 0 until trackGroups.length) { - val trackGroup = trackGroups[i] - for (j in 0 until trackGroup.length) { - val trackMetadata = trackGroup.getFormat(j) - - // Check if the track is a subtitle track - if (MimeTypes.isText(trackMetadata.sampleMimeType)) { - parametersBuilder.setRendererDisabled(i, false) // Enable the renderer for this track group - parametersBuilder.setSelectionOverride(i, trackGroups, DefaultTrackSelector.SelectionOverride(j, 0)) // Override to select this track - break - } - } + if (!hasExtSubtitles && !PrefManager.getVal(PrefName.Subtitles)) { + onSetTrackGroupOverride(dummyTrack, TRACK_TYPE_TEXT) } - // Apply the track selector parameters to select the subtitle - trackSelector.setParameters(parametersBuilder) - }*/ + val isDisabled = (subtitle == null && hasExtSubtitles) + exoPlayer.trackSelectionParameters = exoPlayer.trackSelectionParameters + .buildUpon() + .setTrackTypeDisabled(TRACK_TYPE_TEXT, isDisabled) + .build() + } private fun releasePlayer() { isPlayerPlaying = exoPlayer.playWhenReady @@ -1659,7 +1801,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL aspectRatio = Rational(width, height) - videoInfo.text = "Quality: ${height}p" + videoInfo.text = getString(R.string.video_quality, height) if (exoPlayer.duration < playbackPosition) exoPlayer.seekTo(0) @@ -1716,7 +1858,8 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL if (isInitialized) { val playerCurrentTime = exoPlayer.currentPosition / 1000 currentTimeStamp = model.timeStamps.value?.find { timestamp -> - timestamp.interval.startTime < playerCurrentTime && playerCurrentTime < (timestamp.interval.endTime - 1) + timestamp.interval.startTime < playerCurrentTime + && playerCurrentTime < (timestamp.interval.endTime - 1) } val new = currentTimeStamp @@ -1735,35 +1878,33 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL timer = null return } - if (timer == null) { - timer = object : CountDownTimer(5000, 1000) { - override fun onTick(millisUntilFinished: Long) { - if (new == null){ - skipTimeButton.visibility = View.GONE - exoSkip.visibility = View.VISIBLE - disappeared = false - functionstarted = false - cancelTimer() - } - } - - override fun onFinish() { + timer = object : CountDownTimer(5000, 1000) { + override fun onTick(millisUntilFinished: Long) { + if (new == null) { skipTimeButton.visibility = View.GONE - exoSkip.visibility = View.VISIBLE - disappeared = true + exoSkip.isVisible = PrefManager.getVal(PrefName.SkipTime) > 0 + disappeared = false functionstarted = false cancelTimer() } } - timer?.start() + + override fun onFinish() { + skipTimeButton.visibility = View.GONE + exoSkip.isVisible = PrefManager.getVal(PrefName.SkipTime) > 0 + disappeared = true + functionstarted = false + cancelTimer() + } } + timer?.start() } if (PrefManager.getVal(PrefName.ShowTimeStampButton)) { - if (!functionstarted && !disappeared && PrefManager.getVal(PrefName.AutoHideTimeStamps)) { + if (!functionstarted && !disappeared && PrefManager.getVal(PrefName.AutoHideTimeStamps)) { disappearSkip() - } else if (!PrefManager.getVal(PrefName.AutoHideTimeStamps)){ + } else if (!PrefManager.getVal(PrefName.AutoHideTimeStamps)) { skipTimeButton.visibility = View.VISIBLE exoSkip.visibility = View.GONE skipTimeText.text = new.skipType.getType() @@ -1771,6 +1912,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL exoPlayer.seekTo((new.interval.endTime * 1000).toLong()) } } + } if (PrefManager.getVal(PrefName.AutoSkipOPED) && (new.skipType == "op" || new.skipType == "ed") && !skippedTimeStamps.contains(new) @@ -1778,6 +1920,13 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL exoPlayer.seekTo((new.interval.endTime * 1000).toLong()) skippedTimeStamps.add(new) } + if (PrefManager.getVal(PrefName.AutoSkipRecap) && new.skipType == "recap" && !skippedTimeStamps.contains( + new + ) + ) { + exoPlayer.seekTo((new.interval.endTime * 1000).toLong()) + skippedTimeStamps.add(new) + } new.skipType.getType() } else { disappeared = false @@ -1792,43 +1941,95 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL }, 500) } + fun onSetTrackGroupOverride(trackGroup: Tracks.Group, type: @C.TrackType Int, index: Int = 0) { + val isDisabled = trackGroup.getTrackFormat(0).language == "none" + exoPlayer.trackSelectionParameters = exoPlayer.trackSelectionParameters + .buildUpon() + .setTrackTypeDisabled(TRACK_TYPE_TEXT, isDisabled) + .setOverrideForType( + TrackSelectionOverride(trackGroup.mediaTrackGroup, index) + ) + .build() + if (type == TRACK_TYPE_TEXT) setupSubFormatting(playerView) + playerView.subtitleView?.alpha = when (isDisabled) { + false -> PrefManager.getVal(PrefName.SubAlpha) + true -> 0f + } + } + + private val dummyTrack = Tracks.Group( + TrackGroup("Dummy Track", Format.Builder().apply { setLanguage("none") }.build()), + true, + intArrayOf(1), + booleanArrayOf(false) + ) + override fun onTracksChanged(tracks: Tracks) { + val audioTracks: ArrayList = arrayListOf() + val subTracks: ArrayList = arrayListOf(dummyTrack) tracks.groups.forEach { - println("Track__: $it") - println("Track__: ${it.length}") - println("Track__: ${it.isSelected}") - println("Track__: ${it.type}") - println("Track__: ${it.mediaTrackGroup.id}") - if (it.type == 3 && it.mediaTrackGroup.id == "1:") { - playerView.player?.trackSelectionParameters = - playerView.player?.trackSelectionParameters?.buildUpon() - ?.setOverrideForType( - TrackSelectionOverride(it.mediaTrackGroup, it.length - 1) - ) - ?.build()!! - } else if (it.type == 3) { - playerView.player?.trackSelectionParameters = - playerView.player?.trackSelectionParameters?.buildUpon() - ?.addOverride( - TrackSelectionOverride(it.mediaTrackGroup, listOf()) - ) - ?.build()!! + println( + "Track__: $it\nTrack__: ${it.length}\nTrack__: ${it.isSelected}\n" + + "Track__: ${it.type}\nTrack__: ${it.mediaTrackGroup.id}" + ) + when (it.type) { + TRACK_TYPE_AUDIO -> { + if (it.isSupported(true)) audioTracks.add(it) + } + + TRACK_TYPE_TEXT -> { + if (!hasExtSubtitles) { + if (it.isSupported(true)) subTracks.add(it) + return@forEach + } + } } } - println("Track: ${tracks.groups.size}") + exoAudioTrack.isVisible = audioTracks.size > 1 + exoAudioTrack.setOnClickListener { + TrackGroupDialogFragment(this, audioTracks, TRACK_TYPE_AUDIO, audioLanguages) + .show(supportFragmentManager, "dialog") + } + if (!hasExtSubtitles) { + exoSubtitle.isVisible = subTracks.size > 1 + exoSubtitle.setOnClickListener { + TrackGroupDialogFragment(this, subTracks, TRACK_TYPE_TEXT) + .show(supportFragmentManager, "dialog") + } + } + } + + private val onChangeSettings = registerForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { _: ActivityResult -> + if (!hasExtSubtitles) { + exoPlayer.currentTracks.groups.forEach { trackGroup -> + when (trackGroup.type) { + TRACK_TYPE_TEXT -> { + if (PrefManager.getVal(PrefName.Subtitles)) { + onSetTrackGroupOverride(trackGroup, TRACK_TYPE_TEXT) + } else { + onSetTrackGroupOverride(dummyTrack, TRACK_TYPE_TEXT) + } + } + + else -> {} + } + } + } + if (isInitialized) exoPlayer.play() } override fun onPlayerError(error: PlaybackException) { when (error.errorCode) { - PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED - -> { + PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, + PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED -> { toast("Source Exception : ${error.message}") isPlayerPlaying = true sourceClick() } - else - -> { + else -> { toast("Player Error ${error.errorCode} (${error.errorCodeName}) : ${error.message}") Injekt.get().logException(error) } @@ -1838,7 +2039,6 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL private var isBuffering = true override fun onPlaybackStateChanged(playbackState: Int) { if (playbackState == ExoPlayer.STATE_READY) { - exoPlayer.play() if (episodeLength == 0f) { episodeLength = exoPlayer.duration.toFloat() @@ -1893,7 +2093,8 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL } } - override fun onNewIntent(intent: Intent?) { + @SuppressLint("UnsafeIntentLaunch") + override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) finishAndRemoveTask() startActivity(intent) @@ -1922,10 +2123,11 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL // Cast private fun cast() { val videoURL = video?.file?.url ?: return + val subtitleUrl = if (!hasExtSubtitles) video!!.file.url else subtitle!!.file.url val shareVideo = Intent(Intent.ACTION_VIEW) shareVideo.setDataAndType(Uri.parse(videoURL), "video/*") shareVideo.setPackage("com.instantbits.cast.webvideo") - if (subtitle != null) shareVideo.putExtra("subtitle", subtitle!!.file.url) + if (subtitle != null) shareVideo.putExtra("subtitle", subtitleUrl) shareVideo.putExtra( "title", media.userPreferredName + " : Ep " + episodeTitleArr[currentEpisodeIndex] @@ -2102,16 +2304,16 @@ class CustomCastButton : MediaRouteButton { fun setCastCallback(castCallback: () -> Unit) { this.castCallback = castCallback } + constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) - constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) - - constructor(context: Context, attrs: AttributeSet, castCallback: () -> Unit) : super(context, attrs) { - this.castCallback = castCallback - } - + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( + context, + attrs, + defStyleAttr + ) override fun performClick(): Boolean { return if (PrefManager.getVal(PrefName.UseInternalCast)) { @@ -2121,4 +2323,4 @@ class CustomCastButton : MediaRouteButton { true } } -} +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/anime/SelectorDialogFragment.kt b/app/src/main/java/ani/dantotsu/media/anime/SelectorDialogFragment.kt index f83b22ad..e93267e2 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/SelectorDialogFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/SelectorDialogFragment.kt @@ -3,38 +3,66 @@ package ani.dantotsu.media.anime import android.annotation.SuppressLint import android.app.Activity import android.app.AlertDialog +import android.content.ActivityNotFoundException +import android.content.ComponentName import android.content.DialogInterface import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle -import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.activity.result.ActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView -import ani.dantotsu.* +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.R +import ani.dantotsu.addons.download.DownloadAddonManager +import ani.dantotsu.addons.torrent.TorrentAddonManager import ani.dantotsu.connections.crashlytics.CrashlyticsInterface +import ani.dantotsu.copyToClipboard +import ani.dantotsu.currActivity +import ani.dantotsu.currContext import ani.dantotsu.databinding.BottomSheetSelectorBinding import ani.dantotsu.databinding.ItemStreamBinding import ani.dantotsu.databinding.ItemUrlBinding +import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.video.Helper +import ani.dantotsu.getThemeColor +import ani.dantotsu.hideSystemBars import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaType +import ani.dantotsu.media.SubtitleDownloader +import ani.dantotsu.navBarHeight import ani.dantotsu.others.Download.download import ani.dantotsu.parsers.Subtitle +import ani.dantotsu.parsers.Video import ani.dantotsu.parsers.VideoExtractor import ani.dantotsu.parsers.VideoType +import ani.dantotsu.setSafeOnClickListener +import ani.dantotsu.settings.SettingsAddonActivity import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.snackString +import ani.dantotsu.toast +import ani.dantotsu.tryWith +import ani.dantotsu.util.Logger +import ani.dantotsu.util.customAlertDialog import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext +import tachiyomi.core.util.lang.launchIO import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.text.DecimalFormat @@ -71,10 +99,8 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { _binding = BottomSheetSelectorBinding.inflate(inflater, container, false) val window = dialog?.window window?.statusBarColor = Color.TRANSPARENT - val typedValue = TypedValue() - val theme = requireContext().theme - theme.resolveAttribute(com.google.android.material.R.attr.colorSurface, typedValue, true) - window?.navigationBarColor = typedValue.data + window?.navigationBarColor = + requireContext().getThemeColor(com.google.android.material.R.attr.colorSurface) return binding.root } @@ -211,12 +237,110 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { super.onViewCreated(view, savedInstanceState) } + private val externalPlayerResult = registerForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { result: ActivityResult -> + Logger.log(result.data.toString()) + } + + private fun exportMagnetIntent(episode: Episode, video: Video): Intent { + val amnis = "com.amnis" + return Intent(Intent.ACTION_VIEW).apply { + component = ComponentName(amnis, "$amnis.gui.player.PlayerActivity") + data = Uri.parse(video.file.url) + putExtra("title", "${media?.name} - ${episode.title}") + putExtra("position", 0) + putExtra(Intent.EXTRA_RETURN_RESULT, true) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + putExtra("secure_uri", true) + val headersArray = arrayOf() + video.file.headers.forEach { + headersArray.plus(arrayOf(it.key, it.value)) + } + putExtra("headers", headersArray) + } + } + + @OptIn(DelicateCoroutinesApi::class) @SuppressLint("UnsafeOptInUsageError") fun startExoplayer(media: Media) { prevEpisode = null + episode?.let { ep -> + val video = ep.extractors?.find { + it.server.name == ep.selectedExtractor + }?.videos?.getOrNull(ep.selectedVideo) + video?.file?.url?.let { url -> + if (url.startsWith("magnet:") || url.endsWith(".torrent")) { + val torrentExtension = Injekt.get() + if (torrentExtension.isAvailable()) { + val activity = currActivity() ?: requireActivity() + launchIO { + try { + val extension = torrentExtension.extension!!.extension + torrentExtension.torrentHash?.let { + extension.removeTorrent(it) + } + val index = if (url.contains("index=")) { + url.substringAfter("index=").toIntOrNull() ?: 0 + } else 0 + Logger.log("Sending: ${url}, ${video.quality}, $index") + val currentTorrent = extension.addTorrent( + url, video.quality.toString(), "", "", false + ) + torrentExtension.torrentHash = currentTorrent.hash + video.file.url = extension.getLink(currentTorrent, index) + Logger.log("Received: ${video.file.url}") + if (launch == true) { + Intent(activity, ExoplayerView::class.java).apply { + ExoplayerView.media = media + ExoplayerView.initialized = true + startActivity(this) + } + } else { + model.setEpisode( + media.anime!!.episodes!![media.anime.selectedEpisode!!]!!, + "startExo no launch" + ) + } + dismiss() + } catch (e: Exception) { + Injekt.get().logException(e) + Logger.log(e) + toast("Error starting video: ${e.message}") + dismiss() + } + } + } else { + try { + externalPlayerResult.launch(exportMagnetIntent(ep, video)) + } catch (e: ActivityNotFoundException) { + val amnis = "com.amnis" + try { + startActivity( + Intent( + Intent.ACTION_VIEW, + Uri.parse("market://details?id=$amnis") + ) + ) + dismiss() + } catch (e: ActivityNotFoundException) { + startActivity( + Intent( + Intent.ACTION_VIEW, + Uri.parse("https://play.google.com/store/apps/details?id=$amnis") + ) + ) + } + } + } + return + } + } + } + dismiss() - if (launch!! || model.watchSources!!.isDownloadedSource(media.selected!!.sourceIndex)) { + if (launch!!) { stopAddingToList() val intent = Intent(activity, ExoplayerView::class.java) ExoplayerView.media = media @@ -274,7 +398,7 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { } fun performClick(position: Int) { - try { //bandaid fix for crash + try { val extractor = links[position] media!!.anime!!.episodes!![media!!.anime!!.selectedEpisode!!]?.selectedExtractor = extractor.server.name @@ -302,7 +426,6 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { ) } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: UrlViewHolder, position: Int) { val binding = holder.binding val video = extractor.videos[position] @@ -311,6 +434,49 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { } else { binding.urlDownload.visibility = View.GONE } + val subtitles = extractor.subtitles + if (subtitles.isNotEmpty()) { + binding.urlSub.visibility = View.VISIBLE + } else { + binding.urlSub.visibility = View.GONE + } + binding.urlSub.setOnClickListener { + if (subtitles.isNotEmpty()) { + val subtitleNames = subtitles.map { it.language } + var subtitleToDownload: Subtitle? = null + val alertDialog = AlertDialog.Builder(context, R.style.MyPopup) + .setTitle(R.string.download_subtitle) + .setSingleChoiceItems( + subtitleNames.toTypedArray(), + -1 + ) { _, which -> + subtitleToDownload = subtitles[which] + } + .setPositiveButton(R.string.download) { dialog, _ -> + scope.launch { + if (subtitleToDownload != null) { + SubtitleDownloader.downloadSubtitle( + requireContext(), + subtitleToDownload!!.file.url, + DownloadedType( + media!!.mainName(), + media!!.anime!!.episodes!![media!!.anime!!.selectedEpisode!!]!!.number, + MediaType.ANIME + ) + ) + } + } + dialog.dismiss() + } + .setNegativeButton(R.string.cancel) { dialog, _ -> + dialog.dismiss() + } + .show() + alertDialog.window?.setDimAmount(0.8f) + } else { + snackString(R.string.no_subtitles_available) + } + } binding.urlDownload.setSafeOnClickListener { media!!.anime!!.episodes!![media!!.anime!!.selectedEpisode!!]!!.selectedExtractor = extractor.server.name @@ -323,90 +489,169 @@ class SelectorDialogFragment : BottomSheetDialogFragment() { media!!.userPreferredName ) } else { - val episode = media!!.anime!!.episodes!![media!!.anime!!.selectedEpisode!!]!! + val downloadAddonManager: DownloadAddonManager = Injekt.get() + if (!downloadAddonManager.isAvailable()){ + val context = currContext() ?: requireContext() + context.customAlertDialog().apply { + setTitle(R.string.download_addon_not_installed) + setMessage(R.string.would_you_like_to_install) + setPosButton(R.string.yes) { + ContextCompat.startActivity( + context, + Intent(context, SettingsAddonActivity::class.java), + null + ) + } + setNegButton(R.string.no) { + return@setNegButton + } + show() + } + dismiss() + return@setSafeOnClickListener + } + val episode = + media!!.anime!!.episodes!![media!!.anime!!.selectedEpisode!!]!! val selectedVideo = if (extractor.videos.size > episode.selectedVideo) extractor.videos[episode.selectedVideo] else null - val subtitles = extractor.subtitles val subtitleNames = subtitles.map { it.language } - var subtitleToDownload: Subtitle? = null - val activity = currActivity()?:requireActivity() + var selectedSubtitles: MutableList> = mutableListOf() + var selectedAudioTracks: MutableList> = mutableListOf() + val activity = currActivity() ?: requireActivity() + selectedVideo?.file?.url?.let { url -> + if (url.startsWith("magnet:") || url.endsWith(".torrent")) { + val torrentExtension = Injekt.get() + if (!torrentExtension.isAvailable()) { + toast(R.string.torrent_addon_not_available) + return@setSafeOnClickListener + } + runBlocking { + try { + withContext(Dispatchers.IO) { + val extension = torrentExtension.extension!!.extension + torrentExtension.torrentHash?.let { + extension.removeTorrent(it) + } + val index = if (url.contains("index=")) { + url.substringAfter("index=").toIntOrNull() ?: 0 + } else 0 + Logger.log("Sending: ${url}, ${selectedVideo.quality}, $index") + val currentTorrent = extension.addTorrent( + url, selectedVideo.quality.toString(), "", "", false + ) + torrentExtension.torrentHash = currentTorrent.hash + selectedVideo.file.url = + extension.getLink(currentTorrent, index) + Logger.log("Received: ${selectedVideo.file.url}") + } + } catch (e: Exception) { + Injekt.get().logException(e) + Logger.log(e) + toast("Error starting video: ${e.message}") + return@runBlocking + } + } + } + } + val currContext = currContext() ?: requireContext() + fun go() { + if (selectedVideo != null) { + Helper.startAnimeDownloadService( + activity, + media!!.mainName(), + episode.number, + selectedVideo, + selectedSubtitles, + selectedAudioTracks, + media, + episode.thumb?.url ?: media!!.banner ?: media!!.cover + ) + broadcastDownloadStarted(episode.number, activity) + } else { + snackString(R.string.no_video_selected) + } + } + fun checkAudioTracks() { + val audioTracks = extractor.audioTracks.map { it.lang } + if (audioTracks.isNotEmpty()) { + val audioNamesArray = audioTracks.toTypedArray() + val checkedItems = BooleanArray(audioNamesArray.size) { false } + val alertDialog = AlertDialog.Builder(currContext, R.style.MyPopup) + .setTitle(R.string.download_audio_tracks) + .setMultiChoiceItems(audioNamesArray, checkedItems) { _, which, isChecked -> + val audioPair = Pair(extractor.audioTracks[which].url, extractor.audioTracks[which].lang) + if (isChecked) { + selectedAudioTracks.add(audioPair) + } else { + selectedAudioTracks.remove(audioPair) + } + } + .setPositiveButton(R.string.download) { _, _ -> + dialog?.dismiss() + go() + } + .setNegativeButton(R.string.skip) { dialog, _ -> + selectedAudioTracks = mutableListOf() + go() + dialog.dismiss() + } + .setNeutralButton(R.string.cancel) { dialog, _ -> + selectedAudioTracks = mutableListOf() + dialog.dismiss() + } + .show() + alertDialog.window?.setDimAmount(0.8f) + } else { + go() + } + } if (subtitles.isNotEmpty()) { - val alertDialog = AlertDialog.Builder(context, R.style.MyPopup) - .setTitle("Download Subtitle") - .setSingleChoiceItems( - subtitleNames.toTypedArray(), - -1 - ) { dialog, which -> - subtitleToDownload = subtitles[which] + val subtitleNamesArray = subtitleNames.toTypedArray() + val checkedItems = BooleanArray(subtitleNamesArray.size) { false } + + val alertDialog = AlertDialog.Builder(currContext, R.style.MyPopup) + .setTitle(R.string.download_subtitle) + .setMultiChoiceItems(subtitleNamesArray, checkedItems) { _, which, isChecked -> + val subtitlePair = Pair(subtitles[which].file.url, subtitles[which].language) + if (isChecked) { + selectedSubtitles.add(subtitlePair) + } else { + selectedSubtitles.remove(subtitlePair) + } } - .setPositiveButton("Download") { _, _ -> + .setPositiveButton(R.string.download) { _, _ -> dialog?.dismiss() - if (selectedVideo != null) { - Helper.startAnimeDownloadService( - activity, - media!!.mainName(), - episode.number, - selectedVideo, - subtitleToDownload, - media, - episode.thumb?.url ?: media!!.banner ?: media!!.cover - ) - broadcastDownloadStarted(episode.number, activity) - } else { - snackString("No Video Selected") - } + checkAudioTracks() } - .setNegativeButton("Skip") { dialog, _ -> - subtitleToDownload = null - if (selectedVideo != null) { - Helper.startAnimeDownloadService( - currActivity()!!, - media!!.mainName(), - episode.number, - selectedVideo, - subtitleToDownload, - media, - episode.thumb?.url ?: media!!.banner ?: media!!.cover - ) - broadcastDownloadStarted(episode.number, activity) - } else { - snackString("No Video Selected") - } + .setNegativeButton(R.string.skip) { dialog, _ -> + selectedSubtitles = mutableListOf() + checkAudioTracks() dialog.dismiss() } - .setNeutralButton("Cancel") { dialog, _ -> - subtitleToDownload = null + .setNeutralButton(R.string.cancel) { dialog, _ -> + selectedSubtitles = mutableListOf() dialog.dismiss() } .show() alertDialog.window?.setDimAmount(0.8f) } else { - if (selectedVideo != null) { - Helper.startAnimeDownloadService( - requireActivity(), - media!!.mainName(), - episode.number, - selectedVideo, - subtitleToDownload, - media, - episode.thumb?.url ?: media!!.banner ?: media!!.cover - ) - broadcastDownloadStarted(episode.number, activity) - } else { - snackString("No Video Selected") - } + checkAudioTracks() } } dismiss() } if (video.format == VideoType.CONTAINER) { - binding.urlSize.visibility = if (video.size != null) View.VISIBLE else View.GONE - binding.urlSize.text = - // if video size is null or 0, show "Unknown Size" else show the size in MB - (if (video.extraNote != null) " : " else "") + (if (video.size == 0.0) "Unknown Size" else (DecimalFormat( - "#.##" - ).format(video.size ?: 0).toString() + " MB")) + binding.urlSize.isVisible = video.size != null + // if video size is null or 0, show "Unknown Size" else show the size in MB + val sizeText = getString( + R.string.mb_size, "${if (video.extraNote != null) " : " else ""}${ + if (video.size == 0.0) getString(R.string.size_unknown) else DecimalFormat("#.##").format( + video.size ?: 0 + ) + }" + ) + binding.urlSize.text = sizeText } binding.urlNote.visibility = View.VISIBLE binding.urlNote.text = video.format.name diff --git a/app/src/main/java/ani/dantotsu/media/anime/SubtitleDialogFragment.kt b/app/src/main/java/ani/dantotsu/media/anime/SubtitleDialogFragment.kt index 8b172fe1..c17b286c 100644 --- a/app/src/main/java/ani/dantotsu/media/anime/SubtitleDialogFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/anime/SubtitleDialogFragment.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media.anime -import android.app.Activity import android.graphics.Color.TRANSPARENT import android.os.Bundle import android.view.LayoutInflater @@ -68,7 +67,11 @@ class SubtitleDialogFragment : BottomSheetDialogFragment() { binding.subtitleTitle.setText(R.string.none) model.getMedia().observe(viewLifecycleOwner) { media -> val mediaID: Int = media.id - val selSubs = PrefManager.getNullableCustomVal("subLang_${mediaID}", null, String::class.java) + val selSubs = PrefManager.getNullableCustomVal( + "subLang_${mediaID}", + null, + String::class.java + ) if (episode.selectedSubtitle != null && selSubs != "None") { binding.root.setCardBackgroundColor(TRANSPARENT) } @@ -108,12 +111,15 @@ class SubtitleDialogFragment : BottomSheetDialogFragment() { model.getMedia().observe(viewLifecycleOwner) { media -> val mediaID: Int = media.id val selSubs: String? = - PrefManager.getNullableCustomVal("subLang_${mediaID}", null, String::class.java) + PrefManager.getNullableCustomVal( + "subLang_${mediaID}", + null, + String::class.java + ) if (episode.selectedSubtitle != position - 1 && selSubs != subtitles[position - 1].language) { binding.root.setCardBackgroundColor(TRANSPARENT) } } - val activity: Activity = requireActivity() as ExoplayerView binding.root.setOnClickListener { episode.selectedSubtitle = position - 1 model.setEpisode(episode, "Subtitle") diff --git a/app/src/main/java/ani/dantotsu/media/anime/TrackGroupDialogFragment.kt b/app/src/main/java/ani/dantotsu/media/anime/TrackGroupDialogFragment.kt new file mode 100644 index 00000000..28ce26fb --- /dev/null +++ b/app/src/main/java/ani/dantotsu/media/anime/TrackGroupDialogFragment.kt @@ -0,0 +1,118 @@ +package ani.dantotsu.media.anime + +import android.annotation.SuppressLint +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.annotation.OptIn +import androidx.media3.common.C.TRACK_TYPE_AUDIO +import androidx.media3.common.C.TrackType +import androidx.media3.common.Tracks +import androidx.media3.common.util.UnstableApi +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.R +import ani.dantotsu.databinding.BottomSheetSubtitlesBinding +import ani.dantotsu.databinding.ItemSubtitleTextBinding +import java.util.Locale + +@OptIn(UnstableApi::class) +class TrackGroupDialogFragment( + private var instance: ExoplayerView, + private var trackGroups: ArrayList, + private var type: @TrackType Int, + private var overrideTrackNames: List>? = null +) : BottomSheetDialogFragment() { + private var _binding: BottomSheetSubtitlesBinding? = null + private val binding get() = _binding!! + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = BottomSheetSubtitlesBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (type == TRACK_TYPE_AUDIO) binding.selectionTitle.text = getString(R.string.audio_tracks) + binding.subtitlesRecycler.layoutManager = LinearLayoutManager(requireContext()) + binding.subtitlesRecycler.adapter = TrackGroupAdapter() + } + + inner class TrackGroupAdapter : RecyclerView.Adapter() { + inner class StreamViewHolder(val binding: ItemSubtitleTextBinding) : + RecyclerView.ViewHolder(binding.root) + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StreamViewHolder = + StreamViewHolder( + ItemSubtitleTextBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + @SuppressLint("SetTextI18n") + @OptIn(UnstableApi::class) + override fun onBindViewHolder(holder: StreamViewHolder, position: Int) { + val binding = holder.binding + trackGroups[position].let { trackGroup -> + if (overrideTrackNames?.getOrNull(position - (trackGroups.size - (overrideTrackNames?.size?:0))) != null) { + val pair = overrideTrackNames!![position - (trackGroups.size - overrideTrackNames!!.size)] + binding.subtitleTitle.text = + "[${pair.second}] ${pair.first}" + } else when (val language = trackGroup.getTrackFormat(0).language?.lowercase()) { + null -> { + binding.subtitleTitle.text = + getString(R.string.unknown_track, "Track $position") + } + + "none" -> { + binding.subtitleTitle.text = getString(R.string.disabled_track) + } + + else -> { + val locale = if (language.contains("-")) { + val parts = language.split("-") + try { + Locale(parts[0], parts[1]) + } catch (ignored: Exception) { + null + } + } else { + try { + Locale(language) + } catch (ignored: Exception) { + null + } + } + binding.subtitleTitle.text = locale?.let { + "[${it.language}] ${it.displayName}" + } ?: getString(R.string.unknown_track, language) + } + } + if (trackGroup.isSelected) { + val selected = "✔ ${binding.subtitleTitle.text}" + binding.subtitleTitle.text = selected + } + binding.root.setOnClickListener { + dismiss() + instance.onSetTrackGroupOverride(trackGroup, type) + } + } + } + + override fun getItemCount(): Int = trackGroups.size + } + + override fun onDestroy() { + _binding = null + super.onDestroy() + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/comments/CommentItem.kt b/app/src/main/java/ani/dantotsu/media/comments/CommentItem.kt index b78d4dce..6c552090 100644 --- a/app/src/main/java/ani/dantotsu/media/comments/CommentItem.kt +++ b/app/src/main/java/ani/dantotsu/media/comments/CommentItem.kt @@ -4,6 +4,7 @@ import android.annotation.SuppressLint import android.content.Intent import android.graphics.Color import android.view.View +import android.widget.PopupMenu import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import ani.dantotsu.R @@ -11,7 +12,9 @@ import ani.dantotsu.connections.comments.Comment import ani.dantotsu.connections.comments.CommentsAPI import ani.dantotsu.copyToClipboard import ani.dantotsu.databinding.ItemCommentsBinding +import ani.dantotsu.getAppString import ani.dantotsu.loadImage +import ani.dantotsu.openImage import ani.dantotsu.others.ImageViewDialog import ani.dantotsu.profile.ProfileActivity import ani.dantotsu.setAnimation @@ -28,17 +31,20 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date +import java.util.Locale import java.util.TimeZone import kotlin.math.abs import kotlin.math.sqrt -class CommentItem(val comment: Comment, - private val markwon: Markwon, - val parentSection: Section, - private val commentsFragment: CommentsFragment, - private val backgroundColor: Int, - val commentDepth: Int -) : BindableItem() { +class CommentItem( + val comment: Comment, + private val markwon: Markwon, + val parentSection: Section, + private val commentsFragment: CommentsFragment, + private val backgroundColor: Int, + val commentDepth: Int +) : + BindableItem() { lateinit var binding: ItemCommentsBinding val adapter = GroupieAdapter() private var subCommentIds: MutableList = mutableListOf() @@ -52,167 +58,211 @@ class CommentItem(val comment: Comment, adapter.add(repliesSection) } - @SuppressLint("SetTextI18n") override fun bind(viewBinding: ItemCommentsBinding, position: Int) { binding = viewBinding setAnimation(binding.root.context, binding.root) - viewBinding.commentRepliesList.layoutManager = LinearLayoutManager(commentsFragment.activity) - viewBinding.commentRepliesList.adapter = adapter - val isUserComment = CommentsAPI.userId == comment.userId - val levelColor = getAvatarColor(comment.totalVotes, backgroundColor) - markwon.setMarkdown(viewBinding.commentText, comment.content) - viewBinding.commentDelete.visibility = if (isUserComment || CommentsAPI.isAdmin || CommentsAPI.isMod) View.VISIBLE else View.GONE - viewBinding.commentBanUser.visibility = if ((CommentsAPI.isAdmin || CommentsAPI.isMod) && !isUserComment) View.VISIBLE else View.GONE - viewBinding.commentReport.visibility = if (!isUserComment) View.VISIBLE else View.GONE - viewBinding.commentEdit.visibility = if (isUserComment) View.VISIBLE else View.GONE - if (comment.tag == null) { - viewBinding.commentUserTagLayout.visibility = View.GONE - } else { - viewBinding.commentUserTagLayout.visibility = View.VISIBLE - viewBinding.commentUserTag.text = comment.tag.toString() - } - replying(isReplying) //sets default text - editing(isEditing) - if ((comment.replyCount ?: 0) > 0) { - viewBinding.commentTotalReplies.visibility = View.VISIBLE - viewBinding.commentRepliesDivider.visibility = View.VISIBLE - viewBinding.commentTotalReplies.text = if(repliesVisible) "Hide Replies" else - "View ${comment.replyCount} repl${if (comment.replyCount == 1) "y" else "ies"}" - } else { - viewBinding.commentTotalReplies.visibility = View.GONE - viewBinding.commentRepliesDivider.visibility = View.GONE - } - viewBinding.commentReply.visibility = View.VISIBLE - viewBinding.commentTotalReplies.setOnClickListener { - if (repliesVisible) { - repliesSection.clear() - removeSubCommentIds() - viewBinding.commentTotalReplies.text = "View ${comment.replyCount} repl${if (comment.replyCount == 1) "y" else "ies"}" - repliesVisible = false + val item = this + viewBinding.apply { + commentRepliesList.layoutManager = + LinearLayoutManager(commentsFragment.activity) + commentRepliesList.adapter = adapter + val isUserComment = CommentsAPI.userId == comment.userId + val levelColor = getAvatarColor(comment.totalVotes, backgroundColor) + markwon.setMarkdown(commentText, comment.content) + commentEdit.visibility = if (isUserComment) View.VISIBLE else View.GONE + if (comment.tag == null) { + commentUserTagLayout.visibility = View.GONE } else { - viewBinding.commentTotalReplies.text = "Hide Replies" - repliesSection.clear() - commentsFragment.viewReplyCallback(this) - repliesVisible = true + commentUserTagLayout.visibility = View.VISIBLE + commentUserTag.text = comment.tag.toString() + } + replying(isReplying) //sets default text + editing(isEditing) + if ((comment.replyCount ?: 0) > 0) { + commentTotalReplies.visibility = View.VISIBLE + commentRepliesDivider.visibility = View.VISIBLE + commentTotalReplies.context.run { + commentTotalReplies.text = if (repliesVisible) + getString(R.string.hide_replies) + else + if (comment.replyCount == 1) + getString(R.string.view_reply) + else + getString(R.string.view_replies_count, comment.replyCount) + } + } else { + commentTotalReplies.visibility = View.GONE + commentRepliesDivider.visibility = View.GONE + } + commentReply.visibility = View.VISIBLE + commentTotalReplies.setOnClickListener { + if (repliesVisible) { + repliesSection.clear() + removeSubCommentIds() + commentTotalReplies.context.run { + commentTotalReplies.text = if (comment.replyCount == 1) + getString(R.string.view_reply) + else + getString(R.string.view_replies_count, comment.replyCount) + } + repliesVisible = false + } else { + commentTotalReplies.setText(R.string.hide_replies) + repliesSection.clear() + commentsFragment.viewReplyCallback(item) + repliesVisible = true + } } - } - viewBinding.commentUserName.setOnClickListener { - ContextCompat.startActivity( - commentsFragment.activity, Intent(commentsFragment.activity, ProfileActivity::class.java) - .putExtra("userId", comment.userId.toInt()) - .putExtra("userLVL","[${levelColor.second}]"), null - ) - } - viewBinding.commentUserAvatar.setOnClickListener { - ContextCompat.startActivity( - commentsFragment.activity, Intent(commentsFragment.activity, ProfileActivity::class.java) - .putExtra("userId", comment.userId.toInt()) - .putExtra("userLVL","[${levelColor.second}]"), null - ) - } - viewBinding.commentText.setOnLongClickListener { - copyToClipboard(comment.content) - true - } + commentUserName.setOnClickListener { + ContextCompat.startActivity( + commentsFragment.activity, + Intent(commentsFragment.activity, ProfileActivity::class.java) + .putExtra("userId", comment.userId.toInt()), + null + ) + } + commentUserAvatar.setOnClickListener { + ContextCompat.startActivity( + commentsFragment.activity, + Intent(commentsFragment.activity, ProfileActivity::class.java) + .putExtra("userId", comment.userId.toInt()), + null + ) + } + commentText.setOnLongClickListener { + copyToClipboard(comment.content) + true + } - viewBinding.commentEdit.setOnClickListener { - editing(!isEditing) - commentsFragment.editCallback(this) - } - viewBinding.commentReply.setOnClickListener { - replying(!isReplying) - commentsFragment.replyTo(this, comment.username) - commentsFragment.replyCallback(this) - } - viewBinding.modBadge.visibility = if (comment.isMod == true) View.VISIBLE else View.GONE - viewBinding.adminBadge.visibility = if (comment.isAdmin == true) View.VISIBLE else View.GONE - viewBinding.commentDelete.setOnClickListener { - dialogBuilder("Delete Comment", "Are you sure you want to delete this comment?") { + commentEdit.setOnClickListener { + editing(!isEditing) + commentsFragment.editCallback(item) + } + commentReply.setOnClickListener { + replying(!isReplying) + commentsFragment.replyTo(item, comment.username) + commentsFragment.replyCallback(item) + } + modBadge.visibility = if (comment.isMod == true) View.VISIBLE else View.GONE + adminBadge.visibility = + if (comment.isAdmin == true) View.VISIBLE else View.GONE + commentInfo.setOnClickListener { + val popup = PopupMenu(commentsFragment.requireContext(), commentInfo) + popup.menuInflater.inflate(R.menu.profile_details_menu, popup.menu) + popup.menu.findItem(R.id.commentDelete)?.isVisible = + isUserComment || CommentsAPI.isAdmin || CommentsAPI.isMod + popup.menu.findItem(R.id.commentBanUser)?.isVisible = + (CommentsAPI.isAdmin || CommentsAPI.isMod) && !isUserComment + popup.menu.findItem(R.id.commentReport)?.isVisible = !isUserComment + popup.setOnMenuItemClickListener { item -> + when (item.itemId) { + R.id.commentReport -> { + dialogBuilder( + getAppString(R.string.report_comment), + getAppString(R.string.report_comment_confirm) + ) { + CoroutineScope(Dispatchers.Main + SupervisorJob()).launch { + val success = CommentsAPI.reportComment( + comment.commentId, + comment.username, + commentsFragment.mediaName, + comment.userId + ) + if (success) { + snackString(R.string.comment_reported) + } + } + } + true + } + + R.id.commentDelete -> { + dialogBuilder( + getAppString(R.string.delete_comment), + getAppString(R.string.delete_comment_confirm) + ) { + CoroutineScope(Dispatchers.Main + SupervisorJob()).launch { + val success = CommentsAPI.deleteComment(comment.commentId) + if (success) { + snackString(R.string.comment_deleted) + parentSection.remove(this@CommentItem) + } + } + } + true + } + + R.id.commentBanUser -> { + dialogBuilder( + getAppString(R.string.ban_user), + getAppString(R.string.ban_user_confirm) + ) { + CoroutineScope(Dispatchers.Main + SupervisorJob()).launch { + val success = CommentsAPI.banUser(comment.userId) + if (success) { + snackString(R.string.user_banned) + } + } + } + true + } + + else -> { + false + } + } + } + popup.show() + } + //fill the icon if the user has liked the comment + setVoteButtons(viewBinding) + commentUpVote.setOnClickListener { + val voteType = if (comment.userVoteType == 1) 0 else 1 + val previousVoteType = comment.userVoteType val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) scope.launch { - val success = CommentsAPI.deleteComment(comment.commentId) + val success = CommentsAPI.vote(comment.commentId, voteType) if (success) { - snackString("Comment Deleted") - parentSection.remove(this@CommentItem) + comment.userVoteType = voteType + + if (previousVoteType == -1) { + comment.downvotes -= 1 + } + comment.upvotes += if (voteType == 1) 1 else -1 + notifyChanged() } } } - } - viewBinding.commentBanUser.setOnClickListener { - dialogBuilder("Ban User", "Are you sure you want to ban this user?") { + + commentDownVote.setOnClickListener { + val voteType = if (comment.userVoteType == -1) 0 else -1 + val previousVoteType = comment.userVoteType val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) scope.launch { - val success = CommentsAPI.banUser(comment.userId) + val success = CommentsAPI.vote(comment.commentId, voteType) if (success) { - snackString("User Banned") + comment.userVoteType = voteType + if (previousVoteType == 1) { + comment.upvotes -= 1 + } + comment.downvotes += if (voteType == -1) 1 else -1 + notifyChanged() } } } - } - viewBinding.commentReport.setOnClickListener { - dialogBuilder("Report Comment", "Only report comments that violate the rules. Are you sure you want to report this comment?") { - val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) - scope.launch { - val success = CommentsAPI.reportComment(comment.commentId, comment.username, commentsFragment.mediaName, comment.userId) - if (success) { - snackString("Comment Reported") - } - } - } - } - //fill the icon if the user has liked the comment - setVoteButtons(viewBinding) - viewBinding.commentUpVote.setOnClickListener { - val voteType = if (comment.userVoteType == 1) 0 else 1 - val previousVoteType = comment.userVoteType - val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) - scope.launch { - val success = CommentsAPI.vote(comment.commentId, voteType) - if (success) { - comment.userVoteType = voteType - - if (previousVoteType == -1) { - comment.downvotes -= 1 - } - comment.upvotes += if (voteType == 1) 1 else -1 - - notifyChanged() - } - } - } - - viewBinding.commentDownVote.setOnClickListener { - val voteType = if (comment.userVoteType == -1) 0 else -1 - val previousVoteType = comment.userVoteType - val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) - scope.launch { - val success = CommentsAPI.vote(comment.commentId, voteType) - if (success) { - comment.userVoteType = voteType - - if (previousVoteType == 1) { - comment.upvotes -= 1 - } - comment.downvotes += if (voteType == -1) 1 else -1 - - notifyChanged() - } - } - } - viewBinding.commentTotalVotes.text = (comment.upvotes - comment.downvotes).toString() - viewBinding.commentUserAvatar.setOnLongClickListener { - ImageViewDialog.newInstance( - commentsFragment.activity, - "${comment.username}'s [Cover]", - comment.profilePictureUrl + commentTotalVotes.text = (comment.upvotes - comment.downvotes).toString() + commentUserAvatar.openImage( + commentsFragment.activity.getString(R.string.avatar, comment.username), + comment.profilePictureUrl ?: "" ) + comment.profilePictureUrl?.let { commentUserAvatar.loadImage(it) } + commentUserName.text = comment.username + val userColor = "[${levelColor.second}]" + commentUserLevel.text = userColor + commentUserLevel.setTextColor(levelColor.first) + commentUserTime.text = formatTimestamp(comment.timestamp) } - comment.profilePictureUrl?.let { viewBinding.commentUserAvatar.loadImage(it) } - viewBinding.commentUserName.text = comment.username - viewBinding.commentUserLevel.text = "[${levelColor.second}]" - viewBinding.commentUserLevel.setTextColor(levelColor.first) - viewBinding.commentUserTime.text = formatTimestamp(comment.timestamp) } override fun getLayout(): Int { @@ -228,12 +278,16 @@ class CommentItem(val comment: Comment, } fun replying(isReplying: Boolean) { - binding.commentReply.text = if (isReplying) commentsFragment.activity.getString(R.string.cancel) else "Reply" + binding.commentReply.text = + if (isReplying) commentsFragment.activity.getString(R.string.cancel) else "Reply" this.isReplying = isReplying } fun editing(isEditing: Boolean) { - binding.commentEdit.text = if (isEditing) commentsFragment.activity.getString(R.string.cancel) else commentsFragment.activity.getString(R.string.edit) + binding.commentEdit.text = + if (isEditing) commentsFragment.activity.getString(R.string.cancel) else commentsFragment.activity.getString( + R.string.edit + ) this.isEditing = isEditing } @@ -241,8 +295,9 @@ class CommentItem(val comment: Comment, subCommentIds.add(id) } - private fun removeSubCommentIds(){ + private fun removeSubCommentIds() { subCommentIds.forEach { id -> + @Suppress("UNCHECKED_CAST") val parentComments = parentSection.groups as? List ?: emptyList() val commentToRemove = parentComments.find { it.comment.commentId == id } commentToRemove?.let { @@ -260,11 +315,13 @@ class CommentItem(val comment: Comment, viewBinding.commentUpVote.alpha = 1f viewBinding.commentDownVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) } + -1 -> { viewBinding.commentUpVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) viewBinding.commentDownVote.setImageResource(R.drawable.ic_round_upvote_active_24) viewBinding.commentDownVote.alpha = 1f } + else -> { viewBinding.commentUpVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) viewBinding.commentDownVote.setImageResource(R.drawable.ic_round_upvote_inactive_24) @@ -272,9 +329,10 @@ class CommentItem(val comment: Comment, } } + @SuppressLint("SimpleDateFormat") private fun formatTimestamp(timestamp: String): String { return try { - val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT) dateFormat.timeZone = TimeZone.getTimeZone("UTC") val parsedDate = dateFormat.parse(timestamp) val currentDate = Date() @@ -297,8 +355,9 @@ class CommentItem(val comment: Comment, } companion object { + @SuppressLint("SimpleDateFormat") fun timestampToMillis(timestamp: String): Long { - val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT) dateFormat.timeZone = TimeZone.getTimeZone("UTC") val parsedDate = dateFormat.parse(timestamp) return parsedDate?.time ?: 0 @@ -307,7 +366,8 @@ class CommentItem(val comment: Comment, private fun getAvatarColor(voteCount: Int, backgroundColor: Int): Pair { val level = if (voteCount < 0) 0 else sqrt(abs(voteCount.toDouble()) / 0.8).toInt() - val colorString = if (level > usernameColors.size - 1) usernameColors[usernameColors.size - 1] else usernameColors[level] + val colorString = + if (level > usernameColors.size - 1) usernameColors[usernameColors.size - 1] else usernameColors[level] var color = Color.parseColor(colorString) val ratio = getContrastRatio(color, backgroundColor) if (ratio < 4.5) { @@ -325,16 +385,17 @@ class CommentItem(val comment: Comment, * @param callback the callback to call when the user clicks yes */ private fun dialogBuilder(title: String, message: String, callback: () -> Unit) { - val alertDialog = android.app.AlertDialog.Builder(commentsFragment.activity, R.style.MyPopup) - .setTitle(title) - .setMessage(message) - .setPositiveButton("Yes") { dialog, _ -> - callback() - dialog.dismiss() - } - .setNegativeButton("No") { dialog, _ -> - dialog.dismiss() - } + val alertDialog = + android.app.AlertDialog.Builder(commentsFragment.activity, R.style.MyPopup) + .setTitle(title) + .setMessage(message) + .setPositiveButton("Yes") { dialog, _ -> + callback() + dialog.dismiss() + } + .setNegativeButton("No") { dialog, _ -> + dialog.dismiss() + } val dialog = alertDialog.show() dialog?.window?.setDimAmount(0.8f) } diff --git a/app/src/main/java/ani/dantotsu/media/comments/CommentsFragment.kt b/app/src/main/java/ani/dantotsu/media/comments/CommentsFragment.kt index 5e699799..ff861dbe 100644 --- a/app/src/main/java/ani/dantotsu/media/comments/CommentsFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/comments/CommentsFragment.kt @@ -28,6 +28,7 @@ import ani.dantotsu.connections.comments.CommentsAPI import ani.dantotsu.databinding.FragmentCommentsBinding import ani.dantotsu.loadImage import ani.dantotsu.media.MediaDetailsActivity +import ani.dantotsu.setBaseline import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.snackString @@ -73,6 +74,12 @@ class CommentsFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity = requireActivity() as MediaDetailsActivity + + binding.commentsListContainer.setBaseline( + activity.navBar, + activity.binding.commentInputLayout + ) + //get the media id from the intent val mediaId = arguments?.getInt("mediaId") ?: -1 mediaName = arguments?.getString("mediaName") ?: "unknown" @@ -114,7 +121,6 @@ class CommentsFragment : Fragment() { } } } else { - toast("Not logged in") activity.binding.commentMessageContainer.visibility = View.GONE } @@ -297,7 +303,7 @@ class CommentsFragment : Fragment() { activity.binding.commentLabel.setOnClickListener { //alert dialog to enter a number, with a cancel and ok button - val alertDialog = android.app.AlertDialog.Builder(activity, R.style.MyPopup) + val alertDialog = AlertDialog.Builder(activity, R.style.MyPopup) .setTitle("Enter a chapter/episode number tag") .setView(R.layout.dialog_edittext) .setPositiveButton("OK") { dialog, _ -> @@ -523,11 +529,10 @@ class CommentsFragment : Fragment() { } - @SuppressLint("SetTextI18n") fun replyTo(comment: CommentItem, username: String) { if (comment.isReplying) { activity.binding.commentReplyToContainer.visibility = View.VISIBLE - activity.binding.commentReplyTo.text = "Replying to $username" + activity.binding.commentReplyTo.text = getString(R.string.replying_to, username) activity.binding.commentReplyToCancel.setOnClickListener { comment.replying(false) replyCallback(comment) @@ -574,7 +579,7 @@ class CommentsFragment : Fragment() { * Called when the user tries to comment for the first time */ private fun showCommentRulesDialog() { - val alertDialog = android.app.AlertDialog.Builder(activity, R.style.MyPopup) + val alertDialog = AlertDialog.Builder(activity, R.style.MyPopup) .setTitle("Commenting Rules") .setMessage( "I WILL BAN YOU WITHOUT HESITATION\n" + diff --git a/app/src/main/java/ani/dantotsu/media/manga/MangaCache.kt b/app/src/main/java/ani/dantotsu/media/manga/MangaCache.kt index ebf1c57f..359c64a5 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/MangaCache.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/MangaCache.kt @@ -2,7 +2,6 @@ package ani.dantotsu.media.manga import android.content.ContentResolver import android.content.ContentValues -import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri @@ -10,8 +9,8 @@ import android.os.Build import android.os.Environment import android.provider.MediaStore import android.util.LruCache -import ani.dantotsu.util.Logger import ani.dantotsu.snackString +import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.coroutines.Dispatchers @@ -25,15 +24,13 @@ data class ImageData( ) { suspend fun fetchAndProcessImage( page: Page, - httpSource: HttpSource, - context: Context + httpSource: HttpSource ): Bitmap? { return withContext(Dispatchers.IO) { try { // Fetch the image val response = httpSource.getImage(page) - Logger.log("Response: ${response.code}") - Logger.log("Response: ${response.message}") + Logger.log("Response: ${response.code} - ${response.message}") // Convert the Response to an InputStream val inputStream = response.body.byteStream() diff --git a/app/src/main/java/ani/dantotsu/media/manga/MangaChapterAdapter.kt b/app/src/main/java/ani/dantotsu/media/manga/MangaChapterAdapter.kt index d19aa011..933928e0 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/MangaChapterAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/MangaChapterAdapter.kt @@ -1,8 +1,6 @@ package ani.dantotsu.media.manga -import android.annotation.SuppressLint import android.app.AlertDialog -import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -16,12 +14,14 @@ import ani.dantotsu.currContext import ani.dantotsu.databinding.ItemChapterListBinding import ani.dantotsu.databinding.ItemEpisodeCompactBinding import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaNameAdapter import ani.dantotsu.setAnimation +import ani.dantotsu.util.customAlertDialog +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date import java.util.Locale -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch class MangaChapterAdapter( private var type: Int, @@ -145,8 +145,6 @@ class MangaChapterAdapter( inner class ChapterListViewHolder(val binding: ItemChapterListBinding) : RecyclerView.ViewHolder(binding.root) { private val activeCoroutines = mutableSetOf() - private val typedValue1 = TypedValue() - private val typedValue2 = TypedValue() fun bind(chapterNumber: String, progress: String?) { if (progress != null) { binding.itemChapterTitle.visibility = View.VISIBLE @@ -201,17 +199,6 @@ class MangaChapterAdapter( } init { - val theme = currContext()?.theme - theme?.resolveAttribute( - com.google.android.material.R.attr.colorError, - typedValue1, - true - ) - theme?.resolveAttribute( - com.google.android.material.R.attr.colorPrimary, - typedValue2, - true - ) itemView.setOnClickListener { if (0 <= bindingAdapterPosition && bindingAdapterPosition < arr.size) fragment.onMangaChapterClick(arr[bindingAdapterPosition].number) @@ -223,16 +210,15 @@ class MangaChapterAdapter( fragment.onMangaChapterStopDownloadClick(chapterNumber) return@setOnClickListener } else if (downloadedChapters.contains(chapterNumber)) { - val builder = AlertDialog.Builder(currContext(), R.style.MyPopup) - builder.setTitle("Delete Chapter") - builder.setMessage("Are you sure you want to delete ${chapterNumber}?") - builder.setPositiveButton("Yes") { _, _ -> - fragment.onMangaChapterRemoveDownloadClick(chapterNumber) + it.context.customAlertDialog().apply { + setTitle("Delete Chapter") + setMessage("Are you sure you want to delete ${chapterNumber}?") + setPosButton(R.string.delete) { + fragment.onMangaChapterRemoveDownloadClick(chapterNumber) + } + setNegButton(R.string.cancel) + show() } - builder.setNegativeButton("No") { _, _ -> - } - val dialog = builder.show() - dialog.window?.setDimAmount(0.8f) return@setOnClickListener } else { fragment.onMangaChapterDownloadClick(chapterNumber) @@ -242,37 +228,36 @@ class MangaChapterAdapter( } binding.itemDownload.setOnLongClickListener { //Alert dialog asking for the number of chapters to download - val alertDialog = AlertDialog.Builder(currContext(), R.style.MyPopup) - alertDialog.setTitle("Multi Chapter Downloader") - alertDialog.setMessage("Enter the number of chapters to download") - val input = NumberPicker(currContext()) - input.minValue = 1 - input.maxValue = itemCount - bindingAdapterPosition - input.value = 1 - alertDialog.setView(input) - alertDialog.setPositiveButton("OK") { _, _ -> - downloadNChaptersFrom(bindingAdapterPosition, input.value) + it.context.customAlertDialog().apply { + setTitle("Multi Chapter Downloader") + setMessage("Enter the number of chapters to download") + val input = NumberPicker(currContext()) + input.minValue = 1 + input.maxValue = itemCount - bindingAdapterPosition + input.value = 1 + setCustomView(input) + setPosButton("OK") { + downloadNChaptersFrom(bindingAdapterPosition, input.value) + } + setNegButton("Cancel") + show() } - alertDialog.setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() } - val dialog = alertDialog.show() - dialog.window?.setDimAmount(0.8f) true } } } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is ChapterCompactViewHolder -> { val binding = holder.binding setAnimation(fragment.requireContext(), holder.binding.root) val ep = arr[position] - val parsedNumber = MangaNameAdapter.findChapterNumber(ep.number)?.toInt() + val parsedNumber = MediaNameAdapter.findChapterNumber(ep.number)?.toInt() binding.itemEpisodeNumber.text = parsedNumber?.toString() ?: ep.number if (media.userProgress != null) { - if ((MangaNameAdapter.findChapterNumber(ep.number) + if ((MediaNameAdapter.findChapterNumber(ep.number) ?: 9999f) <= media.userProgress!!.toFloat() ) binding.itemEpisodeViewedCover.visibility = View.VISIBLE @@ -281,7 +266,7 @@ class MangaChapterAdapter( binding.itemEpisodeCont.setOnLongClickListener { updateProgress( media, - MangaNameAdapter.findChapterNumber(ep.number).toString() + MediaNameAdapter.findChapterNumber(ep.number).toString() ) true } @@ -317,7 +302,7 @@ class MangaChapterAdapter( } else binding.itemChapterTitle.visibility = View.VISIBLE if (media.userProgress != null) { - if ((MangaNameAdapter.findChapterNumber(ep.number) + if ((MediaNameAdapter.findChapterNumber(ep.number) ?: 9999f) <= media.userProgress!!.toFloat() ) { binding.itemEpisodeViewedCover.visibility = View.VISIBLE @@ -328,7 +313,7 @@ class MangaChapterAdapter( binding.root.setOnLongClickListener { updateProgress( media, - MangaNameAdapter.findChapterNumber(ep.number).toString() + MediaNameAdapter.findChapterNumber(ep.number).toString() ) true } @@ -344,6 +329,7 @@ class MangaChapterAdapter( fun updateType(t: Int) { type = t } + private fun formatDate(timestamp: Long?): String { timestamp ?: return "" // Return empty string if timestamp is null @@ -367,6 +353,7 @@ class MangaChapterAdapter( else -> "Just now" } } + 1L -> "1 day ago" in 2..6 -> "$daysDifference days ago" else -> SimpleDateFormat("dd MMM yyyy", Locale.getDefault()).format(targetDate) diff --git a/app/src/main/java/ani/dantotsu/media/manga/MangaNameAdapter.kt b/app/src/main/java/ani/dantotsu/media/manga/MangaNameAdapter.kt deleted file mode 100644 index ae755faa..00000000 --- a/app/src/main/java/ani/dantotsu/media/manga/MangaNameAdapter.kt +++ /dev/null @@ -1,29 +0,0 @@ -package ani.dantotsu.media.manga - -import java.util.regex.Matcher -import java.util.regex.Pattern - -class MangaNameAdapter { - companion object { - const val chapterRegex = "(chapter|chap|ch|c)[\\s:.\\-]*([\\d]+\\.?[\\d]*)[\\s:.\\-]*" - const val filedChapterNumberRegex = "(?= mangaReadSources.names.size) 0 else it } @@ -96,6 +102,9 @@ class MangaReadAdapter( showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } } } } + media.selected?.scanlators?.let { + hiddenScanlators.addAll(it) + } binding.animeSource.setAdapter( ArrayAdapter( fragment.requireContext(), @@ -121,7 +130,7 @@ class MangaReadAdapter( // Check if 'extension' and 'selected' properties exist and are accessible (mangaReadSources[source] as? DynamicMangaParser)?.let { ext -> ext.sourceLanguage = i - fragment.onLangChange(i) + fragment.onLangChange(i, ext.saveName) fragment.onSourceChange(media.selected!!.sourceIndex).apply { binding.animeSourceTitle.text = showUserText showUserTextListener = @@ -188,8 +197,8 @@ class MangaReadAdapter( else -> dialogBinding.animeSourceList } when (style) { - 0 -> dialogBinding.layoutText.text = "List" - 1 -> dialogBinding.layoutText.text = "Compact" + 0 -> dialogBinding.layoutText.setText(R.string.list) + 1 -> dialogBinding.layoutText.setText(R.string.compact) else -> dialogBinding.animeSourceList } selected.alpha = 1f @@ -201,18 +210,18 @@ class MangaReadAdapter( dialogBinding.animeSourceList.setOnClickListener { selected(it as ImageButton) style = 0 - dialogBinding.layoutText.text = "List" + dialogBinding.layoutText.setText(R.string.list) run = true } dialogBinding.animeSourceCompact.setOnClickListener { selected(it as ImageButton) style = 1 - dialogBinding.layoutText.text = "Compact" + dialogBinding.layoutText.setText(R.string.compact) run = true } dialogBinding.animeWebviewContainer.setOnClickListener { if (!WebViewUtil.supportsWebView(fragment.requireContext())) { - toast("WebView not installed") + toast(R.string.webview_not_installed) } //start CookieCatcher activity if (mangaReadSources.names.isNotEmpty() && source in 0 until mangaReadSources.names.size) { @@ -223,7 +232,7 @@ class MangaReadAdapter( refresh = true val intent = Intent(fragment.requireContext(), CookieCatcher::class.java) .putExtra("url", url) - ContextCompat.startActivity(fragment.requireContext(), intent, null) + startActivity(fragment.requireContext(), intent, null) } } } @@ -249,12 +258,13 @@ class MangaReadAdapter( } //Scanlator - dialogBinding.animeScanlatorContainer.visibility = - if (options.count() > 1) View.VISIBLE else View.GONE + dialogBinding.animeScanlatorContainer.isVisible = options.count() > 1 dialogBinding.scanlatorNo.text = "${options.count()}" dialogBinding.animeScanlatorTop.setOnClickListener { - val dialogView2 = LayoutInflater.from(currContext()).inflate(R.layout.custom_dialog_layout, null) - val checkboxContainer = dialogView2.findViewById(R.id.checkboxContainer) + val dialogView2 = + LayoutInflater.from(currContext()).inflate(R.layout.custom_dialog_layout, null) + val checkboxContainer = + dialogView2.findViewById(R.id.checkboxContainer) val tickAllButton = dialogView2.findViewById(R.id.toggleButton) // Function to get the right image resource for the toggle button @@ -359,7 +369,6 @@ class MangaReadAdapter( } //Chips - @SuppressLint("SetTextI18n") fun updateChips(limit: Int, names: Array, arr: Array, selected: Int = 0) { val binding = _binding if (binding != null) { @@ -382,8 +391,8 @@ class MangaReadAdapter( ) } - val startChapter = MangaNameAdapter.findChapterNumber(names[limit * (position)]) - val endChapter = MangaNameAdapter.findChapterNumber(names[last - 1]) + val startChapter = MediaNameAdapter.findChapterNumber(names[limit * (position)]) + val endChapter = MediaNameAdapter.findChapterNumber(names[last - 1]) val startChapterString = if (startChapter != null) { "Ch.$startChapter" } else { @@ -395,7 +404,8 @@ class MangaReadAdapter( names[last - 1] } //chip.text = "${names[limit * (position)]} - ${names[last - 1]}" - chip.text = "$startChapterString - $endChapterString" + val chipText = "$startChapterString - $endChapterString" + chip.text = chipText chip.setTextColor( ContextCompat.getColorStateList( fragment.requireContext(), @@ -429,7 +439,6 @@ class MangaReadAdapter( _binding?.animeSourceChipGroup?.removeAllViews() } - @SuppressLint("SetTextI18n") fun handleChapters() { val binding = _binding @@ -437,7 +446,11 @@ class MangaReadAdapter( if (media.manga?.chapters != null) { val chapters = media.manga.chapters!!.keys.toTypedArray() val anilistEp = (media.userProgress ?: 0).plus(1) - val appEp = PrefManager.getNullableCustomVal("${media.id}_current_chp", null, String::class.java) + val appEp = PrefManager.getNullableCustomVal( + "${media.id}_current_chp", + null, + String::class.java + ) ?.toIntOrNull() ?: 1 var continueEp = (if (anilistEp > appEp) anilistEp else appEp).toString() val filteredChapters = chapters.filter { chapterKey -> @@ -445,7 +458,7 @@ class MangaReadAdapter( chapter.scanlator !in hiddenScanlators } val formattedChapters = filteredChapters.map { - MangaNameAdapter.findChapterNumber(it)?.toInt()?.toString() + MediaNameAdapter.findChapterNumber(it)?.toInt()?.toString() } if (formattedChapters.contains(continueEp)) { continueEp = chapters[formattedChapters.indexOf(continueEp)] @@ -466,7 +479,11 @@ class MangaReadAdapter( val ep = media.manga.chapters!![continueEp]!! binding.itemEpisodeImage.loadImage(media.banner ?: media.cover) binding.animeSourceContinueText.text = - currActivity()!!.getString(R.string.continue_chapter) + "${ep.number}${if (!ep.title.isNullOrEmpty()) "\n${ep.title}" else ""}" + currActivity()!!.getString( + R.string.continue_chapter, + ep.number, + if (!ep.title.isNullOrEmpty()) ep.title else "" + ) binding.animeSourceContinue.setOnClickListener { fragment.onMangaChapterClick(continueEp) } @@ -481,12 +498,27 @@ class MangaReadAdapter( binding.animeSourceContinue.visibility = View.GONE } binding.animeSourceProgressBar.visibility = View.GONE - if (media.manga.chapters!!.isNotEmpty()) { - binding.animeSourceNotFound.visibility = View.GONE - binding.faqbutton.visibility = View.GONE - } else { - binding.animeSourceNotFound.visibility = View.VISIBLE - binding.faqbutton.visibility = View.VISIBLE + val sourceFound = media.manga.chapters!!.isNotEmpty() + binding.animeSourceNotFound.isGone = sourceFound + binding.faqbutton.isGone = sourceFound + if (!sourceFound && PrefManager.getVal(PrefName.SearchSources)) { + if (binding.animeSource.adapter.count > media.selected!!.sourceIndex + 1) { + val nextIndex = media.selected!!.sourceIndex + 1 + binding.animeSource.setText( + binding.animeSource.adapter + .getItem(nextIndex).toString(), false + ) + fragment.onSourceChange(nextIndex).apply { + binding.animeSourceTitle.text = showUserText + showUserTextListener = + { MainScope().launch { binding.animeSourceTitle.text = it } } + setLanguageList(0, nextIndex) + } + subscribeButton(false) + // invalidate if it's the last source + val invalidate = nextIndex == mangaReadSources.names.size - 1 + fragment.loadChapters(nextIndex, invalidate) + } } } else { binding.animeSourceContinue.visibility = View.GONE @@ -516,11 +548,10 @@ class MangaReadAdapter( val adapter = ArrayAdapter( fragment.requireContext(), R.layout.item_dropdown, - parser.extension.sources.map { LanguageMapper.mapLanguageCodeToName(it.lang) } + parser.extension.sources.map { LanguageMapper.getLanguageName(it.lang) } ) val items = adapter.count - binding?.animeSourceLanguageContainer?.visibility = - if (items > 1) View.VISIBLE else View.GONE + binding?.animeSourceLanguageContainer?.isVisible = items > 1 binding?.animeSourceLanguage?.setAdapter(adapter) diff --git a/app/src/main/java/ani/dantotsu/media/manga/MangaReadFragment.kt b/app/src/main/java/ani/dantotsu/media/manga/MangaReadFragment.kt index 621e07fb..bce5f312 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/MangaReadFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/MangaReadFragment.kt @@ -20,6 +20,8 @@ import androidx.cardview.widget.CardView import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.math.MathUtils.clamp +import androidx.core.view.isGone +import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels @@ -28,26 +30,36 @@ import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 -import ani.dantotsu.* +import ani.dantotsu.R import ani.dantotsu.databinding.FragmentAnimeWatchBinding import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager +import ani.dantotsu.download.DownloadsManager.Companion.compareName import ani.dantotsu.download.manga.MangaDownloaderService import ani.dantotsu.download.manga.MangaServiceDataSingleton +import ani.dantotsu.dp +import ani.dantotsu.isOnline import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsActivity import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType import ani.dantotsu.media.manga.mangareader.ChapterLoaderDialog +import ani.dantotsu.navBarHeight +import ani.dantotsu.notifications.subscription.SubscriptionHelper +import ani.dantotsu.notifications.subscription.SubscriptionHelper.Companion.saveSubscription import ani.dantotsu.others.LanguageMapper import ani.dantotsu.parsers.DynamicMangaParser import ani.dantotsu.parsers.HMangaSources import ani.dantotsu.parsers.MangaParser import ani.dantotsu.parsers.MangaSources +import ani.dantotsu.setNavigationTheme import ani.dantotsu.settings.extensionprefs.MangaSourcePreferencesFragment import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName -import ani.dantotsu.notifications.subscription.SubscriptionHelper -import ani.dantotsu.notifications.subscription.SubscriptionHelper.Companion.saveSubscription +import ani.dantotsu.snackString +import ani.dantotsu.util.StoragePermissions.Companion.accessAlertDialog +import ani.dantotsu.util.StoragePermissions.Companion.hasDirAccess import com.google.android.material.appbar.AppBarLayout import eu.kanade.tachiyomi.extension.manga.model.MangaExtension import eu.kanade.tachiyomi.source.ConfigurableSource @@ -182,8 +194,8 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { ) for (download in downloadManager.mangaDownloadedTypes) { - if (download.title == media.mainName()) { - chapterAdapter.stopDownload(download.chapter) + if (media.compareName(download.titleName)) { + chapterAdapter.stopDownload(download.chapterName) } } @@ -191,6 +203,10 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { ConcatAdapter(headerAdapter, chapterAdapter) lifecycleScope.launch(Dispatchers.IO) { + val offline = + !isOnline(binding.root.context) || PrefManager.getVal(PrefName.OfflineMode) + if (offline) media.selected!!.sourceIndex = + model.mangaReadSources!!.list.lastIndex model.loadMangaChapters(media, media.selected!!.sourceIndex) } loaded = true @@ -220,7 +236,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { val chapters = media.manga?.chapters?.values?.toList() //filter by selected language val progressChapterIndex = (chapters?.indexOfFirst { - MangaNameAdapter.findChapterNumber(it.number)?.toInt() == selected + MediaNameAdapter.findChapterNumber(it.number)?.toInt() == selected } ?: 0) + 1 if (progressChapterIndex < 0 || n < 1 || chapters == null) return @@ -305,11 +321,12 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { return model.mangaReadSources?.get(i)!! } - fun onLangChange(i: Int) { + fun onLangChange(i: Int, saveName: String) { val selected = model.loadSelected(media) selected.langIndex = i model.saveSelected(media.id, selected) media.selected = selected + PrefManager.removeCustomVal("${saveName}_${media.id}") } fun onScanlatorChange(list: List) { @@ -354,14 +371,12 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { val changeUIVisibility: (Boolean) -> Unit = { show -> val activity = activity if (activity is MediaDetailsActivity && isAdded) { - val visibility = if (show) View.VISIBLE else View.GONE - activity.findViewById(R.id.mediaAppBar).visibility = visibility - activity.findViewById(R.id.mediaViewPager).visibility = visibility - activity.findViewById(R.id.mediaCover).visibility = visibility - activity.findViewById(R.id.mediaClose).visibility = visibility - activity.tabLayout.setVisibility(visibility) - activity.findViewById(R.id.fragmentExtensionsContainer).visibility = - if (show) View.GONE else View.VISIBLE + activity.findViewById(R.id.mediaAppBar).isVisible = show + activity.findViewById(R.id.mediaViewPager).isVisible = show + activity.findViewById(R.id.mediaCover).isVisible = show + activity.findViewById(R.id.mediaClose).isVisible = show + activity.navBar.isVisible = show + activity.findViewById(R.id.fragmentExtensionsContainer).isGone = show } } var itemSelected = false @@ -370,7 +385,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { var selectedSetting = allSettings[0] if (allSettings.size > 1) { val names = - allSettings.map { LanguageMapper.mapLanguageCodeToName(it.lang) }.toTypedArray() + allSettings.map { LanguageMapper.getLanguageName(it.lang) }.toTypedArray() val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup) .setTitle("Select a Source") .setSingleChoiceItems(names, -1) { dialog, which -> @@ -428,51 +443,65 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { } fun onMangaChapterDownloadClick(i: String) { - if (!isNotificationPermissionGranted()) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - ActivityCompat.requestPermissions( - requireActivity(), - arrayOf(Manifest.permission.POST_NOTIFICATIONS), - 1 - ) - } - } - - model.continueMedia = false - media.manga?.chapters?.get(i)?.let { chapter -> - val parser = - model.mangaReadSources?.get(media.selected!!.sourceIndex) as? DynamicMangaParser - parser?.let { - CoroutineScope(Dispatchers.IO).launch { - val images = parser.imageList("", chapter.sChapter) - - // Create a download task - val downloadTask = MangaDownloaderService.DownloadTask( - title = media.mainName(), - chapter = chapter.title!!, - imageData = images, - sourceMedia = media, - retries = 2, - simultaneousDownloads = 2 + activity?.let { + if (!isNotificationPermissionGranted()) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + ActivityCompat.requestPermissions( + it, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + 1 ) + } + } + fun continueDownload() { + model.continueMedia = false + media.manga?.chapters?.get(i)?.let { chapter -> + val parser = + model.mangaReadSources?.get(media.selected!!.sourceIndex) as? DynamicMangaParser + parser?.let { + CoroutineScope(Dispatchers.IO).launch { + val images = parser.imageList(chapter.sChapter) - MangaServiceDataSingleton.downloadQueue.offer(downloadTask) + // Create a download task + val downloadTask = MangaDownloaderService.DownloadTask( + title = media.mainName(), + chapter = chapter.title!!, + imageData = images, + sourceMedia = media, + retries = 2, + simultaneousDownloads = 2 + ) - // If the service is not already running, start it - if (!MangaServiceDataSingleton.isServiceRunning) { - val intent = Intent(context, MangaDownloaderService::class.java) - withContext(Dispatchers.Main) { - ContextCompat.startForegroundService(requireContext(), intent) + MangaServiceDataSingleton.downloadQueue.offer(downloadTask) + + // If the service is not already running, start it + if (!MangaServiceDataSingleton.isServiceRunning) { + val intent = Intent(context, MangaDownloaderService::class.java) + withContext(Dispatchers.Main) { + ContextCompat.startForegroundService(requireContext(), intent) + } + MangaServiceDataSingleton.isServiceRunning = true + } + + // Inform the adapter that the download has started + withContext(Dispatchers.Main) { + chapterAdapter.startDownload(i) + } } - MangaServiceDataSingleton.isServiceRunning = true - } - - // Inform the adapter that the download has started - withContext(Dispatchers.Main) { - chapterAdapter.startDownload(i) } } } + if (!hasDirAccess(it)) { + (it as MediaDetailsActivity).accessAlertDialog(it.launcher) { success -> + if (success) { + continueDownload() + } else { + snackString(getString(R.string.download_permission_required)) + } + } + } else { + continueDownload() + } } } @@ -492,10 +521,11 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { DownloadedType( media.mainName(), i, - DownloadedType.Type.MANGA + MediaType.MANGA ) - ) - chapterAdapter.deleteDownload(i) + ) { + chapterAdapter.deleteDownload(i) + } } fun onMangaChapterStopDownloadClick(i: String) { @@ -510,10 +540,11 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener { DownloadedType( media.mainName(), i, - DownloadedType.Type.MANGA + MediaType.MANGA ) - ) - chapterAdapter.purgeDownload(i) + ) { + chapterAdapter.purgeDownload(i) + } } private val downloadStatusReceiver = object : BroadcastReceiver() { diff --git a/app/src/main/java/ani/dantotsu/media/manga/mangareader/BaseImageAdapter.kt b/app/src/main/java/ani/dantotsu/media/manga/mangareader/BaseImageAdapter.kt index c313d71d..cd5fa2b8 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/mangareader/BaseImageAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/mangareader/BaseImageAdapter.kt @@ -13,16 +13,19 @@ import androidx.core.view.GestureDetectorCompat import androidx.core.view.updateLayoutParams import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.RecyclerView -import ani.dantotsu.* +import ani.dantotsu.FileUrl +import ani.dantotsu.GesturesListener +import ani.dantotsu.R import ani.dantotsu.media.manga.MangaCache import ani.dantotsu.media.manga.MangaChapter +import ani.dantotsu.px import ani.dantotsu.settings.CurrentReaderSettings +import ani.dantotsu.tryWithSuspend import com.alexvasilkov.gestures.views.GestureFrameLayout import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.load.resource.bitmap.BitmapTransformation -import eu.kanade.tachiyomi.source.model.Page import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -34,7 +37,19 @@ abstract class BaseImageAdapter( chapter: MangaChapter ) : RecyclerView.Adapter() { val settings = activity.defaultSettings - val images = chapter.images() + private val chapterImages = chapter.images() + var images = chapterImages + + override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { + images = if (settings.layout == CurrentReaderSettings.Layouts.PAGED + && settings.direction == CurrentReaderSettings.Directions.BOTTOM_TO_TOP + ) { + chapterImages.reversed() + } else { + chapterImages + } + super.onAttachedToRecyclerView(recyclerView) + } @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { @@ -118,13 +133,13 @@ abstract class BaseImageAdapter( abstract suspend fun loadImage(position: Int, parent: View): Boolean companion object { - suspend fun Context.loadBitmap_old( + suspend fun Context.loadBitmapOld( link: FileUrl, transforms: List ): Bitmap? { //still used in some places return tryWithSuspend { withContext(Dispatchers.IO) { - Glide.with(this@loadBitmap_old) + Glide.with(this@loadBitmapOld) .asBitmap() .let { if (link.url.startsWith("file://")) { @@ -158,23 +173,26 @@ abstract class BaseImageAdapter( Glide.with(this@loadBitmap) .asBitmap() .let { - val fileUri = Uri.fromFile(File(link.url)).toString() val localFile = File(link.url) if (localFile.exists()) { it.load(localFile.absoluteFile) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) + } else if (link.url.startsWith("content://")) { + it.load(Uri.parse(link.url)) + .skipMemoryCache(true) + .diskCacheStrategy(DiskCacheStrategy.NONE) } else { mangaCache.get(link.url)?.let { imageData -> val bitmap = imageData.fetchAndProcessImage( imageData.page, - imageData.source, - context = this@loadBitmap + imageData.source ) it.load(bitmap) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) } + } } ?.let { @@ -207,9 +225,4 @@ abstract class BaseImageAdapter( return newBitmap } } - -} - -interface ImageFetcher { - suspend fun fetchImage(page: Page): Bitmap? } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/media/manga/mangareader/ChapterLoaderDialog.kt b/app/src/main/java/ani/dantotsu/media/manga/mangareader/ChapterLoaderDialog.kt index e1bebb83..cd2337f6 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/mangareader/ChapterLoaderDialog.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/mangareader/ChapterLoaderDialog.kt @@ -3,7 +3,6 @@ package ani.dantotsu.media.manga.mangareader import android.content.Intent import android.graphics.Color import android.os.Bundle -import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -14,6 +13,7 @@ import ani.dantotsu.BottomSheetDialogFragment import ani.dantotsu.R import ani.dantotsu.currActivity import ani.dantotsu.databinding.BottomSheetSelectorBinding +import ani.dantotsu.getThemeColor import ani.dantotsu.media.MediaDetailsViewModel import ani.dantotsu.media.MediaSingleton import ani.dantotsu.media.manga.MangaChapter @@ -37,7 +37,7 @@ class ChapterLoaderDialog : BottomSheetDialogFragment() { binding.selectorAutoListContainer.visibility = View.VISIBLE binding.selectorListContainer.visibility = View.GONE - binding.selectorTitle.text = getString(R.string.loading_next_chap) + binding.selectorTitle.text = getString(R.string.loading_chap_number, chp.number) binding.selectorCancel.setOnClickListener { dismiss() } @@ -49,8 +49,7 @@ class ChapterLoaderDialog : BottomSheetDialogFragment() { lifecycleScope.launch(Dispatchers.IO) { if (model.loadMangaChapterImages( chp, - m.selected!!, - m.mainName() + m.selected!! ) ) { val activity = currActivity() @@ -79,10 +78,7 @@ class ChapterLoaderDialog : BottomSheetDialogFragment() { _binding = BottomSheetSelectorBinding.inflate(inflater, container, false) val window = dialog?.window window?.statusBarColor = Color.TRANSPARENT - val typedValue = TypedValue() - val theme = requireContext().theme - theme.resolveAttribute(com.google.android.material.R.attr.colorSurface, typedValue, true) - window?.navigationBarColor = typedValue.data + window?.navigationBarColor = requireContext().getThemeColor(com.google.android.material.R.attr.colorSurface) return binding.root } diff --git a/app/src/main/java/ani/dantotsu/media/manga/mangareader/MangaReaderActivity.kt b/app/src/main/java/ani/dantotsu/media/manga/mangareader/MangaReaderActivity.kt index 157c6146..86085f58 100644 --- a/app/src/main/java/ani/dantotsu/media/manga/mangareader/MangaReaderActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/manga/mangareader/MangaReaderActivity.kt @@ -10,8 +10,19 @@ import android.content.res.Resources import android.graphics.Bitmap import android.os.Build import android.os.Bundle -import android.view.* -import android.view.KeyEvent.* +import android.view.HapticFeedbackConstants +import android.view.KeyEvent +import android.view.KeyEvent.ACTION_DOWN +import android.view.KeyEvent.KEYCODE_DPAD_DOWN +import android.view.KeyEvent.KEYCODE_DPAD_UP +import android.view.KeyEvent.KEYCODE_PAGE_DOWN +import android.view.KeyEvent.KEYCODE_PAGE_UP +import android.view.KeyEvent.KEYCODE_VOLUME_DOWN +import android.view.KeyEvent.KEYCODE_VOLUME_UP +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager import android.view.animation.OvershootInterpolator import android.widget.AdapterView import android.widget.CheckBox @@ -20,13 +31,16 @@ import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.math.MathUtils.clamp import androidx.core.view.GestureDetectorCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 -import ani.dantotsu.* +import ani.dantotsu.GesturesListener +import ani.dantotsu.NoPaddingArrayAdapter +import ani.dantotsu.R import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.crashlytics.CrashlyticsInterface import ani.dantotsu.connections.discord.Discord @@ -34,25 +48,41 @@ import ani.dantotsu.connections.discord.DiscordService import ani.dantotsu.connections.discord.DiscordServiceRunningSingleton import ani.dantotsu.connections.discord.RPC import ani.dantotsu.connections.updateProgress +import ani.dantotsu.currContext import ani.dantotsu.databinding.ActivityMangaReaderBinding +import ani.dantotsu.dp +import ani.dantotsu.hideSystemBarsExtendView +import ani.dantotsu.isOnline +import ani.dantotsu.logError import ani.dantotsu.media.Media import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaNameAdapter import ani.dantotsu.media.MediaSingleton import ani.dantotsu.media.manga.MangaCache import ani.dantotsu.media.manga.MangaChapter -import ani.dantotsu.media.manga.MangaNameAdapter import ani.dantotsu.others.ImageViewDialog import ani.dantotsu.parsers.HMangaSources import ani.dantotsu.parsers.MangaImage import ani.dantotsu.parsers.MangaSources +import ani.dantotsu.px +import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.settings.CurrentReaderSettings import ani.dantotsu.settings.CurrentReaderSettings.Companion.applyWebtoon -import ani.dantotsu.settings.CurrentReaderSettings.Directions.* -import ani.dantotsu.settings.CurrentReaderSettings.DualPageModes.* -import ani.dantotsu.settings.CurrentReaderSettings.Layouts.* +import ani.dantotsu.settings.CurrentReaderSettings.Directions.BOTTOM_TO_TOP +import ani.dantotsu.settings.CurrentReaderSettings.Directions.LEFT_TO_RIGHT +import ani.dantotsu.settings.CurrentReaderSettings.Directions.RIGHT_TO_LEFT +import ani.dantotsu.settings.CurrentReaderSettings.Directions.TOP_TO_BOTTOM +import ani.dantotsu.settings.CurrentReaderSettings.DualPageModes.Automatic +import ani.dantotsu.settings.CurrentReaderSettings.DualPageModes.Force +import ani.dantotsu.settings.CurrentReaderSettings.DualPageModes.No +import ani.dantotsu.settings.CurrentReaderSettings.Layouts.CONTINUOUS_PAGED +import ani.dantotsu.settings.CurrentReaderSettings.Layouts.PAGED import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.showSystemBarsRetractView +import ani.dantotsu.snackString import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.tryWith import com.alexvasilkov.gestures.views.GestureFrameLayout import com.bumptech.glide.load.resource.bitmap.BitmapTransformation import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView @@ -65,11 +95,11 @@ import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream -import java.util.* +import java.util.Timer +import java.util.TimerTask import kotlin.math.min import kotlin.properties.Delegates -@SuppressLint("SetTextI18n") class MangaReaderActivity : AppCompatActivity() { private val mangaCache = Injekt.get() @@ -88,7 +118,6 @@ class MangaReaderActivity : AppCompatActivity() { private var isContVisible = false private var showProgressDialog = true - private var hidescrollbar = false private var maxChapterPage = 0L private var currentChapterPage = 0L @@ -100,6 +129,13 @@ class MangaReaderActivity : AppCompatActivity() { var sliding = false var isAnimating = false + private val directionRLBT + get() = defaultSettings.direction == RIGHT_TO_LEFT + || defaultSettings.direction == BOTTOM_TO_TOP + private val directionPagedBT + get() = defaultSettings.layout == CurrentReaderSettings.Layouts.PAGED + && defaultSettings.direction == CurrentReaderSettings.Directions.BOTTOM_TO_TOP + override fun onAttachedToWindow() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && !PrefManager.getVal(PrefName.ShowSystemBars)) { val displayCutout = window.decorView.rootWindowInsets.displayCutout @@ -123,7 +159,7 @@ class MangaReaderActivity : AppCompatActivity() { } private fun hideSystemBars() { - if (PrefManager.getVal(PrefName.ShowSystemBars)) + if (PrefManager.getVal(PrefName.ShowSystemBars)) showSystemBarsRetractView() else hideSystemBarsExtendView() @@ -151,7 +187,11 @@ class MangaReaderActivity : AppCompatActivity() { defaultSettings = loadReaderSettings("reader_settings") ?: defaultSettings onBackPressedDispatcher.addCallback(this) { - val chapter = (MangaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) + if (!::media.isInitialized) { + finish() + return@addCallback + } + val chapter = (MediaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) ?.minus(1L) ?: 0).toString() if (chapter == "0.0" && PrefManager.getVal(PrefName.ChapterZeroReader) // Not asking individually or incognito @@ -195,8 +235,13 @@ class MangaReaderActivity : AppCompatActivity() { binding.mangaReaderRecycler.scrollToPosition((value.toInt() - 1) / (dualPage { 2 } ?: 1)) else - binding.mangaReaderPager.currentItem = - (value.toInt() - 1) / (dualPage { 2 } ?: 1) + if (defaultSettings.direction == CurrentReaderSettings.Directions.BOTTOM_TO_TOP) { + binding.mangaReaderPager.currentItem = + (maxChapterPage.toInt() - value.toInt()) / (dualPage { 2 } ?: 1) + } else { + binding.mangaReaderPager.currentItem = + (value.toInt() - 1) / (dualPage { 2 } ?: 1) + } pageSliderHide() } } @@ -223,8 +268,7 @@ class MangaReaderActivity : AppCompatActivity() { chapter = chapters[media.manga!!.selectedChapter] ?: return model.mangaReadSources = if (media.isAdult) HMangaSources else MangaSources - binding.mangaReaderSource.visibility = - if (PrefManager.getVal(PrefName.ShowSource)) View.VISIBLE else View.GONE + binding.mangaReaderSource.isVisible = PrefManager.getVal(PrefName.ShowSource) if (model.mangaReadSources!!.names.isEmpty()) { //try to reload sources try { @@ -303,11 +347,15 @@ class MangaReaderActivity : AppCompatActivity() { binding.mangaReaderNextChapter.performClick() } binding.mangaReaderNextChapter.setOnClickListener { - if (defaultSettings.direction == RIGHT_TO_LEFT || defaultSettings.direction == BOTTOM_TO_TOP) { + if (directionRLBT) { if (currentChapterIndex > 0) change(currentChapterIndex - 1) else snackString(getString(R.string.first_chapter)) } else { - if (chaptersArr.size > currentChapterIndex + 1) progress { change(currentChapterIndex + 1) } + if (chaptersArr.size > currentChapterIndex + 1) progress { + change( + currentChapterIndex + 1 + ) + } else snackString(getString(R.string.next_chapter_not_found)) } } @@ -316,8 +364,12 @@ class MangaReaderActivity : AppCompatActivity() { binding.mangaReaderPreviousChapter.performClick() } binding.mangaReaderPreviousChapter.setOnClickListener { - if (defaultSettings.direction == RIGHT_TO_LEFT || defaultSettings.direction == BOTTOM_TO_TOP) { - if (chaptersArr.size > currentChapterIndex + 1) progress { change(currentChapterIndex + 1) } + if (directionRLBT) { + if (chaptersArr.size > currentChapterIndex + 1) progress { + change( + currentChapterIndex + 1 + ) + } else snackString(getString(R.string.next_chapter_not_found)) } else { if (currentChapterIndex > 0) change(currentChapterIndex - 1) @@ -333,7 +385,7 @@ class MangaReaderActivity : AppCompatActivity() { PrefManager.setCustomVal("${media.id}_current_chp", chap.number) currentChapterIndex = chaptersArr.indexOf(chap.number) binding.mangaReaderChapterSelect.setSelection(currentChapterIndex) - if (defaultSettings.direction == RIGHT_TO_LEFT || defaultSettings.direction == BOTTOM_TO_TOP) { + if (directionRLBT) { binding.mangaReaderNextChap.text = chaptersTitleArr.getOrNull(currentChapterIndex - 1) ?: "" binding.mangaReaderPrevChap.text = @@ -350,6 +402,28 @@ class MangaReaderActivity : AppCompatActivity() { val incognito: Boolean = PrefManager.getVal(PrefName.Incognito) if ((isOnline(context) && !offline) && Discord.token != null && !incognito) { lifecycleScope.launch { + val discordMode = PrefManager.getCustomVal("discord_mode", "dantotsu") + val buttons = when (discordMode) { + "nothing" -> mutableListOf( + RPC.Link(getString(R.string.view_manga), media.shareLink ?: ""), + ) + + "dantotsu" -> mutableListOf( + RPC.Link(getString(R.string.view_manga), media.shareLink ?: ""), + RPC.Link("Read on Dantotsu", getString(R.string.dantotsu)) + ) + + "anilist" -> { + val userId = PrefManager.getVal(PrefName.AnilistUserId) + val anilistLink = "https://anilist.co/user/$userId/" + mutableListOf( + RPC.Link(getString(R.string.view_manga), media.shareLink ?: ""), + RPC.Link("View My AniList", anilistLink) + ) + } + + else -> mutableListOf() + } val presence = RPC.createPresence( RPC.Companion.RPCData( applicationId = Discord.application_Id, @@ -359,19 +433,12 @@ class MangaReaderActivity : AppCompatActivity() { ?: getString(R.string.chapter_num, chap.number), state = "${chap.number}/${media.manga?.totalChapters ?: "??"}", largeImage = media.cover?.let { cover -> - RPC.Link(media.userPreferredName, cover) - }, - smallImage = RPC.Link( - "Dantotsu", - Discord.small_Image - ), - buttons = mutableListOf( - RPC.Link(getString(R.string.view_manga), media.shareLink ?: ""), RPC.Link( - "Stream on Dantotsu", - "https://github.com/rebelonion/Dantotsu/" + media.userPreferredName, + cover ) - ) + }, + buttons = buttons ) ) val intent = Intent(context, DiscordService::class.java).apply { @@ -387,8 +454,7 @@ class MangaReaderActivity : AppCompatActivity() { scope.launch(Dispatchers.IO) { model.loadMangaChapterImages( chapter, - media.selected!!, - media.mainName() + media.selected!! ) } } @@ -428,7 +494,11 @@ class MangaReaderActivity : AppCompatActivity() { currentChapterPage = PrefManager.getCustomVal("${media.id}_${chapter.number}", 1L) - val chapImages = chapter.images() + val chapImages = if (directionPagedBT) { + chapter.images().reversed() + } else { + chapter.images() + } maxChapterPage = 0 if (chapImages.isNotEmpty()) { @@ -452,7 +522,11 @@ class MangaReaderActivity : AppCompatActivity() { } - val currentPage = currentChapterPage.toInt() + val currentPage = if (directionPagedBT) { + maxChapterPage - currentChapterPage + 1 + } else { + currentChapterPage + }.toInt() if ((defaultSettings.direction == TOP_TO_BOTTOM || defaultSettings.direction == BOTTOM_TO_TOP)) { binding.mangaReaderSwipy.vertical = true @@ -481,10 +555,10 @@ class MangaReaderActivity : AppCompatActivity() { binding.TopSwipeText.text = chaptersTitleArr.getOrNull(currentChapterIndex + 1) ?: getString(R.string.no_chapter) binding.mangaReaderSwipy.onTopSwiped = { - binding.mangaReaderNextChapter.performClick() + binding.mangaReaderPreviousChapter.performClick() } binding.mangaReaderSwipy.onBottomSwiped = { - binding.mangaReaderPreviousChapter.performClick() + binding.mangaReaderNextChapter.performClick() } } binding.mangaReaderSwipy.topBeingSwiped = { value -> @@ -593,7 +667,7 @@ class MangaReaderActivity : AppCompatActivity() { RecyclerView.VERTICAL else RecyclerView.HORIZONTAL, - !(defaultSettings.direction == TOP_TO_BOTTOM || defaultSettings.direction == LEFT_TO_RIGHT) + directionRLBT ) manager.preloadItemCount = 5 @@ -610,6 +684,8 @@ class MangaReaderActivity : AppCompatActivity() { else false } + manager.setStackFromEnd(defaultSettings.direction == BOTTOM_TO_TOP) + addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(v: RecyclerView, dx: Int, dy: Int) { defaultSettings.apply { @@ -664,9 +740,7 @@ class MangaReaderActivity : AppCompatActivity() { visibility = View.VISIBLE adapter = imageAdapter layoutDirection = - if (defaultSettings.direction == BOTTOM_TO_TOP || defaultSettings.direction == RIGHT_TO_LEFT) - View.LAYOUT_DIRECTION_RTL - else View.LAYOUT_DIRECTION_LTR + if (directionRLBT) View.LAYOUT_DIRECTION_RTL else View.LAYOUT_DIRECTION_LTR orientation = if (defaultSettings.direction == LEFT_TO_RIGHT || defaultSettings.direction == RIGHT_TO_LEFT) ViewPager2.ORIENTATION_HORIZONTAL @@ -741,12 +815,12 @@ class MangaReaderActivity : AppCompatActivity() { goneTimer.schedule(timerTask, controllerDuration) } - enum class pressPos { + enum class PressPos { LEFT, RIGHT, CENTER } fun handleController(shouldShow: Boolean? = null, event: MotionEvent? = null) { - var pressLocation = pressPos.CENTER + var pressLocation = PressPos.CENTER if (!sliding) { if (event != null && defaultSettings.layout == PAGED) { if (event.action != MotionEvent.ACTION_UP) return @@ -755,24 +829,24 @@ class MangaReaderActivity : AppCompatActivity() { val screenWidth = Resources.getSystem().displayMetrics.widthPixels //if in the 1st 1/5th of the screen width, left and lower than 1/5th of the screen height, left if (screenWidth / 5 in x + 1.. screenWidth - screenWidth / 5 && y > screenWidth / 5) { - pressLocation = if (defaultSettings.direction == RIGHT_TO_LEFT || defaultSettings.direction == BOTTOM_TO_TOP) { - pressPos.LEFT + pressLocation = if (defaultSettings.direction == RIGHT_TO_LEFT) { + PressPos.LEFT } else { - pressPos.RIGHT + PressPos.RIGHT } } } // if pressLocation is left or right go to previous or next page (paged mode only) - if (pressLocation == pressPos.LEFT) { + if (pressLocation == PressPos.LEFT) { if (binding.mangaReaderPager.currentItem > 0) { //if the current images zoomed in, go back to normal before going to previous page @@ -783,7 +857,7 @@ class MangaReaderActivity : AppCompatActivity() { return } - } else if (pressLocation == pressPos.RIGHT) { + } else if (pressLocation == PressPos.RIGHT) { if (binding.mangaReaderPager.currentItem < maxChapterPage - 1) { //if the current images zoomed in, go back to normal before going to next page if (imageAdapter?.isZoomed() == true) { @@ -859,9 +933,10 @@ class MangaReaderActivity : AppCompatActivity() { } } binding.mangaReaderSlider.layoutDirection = - if (defaultSettings.direction == RIGHT_TO_LEFT || defaultSettings.direction == BOTTOM_TO_TOP) + if (directionRLBT) View.LAYOUT_DIRECTION_RTL - else View.LAYOUT_DIRECTION_LTR + else + View.LAYOUT_DIRECTION_LTR shouldShow?.apply { isContVisible = !this } if (isContVisible) { isContVisible = false @@ -894,7 +969,11 @@ class MangaReaderActivity : AppCompatActivity() { } private var loading = false - fun updatePageNumber(page: Long) { + fun updatePageNumber(pageNumber: Long) { + var page = pageNumber + if (directionPagedBT) { + page = maxChapterPage - pageNumber + 1 + } if (currentChapterPage != page) { currentChapterPage = page PrefManager.setCustomVal("${media.id}_${chapter.number}", page) @@ -910,7 +989,6 @@ class MangaReaderActivity : AppCompatActivity() { model.loadMangaChapterImages( chapters[chaptersArr.getOrNull(currentChapterIndex + 1) ?: return@launch]!!, media.selected!!, - media.mainName(), false ) loading = false @@ -943,7 +1021,7 @@ class MangaReaderActivity : AppCompatActivity() { PrefManager.setCustomVal("${media.id}_save_progress", true) updateProgress( media, - MangaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) + MediaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) .toString() ) dialog.dismiss() @@ -961,11 +1039,11 @@ class MangaReaderActivity : AppCompatActivity() { if (!incognito && PrefManager.getCustomVal( "${media.id}_save_progress", true - ) && if (media.isAdult) PrefManager.getVal(PrefName.UpdateForHReader) else true + ) && if (media.isAdult) PrefManager.getVal(PrefName.UpdateForHReader) else true ) updateProgress( media, - MangaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) + MediaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!) .toString() ) runnable.run() @@ -1060,4 +1138,4 @@ class MangaReaderActivity : AppCompatActivity() { } return true } -} \ No newline at end of file +} diff --git a/app/src/main/java/ani/dantotsu/media/novel/NovelReadFragment.kt b/app/src/main/java/ani/dantotsu/media/novel/NovelReadFragment.kt index 859dfdac..c95328f6 100644 --- a/app/src/main/java/ani/dantotsu/media/novel/NovelReadFragment.kt +++ b/app/src/main/java/ani/dantotsu/media/novel/NovelReadFragment.kt @@ -5,40 +5,43 @@ import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle -import android.os.Environment import android.os.Handler import android.os.Looper import android.os.Parcelable -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat -import androidx.core.content.FileProvider import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.LinearLayoutManager +import ani.dantotsu.R +import ani.dantotsu.currContext import ani.dantotsu.databinding.FragmentAnimeWatchBinding import ani.dantotsu.download.DownloadedType import ani.dantotsu.download.DownloadsManager import ani.dantotsu.download.novel.NovelDownloaderService import ani.dantotsu.download.novel.NovelServiceDataSingleton import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaDetailsActivity import ani.dantotsu.media.MediaDetailsViewModel +import ani.dantotsu.media.MediaType import ani.dantotsu.media.novel.novelreader.NovelReaderActivity import ani.dantotsu.navBarHeight import ani.dantotsu.parsers.ShowResponse +import ani.dantotsu.snackString import ani.dantotsu.util.Logger +import ani.dantotsu.util.StoragePermissions +import ani.dantotsu.util.StoragePermissions.Companion.accessAlertDialog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class NovelReadFragment : Fragment(), DownloadTriggerCallback, @@ -61,26 +64,40 @@ class NovelReadFragment : Fragment(), override fun downloadTrigger(novelDownloadPackage: NovelDownloadPackage) { Logger.log("novel link: ${novelDownloadPackage.link}") - val downloadTask = NovelDownloaderService.DownloadTask( - title = media.mainName(), - chapter = novelDownloadPackage.novelName, - downloadLink = novelDownloadPackage.link, - originalLink = novelDownloadPackage.originalLink, - sourceMedia = media, - coverUrl = novelDownloadPackage.coverUrl, - retries = 2, - ) - NovelServiceDataSingleton.downloadQueue.offer(downloadTask) - CoroutineScope(Dispatchers.IO).launch { + activity?.let { + fun continueDownload() { + val downloadTask = NovelDownloaderService.DownloadTask( + title = media.mainName(), + chapter = novelDownloadPackage.novelName, + downloadLink = novelDownloadPackage.link, + originalLink = novelDownloadPackage.originalLink, + sourceMedia = media, + coverUrl = novelDownloadPackage.coverUrl, + retries = 2, + ) + NovelServiceDataSingleton.downloadQueue.offer(downloadTask) + CoroutineScope(Dispatchers.IO).launch { - if (!NovelServiceDataSingleton.isServiceRunning) { - val intent = Intent(context, NovelDownloaderService::class.java) - withContext(Dispatchers.Main) { - ContextCompat.startForegroundService(requireContext(), intent) + if (!NovelServiceDataSingleton.isServiceRunning) { + val intent = Intent(context, NovelDownloaderService::class.java) + withContext(Dispatchers.Main) { + ContextCompat.startForegroundService(requireContext(), intent) + } + NovelServiceDataSingleton.isServiceRunning = true + } } - NovelServiceDataSingleton.isServiceRunning = true } - + if (!StoragePermissions.hasDirAccess(it)) { + (it as MediaDetailsActivity).accessAlertDialog(it.launcher) { success -> + if (success) { + continueDownload() + } else { + snackString(getString(R.string.download_permission_required)) + } + } + } else { + continueDownload() + } } } @@ -90,27 +107,33 @@ class NovelReadFragment : Fragment(), DownloadedType( media.mainName(), novel.name, - DownloadedType.Type.NOVEL + MediaType.NOVEL ) ) ) { - val file = File( - context?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "${DownloadsManager.novelLocation}/${media.mainName()}/${novel.name}/0.epub" - ) - if (!file.exists()) return false - val fileUri = FileProvider.getUriForFile( - requireContext(), - "${requireContext().packageName}.provider", - file - ) - val intent = Intent(context, NovelReaderActivity::class.java).apply { - action = Intent.ACTION_VIEW - setDataAndType(fileUri, "application/epub+zip") - flags = Intent.FLAG_GRANT_READ_URI_PERMISSION + try { + val directory = + DownloadsManager.getSubDirectory( + context ?: currContext()!!, + MediaType.NOVEL, + false, + media.mainName(), + novel.name + ) + val file = directory?.findFile("0.epub") + if (file?.exists() == false) return false + val fileUri = file?.uri ?: return false + val intent = Intent(context, NovelReaderActivity::class.java).apply { + action = Intent.ACTION_VIEW + setDataAndType(fileUri, "application/epub+zip") + flags = Intent.FLAG_GRANT_READ_URI_PERMISSION + } + startActivity(intent) + return true + } catch (e: Exception) { + Logger.log(e) + return false } - startActivity(intent) - return true } else { return false } @@ -122,7 +145,7 @@ class NovelReadFragment : Fragment(), DownloadedType( media.mainName(), novel.name, - DownloadedType.Type.NOVEL + MediaType.NOVEL ) ) } @@ -133,9 +156,9 @@ class NovelReadFragment : Fragment(), DownloadedType( media.mainName(), novel.name, - DownloadedType.Type.NOVEL + MediaType.NOVEL ) - ) + ) {} } private val downloadStatusReceiver = object : BroadcastReceiver() { diff --git a/app/src/main/java/ani/dantotsu/media/novel/NovelResponseAdapter.kt b/app/src/main/java/ani/dantotsu/media/novel/NovelResponseAdapter.kt index 8da7c35b..92ddc739 100644 --- a/app/src/main/java/ani/dantotsu/media/novel/NovelResponseAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/novel/NovelResponseAdapter.kt @@ -1,14 +1,14 @@ package ani.dantotsu.media.novel -import android.util.Log -import android.util.TypedValue import android.view.LayoutInflater -import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import ani.dantotsu.R import ani.dantotsu.databinding.ItemNovelResponseBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.loadImage import ani.dantotsu.parsers.ShowResponse import ani.dantotsu.setAnimation import ani.dantotsu.snackString @@ -38,19 +38,9 @@ class NovelResponseAdapter( val binding = holder.binding val novel = list[position] setAnimation(fragment.requireContext(), holder.binding.root) + binding.itemEpisodeImage.loadImage(novel.coverUrl, 400, 0) - val cover = GlideUrl(novel.coverUrl.url) { novel.coverUrl.headers } - Glide.with(binding.itemEpisodeImage).load(cover).override(400, 0) - .into(binding.itemEpisodeImage) - - val typedValue = TypedValue() - fragment.requireContext().theme?.resolveAttribute( - com.google.android.material.R.attr.colorOnBackground, - typedValue, - true - ) - val color = typedValue.data - + val color =fragment.requireContext().getThemeColor(com.google.android.material.R.attr.colorOnBackground) binding.itemEpisodeTitle.text = novel.name binding.itemEpisodeFiller.text = if (downloadedCheckCallback.downloadedCheck(novel)) { @@ -71,8 +61,7 @@ class NovelResponseAdapter( } binding.itemEpisodeDesc2.text = novel.extra?.get("1") ?: "" val desc = novel.extra?.get("2") - binding.itemEpisodeDesc.visibility = - if (desc != null && desc.trim(' ') != "") View.VISIBLE else View.GONE + binding.itemEpisodeDesc.isVisible = !desc.isNullOrBlank() binding.itemEpisodeDesc.text = desc ?: "" binding.root.setOnClickListener { @@ -183,7 +172,7 @@ class NovelResponseAdapter( if (position != -1) { list[position].extra?.remove("0") list[position].extra?.set("0", "Downloading: $progress%") - Logger.log( "updateDownloadProgress: $progress, position: $position") + Logger.log("updateDownloadProgress: $progress, position: $position") notifyItemChanged(position) } } diff --git a/app/src/main/java/ani/dantotsu/media/novel/UrlAdapter.kt b/app/src/main/java/ani/dantotsu/media/novel/UrlAdapter.kt index 96e9bcf8..888499f5 100644 --- a/app/src/main/java/ani/dantotsu/media/novel/UrlAdapter.kt +++ b/app/src/main/java/ani/dantotsu/media/novel/UrlAdapter.kt @@ -1,6 +1,5 @@ package ani.dantotsu.media.novel -import android.annotation.SuppressLint import android.view.HapticFeedbackConstants import android.view.LayoutInflater import android.view.View @@ -31,7 +30,6 @@ class UrlAdapter( ) } - @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: UrlViewHolder, position: Int) { val binding = holder.binding val url = urls[position] diff --git a/app/src/main/java/ani/dantotsu/media/novel/novelreader/NovelReaderActivity.kt b/app/src/main/java/ani/dantotsu/media/novel/novelreader/NovelReaderActivity.kt index 13712c21..170980bc 100644 --- a/app/src/main/java/ani/dantotsu/media/novel/novelreader/NovelReaderActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/novel/novelreader/NovelReaderActivity.kt @@ -59,7 +59,8 @@ import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream -import java.util.* +import java.util.Timer +import java.util.TimerTask import kotlin.math.min import kotlin.properties.Delegates @@ -291,7 +292,11 @@ class NovelReaderActivity : AppCompatActivity(), EbookReaderEventListener { applySettings() } - val cfi = PrefManager.getNullableCustomVal("${sanitizedBookId}_progress", null, String::class.java) + val cfi = PrefManager.getNullableCustomVal( + "${sanitizedBookId}_progress", + null, + String::class.java + ) cfi?.let { binding.bookReader.goto(it) } binding.progress.visibility = View.GONE diff --git a/app/src/main/java/ani/dantotsu/media/user/ListActivity.kt b/app/src/main/java/ani/dantotsu/media/user/ListActivity.kt index 7ce2f136..994a0c78 100644 --- a/app/src/main/java/ani/dantotsu/media/user/ListActivity.kt +++ b/app/src/main/java/ani/dantotsu/media/user/ListActivity.kt @@ -1,23 +1,24 @@ package ani.dantotsu.media.user -import android.annotation.SuppressLint import android.os.Bundle -import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.view.Window -import android.view.WindowManager +import android.view.inputmethod.InputMethodManager import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.PopupMenu import androidx.core.content.ContextCompat +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams +import androidx.core.widget.addTextChangedListener import androidx.lifecycle.MutableLiveData import androidx.lifecycle.lifecycleScope import ani.dantotsu.R import ani.dantotsu.Refresh import ani.dantotsu.databinding.ActivityListBinding -import ani.dantotsu.navBarHeight +import ani.dantotsu.getThemeColor +import ani.dantotsu.hideSystemBarsExtendView import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.statusBarHeight @@ -28,34 +29,21 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext + class ListActivity : AppCompatActivity() { private lateinit var binding: ActivityListBinding private val scope = lifecycleScope private var selectedTabIdx = 0 - @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeManager(this).applyTheme() binding = ActivityListBinding.inflate(layoutInflater) - val typedValue = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorSurface, typedValue, true) - val primaryColor = typedValue.data - val typedValue2 = TypedValue() - theme.resolveAttribute( - com.google.android.material.R.attr.colorOnBackground, - typedValue2, - true - ) - val titleTextColor = typedValue2.data - val typedValue3 = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue3, true) - val primaryTextColor = typedValue3.data - val typedValue4 = TypedValue() - theme.resolveAttribute(com.google.android.material.R.attr.colorOutline, typedValue4, true) - val secondaryTextColor = typedValue4.data + val primaryColor = getThemeColor(com.google.android.material.R.attr.colorSurface) + val primaryTextColor = getThemeColor(com.google.android.material.R.attr.colorPrimary) + val secondaryTextColor = getThemeColor(com.google.android.material.R.attr.colorOutline) window.statusBarColor = primaryColor window.navigationBarColor = primaryColor @@ -72,10 +60,7 @@ class ListActivity : AppCompatActivity() { } else { binding.root.fitsSystemWindows = false requestWindowFeature(Window.FEATURE_NO_TITLE) - window.setFlags( - WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN - ) + hideSystemBarsExtendView() binding.settingsContainer.updateLayoutParams { topMargin = statusBarHeight } @@ -83,8 +68,10 @@ class ListActivity : AppCompatActivity() { setContentView(binding.root) val anime = intent.getBooleanExtra("anime", true) - binding.listTitle.text = - intent.getStringExtra("username") + "'s " + (if (anime) "Anime" else "Manga") + " List" + binding.listTitle.text = getString( + R.string.user_list, intent.getStringExtra("username"), + if (anime) getString(R.string.anime) else getString(R.string.manga) + ) binding.listTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab?) { this@ListActivity.selectedTabIdx = tab?.position ?: 0 @@ -171,7 +158,8 @@ class ListActivity : AppCompatActivity() { } binding.filter.setOnClickListener { - val genres = PrefManager.getVal>(PrefName.GenresList).toMutableSet().sorted() + val genres = + PrefManager.getVal>(PrefName.GenresList).toMutableSet().sorted() val popup = PopupMenu(this, it) popup.menu.add("All") genres.forEach { genre -> @@ -189,10 +177,32 @@ class ListActivity : AppCompatActivity() { //get the current tab val currentTab = binding.listTabLayout.getTabAt(binding.listTabLayout.selectedTabPosition) - val currentViewePager = binding.listViewPager.getChildAt(0) val currentFragment = supportFragmentManager.findFragmentByTag("f" + currentTab?.position.toString()) as? ListFragment currentFragment?.randomOptionClick() } + + binding.search.setOnClickListener { + toggleSearchView(binding.searchView.isVisible) + if (!binding.searchView.isVisible) { + model.unfilterLists() + } + } + + binding.searchViewText.addTextChangedListener { + model.searchLists(binding.searchViewText.text.toString()) + } + } + + private fun toggleSearchView(isVisible: Boolean) { + if (isVisible) { + binding.searchView.visibility = View.GONE + binding.searchViewText.text.clear() + } else { + binding.searchView.visibility = View.VISIBLE + binding.searchViewText.requestFocus() + val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager + imm.showSoftInput(binding.searchViewText, InputMethodManager.SHOW_IMPLICIT) + } } } diff --git a/app/src/main/java/ani/dantotsu/media/user/ListViewModel.kt b/app/src/main/java/ani/dantotsu/media/user/ListViewModel.kt index d415b432..d81bef7d 100644 --- a/app/src/main/java/ani/dantotsu/media/user/ListViewModel.kt +++ b/app/src/main/java/ani/dantotsu/media/user/ListViewModel.kt @@ -38,4 +38,30 @@ class ListViewModel : ViewModel() { lists.postValue(filteredLists) } + fun searchLists(search: String) { + if (search.isEmpty()) { + lists.postValue(unfilteredLists.value) + return + } + val currentLists = unfilteredLists.value ?: return + val filteredLists = currentLists.mapValues { entry -> + entry.value.filter { media -> + media.name?.contains( + search, + ignoreCase = true + ) == true || media.synonyms.any { it.contains(search, ignoreCase = true) } || + media.nameRomaji.contains( + search, + ignoreCase = true + ) + } as ArrayList + }.toMutableMap() + + lists.postValue(filteredLists) + } + + fun unfilterLists() { + lists.postValue(unfilteredLists.value) + } + } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/AlarmManagerScheduler.kt b/app/src/main/java/ani/dantotsu/notifications/AlarmManagerScheduler.kt index 2c729d0b..f5ed216c 100644 --- a/app/src/main/java/ani/dantotsu/notifications/AlarmManagerScheduler.kt +++ b/app/src/main/java/ani/dantotsu/notifications/AlarmManagerScheduler.kt @@ -5,9 +5,9 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build +import ani.dantotsu.notifications.TaskScheduler.TaskType import ani.dantotsu.notifications.anilist.AnilistNotificationReceiver import ani.dantotsu.notifications.comment.CommentNotificationReceiver -import ani.dantotsu.notifications.TaskScheduler.TaskType import ani.dantotsu.notifications.subscription.SubscriptionNotificationReceiver import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName @@ -15,7 +15,7 @@ import java.util.concurrent.TimeUnit class AlarmManagerScheduler(private val context: Context) : TaskScheduler { override fun scheduleRepeatingTask(taskType: TaskType, interval: Long) { - if (interval < TimeUnit.MINUTES.toMillis(15)) { + if (interval * 1000 < TimeUnit.MINUTES.toMillis(15)) { cancelTask(taskType) return } diff --git a/app/src/main/java/ani/dantotsu/notifications/BootCompletedReceiver.kt b/app/src/main/java/ani/dantotsu/notifications/BootCompletedReceiver.kt index 8cfc0a1c..66c1f294 100644 --- a/app/src/main/java/ani/dantotsu/notifications/BootCompletedReceiver.kt +++ b/app/src/main/java/ani/dantotsu/notifications/BootCompletedReceiver.kt @@ -5,9 +5,9 @@ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build +import ani.dantotsu.notifications.TaskScheduler.TaskType import ani.dantotsu.notifications.anilist.AnilistNotificationWorker import ani.dantotsu.notifications.comment.CommentNotificationWorker -import ani.dantotsu.notifications.TaskScheduler.TaskType import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.util.Logger diff --git a/app/src/main/java/ani/dantotsu/notifications/TaskScheduler.kt b/app/src/main/java/ani/dantotsu/notifications/TaskScheduler.kt index fa0304ed..af7362a7 100644 --- a/app/src/main/java/ani/dantotsu/notifications/TaskScheduler.kt +++ b/app/src/main/java/ani/dantotsu/notifications/TaskScheduler.kt @@ -21,11 +21,16 @@ interface TaskScheduler { for (taskType in TaskType.entries) { val interval = when (taskType) { TaskType.COMMENT_NOTIFICATION -> CommentNotificationWorker.checkIntervals[PrefManager.getVal( - PrefName.CommentNotificationInterval)] + PrefName.CommentNotificationInterval + )] + TaskType.ANILIST_NOTIFICATION -> AnilistNotificationWorker.checkIntervals[PrefManager.getVal( - PrefName.AnilistNotificationInterval)] + PrefName.AnilistNotificationInterval + )] + TaskType.SUBSCRIPTION_NOTIFICATION -> SubscriptionNotificationWorker.checkIntervals[PrefManager.getVal( - PrefName.SubscriptionNotificationInterval)] + PrefName.SubscriptionNotificationInterval + )] } scheduleRepeatingTask(taskType, interval) } @@ -39,7 +44,30 @@ interface TaskScheduler { WorkManagerScheduler(context) } } + + fun scheduleSingleWork(context: Context) { + val workManager = androidx.work.WorkManager.getInstance(context) + workManager.enqueueUniqueWork( + CommentNotificationWorker.WORK_NAME + "_single", + androidx.work.ExistingWorkPolicy.REPLACE, + androidx.work.OneTimeWorkRequest.Builder(CommentNotificationWorker::class.java) + .build() + ) + workManager.enqueueUniqueWork( + AnilistNotificationWorker.WORK_NAME + "_single", + androidx.work.ExistingWorkPolicy.REPLACE, + androidx.work.OneTimeWorkRequest.Builder(AnilistNotificationWorker::class.java) + .build() + ) + workManager.enqueueUniqueWork( + SubscriptionNotificationWorker.WORK_NAME + "_single", + androidx.work.ExistingWorkPolicy.REPLACE, + androidx.work.OneTimeWorkRequest.Builder(SubscriptionNotificationWorker::class.java) + .build() + ) + } } + enum class TaskType { COMMENT_NOTIFICATION, ANILIST_NOTIFICATION, diff --git a/app/src/main/java/ani/dantotsu/notifications/WorkManagerScheduler.kt b/app/src/main/java/ani/dantotsu/notifications/WorkManagerScheduler.kt index 422f5586..d66c0985 100644 --- a/app/src/main/java/ani/dantotsu/notifications/WorkManagerScheduler.kt +++ b/app/src/main/java/ani/dantotsu/notifications/WorkManagerScheduler.kt @@ -10,7 +10,7 @@ import ani.dantotsu.notifications.subscription.SubscriptionNotificationWorker class WorkManagerScheduler(private val context: Context) : TaskScheduler { override fun scheduleRepeatingTask(taskType: TaskType, interval: Long) { - if (interval < PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS) { + if (interval * 1000 < PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS) { cancelTask(taskType) return } diff --git a/app/src/main/java/ani/dantotsu/notifications/anilist/AnilistNotificationWorker.kt b/app/src/main/java/ani/dantotsu/notifications/anilist/AnilistNotificationWorker.kt index f3506fc8..4c5bf9b6 100644 --- a/app/src/main/java/ani/dantotsu/notifications/anilist/AnilistNotificationWorker.kt +++ b/app/src/main/java/ani/dantotsu/notifications/anilist/AnilistNotificationWorker.kt @@ -10,6 +10,11 @@ class AnilistNotificationWorker(appContext: Context, workerParams: WorkerParamet override suspend fun doWork(): Result { Logger.log("AnilistNotificationWorker: doWork") + if (System.currentTimeMillis() - lastCheck < 60000) { + Logger.log("AnilistNotificationWorker: doWork skipped") + return Result.success() + } + lastCheck = System.currentTimeMillis() return if (AnilistNotificationTask().execute(applicationContext)) { Result.success() } else { @@ -21,5 +26,6 @@ class AnilistNotificationWorker(appContext: Context, workerParams: WorkerParamet companion object { val checkIntervals = arrayOf(0L, 30, 60, 120, 240, 360, 720, 1440) const val WORK_NAME = "ani.dantotsu.notifications.anilist.AnilistNotificationWorker" + private var lastCheck = 0L } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationTask.kt b/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationTask.kt index ec6b2361..97cbcc0a 100644 --- a/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationTask.kt +++ b/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationTask.kt @@ -30,7 +30,7 @@ class CommentNotificationTask : Task { withContext(Dispatchers.IO) { PrefManager.init(context) //make sure prefs are initialized val client = OkHttpClient() - CommentsAPI.fetchAuthToken(client) + CommentsAPI.fetchAuthToken(context, client) val notificationResponse = CommentsAPI.getNotifications(client) var notifications = notificationResponse?.notifications?.toMutableList() //if we have at least one reply notification, we need to fetch the media titles @@ -46,26 +46,25 @@ class CommentNotificationTask : Task { ) notifications = - notifications?.filter { it.type != 3 || it.notificationId > recentGlobal } + notifications?.filter { !it.type.isGlobal() || it.notificationId > recentGlobal } ?.toMutableList() val newRecentGlobal = - notifications?.filter { it.type == 3 }?.maxOfOrNull { it.notificationId } + notifications?.filter { it.type.isGlobal() }?.maxOfOrNull { it.notificationId } if (newRecentGlobal != null) { PrefManager.setVal(PrefName.RecentGlobalNotification, newRecentGlobal) } if (notifications.isNullOrEmpty()) return@withContext PrefManager.setVal( PrefName.UnreadCommentNotifications, - PrefManager.getVal(PrefName.UnreadCommentNotifications) + (notifications.size - ?: 0) + PrefManager.getVal(PrefName.UnreadCommentNotifications) + (notifications.size) ) notifications.forEach { val type: CommentNotificationWorker.NotificationType = when (it.type) { 1 -> CommentNotificationWorker.NotificationType.COMMENT_REPLY 2 -> CommentNotificationWorker.NotificationType.COMMENT_WARNING - 3 -> CommentNotificationWorker.NotificationType.APP_GLOBAL + 3 -> CommentNotificationWorker.NotificationType.DANTOTSU_UPDATE 420 -> CommentNotificationWorker.NotificationType.NO_NOTIFICATION else -> CommentNotificationWorker.NotificationType.UNKNOWN } @@ -77,6 +76,7 @@ class CommentNotificationTask : Task { val commentStore = CommentStore( title, message, + CommentNotificationWorker.NotificationType.COMMENT_WARNING, it.mediaId, it.commentId ) @@ -102,6 +102,7 @@ class CommentNotificationTask : Task { val commentStore = CommentStore( title, message, + CommentNotificationWorker.NotificationType.COMMENT_REPLY, it.mediaId, it.commentId ) @@ -119,13 +120,14 @@ class CommentNotificationTask : Task { ) } - CommentNotificationWorker.NotificationType.APP_GLOBAL -> { + CommentNotificationWorker.NotificationType.DANTOTSU_UPDATE -> { val title = "Update from Dantotsu" val message = it.content ?: "New feature available" val commentStore = CommentStore( title, message, + CommentNotificationWorker.NotificationType.DANTOTSU_UPDATE, null, null ) @@ -133,7 +135,7 @@ class CommentNotificationTask : Task { createNotification( context, - CommentNotificationWorker.NotificationType.APP_GLOBAL, + CommentNotificationWorker.NotificationType.DANTOTSU_UPDATE, message, title, 0, @@ -186,7 +188,7 @@ class CommentNotificationTask : Task { null ) ?: listOf() val newStore = notificationStore.toMutableList() - if (newStore.size > 10) { + if (newStore.size > 30) { newStore.remove(newStore.minByOrNull { it.time }) } if (newStore.any { it.content == notification.content }) { @@ -266,7 +268,7 @@ class CommentNotificationTask : Task { builder.build() } - CommentNotificationWorker.NotificationType.APP_GLOBAL -> { + CommentNotificationWorker.NotificationType.DANTOTSU_UPDATE -> { val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } @@ -293,6 +295,7 @@ class CommentNotificationTask : Task { return notification } + @Suppress("unused") private fun getBitmapFromVectorDrawable(context: Context, drawableId: Int): Bitmap? { val drawable = ContextCompat.getDrawable(context, drawableId) ?: return null val bitmap = Bitmap.createBitmap( @@ -313,4 +316,6 @@ class CommentNotificationTask : Task { null } } + + private fun Int?.isGlobal() = this == 3 || this == 420 } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationWorker.kt b/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationWorker.kt index 47d61fd5..496d0f0e 100644 --- a/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationWorker.kt +++ b/app/src/main/java/ani/dantotsu/notifications/comment/CommentNotificationWorker.kt @@ -11,6 +11,11 @@ class CommentNotificationWorker(appContext: Context, workerParams: WorkerParamet CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Logger.log("CommentNotificationWorker: doWork") + if (System.currentTimeMillis() - lastCheck < 60000) { + Logger.log("CommentNotificationWorker: doWork skipped") + return Result.success() + } + lastCheck = System.currentTimeMillis() return if (CommentNotificationTask().execute(applicationContext)) { Result.success() } else { @@ -22,7 +27,7 @@ class CommentNotificationWorker(appContext: Context, workerParams: WorkerParamet enum class NotificationType(val id: String) { COMMENT_REPLY(Notifications.CHANNEL_COMMENTS), COMMENT_WARNING(Notifications.CHANNEL_COMMENT_WARING), - APP_GLOBAL(Notifications.CHANNEL_APP_GLOBAL), + DANTOTSU_UPDATE(Notifications.CHANNEL_APP_GLOBAL), NO_NOTIFICATION("no_notification"), UNKNOWN("unknown") } @@ -30,5 +35,6 @@ class CommentNotificationWorker(appContext: Context, workerParams: WorkerParamet companion object { val checkIntervals = arrayOf(0L, 480, 720, 1440) const val WORK_NAME = "ani.dantotsu.notifications.comment.CommentNotificationWorker" + private var lastCheck = 0L } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/comment/CommentStore.kt b/app/src/main/java/ani/dantotsu/notifications/comment/CommentStore.kt index bc6ab98b..e9381d45 100644 --- a/app/src/main/java/ani/dantotsu/notifications/comment/CommentStore.kt +++ b/app/src/main/java/ani/dantotsu/notifications/comment/CommentStore.kt @@ -3,18 +3,16 @@ package ani.dantotsu.notifications.comment import kotlinx.serialization.Serializable -@Suppress("INAPPROPRIATE_CONST_NAME") @Serializable data class CommentStore( val title: String, val content: String, + val type: CommentNotificationWorker.NotificationType, val mediaId: Int? = null, val commentId: Int? = null, val time: Long = System.currentTimeMillis(), ) : java.io.Serializable { companion object { - - @Suppress("INAPPROPRIATE_CONST_NAME") - private const val serialVersionUID = 1L + private const val serialVersionUID = 2L } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/comment/MediaNameFetch.kt b/app/src/main/java/ani/dantotsu/notifications/comment/MediaNameFetch.kt index 15e0e7e6..96e006bb 100644 --- a/app/src/main/java/ani/dantotsu/notifications/comment/MediaNameFetch.kt +++ b/app/src/main/java/ani/dantotsu/notifications/comment/MediaNameFetch.kt @@ -66,6 +66,7 @@ class MediaNameFetch { val type = object : TypeToken() {}.type return gson.fromJson(response, type) } + data class ReturnedData(val title: String, val coverImage: String, val color: String) data class MediaResponse(val data: Map) diff --git a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionHelper.kt b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionHelper.kt index 9c8498a4..e9156ed7 100644 --- a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionHelper.kt +++ b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionHelper.kt @@ -3,18 +3,20 @@ package ani.dantotsu.notifications.subscription import ani.dantotsu.R import ani.dantotsu.currContext import ani.dantotsu.media.Media +import ani.dantotsu.media.MediaNameAdapter import ani.dantotsu.media.Selected -import ani.dantotsu.media.manga.MangaNameAdapter +import ani.dantotsu.media.emptyMedia import ani.dantotsu.parsers.AnimeParser import ani.dantotsu.parsers.AnimeSources +import ani.dantotsu.parsers.BaseParser import ani.dantotsu.parsers.Episode -import ani.dantotsu.parsers.HAnimeSources -import ani.dantotsu.parsers.HMangaSources import ani.dantotsu.parsers.MangaChapter import ani.dantotsu.parsers.MangaParser import ani.dantotsu.parsers.MangaSources +import ani.dantotsu.parsers.ShowResponse import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName +import ani.dantotsu.toast import ani.dantotsu.tryWithSuspend import ani.dantotsu.util.Logger import kotlinx.coroutines.withTimeoutOrNull @@ -25,7 +27,7 @@ class SubscriptionHelper { mediaId: Int ): Selected { val data = - PrefManager.getNullableCustomVal("${mediaId}-select", null, Selected::class.java) + PrefManager.getNullableCustomVal("Selected-${mediaId}", null, Selected::class.java) ?: Selected().let { it.sourceIndex = 0 it.preferDub = PrefManager.getVal(PrefName.SettingsPreferDub) @@ -34,14 +36,17 @@ class SubscriptionHelper { return data } - private fun saveSelected( mediaId: Int, data: Selected) { - PrefManager.setCustomVal("${mediaId}-select", data) + private fun saveSelected(mediaId: Int, data: Selected) { + PrefManager.setCustomVal("Selected-${mediaId}", data) } fun getAnimeParser(id: Int): AnimeParser { val sources = AnimeSources Logger.log("getAnimeParser size: ${sources.list.size}") val selected = loadSelected(id) + if (selected.sourceIndex >= sources.list.size) { + selected.sourceIndex = 0 + } val parser = sources[selected.sourceIndex] parser.selectDub = selected.preferDub return parser @@ -49,16 +54,18 @@ class SubscriptionHelper { suspend fun getEpisode( parser: AnimeParser, - id: Int + subscribeMedia: SubscribeMedia ): Episode? { - val selected = loadSelected(id) + val selected = loadSelected(subscribeMedia.id) val ep = withTimeoutOrNull(10 * 1000) { tryWithSuspend { - val show = parser.loadSavedShowResponse(id) ?: throw Exception( + val show = parser.loadSavedShowResponse(subscribeMedia.id) + ?: forceLoadShowResponse(subscribeMedia, selected, parser) + ?: throw Exception( currContext()?.getString( R.string.failed_to_load_data, - id + subscribeMedia.id ) ) show.sAnime?.let { @@ -72,27 +79,33 @@ class SubscriptionHelper { return ep?.apply { selected.latest = number.toFloat() - saveSelected(id, selected) + saveSelected(subscribeMedia.id, selected) } } fun getMangaParser(id: Int): MangaParser { val sources = MangaSources + Logger.log("getMangaParser size: ${sources.list.size}") val selected = loadSelected(id) + if (selected.sourceIndex >= sources.list.size) { + selected.sourceIndex = 0 + } return sources[selected.sourceIndex] } suspend fun getChapter( parser: MangaParser, - id: Int + subscribeMedia: SubscribeMedia ): MangaChapter? { - val selected = loadSelected(id) + val selected = loadSelected(subscribeMedia.id) val chp = withTimeoutOrNull(10 * 1000) { tryWithSuspend { - val show = parser.loadSavedShowResponse(id) ?: throw Exception( + val show = parser.loadSavedShowResponse(subscribeMedia.id) + ?: forceLoadShowResponse(subscribeMedia, selected, parser) + ?: throw Exception( currContext()?.getString( R.string.failed_to_load_data, - id + subscribeMedia.id ) ) show.sManga?.let { @@ -105,18 +118,41 @@ class SubscriptionHelper { } return chp?.apply { - selected.latest = MangaNameAdapter.findChapterNumber(number) ?: 0f - saveSelected(id, selected) + selected.latest = MediaNameAdapter.findChapterNumber(number) ?: 0f + saveSelected(subscribeMedia.id, selected) } } + private suspend fun forceLoadShowResponse(subscribeMedia: SubscribeMedia, selected: Selected, parser: BaseParser): ShowResponse? { + val tempMedia = Media( + id = subscribeMedia.id, + name = null, + nameRomaji = subscribeMedia.name, + userPreferredName = subscribeMedia.name, + isAdult = subscribeMedia.isAdult, + isFav = false, + isListPrivate = false, + userScore = 0, + userRepeat = 0, + format = null, + selected = selected + ) + parser.autoSearch(tempMedia) + return parser.loadSavedShowResponse(subscribeMedia.id) + } + data class SubscribeMedia( val isAnime: Boolean, val isAdult: Boolean, val id: Int, val name: String, - val image: String? - ) : java.io.Serializable + val image: String?, + val banner: String? = null + ) : java.io.Serializable { + companion object { + private const val serialVersionUID = 1L + } + } private const val SUBSCRIPTIONS = "subscriptions" @@ -129,6 +165,19 @@ class SubscriptionHelper { ) as? Map) ?: mapOf().also { PrefManager.setCustomVal(SUBSCRIPTIONS, it) } + @Suppress("UNCHECKED_CAST") + fun deleteSubscription(id: Int, showSnack: Boolean = false) { + val data = PrefManager.getNullableCustomVal( + SUBSCRIPTIONS, + null, + Map::class.java + ) as? MutableMap + ?: mutableMapOf() + data.remove(id) + PrefManager.setCustomVal(SUBSCRIPTIONS, data) + if (showSnack) toast(R.string.subscription_deleted) + } + @Suppress("UNCHECKED_CAST") fun saveSubscription(media: Media, subscribed: Boolean) { val data = PrefManager.getNullableCustomVal( @@ -144,7 +193,8 @@ class SubscriptionHelper { media.isAdult, media.id, media.userPreferredName, - media.cover + media.cover, + media.banner ) data[media.id] = new } diff --git a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationTask.kt b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationTask.kt index ecbf6bd2..6fc8fb59 100644 --- a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationTask.kt +++ b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationTask.kt @@ -98,7 +98,7 @@ class SubscriptionNotificationTask : Task { val ep: Episode? = SubscriptionHelper.getEpisode( parser, - media.id + media ) if (ep != null) context.getString(R.string.episode) + "${ep.number}${ if (ep.title != null) " : ${ep.title}" else "" @@ -113,11 +113,22 @@ class SubscriptionNotificationTask : Task { val ep: MangaChapter? = SubscriptionHelper.getChapter( parser, - media.id + media ) if (ep != null) ep.number + " " + context.getString(R.string.just_released) to null else null } ?: return@map + addSubscriptionToStore( + SubscriptionStore( + media.name, + text.first, + media.id, + image = media.image, + banner = media.banner + ) + ) + PrefManager.setVal(PrefName.UnreadCommentNotifications, + PrefManager.getVal(PrefName.UnreadCommentNotifications) + 1) val notification = createNotification( context.applicationContext, media, @@ -185,7 +196,7 @@ class SubscriptionNotificationTask : Task { size: Int ): NotificationCompat.Builder { return NotificationCompat.Builder(context, CHANNEL_SUBSCRIPTION_CHECK_PROGRESS) - .setPriority(NotificationCompat.PRIORITY_LOW) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(context.getString(R.string.checking_subscriptions_title)) .setProgress(size, 0, false) @@ -219,4 +230,21 @@ class SubscriptionNotificationTask : Task { } ) } + + private fun addSubscriptionToStore(notification: SubscriptionStore) { + val notificationStore = PrefManager.getNullableVal>( + PrefName.SubscriptionNotificationStore, + null + ) ?: listOf() + val newStore = notificationStore.toMutableList() + if (newStore.size >= 100) { + newStore.remove(newStore.minByOrNull { it.time }) + } + if (newStore.any { it.title == notification.title && it.content == notification.content}) { + return + } + + newStore.add(notification) + PrefManager.setVal(PrefName.SubscriptionNotificationStore, newStore) + } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationWorker.kt b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationWorker.kt index 22086b3b..72092fce 100644 --- a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationWorker.kt +++ b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionNotificationWorker.kt @@ -3,7 +3,6 @@ package ani.dantotsu.notifications.subscription import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import ani.dantotsu.notifications.anilist.AnilistNotificationTask import ani.dantotsu.util.Logger class SubscriptionNotificationWorker(appContext: Context, workerParams: WorkerParameters) : @@ -11,7 +10,12 @@ class SubscriptionNotificationWorker(appContext: Context, workerParams: WorkerPa override suspend fun doWork(): Result { Logger.log("SubscriptionNotificationWorker: doWork") - return if (AnilistNotificationTask().execute(applicationContext)) { + if (System.currentTimeMillis() - lastCheck < 60000) { + Logger.log("SubscriptionNotificationWorker: doWork skipped") + return Result.success() + } + lastCheck = System.currentTimeMillis() + return if (SubscriptionNotificationTask().execute(applicationContext)) { Result.success() } else { Logger.log("SubscriptionNotificationWorker: doWork failed") @@ -23,5 +27,6 @@ class SubscriptionNotificationWorker(appContext: Context, workerParams: WorkerPa val checkIntervals = arrayOf(0L, 480, 720, 1440) const val WORK_NAME = "ani.dantotsu.notifications.subscription.SubscriptionNotificationWorker" + private var lastCheck = 0L } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionStore.kt b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionStore.kt new file mode 100644 index 00000000..381f2f75 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/notifications/subscription/SubscriptionStore.kt @@ -0,0 +1,18 @@ +package ani.dantotsu.notifications.subscription + +import kotlinx.serialization.Serializable + +@Serializable +data class SubscriptionStore( + val title: String, + val content: String, + val mediaId: Int, + val type: String = "SUBSCRIPTION", + val time: Long = System.currentTimeMillis(), + val image: String? = "", + val banner: String? = "", +) : java.io.Serializable { + companion object { + private const val serialVersionUID = 1L + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/offline/OfflineFragment.kt b/app/src/main/java/ani/dantotsu/offline/OfflineFragment.kt index 5807cb48..4702130c 100644 --- a/app/src/main/java/ani/dantotsu/offline/OfflineFragment.kt +++ b/app/src/main/java/ani/dantotsu/offline/OfflineFragment.kt @@ -4,6 +4,7 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.fragment.app.Fragment import ani.dantotsu.R @@ -30,10 +31,15 @@ class OfflineFragment : Fragment() { offline = PrefManager.getVal(PrefName.OfflineMode) binding.noInternet.text = if (offline) "Offline Mode" else getString(R.string.no_internet) - binding.refreshButton.visibility = if (offline) View.GONE else View.VISIBLE + binding.refreshButton.text = if (offline) "Go Online" else getString(R.string.refresh) binding.refreshButton.setOnClickListener { - if (isOnline(requireContext())) { + if (offline && isOnline(requireContext())) { + PrefManager.setVal(PrefName.OfflineMode, false) startMainActivity(requireActivity()) + } else { + if (isOnline(requireContext()) ) { + startMainActivity(requireActivity()) + } } } return binding.root diff --git a/app/src/main/java/ani/dantotsu/others/AndroidBug5497Workaround.kt b/app/src/main/java/ani/dantotsu/others/AndroidBug5497Workaround.kt index 46e8a297..dbe4e7d7 100644 --- a/app/src/main/java/ani/dantotsu/others/AndroidBug5497Workaround.kt +++ b/app/src/main/java/ani/dantotsu/others/AndroidBug5497Workaround.kt @@ -5,13 +5,16 @@ import android.graphics.Rect import android.view.View import android.widget.FrameLayout -class AndroidBug5497Workaround private constructor(activity: Activity, private val callback: (Boolean) -> Unit) { +class AndroidBug5497Workaround private constructor( + activity: Activity, + private val callback: (Boolean) -> Unit +) { private val mChildOfContent: View private var usableHeightPrevious = 0 private val frameLayoutParams: FrameLayout.LayoutParams init { - val content = activity.findViewById(android.R.id.content) as FrameLayout + val content: FrameLayout = activity.findViewById(android.R.id.content) mChildOfContent = content.getChildAt(0) mChildOfContent.viewTreeObserver.addOnGlobalLayoutListener { possiblyResizeChildOfContent() } frameLayoutParams = mChildOfContent.layoutParams as FrameLayout.LayoutParams @@ -42,9 +45,15 @@ class AndroidBug5497Workaround private constructor(activity: Activity, private v return r.bottom } + /** + * Fixes windowSoftInputMode adjustResize when used with setDecorFitsSystemWindows(false) + * + * @see adjustResize breaks when activity is fullscreen + */ companion object { - // For more information, see https://issuetracker.google.com/issues/36911528 - // To use this class, simply invoke assistActivity() on an Activity that already has its content view set. + /** + * Called on an Activity after the content view has been set. + */ fun assistActivity(activity: Activity, callback: (Boolean) -> Unit) { AndroidBug5497Workaround(activity, callback) } diff --git a/app/src/main/java/ani/dantotsu/others/CrashActivity.kt b/app/src/main/java/ani/dantotsu/others/CrashActivity.kt new file mode 100644 index 00000000..d3b5e754 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/others/CrashActivity.kt @@ -0,0 +1,59 @@ +package ani.dantotsu.others + +import android.content.Intent +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.FileProvider +import androidx.core.view.updateLayoutParams +import ani.dantotsu.R +import ani.dantotsu.databinding.ActivityCrashBinding +import ani.dantotsu.initActivity +import ani.dantotsu.navBarHeight +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import eu.kanade.tachiyomi.util.system.copyToClipboard +import java.io.File + + +class CrashActivity : AppCompatActivity() { + private lateinit var binding: ActivityCrashBinding + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + initActivity(this) + binding = ActivityCrashBinding.inflate(layoutInflater) + + setContentView(binding.root) + binding.root.updateLayoutParams { + topMargin = statusBarHeight + bottomMargin = navBarHeight + } + val stackTrace = intent.getStringExtra("stackTrace") ?: "No stack trace available" + + binding.crashReportView.setText(stackTrace) + binding.crashReportView.setOnKeyListener(View.OnKeyListener { _, _, _ -> + true // Blocks input from hardware keyboards. + }) + + binding.copyButton.setOnClickListener { + copyToClipboard("Crash log", stackTrace) + } + + binding.shareAsTextFileButton.setOnClickListener { + shareAsTextFile(stackTrace) + } + } + + private fun shareAsTextFile(stackTrace: String) { + val file = File(cacheDir, "crash_log.txt") + file.writeText(stackTrace) + val uri = FileProvider.getUriForFile(this, "${packageName}.provider", file) + val intent = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_STREAM, uri) + } + startActivity(Intent.createChooser(intent, getString(R.string.share))) + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/others/Download.kt b/app/src/main/java/ani/dantotsu/others/Download.kt index 3a266af4..c25c12aa 100644 --- a/app/src/main/java/ani/dantotsu/others/Download.kt +++ b/app/src/main/java/ani/dantotsu/others/Download.kt @@ -1,6 +1,5 @@ package ani.dantotsu.others -import android.app.DownloadManager import android.content.ComponentName import android.content.Context import android.content.Intent @@ -8,7 +7,6 @@ import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.os.Environment -import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import ani.dantotsu.FileUrl import ani.dantotsu.R @@ -19,9 +17,6 @@ import ani.dantotsu.parsers.Book import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.toast -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch import java.io.File object Download { @@ -36,16 +31,8 @@ object Download { } private fun getDownloadDir(context: Context): File { - val direct: File - if (PrefManager.getVal(PrefName.SdDl)) { - val arrayOfFiles = ContextCompat.getExternalFilesDirs(context, null) - val parentDirectory = arrayOfFiles[1].toString() - direct = File(parentDirectory) - if (!direct.exists()) direct.mkdirs() - } else { - direct = File("storage/emulated/0/${Environment.DIRECTORY_DOWNLOADS}/Dantotsu/") - if (!direct.exists()) direct.mkdirs() - } + val direct = File("storage/emulated/0/${Environment.DIRECTORY_DOWNLOADS}/Dantotsu/") + if (!direct.exists()) direct.mkdirs() return direct } @@ -96,52 +83,10 @@ object Download { when (PrefManager.getVal(PrefName.DownloadManager) as Int) { 1 -> oneDM(context, file, notif ?: fileName) 2 -> adm(context, file, fileName, folder) - else -> defaultDownload(context, file, fileName, folder, notif ?: fileName) + else -> oneDM(context, file, notif ?: fileName) } } - private fun defaultDownload( - context: Context, - file: FileUrl, - fileName: String, - folder: String, - notif: String - ) { - val manager = - context.getSystemService(AppCompatActivity.DOWNLOAD_SERVICE) as DownloadManager - val request: DownloadManager.Request = DownloadManager.Request(Uri.parse(file.url)) - file.headers.forEach { - request.addRequestHeader(it.key, it.value) - } - CoroutineScope(Dispatchers.IO).launch { - try { - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) - - val arrayOfFiles = ContextCompat.getExternalFilesDirs(context, null) - if (PrefManager.getVal(PrefName.SdDl) && arrayOfFiles.size > 1 && arrayOfFiles[0] != null && arrayOfFiles[1] != null) { - val parentDirectory = arrayOfFiles[1].toString() + folder - val direct = File(parentDirectory) - if (!direct.exists()) direct.mkdirs() - request.setDestinationUri(Uri.fromFile(File("$parentDirectory$fileName"))) - } else { - val direct = File(Environment.DIRECTORY_DOWNLOADS + "/Dantotsu$folder") - if (!direct.exists()) direct.mkdirs() - request.setDestinationInExternalPublicDir( - Environment.DIRECTORY_DOWNLOADS, - "/Dantotsu$folder$fileName" - ) - } - request.setTitle(notif) - manager.enqueue(request) - toast(currContext()?.getString(R.string.started_downloading, notif)) - } catch (e: SecurityException) { - toast(currContext()?.getString(R.string.permission_required)) - } catch (e: Exception) { - toast(e.toString()) - } - } - } - private fun oneDM(context: Context, file: FileUrl, notif: String) { val appName = if (isPackageInstalled("idm.internet.download.manager.plus", context.packageManager)) { diff --git a/app/src/main/java/ani/dantotsu/others/ImageViewDialog.kt b/app/src/main/java/ani/dantotsu/others/ImageViewDialog.kt index e11715c7..e721e84d 100644 --- a/app/src/main/java/ani/dantotsu/others/ImageViewDialog.kt +++ b/app/src/main/java/ani/dantotsu/others/ImageViewDialog.kt @@ -12,9 +12,8 @@ import ani.dantotsu.BottomSheetDialogFragment import ani.dantotsu.FileUrl import ani.dantotsu.R import ani.dantotsu.databinding.BottomSheetImageBinding -import ani.dantotsu.downloadsPermission import ani.dantotsu.media.manga.mangareader.BaseImageAdapter.Companion.loadBitmap -import ani.dantotsu.media.manga.mangareader.BaseImageAdapter.Companion.loadBitmap_old +import ani.dantotsu.media.manga.mangareader.BaseImageAdapter.Companion.loadBitmapOld import ani.dantotsu.media.manga.mangareader.BaseImageAdapter.Companion.mergeBitmap import ani.dantotsu.openLinkInBrowser import ani.dantotsu.saveImageToDownloads @@ -22,6 +21,7 @@ import ani.dantotsu.setSafeOnClickListener import ani.dantotsu.shareImage import ani.dantotsu.snackString import ani.dantotsu.toast +import ani.dantotsu.util.StoragePermissions.Companion.downloadsPermission import com.bumptech.glide.load.resource.bitmap.BitmapTransformation import com.davemorrissey.labs.subscaleview.ImageSource import kotlinx.coroutines.launch @@ -84,9 +84,9 @@ class ImageViewDialog : BottomSheetDialogFragment() { viewLifecycleOwner.lifecycleScope.launch { val binding = _binding ?: return@launch - var bitmap = context.loadBitmap_old(image, trans1 ?: listOf()) + var bitmap = context.loadBitmapOld(image, trans1 ?: listOf()) var bitmap2 = - if (image2 != null) context.loadBitmap_old(image2, trans2 ?: listOf()) else null + if (image2 != null) context.loadBitmapOld(image2, trans2 ?: listOf()) else null if (bitmap == null) { bitmap = context.loadBitmap(image, trans1 ?: listOf()) bitmap2 = diff --git a/app/src/main/java/ani/dantotsu/others/Kitsu.kt b/app/src/main/java/ani/dantotsu/others/Kitsu.kt index f548fc31..958c1b46 100644 --- a/app/src/main/java/ani/dantotsu/others/Kitsu.kt +++ b/app/src/main/java/ani/dantotsu/others/Kitsu.kt @@ -2,10 +2,10 @@ package ani.dantotsu.others import ani.dantotsu.FileUrl import ani.dantotsu.client -import ani.dantotsu.util.Logger import ani.dantotsu.media.Media import ani.dantotsu.media.anime.Episode import ani.dantotsu.tryWithSuspend +import ani.dantotsu.util.Logger import com.google.gson.Gson import com.lagradost.nicehttp.NiceResponse import kotlinx.serialization.SerialName diff --git a/app/src/main/java/ani/dantotsu/others/LanguageMapper.kt b/app/src/main/java/ani/dantotsu/others/LanguageMapper.kt index 3d9c439b..b12cc633 100644 --- a/app/src/main/java/ani/dantotsu/others/LanguageMapper.kt +++ b/app/src/main/java/ani/dantotsu/others/LanguageMapper.kt @@ -1,124 +1,149 @@ package ani.dantotsu.others +import java.util.Locale + class LanguageMapper { companion object { - fun mapLanguageCodeToName(code: String): String { - return when (code) { - "all" -> "Multi" - "af" -> "Afrikaans" - "am" -> "Amharic" - "ar" -> "Arabic" - "as" -> "Assamese" - "az" -> "Azerbaijani" - "be" -> "Belarusian" - "bg" -> "Bulgarian" - "bn" -> "Bengali" - "bs" -> "Bosnian" - "ca" -> "Catalan" - "ceb" -> "Cebuano" - "cs" -> "Czech" - "da" -> "Danish" - "de" -> "German" - "el" -> "Greek" - "en" -> "English" - "en-Us" -> "English (United States)" - "eo" -> "Esperanto" - "es" -> "Spanish" - "es-419" -> "Spanish (Latin America)" - "et" -> "Estonian" - "eu" -> "Basque" - "fa" -> "Persian" - "fi" -> "Finnish" - "fil" -> "Filipino" - "fo" -> "Faroese" - "fr" -> "French" - "ga" -> "Irish" - "gn" -> "Guarani" - "gu" -> "Gujarati" - "ha" -> "Hausa" - "he" -> "Hebrew" - "hi" -> "Hindi" - "hr" -> "Croatian" - "ht" -> "Haitian Creole" - "hu" -> "Hungarian" - "hy" -> "Armenian" - "id" -> "Indonesian" - "ig" -> "Igbo" - "is" -> "Icelandic" - "it" -> "Italian" - "ja" -> "Japanese" - "jv" -> "Javanese" - "ka" -> "Georgian" - "kk" -> "Kazakh" - "km" -> "Khmer" - "kn" -> "Kannada" - "ko" -> "Korean" - "ku" -> "Kurdish" - "ky" -> "Kyrgyz" - "la" -> "Latin" - "lb" -> "Luxembourgish" - "lo" -> "Lao" - "lt" -> "Lithuanian" - "lv" -> "Latvian" - "mg" -> "Malagasy" - "mi" -> "Maori" - "mk" -> "Macedonian" - "ml" -> "Malayalam" - "mn" -> "Mongolian" - "mo" -> "Moldovan" - "mr" -> "Marathi" - "ms" -> "Malay" - "mt" -> "Maltese" - "my" -> "Burmese" - "ne" -> "Nepali" - "nl" -> "Dutch" - "no" -> "Norwegian" - "ny" -> "Chichewa" - "pl" -> "Polish" - "pt" -> "Portuguese" - "pt-BR" -> "Portuguese (Brazil)" - "pt-PT" -> "Portuguese (Portugal)" - "ps" -> "Pashto" - "ro" -> "Romanian" - "rm" -> "Romansh" - "ru" -> "Russian" - "sd" -> "Sindhi" - "sh" -> "Serbo-Croatian" - "si" -> "Sinhala" - "sk" -> "Slovak" - "sl" -> "Slovenian" - "sm" -> "Samoan" - "sn" -> "Shona" - "so" -> "Somali" - "sq" -> "Albanian" - "sr" -> "Serbian" - "st" -> "Southern Sotho" - "sv" -> "Swedish" - "sw" -> "Swahili" - "ta" -> "Tamil" - "te" -> "Telugu" - "tg" -> "Tajik" - "th" -> "Thai" - "ti" -> "Tigrinya" - "tk" -> "Turkmen" - "tl" -> "Tagalog" - "to" -> "Tongan" - "tr" -> "Turkish" - "uk" -> "Ukrainian" - "ur" -> "Urdu" - "uz" -> "Uzbek" - "vi" -> "Vietnamese" - "yo" -> "Yoruba" - "zh" -> "Chinese" - "zh-Hans" -> "Chinese (Simplified)" - "zh-Hant" -> "Chinese (Traditional)" - "zh-Habt" -> "Chinese (Hakka)" - "zu" -> "Zulu" - else -> code + private val codeMap: Map = mapOf( + "all" to "Multi", + "af" to "Afrikaans", + "am" to "Amharic", + "ar" to "Arabic", + "as" to "Assamese", + "az" to "Azerbaijani", + "be" to "Belarusian", + "bg" to "Bulgarian", + "bn" to "Bengali", + "bs" to "Bosnian", + "ca" to "Catalan", + "ceb" to "Cebuano", + "cs" to "Czech", + "da" to "Danish", + "de" to "German", + "el" to "Greek", + "en" to "English", + "en-Us" to "English (United States)", + "eo" to "Esperanto", + "es" to "Spanish", + "es-419" to "Spanish (Latin America)", + "es-ES" to "Spanish (Spain)", + "et" to "Estonian", + "eu" to "Basque", + "fa" to "Persian", + "fi" to "Finnish", + "fil" to "Filipino", + "fo" to "Faroese", + "fr" to "French", + "ga" to "Irish", + "gn" to "Guarani", + "gu" to "Gujarati", + "ha" to "Hausa", + "he" to "Hebrew", + "hi" to "Hindi", + "hr" to "Croatian", + "ht" to "Haitian Creole", + "hu" to "Hungarian", + "hy" to "Armenian", + "id" to "Indonesian", + "ig" to "Igbo", + "is" to "Icelandic", + "it" to "Italian", + "ja" to "Japanese", + "jv" to "Javanese", + "ka" to "Georgian", + "kk" to "Kazakh", + "km" to "Khmer", + "kn" to "Kannada", + "ko" to "Korean", + "ku" to "Kurdish", + "ky" to "Kyrgyz", + "la" to "Latin", + "lb" to "Luxembourgish", + "lo" to "Lao", + "lt" to "Lithuanian", + "lv" to "Latvian", + "mg" to "Malagasy", + "mi" to "Maori", + "mk" to "Macedonian", + "ml" to "Malayalam", + "mn" to "Mongolian", + "mo" to "Moldovan", + "mr" to "Marathi", + "ms" to "Malay", + "mt" to "Maltese", + "my" to "Burmese", + "ne" to "Nepali", + "nl" to "Dutch", + "no" to "Norwegian", + "ny" to "Chichewa", + "pl" to "Polish", + "pt" to "Portuguese", + "pt-BR" to "Portuguese (Brazil)", + "pt-PT" to "Portuguese (Portugal)", + "ps" to "Pashto", + "ro" to "Romanian", + "rm" to "Romansh", + "ru" to "Russian", + "sd" to "Sindhi", + "sh" to "Serbo-Croatian", + "si" to "Sinhala", + "sk" to "Slovak", + "sl" to "Slovenian", + "sm" to "Samoan", + "sn" to "Shona", + "so" to "Somali", + "sq" to "Albanian", + "sr" to "Serbian", + "st" to "Southern Sotho", + "sv" to "Swedish", + "sw" to "Swahili", + "ta" to "Tamil", + "te" to "Telugu", + "tg" to "Tajik", + "th" to "Thai", + "ti" to "Tigrinya", + "tk" to "Turkmen", + "tl" to "Tagalog", + "to" to "Tongan", + "tr" to "Turkish", + "uk" to "Ukrainian", + "ur" to "Urdu", + "uz" to "Uzbek", + "vi" to "Vietnamese", + "yo" to "Yoruba", + "zh" to "Chinese", + "zh-Hans" to "Chinese (Simplified)", + "zh-Hant" to "Chinese (Traditional)", + "zh-Habt" to "Chinese (Hakka)", + "zu" to "Zulu" + ) + + fun getLanguageName(code: String): String { + return if (code.contains("-")) { + try { + val parts = code.split("-") + Locale(parts[0], parts[1]).displayName + } catch (ignored: Exception) { + code + } + } else { + try { + if (code == "all") { + return codeMap[code] ?: code + } + Locale(code).displayName + } catch (ignored: Exception) { + code + } } } + fun getLanguageCode(language: String): String { + return codeMap.filterValues { it.lowercase() == language.lowercase() }.keys.firstOrNull() + ?: "all" + } + enum class Language(val code: String) { ALL("all"), ARABIC("ar"), diff --git a/app/src/main/java/ani/dantotsu/others/OutlineTextView.kt b/app/src/main/java/ani/dantotsu/others/OutlineTextView.kt index e2c17cc0..105f34a7 100644 --- a/app/src/main/java/ani/dantotsu/others/OutlineTextView.kt +++ b/app/src/main/java/ani/dantotsu/others/OutlineTextView.kt @@ -1,9 +1,11 @@ package ani.dantotsu.others import android.content.Context +import android.content.res.Resources import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet +import android.util.TypedValue import androidx.appcompat.widget.AppCompatTextView import ani.dantotsu.R @@ -54,14 +56,15 @@ class OutlineTextView : AppCompatTextView { setStrokeWidth(strokeWidth) } + private val Float.toPx + get() = TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics + ) private fun setStrokeWidth(width: Float) { - strokeWidth = width.toPx(context) + strokeWidth = width.toPx } - private fun Float.toPx(context: Context) = - (this * context.resources.displayMetrics.scaledDensity + 0.5F) - override fun invalidate() { if (isDrawing) return super.invalidate() diff --git a/app/src/main/java/ani/dantotsu/others/SpoilerPlugin.kt b/app/src/main/java/ani/dantotsu/others/SpoilerPlugin.kt index 79b6138a..8cb584d6 100644 --- a/app/src/main/java/ani/dantotsu/others/SpoilerPlugin.kt +++ b/app/src/main/java/ani/dantotsu/others/SpoilerPlugin.kt @@ -12,9 +12,13 @@ import io.noties.markwon.AbstractMarkwonPlugin import io.noties.markwon.utils.ColorUtils import java.util.regex.Pattern -class SpoilerPlugin : AbstractMarkwonPlugin() { +class SpoilerPlugin(private val anilist: Boolean = false) : AbstractMarkwonPlugin() { override fun beforeSetText(textView: TextView, markdown: Spanned) { - applySpoilerSpans(markdown as Spannable) + if (anilist) { + applySpoilerSpans(markdown as Spannable, ARE) + } else { + applySpoilerSpans(markdown as Spannable) + } } private class RedditSpoilerSpan : CharacterStyle() { @@ -45,9 +49,10 @@ class SpoilerPlugin : AbstractMarkwonPlugin() { companion object { private val RE = Pattern.compile("\\|\\|.+?\\|\\|") - private fun applySpoilerSpans(spannable: Spannable) { + private val ARE = Pattern.compile("~!.+?!~") + private fun applySpoilerSpans(spannable: Spannable, regex: Pattern = RE) { val text = spannable.toString() - val matcher = RE.matcher(text) + val matcher = regex.matcher(text) while (matcher.find()) { val spoilerSpan = RedditSpoilerSpan() val clickableSpan: ClickableSpan = object : ClickableSpan() { diff --git a/app/src/main/java/ani/dantotsu/others/Xpandable.kt b/app/src/main/java/ani/dantotsu/others/Xpandable.kt index 527380ef..1c4fe3bf 100644 --- a/app/src/main/java/ani/dantotsu/others/Xpandable.kt +++ b/app/src/main/java/ani/dantotsu/others/Xpandable.kt @@ -12,7 +12,8 @@ import ani.dantotsu.R class Xpandable @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : LinearLayout(context, attrs) { - var expanded: Boolean = false + private var expanded: Boolean = false + private var listeners: ArrayList = arrayListOf() init { context.withStyledAttributes(attrs, R.styleable.Xpandable) { @@ -37,7 +38,6 @@ class Xpandable @JvmOverloads constructor( super.onAttachedToWindow() } - private fun hideAll() { children.forEach { if (it != getChildAt(0)) { @@ -48,8 +48,12 @@ class Xpandable @JvmOverloads constructor( it.visibility = GONE }, 300) } - } + postDelayed({ + listeners.forEach { + it.onRetract() + } + }, 300) } private fun showAll() { @@ -61,6 +65,25 @@ class Xpandable @JvmOverloads constructor( ObjectAnimator.ofFloat(it, "alpha", 0f, 1f).setDuration(200).start() } } + postDelayed({ + listeners.forEach { + it.onExpand() + } + }, 300) + } + + @Suppress("unused") + fun addOnChangeListener(listener: OnChangeListener) { + listeners.add(listener) + } + + fun removeListener(listener: OnChangeListener) { + listeners.remove(listener) + } + + interface OnChangeListener { + fun onExpand() + fun onRetract() } } \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/others/calc/CalcActivity.kt b/app/src/main/java/ani/dantotsu/others/calc/CalcActivity.kt new file mode 100644 index 00000000..442ab396 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/others/calc/CalcActivity.kt @@ -0,0 +1,125 @@ +package ani.dantotsu.others.calc + +import android.content.Intent +import android.os.Bundle +import android.text.Spannable +import android.text.SpannableString +import android.text.style.ForegroundColorSpan +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.doOnAttach +import androidx.core.view.updateLayoutParams +import ani.dantotsu.MainActivity +import ani.dantotsu.R +import ani.dantotsu.databinding.ActivityCalcBinding +import ani.dantotsu.getThemeColor +import ani.dantotsu.initActivity +import ani.dantotsu.navBarHeight +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.util.NumberConverter.Companion.toBinary +import ani.dantotsu.util.NumberConverter.Companion.toHex + +class CalcActivity : AppCompatActivity() { + private lateinit var binding: ActivityCalcBinding + private lateinit var code: String + private val stack = CalcStack() + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + binding = ActivityCalcBinding.inflate(layoutInflater) + setContentView(binding.root) + binding.root.doOnAttach { + initActivity(this) + binding.displayContainer.updateLayoutParams { + topMargin += statusBarHeight + } + binding.buttonContainer.updateLayoutParams { + bottomMargin += navBarHeight + } + } + code = intent.getStringExtra("code") ?: "0" + + binding.apply { + button0.setOnClickListener { stack.add('0'); updateDisplay() } + button1.setOnClickListener { stack.add('1'); updateDisplay() } + button2.setOnClickListener { stack.add('2'); updateDisplay() } + button3.setOnClickListener { stack.add('3'); updateDisplay() } + button4.setOnClickListener { stack.add('4'); updateDisplay() } + button5.setOnClickListener { stack.add('5'); updateDisplay() } + button6.setOnClickListener { stack.add('6'); updateDisplay() } + button7.setOnClickListener { stack.add('7'); updateDisplay() } + button8.setOnClickListener { stack.add('8'); updateDisplay() } + button9.setOnClickListener { stack.add('9'); updateDisplay() } + buttonDot.setOnClickListener { stack.add('.'); updateDisplay() } + buttonAdd.setOnClickListener { stack.add('+'); updateDisplay() } + buttonSubtract.setOnClickListener { stack.add('-'); updateDisplay() } + buttonMultiply.setOnClickListener { stack.add('*'); updateDisplay() } + buttonDivide.setOnClickListener { stack.add('/'); updateDisplay() } + buttonEquals.setOnClickListener { + try { + val ans = stack.evaluate() + updateDisplay() + binding.displayBinary.text = ans.toBinary() + binding.displayHex.text = ans.toHex() + } catch (e: Exception) { + display.text = getString(R.string.error) + } + } + buttonClear.setOnClickListener { + stack.clear() + binding.displayBinary.text = "" + binding.displayHex.text = "" + binding.display.text = "0" + } + buttonBackspace.setOnClickListener { + stack.remove() + updateDisplay() + } + display.text = "0" + } + } + + private fun success() { + hasPermission = true + ContextCompat.startActivity( + this, + Intent(this, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK), + null + ) + } + + private fun updateDisplay() { + if (stack.getExpression().isEmpty()) { + binding.display.text = "0" + return + } + val expression = stack.getExpression().replace("*", "×").replace("/", "÷") + val spannable = SpannableString(expression) + + val operators = arrayOf('+', '-', '×', '÷') + + expression.forEachIndexed { index, char -> + if (char in operators) { + val color = getThemeColor(com.google.android.material.R.attr.colorSecondary) + spannable.setSpan( + ForegroundColorSpan(color), + index, + index + 1, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + ) + } + } + binding.display.text = spannable + val text = binding.display.text.toString() + if (text == code) { + success() + } + } + + companion object { + var hasPermission = false + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/others/calc/CalcStack.kt b/app/src/main/java/ani/dantotsu/others/calc/CalcStack.kt new file mode 100644 index 00000000..563e9083 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/others/calc/CalcStack.kt @@ -0,0 +1,103 @@ +package ani.dantotsu.others.calc + +import java.util.Stack + +class CalcStack { + private var expression: String = "" + private val maxExpressionLength = 256 + + fun evaluate(): Double { + val ops = Stack() + val values = Stack() + + var i = 0 + while (i < expression.length) { + when { + expression[i] == ' ' -> i++ + expression[i].isDigit() || expression[i] == '.' -> { + var value = 0.0 + var isDecimal = false + var decimalFactor = 0.1 + while (i < expression.length && (expression[i].isDigit() || expression[i] == '.' && !isDecimal)) { + if (expression[i] == '.') { + isDecimal = true + } else if (!isDecimal) { + value = value * 10 + (expression[i] - '0') + } else { + value += (expression[i] - '0') * decimalFactor + decimalFactor *= 0.1 + } + i++ + } + values.push(value) + i-- // to compensate the additional i++ in the loop + } + + else -> { + while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(expression[i])) { + val val2 = values.pop() + val val1 = values.pop() + val op = ops.pop() + values.push(applyOp(val1, val2, op)) + } + ops.push(expression[i]) + } + } + i++ + } + + while (!ops.isEmpty()) { + val val2 = values.pop() + val val1 = values.pop() + val op = ops.pop() + values.push(applyOp(val1, val2, op)) + } + + + val ans = values.pop() + expression = ans.toString() + return ans + } + + fun add(c: Char) { + if (expression.length >= maxExpressionLength) return + expression += c + } + + fun clear() { + expression = "" + } + + fun remove() { + if (expression.isNotEmpty()) { + expression = expression.substring(0, expression.length - 1) + } + } + + fun getExpression(): String { + return expression + } + + + private fun precedence(op: Char): Int { + return when (op) { + '+', '-' -> 1 + '*', '/' -> 2 + else -> -1 + } + } + + private fun applyOp(a: Double, b: Double, op: Char): Double { + return when (op) { + '+' -> a + b + '-' -> a - b + '*' -> a * b + '/' -> { + if (b == 0.0) throw UnsupportedOperationException("Cannot divide by zero.") + a / b + } + + else -> 0.0 + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/others/imagesearch/ImageSearchViewModel.kt b/app/src/main/java/ani/dantotsu/others/imagesearch/ImageSearchViewModel.kt index f82b0821..b4c101c4 100644 --- a/app/src/main/java/ani/dantotsu/others/imagesearch/ImageSearchViewModel.kt +++ b/app/src/main/java/ani/dantotsu/others/imagesearch/ImageSearchViewModel.kt @@ -26,7 +26,11 @@ class ImageSearchViewModel : ViewModel() { ) .build() - val res = client.post(url, requestBody = requestBody).parsed() + val res = try { + client.post(url, requestBody = requestBody).parsed() + } catch (e: Exception) { + SearchResult(error = e.message) + } searchResultLiveData.postValue(res) } diff --git a/app/src/main/java/ani/dantotsu/others/webview/CookieCatcher.kt b/app/src/main/java/ani/dantotsu/others/webview/CookieCatcher.kt index 73ae553a..5dffd4fa 100644 --- a/app/src/main/java/ani/dantotsu/others/webview/CookieCatcher.kt +++ b/app/src/main/java/ani/dantotsu/others/webview/CookieCatcher.kt @@ -12,19 +12,20 @@ import androidx.appcompat.app.AppCompatActivity import ani.dantotsu.R import ani.dantotsu.themes.ThemeManager import eu.kanade.tachiyomi.network.NetworkHelper +import eu.kanade.tachiyomi.util.system.getSerializableExtraCompat import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class CookieCatcher : AppCompatActivity() { @SuppressLint("SetJavaScriptEnabled") - @Suppress("UNCHECKED_CAST") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeManager(this).applyTheme() //get url from intent - val url = intent.getStringExtra("url") ?: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" - val headers: Map = intent.getSerializableExtra("headers") as? Map ?: emptyMap() + val url = intent.getStringExtra("url") ?: getString(R.string.cursed_yt) + val headers: Map = + intent.getSerializableExtraCompat("headers") as? Map ?: emptyMap() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { val process = Application.getProcessName() diff --git a/app/src/main/java/ani/dantotsu/parsers/AnimeParser.kt b/app/src/main/java/ani/dantotsu/parsers/AnimeParser.kt index 8914c440..e41a7361 100644 --- a/app/src/main/java/ani/dantotsu/parsers/AnimeParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/AnimeParser.kt @@ -90,14 +90,12 @@ abstract class AnimeParser : BaseParser() { domain = domain.substring(4) } - val extractor: VideoExtractor? = when (domain) { + return when (domain) { else -> { println("$name : No extractor found for: $domain | ${server.embed.url}") null } } - - return extractor } /** diff --git a/app/src/main/java/ani/dantotsu/parsers/AniyomiAdapter.kt b/app/src/main/java/ani/dantotsu/parsers/AniyomiAdapter.kt index 5ef0adf1..df97b2ec 100644 --- a/app/src/main/java/ani/dantotsu/parsers/AniyomiAdapter.kt +++ b/app/src/main/java/ani/dantotsu/parsers/AniyomiAdapter.kt @@ -1,21 +1,13 @@ package ani.dantotsu.parsers -import android.content.ContentResolver -import android.content.ContentValues import android.content.Context -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.net.Uri -import android.os.Build -import android.os.Environment -import android.provider.MediaStore import ani.dantotsu.FileUrl import ani.dantotsu.currContext -import ani.dantotsu.util.Logger -import ani.dantotsu.media.anime.AnimeNameAdapter +import ani.dantotsu.media.MediaNameAdapter import ani.dantotsu.media.manga.ImageData import ani.dantotsu.media.manga.MangaCache import ani.dantotsu.snackString +import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.animesource.model.AnimesPage @@ -35,12 +27,10 @@ import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.lang.awaitSingle -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit @@ -48,20 +38,10 @@ import kotlinx.coroutines.withContext import okhttp3.Request import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.io.FileOutputStream import java.io.UnsupportedEncodingException +import java.net.MalformedURLException import java.net.URL import java.net.URLDecoder -import java.util.regex.Pattern - -class AniyomiAdapter { - fun aniyomiToAnimeParser(extension: AnimeExtension.Installed): DynamicAnimeParser { - return DynamicAnimeParser(extension) - } - - -} class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { val extension: AnimeExtension.Installed @@ -73,8 +53,11 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { override val name = extension.name override val saveName = extension.name - override val hostUrl = extension.sources.first().name + override val hostUrl = + (extension.sources.first() as? AnimeHttpSource)?.baseUrl ?: extension.sources.first().name override val isNSFW = extension.isNsfw + override val icon = extension.icon + override var selectDub: Boolean get() = getDub() set(value) { @@ -93,27 +76,27 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { configurableSource.getPreferenceKey(), Context.MODE_PRIVATE ) - sharedPreferences.all.filterValues { AnimeNameAdapter.getSubDub(it.toString()) != AnimeNameAdapter.Companion.SubDubType.NULL } + sharedPreferences.all.filterValues { MediaNameAdapter.getSubDub(it.toString()) != MediaNameAdapter.SubDubType.NULL } .forEach { value -> - return when (AnimeNameAdapter.getSubDub(value.value.toString())) { - AnimeNameAdapter.Companion.SubDubType.SUB -> false - AnimeNameAdapter.Companion.SubDubType.DUB -> true - AnimeNameAdapter.Companion.SubDubType.NULL -> false + return when (MediaNameAdapter.getSubDub(value.value.toString())) { + MediaNameAdapter.SubDubType.SUB -> false + MediaNameAdapter.SubDubType.DUB -> true + MediaNameAdapter.SubDubType.NULL -> false } } } return false } - fun setDub(setDub: Boolean) { + private fun setDub(setDub: Boolean) { if (sourceLanguage >= extension.sources.size) { sourceLanguage = extension.sources.size - 1 } val configurableSource = extension.sources[sourceLanguage] as? ConfigurableAnimeSource ?: return val type = when (setDub) { - true -> AnimeNameAdapter.Companion.SubDubType.DUB - false -> AnimeNameAdapter.Companion.SubDubType.SUB + true -> MediaNameAdapter.SubDubType.DUB + false -> MediaNameAdapter.SubDubType.SUB } currContext()?.let { context -> val sharedPreferences = @@ -121,9 +104,9 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { configurableSource.getPreferenceKey(), Context.MODE_PRIVATE ) - sharedPreferences.all.filterValues { AnimeNameAdapter.getSubDub(it.toString()) != AnimeNameAdapter.Companion.SubDubType.NULL } + sharedPreferences.all.filterValues { MediaNameAdapter.getSubDub(it.toString()) != MediaNameAdapter.SubDubType.NULL } .forEach { value -> - val setValue = AnimeNameAdapter.setSubDub(value.value.toString(), type) + val setValue = MediaNameAdapter.setSubDub(value.value.toString(), type) if (setValue != null) { sharedPreferences.edit().putString(value.key, setValue).apply() } @@ -142,9 +125,9 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { Context.MODE_PRIVATE ) sharedPreferences.all.filterValues { - AnimeNameAdapter.setSubDub( + MediaNameAdapter.setSubDub( it.toString(), - AnimeNameAdapter.Companion.SubDubType.NULL + MediaNameAdapter.SubDubType.NULL ) != null } .forEach { _ -> return true } @@ -170,7 +153,7 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { val sortedEpisodes = if (res[0].episode_number == -1f) { // Find the number in the string and sort by that number val sortedByStringNumber = res.sortedBy { - val matchResult = AnimeNameAdapter.findEpisodeNumber(it.name) + val matchResult = MediaNameAdapter.findEpisodeNumber(it.name) val number = matchResult ?: Float.MAX_VALUE it.episode_number = number // Store the found number in episode_number number @@ -191,13 +174,13 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { var episodeCounter = 1f // Group by season, sort within each season, and then renumber while keeping episode number 0 as is val seasonGroups = - res.groupBy { AnimeNameAdapter.findSeasonNumber(it.name) ?: 0 } - seasonGroups.keys.sortedBy { it.toInt() } + res.groupBy { MediaNameAdapter.findSeasonNumber(it.name) ?: 0 } + seasonGroups.keys.sortedBy { it } .flatMap { season -> seasonGroups[season]?.sortedBy { it.episode_number }?.map { episode -> if (episode.episode_number != 0f) { // Skip renumbering for episode number 0 val potentialNumber = - AnimeNameAdapter.findEpisodeNumber(episode.name) + MediaNameAdapter.findEpisodeNumber(episode.name) if (potentialNumber != null) { episode.episode_number = potentialNumber } else { @@ -209,7 +192,7 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { } ?: emptyList() } } - return sortedEpisodes.map { SEpisodeToEpisode(it) } + return sortedEpisodes.map { sEpisodeToEpisode(it) } } catch (e: Exception) { Logger.log("Exception: $e") } @@ -244,7 +227,7 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { return try { val videos = source.getVideoList(sEpisode) - videos.map { VideoToVideoServer(it) } + videos.map { videoToVideoServer(it) } } catch (e: Exception) { Logger.log("Exception occurred: ${e.message}") emptyList() @@ -265,17 +248,19 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { } as? AnimeHttpSource ?: (extension.sources[sourceLanguage] as? AnimeCatalogueSource ?: return emptyList()) return try { - val res = source.fetchSearchAnime(1, query, source.getFilterList()).awaitSingle() + val res = source.getSearchAnime(1, query, source.getFilterList()) Logger.log("query: $query") convertAnimesPageToShowResponse(res) } catch (e: CloudflareBypassException) { Logger.log("Exception in search: $e") + Logger.log(e) withContext(Dispatchers.Main) { snackString("Failed to bypass Cloudflare") } emptyList() } catch (e: Exception) { Logger.log("General exception in search: $e") + Logger.log(e) emptyList() } } @@ -287,16 +272,13 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { val name = sAnime.title val link = sAnime.url val coverUrl = sAnime.thumbnail_url ?: "" - val otherNames = emptyList() // Populate as needed - val total = 1 - val extra: Map? = null // Populate as needed // Create a new ShowResponse ShowResponse(name, link, coverUrl, sAnime) } } - private fun SEpisodeToEpisode(sEpisode: SEpisode): Episode { + private fun sEpisodeToEpisode(sEpisode: SEpisode): Episode { //if the float episode number is a whole number, convert it to an int val episodeNumberInt = if (sEpisode.episode_number % 1 == 0f) { @@ -324,7 +306,7 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { ) } - private fun VideoToVideoServer(video: Video): VideoServer { + private fun videoToVideoServer(video: Video): VideoServer { return VideoServer( video.quality, video.url, @@ -335,7 +317,7 @@ class DynamicAnimeParser(extension: AnimeExtension.Installed) : AnimeParser() { } class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { - val mangaCache = Injekt.get() + private val mangaCache = Injekt.get() val extension: MangaExtension.Installed var sourceLanguage = 0 @@ -345,8 +327,10 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { override val name = extension.name override val saveName = extension.name - override val hostUrl = extension.sources.first().name + override val hostUrl = + (extension.sources.first() as? HttpSource)?.baseUrl ?: extension.sources.first().name override val isNSFW = extension.isNsfw + override val icon = extension.icon override suspend fun loadChapters( mangaLink: String, @@ -363,7 +347,7 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { return try { val res = source.getChapterList(sManga) val reversedRes = res.reversed() - val chapterList = reversedRes.map { SChapterToMangaChapter(it) } + val chapterList = reversedRes.map { sChapterToMangaChapter(it) } Logger.log("chapterList size: ${chapterList.size}") Logger.log("chapterList: ${chapterList[1].title}") Logger.log("chapterList: ${chapterList[1].description}") @@ -382,7 +366,7 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { sourceLanguage = 0 extension.sources[sourceLanguage] } as? HttpSource ?: return emptyList() - var imageDataList: List = listOf() + val imageDataList: MutableList = mutableListOf() val ret = coroutineScope { try { Logger.log("source.name " + source.name) @@ -410,7 +394,7 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { return ret } - suspend fun imageList(chapterLink: String, sChapter: SChapter): List { + suspend fun imageList(sChapter: SChapter): List { val source = try { extension.sources[sourceLanguage] } catch (e: Exception) { @@ -443,121 +427,6 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { } } - suspend fun fetchAndProcessImage( - page: Page, - httpSource: HttpSource, - context: Context - ): Bitmap? { - return withContext(Dispatchers.IO) { - try { - // Fetch the image - val response = httpSource.getImage(page) - Logger.log("Response: ${response.code}") - Logger.log("Response: ${response.message}") - - // Convert the Response to an InputStream - val inputStream = response.body.byteStream() - - // Convert InputStream to Bitmap - val bitmap = BitmapFactory.decodeStream(inputStream) - - inputStream.close() - ani.dantotsu.media.manga.saveImage( - bitmap, - context.contentResolver, - page.imageUrl!!, - Bitmap.CompressFormat.JPEG, - 100 - ) - - return@withContext bitmap - } catch (e: Exception) { - // Handle any exceptions - Logger.log("An error occurred: ${e.message}") - return@withContext null - } - } - } - - - fun fetchAndSaveImage(page: Page, httpSource: HttpSource, contentResolver: ContentResolver) { - CoroutineScope(Dispatchers.IO).launch { - try { - // Fetch the image - val response = httpSource.getImage(page) - - // Convert the Response to an InputStream - val inputStream = response.body.byteStream() - - // Convert InputStream to Bitmap - val bitmap = BitmapFactory.decodeStream(inputStream) - - withContext(Dispatchers.IO) { - // Save the Bitmap using MediaStore API - saveImage( - bitmap, - contentResolver, - "image_${System.currentTimeMillis()}.jpg", - Bitmap.CompressFormat.JPEG, - 100 - ) - } - - inputStream.close() - } catch (e: Exception) { - // Handle any exceptions - Logger.log("An error occurred: ${e.message}") - } - } - } - - fun saveImage( - bitmap: Bitmap, - contentResolver: ContentResolver, - filename: String, - format: Bitmap.CompressFormat, - quality: Int - ) { - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, filename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/${format.name.lowercase()}") - put( - MediaStore.MediaColumns.RELATIVE_PATH, - "${Environment.DIRECTORY_DOWNLOADS}/Dantotsu/Anime" - ) - } - - val uri: Uri? = contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - contentValues - ) - - uri?.let { - contentResolver.openOutputStream(it)?.use { os -> - bitmap.compress(format, quality, os) - } - } - } else { - val directory = - File("${Environment.getExternalStorageDirectory()}${File.separator}Dantotsu${File.separator}Anime") - if (!directory.exists()) { - directory.mkdirs() - } - - val file = File(directory, filename) - FileOutputStream(file).use { outputStream -> - bitmap.compress(format, quality, outputStream) - } - } - } catch (e: Exception) { - // Handle exception here - Logger.log("Exception while saving image: ${e.message}") - } - } - - override suspend fun search(query: String): List { val source = try { extension.sources[sourceLanguage] @@ -589,9 +458,6 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { val name = sManga.title val link = sManga.url val coverUrl = sManga.thumbnail_url ?: "" - val otherNames = emptyList() // Populate as needed - val total = 1 - val extra: Map? = null // Populate as needed // Create a new ShowResponse ShowResponse(name, link, coverUrl, sManga) @@ -600,12 +466,10 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { private fun pageToMangaImage(page: Page): MangaImage { var headersMap = mapOf() - var urlWithoutHeaders = "" var url = "" page.imageUrl?.let { val splitUrl = it.split("&") - urlWithoutHeaders = splitUrl.getOrNull(0) ?: "" url = it headersMap = splitUrl.mapNotNull { part -> @@ -632,7 +496,7 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { } - private fun SChapterToMangaChapter(sChapter: SChapter): MangaChapter { + private fun sChapterToMangaChapter(sChapter: SChapter): MangaChapter { return MangaChapter( sChapter.name, sChapter.url, @@ -643,85 +507,69 @@ class DynamicMangaParser(extension: MangaExtension.Installed) : MangaParser() { sChapter.date_upload ) } - - fun parseChapterTitle(title: String): Triple { - val volumePattern = - Pattern.compile("(?:vol\\.?|v|volume\\s?)(\\d+)", Pattern.CASE_INSENSITIVE) - val chapterPattern = - Pattern.compile("(?:ch\\.?|chapter\\s?)(\\d+)", Pattern.CASE_INSENSITIVE) - - val volumeMatcher = volumePattern.matcher(title) - val chapterMatcher = chapterPattern.matcher(title) - - val volumeNumber = if (volumeMatcher.find()) volumeMatcher.group(1) else null - val chapterNumber = if (chapterMatcher.find()) chapterMatcher.group(1) else null - - var remainingTitle = title - if (volumeNumber != null) { - remainingTitle = - volumeMatcher.group(0)?.let { remainingTitle.replace(it, "") }.toString() - } - if (chapterNumber != null) { - remainingTitle = - chapterMatcher.group(0)?.let { remainingTitle.replace(it, "") }.toString() - } - - return Triple(volumeNumber, chapterNumber, remainingTitle.trim()) - } - } -class VideoServerPassthrough(val videoServer: VideoServer) : VideoExtractor() { +class VideoServerPassthrough(private val videoServer: VideoServer) : VideoExtractor() { override val server: VideoServer get() = videoServer override suspend fun extract(): VideoContainer { - val vidList = listOfNotNull(videoServer.video?.let { AniVideoToSaiVideo(it) }) - val subList = videoServer.video?.subtitleTracks?.map { TrackToSubtitle(it) } ?: emptyList() + val vidList = listOfNotNull(videoServer.video?.let { aniVideoToSaiVideo(it) }) + val subList = videoServer.video?.subtitleTracks?.map { trackToSubtitle(it) } ?: emptyList() + val audioList = videoServer.video?.audioTracks ?: emptyList() return if (vidList.isNotEmpty()) { - VideoContainer(vidList, subList) + VideoContainer(vidList, subList, audioList) } else { throw Exception("No videos found") } } - private fun AniVideoToSaiVideo(aniVideo: Video): ani.dantotsu.parsers.Video { + private fun aniVideoToSaiVideo(aniVideo: Video): ani.dantotsu.parsers.Video { // Find the number value from the .quality string val number = Regex("""\d+""").find(aniVideo.quality)?.value?.toInt() ?: 0 // Check for null video URL val videoUrl = aniVideo.videoUrl ?: throw Exception("Video URL is null") - val urlObj = URL(videoUrl) - val path = urlObj.path - val query = urlObj.query + var format: VideoType? - var format = getVideoType(path) + try { + val urlObj = URL(videoUrl) + val path = urlObj.path + val query = urlObj.query - if (format == null && query != null) { - val queryPairs: List> = query.split("&").map { - val idx = it.indexOf("=") - val key = URLDecoder.decode(it.substring(0, idx), "UTF-8") - val value = URLDecoder.decode(it.substring(idx + 1), "UTF-8") - Pair(key, value) + format = getVideoType(path) + + if (format == null && query != null) { + val queryPairs: List> = query.split("&").map { + val idx = it.indexOf("=") + val key = URLDecoder.decode(it.substring(0, idx), "UTF-8") + val value = URLDecoder.decode(it.substring(idx + 1), "UTF-8") + Pair(key, value) + } + + // Assume the file is named under the "file" query parameter + val fileName = queryPairs.find { it.first == "file" }?.second ?: "" + + format = getVideoType(fileName) + // this solves a problem no one has, so I'm commenting it out for now + //if (format == null) { + // val networkHelper = Injekt.get() + // format = headRequest(videoUrl, networkHelper) + //} } - // Assume the file is named under the "file" query parameter - val fileName = queryPairs.find { it.first == "file" }?.second ?: "" - - format = getVideoType(fileName) - // this solves a problem no one has, so I'm commenting it out for now - //if (format == null) { - // val networkHelper = Injekt.get() - // format = headRequest(videoUrl, networkHelper) - //} - } - - // If the format is still undetermined, log an error - if (format == null) { - Logger.log("Unknown video format: $videoUrl") - format = VideoType.CONTAINER + // If the format is still undetermined, log an error + if (format == null) { + Logger.log("Unknown video format: $videoUrl") + format = VideoType.CONTAINER + } + } catch (malformed: MalformedURLException) { + if (videoUrl.startsWith("magnet:") || videoUrl.endsWith(".torrent")) + format = VideoType.CONTAINER + else + throw malformed } val headersMap: Map = aniVideo.headers?.toMultimap()?.mapValues { it.value.joinToString() } ?: mapOf() @@ -729,7 +577,7 @@ class VideoServerPassthrough(val videoServer: VideoServer) : VideoExtractor() { return Video( number, - format, + format!!, FileUrl(videoUrl, headersMap), if (aniVideo.totalContentLength == 0L) null else aniVideo.bytesDownloaded.toDouble() ) @@ -750,6 +598,7 @@ class VideoServerPassthrough(val videoServer: VideoServer) : VideoExtractor() { return type } + @Suppress("unused") private fun headRequest(fileName: String, networkHelper: NetworkHelper): VideoType? { return try { Logger.log("attempting head request for $fileName") @@ -789,9 +638,9 @@ class VideoServerPassthrough(val videoServer: VideoServer) : VideoExtractor() { } - private fun TrackToSubtitle(track: Track): Subtitle { + private fun trackToSubtitle(track: Track): Subtitle { //use Dispatchers.IO to make a HTTP request to determine the subtitle type - var type: SubtitleType? = null + var type: SubtitleType? runBlocking { type = findSubtitleType(track.url) } diff --git a/app/src/main/java/ani/dantotsu/parsers/BaseParser.kt b/app/src/main/java/ani/dantotsu/parsers/BaseParser.kt index 014be93d..abfe0f8a 100644 --- a/app/src/main/java/ani/dantotsu/parsers/BaseParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/BaseParser.kt @@ -1,17 +1,22 @@ package ani.dantotsu.parsers +import android.graphics.drawable.Drawable import ani.dantotsu.FileUrl import ani.dantotsu.R import ani.dantotsu.currContext import ani.dantotsu.media.Media +import ani.dantotsu.okHttpClient import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.source.model.SManga import me.xdrop.fuzzywuzzy.FuzzySearch +import okhttp3.OkHttpClient +import okhttp3.Request import java.io.Serializable import java.net.URLDecoder import java.net.URLEncoder +import kotlin.system.measureTimeMillis abstract class BaseParser { @@ -41,6 +46,11 @@ abstract class BaseParser { * **/ open val language = "English" + /** + * Icon of the site, can be null + */ + open val icon: Drawable? = null + /** * Search for Anime/Manga/Novel, returns a List of Responses * @@ -54,6 +64,11 @@ abstract class BaseParser { * Isn't necessary to override, but recommended, if you want to improve auto search results * **/ open suspend fun autoSearch(mediaObj: Media): ShowResponse? { + (this as? DynamicMangaParser)?.let { ext -> + mediaObj.selected?.langIndex?.let { + ext.sourceLanguage = it + } + } var response: ShowResponse? = loadSavedShowResponse(mediaObj.id) if (response != null && this !is OfflineMangaParser && this !is OfflineAnimeParser) { saveShowResponse(mediaObj.id, response, true) @@ -128,10 +143,40 @@ abstract class BaseParser { return response } + /** + * ping the site to check if it's working or not. + * @return Triple : First Int is the status code, Second Int is the response time in milliseconds, Third String is the response message. + */ + fun ping(): Triple { + val client = OkHttpClient() + var statusCode = 0 + var responseTime: Int? = null + var responseMessage = "" + println("Pinging $name at $hostUrl") + try { + val request = Request.Builder() + .url(hostUrl) + .build() + responseTime = measureTimeMillis { + client.newCall(request).execute().use { response -> + statusCode = response.code + responseMessage = response.message.ifEmpty { "None" } + } + }.toInt() + } catch (e: Exception) { + Logger.log("Failed to ping $name") + statusCode = -1 + responseMessage = if (e.message.isNullOrEmpty()) "None" else e.message!! + Logger.log(e) + } + return Triple(statusCode, responseTime, responseMessage) + } /** * Used to get an existing Search Response which was selected by the user. - * **/ + * @param mediaId : The mediaId of the Media object. + * @return ShowResponse? : The ShowResponse object if found, else null. + */ open suspend fun loadSavedShowResponse(mediaId: Int): ShowResponse? { checkIfVariablesAreEmpty() return PrefManager.getNullableCustomVal( @@ -143,7 +188,10 @@ abstract class BaseParser { /** * Used to save Shows Response using `saveName`. - * **/ + * @param mediaId : The mediaId of the Media object. + * @param response : The ShowResponse object to save. + * @param selected : Boolean : If the ShowResponse was selected by the user or not. + */ open fun saveShowResponse(mediaId: Int, response: ShowResponse?, selected: Boolean = false) { if (response != null) { checkIfVariablesAreEmpty() diff --git a/app/src/main/java/ani/dantotsu/parsers/BaseSources.kt b/app/src/main/java/ani/dantotsu/parsers/BaseSources.kt index 475d681f..1dd000b8 100644 --- a/app/src/main/java/ani/dantotsu/parsers/BaseSources.kt +++ b/app/src/main/java/ani/dantotsu/parsers/BaseSources.kt @@ -1,11 +1,11 @@ package ani.dantotsu.parsers import ani.dantotsu.Lazier -import ani.dantotsu.util.Logger import ani.dantotsu.media.Media import ani.dantotsu.media.anime.Episode import ani.dantotsu.media.manga.MangaChapter import ani.dantotsu.tryWithSuspend +import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.source.model.SManga diff --git a/app/src/main/java/ani/dantotsu/parsers/ExtensionSelectItem.kt b/app/src/main/java/ani/dantotsu/parsers/ExtensionSelectItem.kt new file mode 100644 index 00000000..8c9c20d5 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/parsers/ExtensionSelectItem.kt @@ -0,0 +1,38 @@ +package ani.dantotsu.parsers + +import android.graphics.drawable.Drawable +import android.view.View +import ani.dantotsu.R +import ani.dantotsu.databinding.ItemExtensionSelectBinding +import com.xwray.groupie.viewbinding.BindableItem + +class ExtensionSelectItem( + private val name: String, + private val image: Drawable?, + private var isSelected: Boolean, + val selectCallback: (String, Boolean) -> Unit +) : BindableItem() { + private lateinit var binding: ItemExtensionSelectBinding + + override fun bind(viewBinding: ItemExtensionSelectBinding, position: Int) { + binding = viewBinding + binding.extensionNameTextView.text = name + image?.let { + binding.extensionIconImageView.setImageDrawable(it) + } + binding.extensionCheckBox.setOnCheckedChangeListener(null) + binding.extensionCheckBox.isChecked = isSelected + binding.extensionCheckBox.setOnCheckedChangeListener { _, isChecked -> + isSelected = isChecked + selectCallback(name, isChecked) + } + } + + override fun getLayout(): Int { + return R.layout.item_extension_select + } + + override fun initializeViewBinding(view: View): ItemExtensionSelectBinding { + return ItemExtensionSelectBinding.bind(view) + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/parsers/ExtensionTestItem.kt b/app/src/main/java/ani/dantotsu/parsers/ExtensionTestItem.kt new file mode 100644 index 00000000..e9bc4292 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/parsers/ExtensionTestItem.kt @@ -0,0 +1,386 @@ +package ani.dantotsu.parsers + +import android.annotation.SuppressLint +import android.content.Context +import android.view.View +import androidx.core.view.isVisible +import ani.dantotsu.R +import ani.dantotsu.databinding.ItemExtensionTestBinding +import ani.dantotsu.getThemeColor +import com.xwray.groupie.viewbinding.BindableItem +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class ExtensionTestItem( + private var extensionType: String, + private var testType: String, + private var extension: BaseParser, + private var searchString: String +) : BindableItem() { + private lateinit var binding: ItemExtensionTestBinding + private lateinit var context: Context + private var job: Job? = null + private var isRunning = false + private var pingResult: Triple? = null + private var searchResultData: TestResult = TestResult() + private var episodeResultData: TestResult = TestResult() + private var serverResultData: TestResult = TestResult() + + override fun bind(viewBinding: ItemExtensionTestBinding, position: Int) { + binding = viewBinding + context = binding.root.context + binding.extensionIconImageView.setImageDrawable(extension.icon) + binding.extensionNameTextView.text = extension.name + binding.extensionLoading.isVisible = isRunning + hideAllResults() + + println(searchString) + pingResult() + searchResult() + episodeResult() + serverResult() + } + + override fun getLayout(): Int { + return R.layout.item_extension_test + } + + override fun initializeViewBinding(view: View): ItemExtensionTestBinding { + return ItemExtensionTestBinding.bind(view) + } + + private fun hideAllResults() { + if (::binding.isInitialized.not()) return + binding.searchResultText.isVisible = false + binding.episodeResultText.isVisible = false + binding.serverResultText.isVisible = false + } + + fun cancelJob() { + job?.cancel() + job = null + binding.extensionLoading.isVisible = false + } + + fun startTest() { + pingResult = null + searchResultData = TestResult() + episodeResultData = TestResult() + serverResultData = TestResult() + isRunning = true + hideAllResults() + job?.cancel() + job = Job() + CoroutineScope(Dispatchers.IO + job!!).launch { + when (extensionType) { + "anime" -> { + val extension = extension as AnimeParser + runAnimeTest(extension) + } + + "manga" -> { + val extension = extension as MangaParser + runMangaTest(extension) + } + + "novel" -> { + val extension = extension as NovelParser + runNovelTest(extension) + } + } + } + } + + private suspend fun runAnimeTest(extension: AnimeParser) { + if (testType == "ping") { + pingResult = extension.ping() + withContext(Dispatchers.Main) { + pingResult() + } + done() + return + } + val searchStart = System.currentTimeMillis() + val searchResult = extension.search(searchString) + searchResultData.time = (System.currentTimeMillis() - searchStart).toInt() + searchResultData.size = searchResult.size + withContext(Dispatchers.Main) { + searchResult() + } + if (searchResultData.size == 0 || testType == "basic") { + done() + return + } + val episodeResultTime = System.currentTimeMillis() + val episodeResult = extension.loadEpisodes("", null, searchResult.first().sAnime!!) + episodeResultData.time = (System.currentTimeMillis() - episodeResultTime).toInt() + episodeResultData.size = episodeResult.size + withContext(Dispatchers.Main) { + episodeResult() + } + if (episodeResultData.size == 0) { + done() + return + } + val serverResultTime = System.currentTimeMillis() + val serverResult = extension.loadVideoServers("", null, episodeResult.first().sEpisode!!) + serverResultData.time = (System.currentTimeMillis() - serverResultTime).toInt() + serverResultData.size = serverResult.size + withContext(Dispatchers.Main) { + serverResult() + } + + done() + } + + private suspend fun runMangaTest(extension: MangaParser) { + if (testType == "ping") { + pingResult = extension.ping() + withContext(Dispatchers.Main) { + pingResult() + } + done() + return + } + val searchStart = System.currentTimeMillis() + val searchResult = extension.search(searchString) + searchResultData.time = (System.currentTimeMillis() - searchStart).toInt() + searchResultData.size = searchResult.size + withContext(Dispatchers.Main) { + searchResult() + } + if (searchResultData.size == 0 || testType == "basic") { + done() + return + } + val episodeResultStart = System.currentTimeMillis() + val chapterResult = extension.loadChapters("", null, searchResult.first().sManga!!) + episodeResultData.time = (System.currentTimeMillis() - episodeResultStart).toInt() + episodeResultData.size = chapterResult.size + withContext(Dispatchers.Main) { + episodeResult() + } + if (episodeResultData.size == 0) { + done() + return + } + val serverResultStart = System.currentTimeMillis() + val serverResult = extension.loadImages("", chapterResult.first().sChapter) + serverResultData.time = (System.currentTimeMillis() - serverResultStart).toInt() + serverResultData.size = serverResult.size + withContext(Dispatchers.Main) { + serverResult() + } + + done() + } + + private suspend fun runNovelTest(extension: NovelParser) { + if (testType == "ping") { + withContext(Dispatchers.Main) { + pingResult() + } + done() + return + } + val searchStart = System.currentTimeMillis() + val searchResult = extension.search(searchString) + searchResultData.time = (System.currentTimeMillis() - searchStart).toInt() + searchResultData.size = searchResult.size + withContext(Dispatchers.Main) { + searchResult() + } + if (searchResultData.size == 0 || testType == "basic") { + done() + return + } + val chapterResultTime = System.currentTimeMillis() + val chapterResult = extension.loadBook(searchResult.first().link, null) + episodeResultData.time = (System.currentTimeMillis() - chapterResultTime).toInt() + episodeResultData.size = chapterResult.links.size + withContext(Dispatchers.Main) { + episodeResult() + serverResult() + } + + done() + } + + private suspend fun done() { + if (::binding.isInitialized.not()) return + withContext(Dispatchers.Main) { + binding.extensionLoading.isVisible = false + isRunning = false + } + } + + private fun pingResult() { + if (::binding.isInitialized.not()) return + if (extensionType == "novel" && testType != "basic") { + binding.pingResultText.isVisible = true + binding.pingResultText.text = context.getString(R.string.test_not_supported) + binding.pingResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_round_info_24, 0, 0, 0 + ) + return + } + if (pingResult == null) { + binding.pingResultText.isVisible = false + return + } else { + binding.pingResultText.isVisible = true + } + binding.pingResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + ) + val (code, time, message) = pingResult!! + if (code == 200) { + binding.pingResultText.text = context.getString(R.string.ping_success, time.toString()) + binding.pingResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_check, 0, 0, 0 + ) + return + } + binding.pingResultText.text = + context.getString(R.string.ping_error, code.toString(), message) + binding.pingResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_cancel, 0, 0, 0 + ) + binding.pingResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorError) + ) + } + + @SuppressLint("SetTextI18n") + private fun searchResult() { + if (::binding.isInitialized.not()) return + if (searchResultData.time == 0) { + binding.searchResultText.isVisible = false + return + } + binding.searchResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + ) + binding.searchResultText.isVisible = true + if (searchResultData.size == 0) { + val text = context.getString(R.string.title_search_test, + context.getString(R.string.no_results_found)) + binding.searchResultText.text = text + binding.searchResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_cancel, 0, 0, 0 + ) + binding.searchResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorError) + ) + return + } + val text = context.getString(R.string.title_search_test, + context.getString(R.string.results_found, searchResultData.size.toString())) + binding.searchResultText.text = text + "\n${searchResultData.time}ms" + binding.searchResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_check, 0, 0, 0 + ) + } + + @SuppressLint("SetTextI18n") + private fun episodeResult() { + if (::binding.isInitialized.not()) return + if (episodeResultData.time == 0) { + binding.episodeResultText.isVisible = false + return + } + binding.episodeResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + ) + binding.episodeResultText.isVisible = true + if (episodeResultData.size == 0) { + val text = when(extensionType) { + "anime" -> context.getString(R.string.episode_search_test, + context.getString(R.string.no_results_found)) + "manga" -> context.getString(R.string.chapter_search_test, + context.getString(R.string.no_results_found)) + else -> context.getString(R.string.book_search_test, + context.getString(R.string.no_results_found)) + } + binding.episodeResultText.text = text + binding.episodeResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_cancel, 0, 0, 0 + ) + binding.episodeResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorError) + ) + return + } + val text = when(extensionType) { + "anime" -> context.getString(R.string.episode_search_test, + context.getString(R.string.results_found, episodeResultData.size.toString())) + "manga" -> context.getString(R.string.chapter_search_test, + context.getString(R.string.results_found, episodeResultData.size.toString())) + else -> context.getString(R.string.book_search_test, + context.getString(R.string.results_found, episodeResultData.size.toString())) + } + binding.episodeResultText.text = text + "\n${episodeResultData.time}ms" + binding.episodeResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_check, 0, 0, 0 + ) + } + + @SuppressLint("SetTextI18n") + private fun serverResult() { + if (::binding.isInitialized.not()) return + if (extensionType == "novel") { + binding.pingResultText.isVisible = true + binding.pingResultText.text = context.getString(R.string.test_not_supported) + binding.pingResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_round_info_24, 0, 0, 0 + ) + return + } + if (serverResultData.time == 0) { + binding.serverResultText.isVisible = false + return + } + binding.serverResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorPrimary) + ) + binding.serverResultText.isVisible = true + if (serverResultData.size == 0) { + val text = when(extensionType) { + "anime" -> context.getString(R.string.video_search_test, + context.getString(R.string.no_results_found)) + "manga" -> context.getString(R.string.image_search_test, + context.getString(R.string.no_results_found)) + else -> context.getString(R.string.book_search_test, + context.getString(R.string.no_results_found)) + } + binding.serverResultText.text = text + "\n${serverResultData.time}ms" + binding.serverResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_cancel, 0, 0, 0 + ) + binding.serverResultText.setTextColor( + context.getThemeColor(com.google.android.material.R.attr.colorError) + ) + return + } + val text = when(extensionType) { + "anime" -> context.getString(R.string.video_search_test, + context.getString(R.string.results_found, serverResultData.size.toString())) + "manga" -> context.getString(R.string.image_search_test, + context.getString(R.string.results_found, serverResultData.size.toString())) + else -> context.getString(R.string.book_search_test, + context.getString(R.string.results_found, serverResultData.size.toString())) + } + binding.serverResultText.text = text + binding.serverResultText.setCompoundDrawablesWithIntrinsicBounds( + R.drawable.ic_circle_check, 0, 0, 0 + ) + } + + data class TestResult( + var size: Int = 0, + var time: Int = 0, + ) +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/parsers/ExtensionTestSettingsBottomDialog.kt b/app/src/main/java/ani/dantotsu/parsers/ExtensionTestSettingsBottomDialog.kt new file mode 100644 index 00000000..e8d9cd1b --- /dev/null +++ b/app/src/main/java/ani/dantotsu/parsers/ExtensionTestSettingsBottomDialog.kt @@ -0,0 +1,144 @@ +package ani.dantotsu.parsers + +import android.graphics.drawable.Drawable +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.widget.addTextChangedListener +import androidx.recyclerview.widget.LinearLayoutManager +import ani.dantotsu.BottomSheetDialogFragment +import ani.dantotsu.databinding.BottomSheetExtensionTestSettingsBinding +import ani.dantotsu.parsers.novel.NovelExtensionManager +import com.xwray.groupie.GroupieAdapter +import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager +import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get + +class ExtensionTestSettingsBottomDialog : BottomSheetDialogFragment() { + private var _binding: BottomSheetExtensionTestSettingsBinding? = null + private val binding get() = _binding!! + private val adapter: GroupieAdapter = GroupieAdapter() + private val animeExtension: AnimeExtensionManager = Injekt.get() + private val mangaExtensions: MangaExtensionManager = Injekt.get() + private val novelExtensions: NovelExtensionManager = Injekt.get() + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + _binding = BottomSheetExtensionTestSettingsBinding.inflate(inflater, container, false) + return _binding?.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + binding.extensionSelectionRecyclerView.adapter = adapter + binding.extensionSelectionRecyclerView.layoutManager = LinearLayoutManager( + context, + LinearLayoutManager.VERTICAL, + false + ) + binding.searchViewText.setText(searchQuery) + binding.searchViewText.addTextChangedListener { + searchQuery = it.toString() + } + binding.extensionTypeRadioGroup.check( + when (extensionType) { + "anime" -> binding.animeRadioButton.id + "manga" -> binding.mangaRadioButton.id + "novel" -> binding.novelsRadioButton.id + else -> binding.animeRadioButton.id + } + ) + binding.testTypeRadioGroup.check( + when (testType) { + "ping" -> binding.pingRadioButton.id + "basic" -> binding.basicRadioButton.id + "full" -> binding.fullRadioButton.id + else -> binding.pingRadioButton.id + } + ) + binding.animeRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + extensionType = "anime" + extensionsToTest.clear() + setupAdapter() + } + } + binding.mangaRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + extensionType = "manga" + extensionsToTest.clear() + setupAdapter() + } + } + binding.novelsRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + extensionType = "novel" + extensionsToTest.clear() + setupAdapter() + } + } + binding.pingRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + testType = "ping" + } + } + binding.basicRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + testType = "basic" + } + } + binding.fullRadioButton.setOnCheckedChangeListener { _, b -> + if (b) { + testType = "full" + } + } + binding.extensionTypeTextView.setOnLongClickListener { + binding.searchTextView.visibility = View.VISIBLE + binding.searchView.visibility = View.VISIBLE + true + } + setupAdapter() + } + + override fun onDestroyView() { + _binding = null + super.onDestroyView() + } + + private fun setupAdapter() { + val namesAndUrls: Map = when (extensionType) { + "anime" -> animeExtension.installedExtensionsFlow.value.associate { it.name to it.icon } + "manga" -> mangaExtensions.installedExtensionsFlow.value.associate { it.name to it.icon } + "novel" -> novelExtensions.installedExtensionsFlow.value.associate { it.name to it.icon } + else -> emptyMap() + } + adapter.clear() + namesAndUrls.forEach { (name, icon) -> + val isSelected = extensionsToTest.contains(name) + adapter.add(ExtensionSelectItem(name, icon, isSelected, ::selectedCallback)) + } + } + + private fun selectedCallback(name: String, isSelected: Boolean) { + if (isSelected) { + extensionsToTest.add(name) + } else { + extensionsToTest.remove(name) + } + } + + companion object { + fun newInstance(): ExtensionTestSettingsBottomDialog { + return ExtensionTestSettingsBottomDialog() + } + + var extensionType = "anime" + var testType = "basic" + var searchQuery = "Chainsaw Man" + var extensionsToTest: MutableList = mutableListOf() + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/parsers/MangaParser.kt b/app/src/main/java/ani/dantotsu/parsers/MangaParser.kt index cd757307..bf67a8ca 100644 --- a/app/src/main/java/ani/dantotsu/parsers/MangaParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/MangaParser.kt @@ -1,7 +1,7 @@ package ani.dantotsu.parsers import ani.dantotsu.FileUrl -import ani.dantotsu.media.manga.MangaNameAdapter +import ani.dantotsu.media.MediaNameAdapter import com.bumptech.glide.load.resource.bitmap.BitmapTransformation import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter @@ -33,9 +33,9 @@ abstract class MangaParser : BaseParser() { ): MangaChapter? { val chapter = loadChapters(mangaLink, extra, sManga) val max = chapter - .maxByOrNull { MangaNameAdapter.findChapterNumber(it.number) ?: 0f } + .maxByOrNull { MediaNameAdapter.findChapterNumber(it.number) ?: 0f } return max - ?.takeIf { latest < (MangaNameAdapter.findChapterNumber(it.number) ?: 0.001f) } + ?.takeIf { latest < (MediaNameAdapter.findChapterNumber(it.number) ?: 0.001f) } } /** diff --git a/app/src/main/java/ani/dantotsu/parsers/NovelSources.kt b/app/src/main/java/ani/dantotsu/parsers/NovelSources.kt index 9420feb8..ea35a1b3 100644 --- a/app/src/main/java/ani/dantotsu/parsers/NovelSources.kt +++ b/app/src/main/java/ani/dantotsu/parsers/NovelSources.kt @@ -1,6 +1,5 @@ package ani.dantotsu.parsers -import android.util.Log import ani.dantotsu.Lazier import ani.dantotsu.parsers.novel.DynamicNovelParser import ani.dantotsu.parsers.novel.NovelExtension diff --git a/app/src/main/java/ani/dantotsu/parsers/OfflineAnimeParser.kt b/app/src/main/java/ani/dantotsu/parsers/OfflineAnimeParser.kt index 1c9c3b6c..85d1af90 100644 --- a/app/src/main/java/ani/dantotsu/parsers/OfflineAnimeParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/OfflineAnimeParser.kt @@ -1,22 +1,27 @@ package ani.dantotsu.parsers -import android.net.Uri -import android.os.Environment +import android.app.Application import ani.dantotsu.currContext +import ani.dantotsu.download.DownloadCompat.Companion.loadEpisodesCompat +import ani.dantotsu.download.DownloadCompat.Companion.loadSubtitleCompat import ani.dantotsu.download.DownloadsManager -import ani.dantotsu.media.anime.AnimeNameAdapter +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory +import ani.dantotsu.download.anime.AnimeDownloaderService.AnimeDownloadTask.Companion.getTaskName +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType import ani.dantotsu.tryWithSuspend +import ani.dantotsu.util.Logger import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.SEpisodeImpl import me.xdrop.fuzzywuzzy.FuzzySearch import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File import java.util.Locale class OfflineAnimeParser : AnimeParser() { private val downloadManager = Injekt.get() + private val context = Injekt.get() override val name = "Offline" override val saveName = "Offline" @@ -28,22 +33,19 @@ class OfflineAnimeParser : AnimeParser() { extra: Map?, sAnime: SAnime ): List { - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "${DownloadsManager.animeLocation}/$animeLink" - ) + val directory = getSubDirectory(context, MediaType.ANIME, false, animeLink) //get all of the folder names and add them to the list val episodes = mutableListOf() - if (directory.exists()) { - directory.listFiles()?.forEach { + if (directory?.exists() == true) { + directory.listFiles().forEach { //put the title and episdode number in the extra data val extraData = mutableMapOf() extraData["title"] = animeLink - extraData["episode"] = it.name + extraData["episode"] = it.name!! if (it.isDirectory) { val episode = Episode( - it.name, - "$animeLink - ${it.name}", + it.name!!, + getTaskName(animeLink, it.name!!), it.name, null, null, @@ -53,8 +55,11 @@ class OfflineAnimeParser : AnimeParser() { episodes.add(episode) } } - episodes.sortBy { AnimeNameAdapter.findEpisodeNumber(it.number) } - return episodes + //episodes.sortBy { MediaNameAdapter.findEpisodeNumber(it.number) } + episodes.addAll(loadEpisodesCompat(animeLink, extra, sAnime)) + //filter those with the same name + return episodes.distinctBy { it.number } + .sortedBy { MediaNameAdapter.findEpisodeNumber(it.number) } } return emptyList() } @@ -75,13 +80,16 @@ class OfflineAnimeParser : AnimeParser() { override suspend fun search(query: String): List { - val titles = downloadManager.animeDownloadedTypes.map { it.title }.distinct() - val returnTitles: MutableList = mutableListOf() + val titles = downloadManager.animeDownloadedTypes.map { it.titleName }.distinct() + val returnTitlesPair: MutableList> = mutableListOf() for (title in titles) { - if (FuzzySearch.ratio(title.lowercase(), query.lowercase()) > 80) { - returnTitles.add(title) + Logger.log("Comparing $title to $query") + val score = FuzzySearch.ratio(title.lowercase(), query.lowercase()) + if (score > 80) { + returnTitlesPair.add(Pair(title, score)) } } + val returnTitles = returnTitlesPair.sortedByDescending { it.second }.map { it.first } val returnList: MutableList = mutableListOf() for (title in returnTitles) { returnList.add(ShowResponse(title, title, title)) @@ -110,7 +118,7 @@ class OfflineAnimeParser : AnimeParser() { } -class OfflineVideoExtractor(val videoServer: VideoServer) : VideoExtractor() { +class OfflineVideoExtractor(private val videoServer: VideoServer) : VideoExtractor() { override val server: VideoServer get() = videoServer @@ -130,27 +138,29 @@ class OfflineVideoExtractor(val videoServer: VideoServer) : VideoExtractor() { private fun getSubtitle(title: String, episode: String): List? { currContext()?.let { - DownloadsManager.getDirectory( + getSubDirectory( it, - ani.dantotsu.download.DownloadedType.Type.ANIME, + MediaType.ANIME, + false, title, episode - ).listFiles()?.forEach { - if (it.name.contains("subtitle")) { + )?.listFiles()?.forEach { file -> + if (file.name?.contains("subtitle") == true) { return listOf( Subtitle( "Downloaded Subtitle", - Uri.fromFile(it).toString(), - determineSubtitletype(it.absolutePath) + file.uri.toString(), + determineSubtitleType(file.name ?: "") ) ) } } + loadSubtitleCompat(title, episode)?.let { return it } } return null } - fun determineSubtitletype(url: String): SubtitleType { + private fun determineSubtitleType(url: String): SubtitleType { return when { url.lowercase(Locale.ROOT).endsWith("ass") -> SubtitleType.ASS url.lowercase(Locale.ROOT).endsWith("vtt") -> SubtitleType.VTT diff --git a/app/src/main/java/ani/dantotsu/parsers/OfflineMangaParser.kt b/app/src/main/java/ani/dantotsu/parsers/OfflineMangaParser.kt index 25099d78..f0c1237f 100644 --- a/app/src/main/java/ani/dantotsu/parsers/OfflineMangaParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/OfflineMangaParser.kt @@ -1,19 +1,22 @@ package ani.dantotsu.parsers -import android.os.Environment -import ani.dantotsu.currContext +import android.app.Application +import ani.dantotsu.download.DownloadCompat.Companion.loadChaptersCompat +import ani.dantotsu.download.DownloadCompat.Companion.loadImagesCompat import ani.dantotsu.download.DownloadsManager +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType import ani.dantotsu.util.Logger -import ani.dantotsu.media.manga.MangaNameAdapter import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import me.xdrop.fuzzywuzzy.FuzzySearch import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class OfflineMangaParser : MangaParser() { private val downloadManager = Injekt.get() + private val context = Injekt.get() override val hostUrl: String = "Offline" override val name: String = "Offline" @@ -23,17 +26,14 @@ class OfflineMangaParser : MangaParser() { extra: Map?, sManga: SManga ): List { - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/$mangaLink" - ) + val directory = getSubDirectory(context, MediaType.MANGA, false, mangaLink) //get all of the folder names and add them to the list val chapters = mutableListOf() - if (directory.exists()) { - directory.listFiles()?.forEach { + if (directory?.exists() == true) { + directory.listFiles().forEach { if (it.isDirectory) { val chapter = MangaChapter( - it.name, + it.name!!, "$mangaLink/${it.name}", it.name, null, @@ -43,46 +43,52 @@ class OfflineMangaParser : MangaParser() { chapters.add(chapter) } } - chapters.sortBy { MangaNameAdapter.findChapterNumber(it.number) } - return chapters + chapters.addAll(loadChaptersCompat(mangaLink, extra, sManga)) + return chapters.distinctBy { it.number } + .sortedBy { MediaNameAdapter.findChapterNumber(it.number) } } return emptyList() } override suspend fun loadImages(chapterLink: String, sChapter: SChapter): List { - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Manga/$chapterLink" - ) + val title = chapterLink.split("/").first() + val chapter = chapterLink.split("/").last() + val directory = getSubDirectory(context, MediaType.MANGA, false, title, chapter) val images = mutableListOf() val imageNumberRegex = Regex("""(\d+)\.jpg$""") - if (directory.exists()) { - directory.listFiles()?.forEach { + if (directory?.exists() == true) { + directory.listFiles().forEach { if (it.isFile) { - val image = MangaImage(it.absolutePath, false, null) + val image = MangaImage(it.uri.toString(), false, null) images.add(image) } } - images.sortBy { image -> - val matchResult = imageNumberRegex.find(image.url.url) - matchResult?.groups?.get(1)?.value?.toIntOrNull() ?: Int.MAX_VALUE - } for (image in images) { Logger.log("imageNumber: ${image.url.url}") } - return images + return if (images.isNotEmpty()) { + images.sortBy { image -> + val matchResult = imageNumberRegex.find(image.url.url) + matchResult?.groups?.get(1)?.value?.toIntOrNull() ?: Int.MAX_VALUE + } + images + } else { + loadImagesCompat(chapterLink, sChapter) + } } return emptyList() } override suspend fun search(query: String): List { - val titles = downloadManager.mangaDownloadedTypes.map { it.title }.distinct() - val returnTitles: MutableList = mutableListOf() + val titles = downloadManager.mangaDownloadedTypes.map { it.titleName }.distinct() + val returnTitlesPair: MutableList> = mutableListOf() for (title in titles) { - if (FuzzySearch.ratio(title.lowercase(), query.lowercase()) > 80) { - returnTitles.add(title) + val score = FuzzySearch.ratio(title.lowercase(), query.lowercase()) + if (score > 80) { + returnTitlesPair.add(Pair(title, score)) } } + val returnTitles = returnTitlesPair.sortedByDescending { it.second }.map { it.first } val returnList: MutableList = mutableListOf() for (title in returnTitles) { returnList.add(ShowResponse(title, title, title)) diff --git a/app/src/main/java/ani/dantotsu/parsers/OfflineNovelParser.kt b/app/src/main/java/ani/dantotsu/parsers/OfflineNovelParser.kt index 534c3ac5..7a3535e0 100644 --- a/app/src/main/java/ani/dantotsu/parsers/OfflineNovelParser.kt +++ b/app/src/main/java/ani/dantotsu/parsers/OfflineNovelParser.kt @@ -1,16 +1,18 @@ package ani.dantotsu.parsers -import android.os.Environment -import ani.dantotsu.currContext +import android.app.Application import ani.dantotsu.download.DownloadsManager -import ani.dantotsu.media.manga.MangaNameAdapter +import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory +import ani.dantotsu.media.MediaNameAdapter +import ani.dantotsu.media.MediaType +import ani.dantotsu.util.Logger import me.xdrop.fuzzywuzzy.FuzzySearch import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class OfflineNovelParser : NovelParser() { private val downloadManager = Injekt.get() + private val context = Injekt.get() override val hostUrl: String = "Offline" override val name: String = "Offline" @@ -21,24 +23,21 @@ class OfflineNovelParser : NovelParser() { override suspend fun loadBook(link: String, extra: Map?): Book { //link should be a directory - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/$link" - ) + val directory = getSubDirectory(context, MediaType.NOVEL, false, link) val chapters = mutableListOf() - if (directory.exists()) { - directory.listFiles()?.forEach { + if (directory?.exists() == true) { + directory.listFiles().forEach { if (it.isDirectory) { val chapter = Book( - it.name, - it.absolutePath + "/cover.jpg", + it.name ?: "Unknown", + it.uri.toString(), null, - listOf(it.absolutePath + "/0.epub") + listOf(it.uri.toString()) ) chapters.add(chapter) } } - chapters.sortBy { MangaNameAdapter.findChapterNumber(it.name) } + chapters.sortBy { MediaNameAdapter.findChapterNumber(it.name) } return chapters.first() } return Book( @@ -50,32 +49,31 @@ class OfflineNovelParser : NovelParser() { } override suspend fun search(query: String): List { - val titles = downloadManager.novelDownloadedTypes.map { it.title }.distinct() - val returnTitles: MutableList = mutableListOf() + val titles = downloadManager.novelDownloadedTypes.map { it.titleName }.distinct() + val returnTitlesPair: MutableList> = mutableListOf() for (title in titles) { - if (FuzzySearch.ratio(title.lowercase(), query.lowercase()) > 80) { - returnTitles.add(title) + Logger.log("Comparing $title to $query") + val score = FuzzySearch.ratio(title.lowercase(), query.lowercase()) + if (score > 80) { + returnTitlesPair.add(Pair(title, score)) } } + val returnTitles = returnTitlesPair.sortedByDescending { it.second }.map { it.first } val returnList: MutableList = mutableListOf() for (title in returnTitles) { //need to search the subdirectories for the ShowResponses - val directory = File( - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), - "Dantotsu/Novel/$title" - ) + val directory = getSubDirectory(context, MediaType.NOVEL, false, title) val names = mutableListOf() - if (directory.exists()) { - directory.listFiles()?.forEach { + if (directory?.exists() == true) { + directory.listFiles().forEach { if (it.isDirectory) { - names.add(it.name) + names.add(it.name ?: "Unknown") } } } - val cover = - currContext()?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath + "/Dantotsu/Novel/$title/cover.jpg" + val cover = directory?.findFile("cover.jpg")?.uri.toString() names.forEach { - returnList.add(ShowResponse(it, it, cover)) + returnList.add(ShowResponse(it, query, cover)) } } return returnList diff --git a/app/src/main/java/ani/dantotsu/parsers/ParserTestActivity.kt b/app/src/main/java/ani/dantotsu/parsers/ParserTestActivity.kt new file mode 100644 index 00000000..7d7f67f5 --- /dev/null +++ b/app/src/main/java/ani/dantotsu/parsers/ParserTestActivity.kt @@ -0,0 +1,115 @@ +package ani.dantotsu.parsers + +import android.os.Bundle +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.updateLayoutParams +import androidx.recyclerview.widget.LinearLayoutManager +import ani.dantotsu.R +import ani.dantotsu.databinding.ActivityParserTestBinding +import ani.dantotsu.initActivity +import ani.dantotsu.navBarHeight +import ani.dantotsu.statusBarHeight +import ani.dantotsu.themes.ThemeManager +import ani.dantotsu.toast +import com.xwray.groupie.GroupieAdapter + +class ParserTestActivity : AppCompatActivity() { + private lateinit var binding: ActivityParserTestBinding + val adapter = GroupieAdapter() + val extensionsToTest: MutableList = mutableListOf() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ThemeManager(this).applyTheme() + initActivity(this) + binding = ActivityParserTestBinding.inflate(layoutInflater) + binding.toolbar.updateLayoutParams { + topMargin = statusBarHeight + } + binding.extensionResultsRecyclerView.updateLayoutParams { + bottomMargin = navBarHeight + } + setContentView(binding.root) + + binding.extensionResultsRecyclerView.adapter = adapter + binding.extensionResultsRecyclerView.layoutManager = LinearLayoutManager( + this, + LinearLayoutManager.VERTICAL, + false + ) + binding.backButton.setOnClickListener { + onBackPressedDispatcher.onBackPressed() + } + binding.optionsLayout.setOnClickListener { + ExtensionTestSettingsBottomDialog.newInstance() + .show(supportFragmentManager, "extension_test_settings") + } + + binding.startButton.setOnClickListener { + if (ExtensionTestSettingsBottomDialog.extensionsToTest.isEmpty()) { + toast(R.string.no_extensions_selected) + return@setOnClickListener + } + extensionsToTest.forEach { + it.cancelJob() + } + extensionsToTest.clear() + adapter.clear() + when (ExtensionTestSettingsBottomDialog.extensionType) { + "anime" -> { + ExtensionTestSettingsBottomDialog.extensionsToTest.forEach { name -> + val extension = + AnimeSources.list.find { source -> source.name == name }?.get?.value + extension?.let { + extensionsToTest.add( + ExtensionTestItem( + "anime", + ExtensionTestSettingsBottomDialog.testType, + it, + ExtensionTestSettingsBottomDialog.searchQuery + ) + ) + } + } + } + "manga" -> { + ExtensionTestSettingsBottomDialog.extensionsToTest.forEach { name -> + val extension = + MangaSources.list.find { source -> source.name == name }?.get?.value + extension?.let { + extensionsToTest.add( + ExtensionTestItem( + "manga", + ExtensionTestSettingsBottomDialog.testType, + it, + ExtensionTestSettingsBottomDialog.searchQuery + ) + ) + } + } + } + "novel" -> { + ExtensionTestSettingsBottomDialog.extensionsToTest.forEach { name -> + val extension = + NovelSources.list.find { source -> source.name == name }?.get?.value + extension?.let { + extensionsToTest.add( + ExtensionTestItem( + "novel", + ExtensionTestSettingsBottomDialog.testType, + it, + ExtensionTestSettingsBottomDialog.searchQuery + ) + ) + } + } + } + } + extensionsToTest.forEach { + adapter.add(it) + it.startTest() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ani/dantotsu/parsers/VideoExtractor.kt b/app/src/main/java/ani/dantotsu/parsers/VideoExtractor.kt index ef164b34..e908adee 100644 --- a/app/src/main/java/ani/dantotsu/parsers/VideoExtractor.kt +++ b/app/src/main/java/ani/dantotsu/parsers/VideoExtractor.kt @@ -1,6 +1,7 @@ package ani.dantotsu.parsers import ani.dantotsu.FileUrl +import eu.kanade.tachiyomi.animesource.model.Track import java.io.Serializable /** @@ -12,6 +13,7 @@ abstract class VideoExtractor : Serializable { abstract val server: VideoServer var videos: List