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