mirror of
https://github.com/rebelonion/Dantotsu.git
synced 2026-01-26 21:51:02 +00:00
Merge branch 'dev' into dev
This commit is contained in:
247
.github/workflows/beta.yml
vendored
247
.github/workflows/beta.yml
vendored
@@ -12,6 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CI: true
|
||||
SKIP_BUILD: false
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
@@ -19,14 +20,12 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
- name: Download last SHA artifact
|
||||
uses: dawidd6/action-download-artifact@v3
|
||||
with:
|
||||
workflow: beta.yml
|
||||
name: last-sha
|
||||
path: .
|
||||
|
||||
continue-on-error: true
|
||||
|
||||
- name: Get Commits Since Last Run
|
||||
@@ -39,7 +38,9 @@ jobs:
|
||||
fi
|
||||
echo "Commits since $LAST_SHA:"
|
||||
# Accumulate commit logs in a shell variable
|
||||
COMMIT_LOGS=$(git log $LAST_SHA..HEAD --pretty=format:"● %s ~%an")
|
||||
COMMIT_LOGS=$(git log $LAST_SHA..HEAD --pretty=format:"● %s ~%an [֍](https://github.com/${{ github.repository }}/commit/%H)")
|
||||
# Replace commit messages with pull request links
|
||||
COMMIT_LOGS=$(echo "$COMMIT_LOGS" | sed -E 's/#([0-9]+)/[#\1](https:\/\/github.com\/rebelonion\/Dantotsu\/pull\/\1)/g')
|
||||
# URL-encode the newline characters for GitHub Actions
|
||||
COMMIT_LOGS="${COMMIT_LOGS//'%'/'%25'}"
|
||||
COMMIT_LOGS="${COMMIT_LOGS//$'\n'/'%0A'}"
|
||||
@@ -65,26 +66,40 @@ jobs:
|
||||
echo "Version $VERSION"
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: List files in the directory
|
||||
run: ls -l
|
||||
|
||||
- name: Setup JDK 17
|
||||
if: ${{ env.SKIP_BUILD != 'true' }}
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 17
|
||||
cache: gradle
|
||||
|
||||
- name: Decode Keystore File
|
||||
run: echo "${{ secrets.KEYSTORE_FILE }}" | base64 -d > $GITHUB_WORKSPACE/key.keystore
|
||||
|
||||
- name: List files in the directory
|
||||
run: ls -l
|
||||
|
||||
- name: Make gradlew executable
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
- 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: Decode Keystore File
|
||||
if: ${{ github.repository == 'rebelonion/Dantotsu' }}
|
||||
run: echo "${{ secrets.KEYSTORE_FILE }}" | base64 -d > $GITHUB_WORKSPACE/key.keystore
|
||||
|
||||
- name: Make gradlew executable
|
||||
if: ${{ env.SKIP_BUILD != 'true' }}
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
- name: Build with Gradle
|
||||
if: ${{ env.SKIP_BUILD != 'true' }}
|
||||
run: |
|
||||
if [ "${{ github.repository }}" == "rebelonion/Dantotsu" ]; then
|
||||
./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 }};
|
||||
else
|
||||
./gradlew assembleGoogleAlpha;
|
||||
fi
|
||||
|
||||
- name: Upload a Build Artifact
|
||||
if: ${{ env.SKIP_BUILD != 'true' }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Dantotsu
|
||||
@@ -93,25 +108,203 @@ jobs:
|
||||
path: "app/build/outputs/apk/google/alpha/app-google-alpha.apk"
|
||||
|
||||
- name: Upload APK to Discord and Telegram
|
||||
if: ${{ github.repository == 'rebelonion/Dantotsu' }}
|
||||
shell: bash
|
||||
run: |
|
||||
#Discord
|
||||
# Prepare Discord embed
|
||||
fetch_user_details() {
|
||||
local login=$1
|
||||
user_details=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
"https://api.github.com/users/$login")
|
||||
name=$(echo "$user_details" | jq -r '.name // .login')
|
||||
login=$(echo "$user_details" | jq -r '.login')
|
||||
avatar_url=$(echo "$user_details" | jq -r '.avatar_url')
|
||||
echo "$name|$login|$avatar_url"
|
||||
}
|
||||
|
||||
# Additional information for the goats
|
||||
declare -A additional_info
|
||||
additional_info["ibo"]="\n Discord: <@951737931159187457>\n AniList: [takarealist112](<https://anilist.co/user/takarealist112/>)"
|
||||
additional_info["aayush262"]="\n Discord: <@918825160654598224>\n AniList: [aayush262](<https://anilist.co/user/aayush262/>)"
|
||||
additional_info["rebelonion"]="\n Discord: <@714249925248024617>\n AniList: [rebelonion](<https://anilist.co/user/rebelonion/>)\n PornHub: [rebelonion](<https://www.cornhub.com/model/rebelonion>)"
|
||||
|
||||
# Decimal color codes for contributors
|
||||
declare -A contributor_colors
|
||||
default_color="#ff25f9"
|
||||
contributor_colors["ibo"]="#ff7500"
|
||||
contributor_colors["aayush262"]="#5d689d"
|
||||
contributor_colors["Sadwhy"]="#ff7e95"
|
||||
contributor_colors["rebelonion"]="#d4e5ed"
|
||||
hex_to_decimal() { printf '%d' "0x${1#"#"}"; }
|
||||
|
||||
# Count recent commits and create an associative array
|
||||
declare -A recent_commit_counts
|
||||
while read -r count name; do
|
||||
recent_commit_counts["$name"]=$count
|
||||
done < <(echo "$COMMIT_LOG" | sed 's/%0A/\n/g' | grep -oP '(?<=~)[^[]*' | sort | uniq -c | sort -rn)
|
||||
# Fetch contributors from GitHub
|
||||
contributors=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/contributors")
|
||||
|
||||
# Create a sorted list of contributors based on recent commit counts
|
||||
sorted_contributors=$(for login in $(echo "$contributors" | jq -r '.[].login'); do
|
||||
user_info=$(fetch_user_details "$login")
|
||||
name=$(echo "$user_info" | cut -d'|' -f1)
|
||||
count=${recent_commit_counts["$name"]:-0}
|
||||
echo "$count|$login"
|
||||
done | sort -rn | cut -d'|' -f2)
|
||||
|
||||
# Initialize needed variables
|
||||
developers=""
|
||||
committers_count=0
|
||||
max_commits=0
|
||||
top_contributor=""
|
||||
top_contributor_count=0
|
||||
top_contributor_avatar=""
|
||||
embed_color=$default_color
|
||||
|
||||
# Process contributors in the new order
|
||||
while read -r login; do
|
||||
user_info=$(fetch_user_details "$login")
|
||||
name=$(echo "$user_info" | cut -d'|' -f1)
|
||||
login=$(echo "$user_info" | cut -d'|' -f2)
|
||||
avatar_url=$(echo "$user_info" | cut -d'|' -f3)
|
||||
|
||||
# Only process if they have recent commits
|
||||
commit_count=${recent_commit_counts["$name"]:-0}
|
||||
if [ $commit_count -gt 0 ]; then
|
||||
# Update top contributor information
|
||||
if [ $commit_count -gt $max_commits ]; then
|
||||
max_commits=$commit_count
|
||||
top_contributors=("$login")
|
||||
top_contributor_count=1
|
||||
top_contributor_avatar="$avatar_url"
|
||||
embed_color=$(hex_to_decimal "${contributor_colors[$name]:-$default_color}")
|
||||
elif [ $commit_count -eq $max_commits ]; then
|
||||
top_contributors+=("$login")
|
||||
top_contributor_count=$((top_contributor_count + 1))
|
||||
embed_color=$default_color
|
||||
fi
|
||||
|
||||
# Get commit count for this contributor on the dev branch
|
||||
branch_commit_count=$(git rev-list --count dev --author="$login")
|
||||
|
||||
extra_info="${additional_info[$name]}"
|
||||
if [ -n "$extra_info" ]; then
|
||||
extra_info=$(echo "$extra_info" | sed 's/\\n/\n- /g')
|
||||
fi
|
||||
|
||||
# Construct the developer entry
|
||||
developer_entry="◗ **${name}** ${extra_info}
|
||||
- Github: [${login}](https://github.com/${login})
|
||||
- Commits: ${branch_commit_count}"
|
||||
|
||||
# Add the entry to developers, with a newline if it's not the first entry
|
||||
if [ -n "$developers" ]; then
|
||||
developers="${developers}
|
||||
${developer_entry}"
|
||||
else
|
||||
developers="${developer_entry}"
|
||||
fi
|
||||
committers_count=$((committers_count + 1))
|
||||
fi
|
||||
done <<< "$sorted_contributors"
|
||||
|
||||
# Set the thumbnail URL and color based on top contributor(s)
|
||||
if [ $top_contributor_count -eq 1 ]; then
|
||||
thumbnail_url="$top_contributor_avatar"
|
||||
else
|
||||
thumbnail_url="https://i.imgur.com/5o3Y9Jb.gif"
|
||||
embed_color=$default_color
|
||||
fi
|
||||
|
||||
# Truncate field values
|
||||
max_length=1000
|
||||
commit_messages=$(echo "$COMMIT_LOG" | sed 's/%0A/\n/g; s/^/\n/')
|
||||
# Truncate commit messages if they are too long
|
||||
max_length=1900 # Adjust this value as needed
|
||||
if [ ${#developers} -gt $max_length ]; then
|
||||
developers="${developers:0:$max_length}... (truncated)"
|
||||
fi
|
||||
if [ ${#commit_messages} -gt $max_length ]; then
|
||||
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-alpha.apk" ${{ secrets.DISCORD_WEBHOOK }}
|
||||
|
||||
#Telegram
|
||||
curl -F "chat_id=${{ secrets.TELEGRAM_CHANNEL_ID }}" \
|
||||
-F "document=@app/build/outputs/apk/google/alpha/app-google-alpha.apk" \
|
||||
-F "caption=Alpha-Build: ${VERSION}: ${commit_messages}" \
|
||||
https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendDocument
|
||||
|
||||
# Construct Discord payload
|
||||
discord_data=$(jq -nc \
|
||||
--arg field_value "$commit_messages" \
|
||||
--arg author_value "$developers" \
|
||||
--arg footer_text "Version $VERSION" \
|
||||
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" \
|
||||
--arg thumbnail_url "$thumbnail_url" \
|
||||
--argjson embed_color "$embed_color" \
|
||||
'{
|
||||
"content": "<@&1225347048321191996>",
|
||||
"embeds": [
|
||||
{
|
||||
"title": "New Alpha-Build dropped",
|
||||
"color": $embed_color,
|
||||
"fields": [
|
||||
{
|
||||
"name": "Commits:",
|
||||
"value": $field_value,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "Developers:",
|
||||
"value": $author_value,
|
||||
"inline": false
|
||||
}
|
||||
],
|
||||
"footer": {
|
||||
"text": $footer_text
|
||||
},
|
||||
"timestamp": $timestamp,
|
||||
"thumbnail": {
|
||||
"url": $thumbnail_url
|
||||
}
|
||||
}
|
||||
],
|
||||
"attachments": []
|
||||
}')
|
||||
|
||||
# Send Discord message
|
||||
curl -H "Content-Type: application/json" \
|
||||
-d "$discord_data" \
|
||||
${{ secrets.DISCORD_WEBHOOK }}
|
||||
echo "You have only send an embed to discord due to SKIP_BUILD being set to true"
|
||||
|
||||
# Upload APK to Discord
|
||||
if [ "$SKIP_BUILD" != "true" ]; then
|
||||
curl -F "payload_json=${contentbody}" \
|
||||
-F "dantotsu_debug=@app/build/outputs/apk/google/alpha/app-google-alpha.apk" \
|
||||
${{ secrets.DISCORD_WEBHOOK }}
|
||||
else
|
||||
echo "Skipping APK upload to Discord due to SKIP_BUILD being set to true"
|
||||
fi
|
||||
|
||||
# Format commit messages for Telegram
|
||||
telegram_commit_messages=$(echo "$COMMIT_LOG" | sed 's/%0A/\n/g' | while read -r line; do
|
||||
message=$(echo "$line" | sed -E 's/● (.*) ~(.*) \[֍\]\((.*)\)/● \1 ~\2 <a href="\3">֍<\/a>/')
|
||||
message=$(echo "$message" | sed -E 's/\[#([0-9]+)\]\((https:\/\/github\.com\/[^)]+)\)/<a href="\2">#\1<\/a>/g')
|
||||
echo "$message"
|
||||
done)
|
||||
telegram_commit_messages="<blockquote>${telegram_commit_messages}</blockquote>"
|
||||
|
||||
# Upload APK to Telegram
|
||||
if [ "$SKIP_BUILD" != "true" ]; then
|
||||
APK_PATH="app/build/outputs/apk/google/alpha/app-google-alpha.apk"
|
||||
response=$(curl -sS -f -X POST \
|
||||
"https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendDocument" \
|
||||
-F "chat_id=${{ secrets.TELEGRAM_CHANNEL_ID }}" \
|
||||
-F "document=@$APK_PATH" \
|
||||
-F "caption=New Alpha-Build dropped 🔥
|
||||
|
||||
Commits:
|
||||
${telegram_commit_messages}
|
||||
version: ${VERSION}" \
|
||||
-F "parse_mode=HTML")
|
||||
else
|
||||
echo "Skipping Telegram message and APK upload due to SKIP_BUILD being set to true"
|
||||
fi
|
||||
|
||||
env:
|
||||
COMMIT_LOG: ${{ env.COMMIT_LOG }}
|
||||
VERSION: ${{ env.VERSION }}
|
||||
|
||||
675
LICENSE.md
675
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. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
This UPL terminates automatically if the terms and conditions are not followed by the licensee.
|
||||
|
||||
@@ -18,8 +18,8 @@ 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
|
||||
|
||||
}
|
||||
@@ -51,7 +51,7 @@ android {
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix ".beta"
|
||||
versionNameSuffix "-beta04"
|
||||
versionNameSuffix "-beta01"
|
||||
manifestPlaceholders.icon_placeholder = "@mipmap/ic_launcher_beta"
|
||||
manifestPlaceholders.icon_placeholder_round = "@mipmap/ic_launcher_beta_round"
|
||||
debuggable false
|
||||
@@ -101,6 +101,8 @@ dependencies {
|
||||
implementation 'androidx.preference:preference-ktx:1.2.1'
|
||||
implementation 'androidx.webkit:webkit:1.11.0'
|
||||
implementation "com.anggrayudi:storage:1.5.5"
|
||||
implementation "androidx.biometric:biometric:1.1.0"
|
||||
|
||||
|
||||
// Glide
|
||||
ext.glide_version = '4.16.0'
|
||||
|
||||
@@ -1,9 +1,40 @@
|
||||
package ani.dantotsu.others
|
||||
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Locale
|
||||
|
||||
object AppUpdater {
|
||||
suspend fun check(activity: FragmentActivity, post: Boolean = false) {
|
||||
//no-op
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class GithubResponse(
|
||||
@SerialName("html_url")
|
||||
val htmlUrl: String,
|
||||
@SerialName("tag_name")
|
||||
val tagName: String,
|
||||
val prerelease: Boolean,
|
||||
@SerialName("created_at")
|
||||
val createdAt: String,
|
||||
val body: String? = null,
|
||||
val assets: List<Asset>? = null
|
||||
) {
|
||||
@Serializable
|
||||
data class Asset(
|
||||
@SerialName("browser_download_url")
|
||||
val browserDownloadURL: String
|
||||
)
|
||||
|
||||
fun timeStamp(): Long {
|
||||
return dateFormat.parse(createdAt)!!.time
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import ani.dantotsu.util.Logger
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.MainScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.time.delay
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
@@ -69,7 +70,11 @@ object AppUpdater {
|
||||
)
|
||||
addView(
|
||||
TextView(activity).apply {
|
||||
val markWon = buildMarkwon(activity, false)
|
||||
val markWon = try { //slower phones can destroy the activity before this is done
|
||||
buildMarkwon(activity, false)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
return@runOnUiThread
|
||||
}
|
||||
markWon.setMarkdown(this, md)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -129,6 +129,8 @@
|
||||
<data android:scheme="file" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".others.calc.CalcActivity"
|
||||
android:parentActivityName=".MainActivity" />
|
||||
<activity android:name=".settings.FAQActivity" />
|
||||
<activity android:name=".settings.ReaderSettingsActivity" />
|
||||
<activity android:name=".settings.UserInterfaceSettingsActivity" />
|
||||
@@ -192,14 +194,15 @@
|
||||
android:label="Inbox Activity"
|
||||
android:parentActivityName=".MainActivity" />
|
||||
<activity
|
||||
android:name=".profile.activity.NotificationActivity"
|
||||
android:name=".profile.notification.NotificationActivity"
|
||||
android:label="Inbox Activity"
|
||||
android:parentActivityName=".MainActivity" />
|
||||
<activity
|
||||
android:name=".others.imagesearch.ImageSearchActivity"
|
||||
android:parentActivityName=".MainActivity" />
|
||||
<activity
|
||||
android:name=".util.MarkdownCreatorActivity"/>
|
||||
android:name=".util.ActivityMarkdownCreator"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
<activity android:name=".parsers.ParserTestActivity" />
|
||||
<activity
|
||||
android:name=".media.ReviewActivity"
|
||||
|
||||
@@ -38,8 +38,8 @@ import logcat.AndroidLogcatLogger
|
||||
import logcat.LogPriority
|
||||
import logcat.LogcatLogger
|
||||
import uy.kohesive.injekt.Injekt
|
||||
import uy.kohesive.injekt.api.addSingletonFactory
|
||||
import uy.kohesive.injekt.api.get
|
||||
import java.lang.IllegalStateException
|
||||
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
@@ -64,13 +64,19 @@ class App : MultiDexApplication() {
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
PrefManager.init(this)
|
||||
|
||||
val crashlytics =
|
||||
ani.dantotsu.connections.crashlytics.CrashlyticsFactory.createCrashlytics()
|
||||
Injekt.addSingletonFactory<CrashlyticsInterface> { 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<CrashlyticsInterface>()
|
||||
crashlytics.initialize(this)
|
||||
|
||||
val useMaterialYou: Boolean = PrefManager.getVal(PrefName.UseMaterialYou)
|
||||
if (useMaterialYou) {
|
||||
@@ -92,10 +98,6 @@ class App : MultiDexApplication() {
|
||||
}
|
||||
crashlytics.setCustomKey("device Info", SettingsActivity.getDeviceInfo())
|
||||
|
||||
Logger.init(this)
|
||||
Thread.setDefaultUncaughtExceptionHandler(FinalExceptionHandler())
|
||||
Logger.log(Log.WARN, "App: Logging started")
|
||||
|
||||
initializeNetwork()
|
||||
|
||||
setupNotificationChannels()
|
||||
@@ -154,6 +156,7 @@ class App : MultiDexApplication() {
|
||||
override fun onActivityCreated(p0: Activity, p1: Bundle?) {
|
||||
lastActivity = p0.javaClass.simpleName
|
||||
}
|
||||
|
||||
override fun onActivityStarted(p0: Activity) {
|
||||
currentActivity = p0
|
||||
}
|
||||
|
||||
@@ -84,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
|
||||
@@ -95,9 +96,12 @@ 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
|
||||
@@ -116,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
|
||||
@@ -343,7 +348,8 @@ open class BottomSheetDialogFragment : BottomSheetDialogFragment() {
|
||||
val behavior = BottomSheetBehavior.from(requireView().parent as View)
|
||||
behavior.state = BottomSheetBehavior.STATE_EXPANDED
|
||||
}
|
||||
window.navigationBarColor = requireContext().getThemeColor(com.google.android.material.R.attr.colorSurface)
|
||||
window.navigationBarColor =
|
||||
requireContext().getThemeColor(com.google.android.material.R.attr.colorSurface)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -642,7 +648,8 @@ fun ImageView.loadImage(file: FileUrl?, width: Int = 0, height: Int = 0) {
|
||||
.override(width, height).into(this)
|
||||
} else {
|
||||
val glideUrl = GlideUrl(file.url) { file.headers }
|
||||
Glide.with(this.context).load(glideUrl).transition(withCrossFade()).override(width, height)
|
||||
Glide.with(this.context).load(glideUrl).transition(withCrossFade())
|
||||
.override(width, height)
|
||||
.into(this)
|
||||
}
|
||||
}
|
||||
@@ -848,7 +855,7 @@ fun savePrefsToDownloads(
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("StringFormatMatches")
|
||||
fun savePrefs(serialized: String, path: String, title: String, context: Context): File? {
|
||||
var file = File(path, "$title.ani")
|
||||
var counter = 1
|
||||
@@ -868,6 +875,7 @@ fun savePrefs(serialized: String, path: String, title: String, context: Context)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("StringFormatMatches")
|
||||
fun savePrefs(
|
||||
serialized: String,
|
||||
path: String,
|
||||
@@ -914,7 +922,7 @@ fun shareImage(title: String, bitmap: Bitmap, context: Context) {
|
||||
intent.putExtra(Intent.EXTRA_STREAM, contentUri)
|
||||
context.startActivity(Intent.createChooser(intent, "Share $title"))
|
||||
}
|
||||
|
||||
@SuppressLint("StringFormatMatches")
|
||||
fun saveImage(image: Bitmap, path: String, imageFileName: String): File? {
|
||||
val imageFile = File(path, "$imageFileName.png")
|
||||
return try {
|
||||
@@ -1388,11 +1396,64 @@ fun blurImage(imageView: ImageView, banner: String?) {
|
||||
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
|
||||
@@ -1408,7 +1469,7 @@ fun buildMarkwon(
|
||||
.usePlugin(object : AbstractMarkwonPlugin() {
|
||||
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
|
||||
builder.linkResolver { _, link ->
|
||||
copyToClipboard(link, true)
|
||||
openOrCopyAnilistLink(link)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1441,7 +1502,6 @@ fun buildMarkwon(
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onLoadFailed(
|
||||
e: GlideException?,
|
||||
model: Any?,
|
||||
|
||||
@@ -48,9 +48,10 @@ import ani.dantotsu.home.NoInternet
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
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.profile.notification.NotificationActivity
|
||||
import ani.dantotsu.settings.ExtensionsActivity
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefManager.asLiveBool
|
||||
@@ -60,6 +61,7 @@ import ani.dantotsu.settings.saving.internal.PreferenceKeystore
|
||||
import ani.dantotsu.settings.saving.internal.PreferencePackager
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.snackbar.BaseTransientBottomBar
|
||||
import com.google.android.material.snackbar.Snackbar
|
||||
import com.google.android.material.textfield.TextInputEditText
|
||||
@@ -100,6 +102,20 @@ class MainActivity : AppCompatActivity() {
|
||||
setContentView(binding.root)
|
||||
|
||||
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
|
||||
@@ -297,6 +313,7 @@ class MainActivity : AppCompatActivity() {
|
||||
mainViewPager.adapter =
|
||||
ViewPagerAdapter(supportFragmentManager, lifecycle)
|
||||
mainViewPager.setPageTransformer(ZoomOutPageTransformer())
|
||||
mainViewPager.offscreenPageLimit = 1
|
||||
navbar.selectTabAt(selectedOption)
|
||||
navbar.setOnTabSelectListener(object :
|
||||
AnimatedBottomBar.OnTabSelectListener {
|
||||
@@ -350,7 +367,6 @@ class MainActivity : AppCompatActivity() {
|
||||
} else if (fragmentToLoad == "NOTIFICATIONS" && activityId != -1) {
|
||||
Logger.log("MainActivity, onCreate: $activityId")
|
||||
val notificationIntent = Intent(this, NotificationActivity::class.java).apply {
|
||||
putExtra("FRAGMENT_TO_LOAD", "NOTIFICATIONS")
|
||||
putExtra("activityId", activityId)
|
||||
}
|
||||
launched = true
|
||||
@@ -479,35 +495,28 @@ class MainActivity : AppCompatActivity() {
|
||||
val password = CharArray(16).apply { fill('0') }
|
||||
|
||||
// Inflate the dialog layout
|
||||
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.root)
|
||||
.setPositiveButton("OK", null)
|
||||
.setNegativeButton("Cancel") { dialog, _ ->
|
||||
val dialogView = DialogUserAgentBinding.inflate(layoutInflater).apply {
|
||||
userAgentTextBox.hint = "Password"
|
||||
subtitle.visibility = View.VISIBLE
|
||||
subtitle.text = getString(R.string.enter_password_to_decrypt_file)
|
||||
}
|
||||
customAlertDialog().apply {
|
||||
setTitle("Enter Password")
|
||||
setCustomView(dialogView.root)
|
||||
setPosButton(R.string.yes) {
|
||||
val editText = dialogView.userAgentTextBox
|
||||
if (editText.text?.isNotBlank() == true) {
|
||||
editText.text?.toString()?.trim()?.toCharArray(password)
|
||||
callback(password)
|
||||
} else {
|
||||
toast("Password cannot be empty")
|
||||
}
|
||||
}
|
||||
setNegButton(R.string.cancel) {
|
||||
password.fill('0')
|
||||
dialog.dismiss()
|
||||
callback(null)
|
||||
}
|
||||
.create()
|
||||
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
dialog.show()
|
||||
|
||||
// Override the positive button here
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
val editText = dialog.findViewById<TextInputEditText>(R.id.userAgentTextBox)
|
||||
if (editText?.text?.isNotBlank() == true) {
|
||||
editText.text?.toString()?.trim()?.toCharArray(password)
|
||||
dialog.dismiss()
|
||||
callback(password)
|
||||
} else {
|
||||
toast("Password cannot be empty")
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ interface DownloadAddonApiV2 {
|
||||
|
||||
fun setDownloadPath(context: Context, uri: Uri): String
|
||||
|
||||
fun getReadPath(context: Context, uri: Uri): String
|
||||
|
||||
suspend fun executeFFProbe(
|
||||
videoUrl: String,
|
||||
headers: Map<String, String> = emptyMap(),
|
||||
@@ -24,9 +26,15 @@ interface DownloadAddonApiV2 {
|
||||
statCallback: (Double) -> Unit
|
||||
): Long
|
||||
|
||||
suspend fun customFFMpeg(command: String, videoUrls: List<String>, logCallback: (String) -> Unit): Long
|
||||
|
||||
suspend fun customFFProbe(command: String, videoUrls: List<String>, logCallback: (String) -> Unit)
|
||||
|
||||
fun getState(sessionId: Long): String
|
||||
|
||||
fun getStackTrace(sessionId: Long): String?
|
||||
|
||||
fun hadError(sessionId: Long): Boolean
|
||||
|
||||
fun getFileExtension(): Pair<String, String> = Pair("mkv", "video/x-matroska")
|
||||
}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -60,10 +60,6 @@ class AppModule(val app: Application) : InjektModule {
|
||||
|
||||
addSingletonFactory { StandaloneDatabaseProvider(app) }
|
||||
|
||||
addSingletonFactory<CrashlyticsInterface> {
|
||||
ani.dantotsu.connections.crashlytics.CrashlyticsFactory.createCrashlytics()
|
||||
}
|
||||
|
||||
addSingletonFactory { MangaCache() }
|
||||
|
||||
ContextCompat.getMainExecutor(app).execute {
|
||||
|
||||
@@ -3,9 +3,9 @@ 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.connections.anilist.api.ToggleLike
|
||||
import ani.dantotsu.currContext
|
||||
import com.google.gson.Gson
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
class AnilistMutations {
|
||||
@@ -76,13 +76,52 @@ class AnilistMutations {
|
||||
|
||||
|
||||
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}}}}"
|
||||
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.RateReviewResponse>(query)
|
||||
}
|
||||
|
||||
suspend fun postActivity(text:String): String {
|
||||
suspend fun toggleFollow(id: Int): Query.ToggleFollow? {
|
||||
return executeQuery<Query.ToggleFollow>(
|
||||
"""mutation{ToggleFollow(userId:$id){id, isFollowing, isFollower}}"""
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun toggleLike(id: Int, type: String): ToggleLike? {
|
||||
return executeQuery<ToggleLike>(
|
||||
"""mutation Like{ToggleLikeV2(id:$id,type:$type){__typename}}"""
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun postActivity(text: String, edit: Int? = null): String {
|
||||
val encodedText = text.stringSanitizer()
|
||||
val query = "mutation{SaveTextActivity(text:$encodedText){siteUrl}}"
|
||||
val query =
|
||||
"mutation{SaveTextActivity(${if (edit != null) "id:$edit," else ""} text:$encodedText){siteUrl}}"
|
||||
val result = executeQuery<JsonObject>(query)
|
||||
val errors = result?.get("errors")
|
||||
return errors?.toString()
|
||||
?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success")
|
||||
}
|
||||
|
||||
suspend fun postMessage(
|
||||
userId: Int,
|
||||
text: String,
|
||||
edit: Int? = null,
|
||||
isPrivate: Boolean = false
|
||||
): String {
|
||||
val encodedText = text.replace("", "").stringSanitizer()
|
||||
val query =
|
||||
"mutation{SaveMessageActivity(${if (edit != null) "id:$edit," else ""} recipientId:$userId,message:$encodedText,private:$isPrivate){id}}"
|
||||
val result = executeQuery<JsonObject>(query)
|
||||
val errors = result?.get("errors")
|
||||
return errors?.toString()
|
||||
?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success")
|
||||
}
|
||||
|
||||
suspend fun postReply(activityId: Int, text: String, edit: Int? = null): String {
|
||||
val encodedText = text.stringSanitizer()
|
||||
val query =
|
||||
"mutation{SaveActivityReply(${if (edit != null) "id:$edit," else ""} activityId:$activityId,text:$encodedText){id}}"
|
||||
val result = executeQuery<JsonObject>(query)
|
||||
val errors = result?.get("errors")
|
||||
return errors?.toString()
|
||||
@@ -92,22 +131,29 @@ class AnilistMutations {
|
||||
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 query =
|
||||
"mutation{SaveReview(mediaId:$mediaId,summary:$encodedSummary,body:$encodedBody,score:$score){siteUrl}}"
|
||||
val result = executeQuery<JsonObject>(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}}"
|
||||
suspend fun deleteActivityReply(activityId: Int): Boolean {
|
||||
val query = "mutation{DeleteActivityReply(id:$activityId){deleted}}"
|
||||
val result = executeQuery<JsonObject>(query)
|
||||
val errors = result?.get("errors")
|
||||
return errors?.toString()
|
||||
?: (currContext()?.getString(ani.dantotsu.R.string.success) ?: "Success")
|
||||
return errors == null
|
||||
}
|
||||
|
||||
suspend fun deleteActivity(activityId: Int): Boolean {
|
||||
val query = "mutation{DeleteActivity(id:$activityId){deleted}}"
|
||||
val result = executeQuery<JsonObject>(query)
|
||||
val errors = result?.get("errors")
|
||||
return errors == null
|
||||
}
|
||||
|
||||
|
||||
private fun String.stringSanitizer(): String {
|
||||
val sb = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
@@ -6,6 +6,7 @@ import ani.dantotsu.checkGenreTime
|
||||
import ani.dantotsu.checkId
|
||||
import ani.dantotsu.connections.anilist.Anilist.authorRoles
|
||||
import ani.dantotsu.connections.anilist.Anilist.executeQuery
|
||||
import ani.dantotsu.connections.anilist.api.Activity
|
||||
import ani.dantotsu.connections.anilist.api.FeedResponse
|
||||
import ani.dantotsu.connections.anilist.api.FuzzyDate
|
||||
import ani.dantotsu.connections.anilist.api.NotificationResponse
|
||||
@@ -75,7 +76,7 @@ class AnilistQueries {
|
||||
media.cameFromContinue = false
|
||||
|
||||
val query =
|
||||
"""{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}}}}}"""
|
||||
"""{Media(id:${media.id}){id favourites popularity episodes chapters streamingEpisodes {title thumbnail url site} 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.Media>(query, force = true)
|
||||
@@ -90,7 +91,7 @@ class AnilistQueries {
|
||||
media.popularity = fetchedMedia.popularity
|
||||
media.startDate = fetchedMedia.startDate
|
||||
media.endDate = fetchedMedia.endDate
|
||||
|
||||
media.streamingEpisodes = fetchedMedia.streamingEpisodes
|
||||
if (fetchedMedia.genres != null) {
|
||||
media.genres = arrayListOf()
|
||||
fetchedMedia.genres?.forEach { i ->
|
||||
@@ -211,7 +212,7 @@ class AnilistQueries {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fetchedMedia.reviews?.nodes != null){
|
||||
if (fetchedMedia.reviews?.nodes != null) {
|
||||
media.review = fetchedMedia.reviews!!.nodes as ArrayList<Query.Review>
|
||||
}
|
||||
if (user?.mediaList?.isNotEmpty() == true) {
|
||||
@@ -376,6 +377,7 @@ class AnilistQueries {
|
||||
}
|
||||
return media
|
||||
}
|
||||
|
||||
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 } } } } } """
|
||||
}
|
||||
@@ -416,8 +418,68 @@ 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 getUserStatus(): ArrayList<User>? {
|
||||
val toShow: List<Boolean> =
|
||||
PrefManager.getVal(PrefName.HomeLayout)
|
||||
if (toShow.getOrNull(7) != true) return null
|
||||
var query = """{"""
|
||||
query += "Page1:${status(1)}Page2:${status(2)}"
|
||||
query += """}""".trimEnd(',')
|
||||
val response = executeQuery<Query.HomePageMedia>(query, show = true)
|
||||
val list = mutableListOf<User>()
|
||||
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 != true }
|
||||
.filter { it.createdAt * 1000L > threeDaysAgo }.toList()
|
||||
.sortedByDescending { it.createdAt }
|
||||
val anilistActivities = mutableListOf<User>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (anilistActivities.isEmpty() && Anilist.token != null){
|
||||
anilistActivities.add(0,
|
||||
User(
|
||||
Anilist.userid!!,
|
||||
Anilist.username!!,
|
||||
Anilist.avatar,
|
||||
Anilist.bg,
|
||||
activity = listOf()
|
||||
)
|
||||
)
|
||||
}
|
||||
list.addAll(0, anilistActivities)
|
||||
return list.toCollection(ArrayList())
|
||||
} else return null
|
||||
}
|
||||
|
||||
suspend fun initHomePage(): Map<String, ArrayList<*>> {
|
||||
val removeList = PrefManager.getCustomVal("removeList", setOf<Int>())
|
||||
val hidePrivate = PrefManager.getVal<Boolean>(PrefName.HidePrivate)
|
||||
val removedMedia = ArrayList<Media>()
|
||||
val toShow: List<Boolean> =
|
||||
PrefManager.getVal(PrefName.HomeLayout) // anime continue, anime fav, anime planned, manga continue, manga fav, manga planned, recommendations
|
||||
@@ -453,7 +515,6 @@ class AnilistQueries {
|
||||
"ANIME"
|
||||
)
|
||||
}, recommendationPlannedQueryManga: ${recommendationPlannedQuery("MANGA")}"""
|
||||
if (toShow.getOrNull(7) == true) query += "Page1:${status(1)}Page2:${status(2)}"
|
||||
query += """}""".trimEnd(',')
|
||||
|
||||
val response = executeQuery<Query.HomePageMedia>(query, show = true)
|
||||
@@ -468,7 +529,7 @@ class AnilistQueries {
|
||||
current?.lists?.forEach { li ->
|
||||
li.entries?.reversed()?.forEach {
|
||||
val m = Media(it)
|
||||
if (m.id !in removeList) {
|
||||
if (m.id !in removeList && if (hidePrivate) !m.isListPrivate else true) {
|
||||
m.cameFromContinue = true
|
||||
subMap[m.id] = m
|
||||
} else {
|
||||
@@ -480,7 +541,7 @@ class AnilistQueries {
|
||||
repeating?.lists?.forEach { li ->
|
||||
li.entries?.reversed()?.forEach {
|
||||
val m = Media(it)
|
||||
if (m.id !in removeList) {
|
||||
if (m.id !in removeList && if (hidePrivate) !m.isListPrivate else true) {
|
||||
m.cameFromContinue = true
|
||||
subMap[m.id] = m
|
||||
} else {
|
||||
@@ -519,7 +580,7 @@ class AnilistQueries {
|
||||
current?.lists?.forEach { li ->
|
||||
li.entries?.reversed()?.forEach {
|
||||
val m = Media(it)
|
||||
if (m.id !in removeList) {
|
||||
if (m.id !in removeList && if (hidePrivate) !m.isListPrivate else true) {
|
||||
m.cameFromContinue = true
|
||||
subMap[m.id] = m
|
||||
} else {
|
||||
@@ -552,7 +613,7 @@ class AnilistQueries {
|
||||
apiMediaList?.edges?.forEach {
|
||||
it.node?.let { i ->
|
||||
val m = Media(i).apply { isFav = true }
|
||||
if (m.id !in removeList) {
|
||||
if (m.id !in removeList && if (hidePrivate) !m.isListPrivate else true) {
|
||||
returnArray.add(m)
|
||||
} else {
|
||||
removedMedia.add(m)
|
||||
@@ -618,47 +679,8 @@ class AnilistQueries {
|
||||
list.sortByDescending { it.meanScore }
|
||||
returnMap["recommendations"] = list
|
||||
}
|
||||
if (toShow.getOrNull(7) == true) {
|
||||
val list = mutableListOf<User>()
|
||||
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<User>()
|
||||
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<Media>
|
||||
}
|
||||
returnMap["hidden"] = removedMedia.distinctBy { it.id }.toCollection(arrayListOf())
|
||||
return returnMap
|
||||
}
|
||||
|
||||
@@ -1034,152 +1056,110 @@ 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 mediaList(media1: Page?): ArrayList<Media> {
|
||||
val combinedList = arrayListOf<Media>()
|
||||
media1?.media?.mapTo(combinedList) { Media(it) }
|
||||
return combinedList
|
||||
}
|
||||
private fun getPreference(pref: PrefName): Boolean = PrefManager.getVal(pref)
|
||||
private fun buildQueryString(sort: String, type: String, format: String? = null, country: String? = null): String {
|
||||
val includeList = if (type == "ANIME" && !getPreference(PrefName.IncludeAnimeList)) "onList:false" else if (type == "MANGA" && !getPreference(PrefName.IncludeMangaList)) "onList:false" else ""
|
||||
val isAdult = if (getPreference(PrefName.AdultOnly)) "isAdult:true" else ""
|
||||
val formatFilter = format?.let { "format: $it, " } ?: ""
|
||||
val countryFilter = country?.let { "countryOfOrigin: $it, " } ?: ""
|
||||
|
||||
return """Page(page:1,perPage:50){
|
||||
pageInfo{hasNextPage total}
|
||||
media(sort:$sort, type:$type, $formatFilter $countryFilter $includeList $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 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}}}}"""
|
||||
val currentTime = System.currentTimeMillis() / 1000
|
||||
return """Page(page:$page,perPage:50){
|
||||
pageInfo{hasNextPage total}
|
||||
airingSchedules(airingAt_greater:0 airingAt_lesser:${currentTime - 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 queryAnimeList(): String {
|
||||
return """{
|
||||
recentUpdates:${recentAnimeUpdates(1)}
|
||||
recentUpdates2:${recentAnimeUpdates(2)}
|
||||
trendingMovies:${buildQueryString("POPULARITY_DESC", "ANIME", "MOVIE")}
|
||||
topRated:${buildQueryString("SCORE_DESC", "ANIME")}
|
||||
mostFav:${buildQueryString("FAVOURITES_DESC", "ANIME")}
|
||||
}"""
|
||||
}
|
||||
|
||||
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}}}"""
|
||||
private fun queryMangaList(): String {
|
||||
return """{
|
||||
trendingManga:${buildQueryString("POPULARITY_DESC", "MANGA", country = "JP")}
|
||||
trendingManhwa:${buildQueryString("POPULARITY_DESC", "MANGA", country = "KR")}
|
||||
trendingNovel:${buildQueryString("POPULARITY_DESC", "MANGA", format = "NOVEL", country = "JP")}
|
||||
topRated:${buildQueryString("SCORE_DESC", "MANGA")}
|
||||
mostFav:${buildQueryString("FAVOURITES_DESC", "MANGA")}
|
||||
|
||||
}"""
|
||||
}
|
||||
|
||||
suspend fun loadAnimeList(): Map<String, ArrayList<Media>> {
|
||||
val list = mutableMapOf<String, ArrayList<Media>>()
|
||||
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.AnimeList>(query(), force = true)?.data?.apply {
|
||||
|
||||
fun filterRecentUpdates(
|
||||
page: Page?,
|
||||
): ArrayList<Media> {
|
||||
val listOnly: Boolean = PrefManager.getVal(PrefName.RecentlyListOnly)
|
||||
val adultOnly: Boolean = PrefManager.getVal(PrefName.AdultOnly)
|
||||
val idArr = mutableListOf<Int>()
|
||||
list["recentUpdates"] = recentUpdates?.airingSchedules?.mapNotNull { i ->
|
||||
return page?.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)) {
|
||||
if (!idArr.contains(it.id)) {
|
||||
val shouldAdd = when {
|
||||
!listOnly && it.countryOfOrigin == "JP" && Anilist.adult && adultOnly && it.isAdult == true -> true
|
||||
!listOnly && !adultOnly && it.countryOfOrigin == "JP" && it.isAdult == false -> true
|
||||
listOnly && it.mediaListEntry != null -> true
|
||||
else -> false
|
||||
}
|
||||
if (shouldAdd) {
|
||||
idArr.add(it.id)
|
||||
Media(it)
|
||||
} else null
|
||||
else null
|
||||
} else null
|
||||
}
|
||||
} as ArrayList<Media>
|
||||
|
||||
list["trendingMovies"] = trendingMovies?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["topRated"] = topRated?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["mostFav"] = mostFav?.media?.map { Media(it) } as ArrayList<Media>
|
||||
|
||||
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
|
||||
}
|
||||
} as ArrayList<Media>)
|
||||
list["trendingMovies"]?.addAll(trendingMovies2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["topRated"]?.addAll(topRated2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["mostFav"]?.addAll(mostFav2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
}?.toCollection(ArrayList()) ?: arrayListOf()
|
||||
}
|
||||
executeQuery<Query.AnimeList>(queryAnimeList(), force = true)?.data?.apply {
|
||||
list["recentUpdates"] = filterRecentUpdates(recentUpdates)
|
||||
list["trendingMovies"] = mediaList(trendingMovies)
|
||||
list["topRated"] = mediaList(topRated)
|
||||
list["mostFav"] = mediaList(mostFav)
|
||||
}
|
||||
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<String, ArrayList<Media>> {
|
||||
val list = mutableMapOf<String, ArrayList<Media>>()
|
||||
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.MangaList>(queryMangaList(), force = true)?.data?.apply {
|
||||
list["trendingManga"] = mediaList(trendingManga)
|
||||
list["trendingManhwa"] = mediaList(trendingManhwa)
|
||||
list["trendingNovel"] = mediaList(trendingNovel)
|
||||
list["topRated"] = mediaList(topRated)
|
||||
list["mostFav"] = mediaList(mostFav)
|
||||
}
|
||||
|
||||
executeQuery<Query.MangaList>(query(), force = true)?.data?.apply {
|
||||
list["trendingManga"] = trendingManga?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["trendingManhwa"] = trendingManhwa?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["trendingNovel"] = trendingNovel?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["topRated"] = topRated?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["mostFav"] = mostFav?.media?.map { Media(it) } as ArrayList<Media>
|
||||
list["trendingManga"]?.addAll(trendingManga2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["trendingManhwa"]?.addAll(trendingManhwa2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["trendingNovel"]?.addAll(trendingNovel2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["topRated"]?.addAll(topRated2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
list["mostFav"]?.addAll(mostFav2?.media?.map { Media(it) } as ArrayList<Media>)
|
||||
|
||||
}
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
|
||||
suspend fun recentlyUpdated(
|
||||
greater: Long = 0,
|
||||
lesser: Long = System.currentTimeMillis() / 1000 - 10000
|
||||
@@ -1508,25 +1488,17 @@ Page(page:$page,perPage:50) {
|
||||
return author
|
||||
}
|
||||
|
||||
suspend fun getReviews(mediaId: Int, page: Int = 1, sort: String = "SCORE_DESC"): Query.ReviewsResponse? {
|
||||
suspend fun getReviews(
|
||||
mediaId: Int,
|
||||
page: Int = 1,
|
||||
sort: String = "SCORE_DESC"
|
||||
): Query.ReviewsResponse? {
|
||||
return executeQuery<Query.ReviewsResponse>(
|
||||
"""{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<Query.ToggleFollow>(
|
||||
"""mutation{ToggleFollow(userId:$id){id, isFollowing, isFollower}}"""
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun toggleLike(id: Int, type: String): ToggleLike? {
|
||||
return executeQuery<ToggleLike>(
|
||||
"""mutation Like{ToggleLikeV2(id:$id,type:$type){__typename}}"""
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getUserProfile(id: Int): Query.UserProfileResponse? {
|
||||
return executeQuery<Query.UserProfileResponse>(
|
||||
"""{followerPage:Page{followers(userId:$id){id}pageInfo{total}}followingPage:Page{following(userId:$id){id}pageInfo{total}}user:User(id:$id){id name about(asHtml:true)avatar{medium large}bannerImage isFollowing isFollower isBlocked favourites{anime{nodes{id coverImage{extraLarge large medium color}}}manga{nodes{id coverImage{extraLarge large medium color}}}characters{nodes{id name{first middle last full native alternative userPreferred}image{large medium}isFavourite}}staff{nodes{id name{first middle last full native alternative userPreferred}image{large medium}isFavourite}}studios{nodes{id name isFavourite}}}statistics{anime{count meanScore standardDeviation minutesWatched episodesWatched chaptersRead volumesRead}manga{count meanScore standardDeviation minutesWatched episodesWatched chaptersRead volumesRead}}siteUrl}}""",
|
||||
@@ -1585,11 +1557,13 @@ Page(page:$page,perPage:50) {
|
||||
suspend fun getNotifications(
|
||||
id: Int,
|
||||
page: Int = 1,
|
||||
resetNotification: Boolean = true
|
||||
resetNotification: Boolean = true,
|
||||
type: Boolean? = null
|
||||
): NotificationResponse? {
|
||||
val type_in = "type_in:[AIRING,MEDIA_MERGE,MEDIA_DELETION,MEDIA_DATA_CHANGE]"
|
||||
val reset = if (resetNotification) "true" else "false"
|
||||
val res = executeQuery<NotificationResponse>(
|
||||
"""{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,}}}}""",
|
||||
"""{User(id:$id){unreadNotificationCount}Page(page:$page,perPage:$ITEMS_PER_PAGE){pageInfo{currentPage,hasNextPage}notifications(resetNotificationCount:$reset , ${if (type == true) type_in else ""}){__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,}}}}""",
|
||||
force = true
|
||||
)
|
||||
if (res != null && resetNotification) {
|
||||
@@ -1612,7 +1586,7 @@ Page(page:$page,perPage:50) {
|
||||
else if (global) "isFollowing:false,hasRepliesOrTypeText:true,"
|
||||
else "isFollowing:true,"
|
||||
return executeQuery<FeedResponse>(
|
||||
"""{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
|
||||
)
|
||||
}
|
||||
@@ -1620,8 +1594,9 @@ Page(page:$page,perPage:50) {
|
||||
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}}}}}"""
|
||||
): 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,10 @@ class AnilistHomeViewModel : ViewModel() {
|
||||
MutableLiveData<ArrayList<User>>(null)
|
||||
|
||||
fun getUserStatus(): LiveData<ArrayList<User>> = userStatus
|
||||
suspend fun initUserStatus() {
|
||||
val res = Anilist.query.getUserStatus()
|
||||
res?.let { userStatus.postValue(it) }
|
||||
}
|
||||
|
||||
private val hidden: MutableLiveData<ArrayList<Media>> =
|
||||
MutableLiveData<ArrayList<Media>>(null)
|
||||
@@ -98,7 +102,6 @@ class AnilistHomeViewModel : ViewModel() {
|
||||
res["plannedManga"]?.let { mangaPlanned.postValue(it as ArrayList<Media>?) }
|
||||
res["recommendations"]?.let { recommendation.postValue(it as ArrayList<Media>?) }
|
||||
res["hidden"]?.let { hidden.postValue(it as ArrayList<Media>?) }
|
||||
res["status"]?.let { userStatus.postValue(it as ArrayList<User>?) }
|
||||
}
|
||||
|
||||
suspend fun loadMain(context: FragmentActivity) {
|
||||
|
||||
@@ -163,13 +163,9 @@ class Query {
|
||||
@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?,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -181,15 +177,10 @@ class Query {
|
||||
@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?,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ data class Media(
|
||||
@SerialName("externalLinks") var externalLinks: List<MediaExternalLink>?,
|
||||
|
||||
// Data and links to legal streaming episodes on external sites
|
||||
// @SerialName("streamingEpisodes") var streamingEpisodes: List<MediaStreamingEpisode>?,
|
||||
@SerialName("streamingEpisodes") var streamingEpisodes: List<MediaStreamingEpisode>?,
|
||||
|
||||
// The ranking of the media in a particular time span and format compared to other media
|
||||
// @SerialName("rankings") var rankings: List<MediaRank>?,
|
||||
@@ -239,7 +239,20 @@ data class AiringSchedule(
|
||||
// The associate media of the airing episode
|
||||
@SerialName("media") var media: Media?,
|
||||
)
|
||||
@Serializable
|
||||
data class MediaStreamingEpisode(
|
||||
// The title of the episode
|
||||
@SerialName("title") var title: String?,
|
||||
|
||||
// The thumbnail image of the episode
|
||||
@SerialName("thumbnail") var thumbnail: String?,
|
||||
|
||||
// The url of the episode
|
||||
@SerialName("url") var url: String?,
|
||||
|
||||
// The site location of the streaming episode
|
||||
@SerialName("site") var site: String?,
|
||||
)
|
||||
@Serializable
|
||||
data class MediaCoverImage(
|
||||
// The cover image url of the media at its largest size. If this size isn't available, large will be provided instead.
|
||||
|
||||
@@ -111,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
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package ani.dantotsu.connections.github
|
||||
|
||||
import ani.dantotsu.Mapper
|
||||
import ani.dantotsu.client
|
||||
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 Forks {
|
||||
|
||||
fun getForks(): Array<Developer> {
|
||||
var forks = arrayOf<Developer>()
|
||||
runBlocking(Dispatchers.IO) {
|
||||
val res =
|
||||
client.get("https://api.github.com/repos/rebelonion/Dantotsu/forks?sort=stargazers")
|
||||
.parsed<JsonArray>().map {
|
||||
Mapper.json.decodeFromJsonElement<GithubResponse>(it)
|
||||
}
|
||||
res.forEach {
|
||||
forks = forks.plus(
|
||||
Developer(
|
||||
it.name,
|
||||
it.owner.avatarUrl,
|
||||
it.owner.login,
|
||||
it.htmlUrl
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return forks
|
||||
}
|
||||
|
||||
|
||||
@Serializable
|
||||
data class GithubResponse(
|
||||
@SerialName("name")
|
||||
val name: String,
|
||||
val owner: Owner,
|
||||
@SerialName("html_url")
|
||||
val htmlUrl: String,
|
||||
) {
|
||||
@Serializable
|
||||
data class Owner(
|
||||
@SerialName("login")
|
||||
val login: String,
|
||||
@SerialName("avatar_url")
|
||||
val avatarUrl: String
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ class DownloadCompat {
|
||||
Logger.log(e)
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
return OfflineAnimeModel(
|
||||
"unknown",
|
||||
downloadedType.titleName,
|
||||
"0",
|
||||
"??",
|
||||
"??",
|
||||
@@ -188,7 +188,7 @@ class DownloadCompat {
|
||||
Logger.log(e)
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
return OfflineMangaModel(
|
||||
"unknown",
|
||||
downloadedType.titleName,
|
||||
"0",
|
||||
"??",
|
||||
"??",
|
||||
@@ -347,7 +347,7 @@ class DownloadCompat {
|
||||
}
|
||||
|
||||
@Deprecated("external storage is deprecated, use SAF instead")
|
||||
fun removeDownloadCompat(context: Context, downloadedType: DownloadedType) {
|
||||
fun removeDownloadCompat(context: Context, downloadedType: DownloadedType, toast: Boolean) {
|
||||
val directory = if (downloadedType.type == MediaType.MANGA) {
|
||||
File(
|
||||
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
|
||||
@@ -368,10 +368,13 @@ class DownloadCompat {
|
||||
// Check if the directory exists and delete it recursively
|
||||
if (directory.exists()) {
|
||||
val deleted = directory.deleteRecursively()
|
||||
if (deleted) {
|
||||
Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT).show()
|
||||
if (toast) {
|
||||
if (deleted) {
|
||||
Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(context, "Failed to delete directory", Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import com.anggrayudi.storage.callback.FolderCallback
|
||||
import com.anggrayudi.storage.file.deleteRecursively
|
||||
import com.anggrayudi.storage.file.findFolder
|
||||
import com.anggrayudi.storage.file.moveFolderTo
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
@@ -60,7 +59,7 @@ class DownloadsManager(private val context: Context) {
|
||||
toast: Boolean = true,
|
||||
onFinished: () -> Unit
|
||||
) {
|
||||
removeDownloadCompat(context, downloadedType)
|
||||
removeDownloadCompat(context, downloadedType, toast)
|
||||
downloadsList.remove(downloadedType)
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
removeDirectory(downloadedType, toast)
|
||||
@@ -279,6 +278,7 @@ class DownloadsManager(private val context: Context) {
|
||||
* @param type the type of media
|
||||
* @return the base directory
|
||||
*/
|
||||
@Synchronized
|
||||
private fun getBaseDirectory(context: Context, type: MediaType): DocumentFile? {
|
||||
val baseDirectory = Uri.parse(PrefManager.getVal<String>(PrefName.DownloadsDir))
|
||||
if (baseDirectory == Uri.EMPTY) return null
|
||||
@@ -307,6 +307,7 @@ class DownloadsManager(private val context: Context) {
|
||||
* @param chapter the chapter of the media
|
||||
* @return the subdirectory
|
||||
*/
|
||||
@Synchronized
|
||||
fun getSubDirectory(
|
||||
context: Context,
|
||||
type: MediaType,
|
||||
@@ -344,23 +345,34 @@ class DownloadsManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun getBaseDirectory(context: Context): DocumentFile? {
|
||||
val baseDirectory = Uri.parse(PrefManager.getVal<String>(PrefName.DownloadsDir))
|
||||
if (baseDirectory == Uri.EMPTY) return null
|
||||
return DocumentFile.fromTreeUri(context, baseDirectory)
|
||||
val base = DocumentFile.fromTreeUri(context, baseDirectory) ?: return null
|
||||
return base.findOrCreateFolder(BASE_LOCATION, false)
|
||||
}
|
||||
|
||||
private val lock = Any()
|
||||
|
||||
private fun DocumentFile.findOrCreateFolder(
|
||||
name: String, overwrite: Boolean
|
||||
): DocumentFile? {
|
||||
return if (overwrite) {
|
||||
findFolder(name.findValidName())?.delete()
|
||||
createDirectory(name.findValidName())
|
||||
} else {
|
||||
findFolder(name.findValidName()) ?: createDirectory(name.findValidName())
|
||||
val validName = name.findValidName()
|
||||
synchronized(lock) {
|
||||
return if (overwrite) {
|
||||
findFolder(validName)?.delete()
|
||||
createDirectory(validName)
|
||||
} else {
|
||||
val folder = findFolder(validName)
|
||||
folder ?: createDirectory(validName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun DocumentFile.findFolder(name: String): DocumentFile? =
|
||||
listFiles().find { it.name == name && it.isDirectory }
|
||||
|
||||
private const val RATIO_THRESHOLD = 95
|
||||
fun Media.compareName(name: String): Boolean {
|
||||
val mainName = mainName().findValidName().lowercase()
|
||||
@@ -379,7 +391,7 @@ class DownloadsManager(private val context: Context) {
|
||||
|
||||
private const val RESERVED_CHARS = "|\\?*<\":>+[]/'"
|
||||
fun String?.findValidName(): String {
|
||||
return this?.filterNot { RESERVED_CHARS.contains(it) } ?: ""
|
||||
return this?.replace("/", "_")?.filterNot { RESERVED_CHARS.contains(it) } ?: ""
|
||||
}
|
||||
|
||||
data class DownloadedType(
|
||||
|
||||
@@ -26,6 +26,7 @@ import ani.dantotsu.download.DownloadedType
|
||||
import ani.dantotsu.download.DownloadsManager
|
||||
import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory
|
||||
import ani.dantotsu.download.anime.AnimeDownloaderService.AnimeDownloadTask.Companion.getTaskName
|
||||
import ani.dantotsu.download.findValidName
|
||||
import ani.dantotsu.media.Media
|
||||
import ani.dantotsu.media.MediaType
|
||||
import ani.dantotsu.media.anime.AnimeWatchFragment
|
||||
@@ -180,7 +181,6 @@ class AnimeDownloaderService : Service() {
|
||||
}
|
||||
|
||||
private fun updateNotification() {
|
||||
// Update the notification to reflect the current state of the queue
|
||||
val pendingDownloads = AnimeServiceDataSingleton.downloadQueue.size
|
||||
val text = if (pendingDownloads > 0) {
|
||||
"Pending downloads: $pendingDownloads"
|
||||
@@ -200,8 +200,8 @@ class AnimeDownloaderService : Service() {
|
||||
|
||||
@androidx.annotation.OptIn(UnstableApi::class)
|
||||
suspend fun download(task: AnimeDownloadTask) {
|
||||
try {
|
||||
withContext(Dispatchers.Main) {
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val notifi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
ContextCompat.checkSelfPermission(
|
||||
this@AnimeDownloaderService,
|
||||
@@ -213,25 +213,39 @@ class AnimeDownloaderService : Service() {
|
||||
|
||||
builder.setContentText("Downloading ${getTaskName(task.title, task.episode)}")
|
||||
if (notifi) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
|
||||
val outputDir = getSubDirectory(
|
||||
val baseOutputDir = getSubDirectory(
|
||||
this@AnimeDownloaderService,
|
||||
MediaType.ANIME,
|
||||
false,
|
||||
task.title
|
||||
) ?: throw Exception("Failed to create output directory")
|
||||
val outputDir = getSubDirectory(
|
||||
this@AnimeDownloaderService,
|
||||
MediaType.ANIME,
|
||||
true,
|
||||
task.title,
|
||||
task.episode
|
||||
) ?: throw Exception("Failed to create output directory")
|
||||
|
||||
outputDir.findFile("${task.getTaskName()}.mkv")?.delete()
|
||||
val extension = ffExtension!!.getFileExtension()
|
||||
outputDir.findFile("${task.getTaskName().findValidName()}.${extension.first}")
|
||||
?.delete()
|
||||
|
||||
val outputFile =
|
||||
outputDir.createFile("video/x-matroska", "${task.getTaskName()}.mkv")
|
||||
outputDir.createFile(
|
||||
extension.second,
|
||||
"${task.getTaskName()}.${extension.first}"
|
||||
)
|
||||
?: throw Exception("Failed to create output file")
|
||||
|
||||
var percent = 0
|
||||
var totalLength = 0.0
|
||||
val path = ffExtension!!.setDownloadPath(
|
||||
val path = ffExtension.setDownloadPath(
|
||||
this@AnimeDownloaderService,
|
||||
outputFile.uri
|
||||
)
|
||||
@@ -270,7 +284,7 @@ class AnimeDownloaderService : Service() {
|
||||
currentTasks.find { it.getTaskName() == task.getTaskName() }?.sessionId =
|
||||
ffTask
|
||||
|
||||
saveMediaInfo(task)
|
||||
saveMediaInfo(task, baseOutputDir)
|
||||
|
||||
// periodically check if the download is complete
|
||||
while (ffExtension.getState(ffTask) != "COMPLETED") {
|
||||
@@ -284,7 +298,11 @@ class AnimeDownloaderService : Service() {
|
||||
)
|
||||
} Download failed"
|
||||
)
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
if (notifi) {
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
toast("${getTaskName(task.title, task.episode)} Download failed")
|
||||
Logger.log("Download failed: ${ffExtension.getStackTrace(ffTask)}")
|
||||
downloadsManager.removeDownload(
|
||||
@@ -317,7 +335,9 @@ class AnimeDownloaderService : Service() {
|
||||
percent.coerceAtMost(99)
|
||||
)
|
||||
if (notifi) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
kotlinx.coroutines.delay(2000)
|
||||
}
|
||||
@@ -332,14 +352,19 @@ class AnimeDownloaderService : Service() {
|
||||
)
|
||||
} Download failed"
|
||||
)
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
if (notifi) {
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
snackString("${getTaskName(task.title, task.episode)} Download failed")
|
||||
downloadsManager.removeDownload(
|
||||
DownloadedType(
|
||||
task.title,
|
||||
task.episode,
|
||||
MediaType.ANIME,
|
||||
)
|
||||
MediaType.ANIME
|
||||
),
|
||||
false
|
||||
) {}
|
||||
Injekt.get<CrashlyticsInterface>().logException(
|
||||
Exception(
|
||||
@@ -363,7 +388,11 @@ class AnimeDownloaderService : Service() {
|
||||
)
|
||||
} Download completed"
|
||||
)
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
if (notifi) {
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
snackString("${getTaskName(task.title, task.episode)} Download completed")
|
||||
PrefManager.getAnimeDownloadPreferences().edit().putString(
|
||||
task.getTaskName(),
|
||||
@@ -381,23 +410,20 @@ class AnimeDownloaderService : Service() {
|
||||
broadcastDownloadFinished(task.episode)
|
||||
} else throw Exception("Download failed")
|
||||
|
||||
} catch (e: Exception) {
|
||||
if (e.message?.contains("Coroutine was cancelled") == false) { //wut
|
||||
Logger.log("Exception while downloading file: ${e.message}")
|
||||
snackString("Exception while downloading file: ${e.message}")
|
||||
e.printStackTrace()
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
}
|
||||
broadcastDownloadFailed(task.episode)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (e.message?.contains("Coroutine was cancelled") == false) { //wut
|
||||
Logger.log("Exception while downloading file: ${e.message}")
|
||||
snackString("Exception while downloading file: ${e.message}")
|
||||
e.printStackTrace()
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
}
|
||||
broadcastDownloadFailed(task.episode)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveMediaInfo(task: AnimeDownloadTask) {
|
||||
private fun saveMediaInfo(task: AnimeDownloadTask, directory: DocumentFile) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
val directory =
|
||||
getSubDirectory(this@AnimeDownloaderService, MediaType.ANIME, false, task.title)
|
||||
?: throw Exception("Directory not found")
|
||||
directory.findFile("media.json")?.forceDelete(this@AnimeDownloaderService)
|
||||
val file = directory.createFile("application/json", "media.json")
|
||||
?: throw Exception("File not created")
|
||||
|
||||
@@ -30,6 +30,7 @@ import ani.dantotsu.bottomBar
|
||||
import ani.dantotsu.connections.crashlytics.CrashlyticsInterface
|
||||
import ani.dantotsu.currActivity
|
||||
import ani.dantotsu.currContext
|
||||
import ani.dantotsu.download.DownloadCompat
|
||||
import ani.dantotsu.download.DownloadCompat.Companion.loadMediaCompat
|
||||
import ani.dantotsu.download.DownloadCompat.Companion.loadOfflineAnimeModelCompat
|
||||
import ani.dantotsu.download.DownloadedType
|
||||
@@ -48,6 +49,7 @@ import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.anggrayudi.storage.file.openInputStream
|
||||
import com.google.android.material.card.MaterialCardView
|
||||
import com.google.android.material.imageview.ShapeableImageView
|
||||
@@ -202,25 +204,22 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener {
|
||||
val type: MediaType = MediaType.ANIME
|
||||
|
||||
// Alert dialog to confirm deletion
|
||||
val builder =
|
||||
androidx.appcompat.app.AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
builder.setTitle("Delete ${item.title}?")
|
||||
builder.setMessage("Are you sure you want to delete ${item.title}?")
|
||||
builder.setPositiveButton("Yes") { _, _ ->
|
||||
downloadManager.removeMedia(item.title, type)
|
||||
val mediaIds =
|
||||
PrefManager.getAnimeDownloadPreferences().all?.filter { it.key.contains(item.title) }?.values
|
||||
?: emptySet()
|
||||
if (mediaIds.isEmpty()) {
|
||||
snackString("No media found") // if this happens, terrible things have happened
|
||||
requireContext().customAlertDialog().apply {
|
||||
setTitle("Delete ${item.title}?")
|
||||
setMessage("Are you sure you want to delete ${item.title}?")
|
||||
setPosButton(R.string.yes) {
|
||||
downloadManager.removeMedia(item.title, type)
|
||||
val mediaIds = PrefManager.getAnimeDownloadPreferences().all?.filter { it.key.contains(item.title) }?.values ?: emptySet()
|
||||
if (mediaIds.isEmpty()) {
|
||||
snackString("No media found") // if this happens, terrible things have happened
|
||||
}
|
||||
getDownloads()
|
||||
}
|
||||
getDownloads()
|
||||
setNegButton(R.string.no) {
|
||||
// Do nothing
|
||||
}
|
||||
show()
|
||||
}
|
||||
builder.setNegativeButton("No") { _, _ ->
|
||||
// Do nothing
|
||||
}
|
||||
val dialog = builder.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -319,17 +318,20 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener {
|
||||
)
|
||||
val gson = GsonBuilder()
|
||||
.registerTypeAdapter(SChapter::class.java, InstanceCreator<SChapter> {
|
||||
SChapterImpl() // Provide an instance of SChapterImpl
|
||||
SChapterImpl()
|
||||
})
|
||||
.registerTypeAdapter(SAnime::class.java, InstanceCreator<SAnime> {
|
||||
SAnimeImpl() // Provide an instance of SAnimeImpl
|
||||
SAnimeImpl()
|
||||
})
|
||||
.registerTypeAdapter(SEpisode::class.java, InstanceCreator<SEpisode> {
|
||||
SEpisodeImpl() // Provide an instance of SEpisodeImpl
|
||||
SEpisodeImpl()
|
||||
})
|
||||
.create()
|
||||
val media = directory?.findFile("media.json")
|
||||
?: return loadMediaCompat(downloadedType)
|
||||
if (media == null) {
|
||||
Logger.log("No media.json found at ${directory?.uri?.path}")
|
||||
return loadMediaCompat(downloadedType)
|
||||
}
|
||||
val mediaJson =
|
||||
media.openInputStream(context ?: currContext()!!)?.bufferedReader().use {
|
||||
it?.readText()
|
||||
@@ -394,6 +396,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener {
|
||||
bannerUri
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Logger.log(e)
|
||||
return try {
|
||||
loadOfflineAnimeModelCompat(downloadedType)
|
||||
} catch (e: Exception) {
|
||||
@@ -401,7 +404,7 @@ class OfflineAnimeFragment : Fragment(), OfflineAnimeSearchListener {
|
||||
Logger.log(e)
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
OfflineAnimeModel(
|
||||
"unknown",
|
||||
downloadedType.titleName,
|
||||
"0",
|
||||
"??",
|
||||
"??",
|
||||
|
||||
@@ -134,15 +134,15 @@ class MangaDownloaderService : Service() {
|
||||
mutex.withLock {
|
||||
downloadJobs[task.chapter] = job
|
||||
}
|
||||
job.join() // Wait for the job to complete before continuing to the next task
|
||||
job.join()
|
||||
mutex.withLock {
|
||||
downloadJobs.remove(task.chapter)
|
||||
}
|
||||
updateNotification() // Update the notification after each task is completed
|
||||
updateNotification()
|
||||
}
|
||||
if (MangaServiceDataSingleton.downloadQueue.isEmpty()) {
|
||||
withContext(Dispatchers.Main) {
|
||||
stopSelf() // Stop the service when the queue is empty
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ class MangaDownloaderService : Service() {
|
||||
|
||||
suspend fun download(task: DownloadTask) {
|
||||
try {
|
||||
withContext(Dispatchers.Main) {
|
||||
withContext(Dispatchers.IO) {
|
||||
val notifi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
ContextCompat.checkSelfPermission(
|
||||
this@MangaDownloaderService,
|
||||
@@ -194,18 +194,27 @@ class MangaDownloaderService : Service() {
|
||||
val deferredMap = mutableMapOf<Int, Deferred<Bitmap?>>()
|
||||
builder.setContentText("Downloading ${task.title} - ${task.chapter}")
|
||||
if (notifi) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
|
||||
getSubDirectory(
|
||||
val baseOutputDir = getSubDirectory(
|
||||
this@MangaDownloaderService,
|
||||
MediaType.MANGA,
|
||||
false,
|
||||
task.title
|
||||
) ?: throw Exception("Base output directory not found")
|
||||
val outputDir = getSubDirectory(
|
||||
this@MangaDownloaderService,
|
||||
MediaType.MANGA,
|
||||
false,
|
||||
task.title,
|
||||
task.chapter
|
||||
)?.deleteRecursively(this@MangaDownloaderService)
|
||||
) ?: throw Exception("Output directory not found")
|
||||
|
||||
outputDir.deleteRecursively(this@MangaDownloaderService, true)
|
||||
|
||||
// Loop through each ImageData object from the task
|
||||
var farthest = 0
|
||||
for ((index, image) in task.imageData.withIndex()) {
|
||||
if (deferredMap.size >= task.simultaneousDownloads) {
|
||||
@@ -226,30 +235,36 @@ class MangaDownloaderService : Service() {
|
||||
}
|
||||
|
||||
if (bitmap != null) {
|
||||
saveToDisk("$index.jpg", bitmap, task.title, task.chapter)
|
||||
saveToDisk("$index.jpg", outputDir, bitmap)
|
||||
}
|
||||
farthest++
|
||||
|
||||
builder.setProgress(task.imageData.size, farthest, false)
|
||||
|
||||
broadcastDownloadProgress(
|
||||
task.chapter,
|
||||
farthest * 100 / task.imageData.size
|
||||
)
|
||||
if (notifi) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
withContext(Dispatchers.Main) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
|
||||
bitmap
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for any remaining deferred to complete
|
||||
deferredMap.values.awaitAll()
|
||||
|
||||
builder.setContentText("${task.title} - ${task.chapter} Download complete")
|
||||
.setProgress(0, 0, false)
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
withContext(Dispatchers.Main) {
|
||||
builder.setContentText("${task.title} - ${task.chapter} Download complete")
|
||||
.setProgress(0, 0, false)
|
||||
if (notifi) {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
}
|
||||
|
||||
saveMediaInfo(task)
|
||||
saveMediaInfo(task, baseOutputDir)
|
||||
downloadsManager.addDownload(
|
||||
DownloadedType(
|
||||
task.title,
|
||||
@@ -269,17 +284,16 @@ class MangaDownloaderService : Service() {
|
||||
}
|
||||
|
||||
|
||||
private fun saveToDisk(fileName: String, bitmap: Bitmap, title: String, chapter: String) {
|
||||
private fun saveToDisk(
|
||||
fileName: String,
|
||||
directory: DocumentFile,
|
||||
bitmap: Bitmap
|
||||
) {
|
||||
try {
|
||||
// Define the directory within the private external storage space
|
||||
val directory = getSubDirectory(this, MediaType.MANGA, false, title, chapter)
|
||||
?: throw Exception("Directory not found")
|
||||
directory.findFile(fileName)?.forceDelete(this)
|
||||
// Create a file reference within that directory for the image
|
||||
val file =
|
||||
directory.createFile("image/jpeg", fileName) ?: throw Exception("File not created")
|
||||
|
||||
// Use a FileOutputStream to write the bitmap to the file
|
||||
file.openOutputStream(this, false).use { outputStream ->
|
||||
if (outputStream == null) throw Exception("Output stream is null")
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
|
||||
@@ -292,11 +306,8 @@ class MangaDownloaderService : Service() {
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
private fun saveMediaInfo(task: DownloadTask) {
|
||||
private fun saveMediaInfo(task: DownloadTask, directory: DocumentFile) {
|
||||
launchIO {
|
||||
val directory =
|
||||
getSubDirectory(this@MangaDownloaderService, MediaType.MANGA, false, task.title)
|
||||
?: throw Exception("Directory not found")
|
||||
directory.findFile("media.json")?.forceDelete(this@MangaDownloaderService)
|
||||
val file = directory.createFile("application/json", "media.json")
|
||||
?: throw Exception("File not created")
|
||||
|
||||
@@ -46,6 +46,7 @@ import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.anggrayudi.storage.file.openInputStream
|
||||
import com.google.android.material.card.MaterialCardView
|
||||
import com.google.android.material.imageview.ShapeableImageView
|
||||
@@ -171,7 +172,11 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
val item = adapter.getItem(position) as OfflineMangaModel
|
||||
val media =
|
||||
downloadManager.mangaDownloadedTypes.firstOrNull { it.titleName.compareName(item.title) }
|
||||
?: downloadManager.novelDownloadedTypes.firstOrNull { it.titleName.compareName(item.title) }
|
||||
?: downloadManager.novelDownloadedTypes.firstOrNull {
|
||||
it.titleName.compareName(
|
||||
item.title
|
||||
)
|
||||
}
|
||||
media?.let {
|
||||
lifecycleScope.launch {
|
||||
ContextCompat.startActivity(
|
||||
@@ -197,19 +202,15 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
MediaType.NOVEL
|
||||
}
|
||||
// Alert dialog to confirm deletion
|
||||
val builder =
|
||||
androidx.appcompat.app.AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
builder.setTitle("Delete ${item.title}?")
|
||||
builder.setMessage("Are you sure you want to delete ${item.title}?")
|
||||
builder.setPositiveButton("Yes") { _, _ ->
|
||||
downloadManager.removeMedia(item.title, type)
|
||||
getDownloads()
|
||||
}
|
||||
builder.setNegativeButton("No") { _, _ ->
|
||||
// Do nothing
|
||||
}
|
||||
val dialog = builder.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
requireContext().customAlertDialog().apply {
|
||||
setTitle("Delete ${item.title}?")
|
||||
setMessage("Are you sure you want to delete ${item.title}?")
|
||||
setPosButton(R.string.yes) {
|
||||
downloadManager.removeMedia(item.title, type)
|
||||
getDownloads()
|
||||
}
|
||||
setNegButton(R.string.no)
|
||||
}.show()
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -279,10 +280,12 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
downloads = listOf()
|
||||
downloadsJob = Job()
|
||||
CoroutineScope(Dispatchers.IO + downloadsJob).launch {
|
||||
val mangaTitles = downloadManager.mangaDownloadedTypes.map { it.titleName.findValidName() }.distinct()
|
||||
val mangaTitles =
|
||||
downloadManager.mangaDownloadedTypes.map { it.titleName.findValidName() }.distinct()
|
||||
val newMangaDownloads = mutableListOf<OfflineMangaModel>()
|
||||
for (title in mangaTitles) {
|
||||
val tDownloads = downloadManager.mangaDownloadedTypes.filter { it.titleName.findValidName() == title }
|
||||
val tDownloads =
|
||||
downloadManager.mangaDownloadedTypes.filter { it.titleName.findValidName() == title }
|
||||
val download = tDownloads.firstOrNull() ?: continue
|
||||
val offlineMangaModel = loadOfflineMangaModel(download)
|
||||
newMangaDownloads += offlineMangaModel
|
||||
@@ -291,7 +294,8 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
val novelTitles = downloadManager.novelDownloadedTypes.map { it.titleName }.distinct()
|
||||
val newNovelDownloads = mutableListOf<OfflineMangaModel>()
|
||||
for (title in novelTitles) {
|
||||
val tDownloads = downloadManager.novelDownloadedTypes.filter { it.titleName.findValidName() == title }
|
||||
val tDownloads =
|
||||
downloadManager.novelDownloadedTypes.filter { it.titleName.findValidName() == title }
|
||||
val download = tDownloads.firstOrNull() ?: continue
|
||||
val offlineMangaModel = loadOfflineMangaModel(download)
|
||||
newNovelDownloads += offlineMangaModel
|
||||
@@ -320,11 +324,14 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
)
|
||||
val gson = GsonBuilder()
|
||||
.registerTypeAdapter(SChapter::class.java, InstanceCreator<SChapter> {
|
||||
SChapterImpl() // Provide an instance of SChapterImpl
|
||||
SChapterImpl()
|
||||
})
|
||||
.create()
|
||||
val media = directory?.findFile("media.json")
|
||||
?: return DownloadCompat.loadMediaCompat(downloadedType)
|
||||
if (media == null) {
|
||||
Logger.log("No media.json found at ${directory?.uri?.path}")
|
||||
return DownloadCompat.loadMediaCompat(downloadedType)
|
||||
}
|
||||
val mediaJson =
|
||||
media.openInputStream(context ?: currContext()!!)?.bufferedReader().use {
|
||||
it?.readText()
|
||||
@@ -340,7 +347,6 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
|
||||
private suspend fun loadOfflineMangaModel(downloadedType: DownloadedType): OfflineMangaModel {
|
||||
val type = downloadedType.type.asText()
|
||||
//load media.json and convert to media class with gson
|
||||
try {
|
||||
val directory = getSubDirectory(
|
||||
context ?: currContext()!!, downloadedType.type,
|
||||
@@ -378,6 +384,7 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
bannerUri
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Logger.log(e)
|
||||
return try {
|
||||
loadOfflineMangaModelCompat(downloadedType)
|
||||
} catch (e: Exception) {
|
||||
@@ -385,7 +392,7 @@ class OfflineMangaFragment : Fragment(), OfflineMangaSearchListener {
|
||||
Logger.log(e)
|
||||
Injekt.get<CrashlyticsInterface>().logException(e)
|
||||
return OfflineMangaModel(
|
||||
"unknown",
|
||||
downloadedType.titleName,
|
||||
"0",
|
||||
"??",
|
||||
"??",
|
||||
|
||||
@@ -239,6 +239,13 @@ class NovelDownloaderService : Service() {
|
||||
return@withContext
|
||||
}
|
||||
|
||||
val baseDirectory = getSubDirectory(
|
||||
this@NovelDownloaderService,
|
||||
MediaType.NOVEL,
|
||||
false,
|
||||
task.title
|
||||
) ?: throw Exception("Directory not found")
|
||||
|
||||
// Start the download
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
@@ -334,7 +341,7 @@ class NovelDownloaderService : Service() {
|
||||
notificationManager.notify(NOTIFICATION_ID, builder.build())
|
||||
}
|
||||
|
||||
saveMediaInfo(task)
|
||||
saveMediaInfo(task, baseDirectory)
|
||||
downloadsManager.addDownload(
|
||||
DownloadedType(
|
||||
task.title,
|
||||
@@ -354,15 +361,8 @@ class NovelDownloaderService : Service() {
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
private fun saveMediaInfo(task: DownloadTask) {
|
||||
private fun saveMediaInfo(task: DownloadTask, directory: DocumentFile) {
|
||||
launchIO {
|
||||
val directory =
|
||||
getSubDirectory(
|
||||
this@NovelDownloaderService,
|
||||
MediaType.NOVEL,
|
||||
false,
|
||||
task.title
|
||||
) ?: throw Exception("Directory not found")
|
||||
directory.findFile("media.json")?.forceDelete(this@NovelDownloaderService)
|
||||
val file = directory.createFile("application/json", "media.json")
|
||||
?: throw Exception("File not created")
|
||||
|
||||
@@ -3,7 +3,6 @@ package ani.dantotsu.download.video
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
@@ -29,10 +28,10 @@ import ani.dantotsu.download.anime.AnimeDownloaderService
|
||||
import ani.dantotsu.download.anime.AnimeServiceDataSingleton
|
||||
import ani.dantotsu.media.Media
|
||||
import ani.dantotsu.media.MediaType
|
||||
import ani.dantotsu.parsers.Subtitle
|
||||
import ani.dantotsu.parsers.Video
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import eu.kanade.tachiyomi.network.NetworkHelper
|
||||
import uy.kohesive.injekt.Injekt
|
||||
import uy.kohesive.injekt.api.get
|
||||
@@ -72,19 +71,19 @@ object Helper {
|
||||
episodeImage
|
||||
)
|
||||
|
||||
val downloadsManger = Injekt.get<DownloadsManager>()
|
||||
val downloadCheck = downloadsManger
|
||||
val downloadsManager = Injekt.get<DownloadsManager>()
|
||||
val downloadCheck = downloadsManager
|
||||
.queryDownload(title, episode, MediaType.ANIME)
|
||||
|
||||
if (downloadCheck) {
|
||||
AlertDialog.Builder(context, R.style.MyPopup)
|
||||
.setTitle("Download Exists")
|
||||
.setMessage("A download for this episode already exists. Do you want to overwrite it?")
|
||||
.setPositiveButton("Yes") { _, _ ->
|
||||
context.customAlertDialog().apply {
|
||||
setTitle("Download Exists")
|
||||
setMessage("A download for this episode already exists. Do you want to overwrite it?")
|
||||
setPosButton(R.string.yes) {
|
||||
PrefManager.getAnimeDownloadPreferences().edit()
|
||||
.remove(animeDownloadTask.getTaskName())
|
||||
.apply()
|
||||
downloadsManger.removeDownload(
|
||||
downloadsManager.removeDownload(
|
||||
DownloadedType(
|
||||
title,
|
||||
episode,
|
||||
@@ -99,8 +98,9 @@ object Helper {
|
||||
}
|
||||
}
|
||||
}
|
||||
.setNegativeButton("No") { _, _ -> }
|
||||
.show()
|
||||
setNegButton(R.string.no)
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
AnimeServiceDataSingleton.downloadQueue.offer(animeDownloadTask)
|
||||
if (!AnimeServiceDataSingleton.isServiceRunning) {
|
||||
|
||||
@@ -111,8 +111,8 @@ class AnimePageAdapter : RecyclerView.Adapter<AnimePageAdapter.AnimePageViewHold
|
||||
trendingBinding.searchBar.performClick()
|
||||
}
|
||||
|
||||
trendingBinding.notificationCount.visibility =
|
||||
if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE
|
||||
trendingBinding.notificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
|
||||
listOf(
|
||||
@@ -268,11 +268,12 @@ class AnimePageAdapter : RecyclerView.Adapter<AnimePageAdapter.AnimePageViewHold
|
||||
LinearLayoutManager.HORIZONTAL,
|
||||
false
|
||||
)
|
||||
|
||||
more.setOnClickListener {
|
||||
MediaListViewActivity.passedMedia = media.toCollection(ArrayList())
|
||||
ContextCompat.startActivity(
|
||||
it.context, Intent(it.context, MediaListViewActivity::class.java)
|
||||
.putExtra("title", string)
|
||||
.putExtra("media", media as ArrayList<Media>),
|
||||
.putExtra("title", string),
|
||||
null
|
||||
)
|
||||
}
|
||||
@@ -294,8 +295,8 @@ class AnimePageAdapter : RecyclerView.Adapter<AnimePageAdapter.AnimePageViewHold
|
||||
|
||||
fun updateNotificationCount() {
|
||||
if (this::binding.isInitialized) {
|
||||
trendingBinding.notificationCount.visibility =
|
||||
if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE
|
||||
trendingBinding.notificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ class HomeFragment : Fragment() {
|
||||
)
|
||||
binding.homeUserDataProgressBar.visibility = View.GONE
|
||||
binding.homeNotificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
binding.homeNotificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
|
||||
binding.homeAnimeList.setOnClickListener {
|
||||
@@ -233,10 +234,10 @@ class HomeFragment : Fragment() {
|
||||
false
|
||||
)
|
||||
more.setOnClickListener { i ->
|
||||
MediaListViewActivity.passedMedia = it
|
||||
ContextCompat.startActivity(
|
||||
i.context, Intent(i.context, MediaListViewActivity::class.java)
|
||||
.putExtra("title", string)
|
||||
.putExtra("media", it),
|
||||
.putExtra("title", string),
|
||||
null
|
||||
)
|
||||
}
|
||||
@@ -393,11 +394,11 @@ class HomeFragment : Fragment() {
|
||||
true
|
||||
}
|
||||
binding.homeHiddenItemsMore.setSafeOnClickListener { _ ->
|
||||
MediaListViewActivity.passedMedia = it
|
||||
ContextCompat.startActivity(
|
||||
requireActivity(),
|
||||
Intent(requireActivity(), MediaListViewActivity::class.java)
|
||||
.putExtra("title", getString(R.string.hidden))
|
||||
.putExtra("media", it),
|
||||
.putExtra("title", getString(R.string.hidden)),
|
||||
null
|
||||
)
|
||||
}
|
||||
@@ -481,10 +482,12 @@ class HomeFragment : Fragment() {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
model.setListImages()
|
||||
}
|
||||
|
||||
var empty = true
|
||||
val homeLayoutShow: List<Boolean> =
|
||||
PrefManager.getVal(PrefName.HomeLayout)
|
||||
model.initHomePage()
|
||||
model.initUserStatus()
|
||||
(array.indices).forEach { i ->
|
||||
if (homeLayoutShow.elementAt(i)) {
|
||||
empty = false
|
||||
@@ -508,6 +511,7 @@ class HomeFragment : Fragment() {
|
||||
if (!model.loaded) Refresh.activity[1]!!.postValue(true)
|
||||
if (_binding != null) {
|
||||
binding.homeNotificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
binding.homeNotificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
}
|
||||
super.onResume()
|
||||
|
||||
@@ -12,12 +12,14 @@ import androidx.documentfile.provider.DocumentFile
|
||||
import androidx.fragment.app.Fragment
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.databinding.DialogUserAgentBinding
|
||||
import ani.dantotsu.databinding.FragmentLoginBinding
|
||||
import ani.dantotsu.openLinkInBrowser
|
||||
import ani.dantotsu.settings.saving.internal.PreferenceKeystore
|
||||
import ani.dantotsu.settings.saving.internal.PreferencePackager
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.textfield.TextInputEditText
|
||||
|
||||
class LoginFragment : Fragment() {
|
||||
@@ -94,38 +96,31 @@ class LoginFragment : Fragment() {
|
||||
val password = CharArray(16).apply { fill('0') }
|
||||
|
||||
// Inflate the dialog layout
|
||||
val dialogView =
|
||||
LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_user_agent, null)
|
||||
dialogView.findViewById<TextInputEditText>(R.id.userAgentTextBox)?.hint = "Password"
|
||||
val subtitleTextView = dialogView.findViewById<TextView>(R.id.subtitle)
|
||||
subtitleTextView?.visibility = View.VISIBLE
|
||||
subtitleTextView?.text = "Enter your password to decrypt the file"
|
||||
val dialogView = DialogUserAgentBinding.inflate(layoutInflater).apply {
|
||||
userAgentTextBox.hint = "Password"
|
||||
subtitle.visibility = View.VISIBLE
|
||||
subtitle.text = getString(R.string.enter_password_to_decrypt_file)
|
||||
}
|
||||
|
||||
val dialog = AlertDialog.Builder(requireActivity(), R.style.MyPopup)
|
||||
.setTitle("Enter Password")
|
||||
.setView(dialogView)
|
||||
.setPositiveButton("OK", null)
|
||||
.setNegativeButton("Cancel") { dialog, _ ->
|
||||
requireActivity().customAlertDialog().apply {
|
||||
setTitle("Enter Password")
|
||||
setCustomView(dialogView.root)
|
||||
setPosButton(R.string.ok){
|
||||
val editText = dialogView.userAgentTextBox
|
||||
if (editText.text?.isNotBlank() == true) {
|
||||
editText.text?.toString()?.trim()?.toCharArray(password)
|
||||
callback(password)
|
||||
} else {
|
||||
toast("Password cannot be empty")
|
||||
}
|
||||
}
|
||||
setNegButton(R.string.cancel) {
|
||||
password.fill('0')
|
||||
dialog.dismiss()
|
||||
callback(null)
|
||||
}
|
||||
.create()
|
||||
}.show()
|
||||
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
dialog.show()
|
||||
|
||||
// Override the positive button here
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
val editText = dialog.findViewById<TextInputEditText>(R.id.userAgentTextBox)
|
||||
if (editText?.text?.isNotBlank() == true) {
|
||||
editText.text?.toString()?.trim()?.toCharArray(password)
|
||||
dialog.dismiss()
|
||||
callback(password)
|
||||
} else {
|
||||
toast("Password cannot be empty")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun restartApp() {
|
||||
|
||||
@@ -80,6 +80,7 @@ class MangaPageAdapter : RecyclerView.Adapter<MangaPageAdapter.MangaPageViewHold
|
||||
|
||||
updateAvatar()
|
||||
trendingBinding.notificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
trendingBinding.searchBar.hint = "MANGA"
|
||||
trendingBinding.searchBarText.setOnClickListener {
|
||||
@@ -271,10 +272,10 @@ class MangaPageAdapter : RecyclerView.Adapter<MangaPageAdapter.MangaPageViewHold
|
||||
false
|
||||
)
|
||||
more.setOnClickListener {
|
||||
MediaListViewActivity.passedMedia = media.toCollection(ArrayList())
|
||||
ContextCompat.startActivity(
|
||||
it.context, Intent(it.context, MediaListViewActivity::class.java)
|
||||
.putExtra("title", string)
|
||||
.putExtra("media", media as ArrayList<Media>),
|
||||
.putExtra("title", string),
|
||||
null
|
||||
)
|
||||
}
|
||||
@@ -296,8 +297,8 @@ class MangaPageAdapter : RecyclerView.Adapter<MangaPageAdapter.MangaPageViewHold
|
||||
|
||||
fun updateNotificationCount() {
|
||||
if (this::binding.isInitialized) {
|
||||
trendingBinding.notificationCount.visibility =
|
||||
if (Anilist.unreadNotificationCount > 0) View.VISIBLE else View.GONE
|
||||
trendingBinding.notificationCount.isVisible = Anilist.unreadNotificationCount > 0
|
||||
&& PrefManager.getVal<Boolean>(PrefName.ShowNotificationRedDot) == true
|
||||
trendingBinding.notificationCount.text = Anilist.unreadNotificationCount.toString()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.profile.User
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.Logger
|
||||
|
||||
class StatusActivity : AppCompatActivity(), StoriesCallback {
|
||||
private lateinit var activity: ArrayList<User>
|
||||
@@ -44,10 +46,14 @@ class StatusActivity : AppCompatActivity(), StoriesCallback {
|
||||
|
||||
val key = "activities"
|
||||
val watchedActivity = PrefManager.getCustomVal<Set<Int>>(key, setOf())
|
||||
val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity )
|
||||
val startIndex = if ( startFrom > 0) startFrom else 0
|
||||
binding.stories.setStoriesList(activity[position].activity, this, startIndex + 1)
|
||||
|
||||
if (activity.getOrNull(position) != null) {
|
||||
val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity )
|
||||
val startIndex = if ( startFrom > 0) startFrom else 0
|
||||
binding.stories.setStoriesList(activity[position].activity, this, startIndex + 1)
|
||||
} else {
|
||||
Logger.log("index out of bounds for position $position of size ${activity.size}")
|
||||
finish()
|
||||
}
|
||||
|
||||
}
|
||||
private fun findFirstNonMatch(watchedActivity: Set<Int>, activity: List<Activity>): Int {
|
||||
@@ -58,13 +64,16 @@ class StatusActivity : AppCompatActivity(), StoriesCallback {
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
binding.stories.pause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
binding.stories.resume()
|
||||
if (hasWindowFocus())
|
||||
binding.stories.resume()
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
@@ -92,7 +101,7 @@ class StatusActivity : AppCompatActivity(), StoriesCallback {
|
||||
|
||||
override fun onStoriesStart() {
|
||||
position -= 1
|
||||
if (position >= 0) {
|
||||
if (position >= 0 && activity[position].activity.isNotEmpty()) {
|
||||
val key = "activities"
|
||||
val watchedActivity = PrefManager.getCustomVal<Set<Int>>(key, setOf())
|
||||
val startFrom = findFirstNonMatch(watchedActivity, activity[position].activity )
|
||||
|
||||
@@ -30,6 +30,7 @@ import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.User
|
||||
import ani.dantotsu.profile.UsersDialogFragment
|
||||
import ani.dantotsu.profile.activity.ActivityItemBuilder
|
||||
import ani.dantotsu.profile.activity.RepliesBottomDialog
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
@@ -74,8 +75,7 @@ class Stories @JvmOverloads constructor(
|
||||
|
||||
if (context is StoriesCallback) storiesListener = context as StoriesCallback
|
||||
|
||||
binding.leftTouchPanel.setOnTouchListener(this)
|
||||
binding.rightTouchPanel.setOnTouchListener(this)
|
||||
binding.touchPanel.setOnTouchListener(this)
|
||||
}
|
||||
|
||||
|
||||
@@ -264,49 +264,7 @@ class Stories @JvmOverloads constructor(
|
||||
}
|
||||
|
||||
|
||||
private var startClickTime = 0L
|
||||
private var startX = 0f
|
||||
private var startY = 0f
|
||||
private var isLongPress = false
|
||||
private val swipeThreshold = 100
|
||||
override fun onTouch(view: View?, event: MotionEvent?): Boolean {
|
||||
val maxClickDuration = 200
|
||||
when (event?.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
startX = event.x
|
||||
startY = event.y
|
||||
startClickTime = Calendar.getInstance().timeInMillis
|
||||
pause()
|
||||
isLongPress = false
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val deltaX = event.x - startX
|
||||
val deltaY = event.y - startY
|
||||
if (!isLongPress && (abs(deltaX) > swipeThreshold || abs(deltaY) > swipeThreshold)) {
|
||||
isLongPress = true
|
||||
}
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_UP -> {
|
||||
val clickDuration = Calendar.getInstance().timeInMillis - startClickTime
|
||||
if (clickDuration < maxClickDuration && !isLongPress) {
|
||||
when (view?.id) {
|
||||
R.id.leftTouchPanel -> leftPanelTouch()
|
||||
R.id.rightTouchPanel -> rightPanelTouch()
|
||||
}
|
||||
} else {
|
||||
resume()
|
||||
}
|
||||
val deltaX = event.x - startX
|
||||
if (abs(deltaX) > swipeThreshold) {
|
||||
if (deltaX > 0) onStoriesPrevious()
|
||||
else onStoriesCompleted()
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun rightPanelTouch() {
|
||||
Logger.log("rightPanelTouch: $storyIndex")
|
||||
@@ -359,6 +317,7 @@ class Stories @JvmOverloads constructor(
|
||||
timer.resume()
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
private fun loadStory(story: Activity) {
|
||||
val key = "activities"
|
||||
val set = PrefManager.getCustomVal<Set<Int>>(key, setOf()).plus((story.id))
|
||||
@@ -374,6 +333,15 @@ class Stories @JvmOverloads constructor(
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
binding.textActivity.setOnTouchListener { v, event ->
|
||||
onTouchView(v, event, true)
|
||||
v.onTouchEvent(event)
|
||||
}
|
||||
binding.textActivityContainer.setOnTouchListener { v, event ->
|
||||
onTouchView(v, event, true)
|
||||
v.onTouchEvent(event)
|
||||
}
|
||||
fun visible(isList: Boolean) {
|
||||
binding.textActivity.isVisible = !isList
|
||||
binding.textActivityContainer.isVisible = !isList
|
||||
@@ -397,15 +365,15 @@ class Stories @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
} ${story.progress ?: story.media?.title?.userPreferred} " +
|
||||
if (
|
||||
story.status?.contains("completed") == false &&
|
||||
!story.status.contains("plans") &&
|
||||
!story.status.contains("repeating")
|
||||
) {
|
||||
"of ${story.media?.title?.userPreferred}"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
if (
|
||||
story.status?.contains("completed") == false &&
|
||||
!story.status.contains("plans") &&
|
||||
!story.status.contains("repeating")
|
||||
) {
|
||||
"of ${story.media?.title?.userPreferred}"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
binding.infoText.text = text
|
||||
val bannerAnimations: Boolean = PrefManager.getVal(PrefName.BannerAnimations)
|
||||
blurImage(
|
||||
@@ -455,14 +423,14 @@ class Stories @JvmOverloads constructor(
|
||||
}
|
||||
val likeColor = ContextCompat.getColor(context, R.color.yt_red)
|
||||
val notLikeColor = ContextCompat.getColor(context, R.color.bg_opp)
|
||||
binding.replyCount.text = story.replyCount.toString()
|
||||
binding.activityReplies.setColorFilter(ContextCompat.getColor(context, R.color.bg_opp))
|
||||
binding.activityRepliesContainer.setOnClickListener {
|
||||
RepliesBottomDialog.newInstance(story.id)
|
||||
.show(activity.supportFragmentManager, "replies")
|
||||
}
|
||||
binding.activityLike.setColorFilter(if (story.isLiked == true) likeColor else notLikeColor)
|
||||
binding.replyCount.text = story.replyCount.toString()
|
||||
binding.activityLikeCount.text = story.likeCount.toString()
|
||||
binding.activityReplies.setColorFilter(ContextCompat.getColor(context, R.color.bg_opp))
|
||||
binding.activityLikeContainer.setOnClickListener {
|
||||
like()
|
||||
}
|
||||
@@ -484,7 +452,7 @@ class Stories @JvmOverloads constructor(
|
||||
val notLikeColor = ContextCompat.getColor(context, R.color.bg_opp)
|
||||
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
scope.launch {
|
||||
val res = Anilist.query.toggleLike(story.id, "ACTIVITY")
|
||||
val res = Anilist.mutation.toggleLike(story.id, "ACTIVITY")
|
||||
withContext(Dispatchers.Main) {
|
||||
if (res != null) {
|
||||
if (story.isLiked == true) {
|
||||
@@ -502,4 +470,66 @@ class Stories @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
private var startClickTime = 0L
|
||||
private var startX = 0f
|
||||
private var startY = 0f
|
||||
private var isLongPress = false
|
||||
private val swipeThreshold = 100
|
||||
override fun onTouch(view: View, event: MotionEvent): Boolean {
|
||||
onTouchView(view, event)
|
||||
return true
|
||||
}
|
||||
private fun onTouchView(view: View, event: MotionEvent, isText: Boolean = false){
|
||||
val maxClickDuration = 200
|
||||
val screenWidth = view.width
|
||||
val leftHalf = screenWidth / 2
|
||||
val leftQuarter = screenWidth * 0.15
|
||||
val rightQuarter = screenWidth * 0.85
|
||||
when (event.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
startX = event.x
|
||||
startY = event.y
|
||||
startClickTime = Calendar.getInstance().timeInMillis
|
||||
pause()
|
||||
isLongPress = false
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val deltaX = event.x - startX
|
||||
val deltaY = event.y - startY
|
||||
if (!isLongPress && (abs(deltaX) > swipeThreshold || abs(deltaY) > swipeThreshold)) {
|
||||
isLongPress = true
|
||||
}
|
||||
}
|
||||
MotionEvent.ACTION_UP -> {
|
||||
val clickDuration = Calendar.getInstance().timeInMillis - startClickTime
|
||||
if (isText) {
|
||||
if (clickDuration < maxClickDuration && !isLongPress) {
|
||||
if (event.x < leftQuarter) {
|
||||
leftPanelTouch()
|
||||
} else if (event.x > rightQuarter) {
|
||||
rightPanelTouch()
|
||||
}
|
||||
} else {
|
||||
resume()
|
||||
}
|
||||
} else {
|
||||
if (clickDuration < maxClickDuration && !isLongPress) {
|
||||
if (event.x < leftHalf) {
|
||||
leftPanelTouch()
|
||||
} else {
|
||||
rightPanelTouch()
|
||||
}
|
||||
} else {
|
||||
resume()
|
||||
}
|
||||
}
|
||||
val deltaX = event.x - startX
|
||||
if (abs(deltaX) > swipeThreshold) {
|
||||
if (deltaX > 0) onStoriesPrevious()
|
||||
else onStoriesCompleted()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package ani.dantotsu.home.status
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
@@ -15,6 +14,8 @@ import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.User
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
|
||||
class UserStatusAdapter(private val user: ArrayList<User>) :
|
||||
RecyclerView.Adapter<UserStatusAdapter.UsersViewHolder>() {
|
||||
@@ -23,6 +24,10 @@ class UserStatusAdapter(private val user: ArrayList<User>) :
|
||||
RecyclerView.ViewHolder(binding.root) {
|
||||
init {
|
||||
itemView.setOnClickListener {
|
||||
if (user[bindingAdapterPosition].activity.isEmpty()) {
|
||||
snackString("No activity")
|
||||
return@setOnClickListener
|
||||
}
|
||||
StatusActivity.user = user
|
||||
ContextCompat.startActivity(
|
||||
itemView.context,
|
||||
@@ -34,14 +39,23 @@ class UserStatusAdapter(private val user: ArrayList<User>) :
|
||||
)
|
||||
}
|
||||
itemView.setOnLongClickListener {
|
||||
ContextCompat.startActivity(
|
||||
itemView.context,
|
||||
Intent(
|
||||
if (user[bindingAdapterPosition].id == Anilist.userid) {
|
||||
ContextCompat.startActivity(
|
||||
itemView.context,
|
||||
ProfileActivity::class.java
|
||||
).putExtra("userId", user[bindingAdapterPosition].id),
|
||||
null
|
||||
)
|
||||
Intent(itemView.context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "activity"),
|
||||
null
|
||||
)
|
||||
}else{
|
||||
ContextCompat.startActivity(
|
||||
itemView.context,
|
||||
Intent(
|
||||
itemView.context,
|
||||
ProfileActivity::class.java
|
||||
).putExtra("userId", user[bindingAdapterPosition].id),
|
||||
null
|
||||
)
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ class CalendarActivity : AppCompatActivity() {
|
||||
private lateinit var binding: ActivityListBinding
|
||||
private val scope = lifecycleScope
|
||||
private var selectedTabIdx = 1
|
||||
private var showOnlyLibrary = false
|
||||
private val model: OtherDetailsViewModel by viewModels()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -38,8 +39,6 @@ class CalendarActivity : AppCompatActivity() {
|
||||
ThemeManager(this).applyTheme()
|
||||
binding = ActivityListBinding.inflate(layoutInflater)
|
||||
|
||||
|
||||
|
||||
val primaryColor = getThemeColor(com.google.android.material.R.attr.colorSurface)
|
||||
val primaryTextColor = getThemeColor(com.google.android.material.R.attr.colorPrimary)
|
||||
val secondaryTextColor = getThemeColor(com.google.android.material.R.attr.colorOutline)
|
||||
@@ -79,6 +78,17 @@ class CalendarActivity : AppCompatActivity() {
|
||||
override fun onTabReselected(tab: TabLayout.Tab?) {}
|
||||
})
|
||||
|
||||
binding.listed.setOnClickListener {
|
||||
showOnlyLibrary = !showOnlyLibrary
|
||||
binding.listed.setImageResource(
|
||||
if (showOnlyLibrary) R.drawable.ic_round_collections_bookmark_24
|
||||
else R.drawable.ic_round_library_books_24
|
||||
)
|
||||
scope.launch {
|
||||
model.loadCalendar(showOnlyLibrary)
|
||||
}
|
||||
}
|
||||
|
||||
model.getCalendar().observe(this) {
|
||||
if (it != null) {
|
||||
binding.listProgressBar.visibility = View.GONE
|
||||
@@ -97,11 +107,10 @@ class CalendarActivity : AppCompatActivity() {
|
||||
live.observe(this) {
|
||||
if (it) {
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { model.loadCalendar() }
|
||||
withContext(Dispatchers.IO) { model.loadCalendar(showOnlyLibrary) }
|
||||
live.postValue(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.core.content.ContextCompat
|
||||
import androidx.core.util.Pair
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import ani.dantotsu.copyToClipboard
|
||||
import ani.dantotsu.databinding.ItemCharacterBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.setAnimation
|
||||
@@ -55,6 +56,7 @@ class CharacterAdapter(
|
||||
).toBundle()
|
||||
)
|
||||
}
|
||||
itemView.setOnLongClickListener { copyToClipboard(characterList[bindingAdapterPosition].name ?: ""); true }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.graphics.Bitmap
|
||||
import ani.dantotsu.connections.anilist.api.FuzzyDate
|
||||
import ani.dantotsu.connections.anilist.api.MediaEdge
|
||||
import ani.dantotsu.connections.anilist.api.MediaList
|
||||
import ani.dantotsu.connections.anilist.api.MediaStreamingEpisode
|
||||
import ani.dantotsu.connections.anilist.api.MediaType
|
||||
import ani.dantotsu.connections.anilist.api.Query
|
||||
import ani.dantotsu.media.anime.Anime
|
||||
@@ -76,7 +77,7 @@ data class Media(
|
||||
var nameMAL: String? = null,
|
||||
var shareLink: String? = null,
|
||||
var selected: Selected? = null,
|
||||
|
||||
var streamingEpisodes: List<MediaStreamingEpisode>? = null,
|
||||
var idKitsu: String? = null,
|
||||
|
||||
var cameFromContinue: Boolean = false
|
||||
|
||||
@@ -424,7 +424,8 @@ class MediaDetailsActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedLi
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
navBar.selectTabAt(selected)
|
||||
if (::navBar.isInitialized)
|
||||
navBar.selectTabAt(selected)
|
||||
super.onResume()
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import ani.dantotsu.media.anime.Episode
|
||||
import ani.dantotsu.media.anime.SelectorDialogFragment
|
||||
import ani.dantotsu.media.manga.MangaChapter
|
||||
import ani.dantotsu.others.AniSkip
|
||||
import ani.dantotsu.others.Anify
|
||||
import ani.dantotsu.others.Jikan
|
||||
import ani.dantotsu.others.Kitsu
|
||||
import ani.dantotsu.parsers.AnimeSources
|
||||
@@ -99,6 +100,15 @@ class MediaDetailsViewModel : ViewModel() {
|
||||
if (kitsuEpisodes.value == null) kitsuEpisodes.postValue(Kitsu.getKitsuEpisodesDetails(s))
|
||||
}
|
||||
}
|
||||
private val anifyEpisodes: MutableLiveData<Map<String, Episode>> =
|
||||
MutableLiveData<Map<String, Episode>>(null)
|
||||
|
||||
fun getAnifyEpisodes(): LiveData<Map<String, Episode>> = anifyEpisodes
|
||||
suspend fun loadAnifyEpisodes(s: Int) {
|
||||
tryWithSuspend {
|
||||
if (anifyEpisodes.value == null) anifyEpisodes.postValue(Anify.fetchAndParseMetadata(s))
|
||||
}
|
||||
}
|
||||
|
||||
private val fillerEpisodes: MutableLiveData<Map<String, Episode>> =
|
||||
MutableLiveData<Map<String, Episode>>(null)
|
||||
|
||||
@@ -528,26 +528,11 @@ class MediaInfoFragment : Fragment() {
|
||||
parent,
|
||||
false
|
||||
).apply {
|
||||
fun onUserClick(userId: Int) {
|
||||
val review = media.review!!.find { i -> i.id == userId }
|
||||
if (review != null) {
|
||||
startActivity(
|
||||
Intent(requireContext(), ReviewViewActivity::class.java)
|
||||
.putExtra("review", review)
|
||||
)
|
||||
}
|
||||
}
|
||||
val adapter = GroupieAdapter()
|
||||
media.review!!.forEach {
|
||||
adapter.add(ReviewAdapter(it, ::onUserClick))
|
||||
}
|
||||
media.review!!.forEach { adapter.add(ReviewAdapter(it)) }
|
||||
itemTitle.setText(R.string.reviews)
|
||||
itemRecycler.adapter = adapter
|
||||
itemRecycler.layoutManager = LinearLayoutManager(
|
||||
requireContext(),
|
||||
LinearLayoutManager.VERTICAL,
|
||||
false
|
||||
)
|
||||
itemRecycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
itemMore.visibility = View.VISIBLE
|
||||
itemMore.setSafeOnClickListener {
|
||||
startActivity(
|
||||
|
||||
@@ -52,7 +52,8 @@ class MediaListViewActivity: AppCompatActivity() {
|
||||
binding.listAppBar.setBackgroundColor(primaryColor)
|
||||
binding.listTitle.setTextColor(primaryTextColor)
|
||||
val screenWidth = resources.displayMetrics.run { widthPixels / density }
|
||||
val mediaList = intent.getSerialized("media") as? ArrayList<Media> ?: ArrayList()
|
||||
val mediaList = passedMedia ?: intent.getSerialized("media") as? ArrayList<Media> ?: ArrayList()
|
||||
if (passedMedia != null) passedMedia = null
|
||||
val view = PrefManager.getCustomVal("mediaView", 0)
|
||||
var mediaView: View = when (view) {
|
||||
1 -> binding.mediaList
|
||||
@@ -85,4 +86,8 @@ class MediaListViewActivity: AppCompatActivity() {
|
||||
if (view == 1) 1 else (screenWidth / 120f).toInt()
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
var passedMedia: ArrayList<Media>? = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,25 +26,50 @@ class OtherDetailsViewModel : ViewModel() {
|
||||
if (author.value == null) author.postValue(Anilist.query.getAuthorDetails(m))
|
||||
}
|
||||
|
||||
private var cachedAllCalendarData: Map<String, MutableList<Media>>? = null
|
||||
private var cachedLibraryCalendarData: Map<String, MutableList<Media>>? = null
|
||||
private val calendar: MutableLiveData<Map<String, MutableList<Media>>> = MutableLiveData(null)
|
||||
fun getCalendar(): LiveData<Map<String, MutableList<Media>>> = calendar
|
||||
suspend fun loadCalendar() {
|
||||
val curr = System.currentTimeMillis() / 1000
|
||||
val res = Anilist.query.recentlyUpdated(curr - 86400, curr + (86400 * 6))
|
||||
val df = DateFormat.getDateInstance(DateFormat.FULL)
|
||||
val map = mutableMapOf<String, MutableList<Media>>()
|
||||
val idMap = mutableMapOf<String, MutableList<Int>>()
|
||||
res?.forEach {
|
||||
val v = it.relation?.split(",")?.map { i -> i.toLong() }!!
|
||||
val dateInfo = df.format(Date(v[1] * 1000))
|
||||
val list = map.getOrPut(dateInfo) { mutableListOf() }
|
||||
val idList = idMap.getOrPut(dateInfo) { mutableListOf() }
|
||||
it.relation = "Episode ${v[0]}"
|
||||
if (!idList.contains(it.id)) {
|
||||
idList.add(it.id)
|
||||
list.add(it)
|
||||
suspend fun loadCalendar(showOnlyLibrary: Boolean = false) {
|
||||
if (cachedAllCalendarData == null || cachedLibraryCalendarData == null) {
|
||||
val curr = System.currentTimeMillis() / 1000
|
||||
val res = Anilist.query.recentlyUpdated(curr - 86400, curr + (86400 * 6))
|
||||
val df = DateFormat.getDateInstance(DateFormat.FULL)
|
||||
val allMap = mutableMapOf<String, MutableList<Media>>()
|
||||
val libraryMap = mutableMapOf<String, MutableList<Media>>()
|
||||
val idMap = mutableMapOf<String, MutableList<Int>>()
|
||||
|
||||
val userId = Anilist.userid ?: 0
|
||||
val userLibrary = Anilist.query.getMediaLists(true, userId)
|
||||
val libraryMediaIds = userLibrary.flatMap { it.value }.map { it.id }
|
||||
|
||||
res.forEach {
|
||||
val v = it.relation?.split(",")?.map { i -> i.toLong() }!!
|
||||
val dateInfo = df.format(Date(v[1] * 1000))
|
||||
val list = allMap.getOrPut(dateInfo) { mutableListOf() }
|
||||
val libraryList = if (libraryMediaIds.contains(it.id)) {
|
||||
libraryMap.getOrPut(dateInfo) { mutableListOf() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val idList = idMap.getOrPut(dateInfo) { mutableListOf() }
|
||||
it.relation = "Episode ${v[0]}"
|
||||
if (!idList.contains(it.id)) {
|
||||
idList.add(it.id)
|
||||
list.add(it)
|
||||
libraryList?.add(it)
|
||||
}
|
||||
}
|
||||
|
||||
cachedAllCalendarData = allMap
|
||||
cachedLibraryCalendarData = libraryMap
|
||||
}
|
||||
calendar.postValue(map)
|
||||
|
||||
val cacheToUse: Map<String, MutableList<Media>> = if (showOnlyLibrary) {
|
||||
cachedLibraryCalendarData ?: emptyMap()
|
||||
} else {
|
||||
cachedAllCalendarData ?: emptyMap()
|
||||
}
|
||||
calendar.postValue(cacheToUse)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package ani.dantotsu.media
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.text.SpannableString
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
@@ -19,10 +18,9 @@ import ani.dantotsu.connections.anilist.api.Query
|
||||
import ani.dantotsu.databinding.ActivityFollowBinding
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.profile.FollowerItem
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.util.MarkdownCreatorActivity
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -60,7 +58,7 @@ class ReviewActivity : AppCompatActivity() {
|
||||
binding.followFilterButton.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
this,
|
||||
Intent(this, MarkdownCreatorActivity::class.java)
|
||||
Intent(this, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "review"),
|
||||
null
|
||||
)
|
||||
@@ -122,19 +120,7 @@ class ReviewActivity : AppCompatActivity() {
|
||||
private fun fillList() {
|
||||
adapter.clear()
|
||||
reviews.forEach {
|
||||
adapter.add(
|
||||
ReviewAdapter(
|
||||
it,
|
||||
this::onUserClick
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onUserClick(userId: Int) {
|
||||
val review = reviews.find { it.id == userId }
|
||||
if (review != null) {
|
||||
startActivity(Intent(this, ReviewViewActivity::class.java).putExtra("review", review))
|
||||
adapter.add(ReviewAdapter(it))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,24 @@
|
||||
package ani.dantotsu.media
|
||||
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.view.View
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.core.app.ActivityOptionsCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.util.Pair
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.api.Query
|
||||
import ani.dantotsu.databinding.ItemReviewsBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.openImage
|
||||
import ani.dantotsu.others.ImageViewDialog
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.activity.ActivityItemBuilder
|
||||
import ani.dantotsu.toast
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
@@ -18,19 +30,49 @@ import kotlinx.coroutines.withContext
|
||||
|
||||
class ReviewAdapter(
|
||||
private var review: Query.Review,
|
||||
val clickCallback: (Int) -> Unit
|
||||
) : BindableItem<ItemReviewsBinding>() {
|
||||
private lateinit var binding: ItemReviewsBinding
|
||||
|
||||
override fun bind(viewBinding: ItemReviewsBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
val context = binding.root.context
|
||||
binding.reviewUserName.text = review.user?.name
|
||||
binding.reviewUserAvatar.loadImage(review.user?.avatar?.medium)
|
||||
binding.reviewText.text = review.summary
|
||||
binding.reviewPostTime.text = ActivityItemBuilder.getDateTime(review.createdAt)
|
||||
val text = "[${review.score/ 10.0f}]"
|
||||
binding.reviewTag.text = text
|
||||
binding.root.setOnClickListener { clickCallback(review.id) }
|
||||
binding.root.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ReviewViewActivity::class.java)
|
||||
.putExtra("review", review),
|
||||
null
|
||||
)
|
||||
}
|
||||
binding.reviewUserName.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ProfileActivity::class.java)
|
||||
.putExtra("userId", review.user?.id),
|
||||
null
|
||||
)
|
||||
}
|
||||
binding.reviewUserAvatar.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ProfileActivity::class.java)
|
||||
.putExtra("userId", review.user?.id),
|
||||
null
|
||||
)
|
||||
}
|
||||
binding.reviewUserAvatar.openImage(
|
||||
context.getString(
|
||||
R.string.avatar,
|
||||
review.user?.name
|
||||
),
|
||||
review.user?.avatar?.medium ?: ""
|
||||
)
|
||||
userVote(review.userRating)
|
||||
enableVote()
|
||||
binding.reviewTotalVotes.text = review.rating.toString()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package ani.dantotsu.media
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
@@ -18,6 +19,9 @@ import ani.dantotsu.getThemeColor
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.openImage
|
||||
import ani.dantotsu.others.ImageViewDialog
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.activity.ActivityItemBuilder
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
@@ -47,6 +51,20 @@ class ReviewViewActivity : AppCompatActivity() {
|
||||
binding.userName.text = review.user?.name
|
||||
binding.userAvatar.loadImage(review.user?.avatar?.medium)
|
||||
binding.userTime.text = ActivityItemBuilder.getDateTime(review.createdAt)
|
||||
binding.userContainer.setOnClickListener {
|
||||
startActivity(Intent(this, ProfileActivity::class.java)
|
||||
.putExtra("userId", review.user?.id)
|
||||
)
|
||||
}
|
||||
binding.userAvatar.openImage(
|
||||
binding.root.context.getString(R.string.avatar, review.user?.name),
|
||||
review.user?.avatar?.medium ?: ""
|
||||
)
|
||||
binding.userAvatar.setOnClickListener {
|
||||
startActivity(Intent(this, ProfileActivity::class.java)
|
||||
.putExtra("userId", review.user?.id)
|
||||
)
|
||||
}
|
||||
binding.profileUserBio.settings.loadWithOverviewMode = true
|
||||
binding.profileUserBio.settings.useWideViewPort = true
|
||||
binding.profileUserBio.setInitialScale(1)
|
||||
|
||||
@@ -183,6 +183,12 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri
|
||||
binding.searchByImage.setOnClickListener {
|
||||
activity.startActivity(Intent(activity, ImageSearchActivity::class.java))
|
||||
}
|
||||
binding.clearHistory.setOnClickListener {
|
||||
it.startAnimation(fadeOutAnimation())
|
||||
it.visibility = View.GONE
|
||||
searchHistoryAdapter.clearHistory()
|
||||
}
|
||||
updateClearHistoryVisibility()
|
||||
fun searchTitle() {
|
||||
activity.result.apply {
|
||||
search =
|
||||
@@ -300,11 +306,17 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri
|
||||
}
|
||||
|
||||
binding.searchResultLayout.visibility = View.VISIBLE
|
||||
binding.clearHistory.visibility = View.GONE
|
||||
binding.searchHistoryList.visibility = View.GONE
|
||||
binding.searchByImage.visibility = View.GONE
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateClearHistoryVisibility() {
|
||||
binding.clearHistory.visibility =
|
||||
if (searchHistoryAdapter.itemCount > 0) View.VISIBLE else View.GONE
|
||||
}
|
||||
|
||||
private fun fadeInAnimation(): Animation {
|
||||
return AlphaAnimation(0f, 1f).apply {
|
||||
duration = 150
|
||||
@@ -375,4 +387,3 @@ class SearchAdapter(private val activity: SearchActivity, private val type: Stri
|
||||
override fun getItemCount(): Int = chips.size
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ class SearchHistoryAdapter(private val type: String, private val searchClicked:
|
||||
PrefManager.setVal(historyType, searchHistory)
|
||||
}
|
||||
|
||||
fun clearHistory() {
|
||||
searchHistory?.clear()
|
||||
PrefManager.setVal(historyType, searchHistory)
|
||||
submitList(searchHistory?.toList())
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
parent: ViewGroup,
|
||||
viewType: Int
|
||||
|
||||
@@ -26,4 +26,5 @@ data class Anime(
|
||||
var slug: String? = null,
|
||||
var kitsuEpisodes: Map<String, Episode>? = null,
|
||||
var fillerEpisodes: Map<String, Episode>? = null,
|
||||
var anifyEpisodes: Map<String, Episode>? = null,
|
||||
) : Serializable
|
||||
@@ -8,7 +8,6 @@ import android.view.ViewGroup
|
||||
import android.widget.ArrayAdapter
|
||||
import android.widget.ImageButton
|
||||
import android.widget.LinearLayout
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.ContextCompat.startActivity
|
||||
import androidx.core.view.isGone
|
||||
@@ -19,7 +18,7 @@ import ani.dantotsu.FileUrl
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.currActivity
|
||||
import ani.dantotsu.databinding.DialogLayoutBinding
|
||||
import ani.dantotsu.databinding.ItemAnimeWatchBinding
|
||||
import ani.dantotsu.databinding.ItemMediaSourceBinding
|
||||
import ani.dantotsu.databinding.ItemChipBinding
|
||||
import ani.dantotsu.displayTimer
|
||||
import ani.dantotsu.isOnline
|
||||
@@ -33,12 +32,14 @@ import ani.dantotsu.others.LanguageMapper
|
||||
import ani.dantotsu.others.webview.CookieCatcher
|
||||
import ani.dantotsu.parsers.AnimeSources
|
||||
import ani.dantotsu.parsers.DynamicAnimeParser
|
||||
import ani.dantotsu.parsers.OfflineAnimeParser
|
||||
import ani.dantotsu.parsers.WatchSources
|
||||
import ani.dantotsu.px
|
||||
import ani.dantotsu.settings.FAQActivity
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.chip.Chip
|
||||
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
|
||||
import eu.kanade.tachiyomi.data.notification.Notifications.CHANNEL_SUBSCRIPTION_CHECK
|
||||
@@ -54,16 +55,13 @@ class AnimeWatchAdapter(
|
||||
) : RecyclerView.Adapter<AnimeWatchAdapter.ViewHolder>() {
|
||||
private var autoSelect = true
|
||||
var subscribe: MediaDetailsActivity.PopImageButton? = null
|
||||
private var _binding: ItemAnimeWatchBinding? = null
|
||||
private var _binding: ItemMediaSourceBinding? = null
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
val bind = ItemAnimeWatchBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
val bind = ItemMediaSourceBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
return ViewHolder(bind)
|
||||
}
|
||||
|
||||
private var nestedDialog: AlertDialog? = null
|
||||
|
||||
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
val binding = holder.binding
|
||||
_binding = binding
|
||||
@@ -75,7 +73,7 @@ class AnimeWatchAdapter(
|
||||
null
|
||||
)
|
||||
}
|
||||
//Youtube
|
||||
// Youtube
|
||||
if (media.anime?.youtube != null && PrefManager.getVal(PrefName.ShowYtButton)) {
|
||||
binding.animeSourceYT.visibility = View.VISIBLE
|
||||
binding.animeSourceYT.setOnClickListener {
|
||||
@@ -89,7 +87,7 @@ class AnimeWatchAdapter(
|
||||
R.string.subbed
|
||||
)
|
||||
|
||||
//PreferDub
|
||||
// PreferDub
|
||||
var changing = false
|
||||
binding.animeSourceDubbed.setOnCheckedChangeListener { _, isChecked ->
|
||||
binding.animeSourceDubbedText.text =
|
||||
@@ -99,8 +97,8 @@ class AnimeWatchAdapter(
|
||||
if (!changing) fragment.onDubClicked(isChecked)
|
||||
}
|
||||
|
||||
//Wrong Title
|
||||
binding.animeSourceSearch.setOnClickListener {
|
||||
// Wrong Title
|
||||
binding.mediaSourceSearch.setOnClickListener {
|
||||
SourceSearchDialogFragment().show(
|
||||
fragment.requireActivity().supportFragmentManager,
|
||||
null
|
||||
@@ -108,37 +106,37 @@ class AnimeWatchAdapter(
|
||||
}
|
||||
val offline = !isOnline(binding.root.context) || PrefManager.getVal(PrefName.OfflineMode)
|
||||
|
||||
binding.animeSourceNameContainer.isGone = offline
|
||||
binding.animeSourceSettings.isGone = offline
|
||||
binding.animeSourceSearch.isGone = offline
|
||||
binding.animeSourceTitle.isGone = offline
|
||||
binding.mediaSourceNameContainer.isGone = offline
|
||||
binding.mediaSourceSettings.isGone = offline
|
||||
binding.mediaSourceSearch.isGone = offline
|
||||
binding.mediaSourceTitle.isGone = offline
|
||||
|
||||
//Source Selection
|
||||
// Source Selection
|
||||
var source =
|
||||
media.selected!!.sourceIndex.let { if (it >= watchSources.names.size) 0 else it }
|
||||
setLanguageList(media.selected!!.langIndex, source)
|
||||
if (watchSources.names.isNotEmpty() && source in 0 until watchSources.names.size) {
|
||||
binding.animeSource.setText(watchSources.names[source])
|
||||
binding.mediaSource.setText(watchSources.names[source])
|
||||
watchSources[source].apply {
|
||||
this.selectDub = media.selected!!.preferDub
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately()
|
||||
}
|
||||
}
|
||||
|
||||
binding.animeSource.setAdapter(
|
||||
binding.mediaSource.setAdapter(
|
||||
ArrayAdapter(
|
||||
fragment.requireContext(),
|
||||
R.layout.item_dropdown,
|
||||
watchSources.names
|
||||
)
|
||||
)
|
||||
binding.animeSourceTitle.isSelected = true
|
||||
binding.animeSource.setOnItemClickListener { _, _, i, _ ->
|
||||
binding.mediaSourceTitle.isSelected = true
|
||||
binding.mediaSource.setOnItemClickListener { _, _, i, _ ->
|
||||
fragment.onSourceChange(i).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
changing = true
|
||||
binding.animeSourceDubbed.isChecked = selectDub
|
||||
changing = false
|
||||
@@ -150,15 +148,15 @@ class AnimeWatchAdapter(
|
||||
fragment.loadEpisodes(i, false)
|
||||
}
|
||||
|
||||
binding.animeSourceLanguage.setOnItemClickListener { _, _, i, _ ->
|
||||
binding.mediaSourceLanguage.setOnItemClickListener { _, _, i, _ ->
|
||||
// Check if 'extension' and 'selected' properties exist and are accessible
|
||||
(watchSources[source] as? DynamicAnimeParser)?.let { ext ->
|
||||
ext.sourceLanguage = i
|
||||
fragment.onLangChange(i)
|
||||
fragment.onSourceChange(media.selected!!.sourceIndex).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener =
|
||||
{ MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
{ MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
changing = true
|
||||
binding.animeSourceDubbed.isChecked = selectDub
|
||||
changing = false
|
||||
@@ -170,19 +168,19 @@ class AnimeWatchAdapter(
|
||||
} ?: run { }
|
||||
}
|
||||
|
||||
//settings
|
||||
binding.animeSourceSettings.setOnClickListener {
|
||||
// Settings
|
||||
binding.mediaSourceSettings.setOnClickListener {
|
||||
(watchSources[source] as? DynamicAnimeParser)?.let { ext ->
|
||||
fragment.openSettings(ext.extension)
|
||||
}
|
||||
}
|
||||
|
||||
//Icons
|
||||
// Icons
|
||||
|
||||
//subscribe
|
||||
// Subscribe
|
||||
subscribe = MediaDetailsActivity.PopImageButton(
|
||||
fragment.lifecycleScope,
|
||||
binding.animeSourceSubscribe,
|
||||
binding.mediaSourceSubscribe,
|
||||
R.drawable.ic_round_notifications_active_24,
|
||||
R.drawable.ic_round_notifications_none_24,
|
||||
R.color.bg_opp,
|
||||
@@ -190,117 +188,115 @@ class AnimeWatchAdapter(
|
||||
fragment.subscribed,
|
||||
true
|
||||
) {
|
||||
fragment.onNotificationPressed(it, binding.animeSource.text.toString())
|
||||
fragment.onNotificationPressed(it, binding.mediaSource.text.toString())
|
||||
}
|
||||
|
||||
subscribeButton(false)
|
||||
|
||||
binding.animeSourceSubscribe.setOnLongClickListener {
|
||||
binding.mediaSourceSubscribe.setOnLongClickListener {
|
||||
openSettings(fragment.requireContext(), CHANNEL_SUBSCRIPTION_CHECK)
|
||||
}
|
||||
|
||||
//Nested Button
|
||||
binding.animeNestedButton.setOnClickListener {
|
||||
val dialogView =
|
||||
LayoutInflater.from(fragment.requireContext()).inflate(R.layout.dialog_layout, null)
|
||||
val dialogBinding = DialogLayoutBinding.bind(dialogView)
|
||||
var refresh = false
|
||||
var run = false
|
||||
var reversed = media.selected!!.recyclerReversed
|
||||
var style =
|
||||
media.selected!!.recyclerStyle ?: PrefManager.getVal(PrefName.AnimeDefaultView)
|
||||
dialogBinding.animeSourceTop.rotation = if (reversed) -90f else 90f
|
||||
dialogBinding.sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
dialogBinding.animeSourceTop.setOnClickListener {
|
||||
reversed = !reversed
|
||||
dialogBinding.animeSourceTop.rotation = if (reversed) -90f else 90f
|
||||
dialogBinding.sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
run = true
|
||||
}
|
||||
//Grids
|
||||
var selected = when (style) {
|
||||
0 -> dialogBinding.animeSourceList
|
||||
1 -> dialogBinding.animeSourceGrid
|
||||
2 -> dialogBinding.animeSourceCompact
|
||||
else -> dialogBinding.animeSourceList
|
||||
}
|
||||
when (style) {
|
||||
0 -> dialogBinding.layoutText.setText(R.string.list)
|
||||
1 -> dialogBinding.layoutText.setText(R.string.grid)
|
||||
2 -> dialogBinding.layoutText.setText(R.string.compact)
|
||||
else -> dialogBinding.animeSourceList
|
||||
}
|
||||
selected.alpha = 1f
|
||||
fun selected(it: ImageButton) {
|
||||
selected.alpha = 0.33f
|
||||
selected = it
|
||||
selected.alpha = 1f
|
||||
}
|
||||
dialogBinding.animeSourceList.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 0
|
||||
dialogBinding.layoutText.setText(R.string.list)
|
||||
run = true
|
||||
}
|
||||
dialogBinding.animeSourceGrid.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 1
|
||||
dialogBinding.layoutText.setText(R.string.grid)
|
||||
run = true
|
||||
}
|
||||
dialogBinding.animeSourceCompact.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 2
|
||||
dialogBinding.layoutText.setText(R.string.compact)
|
||||
run = true
|
||||
}
|
||||
dialogBinding.animeWebviewContainer.setOnClickListener {
|
||||
if (!WebViewUtil.supportsWebView(fragment.requireContext())) {
|
||||
toast(R.string.webview_not_installed)
|
||||
// Nested Button
|
||||
binding.mediaNestedButton.setOnClickListener {
|
||||
val dialogBinding = DialogLayoutBinding.inflate(fragment.layoutInflater)
|
||||
dialogBinding.apply {
|
||||
var refresh = false
|
||||
var run = false
|
||||
var reversed = media.selected!!.recyclerReversed
|
||||
var style =
|
||||
media.selected!!.recyclerStyle ?: PrefManager.getVal(PrefName.AnimeDefaultView)
|
||||
|
||||
mediaSourceTop.rotation = if (reversed) -90f else 90f
|
||||
sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
mediaSourceTop.setOnClickListener {
|
||||
reversed = !reversed
|
||||
mediaSourceTop.rotation = if (reversed) -90f else 90f
|
||||
sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
run = true
|
||||
}
|
||||
//start CookieCatcher activity
|
||||
if (watchSources.names.isNotEmpty() && source in 0 until watchSources.names.size) {
|
||||
val sourceAHH = watchSources[source] as? DynamicAnimeParser
|
||||
val sourceHttp =
|
||||
sourceAHH?.extension?.sources?.firstOrNull() as? AnimeHttpSource
|
||||
val url = sourceHttp?.baseUrl
|
||||
url?.let {
|
||||
refresh = true
|
||||
val headersMap = try {
|
||||
sourceHttp.headers.toMultimap()
|
||||
.mapValues { it.value.getOrNull(0) ?: "" }
|
||||
} catch (e: Exception) {
|
||||
emptyMap()
|
||||
// Grids
|
||||
var selected = when (style) {
|
||||
0 -> mediaSourceList
|
||||
1 -> mediaSourceGrid
|
||||
2 -> mediaSourceCompact
|
||||
else -> mediaSourceList
|
||||
}
|
||||
when (style) {
|
||||
0 -> layoutText.setText(R.string.list)
|
||||
1 -> layoutText.setText(R.string.grid)
|
||||
2 -> layoutText.setText(R.string.compact)
|
||||
else -> mediaSourceList
|
||||
}
|
||||
selected.alpha = 1f
|
||||
fun selected(it: ImageButton) {
|
||||
selected.alpha = 0.33f
|
||||
selected = it
|
||||
selected.alpha = 1f
|
||||
}
|
||||
mediaSourceList.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 0
|
||||
layoutText.setText(R.string.list)
|
||||
run = true
|
||||
}
|
||||
mediaSourceGrid.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 1
|
||||
layoutText.setText(R.string.grid)
|
||||
run = true
|
||||
}
|
||||
mediaSourceCompact.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 2
|
||||
layoutText.setText(R.string.compact)
|
||||
run = true
|
||||
}
|
||||
mediaWebviewContainer.setOnClickListener {
|
||||
if (!WebViewUtil.supportsWebView(fragment.requireContext())) {
|
||||
toast(R.string.webview_not_installed)
|
||||
}
|
||||
// Start CookieCatcher activity
|
||||
if (watchSources.names.isNotEmpty() && source in 0 until watchSources.names.size) {
|
||||
val sourceAHH = watchSources[source] as? DynamicAnimeParser
|
||||
val sourceHttp =
|
||||
sourceAHH?.extension?.sources?.firstOrNull() as? AnimeHttpSource
|
||||
val url = sourceHttp?.baseUrl
|
||||
url?.let {
|
||||
refresh = true
|
||||
val headersMap = try {
|
||||
sourceHttp.headers.toMultimap()
|
||||
.mapValues { it.value.getOrNull(0) ?: "" }
|
||||
} catch (e: Exception) {
|
||||
emptyMap()
|
||||
}
|
||||
val intent =
|
||||
Intent(fragment.requireContext(), CookieCatcher::class.java)
|
||||
.putExtra("url", url)
|
||||
.putExtra("headers", headersMap as HashMap<String, String>)
|
||||
startActivity(fragment.requireContext(), intent, null)
|
||||
}
|
||||
val intent = Intent(fragment.requireContext(), CookieCatcher::class.java)
|
||||
.putExtra("url", url)
|
||||
.putExtra("headers", headersMap as HashMap<String, String>)
|
||||
startActivity(fragment.requireContext(), intent, null)
|
||||
}
|
||||
}
|
||||
|
||||
// Hidden
|
||||
mangaScanlatorContainer.visibility = View.GONE
|
||||
animeDownloadContainer.visibility = View.GONE
|
||||
fragment.requireContext().customAlertDialog().apply {
|
||||
setTitle("Options")
|
||||
setCustomView(dialogBinding.root)
|
||||
setPosButton("OK") {
|
||||
if (run) fragment.onIconPressed(style, reversed)
|
||||
if (refresh) fragment.loadEpisodes(source, true)
|
||||
}
|
||||
setNegButton("Cancel") {
|
||||
if (refresh) fragment.loadEpisodes(source, true)
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
//hidden
|
||||
dialogBinding.animeScanlatorContainer.visibility = View.GONE
|
||||
dialogBinding.animeDownloadContainer.visibility = View.GONE
|
||||
|
||||
nestedDialog = AlertDialog.Builder(fragment.requireContext(), R.style.MyPopup)
|
||||
.setTitle("Options")
|
||||
.setView(dialogView)
|
||||
.setPositiveButton("OK") { _, _ ->
|
||||
if (run) fragment.onIconPressed(style, reversed)
|
||||
if (refresh) fragment.loadEpisodes(source, true)
|
||||
}
|
||||
.setNegativeButton("Cancel") { _, _ ->
|
||||
if (refresh) fragment.loadEpisodes(source, true)
|
||||
}
|
||||
.setOnCancelListener {
|
||||
if (refresh) fragment.loadEpisodes(source, true)
|
||||
}
|
||||
.create()
|
||||
nestedDialog?.show()
|
||||
}
|
||||
//Episode Handling
|
||||
// Episode Handling
|
||||
handleEpisodes()
|
||||
}
|
||||
|
||||
@@ -308,7 +304,7 @@ class AnimeWatchAdapter(
|
||||
subscribe?.enabled(enabled)
|
||||
}
|
||||
|
||||
//Chips
|
||||
// Chips
|
||||
fun updateChips(limit: Int, names: Array<String>, arr: Array<Int>, selected: Int = 0) {
|
||||
val binding = _binding
|
||||
if (binding != null) {
|
||||
@@ -319,13 +315,13 @@ class AnimeWatchAdapter(
|
||||
val chip =
|
||||
ItemChipBinding.inflate(
|
||||
LayoutInflater.from(fragment.context),
|
||||
binding.animeSourceChipGroup,
|
||||
binding.mediaSourceChipGroup,
|
||||
false
|
||||
).root
|
||||
chip.isCheckable = true
|
||||
fun selected() {
|
||||
chip.isChecked = true
|
||||
binding.animeWatchChipScroll.smoothScrollTo(
|
||||
binding.mediaWatchChipScroll.smoothScrollTo(
|
||||
(chip.left - screenWidth / 2) + (chip.width / 2),
|
||||
0
|
||||
)
|
||||
@@ -344,14 +340,14 @@ class AnimeWatchAdapter(
|
||||
selected()
|
||||
fragment.onChipClicked(position, limit * (position), last - 1)
|
||||
}
|
||||
binding.animeSourceChipGroup.addView(chip)
|
||||
binding.mediaSourceChipGroup.addView(chip)
|
||||
if (selected == position) {
|
||||
selected()
|
||||
select = chip
|
||||
}
|
||||
}
|
||||
if (select != null)
|
||||
binding.animeWatchChipScroll.apply {
|
||||
binding.mediaWatchChipScroll.apply {
|
||||
post {
|
||||
scrollTo(
|
||||
(select.left - screenWidth / 2) + (select.width / 2),
|
||||
@@ -363,7 +359,7 @@ class AnimeWatchAdapter(
|
||||
}
|
||||
|
||||
fun clearChips() {
|
||||
_binding?.animeSourceChipGroup?.removeAllViews()
|
||||
_binding?.mediaSourceChipGroup?.removeAllViews()
|
||||
}
|
||||
|
||||
fun handleEpisodes() {
|
||||
@@ -379,15 +375,15 @@ class AnimeWatchAdapter(
|
||||
|
||||
var continueEp = (if (anilistEp > appEp) anilistEp else appEp).toString()
|
||||
if (episodes.contains(continueEp)) {
|
||||
binding.animeSourceContinue.visibility = View.VISIBLE
|
||||
binding.sourceContinue.visibility = View.VISIBLE
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
continueEp
|
||||
)
|
||||
if ((binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams).weight > PrefManager.getVal<Float>(
|
||||
if ((binding.itemMediaProgress.layoutParams as LinearLayout.LayoutParams).weight > PrefManager.getVal<Float>(
|
||||
PrefName.WatchPercentage
|
||||
)
|
||||
) {
|
||||
@@ -395,9 +391,9 @@ class AnimeWatchAdapter(
|
||||
if (e != -1 && e + 1 < episodes.size) {
|
||||
continueEp = episodes[e + 1]
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
continueEp
|
||||
)
|
||||
@@ -407,51 +403,63 @@ class AnimeWatchAdapter(
|
||||
|
||||
val cleanedTitle = ep.title?.let { MediaNameAdapter.removeEpisodeNumber(it) }
|
||||
|
||||
binding.itemEpisodeImage.loadImage(
|
||||
binding.itemMediaImage.loadImage(
|
||||
ep.thumb ?: FileUrl[media.banner ?: media.cover], 0
|
||||
)
|
||||
if (ep.filler) binding.itemEpisodeFillerView.visibility = View.VISIBLE
|
||||
|
||||
binding.animeSourceContinueText.text =
|
||||
binding.mediaSourceContinueText.text =
|
||||
currActivity()!!.getString(
|
||||
R.string.continue_episode, ep.number, if (ep.filler)
|
||||
currActivity()!!.getString(R.string.filler_tag)
|
||||
else
|
||||
"", cleanedTitle
|
||||
)
|
||||
binding.animeSourceContinue.setOnClickListener {
|
||||
binding.sourceContinue.setOnClickListener {
|
||||
fragment.onEpisodeClick(continueEp)
|
||||
}
|
||||
if (fragment.continueEp) {
|
||||
if (
|
||||
(binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams)
|
||||
(binding.itemMediaProgress.layoutParams as LinearLayout.LayoutParams)
|
||||
.weight < PrefManager.getVal<Float>(PrefName.WatchPercentage)
|
||||
) {
|
||||
binding.animeSourceContinue.performClick()
|
||||
binding.sourceContinue.performClick()
|
||||
fragment.continueEp = false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
binding.animeSourceContinue.visibility = View.GONE
|
||||
binding.sourceContinue.visibility = View.GONE
|
||||
}
|
||||
|
||||
binding.animeSourceProgressBar.visibility = View.GONE
|
||||
binding.sourceProgressBar.visibility = View.GONE
|
||||
|
||||
val sourceFound = media.anime.episodes!!.isNotEmpty()
|
||||
binding.animeSourceNotFound.isGone = sourceFound
|
||||
val isDownloadedSource = watchSources[media.selected!!.sourceIndex] is OfflineAnimeParser
|
||||
|
||||
if (isDownloadedSource) {
|
||||
binding.sourceNotFound.text = if (sourceFound) {
|
||||
currActivity()!!.getString(R.string.source_not_found)
|
||||
} else {
|
||||
currActivity()!!.getString(R.string.download_not_found)
|
||||
}
|
||||
} else {
|
||||
binding.sourceNotFound.text = currActivity()!!.getString(R.string.source_not_found)
|
||||
}
|
||||
|
||||
binding.sourceNotFound.isGone = sourceFound
|
||||
binding.faqbutton.isGone = sourceFound
|
||||
|
||||
if (!sourceFound && PrefManager.getVal(PrefName.SearchSources) && autoSelect) {
|
||||
if (binding.animeSource.adapter.count > media.selected!!.sourceIndex + 1) {
|
||||
if (binding.mediaSource.adapter.count > media.selected!!.sourceIndex + 1) {
|
||||
val nextIndex = media.selected!!.sourceIndex + 1
|
||||
binding.animeSource.setText(
|
||||
binding.animeSource.adapter
|
||||
binding.mediaSource.setText(
|
||||
binding.mediaSource.adapter
|
||||
.getItem(nextIndex).toString(), false
|
||||
)
|
||||
fragment.onSourceChange(nextIndex).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener =
|
||||
{ MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
{ MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
binding.animeSourceDubbed.isChecked = selectDub
|
||||
binding.animeSourceDubbedCont.isVisible = isDubAvailableSeparately()
|
||||
setLanguageList(0, nextIndex)
|
||||
@@ -460,13 +468,13 @@ class AnimeWatchAdapter(
|
||||
fragment.loadEpisodes(nextIndex, false)
|
||||
}
|
||||
}
|
||||
binding.animeSource.setOnClickListener { autoSelect = false }
|
||||
binding.mediaSource.setOnClickListener { autoSelect = false }
|
||||
} else {
|
||||
binding.animeSourceContinue.visibility = View.GONE
|
||||
binding.animeSourceNotFound.visibility = View.GONE
|
||||
binding.sourceContinue.visibility = View.GONE
|
||||
binding.sourceNotFound.visibility = View.GONE
|
||||
binding.faqbutton.visibility = View.GONE
|
||||
clearChips()
|
||||
binding.animeSourceProgressBar.visibility = View.VISIBLE
|
||||
binding.sourceProgressBar.visibility = View.VISIBLE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -480,9 +488,9 @@ class AnimeWatchAdapter(
|
||||
ext.sourceLanguage = lang
|
||||
}
|
||||
try {
|
||||
binding?.animeSourceLanguage?.setText(parser.extension.sources[lang].lang)
|
||||
binding?.mediaSourceLanguage?.setText(parser.extension.sources[lang].lang)
|
||||
} catch (e: IndexOutOfBoundsException) {
|
||||
binding?.animeSourceLanguage?.setText(
|
||||
binding?.mediaSourceLanguage?.setText(
|
||||
parser.extension.sources.firstOrNull()?.lang ?: "Unknown"
|
||||
)
|
||||
}
|
||||
@@ -493,9 +501,9 @@ class AnimeWatchAdapter(
|
||||
)
|
||||
val items = adapter.count
|
||||
|
||||
binding?.animeSourceLanguageContainer?.visibility =
|
||||
binding?.mediaSourceLanguageContainer?.visibility =
|
||||
if (items > 1) View.VISIBLE else View.GONE
|
||||
binding?.animeSourceLanguage?.setAdapter(adapter)
|
||||
binding?.mediaSourceLanguage?.setAdapter(adapter)
|
||||
|
||||
}
|
||||
}
|
||||
@@ -503,7 +511,7 @@ class AnimeWatchAdapter(
|
||||
|
||||
override fun getItemCount(): Int = 1
|
||||
|
||||
inner class ViewHolder(val binding: ItemAnimeWatchBinding) :
|
||||
inner class ViewHolder(val binding: ItemMediaSourceBinding) :
|
||||
RecyclerView.ViewHolder(binding.root) {
|
||||
init {
|
||||
displayTimer(media, binding.animeSourceContainer)
|
||||
|
||||
@@ -30,11 +30,15 @@ import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import ani.dantotsu.FileUrl
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.FragmentAnimeWatchBinding
|
||||
import ani.dantotsu.addons.download.DownloadAddonManager
|
||||
import ani.dantotsu.connections.anilist.api.MediaStreamingEpisode
|
||||
import ani.dantotsu.databinding.FragmentMediaSourceBinding
|
||||
import ani.dantotsu.download.DownloadedType
|
||||
import ani.dantotsu.download.DownloadsManager
|
||||
import ani.dantotsu.download.DownloadsManager.Companion.compareName
|
||||
import ani.dantotsu.download.DownloadsManager.Companion.getSubDirectory
|
||||
import ani.dantotsu.download.anime.AnimeDownloaderService
|
||||
import ani.dantotsu.download.findValidName
|
||||
import ani.dantotsu.dp
|
||||
import ani.dantotsu.isOnline
|
||||
import ani.dantotsu.media.Media
|
||||
@@ -45,6 +49,7 @@ import ani.dantotsu.media.MediaType
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.notifications.subscription.SubscriptionHelper
|
||||
import ani.dantotsu.notifications.subscription.SubscriptionHelper.Companion.saveSubscription
|
||||
import ani.dantotsu.others.Anify
|
||||
import ani.dantotsu.others.LanguageMapper
|
||||
import ani.dantotsu.parsers.AnimeParser
|
||||
import ani.dantotsu.parsers.AnimeSources
|
||||
@@ -54,15 +59,21 @@ import ani.dantotsu.settings.extensionprefs.AnimeSourcePreferencesFragment
|
||||
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 ani.dantotsu.util.StoragePermissions.Companion.accessAlertDialog
|
||||
import ani.dantotsu.util.StoragePermissions.Companion.hasDirAccess
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.anggrayudi.storage.file.extension
|
||||
import com.google.android.material.appbar.AppBarLayout
|
||||
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
|
||||
import eu.kanade.tachiyomi.extension.anime.model.AnimeExtension
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.launch
|
||||
import tachiyomi.core.util.lang.launchIO
|
||||
import uy.kohesive.injekt.Injekt
|
||||
import uy.kohesive.injekt.api.get
|
||||
import kotlin.math.ceil
|
||||
@@ -70,7 +81,7 @@ import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class AnimeWatchFragment : Fragment() {
|
||||
private var _binding: FragmentAnimeWatchBinding? = null
|
||||
private var _binding: FragmentMediaSourceBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
private val model: MediaDetailsViewModel by activityViewModels()
|
||||
|
||||
@@ -97,7 +108,7 @@ class AnimeWatchFragment : Fragment() {
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View? {
|
||||
_binding = FragmentAnimeWatchBinding.inflate(inflater, container, false)
|
||||
_binding = FragmentMediaSourceBinding.inflate(inflater, container, false)
|
||||
return _binding?.root
|
||||
}
|
||||
|
||||
@@ -118,7 +129,7 @@ class AnimeWatchFragment : Fragment() {
|
||||
)
|
||||
|
||||
|
||||
binding.animeSourceRecycler.updatePadding(bottom = binding.animeSourceRecycler.paddingBottom + navBarHeight)
|
||||
binding.mediaSourceRecycler.updatePadding(bottom = binding.mediaSourceRecycler.paddingBottom + navBarHeight)
|
||||
screenWidth = resources.displayMetrics.widthPixels.dp
|
||||
|
||||
var maxGridSize = (screenWidth / 100f).roundToInt()
|
||||
@@ -142,13 +153,13 @@ class AnimeWatchFragment : Fragment() {
|
||||
}
|
||||
}
|
||||
|
||||
binding.animeSourceRecycler.layoutManager = gridLayoutManager
|
||||
binding.mediaSourceRecycler.layoutManager = gridLayoutManager
|
||||
|
||||
binding.ScrollTop.setOnClickListener {
|
||||
binding.animeSourceRecycler.scrollToPosition(10)
|
||||
binding.animeSourceRecycler.smoothScrollToPosition(0)
|
||||
binding.mediaSourceRecycler.scrollToPosition(10)
|
||||
binding.mediaSourceRecycler.smoothScrollToPosition(0)
|
||||
}
|
||||
binding.animeSourceRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
binding.mediaSourceRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(recyclerView, dx, dy)
|
||||
|
||||
@@ -162,7 +173,7 @@ class AnimeWatchFragment : Fragment() {
|
||||
}
|
||||
})
|
||||
model.scrolledToTop.observe(viewLifecycleOwner) {
|
||||
if (it) binding.animeSourceRecycler.scrollToPosition(0)
|
||||
if (it) binding.mediaSourceRecycler.scrollToPosition(0)
|
||||
}
|
||||
|
||||
continueEp = model.continueMedia ?: false
|
||||
@@ -195,7 +206,7 @@ class AnimeWatchFragment : Fragment() {
|
||||
offlineMode = offlineMode
|
||||
)
|
||||
|
||||
binding.animeSourceRecycler.adapter =
|
||||
binding.mediaSourceRecycler.adapter =
|
||||
ConcatAdapter(headerAdapter, episodeAdapter)
|
||||
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
@@ -204,10 +215,11 @@ class AnimeWatchFragment : Fragment() {
|
||||
if (offline) {
|
||||
media.selected!!.sourceIndex = model.watchSources!!.list.lastIndex
|
||||
} else {
|
||||
awaitAll(
|
||||
async { model.loadKitsuEpisodes(media) },
|
||||
async { model.loadFillerEpisodes(media) }
|
||||
)
|
||||
val kitsuEpisodes = async { model.loadKitsuEpisodes(media) }
|
||||
val anifyEpisodes = async { model.loadAnifyEpisodes(media.id) }
|
||||
val fillerEpisodes = async { model.loadFillerEpisodes(media) }
|
||||
|
||||
awaitAll(kitsuEpisodes, anifyEpisodes, fillerEpisodes)
|
||||
}
|
||||
model.loadEpisodes(media, media.selected!!.sourceIndex)
|
||||
}
|
||||
@@ -222,6 +234,18 @@ class AnimeWatchFragment : Fragment() {
|
||||
val episodes = loadedEpisodes[media.selected!!.sourceIndex]
|
||||
if (episodes != null) {
|
||||
episodes.forEach { (i, episode) ->
|
||||
if (media.anime?.anifyEpisodes != null) {
|
||||
if (media.anime!!.anifyEpisodes!!.containsKey(i)) {
|
||||
episode.desc = media.anime!!.anifyEpisodes!![i]?.desc ?: episode.desc
|
||||
episode.title = if (MediaNameAdapter.removeEpisodeNumberCompletely(
|
||||
episode.title ?: ""
|
||||
).isBlank()
|
||||
) media.anime!!.anifyEpisodes!![i]?.title ?: episode.title else episode.title
|
||||
?: media.anime!!.anifyEpisodes!![i]?.title ?: episode.title
|
||||
episode.thumb = media.anime!!.anifyEpisodes!![i]?.thumb ?: episode.thumb
|
||||
|
||||
}
|
||||
}
|
||||
if (media.anime?.fillerEpisodes != null) {
|
||||
if (media.anime!!.fillerEpisodes!!.containsKey(i)) {
|
||||
episode.title =
|
||||
@@ -231,22 +255,19 @@ class AnimeWatchFragment : Fragment() {
|
||||
}
|
||||
if (media.anime?.kitsuEpisodes != null) {
|
||||
if (media.anime!!.kitsuEpisodes!!.containsKey(i)) {
|
||||
episode.desc =
|
||||
media.anime!!.kitsuEpisodes!![i]?.desc ?: episode.desc
|
||||
episode.desc = media.anime!!.kitsuEpisodes!![i]?.desc ?: episode.desc
|
||||
episode.title = if (MediaNameAdapter.removeEpisodeNumberCompletely(
|
||||
episode.title ?: ""
|
||||
).isBlank()
|
||||
) media.anime!!.kitsuEpisodes!![i]?.title
|
||||
?: episode.title else episode.title
|
||||
?: media.anime!!.kitsuEpisodes!![i]?.title ?: episode.title
|
||||
episode.thumb = media.anime!!.kitsuEpisodes!![i]?.thumb
|
||||
?: FileUrl[media.cover]
|
||||
) media.anime!!.kitsuEpisodes!![i]?.title ?: episode.title else episode.title
|
||||
?: media.anime!!.kitsuEpisodes!![i]?.title ?: episode.title
|
||||
episode.thumb = media.anime!!.kitsuEpisodes!![i]?.thumb ?: episode.thumb
|
||||
}
|
||||
}
|
||||
}
|
||||
media.anime?.episodes = episodes
|
||||
|
||||
//CHIP GROUP
|
||||
// CHIP GROUP
|
||||
val total = episodes.size
|
||||
val divisions = total.toDouble() / 10
|
||||
start = 0
|
||||
@@ -287,6 +308,10 @@ class AnimeWatchFragment : Fragment() {
|
||||
if (i != null)
|
||||
media.anime?.fillerEpisodes = i
|
||||
}
|
||||
model.getAnifyEpisodes().observe(viewLifecycleOwner) { i ->
|
||||
if (i != null)
|
||||
media.anime?.anifyEpisodes = i
|
||||
}
|
||||
}
|
||||
|
||||
fun onSourceChange(i: Int): AnimeParser {
|
||||
@@ -372,20 +397,18 @@ class AnimeWatchFragment : Fragment() {
|
||||
if (allSettings.size > 1) {
|
||||
val names =
|
||||
allSettings.map { LanguageMapper.getLanguageName(it.lang) }.toTypedArray()
|
||||
val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
.setTitle("Select a Source")
|
||||
.setSingleChoiceItems(names, -1) { dialog, which ->
|
||||
requireContext()
|
||||
.customAlertDialog()
|
||||
.apply {
|
||||
setTitle("Select a Source")
|
||||
singleChoiceItems(names) { which ->
|
||||
selectedSetting = allSettings[which]
|
||||
itemSelected = true
|
||||
dialog.dismiss()
|
||||
|
||||
// Move the fragment transaction here
|
||||
requireActivity().runOnUiThread {
|
||||
val fragment =
|
||||
AnimeSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
changeUIVisibility(true)
|
||||
loadEpisodes(media.selected!!.sourceIndex, true)
|
||||
}
|
||||
val fragment = AnimeSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
changeUIVisibility(true)
|
||||
loadEpisodes(media.selected!!.sourceIndex, true)
|
||||
}
|
||||
parentFragmentManager.beginTransaction()
|
||||
.setCustomAnimations(R.anim.slide_up, R.anim.slide_down)
|
||||
.replace(R.id.fragmentExtensionsContainer, fragment)
|
||||
@@ -393,13 +416,13 @@ class AnimeWatchFragment : Fragment() {
|
||||
.commit()
|
||||
}
|
||||
}
|
||||
.setOnDismissListener {
|
||||
onDismiss {
|
||||
if (!itemSelected) {
|
||||
changeUIVisibility(true)
|
||||
}
|
||||
}
|
||||
.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
// If there's only one setting, proceed with the fragment transaction
|
||||
requireActivity().runOnUiThread {
|
||||
@@ -408,11 +431,12 @@ class AnimeWatchFragment : Fragment() {
|
||||
changeUIVisibility(true)
|
||||
loadEpisodes(media.selected!!.sourceIndex, true)
|
||||
}
|
||||
parentFragmentManager.beginTransaction()
|
||||
.setCustomAnimations(R.anim.slide_up, R.anim.slide_down)
|
||||
.replace(R.id.fragmentExtensionsContainer, fragment)
|
||||
.addToBackStack(null)
|
||||
.commit()
|
||||
parentFragmentManager.beginTransaction().apply {
|
||||
setCustomAnimations(R.anim.slide_up, R.anim.slide_down)
|
||||
replace(R.id.fragmentExtensionsContainer, fragment)
|
||||
addToBackStack(null)
|
||||
commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -492,6 +516,89 @@ class AnimeWatchFragment : Fragment() {
|
||||
}
|
||||
}
|
||||
|
||||
@kotlin.OptIn(DelicateCoroutinesApi::class)
|
||||
fun fixDownload(i: String) {
|
||||
toast(R.string.running_fixes)
|
||||
launchIO {
|
||||
try {
|
||||
val context = context ?: throw Exception("Context is null")
|
||||
val directory =
|
||||
getSubDirectory(context, MediaType.ANIME, false, media.mainName(), i)
|
||||
?: throw Exception("Directory is null")
|
||||
val files = directory.listFiles()
|
||||
val videoFiles = files.filter { it.extension == "mp4" || it.extension == "mkv" }
|
||||
if (videoFiles.size != 1) {
|
||||
val biggest =
|
||||
videoFiles.filter { it.length() > 1000 }.maxByOrNull { it.length() }
|
||||
?: throw Exception("No video files found")
|
||||
val newName =
|
||||
AnimeDownloaderService.AnimeDownloadTask.getTaskName(media.mainName(), i)
|
||||
.findValidName() + "." + biggest.extension
|
||||
videoFiles.forEach {
|
||||
if (it != biggest) {
|
||||
it.delete()
|
||||
}
|
||||
}
|
||||
if (newName != biggest.name) {
|
||||
biggest.renameTo(newName)
|
||||
}
|
||||
toast(context.getString(R.string.success) + " (1)")
|
||||
} else {
|
||||
val ffExtension = Injekt.get<DownloadAddonManager>().extension?.extension!!
|
||||
val extension = ffExtension.getFileExtension()
|
||||
val tempFile =
|
||||
directory.createFile(extension.second, "temp.${extension.first}")
|
||||
?: throw Exception("Temp file is null")
|
||||
val tempPath = ffExtension.setDownloadPath(
|
||||
context,
|
||||
tempFile.uri
|
||||
)
|
||||
val videoPath = ffExtension.getReadPath(
|
||||
context,
|
||||
videoFiles[0].uri
|
||||
)
|
||||
|
||||
val id = ffExtension.customFFMpeg(
|
||||
"1", listOf(videoPath, tempPath)
|
||||
) { log ->
|
||||
Logger.log(log)
|
||||
}
|
||||
val timeOut = System.currentTimeMillis() + 1000 * 60 * 10
|
||||
while (ffExtension.getState(id) != "COMPLETED") {
|
||||
if (ffExtension.getState(id) == "FAILED") {
|
||||
Logger.log("Failed to fix download")
|
||||
ffExtension.getStackTrace(id)?.let {
|
||||
Logger.log(it)
|
||||
}
|
||||
toast(R.string.failed_to_fix)
|
||||
return@launchIO
|
||||
}
|
||||
if (System.currentTimeMillis() > timeOut) {
|
||||
Logger.log("Failed to fix download: Timeout")
|
||||
toast(R.string.failed_to_fix)
|
||||
return@launchIO
|
||||
}
|
||||
}
|
||||
if (ffExtension.hadError(id)) {
|
||||
Logger.log("Failed to fix download: ${ffExtension.getStackTrace(id)}")
|
||||
toast(R.string.failed_to_fix)
|
||||
return@launchIO
|
||||
}
|
||||
val name = videoFiles[0].name
|
||||
if (videoFiles[0].delete().not()) {
|
||||
toast(R.string.delete_fail)
|
||||
return@launchIO
|
||||
}
|
||||
tempFile.renameTo(name!!)
|
||||
toast(context.getString(R.string.success) + " (2)")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
toast(getString(R.string.error_msg, e.message))
|
||||
Logger.log(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val downloadStatusReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (!this@AnimeWatchFragment::episodeAdapter.isInitialized) return
|
||||
@@ -528,7 +635,7 @@ class AnimeWatchFragment : Fragment() {
|
||||
private fun reload() {
|
||||
val selected = model.loadSelected(media)
|
||||
|
||||
//Find latest episode for subscription
|
||||
// Find latest episode for subscription
|
||||
selected.latest =
|
||||
media.anime?.episodes?.values?.maxOfOrNull { it.number.toFloatOrNull() ?: 0f } ?: 0f
|
||||
selected.latest =
|
||||
@@ -572,14 +679,14 @@ class AnimeWatchFragment : Fragment() {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
binding.mediaInfoProgressBar.visibility = progress
|
||||
binding.animeSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
binding.mediaSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
|
||||
requireActivity().setNavigationTheme()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
state = binding.animeSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
state = binding.mediaSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -23,6 +23,7 @@ import ani.dantotsu.media.MediaNameAdapter
|
||||
import ani.dantotsu.media.MediaType
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.bumptech.glide.Glide
|
||||
import com.bumptech.glide.load.model.GlideUrl
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -106,8 +107,8 @@ class EpisodeAdapter(
|
||||
|
||||
val thumb =
|
||||
ep.thumb?.let { if (it.url.isNotEmpty()) GlideUrl(it.url) { it.headers } else null }
|
||||
Glide.with(binding.itemEpisodeImage).load(thumb ?: media.cover).override(400, 0)
|
||||
.into(binding.itemEpisodeImage)
|
||||
Glide.with(binding.itemMediaImage).load(thumb ?: media.cover).override(400, 0)
|
||||
.into(binding.itemMediaImage)
|
||||
binding.itemEpisodeNumber.text = ep.number
|
||||
binding.itemEpisodeTitle.text = if (ep.number == title) "Episode $title" else title
|
||||
|
||||
@@ -140,9 +141,9 @@ class EpisodeAdapter(
|
||||
}
|
||||
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
ep.number
|
||||
)
|
||||
@@ -154,8 +155,8 @@ class EpisodeAdapter(
|
||||
|
||||
val thumb =
|
||||
ep.thumb?.let { if (it.url.isNotEmpty()) GlideUrl(it.url) { it.headers } else null }
|
||||
Glide.with(binding.itemEpisodeImage).load(thumb ?: media.cover).override(400, 0)
|
||||
.into(binding.itemEpisodeImage)
|
||||
Glide.with(binding.itemMediaImage).load(thumb ?: media.cover).override(400, 0)
|
||||
.into(binding.itemMediaImage)
|
||||
|
||||
binding.itemEpisodeNumber.text = ep.number
|
||||
binding.itemEpisodeTitle.text = title
|
||||
@@ -183,9 +184,9 @@ class EpisodeAdapter(
|
||||
binding.itemEpisodeViewed.visibility = View.GONE
|
||||
}
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
ep.number
|
||||
)
|
||||
@@ -208,9 +209,9 @@ class EpisodeAdapter(
|
||||
}
|
||||
}
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
ep.number
|
||||
)
|
||||
@@ -318,22 +319,30 @@ class EpisodeAdapter(
|
||||
fragment.onAnimeEpisodeStopDownloadClick(episodeNumber)
|
||||
return@setOnClickListener
|
||||
} else if (downloadedEpisodes.contains(episodeNumber)) {
|
||||
val builder = AlertDialog.Builder(currContext(), R.style.MyPopup)
|
||||
builder.setTitle("Delete Episode")
|
||||
builder.setMessage("Are you sure you want to delete Episode ${episodeNumber}?")
|
||||
builder.setPositiveButton("Yes") { _, _ ->
|
||||
fragment.onAnimeEpisodeRemoveDownloadClick(episodeNumber)
|
||||
}
|
||||
builder.setNegativeButton("No") { _, _ ->
|
||||
}
|
||||
val dialog = builder.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
binding.root.context.customAlertDialog().apply {
|
||||
setTitle("Delete Episode")
|
||||
setMessage("Are you sure you want to delete Episode $episodeNumber?")
|
||||
setPosButton(R.string.yes) {
|
||||
fragment.onAnimeEpisodeRemoveDownloadClick(episodeNumber)
|
||||
}
|
||||
setNegButton(R.string.no)
|
||||
}.show()
|
||||
return@setOnClickListener
|
||||
} else {
|
||||
fragment.onAnimeEpisodeDownloadClick(episodeNumber)
|
||||
}
|
||||
}
|
||||
}
|
||||
binding.itemDownload.setOnLongClickListener {
|
||||
if (0 <= bindingAdapterPosition && bindingAdapterPosition < arr.size) {
|
||||
val episodeNumber = arr[bindingAdapterPosition].number
|
||||
if (downloadedEpisodes.contains(episodeNumber)) {
|
||||
fragment.fixDownload(episodeNumber)
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
binding.itemEpisodeDesc.setOnClickListener {
|
||||
if (binding.itemEpisodeDesc.maxLines == 3)
|
||||
binding.itemEpisodeDesc.maxLines = 100
|
||||
|
||||
@@ -101,6 +101,7 @@ import androidx.mediarouter.app.MediaRouteButton
|
||||
import ani.dantotsu.GesturesListener
|
||||
import ani.dantotsu.NoPaddingArrayAdapter
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.addons.download.DownloadAddonManager
|
||||
import ani.dantotsu.brightnessConverter
|
||||
import ani.dantotsu.circularReveal
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
@@ -1552,6 +1553,7 @@ class ExoplayerView : AppCompatActivity(), Player.Listener, SessionAvailabilityL
|
||||
println(files)
|
||||
val docFile = directory.listFiles().firstOrNull {
|
||||
it.name?.endsWith(".mp4") == true || it.name?.endsWith(".mkv") == true
|
||||
|| it.name?.endsWith(".${Injekt.get<DownloadAddonManager>().extension?.extension?.getFileExtension()?.first ?: "ts"}") == true
|
||||
}
|
||||
if (docFile != null) {
|
||||
val uri = docFile.uri
|
||||
|
||||
@@ -444,15 +444,12 @@ class SelectorDialogFragment : BottomSheetDialogFragment() {
|
||||
if (subtitles.isNotEmpty()) {
|
||||
val subtitleNames = subtitles.map { it.language }
|
||||
var subtitleToDownload: Subtitle? = null
|
||||
val alertDialog = AlertDialog.Builder(context, R.style.MyPopup)
|
||||
.setTitle(R.string.download_subtitle)
|
||||
.setSingleChoiceItems(
|
||||
subtitleNames.toTypedArray(),
|
||||
-1
|
||||
) { _, which ->
|
||||
requireActivity().customAlertDialog().apply {
|
||||
setTitle(R.string.download_subtitle)
|
||||
singleChoiceItems(subtitleNames.toTypedArray()) {which ->
|
||||
subtitleToDownload = subtitles[which]
|
||||
}
|
||||
.setPositiveButton(R.string.download) { dialog, _ ->
|
||||
setPosButton(R.string.download) {
|
||||
scope.launch {
|
||||
if (subtitleToDownload != null) {
|
||||
SubtitleDownloader.downloadSubtitle(
|
||||
@@ -466,13 +463,9 @@ class SelectorDialogFragment : BottomSheetDialogFragment() {
|
||||
)
|
||||
}
|
||||
}
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNegativeButton(R.string.cancel) { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
}
|
||||
.show()
|
||||
alertDialog.window?.setDimAmount(0.8f)
|
||||
setNegButton(R.string.cancel) {}
|
||||
}.show()
|
||||
} else {
|
||||
snackString(R.string.no_subtitles_available)
|
||||
}
|
||||
@@ -576,65 +569,63 @@ class SelectorDialogFragment : BottomSheetDialogFragment() {
|
||||
if (audioTracks.isNotEmpty()) {
|
||||
val audioNamesArray = audioTracks.toTypedArray()
|
||||
val checkedItems = BooleanArray(audioNamesArray.size) { false }
|
||||
val alertDialog = AlertDialog.Builder(currContext, R.style.MyPopup)
|
||||
.setTitle(R.string.download_audio_tracks)
|
||||
.setMultiChoiceItems(audioNamesArray, checkedItems) { _, which, isChecked ->
|
||||
val audioPair = Pair(extractor.audioTracks[which].url, extractor.audioTracks[which].lang)
|
||||
if (isChecked) {
|
||||
selectedAudioTracks.add(audioPair)
|
||||
} else {
|
||||
selectedAudioTracks.remove(audioPair)
|
||||
|
||||
currContext.customAlertDialog().apply{ // ToTest
|
||||
setTitle(R.string.download_audio_tracks)
|
||||
multiChoiceItems(audioNamesArray, checkedItems) {
|
||||
it.forEachIndexed { index, isChecked ->
|
||||
val audioPair = Pair(extractor.audioTracks[index].url, extractor.audioTracks[index].lang)
|
||||
if (isChecked) {
|
||||
selectedAudioTracks.add(audioPair)
|
||||
} else {
|
||||
selectedAudioTracks.remove(audioPair)
|
||||
}
|
||||
}
|
||||
}
|
||||
.setPositiveButton(R.string.download) { _, _ ->
|
||||
dialog?.dismiss()
|
||||
setPosButton(R.string.download) {
|
||||
go()
|
||||
}
|
||||
.setNegativeButton(R.string.skip) { dialog, _ ->
|
||||
setNegButton(R.string.skip) {
|
||||
selectedAudioTracks = mutableListOf()
|
||||
go()
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNeutralButton(R.string.cancel) { dialog, _ ->
|
||||
setNeutralButton(R.string.cancel) {
|
||||
selectedAudioTracks = mutableListOf()
|
||||
dialog.dismiss()
|
||||
}
|
||||
.show()
|
||||
alertDialog.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
go()
|
||||
}
|
||||
}
|
||||
if (subtitles.isNotEmpty()) {
|
||||
if (subtitles.isNotEmpty()) { // ToTest
|
||||
val subtitleNamesArray = subtitleNames.toTypedArray()
|
||||
val checkedItems = BooleanArray(subtitleNamesArray.size) { false }
|
||||
|
||||
val alertDialog = AlertDialog.Builder(currContext, R.style.MyPopup)
|
||||
.setTitle(R.string.download_subtitle)
|
||||
.setMultiChoiceItems(subtitleNamesArray, checkedItems) { _, which, isChecked ->
|
||||
val subtitlePair = Pair(subtitles[which].file.url, subtitles[which].language)
|
||||
if (isChecked) {
|
||||
selectedSubtitles.add(subtitlePair)
|
||||
} else {
|
||||
selectedSubtitles.remove(subtitlePair)
|
||||
currContext.customAlertDialog().apply {
|
||||
setTitle(R.string.download_subtitle)
|
||||
multiChoiceItems(subtitleNamesArray, checkedItems) {
|
||||
it.forEachIndexed { index, isChecked ->
|
||||
val subtitlePair = Pair(subtitles[index].file.url, subtitles[index].language)
|
||||
if (isChecked) {
|
||||
selectedSubtitles.add(subtitlePair)
|
||||
} else {
|
||||
selectedSubtitles.remove(subtitlePair)
|
||||
}
|
||||
}
|
||||
}
|
||||
.setPositiveButton(R.string.download) { _, _ ->
|
||||
dialog?.dismiss()
|
||||
setPosButton(R.string.download) {
|
||||
checkAudioTracks()
|
||||
}
|
||||
.setNegativeButton(R.string.skip) { dialog, _ ->
|
||||
setNegButton(R.string.skip) {
|
||||
selectedSubtitles = mutableListOf()
|
||||
checkAudioTracks()
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNeutralButton(R.string.cancel) { dialog, _ ->
|
||||
setNeutralButton(R.string.cancel) {
|
||||
selectedSubtitles = mutableListOf()
|
||||
dialog.dismiss()
|
||||
}
|
||||
.show()
|
||||
alertDialog.window?.setDimAmount(0.8f)
|
||||
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
checkAudioTracks()
|
||||
}
|
||||
|
||||
@@ -14,12 +14,14 @@ import ani.dantotsu.copyToClipboard
|
||||
import ani.dantotsu.databinding.ItemCommentsBinding
|
||||
import ani.dantotsu.getAppString
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.openImage
|
||||
import ani.dantotsu.others.ImageViewDialog
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.ColorEditor.Companion.adjustColorForContrast
|
||||
import ani.dantotsu.util.ColorEditor.Companion.getContrastRatio
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import com.xwray.groupie.Section
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
@@ -251,13 +253,10 @@ class CommentItem(
|
||||
}
|
||||
}
|
||||
commentTotalVotes.text = (comment.upvotes - comment.downvotes).toString()
|
||||
commentUserAvatar.setOnLongClickListener {
|
||||
ImageViewDialog.newInstance(
|
||||
commentsFragment.activity,
|
||||
commentsFragment.activity.getString(R.string.avatar, comment.username),
|
||||
comment.profilePictureUrl
|
||||
)
|
||||
}
|
||||
commentUserAvatar.openImage(
|
||||
commentsFragment.activity.getString(R.string.avatar, comment.username),
|
||||
comment.profilePictureUrl ?: ""
|
||||
)
|
||||
comment.profilePictureUrl?.let { commentUserAvatar.loadImage(it) }
|
||||
commentUserName.text = comment.username
|
||||
val userColor = "[${levelColor.second}]"
|
||||
@@ -387,19 +386,14 @@ class CommentItem(
|
||||
* @param callback the callback to call when the user clicks yes
|
||||
*/
|
||||
private fun dialogBuilder(title: String, message: String, callback: () -> Unit) {
|
||||
val alertDialog =
|
||||
android.app.AlertDialog.Builder(commentsFragment.activity, R.style.MyPopup)
|
||||
.setTitle(title)
|
||||
.setMessage(message)
|
||||
.setPositiveButton("Yes") { dialog, _ ->
|
||||
callback()
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNegativeButton("No") { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
}
|
||||
val dialog = alertDialog.show()
|
||||
dialog?.window?.setDimAmount(0.8f)
|
||||
commentsFragment.activity.customAlertDialog().apply {
|
||||
setTitle(title)
|
||||
setMessage(message)
|
||||
setPosButton("Yes") {
|
||||
callback()
|
||||
}
|
||||
setNegButton("No") {}
|
||||
}.show()
|
||||
}
|
||||
|
||||
private val usernameColors: Array<String> = arrayOf(
|
||||
|
||||
@@ -25,6 +25,7 @@ import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.comments.Comment
|
||||
import ani.dantotsu.connections.comments.CommentResponse
|
||||
import ani.dantotsu.connections.comments.CommentsAPI
|
||||
import ani.dantotsu.databinding.DialogEdittextBinding
|
||||
import ani.dantotsu.databinding.FragmentCommentsBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
@@ -34,6 +35,7 @@ import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import com.xwray.groupie.Section
|
||||
import io.noties.markwon.editor.MarkwonEditor
|
||||
@@ -162,33 +164,26 @@ class CommentsFragment : Fragment() {
|
||||
}
|
||||
|
||||
binding.commentFilter.setOnClickListener {
|
||||
val alertDialog = AlertDialog.Builder(activity, R.style.MyPopup)
|
||||
.setTitle("Enter a chapter/episode number tag")
|
||||
.setView(R.layout.dialog_edittext)
|
||||
.setPositiveButton("OK") { dialog, _ ->
|
||||
val editText =
|
||||
(dialog as AlertDialog).findViewById<EditText>(R.id.dialogEditText)
|
||||
val text = editText?.text.toString()
|
||||
activity.customAlertDialog().apply {
|
||||
val customView = DialogEdittextBinding.inflate(layoutInflater)
|
||||
setTitle("Enter a chapter/episode number tag")
|
||||
setCustomView(customView.root)
|
||||
setPosButton("OK") {
|
||||
val text = customView.dialogEditText.text.toString()
|
||||
filterTag = text.toIntOrNull()
|
||||
lifecycleScope.launch {
|
||||
loadAndDisplayComments()
|
||||
}
|
||||
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNeutralButton("Clear") { dialog, _ ->
|
||||
setNeutralButton("Clear") {
|
||||
filterTag = null
|
||||
lifecycleScope.launch {
|
||||
loadAndDisplayComments()
|
||||
}
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNegativeButton("Cancel") { dialog, _ ->
|
||||
filterTag = null
|
||||
dialog.dismiss()
|
||||
}
|
||||
val dialog = alertDialog.show()
|
||||
dialog?.window?.setDimAmount(0.8f)
|
||||
setNegButton("Cancel") { filterTag = null }
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
var isFetching = false
|
||||
@@ -303,13 +298,12 @@ class CommentsFragment : Fragment() {
|
||||
|
||||
activity.binding.commentLabel.setOnClickListener {
|
||||
//alert dialog to enter a number, with a cancel and ok button
|
||||
val alertDialog = AlertDialog.Builder(activity, R.style.MyPopup)
|
||||
.setTitle("Enter a chapter/episode number tag")
|
||||
.setView(R.layout.dialog_edittext)
|
||||
.setPositiveButton("OK") { dialog, _ ->
|
||||
val editText =
|
||||
(dialog as AlertDialog).findViewById<EditText>(R.id.dialogEditText)
|
||||
val text = editText?.text.toString()
|
||||
activity.customAlertDialog().apply {
|
||||
val customView = DialogEdittextBinding.inflate(layoutInflater)
|
||||
setTitle("Enter a chapter/episode number tag")
|
||||
setCustomView(customView.root)
|
||||
setPosButton("OK") {
|
||||
val text = customView.dialogEditText.text.toString()
|
||||
tag = text.toIntOrNull()
|
||||
if (tag == null) {
|
||||
activity.binding.commentLabel.background = ResourcesCompat.getDrawable(
|
||||
@@ -324,28 +318,25 @@ class CommentsFragment : Fragment() {
|
||||
null
|
||||
)
|
||||
}
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNeutralButton("Clear") { dialog, _ ->
|
||||
setNeutralButton("Clear") {
|
||||
tag = null
|
||||
activity.binding.commentLabel.background = ResourcesCompat.getDrawable(
|
||||
resources,
|
||||
R.drawable.ic_label_off_24,
|
||||
null
|
||||
)
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNegativeButton("Cancel") { dialog, _ ->
|
||||
setNegButton("Cancel") {
|
||||
tag = null
|
||||
activity.binding.commentLabel.background = ResourcesCompat.getDrawable(
|
||||
resources,
|
||||
R.drawable.ic_label_off_24,
|
||||
null
|
||||
)
|
||||
dialog.dismiss()
|
||||
}
|
||||
val dialog = alertDialog.show()
|
||||
dialog?.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,12 +353,6 @@ class CommentsFragment : Fragment() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
@@ -579,9 +564,9 @@ class CommentsFragment : Fragment() {
|
||||
* Called when the user tries to comment for the first time
|
||||
*/
|
||||
private fun showCommentRulesDialog() {
|
||||
val alertDialog = AlertDialog.Builder(activity, R.style.MyPopup)
|
||||
.setTitle("Commenting Rules")
|
||||
.setMessage(
|
||||
activity.customAlertDialog().apply{
|
||||
setTitle("Commenting Rules")
|
||||
setMessage(
|
||||
"I WILL BAN YOU WITHOUT HESITATION\n" +
|
||||
"1. No racism\n" +
|
||||
"2. No hate speech\n" +
|
||||
@@ -594,16 +579,13 @@ class CommentsFragment : Fragment() {
|
||||
"10. No illegal content\n" +
|
||||
"11. Anything you know you shouldn't comment\n"
|
||||
)
|
||||
.setPositiveButton("I Understand") { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
setPosButton("I Understand") {
|
||||
PrefManager.setVal(PrefName.FirstComment, false)
|
||||
processComment()
|
||||
}
|
||||
.setNegativeButton("Cancel") { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
}
|
||||
val dialog = alertDialog.show()
|
||||
dialog?.window?.setDimAmount(0.8f)
|
||||
setNegButton(R.string.cancel)
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun processComment() {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package ani.dantotsu.media.manga
|
||||
|
||||
import android.app.AlertDialog
|
||||
import android.content.Intent
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
@@ -19,8 +18,9 @@ import androidx.recyclerview.widget.RecyclerView
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.currActivity
|
||||
import ani.dantotsu.currContext
|
||||
import ani.dantotsu.databinding.CustomDialogLayoutBinding
|
||||
import ani.dantotsu.databinding.DialogLayoutBinding
|
||||
import ani.dantotsu.databinding.ItemAnimeWatchBinding
|
||||
import ani.dantotsu.databinding.ItemMediaSourceBinding
|
||||
import ani.dantotsu.databinding.ItemChipBinding
|
||||
import ani.dantotsu.isOnline
|
||||
import ani.dantotsu.loadImage
|
||||
@@ -35,11 +35,13 @@ import ani.dantotsu.others.webview.CookieCatcher
|
||||
import ani.dantotsu.parsers.DynamicMangaParser
|
||||
import ani.dantotsu.parsers.MangaReadSources
|
||||
import ani.dantotsu.parsers.MangaSources
|
||||
import ani.dantotsu.parsers.OfflineMangaParser
|
||||
import ani.dantotsu.px
|
||||
import ani.dantotsu.settings.FAQActivity
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.chip.Chip
|
||||
import eu.kanade.tachiyomi.data.notification.Notifications.CHANNEL_SUBSCRIPTION_CHECK
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
@@ -55,31 +57,29 @@ class MangaReadAdapter(
|
||||
) : RecyclerView.Adapter<MangaReadAdapter.ViewHolder>() {
|
||||
|
||||
var subscribe: MediaDetailsActivity.PopImageButton? = null
|
||||
private var _binding: ItemAnimeWatchBinding? = null
|
||||
private var _binding: ItemMediaSourceBinding? = null
|
||||
val hiddenScanlators = mutableListOf<String>()
|
||||
var scanlatorSelectionListener: ScanlatorSelectionListener? = null
|
||||
var options = listOf<String>()
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
val bind = ItemAnimeWatchBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
val bind = ItemMediaSourceBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
return ViewHolder(bind)
|
||||
}
|
||||
|
||||
private var nestedDialog: AlertDialog? = null
|
||||
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
val binding = holder.binding
|
||||
_binding = binding
|
||||
binding.sourceTitle.setText(R.string.chaps)
|
||||
|
||||
//Fuck u launch
|
||||
// Fuck u launch
|
||||
binding.faqbutton.setOnClickListener {
|
||||
val intent = Intent(fragment.requireContext(), FAQActivity::class.java)
|
||||
startActivity(fragment.requireContext(), intent, null)
|
||||
}
|
||||
|
||||
//Wrong Title
|
||||
binding.animeSourceSearch.setOnClickListener {
|
||||
// Wrong Title
|
||||
binding.mediaSourceSearch.setOnClickListener {
|
||||
SourceSearchDialogFragment().show(
|
||||
fragment.requireActivity().supportFragmentManager,
|
||||
null
|
||||
@@ -87,54 +87,54 @@ class MangaReadAdapter(
|
||||
}
|
||||
val offline = !isOnline(binding.root.context) || PrefManager.getVal(PrefName.OfflineMode)
|
||||
|
||||
binding.animeSourceNameContainer.isGone = offline
|
||||
binding.animeSourceSettings.isGone = offline
|
||||
binding.animeSourceSearch.isGone = offline
|
||||
binding.animeSourceTitle.isGone = offline
|
||||
//Source Selection
|
||||
binding.mediaSourceNameContainer.isGone = offline
|
||||
binding.mediaSourceSettings.isGone = offline
|
||||
binding.mediaSourceSearch.isGone = offline
|
||||
binding.mediaSourceTitle.isGone = offline
|
||||
// Source Selection
|
||||
var source =
|
||||
media.selected!!.sourceIndex.let { if (it >= mangaReadSources.names.size) 0 else it }
|
||||
setLanguageList(media.selected!!.langIndex, source)
|
||||
if (mangaReadSources.names.isNotEmpty() && source in 0 until mangaReadSources.names.size) {
|
||||
binding.animeSource.setText(mangaReadSources.names[source])
|
||||
binding.mediaSource.setText(mangaReadSources.names[source])
|
||||
mangaReadSources[source].apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
}
|
||||
}
|
||||
media.selected?.scanlators?.let {
|
||||
hiddenScanlators.addAll(it)
|
||||
}
|
||||
binding.animeSource.setAdapter(
|
||||
binding.mediaSource.setAdapter(
|
||||
ArrayAdapter(
|
||||
fragment.requireContext(),
|
||||
R.layout.item_dropdown,
|
||||
mangaReadSources.names
|
||||
)
|
||||
)
|
||||
binding.animeSourceTitle.isSelected = true
|
||||
binding.animeSource.setOnItemClickListener { _, _, i, _ ->
|
||||
binding.mediaSourceTitle.isSelected = true
|
||||
binding.mediaSource.setOnItemClickListener { _, _, i, _ ->
|
||||
fragment.onSourceChange(i).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener = { MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
source = i
|
||||
setLanguageList(0, i)
|
||||
}
|
||||
subscribeButton(false)
|
||||
//invalidate if it's the last source
|
||||
// Invalidate if it's the last source
|
||||
val invalidate = i == mangaReadSources.names.size - 1
|
||||
fragment.loadChapters(i, invalidate)
|
||||
}
|
||||
|
||||
binding.animeSourceLanguage.setOnItemClickListener { _, _, i, _ ->
|
||||
binding.mediaSourceLanguage.setOnItemClickListener { _, _, i, _ ->
|
||||
// Check if 'extension' and 'selected' properties exist and are accessible
|
||||
(mangaReadSources[source] as? DynamicMangaParser)?.let { ext ->
|
||||
ext.sourceLanguage = i
|
||||
fragment.onLangChange(i, ext.saveName)
|
||||
fragment.onSourceChange(media.selected!!.sourceIndex).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener =
|
||||
{ MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
{ MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
setLanguageList(i, source)
|
||||
}
|
||||
subscribeButton(false)
|
||||
@@ -143,17 +143,17 @@ class MangaReadAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
//settings
|
||||
binding.animeSourceSettings.setOnClickListener {
|
||||
// Settings
|
||||
binding.mediaSourceSettings.setOnClickListener {
|
||||
(mangaReadSources[source] as? DynamicMangaParser)?.let { ext ->
|
||||
fragment.openSettings(ext.extension)
|
||||
}
|
||||
}
|
||||
|
||||
//Grids
|
||||
// Grids
|
||||
subscribe = MediaDetailsActivity.PopImageButton(
|
||||
fragment.lifecycleScope,
|
||||
binding.animeSourceSubscribe,
|
||||
binding.mediaSourceSubscribe,
|
||||
R.drawable.ic_round_notifications_active_24,
|
||||
R.drawable.ic_round_notifications_none_24,
|
||||
R.color.bg_opp,
|
||||
@@ -161,206 +161,191 @@ class MangaReadAdapter(
|
||||
fragment.subscribed,
|
||||
true
|
||||
) {
|
||||
fragment.onNotificationPressed(it, binding.animeSource.text.toString())
|
||||
fragment.onNotificationPressed(it, binding.mediaSource.text.toString())
|
||||
}
|
||||
|
||||
subscribeButton(false)
|
||||
|
||||
binding.animeSourceSubscribe.setOnLongClickListener {
|
||||
binding.mediaSourceSubscribe.setOnLongClickListener {
|
||||
openSettings(fragment.requireContext(), CHANNEL_SUBSCRIPTION_CHECK)
|
||||
}
|
||||
|
||||
binding.animeNestedButton.setOnClickListener {
|
||||
|
||||
val dialogView =
|
||||
LayoutInflater.from(fragment.requireContext()).inflate(R.layout.dialog_layout, null)
|
||||
val dialogBinding = DialogLayoutBinding.bind(dialogView)
|
||||
binding.mediaNestedButton.setOnClickListener {
|
||||
val dialogBinding = DialogLayoutBinding.inflate(fragment.layoutInflater)
|
||||
var refresh = false
|
||||
var run = false
|
||||
var reversed = media.selected!!.recyclerReversed
|
||||
var style =
|
||||
media.selected!!.recyclerStyle ?: PrefManager.getVal(PrefName.MangaDefaultView)
|
||||
dialogBinding.animeSourceTop.rotation = if (reversed) -90f else 90f
|
||||
dialogBinding.sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
dialogBinding.animeSourceTop.setOnClickListener {
|
||||
reversed = !reversed
|
||||
dialogBinding.animeSourceTop.rotation = if (reversed) -90f else 90f
|
||||
dialogBinding.sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
run = true
|
||||
}
|
||||
dialogBinding.apply {
|
||||
mediaSourceTop.rotation = if (reversed) -90f else 90f
|
||||
sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
mediaSourceTop.setOnClickListener {
|
||||
reversed = !reversed
|
||||
mediaSourceTop.rotation = if (reversed) -90f else 90f
|
||||
sortText.text = if (reversed) "Down to Up" else "Up to Down"
|
||||
run = true
|
||||
}
|
||||
|
||||
//Grids
|
||||
dialogBinding.animeSourceGrid.visibility = View.GONE
|
||||
var selected = when (style) {
|
||||
0 -> dialogBinding.animeSourceList
|
||||
1 -> dialogBinding.animeSourceCompact
|
||||
else -> dialogBinding.animeSourceList
|
||||
}
|
||||
when (style) {
|
||||
0 -> dialogBinding.layoutText.setText(R.string.list)
|
||||
1 -> dialogBinding.layoutText.setText(R.string.compact)
|
||||
else -> dialogBinding.animeSourceList
|
||||
}
|
||||
selected.alpha = 1f
|
||||
fun selected(it: ImageButton) {
|
||||
selected.alpha = 0.33f
|
||||
selected = it
|
||||
// Grids
|
||||
mediaSourceGrid.visibility = View.GONE
|
||||
var selected = when (style) {
|
||||
0 -> mediaSourceList
|
||||
1 -> mediaSourceCompact
|
||||
else -> mediaSourceList
|
||||
}
|
||||
when (style) {
|
||||
0 -> layoutText.setText(R.string.list)
|
||||
1 -> layoutText.setText(R.string.compact)
|
||||
else -> mediaSourceList
|
||||
}
|
||||
selected.alpha = 1f
|
||||
}
|
||||
dialogBinding.animeSourceList.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 0
|
||||
dialogBinding.layoutText.setText(R.string.list)
|
||||
run = true
|
||||
}
|
||||
dialogBinding.animeSourceCompact.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 1
|
||||
dialogBinding.layoutText.setText(R.string.compact)
|
||||
run = true
|
||||
}
|
||||
dialogBinding.animeWebviewContainer.setOnClickListener {
|
||||
if (!WebViewUtil.supportsWebView(fragment.requireContext())) {
|
||||
toast(R.string.webview_not_installed)
|
||||
fun selected(it: ImageButton) {
|
||||
selected.alpha = 0.33f
|
||||
selected = it
|
||||
selected.alpha = 1f
|
||||
}
|
||||
//start CookieCatcher activity
|
||||
if (mangaReadSources.names.isNotEmpty() && source in 0 until mangaReadSources.names.size) {
|
||||
val sourceAHH = mangaReadSources[source] as? DynamicMangaParser
|
||||
val sourceHttp = sourceAHH?.extension?.sources?.firstOrNull() as? HttpSource
|
||||
val url = sourceHttp?.baseUrl
|
||||
url?.let {
|
||||
refresh = true
|
||||
val intent = Intent(fragment.requireContext(), CookieCatcher::class.java)
|
||||
.putExtra("url", url)
|
||||
startActivity(fragment.requireContext(), intent, null)
|
||||
mediaSourceList.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 0
|
||||
layoutText.setText(R.string.list)
|
||||
run = true
|
||||
}
|
||||
mediaSourceCompact.setOnClickListener {
|
||||
selected(it as ImageButton)
|
||||
style = 1
|
||||
layoutText.setText(R.string.compact)
|
||||
run = true
|
||||
}
|
||||
mediaWebviewContainer.setOnClickListener {
|
||||
if (!WebViewUtil.supportsWebView(fragment.requireContext())) {
|
||||
toast(R.string.webview_not_installed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Multi download
|
||||
dialogBinding.downloadNo.text = "0"
|
||||
dialogBinding.animeDownloadTop.setOnClickListener {
|
||||
//Alert dialog asking for the number of chapters to download
|
||||
val alertDialog = AlertDialog.Builder(currContext(), R.style.MyPopup)
|
||||
alertDialog.setTitle("Multi Chapter Downloader")
|
||||
alertDialog.setMessage("Enter the number of chapters to download")
|
||||
val input = NumberPicker(currContext())
|
||||
input.minValue = 1
|
||||
input.maxValue = 20
|
||||
input.value = 1
|
||||
alertDialog.setView(input)
|
||||
alertDialog.setPositiveButton("OK") { _, _ ->
|
||||
dialogBinding.downloadNo.text = "${input.value}"
|
||||
}
|
||||
alertDialog.setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() }
|
||||
val dialog = alertDialog.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
}
|
||||
|
||||
//Scanlator
|
||||
dialogBinding.animeScanlatorContainer.isVisible = options.count() > 1
|
||||
dialogBinding.scanlatorNo.text = "${options.count()}"
|
||||
dialogBinding.animeScanlatorTop.setOnClickListener {
|
||||
val dialogView2 =
|
||||
LayoutInflater.from(currContext()).inflate(R.layout.custom_dialog_layout, null)
|
||||
val checkboxContainer =
|
||||
dialogView2.findViewById<LinearLayout>(R.id.checkboxContainer)
|
||||
val tickAllButton = dialogView2.findViewById<ImageButton>(R.id.toggleButton)
|
||||
|
||||
// Function to get the right image resource for the toggle button
|
||||
fun getToggleImageResource(container: ViewGroup): Int {
|
||||
var allChecked = true
|
||||
var allUnchecked = true
|
||||
|
||||
for (i in 0 until container.childCount) {
|
||||
val checkBox = container.getChildAt(i) as CheckBox
|
||||
if (!checkBox.isChecked) {
|
||||
allChecked = false
|
||||
} else {
|
||||
allUnchecked = false
|
||||
// Start CookieCatcher activity
|
||||
if (mangaReadSources.names.isNotEmpty() && source in 0 until mangaReadSources.names.size) {
|
||||
val sourceAHH = mangaReadSources[source] as? DynamicMangaParser
|
||||
val sourceHttp = sourceAHH?.extension?.sources?.firstOrNull() as? HttpSource
|
||||
val url = sourceHttp?.baseUrl
|
||||
url?.let {
|
||||
refresh = true
|
||||
val intent =
|
||||
Intent(fragment.requireContext(), CookieCatcher::class.java)
|
||||
.putExtra("url", url)
|
||||
startActivity(fragment.requireContext(), intent, null)
|
||||
}
|
||||
}
|
||||
return when {
|
||||
allChecked -> R.drawable.untick_all_boxes
|
||||
allUnchecked -> R.drawable.tick_all_boxes
|
||||
else -> R.drawable.invert_all_boxes
|
||||
}
|
||||
}
|
||||
|
||||
// Dynamically add checkboxes
|
||||
options.forEach { option ->
|
||||
val checkBox = CheckBox(currContext()).apply {
|
||||
text = option
|
||||
setOnCheckedChangeListener { _, _ ->
|
||||
// Update image resource when you change a checkbox
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
// Multi download
|
||||
downloadNo.text = "0"
|
||||
mediaDownloadTop.setOnClickListener {
|
||||
// Alert dialog asking for the number of chapters to download
|
||||
fragment.requireContext().customAlertDialog().apply {
|
||||
setTitle("Multi Chapter Downloader")
|
||||
setMessage("Enter the number of chapters to download")
|
||||
val input = NumberPicker(currContext())
|
||||
input.minValue = 1
|
||||
input.maxValue = 20
|
||||
input.value = 1
|
||||
setCustomView(input)
|
||||
setPosButton(R.string.ok) {
|
||||
downloadNo.text = "${input.value}"
|
||||
}
|
||||
setNegButton(R.string.cancel)
|
||||
show()
|
||||
}
|
||||
|
||||
// Set checked if its already selected
|
||||
if (media.selected!!.scanlators != null) {
|
||||
checkBox.isChecked = media.selected!!.scanlators?.contains(option) != true
|
||||
scanlatorSelectionListener?.onScanlatorsSelected()
|
||||
} else {
|
||||
checkBox.isChecked = true
|
||||
}
|
||||
checkboxContainer.addView(checkBox)
|
||||
}
|
||||
|
||||
// Create AlertDialog
|
||||
val dialog = AlertDialog.Builder(currContext(), R.style.MyPopup)
|
||||
.setView(dialogView2)
|
||||
.setPositiveButton("OK") { _, _ ->
|
||||
hiddenScanlators.clear()
|
||||
for (i in 0 until checkboxContainer.childCount) {
|
||||
val checkBox = checkboxContainer.getChildAt(i) as CheckBox
|
||||
// Scanlator
|
||||
mangaScanlatorContainer.isVisible = options.count() > 1
|
||||
scanlatorNo.text = "${options.count()}"
|
||||
mangaScanlatorTop.setOnClickListener {
|
||||
CustomDialogLayoutBinding.inflate(fragment.layoutInflater)
|
||||
val dialogView = CustomDialogLayoutBinding.inflate(fragment.layoutInflater)
|
||||
val checkboxContainer = dialogView.checkboxContainer
|
||||
val tickAllButton = dialogView.toggleButton
|
||||
|
||||
fun getToggleImageResource(container: ViewGroup): Int {
|
||||
var allChecked = true
|
||||
var allUnchecked = true
|
||||
|
||||
for (i in 0 until container.childCount) {
|
||||
val checkBox = container.getChildAt(i) as CheckBox
|
||||
if (!checkBox.isChecked) {
|
||||
hiddenScanlators.add(checkBox.text.toString())
|
||||
allChecked = false
|
||||
} else {
|
||||
allUnchecked = false
|
||||
}
|
||||
}
|
||||
fragment.onScanlatorChange(hiddenScanlators)
|
||||
scanlatorSelectionListener?.onScanlatorsSelected()
|
||||
}
|
||||
.setNegativeButton("Cancel", null)
|
||||
.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
|
||||
// Standard image resource
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
|
||||
// Listens to ticked checkboxes and changes image resource accordingly
|
||||
tickAllButton.setOnClickListener {
|
||||
// Toggle checkboxes
|
||||
for (i in 0 until checkboxContainer.childCount) {
|
||||
val checkBox = checkboxContainer.getChildAt(i) as CheckBox
|
||||
checkBox.isChecked = !checkBox.isChecked
|
||||
return when {
|
||||
allChecked -> R.drawable.untick_all_boxes
|
||||
allUnchecked -> R.drawable.tick_all_boxes
|
||||
else -> R.drawable.invert_all_boxes
|
||||
}
|
||||
}
|
||||
|
||||
// Update image resource
|
||||
options.forEach { option ->
|
||||
val checkBox = CheckBox(currContext()).apply {
|
||||
text = option
|
||||
setOnCheckedChangeListener { _, _ ->
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
}
|
||||
}
|
||||
|
||||
if (media.selected!!.scanlators != null) {
|
||||
checkBox.isChecked = media.selected!!.scanlators?.contains(option) != true
|
||||
scanlatorSelectionListener?.onScanlatorsSelected()
|
||||
} else {
|
||||
checkBox.isChecked = true
|
||||
}
|
||||
checkboxContainer.addView(checkBox)
|
||||
}
|
||||
|
||||
fragment.requireContext().customAlertDialog().apply {
|
||||
setCustomView(dialogView.root)
|
||||
setPosButton("OK") {
|
||||
hiddenScanlators.clear()
|
||||
for (i in 0 until checkboxContainer.childCount) {
|
||||
val checkBox = checkboxContainer.getChildAt(i) as CheckBox
|
||||
if (!checkBox.isChecked) {
|
||||
hiddenScanlators.add(checkBox.text.toString())
|
||||
}
|
||||
}
|
||||
fragment.onScanlatorChange(hiddenScanlators)
|
||||
scanlatorSelectionListener?.onScanlatorsSelected()
|
||||
}
|
||||
setNegButton("Cancel")
|
||||
}.show()
|
||||
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
|
||||
tickAllButton.setOnClickListener {
|
||||
for (i in 0 until checkboxContainer.childCount) {
|
||||
val checkBox = checkboxContainer.getChildAt(i) as CheckBox
|
||||
checkBox.isChecked = !checkBox.isChecked
|
||||
}
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
}
|
||||
}
|
||||
|
||||
fragment.requireContext().customAlertDialog().apply {
|
||||
setTitle("Options")
|
||||
setCustomView(root)
|
||||
setPosButton("OK") {
|
||||
if (run) fragment.onIconPressed(style, reversed)
|
||||
if (downloadNo.text != "0") {
|
||||
fragment.multiDownload(downloadNo.text.toString().toInt())
|
||||
}
|
||||
if (refresh) fragment.loadChapters(source, true)
|
||||
}
|
||||
setNegButton("Cancel") {
|
||||
if (refresh) fragment.loadChapters(source, true)
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
nestedDialog = AlertDialog.Builder(fragment.requireContext(), R.style.MyPopup)
|
||||
.setTitle("Options")
|
||||
.setView(dialogView)
|
||||
.setPositiveButton("OK") { _, _ ->
|
||||
if (run) fragment.onIconPressed(style, reversed)
|
||||
if (dialogBinding.downloadNo.text != "0") {
|
||||
fragment.multiDownload(dialogBinding.downloadNo.text.toString().toInt())
|
||||
}
|
||||
if (refresh) fragment.loadChapters(source, true)
|
||||
}
|
||||
.setNegativeButton("Cancel") { _, _ ->
|
||||
if (refresh) fragment.loadChapters(source, true)
|
||||
}
|
||||
.setOnCancelListener {
|
||||
if (refresh) fragment.loadChapters(source, true)
|
||||
}
|
||||
.create()
|
||||
nestedDialog?.show()
|
||||
}
|
||||
//Chapter Handling
|
||||
// Chapter Handling
|
||||
handleChapters()
|
||||
}
|
||||
|
||||
@@ -368,7 +353,7 @@ class MangaReadAdapter(
|
||||
subscribe?.enabled(enabled)
|
||||
}
|
||||
|
||||
//Chips
|
||||
// Chips
|
||||
fun updateChips(limit: Int, names: Array<String>, arr: Array<Int>, selected: Int = 0) {
|
||||
val binding = _binding
|
||||
if (binding != null) {
|
||||
@@ -379,13 +364,13 @@ class MangaReadAdapter(
|
||||
val chip =
|
||||
ItemChipBinding.inflate(
|
||||
LayoutInflater.from(fragment.context),
|
||||
binding.animeSourceChipGroup,
|
||||
binding.mediaSourceChipGroup,
|
||||
false
|
||||
).root
|
||||
chip.isCheckable = true
|
||||
fun selected() {
|
||||
chip.isChecked = true
|
||||
binding.animeWatchChipScroll.smoothScrollTo(
|
||||
binding.mediaWatchChipScroll.smoothScrollTo(
|
||||
(chip.left - screenWidth / 2) + (chip.width / 2),
|
||||
0
|
||||
)
|
||||
@@ -403,7 +388,7 @@ class MangaReadAdapter(
|
||||
} else {
|
||||
names[last - 1]
|
||||
}
|
||||
//chip.text = "${names[limit * (position)]} - ${names[last - 1]}"
|
||||
// chip.text = "${names[limit * (position)]} - ${names[last - 1]}"
|
||||
val chipText = "$startChapterString - $endChapterString"
|
||||
chip.text = chipText
|
||||
chip.setTextColor(
|
||||
@@ -417,14 +402,14 @@ class MangaReadAdapter(
|
||||
selected()
|
||||
fragment.onChipClicked(position, limit * (position), last - 1)
|
||||
}
|
||||
binding.animeSourceChipGroup.addView(chip)
|
||||
binding.mediaSourceChipGroup.addView(chip)
|
||||
if (selected == position) {
|
||||
selected()
|
||||
select = chip
|
||||
}
|
||||
}
|
||||
if (select != null)
|
||||
binding.animeWatchChipScroll.apply {
|
||||
binding.mediaWatchChipScroll.apply {
|
||||
post {
|
||||
scrollTo(
|
||||
(select.left - screenWidth / 2) + (select.width / 2),
|
||||
@@ -436,7 +421,7 @@ class MangaReadAdapter(
|
||||
}
|
||||
|
||||
fun clearChips() {
|
||||
_binding?.animeSourceChipGroup?.removeAllViews()
|
||||
_binding?.mediaSourceChipGroup?.removeAllViews()
|
||||
}
|
||||
|
||||
fun handleChapters() {
|
||||
@@ -462,70 +447,86 @@ class MangaReadAdapter(
|
||||
}
|
||||
if (formattedChapters.contains(continueEp)) {
|
||||
continueEp = chapters[formattedChapters.indexOf(continueEp)]
|
||||
binding.animeSourceContinue.visibility = View.VISIBLE
|
||||
binding.sourceContinue.visibility = View.VISIBLE
|
||||
handleProgress(
|
||||
binding.itemEpisodeProgressCont,
|
||||
binding.itemEpisodeProgress,
|
||||
binding.itemEpisodeProgressEmpty,
|
||||
binding.itemMediaProgressCont,
|
||||
binding.itemMediaProgress,
|
||||
binding.itemMediaProgressEmpty,
|
||||
media.id,
|
||||
continueEp
|
||||
)
|
||||
if ((binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams).weight > 0.8f) {
|
||||
if ((binding.itemMediaProgress.layoutParams as LinearLayout.LayoutParams).weight > 0.8f) {
|
||||
val e = chapters.indexOf(continueEp)
|
||||
if (e != -1 && e + 1 < chapters.size) {
|
||||
continueEp = chapters[e + 1]
|
||||
}
|
||||
}
|
||||
val ep = media.manga.chapters!![continueEp]!!
|
||||
binding.itemEpisodeImage.loadImage(media.banner ?: media.cover)
|
||||
binding.animeSourceContinueText.text =
|
||||
binding.itemMediaImage.loadImage(media.banner ?: media.cover)
|
||||
binding.mediaSourceContinueText.text =
|
||||
currActivity()!!.getString(
|
||||
R.string.continue_chapter,
|
||||
ep.number,
|
||||
if (!ep.title.isNullOrEmpty()) ep.title else ""
|
||||
)
|
||||
binding.animeSourceContinue.setOnClickListener {
|
||||
binding.sourceContinue.setOnClickListener {
|
||||
fragment.onMangaChapterClick(continueEp)
|
||||
}
|
||||
if (fragment.continueEp) {
|
||||
if ((binding.itemEpisodeProgress.layoutParams as LinearLayout.LayoutParams).weight < 0.8f) {
|
||||
binding.animeSourceContinue.performClick()
|
||||
if ((binding.itemMediaProgress.layoutParams as LinearLayout.LayoutParams).weight < 0.8f) {
|
||||
binding.sourceContinue.performClick()
|
||||
fragment.continueEp = false
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
binding.animeSourceContinue.visibility = View.GONE
|
||||
binding.sourceContinue.visibility = View.GONE
|
||||
}
|
||||
binding.animeSourceProgressBar.visibility = View.GONE
|
||||
val sourceFound = media.manga.chapters!!.isNotEmpty()
|
||||
binding.animeSourceNotFound.isGone = sourceFound
|
||||
|
||||
binding.sourceProgressBar.visibility = View.GONE
|
||||
|
||||
val sourceFound = filteredChapters.isNotEmpty()
|
||||
val isDownloadedSource = mangaReadSources[media.selected!!.sourceIndex] is OfflineMangaParser
|
||||
|
||||
if (isDownloadedSource) {
|
||||
binding.sourceNotFound.text = if (sourceFound) {
|
||||
currActivity()!!.getString(R.string.source_not_found)
|
||||
} else {
|
||||
currActivity()!!.getString(R.string.download_not_found)
|
||||
}
|
||||
} else {
|
||||
binding.sourceNotFound.text = currActivity()!!.getString(R.string.source_not_found)
|
||||
}
|
||||
|
||||
binding.sourceNotFound.isGone = sourceFound
|
||||
binding.faqbutton.isGone = sourceFound
|
||||
|
||||
|
||||
if (!sourceFound && PrefManager.getVal(PrefName.SearchSources)) {
|
||||
if (binding.animeSource.adapter.count > media.selected!!.sourceIndex + 1) {
|
||||
if (binding.mediaSource.adapter.count > media.selected!!.sourceIndex + 1) {
|
||||
val nextIndex = media.selected!!.sourceIndex + 1
|
||||
binding.animeSource.setText(
|
||||
binding.animeSource.adapter
|
||||
binding.mediaSource.setText(
|
||||
binding.mediaSource.adapter
|
||||
.getItem(nextIndex).toString(), false
|
||||
)
|
||||
fragment.onSourceChange(nextIndex).apply {
|
||||
binding.animeSourceTitle.text = showUserText
|
||||
binding.mediaSourceTitle.text = showUserText
|
||||
showUserTextListener =
|
||||
{ MainScope().launch { binding.animeSourceTitle.text = it } }
|
||||
{ MainScope().launch { binding.mediaSourceTitle.text = it } }
|
||||
setLanguageList(0, nextIndex)
|
||||
}
|
||||
subscribeButton(false)
|
||||
// invalidate if it's the last source
|
||||
// Invalidate if it's the last source
|
||||
val invalidate = nextIndex == mangaReadSources.names.size - 1
|
||||
fragment.loadChapters(nextIndex, invalidate)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
binding.animeSourceContinue.visibility = View.GONE
|
||||
binding.animeSourceNotFound.visibility = View.GONE
|
||||
binding.sourceContinue.visibility = View.GONE
|
||||
binding.sourceNotFound.visibility = View.GONE
|
||||
binding.faqbutton.visibility = View.GONE
|
||||
clearChips()
|
||||
binding.animeSourceProgressBar.visibility = View.VISIBLE
|
||||
binding.sourceProgressBar.visibility = View.VISIBLE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -539,9 +540,9 @@ class MangaReadAdapter(
|
||||
ext.sourceLanguage = lang
|
||||
}
|
||||
try {
|
||||
binding?.animeSourceLanguage?.setText(parser.extension.sources[lang].lang)
|
||||
binding?.mediaSourceLanguage?.setText(parser.extension.sources[lang].lang)
|
||||
} catch (e: IndexOutOfBoundsException) {
|
||||
binding?.animeSourceLanguage?.setText(
|
||||
binding?.mediaSourceLanguage?.setText(
|
||||
parser.extension.sources.firstOrNull()?.lang ?: "Unknown"
|
||||
)
|
||||
}
|
||||
@@ -551,9 +552,9 @@ class MangaReadAdapter(
|
||||
parser.extension.sources.map { LanguageMapper.getLanguageName(it.lang) }
|
||||
)
|
||||
val items = adapter.count
|
||||
binding?.animeSourceLanguageContainer?.isVisible = items > 1
|
||||
binding?.mediaSourceLanguageContainer?.isVisible = items > 1
|
||||
|
||||
binding?.animeSourceLanguage?.setAdapter(adapter)
|
||||
binding?.mediaSourceLanguage?.setAdapter(adapter)
|
||||
|
||||
}
|
||||
}
|
||||
@@ -561,7 +562,7 @@ class MangaReadAdapter(
|
||||
|
||||
override fun getItemCount(): Int = 1
|
||||
|
||||
inner class ViewHolder(val binding: ItemAnimeWatchBinding) :
|
||||
inner class ViewHolder(val binding: ItemMediaSourceBinding) :
|
||||
RecyclerView.ViewHolder(binding.root)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package ani.dantotsu.media.manga
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.AlertDialog
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -31,7 +30,7 @@ import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.FragmentAnimeWatchBinding
|
||||
import ani.dantotsu.databinding.FragmentMediaSourceBinding
|
||||
import ani.dantotsu.download.DownloadedType
|
||||
import ani.dantotsu.download.DownloadsManager
|
||||
import ani.dantotsu.download.DownloadsManager.Companion.compareName
|
||||
@@ -60,6 +59,7 @@ import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.StoragePermissions.Companion.accessAlertDialog
|
||||
import ani.dantotsu.util.StoragePermissions.Companion.hasDirAccess
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.appbar.AppBarLayout
|
||||
import eu.kanade.tachiyomi.extension.manga.model.MangaExtension
|
||||
import eu.kanade.tachiyomi.source.ConfigurableSource
|
||||
@@ -74,7 +74,7 @@ import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
private var _binding: FragmentAnimeWatchBinding? = null
|
||||
private var _binding: FragmentMediaSourceBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
private val model: MediaDetailsViewModel by activityViewModels()
|
||||
|
||||
@@ -101,7 +101,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View? {
|
||||
_binding = FragmentAnimeWatchBinding.inflate(inflater, container, false)
|
||||
_binding = FragmentMediaSourceBinding.inflate(inflater, container, false)
|
||||
return _binding?.root
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
ContextCompat.RECEIVER_EXPORTED
|
||||
)
|
||||
|
||||
binding.animeSourceRecycler.updatePadding(bottom = binding.animeSourceRecycler.paddingBottom + navBarHeight)
|
||||
binding.mediaSourceRecycler.updatePadding(bottom = binding.mediaSourceRecycler.paddingBottom + navBarHeight)
|
||||
screenWidth = resources.displayMetrics.widthPixels.dp
|
||||
|
||||
var maxGridSize = (screenWidth / 100f).roundToInt()
|
||||
@@ -144,13 +144,13 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
}
|
||||
}
|
||||
|
||||
binding.animeSourceRecycler.layoutManager = gridLayoutManager
|
||||
binding.mediaSourceRecycler.layoutManager = gridLayoutManager
|
||||
|
||||
binding.ScrollTop.setOnClickListener {
|
||||
binding.animeSourceRecycler.scrollToPosition(10)
|
||||
binding.animeSourceRecycler.smoothScrollToPosition(0)
|
||||
binding.mediaSourceRecycler.scrollToPosition(10)
|
||||
binding.mediaSourceRecycler.smoothScrollToPosition(0)
|
||||
}
|
||||
binding.animeSourceRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
binding.mediaSourceRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(recyclerView, dx, dy)
|
||||
|
||||
@@ -164,7 +164,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
}
|
||||
})
|
||||
model.scrolledToTop.observe(viewLifecycleOwner) {
|
||||
if (it) binding.animeSourceRecycler.scrollToPosition(0)
|
||||
if (it) binding.mediaSourceRecycler.scrollToPosition(0)
|
||||
}
|
||||
|
||||
continueEp = model.continueMedia ?: false
|
||||
@@ -199,7 +199,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
}
|
||||
}
|
||||
|
||||
binding.animeSourceRecycler.adapter =
|
||||
binding.mediaSourceRecycler.adapter =
|
||||
ConcatAdapter(headerAdapter, chapterAdapter)
|
||||
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
@@ -214,8 +214,8 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
reload()
|
||||
}
|
||||
} else {
|
||||
binding.animeNotSupported.visibility = View.VISIBLE
|
||||
binding.animeNotSupported.text =
|
||||
binding.mediaNotSupported.visibility = View.VISIBLE
|
||||
binding.mediaNotSupported.text =
|
||||
getString(R.string.not_supported, media.format ?: "")
|
||||
}
|
||||
}
|
||||
@@ -231,10 +231,10 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
}
|
||||
|
||||
fun multiDownload(n: Int) {
|
||||
//get last viewed chapter
|
||||
// Get last viewed chapter
|
||||
val selected = media.userProgress
|
||||
val chapters = media.manga?.chapters?.values?.toList()
|
||||
//filter by selected language
|
||||
// Filter by selected language
|
||||
val progressChapterIndex = (chapters?.indexOfFirst {
|
||||
MediaNameAdapter.findChapterNumber(it.number)?.toInt() == selected
|
||||
} ?: 0) + 1
|
||||
@@ -244,7 +244,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
// Calculate the end index
|
||||
val endIndex = minOf(progressChapterIndex + n, chapters.size)
|
||||
|
||||
//make sure there are enough chapters
|
||||
// Make sure there are enough chapters
|
||||
val chaptersToDownload = chapters.subList(progressChapterIndex, endIndex)
|
||||
|
||||
|
||||
@@ -386,32 +386,30 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
if (allSettings.size > 1) {
|
||||
val names =
|
||||
allSettings.map { LanguageMapper.getLanguageName(it.lang) }.toTypedArray()
|
||||
val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
.setTitle("Select a Source")
|
||||
.setSingleChoiceItems(names, -1) { dialog, which ->
|
||||
requireContext().customAlertDialog().apply {
|
||||
setTitle("Select a Source")
|
||||
singleChoiceItems(names) { which ->
|
||||
selectedSetting = allSettings[which]
|
||||
itemSelected = true
|
||||
dialog.dismiss()
|
||||
|
||||
// Move the fragment transaction here
|
||||
val fragment =
|
||||
MangaSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
changeUIVisibility(true)
|
||||
loadChapters(media.selected!!.sourceIndex, true)
|
||||
}
|
||||
val fragment = MangaSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
changeUIVisibility(true)
|
||||
loadChapters(media.selected!!.sourceIndex, true)
|
||||
}
|
||||
parentFragmentManager.beginTransaction()
|
||||
.setCustomAnimations(R.anim.slide_up, R.anim.slide_down)
|
||||
.replace(R.id.fragmentExtensionsContainer, fragment)
|
||||
.addToBackStack(null)
|
||||
.commit()
|
||||
}
|
||||
.setOnDismissListener {
|
||||
onDismiss{
|
||||
if (!itemSelected) {
|
||||
changeUIVisibility(true)
|
||||
}
|
||||
}
|
||||
.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
|
||||
}
|
||||
} else {
|
||||
// If there's only one setting, proceed with the fragment transaction
|
||||
val fragment = MangaSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
@@ -584,7 +582,7 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
private fun reload() {
|
||||
val selected = model.loadSelected(media)
|
||||
|
||||
//Find latest chapter for subscription
|
||||
// Find latest chapter for subscription
|
||||
selected.latest =
|
||||
media.manga?.chapters?.values?.maxOfOrNull { it.number.toFloatOrNull() ?: 0f } ?: 0f
|
||||
selected.latest =
|
||||
@@ -618,14 +616,14 @@ open class MangaReadFragment : Fragment(), ScanlatorSelectionListener {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
binding.mediaInfoProgressBar.visibility = progress
|
||||
binding.animeSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
binding.mediaSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
|
||||
requireActivity().setNavigationTheme()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
state = binding.animeSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
state = binding.mediaSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -83,6 +83,7 @@ import ani.dantotsu.showSystemBarsRetractView
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.tryWith
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.alexvasilkov.gestures.views.GestureFrameLayout
|
||||
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
|
||||
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
|
||||
@@ -1013,28 +1014,27 @@ class MangaReaderActivity : AppCompatActivity() {
|
||||
PrefManager.setCustomVal("${media.id}_progressDialog", !isChecked)
|
||||
showProgressDialog = !isChecked
|
||||
}
|
||||
AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.title_update_progress))
|
||||
.setView(dialogView)
|
||||
.setCancelable(false)
|
||||
.setPositiveButton(getString(R.string.yes)) { dialog, _ ->
|
||||
customAlertDialog().apply {
|
||||
setTitle(R.string.title_update_progress)
|
||||
setCustomView(dialogView)
|
||||
setCancelable(false)
|
||||
setPosButton(R.string.yes) {
|
||||
PrefManager.setCustomVal("${media.id}_save_progress", true)
|
||||
updateProgress(
|
||||
media,
|
||||
MediaNameAdapter.findChapterNumber(media.manga!!.selectedChapter!!)
|
||||
.toString()
|
||||
)
|
||||
dialog.dismiss()
|
||||
runnable.run()
|
||||
}
|
||||
.setNegativeButton(getString(R.string.no)) { dialog, _ ->
|
||||
setNegButton(R.string.no) {
|
||||
PrefManager.setCustomVal("${media.id}_save_progress", false)
|
||||
dialog.dismiss()
|
||||
runnable.run()
|
||||
}
|
||||
.setOnCancelListener { hideSystemBars() }
|
||||
.create()
|
||||
.show()
|
||||
setOnCancelListener { hideSystemBars() }
|
||||
show()
|
||||
|
||||
}
|
||||
} else {
|
||||
if (!incognito && PrefManager.getCustomVal(
|
||||
"${media.id}_save_progress",
|
||||
|
||||
@@ -50,16 +50,16 @@ class NovelReadAdapter(
|
||||
val source =
|
||||
media.selected!!.sourceIndex.let { if (it >= novelReadSources.names.size) 0 else it }
|
||||
if (novelReadSources.names.isNotEmpty() && source in 0 until novelReadSources.names.size) {
|
||||
binding.animeSource.setText(novelReadSources.names[source], false)
|
||||
binding.mediaSource.setText(novelReadSources.names[source], false)
|
||||
}
|
||||
binding.animeSource.setAdapter(
|
||||
binding.mediaSource.setAdapter(
|
||||
ArrayAdapter(
|
||||
fragment.requireContext(),
|
||||
R.layout.item_dropdown,
|
||||
novelReadSources.names
|
||||
)
|
||||
)
|
||||
binding.animeSource.setOnItemClickListener { _, _, i, _ ->
|
||||
binding.mediaSource.setOnItemClickListener { _, _, i, _ ->
|
||||
fragment.onSourceChange(i)
|
||||
search()
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import androidx.recyclerview.widget.ConcatAdapter
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.currContext
|
||||
import ani.dantotsu.databinding.FragmentAnimeWatchBinding
|
||||
import ani.dantotsu.databinding.FragmentMediaSourceBinding
|
||||
import ani.dantotsu.download.DownloadedType
|
||||
import ani.dantotsu.download.DownloadsManager
|
||||
import ani.dantotsu.download.novel.NovelDownloaderService
|
||||
@@ -47,7 +47,7 @@ class NovelReadFragment : Fragment(),
|
||||
DownloadTriggerCallback,
|
||||
DownloadedCheckCallback {
|
||||
|
||||
private var _binding: FragmentAnimeWatchBinding? = null
|
||||
private var _binding: FragmentMediaSourceBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
private val model: MediaDetailsViewModel by activityViewModels()
|
||||
|
||||
@@ -214,11 +214,11 @@ class NovelReadFragment : Fragment(),
|
||||
ContextCompat.RECEIVER_EXPORTED
|
||||
)
|
||||
|
||||
binding.animeSourceRecycler.updatePadding(bottom = binding.animeSourceRecycler.paddingBottom + navBarHeight)
|
||||
binding.mediaSourceRecycler.updatePadding(bottom = binding.mediaSourceRecycler.paddingBottom + navBarHeight)
|
||||
|
||||
binding.animeSourceRecycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
binding.mediaSourceRecycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
model.scrolledToTop.observe(viewLifecycleOwner) {
|
||||
if (it) binding.animeSourceRecycler.scrollToPosition(0)
|
||||
if (it) binding.mediaSourceRecycler.scrollToPosition(0)
|
||||
}
|
||||
|
||||
continueEp = model.continueMedia ?: false
|
||||
@@ -237,7 +237,7 @@ class NovelReadFragment : Fragment(),
|
||||
this,
|
||||
this
|
||||
) // probably a better way to do this but it works
|
||||
binding.animeSourceRecycler.adapter =
|
||||
binding.mediaSourceRecycler.adapter =
|
||||
ConcatAdapter(headerAdapter, novelResponseAdapter)
|
||||
loaded = true
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
@@ -290,7 +290,7 @@ class NovelReadFragment : Fragment(),
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View? {
|
||||
_binding = FragmentAnimeWatchBinding.inflate(inflater, container, false)
|
||||
_binding = FragmentMediaSourceBinding.inflate(inflater, container, false)
|
||||
return _binding?.root
|
||||
}
|
||||
|
||||
@@ -304,12 +304,12 @@ class NovelReadFragment : Fragment(),
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
binding.mediaInfoProgressBar.visibility = progress
|
||||
binding.animeSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
binding.mediaSourceRecycler.layoutManager?.onRestoreInstanceState(state)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
state = binding.animeSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
state = binding.mediaSourceRecycler.layoutManager?.onSaveInstanceState()
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -13,6 +13,7 @@ import ani.dantotsu.parsers.ShowResponse
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.bumptech.glide.Glide
|
||||
import com.bumptech.glide.load.model.GlideUrl
|
||||
|
||||
@@ -38,7 +39,7 @@ class NovelResponseAdapter(
|
||||
val binding = holder.binding
|
||||
val novel = list[position]
|
||||
setAnimation(fragment.requireContext(), holder.binding.root)
|
||||
binding.itemEpisodeImage.loadImage(novel.coverUrl, 400, 0)
|
||||
binding.itemMediaImage.loadImage(novel.coverUrl, 400, 0)
|
||||
|
||||
val color =fragment.requireContext().getThemeColor(com.google.android.material.R.attr.colorOnBackground)
|
||||
binding.itemEpisodeTitle.text = novel.name
|
||||
@@ -93,27 +94,22 @@ class NovelResponseAdapter(
|
||||
}
|
||||
|
||||
binding.root.setOnLongClickListener {
|
||||
val builder = androidx.appcompat.app.AlertDialog.Builder(
|
||||
fragment.requireContext(),
|
||||
R.style.MyPopup
|
||||
)
|
||||
builder.setTitle("Delete ${novel.name}?")
|
||||
builder.setMessage("Are you sure you want to delete ${novel.name}?")
|
||||
builder.setPositiveButton("Yes") { _, _ ->
|
||||
downloadedCheckCallback.deleteDownload(novel)
|
||||
deleteDownload(novel.link)
|
||||
snackString("Deleted ${novel.name}")
|
||||
if (binding.itemEpisodeFiller.text.toString()
|
||||
.contains("Download", ignoreCase = true)
|
||||
) {
|
||||
binding.itemEpisodeFiller.text = ""
|
||||
it.context.customAlertDialog().apply {
|
||||
setTitle("Delete ${novel.name}?")
|
||||
setMessage("Are you sure you want to delete ${novel.name}?")
|
||||
setPosButton(R.string.yes) {
|
||||
downloadedCheckCallback.deleteDownload(novel)
|
||||
deleteDownload(novel.link)
|
||||
snackString("Deleted ${novel.name}")
|
||||
if (binding.itemEpisodeFiller.text.toString()
|
||||
.contains("Download", ignoreCase = true)
|
||||
) {
|
||||
binding.itemEpisodeFiller.text = ""
|
||||
}
|
||||
}
|
||||
setNegButton(R.string.no)
|
||||
show()
|
||||
}
|
||||
builder.setNegativeButton("No") { _, _ ->
|
||||
// Do nothing
|
||||
}
|
||||
val dialog = builder.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ class ListActivity : AppCompatActivity() {
|
||||
|
||||
window.statusBarColor = primaryColor
|
||||
window.navigationBarColor = primaryColor
|
||||
binding.listed.visibility = View.GONE
|
||||
binding.listTabLayout.setBackgroundColor(primaryColor)
|
||||
binding.listAppBar.setBackgroundColor(primaryColor)
|
||||
binding.listTitle.setTextColor(primaryTextColor)
|
||||
|
||||
@@ -146,8 +146,13 @@ class SubscriptionHelper {
|
||||
val isAdult: Boolean,
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val image: String?
|
||||
) : java.io.Serializable
|
||||
val image: String?,
|
||||
val banner: String? = null
|
||||
) : java.io.Serializable {
|
||||
companion object {
|
||||
private const val serialVersionUID = 1L
|
||||
}
|
||||
}
|
||||
|
||||
private const val SUBSCRIPTIONS = "subscriptions"
|
||||
|
||||
@@ -188,7 +193,8 @@ class SubscriptionHelper {
|
||||
media.isAdult,
|
||||
media.id,
|
||||
media.userPreferredName,
|
||||
media.cover
|
||||
media.cover,
|
||||
media.banner
|
||||
)
|
||||
data[media.id] = new
|
||||
}
|
||||
|
||||
@@ -122,7 +122,9 @@ class SubscriptionNotificationTask : Task {
|
||||
SubscriptionStore(
|
||||
media.name,
|
||||
text.first,
|
||||
media.id
|
||||
media.id,
|
||||
image = media.image,
|
||||
banner = media.banner
|
||||
)
|
||||
)
|
||||
PrefManager.setVal(PrefName.UnreadCommentNotifications,
|
||||
@@ -238,6 +240,10 @@ class SubscriptionNotificationTask : Task {
|
||||
if (newStore.size >= 100) {
|
||||
newStore.remove(newStore.minByOrNull { it.time })
|
||||
}
|
||||
if (newStore.any { it.title == notification.title && it.content == notification.content}) {
|
||||
return
|
||||
}
|
||||
|
||||
newStore.add(notification)
|
||||
PrefManager.setVal(PrefName.SubscriptionNotificationStore, newStore)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ data class SubscriptionStore(
|
||||
val mediaId: Int,
|
||||
val type: String = "SUBSCRIPTION",
|
||||
val time: Long = System.currentTimeMillis(),
|
||||
val image: String? = "",
|
||||
val banner: String? = "",
|
||||
) : java.io.Serializable {
|
||||
companion object {
|
||||
private const val serialVersionUID = 1L
|
||||
|
||||
46
app/src/main/java/ani/dantotsu/others/Anify.kt
Normal file
46
app/src/main/java/ani/dantotsu/others/Anify.kt
Normal file
@@ -0,0 +1,46 @@
|
||||
package ani.dantotsu.others
|
||||
|
||||
import ani.dantotsu.FileUrl
|
||||
import ani.dantotsu.Mapper
|
||||
import ani.dantotsu.client
|
||||
import ani.dantotsu.media.anime.Episode
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
|
||||
object Anify {
|
||||
suspend fun fetchAndParseMetadata(id :Int): Map<String, Episode> {
|
||||
val response = client.get("https://api.anify.tv/content-metadata/$id")
|
||||
.parsed<JsonArray>().map {
|
||||
Mapper.json.decodeFromJsonElement<AnifyElement>(it)
|
||||
}
|
||||
return response.firstOrNull()?.data?.associate {
|
||||
it.number.toString() to Episode(
|
||||
number = it.number.toString(),
|
||||
title = it.title,
|
||||
desc = it.description,
|
||||
thumb = FileUrl[it.img],
|
||||
)
|
||||
} ?: emptyMap()
|
||||
}
|
||||
@Serializable
|
||||
data class AnifyElement (
|
||||
@SerialName("providerId")
|
||||
val providerID: String? = null,
|
||||
val data: List<Datum>? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Datum (
|
||||
val id: String? = null,
|
||||
val description: String? = null,
|
||||
val hasDub: Boolean? = null,
|
||||
val img: String? = null,
|
||||
val isFiller: Boolean? = null,
|
||||
val number: Long? = null,
|
||||
val title: String? = null,
|
||||
val updatedAt: Long? = null,
|
||||
val rating: Double? = null
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.core.view.updateLayoutParams
|
||||
@@ -24,7 +25,10 @@ class CrashActivity : AppCompatActivity() {
|
||||
ThemeManager(this).applyTheme()
|
||||
initActivity(this)
|
||||
binding = ActivityCrashBinding.inflate(layoutInflater)
|
||||
|
||||
window.setFlags(
|
||||
WindowManager.LayoutParams.FLAG_SECURE,
|
||||
WindowManager.LayoutParams.FLAG_SECURE
|
||||
)
|
||||
setContentView(binding.root)
|
||||
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin = statusBarHeight
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package ani.dantotsu.others.calc
|
||||
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import androidx.core.content.ContextCompat
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.util.Logger
|
||||
|
||||
object BiometricPromptUtils {
|
||||
private const val TAG = "BiometricPromptUtils"
|
||||
|
||||
/**
|
||||
* Create a BiometricPrompt instance
|
||||
* @param activity: AppCompatActivity
|
||||
* @param processSuccess: success callback
|
||||
*/
|
||||
fun createBiometricPrompt(
|
||||
activity: AppCompatActivity,
|
||||
processSuccess: (BiometricPrompt.AuthenticationResult) -> Unit
|
||||
): BiometricPrompt {
|
||||
val executor = ContextCompat.getMainExecutor(activity)
|
||||
|
||||
val callback = object : BiometricPrompt.AuthenticationCallback() {
|
||||
|
||||
override fun onAuthenticationError(errCode: Int, errString: CharSequence) {
|
||||
super.onAuthenticationError(errCode, errString)
|
||||
Logger.log("$TAG errCode is $errCode and errString is: $errString")
|
||||
}
|
||||
|
||||
override fun onAuthenticationFailed() {
|
||||
super.onAuthenticationFailed()
|
||||
Logger.log("$TAG User biometric rejected.")
|
||||
}
|
||||
|
||||
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||
super.onAuthenticationSucceeded(result)
|
||||
Log.d(TAG, "Authentication was successful")
|
||||
processSuccess(result)
|
||||
}
|
||||
}
|
||||
return BiometricPrompt(activity, executor, callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BiometricPrompt.PromptInfo instance
|
||||
* @param activity: AppCompatActivity
|
||||
* @return BiometricPrompt.PromptInfo: instance
|
||||
*/
|
||||
fun createPromptInfo(activity: AppCompatActivity): BiometricPrompt.PromptInfo =
|
||||
BiometricPrompt.PromptInfo.Builder().apply {
|
||||
setTitle(activity.getString(R.string.bio_prompt_info_title))
|
||||
setDescription(activity.getString(R.string.bio_prompt_info_desc))
|
||||
setConfirmationRequired(false)
|
||||
setNegativeButtonText(activity.getString(R.string.cancel))
|
||||
}.build()
|
||||
}
|
||||
174
app/src/main/java/ani/dantotsu/others/calc/CalcActivity.kt
Normal file
174
app/src/main/java/ani/dantotsu/others/calc/CalcActivity.kt
Normal file
@@ -0,0 +1,174 @@
|
||||
package ani.dantotsu.others.calc
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewGroup
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.doOnAttach
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import ani.dantotsu.MainActivity
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.ActivityCalcBinding
|
||||
import ani.dantotsu.getThemeColor
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.util.NumberConverter.Companion.toBinary
|
||||
import ani.dantotsu.util.NumberConverter.Companion.toHex
|
||||
|
||||
class CalcActivity : AppCompatActivity() {
|
||||
private lateinit var binding: ActivityCalcBinding
|
||||
private lateinit var code: String
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val runnable = Runnable {
|
||||
success()
|
||||
}
|
||||
private val stack = CalcStack()
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
ThemeManager(this).applyTheme()
|
||||
binding = ActivityCalcBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
binding.root.doOnAttach {
|
||||
initActivity(this)
|
||||
binding.displayContainer.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin += statusBarHeight
|
||||
}
|
||||
binding.buttonContainer.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin += navBarHeight
|
||||
}
|
||||
}
|
||||
code = intent.getStringExtra("code") ?: "0"
|
||||
|
||||
binding.apply {
|
||||
button0.setOnClickListener { stack.add('0'); updateDisplay() }
|
||||
button1.setOnClickListener { stack.add('1'); updateDisplay() }
|
||||
button2.setOnClickListener { stack.add('2'); updateDisplay() }
|
||||
button3.setOnClickListener { stack.add('3'); updateDisplay() }
|
||||
button4.setOnClickListener { stack.add('4'); updateDisplay() }
|
||||
button5.setOnClickListener { stack.add('5'); updateDisplay() }
|
||||
button6.setOnClickListener { stack.add('6'); updateDisplay() }
|
||||
button7.setOnClickListener { stack.add('7'); updateDisplay() }
|
||||
button8.setOnClickListener { stack.add('8'); updateDisplay() }
|
||||
button9.setOnClickListener { stack.add('9'); updateDisplay() }
|
||||
buttonDot.setOnClickListener { stack.add('.'); updateDisplay() }
|
||||
buttonAdd.setOnClickListener { stack.add('+'); updateDisplay() }
|
||||
buttonSubtract.setOnClickListener { stack.add('-'); updateDisplay() }
|
||||
buttonMultiply.setOnClickListener { stack.add('*'); updateDisplay() }
|
||||
buttonDivide.setOnClickListener { stack.add('/'); updateDisplay() }
|
||||
buttonEquals.setOnClickListener {
|
||||
try {
|
||||
val ans = stack.evaluate()
|
||||
updateDisplay()
|
||||
binding.displayBinary.text = ans.toBinary()
|
||||
binding.displayHex.text = ans.toHex()
|
||||
} catch (e: Exception) {
|
||||
display.text = getString(R.string.error)
|
||||
}
|
||||
}
|
||||
buttonClear.setOnClickListener {
|
||||
stack.clear()
|
||||
binding.displayBinary.text = ""
|
||||
binding.displayHex.text = ""
|
||||
binding.display.text = "0"
|
||||
}
|
||||
if (PrefManager.getVal(PrefName.OverridePassword, false)) {
|
||||
buttonClear.setOnTouchListener { v, event ->
|
||||
when (event.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
handler.postDelayed(runnable, 10000)
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_UP -> {
|
||||
v.performClick()
|
||||
handler.removeCallbacks(runnable)
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_CANCEL -> {
|
||||
handler.removeCallbacks(runnable)
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
}
|
||||
buttonBackspace.setOnClickListener {
|
||||
stack.remove()
|
||||
updateDisplay()
|
||||
}
|
||||
display.text = "0"
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (hasPermission) {
|
||||
success()
|
||||
}
|
||||
if (PrefManager.getVal(PrefName.BiometricToken, "").isNotEmpty()) {
|
||||
val bioMetricPrompt = BiometricPromptUtils.createBiometricPrompt(this) {
|
||||
success()
|
||||
}
|
||||
val promptInfo = BiometricPromptUtils.createPromptInfo(this)
|
||||
bioMetricPrompt.authenticate(promptInfo)
|
||||
}
|
||||
}
|
||||
|
||||
private fun success() {
|
||||
hasPermission = true
|
||||
ContextCompat.startActivity(
|
||||
this,
|
||||
Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
private fun updateDisplay() {
|
||||
if (stack.getExpression().isEmpty()) {
|
||||
binding.display.text = "0"
|
||||
return
|
||||
}
|
||||
val expression = stack.getExpression().replace("*", "×").replace("/", "÷")
|
||||
val spannable = SpannableString(expression)
|
||||
|
||||
val operators = arrayOf('+', '-', '×', '÷')
|
||||
|
||||
expression.forEachIndexed { index, char ->
|
||||
if (char in operators) {
|
||||
val color = getThemeColor(com.google.android.material.R.attr.colorSecondary)
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(color),
|
||||
index,
|
||||
index + 1,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
}
|
||||
}
|
||||
binding.display.text = spannable
|
||||
val text = binding.display.text.toString()
|
||||
if (text == code) {
|
||||
success()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
var hasPermission = false
|
||||
}
|
||||
}
|
||||
103
app/src/main/java/ani/dantotsu/others/calc/CalcStack.kt
Normal file
103
app/src/main/java/ani/dantotsu/others/calc/CalcStack.kt
Normal file
@@ -0,0 +1,103 @@
|
||||
package ani.dantotsu.others.calc
|
||||
|
||||
import java.util.Stack
|
||||
|
||||
class CalcStack {
|
||||
private var expression: String = ""
|
||||
private val maxExpressionLength = 256
|
||||
|
||||
fun evaluate(): Double {
|
||||
val ops = Stack<Char>()
|
||||
val values = Stack<Double>()
|
||||
|
||||
var i = 0
|
||||
while (i < expression.length) {
|
||||
when {
|
||||
expression[i] == ' ' -> i++
|
||||
expression[i].isDigit() || expression[i] == '.' -> {
|
||||
var value = 0.0
|
||||
var isDecimal = false
|
||||
var decimalFactor = 0.1
|
||||
while (i < expression.length && (expression[i].isDigit() || expression[i] == '.' && !isDecimal)) {
|
||||
if (expression[i] == '.') {
|
||||
isDecimal = true
|
||||
} else if (!isDecimal) {
|
||||
value = value * 10 + (expression[i] - '0')
|
||||
} else {
|
||||
value += (expression[i] - '0') * decimalFactor
|
||||
decimalFactor *= 0.1
|
||||
}
|
||||
i++
|
||||
}
|
||||
values.push(value)
|
||||
i-- // to compensate the additional i++ in the loop
|
||||
}
|
||||
|
||||
else -> {
|
||||
while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(expression[i])) {
|
||||
val val2 = values.pop()
|
||||
val val1 = values.pop()
|
||||
val op = ops.pop()
|
||||
values.push(applyOp(val1, val2, op))
|
||||
}
|
||||
ops.push(expression[i])
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
while (!ops.isEmpty()) {
|
||||
val val2 = values.pop()
|
||||
val val1 = values.pop()
|
||||
val op = ops.pop()
|
||||
values.push(applyOp(val1, val2, op))
|
||||
}
|
||||
|
||||
|
||||
val ans = values.pop()
|
||||
expression = ans.toString()
|
||||
return ans
|
||||
}
|
||||
|
||||
fun add(c: Char) {
|
||||
if (expression.length >= maxExpressionLength) return
|
||||
expression += c
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
expression = ""
|
||||
}
|
||||
|
||||
fun remove() {
|
||||
if (expression.isNotEmpty()) {
|
||||
expression = expression.substring(0, expression.length - 1)
|
||||
}
|
||||
}
|
||||
|
||||
fun getExpression(): String {
|
||||
return expression
|
||||
}
|
||||
|
||||
|
||||
private fun precedence(op: Char): Int {
|
||||
return when (op) {
|
||||
'+', '-' -> 1
|
||||
'*', '/' -> 2
|
||||
else -> -1
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyOp(a: Double, b: Double, op: Char): Double {
|
||||
return when (op) {
|
||||
'+' -> a + b
|
||||
'-' -> a - b
|
||||
'*' -> a * b
|
||||
'/' -> {
|
||||
if (b == 0.0) throw UnsupportedOperationException("Cannot divide by zero.")
|
||||
a / b
|
||||
}
|
||||
|
||||
else -> 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ object AnimeSources : WatchSources() {
|
||||
}
|
||||
|
||||
fun performReorderAnimeSources() {
|
||||
//remove the downloaded source from the list to avoid duplicates
|
||||
// Remove the downloaded source from the list to avoid duplicates
|
||||
list = list.filter { it.name != "Downloaded" }
|
||||
list = sortPinnedAnimeSources(list, pinnedAnimeSources) + Lazier(
|
||||
{ OfflineAnimeParser() },
|
||||
|
||||
@@ -11,6 +11,7 @@ import ani.dantotsu.util.Logger
|
||||
import eu.kanade.tachiyomi.animesource.model.SAnime
|
||||
import eu.kanade.tachiyomi.source.model.SManga
|
||||
import me.xdrop.fuzzywuzzy.FuzzySearch
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.Serializable
|
||||
import java.net.URLDecoder
|
||||
@@ -147,10 +148,11 @@ abstract class BaseParser {
|
||||
* @return Triple<Int, Int?, String> : First Int is the status code, Second Int is the response time in milliseconds, Third String is the response message.
|
||||
*/
|
||||
fun ping(): Triple<Int, Int?, String> {
|
||||
val client = okHttpClient
|
||||
val client = OkHttpClient()
|
||||
var statusCode = 0
|
||||
var responseTime: Int? = null
|
||||
var responseMessage = ""
|
||||
println("Pinging $name at $hostUrl")
|
||||
try {
|
||||
val request = Request.Builder()
|
||||
.url(hostUrl)
|
||||
@@ -158,7 +160,7 @@ abstract class BaseParser {
|
||||
responseTime = measureTimeMillis {
|
||||
client.newCall(request).execute().use { response ->
|
||||
statusCode = response.code
|
||||
responseMessage = response.message
|
||||
responseMessage = response.message.ifEmpty { "None" }
|
||||
}
|
||||
}.toInt()
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package ani.dantotsu.parsers
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.view.View
|
||||
import androidx.core.view.isVisible
|
||||
@@ -17,16 +18,16 @@ class ExtensionTestItem(
|
||||
private var extensionType: String,
|
||||
private var testType: String,
|
||||
private var extension: BaseParser,
|
||||
private var searchString: String = "Chainsaw Man"
|
||||
private var searchString: String
|
||||
) : BindableItem<ItemExtensionTestBinding>() {
|
||||
private lateinit var binding: ItemExtensionTestBinding
|
||||
private lateinit var context: Context
|
||||
private var job: Job? = null
|
||||
private var isRunning = false
|
||||
private var pingResult: Triple<Int, Int?, String>? = null
|
||||
private var searchResultSize: Int? = null
|
||||
private var episodeResultSize: Int? = null
|
||||
private var serverResultSize: Int? = null
|
||||
private var searchResultData: TestResult = TestResult()
|
||||
private var episodeResultData: TestResult = TestResult()
|
||||
private var serverResultData: TestResult = TestResult()
|
||||
|
||||
override fun bind(viewBinding: ItemExtensionTestBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
@@ -36,6 +37,7 @@ class ExtensionTestItem(
|
||||
binding.extensionLoading.isVisible = isRunning
|
||||
hideAllResults()
|
||||
|
||||
println(searchString)
|
||||
pingResult()
|
||||
searchResult()
|
||||
episodeResult()
|
||||
@@ -65,9 +67,9 @@ class ExtensionTestItem(
|
||||
|
||||
fun startTest() {
|
||||
pingResult = null
|
||||
searchResultSize = null
|
||||
episodeResultSize = null
|
||||
serverResultSize = null
|
||||
searchResultData = TestResult()
|
||||
episodeResultData = TestResult()
|
||||
serverResultData = TestResult()
|
||||
isRunning = true
|
||||
hideAllResults()
|
||||
job?.cancel()
|
||||
@@ -93,34 +95,40 @@ class ExtensionTestItem(
|
||||
}
|
||||
|
||||
private suspend fun runAnimeTest(extension: AnimeParser) {
|
||||
pingResult = extension.ping()
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
if (testType == "ping") {
|
||||
pingResult = extension.ping()
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
done()
|
||||
return
|
||||
}
|
||||
val searchStart = System.currentTimeMillis()
|
||||
val searchResult = extension.search(searchString)
|
||||
searchResultSize = searchResult.size
|
||||
searchResultData.time = (System.currentTimeMillis() - searchStart).toInt()
|
||||
searchResultData.size = searchResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
searchResult()
|
||||
}
|
||||
if (searchResultSize == 0 || testType == "basic") {
|
||||
if (searchResultData.size == 0 || testType == "basic") {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val episodeResultTime = System.currentTimeMillis()
|
||||
val episodeResult = extension.loadEpisodes("", null, searchResult.first().sAnime!!)
|
||||
episodeResultSize = episodeResult.size
|
||||
episodeResultData.time = (System.currentTimeMillis() - episodeResultTime).toInt()
|
||||
episodeResultData.size = episodeResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
episodeResult()
|
||||
}
|
||||
if (episodeResultSize == 0) {
|
||||
if (episodeResultData.size == 0) {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val serverResultTime = System.currentTimeMillis()
|
||||
val serverResult = extension.loadVideoServers("", null, episodeResult.first().sEpisode!!)
|
||||
serverResultSize = serverResult.size
|
||||
serverResultData.time = (System.currentTimeMillis() - serverResultTime).toInt()
|
||||
serverResultData.size = serverResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
serverResult()
|
||||
}
|
||||
@@ -129,85 +137,89 @@ class ExtensionTestItem(
|
||||
}
|
||||
|
||||
private suspend fun runMangaTest(extension: MangaParser) {
|
||||
pingResult = extension.ping()
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
if (testType == "ping") {
|
||||
pingResult = extension.ping()
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
done()
|
||||
return
|
||||
}
|
||||
val searchStart = System.currentTimeMillis()
|
||||
val searchResult = extension.search(searchString)
|
||||
searchResultSize = searchResult.size
|
||||
searchResultData.time = (System.currentTimeMillis() - searchStart).toInt()
|
||||
searchResultData.size = searchResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
searchResult()
|
||||
}
|
||||
if (searchResultSize == 0 || testType == "basic") {
|
||||
if (searchResultData.size == 0 || testType == "basic") {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val episodeResultStart = System.currentTimeMillis()
|
||||
val chapterResult = extension.loadChapters("", null, searchResult.first().sManga!!)
|
||||
episodeResultSize = chapterResult.size
|
||||
episodeResultData.time = (System.currentTimeMillis() - episodeResultStart).toInt()
|
||||
episodeResultData.size = chapterResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
episodeResult()
|
||||
}
|
||||
if (episodeResultSize == 0) {
|
||||
if (episodeResultData.size == 0) {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val serverResultStart = System.currentTimeMillis()
|
||||
val serverResult = extension.loadImages("", chapterResult.first().sChapter)
|
||||
serverResultSize = serverResult.size
|
||||
serverResultData.time = (System.currentTimeMillis() - serverResultStart).toInt()
|
||||
serverResultData.size = serverResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
serverResult()
|
||||
}
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (::binding.isInitialized )
|
||||
binding.extensionLoading.isVisible = false
|
||||
isRunning = false
|
||||
}
|
||||
done()
|
||||
}
|
||||
|
||||
private suspend fun runNovelTest(extension: NovelParser) {
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
if (testType == "ping") {
|
||||
withContext(Dispatchers.Main) {
|
||||
pingResult()
|
||||
}
|
||||
done()
|
||||
return
|
||||
}
|
||||
val searchStart = System.currentTimeMillis()
|
||||
val searchResult = extension.search(searchString)
|
||||
searchResultSize = searchResult.size
|
||||
searchResultData.time = (System.currentTimeMillis() - searchStart).toInt()
|
||||
searchResultData.size = searchResult.size
|
||||
withContext(Dispatchers.Main) {
|
||||
searchResult()
|
||||
}
|
||||
if (searchResultSize == 0 || testType == "basic") {
|
||||
if (searchResultData.size == 0 || testType == "basic") {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val chapterResultTime = System.currentTimeMillis()
|
||||
val chapterResult = extension.loadBook(searchResult.first().link, null)
|
||||
episodeResultSize = chapterResult.links.size
|
||||
episodeResultData.time = (System.currentTimeMillis() - chapterResultTime).toInt()
|
||||
episodeResultData.size = chapterResult.links.size
|
||||
withContext(Dispatchers.Main) {
|
||||
episodeResult()
|
||||
serverResult()
|
||||
}
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (::binding.isInitialized )
|
||||
binding.extensionLoading.isVisible = false
|
||||
isRunning = false
|
||||
}
|
||||
done()
|
||||
}
|
||||
|
||||
private fun done() {
|
||||
private suspend fun done() {
|
||||
if (::binding.isInitialized.not()) return
|
||||
binding.extensionLoading.isVisible = false
|
||||
isRunning = false
|
||||
withContext(Dispatchers.Main) {
|
||||
binding.extensionLoading.isVisible = false
|
||||
isRunning = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun pingResult() {
|
||||
if (::binding.isInitialized.not()) return
|
||||
if (extensionType == "novel") {
|
||||
if (extensionType == "novel" && testType != "basic") {
|
||||
binding.pingResultText.isVisible = true
|
||||
binding.pingResultText.text = context.getString(R.string.test_not_supported)
|
||||
binding.pingResultText.setCompoundDrawablesWithIntrinsicBounds(
|
||||
@@ -242,9 +254,10 @@ class ExtensionTestItem(
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun searchResult() {
|
||||
if (::binding.isInitialized.not()) return
|
||||
if (searchResultSize == null) {
|
||||
if (searchResultData.time == 0) {
|
||||
binding.searchResultText.isVisible = false
|
||||
return
|
||||
}
|
||||
@@ -252,7 +265,7 @@ class ExtensionTestItem(
|
||||
context.getThemeColor(com.google.android.material.R.attr.colorPrimary)
|
||||
)
|
||||
binding.searchResultText.isVisible = true
|
||||
if (searchResultSize == 0) {
|
||||
if (searchResultData.size == 0) {
|
||||
val text = context.getString(R.string.title_search_test,
|
||||
context.getString(R.string.no_results_found))
|
||||
binding.searchResultText.text = text
|
||||
@@ -265,16 +278,17 @@ class ExtensionTestItem(
|
||||
return
|
||||
}
|
||||
val text = context.getString(R.string.title_search_test,
|
||||
context.getString(R.string.results_found, searchResultSize.toString()))
|
||||
binding.searchResultText.text = text
|
||||
context.getString(R.string.results_found, searchResultData.size.toString()))
|
||||
binding.searchResultText.text = text + "\n${searchResultData.time}ms"
|
||||
binding.searchResultText.setCompoundDrawablesWithIntrinsicBounds(
|
||||
R.drawable.ic_circle_check, 0, 0, 0
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun episodeResult() {
|
||||
if (::binding.isInitialized.not()) return
|
||||
if (episodeResultSize == null) {
|
||||
if (episodeResultData.time == 0) {
|
||||
binding.episodeResultText.isVisible = false
|
||||
return
|
||||
}
|
||||
@@ -282,7 +296,7 @@ class ExtensionTestItem(
|
||||
context.getThemeColor(com.google.android.material.R.attr.colorPrimary)
|
||||
)
|
||||
binding.episodeResultText.isVisible = true
|
||||
if (episodeResultSize == 0) {
|
||||
if (episodeResultData.size == 0) {
|
||||
val text = when(extensionType) {
|
||||
"anime" -> context.getString(R.string.episode_search_test,
|
||||
context.getString(R.string.no_results_found))
|
||||
@@ -302,18 +316,19 @@ class ExtensionTestItem(
|
||||
}
|
||||
val text = when(extensionType) {
|
||||
"anime" -> context.getString(R.string.episode_search_test,
|
||||
context.getString(R.string.results_found, episodeResultSize.toString()))
|
||||
context.getString(R.string.results_found, episodeResultData.size.toString()))
|
||||
"manga" -> context.getString(R.string.chapter_search_test,
|
||||
context.getString(R.string.results_found, episodeResultSize.toString()))
|
||||
context.getString(R.string.results_found, episodeResultData.size.toString()))
|
||||
else -> context.getString(R.string.book_search_test,
|
||||
context.getString(R.string.results_found, episodeResultSize.toString()))
|
||||
context.getString(R.string.results_found, episodeResultData.size.toString()))
|
||||
}
|
||||
binding.episodeResultText.text = text
|
||||
binding.episodeResultText.text = text + "\n${episodeResultData.time}ms"
|
||||
binding.episodeResultText.setCompoundDrawablesWithIntrinsicBounds(
|
||||
R.drawable.ic_circle_check, 0, 0, 0
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun serverResult() {
|
||||
if (::binding.isInitialized.not()) return
|
||||
if (extensionType == "novel") {
|
||||
@@ -324,7 +339,7 @@ class ExtensionTestItem(
|
||||
)
|
||||
return
|
||||
}
|
||||
if (serverResultSize == null) {
|
||||
if (serverResultData.time == 0) {
|
||||
binding.serverResultText.isVisible = false
|
||||
return
|
||||
}
|
||||
@@ -332,7 +347,7 @@ class ExtensionTestItem(
|
||||
context.getThemeColor(com.google.android.material.R.attr.colorPrimary)
|
||||
)
|
||||
binding.serverResultText.isVisible = true
|
||||
if (serverResultSize == 0) {
|
||||
if (serverResultData.size == 0) {
|
||||
val text = when(extensionType) {
|
||||
"anime" -> context.getString(R.string.video_search_test,
|
||||
context.getString(R.string.no_results_found))
|
||||
@@ -341,7 +356,7 @@ class ExtensionTestItem(
|
||||
else -> context.getString(R.string.book_search_test,
|
||||
context.getString(R.string.no_results_found))
|
||||
}
|
||||
binding.serverResultText.text = text
|
||||
binding.serverResultText.text = text + "\n${serverResultData.time}ms"
|
||||
binding.serverResultText.setCompoundDrawablesWithIntrinsicBounds(
|
||||
R.drawable.ic_circle_cancel, 0, 0, 0
|
||||
)
|
||||
@@ -352,11 +367,11 @@ class ExtensionTestItem(
|
||||
}
|
||||
val text = when(extensionType) {
|
||||
"anime" -> context.getString(R.string.video_search_test,
|
||||
context.getString(R.string.results_found, serverResultSize.toString()))
|
||||
context.getString(R.string.results_found, serverResultData.size.toString()))
|
||||
"manga" -> context.getString(R.string.image_search_test,
|
||||
context.getString(R.string.results_found, serverResultSize.toString()))
|
||||
context.getString(R.string.results_found, serverResultData.size.toString()))
|
||||
else -> context.getString(R.string.book_search_test,
|
||||
context.getString(R.string.results_found, serverResultSize.toString()))
|
||||
context.getString(R.string.results_found, serverResultData.size.toString()))
|
||||
}
|
||||
binding.serverResultText.text = text
|
||||
binding.serverResultText.setCompoundDrawablesWithIntrinsicBounds(
|
||||
@@ -364,4 +379,8 @@ class ExtensionTestItem(
|
||||
)
|
||||
}
|
||||
|
||||
data class TestResult(
|
||||
var size: Int = 0,
|
||||
var time: Int = 0,
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.BottomSheetDialogFragment
|
||||
import ani.dantotsu.databinding.BottomSheetExtensionTestSettingsBinding
|
||||
@@ -39,6 +40,26 @@ class ExtensionTestSettingsBottomDialog : BottomSheetDialogFragment() {
|
||||
LinearLayoutManager.VERTICAL,
|
||||
false
|
||||
)
|
||||
binding.searchViewText.setText(searchQuery)
|
||||
binding.searchViewText.addTextChangedListener {
|
||||
searchQuery = it.toString()
|
||||
}
|
||||
binding.extensionTypeRadioGroup.check(
|
||||
when (extensionType) {
|
||||
"anime" -> binding.animeRadioButton.id
|
||||
"manga" -> binding.mangaRadioButton.id
|
||||
"novel" -> binding.novelsRadioButton.id
|
||||
else -> binding.animeRadioButton.id
|
||||
}
|
||||
)
|
||||
binding.testTypeRadioGroup.check(
|
||||
when (testType) {
|
||||
"ping" -> binding.pingRadioButton.id
|
||||
"basic" -> binding.basicRadioButton.id
|
||||
"full" -> binding.fullRadioButton.id
|
||||
else -> binding.pingRadioButton.id
|
||||
}
|
||||
)
|
||||
binding.animeRadioButton.setOnCheckedChangeListener { _, b ->
|
||||
if (b) {
|
||||
extensionType = "anime"
|
||||
@@ -75,6 +96,11 @@ class ExtensionTestSettingsBottomDialog : BottomSheetDialogFragment() {
|
||||
testType = "full"
|
||||
}
|
||||
}
|
||||
binding.extensionTypeTextView.setOnLongClickListener {
|
||||
binding.searchTextView.visibility = View.VISIBLE
|
||||
binding.searchView.visibility = View.VISIBLE
|
||||
true
|
||||
}
|
||||
setupAdapter()
|
||||
}
|
||||
|
||||
@@ -111,7 +137,8 @@ class ExtensionTestSettingsBottomDialog : BottomSheetDialogFragment() {
|
||||
}
|
||||
|
||||
var extensionType = "anime"
|
||||
var testType = "ping"
|
||||
var testType = "basic"
|
||||
var searchQuery = "Chainsaw Man"
|
||||
var extensionsToTest: MutableList<String> = mutableListOf()
|
||||
}
|
||||
}
|
||||
@@ -55,13 +55,11 @@ class OfflineAnimeParser : AnimeParser() {
|
||||
episodes.add(episode)
|
||||
}
|
||||
}
|
||||
//episodes.sortBy { MediaNameAdapter.findEpisodeNumber(it.number) }
|
||||
episodes.addAll(loadEpisodesCompat(animeLink, extra, sAnime))
|
||||
//filter those with the same name
|
||||
return episodes.distinctBy { it.number }
|
||||
.sortedBy { MediaNameAdapter.findEpisodeNumber(it.number) }
|
||||
}
|
||||
return emptyList()
|
||||
episodes.addAll(loadEpisodesCompat(animeLink, extra, sAnime))
|
||||
//filter those with the same name
|
||||
return episodes.distinctBy { it.number }
|
||||
.sortedBy { MediaNameAdapter.findEpisodeNumber(it.number) }
|
||||
}
|
||||
|
||||
override suspend fun loadVideoServers(
|
||||
|
||||
@@ -43,11 +43,10 @@ class OfflineMangaParser : MangaParser() {
|
||||
chapters.add(chapter)
|
||||
}
|
||||
}
|
||||
chapters.addAll(loadChaptersCompat(mangaLink, extra, sManga))
|
||||
return chapters.distinctBy { it.number }
|
||||
.sortedBy { MediaNameAdapter.findChapterNumber(it.number) }
|
||||
}
|
||||
return emptyList()
|
||||
chapters.addAll(loadChaptersCompat(mangaLink, extra, sManga))
|
||||
return chapters.distinctBy { it.number }
|
||||
.sortedBy { MediaNameAdapter.findChapterNumber(it.number) }
|
||||
}
|
||||
|
||||
override suspend fun loadImages(chapterLink: String, sChapter: SChapter): List<MangaImage> {
|
||||
@@ -66,17 +65,16 @@ class OfflineMangaParser : MangaParser() {
|
||||
for (image in images) {
|
||||
Logger.log("imageNumber: ${image.url.url}")
|
||||
}
|
||||
return if (images.isNotEmpty()) {
|
||||
images.sortBy { image ->
|
||||
val matchResult = imageNumberRegex.find(image.url.url)
|
||||
matchResult?.groups?.get(1)?.value?.toIntOrNull() ?: Int.MAX_VALUE
|
||||
}
|
||||
images
|
||||
} else {
|
||||
loadImagesCompat(chapterLink, sChapter)
|
||||
}
|
||||
}
|
||||
return emptyList()
|
||||
return if (images.isNotEmpty()) {
|
||||
images.sortBy { image ->
|
||||
val matchResult = imageNumberRegex.find(image.url.url)
|
||||
matchResult?.groups?.get(1)?.value?.toIntOrNull() ?: Int.MAX_VALUE
|
||||
}
|
||||
images
|
||||
} else {
|
||||
loadImagesCompat(chapterLink, sChapter)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun search(query: String): List<ShowResponse> {
|
||||
|
||||
@@ -66,7 +66,8 @@ class ParserTestActivity : AppCompatActivity() {
|
||||
ExtensionTestItem(
|
||||
"anime",
|
||||
ExtensionTestSettingsBottomDialog.testType,
|
||||
it
|
||||
it,
|
||||
ExtensionTestSettingsBottomDialog.searchQuery
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -81,7 +82,8 @@ class ParserTestActivity : AppCompatActivity() {
|
||||
ExtensionTestItem(
|
||||
"manga",
|
||||
ExtensionTestSettingsBottomDialog.testType,
|
||||
it
|
||||
it,
|
||||
ExtensionTestSettingsBottomDialog.searchQuery
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -96,7 +98,8 @@ class ParserTestActivity : AppCompatActivity() {
|
||||
ExtensionTestItem(
|
||||
"novel",
|
||||
ExtensionTestSettingsBottomDialog.testType,
|
||||
it
|
||||
it,
|
||||
ExtensionTestSettingsBottomDialog.searchQuery
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -93,26 +93,37 @@ class FollowActivity : AppCompatActivity() {
|
||||
val screenWidth = resources.displayMetrics.run { widthPixels / density }
|
||||
binding.listRecyclerView.layoutManager = when (getLayoutType(selected)) {
|
||||
0 -> LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||
1 -> GridLayoutManager(this, (screenWidth / 120f).toInt(), GridLayoutManager.VERTICAL, false)
|
||||
1 -> GridLayoutManager(
|
||||
this,
|
||||
(screenWidth / 120f).toInt(),
|
||||
GridLayoutManager.VERTICAL,
|
||||
false
|
||||
)
|
||||
|
||||
else -> LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||
}
|
||||
users?.forEach { user ->
|
||||
val username = SpannableString(user.name ?: "Unknown")
|
||||
if (getLayoutType(selected) == 0) {
|
||||
val username = SpannableString(user.name ?: "Unknown")
|
||||
adapter.add(
|
||||
FollowerItem(
|
||||
false,
|
||||
user.id,
|
||||
username,
|
||||
user.avatar?.medium,
|
||||
user.bannerImage ?: user.avatar?.medium
|
||||
) { onUserClick(it) })
|
||||
) { onUserClick(it) }
|
||||
)
|
||||
} else {
|
||||
adapter.add(
|
||||
GridFollowerItem(
|
||||
FollowerItem(
|
||||
true,
|
||||
user.id,
|
||||
user.name ?: "Unknown",
|
||||
user.avatar?.medium
|
||||
) { onUserClick(it) })
|
||||
username,
|
||||
user.avatar?.medium,
|
||||
user.bannerImage ?: user.avatar?.medium
|
||||
) { onUserClick(it) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,39 +3,43 @@ package ani.dantotsu.profile
|
||||
|
||||
import android.text.SpannableString
|
||||
import android.view.View
|
||||
import androidx.viewbinding.ViewBinding
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.blurImage
|
||||
import ani.dantotsu.databinding.ItemFollowerBinding
|
||||
import ani.dantotsu.databinding.ItemFollowerGridBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
|
||||
class FollowerItem(
|
||||
private val grid: Boolean,
|
||||
private val id: Int,
|
||||
private val name: SpannableString,
|
||||
private val avatar: String?,
|
||||
private val banner: String?,
|
||||
private val altText: String? = null,
|
||||
val clickCallback: (Int) -> Unit
|
||||
) : BindableItem<ItemFollowerBinding>() {
|
||||
private lateinit var binding: ItemFollowerBinding
|
||||
) : BindableItem<ViewBinding>() {
|
||||
|
||||
override fun bind(viewBinding: ItemFollowerBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
binding.profileUserName.text = name
|
||||
avatar?.let { binding.profileUserAvatar.loadImage(it) }
|
||||
altText?.let {
|
||||
binding.altText.visibility = View.VISIBLE
|
||||
binding.altText.text = it
|
||||
override fun bind(viewBinding: ViewBinding, position: Int) {
|
||||
if (grid) {
|
||||
val binding = viewBinding as ItemFollowerGridBinding
|
||||
binding.profileUserName.text = name
|
||||
avatar?.let { binding.profileUserAvatar.loadImage(it) }
|
||||
binding.root.setOnClickListener { clickCallback(id) }
|
||||
} else {
|
||||
val binding = viewBinding as ItemFollowerBinding
|
||||
binding.profileUserName.text = name
|
||||
avatar?.let { binding.profileUserAvatar.loadImage(it) }
|
||||
blurImage(binding.profileBannerImage, banner ?: avatar)
|
||||
binding.root.setOnClickListener { clickCallback(id) }
|
||||
}
|
||||
blurImage(binding.profileBannerImage, banner ?: avatar)
|
||||
binding.root.setOnClickListener { clickCallback(id) }
|
||||
}
|
||||
|
||||
override fun getLayout(): Int {
|
||||
return R.layout.item_follower
|
||||
return if(grid) R.layout.item_follower_grid else R.layout.item_follower
|
||||
}
|
||||
|
||||
override fun initializeViewBinding(view: View): ItemFollowerBinding {
|
||||
return ItemFollowerBinding.bind(view)
|
||||
override fun initializeViewBinding(view: View): ViewBinding {
|
||||
return if(grid) ItemFollowerGridBinding.bind(view) else ItemFollowerBinding.bind(view)
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package ani.dantotsu.profile
|
||||
|
||||
import android.view.View
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.ItemFollowerGridBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
|
||||
class GridFollowerItem(
|
||||
private val id: Int,
|
||||
private val name: String,
|
||||
private val avatar: String?,
|
||||
val clickCallback: (Int) -> Unit
|
||||
) : BindableItem<ItemFollowerGridBinding>() {
|
||||
private lateinit var binding: ItemFollowerGridBinding
|
||||
|
||||
override fun bind(viewBinding: ItemFollowerGridBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
binding.profileUserName.text = name
|
||||
avatar?.let { binding.profileUserAvatar.loadImage(it) }
|
||||
binding.root.setOnClickListener { clickCallback(id) }
|
||||
}
|
||||
|
||||
override fun getLayout(): Int {
|
||||
return R.layout.item_follower_grid
|
||||
}
|
||||
|
||||
override fun initializeViewBinding(view: View): ItemFollowerGridBinding {
|
||||
return ItemFollowerGridBinding.bind(view)
|
||||
}
|
||||
}
|
||||
@@ -28,16 +28,16 @@ import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.media.user.ListActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.openImage
|
||||
import ani.dantotsu.openLinkInBrowser
|
||||
import ani.dantotsu.others.ImageViewDialog
|
||||
import ani.dantotsu.profile.activity.FeedFragment
|
||||
import ani.dantotsu.profile.activity.ActivityFragment
|
||||
import ani.dantotsu.profile.activity.ActivityFragment.Companion.ActivityType
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.MarkdownCreatorActivity
|
||||
import com.google.android.material.appbar.AppBarLayout
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -135,7 +135,7 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
|
||||
followButton.setOnClickListener {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val res = Anilist.query.toggleFollow(user.id)
|
||||
val res = Anilist.mutation.toggleFollow(user.id)
|
||||
if (res?.data?.toggleFollow != null) {
|
||||
withContext(Dispatchers.Main) {
|
||||
snackString(R.string.success)
|
||||
@@ -155,15 +155,8 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
openLinkInBrowser("https://anilist.co/user/${user.name}")
|
||||
true
|
||||
}
|
||||
R.id.action_create_new_activity -> {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, MarkdownCreatorActivity::class.java)
|
||||
.putExtra("type", "activity"),
|
||||
null
|
||||
)
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
@@ -171,15 +164,13 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
}
|
||||
|
||||
profileUserAvatar.loadImage(user.avatar?.medium)
|
||||
profileUserAvatar.setOnLongClickListener {
|
||||
ImageViewDialog.newInstance(
|
||||
context,
|
||||
getString(R.string.avatar, user.name),
|
||||
user.avatar?.medium
|
||||
)
|
||||
}
|
||||
profileUserAvatar.openImage(
|
||||
context.getString(R.string.avatar, user.name),
|
||||
user.avatar?.medium ?: ""
|
||||
)
|
||||
profileUserName.text = user.name
|
||||
val bannerAnimations: ImageView= if (PrefManager.getVal(PrefName.BannerAnimations)) profileBannerImage else profileBannerImageNoKen
|
||||
val bannerAnimations: ImageView =
|
||||
if (PrefManager.getVal(PrefName.BannerAnimations)) profileBannerImage else profileBannerImageNoKen
|
||||
|
||||
blurImage(
|
||||
bannerAnimations,
|
||||
@@ -192,19 +183,17 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
profileMenuButton.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin += statusBarHeight }
|
||||
profileButtonContainer.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin += statusBarHeight }
|
||||
|
||||
profileBannerImage.setOnLongClickListener {
|
||||
ImageViewDialog.newInstance(
|
||||
context,
|
||||
getString(R.string.banner, user.name),
|
||||
user.bannerImage
|
||||
)
|
||||
}
|
||||
profileBannerImage.openImage(
|
||||
context.getString(R.string.banner, user.name),
|
||||
user.bannerImage ?: user.avatar?.medium ?: ""
|
||||
)
|
||||
|
||||
mMaxScrollSize = profileAppBar.totalScrollRange
|
||||
profileAppBar.addOnOffsetChangedListener(context)
|
||||
|
||||
|
||||
profileFollowerCount.text = (respond.data.followerPage?.pageInfo?.total ?: 0).toString()
|
||||
profileFollowerCount.text =
|
||||
(respond.data.followerPage?.pageInfo?.total ?: 0).toString()
|
||||
profileFollowerCountContainer.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
@@ -214,7 +203,8 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
null
|
||||
)
|
||||
}
|
||||
profileFollowingCount.text = (respond.data.followingPage?.pageInfo?.total ?: 0).toString()
|
||||
profileFollowingCount.text =
|
||||
(respond.data.followingPage?.pageInfo?.total ?: 0).toString()
|
||||
profileFollowingCountContainer.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
@@ -325,7 +315,7 @@ class ProfileActivity : AppCompatActivity(), AppBarLayout.OnOffsetChangedListene
|
||||
override fun getItemCount(): Int = 3
|
||||
override fun createFragment(position: Int): Fragment = when (position) {
|
||||
0 -> ProfileFragment.newInstance(user)
|
||||
1 -> FeedFragment.newInstance(user.id, false, -1)
|
||||
1 -> ActivityFragment.newInstance(ActivityType.OTHER_USER, user.id)
|
||||
2 -> StatsFragment.newInstance(user)
|
||||
else -> ProfileFragment.newInstance(user)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import ani.dantotsu.media.Character
|
||||
import ani.dantotsu.media.CharacterAdapter
|
||||
import ani.dantotsu.media.Media
|
||||
import ani.dantotsu.media.MediaAdaptor
|
||||
import ani.dantotsu.openOrCopyAnilistLink
|
||||
import ani.dantotsu.setBaseline
|
||||
import ani.dantotsu.setSlideIn
|
||||
import ani.dantotsu.setSlideUp
|
||||
@@ -97,6 +98,7 @@ class ProfileFragment : Fragment() {
|
||||
view: WebView?,
|
||||
request: WebResourceRequest?
|
||||
): Boolean {
|
||||
openOrCopyAnilistLink(request?.url.toString())
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package ani.dantotsu.profile.activity
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.api.Activity
|
||||
import ani.dantotsu.databinding.FragmentFeedBinding
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import eu.kanade.tachiyomi.util.system.getSerializableCompat
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class ActivityFragment : Fragment() {
|
||||
private lateinit var type: ActivityType
|
||||
private var userId: Int? = null
|
||||
private var activityId: Int? = null
|
||||
private lateinit var binding: FragmentFeedBinding
|
||||
private var adapter: GroupieAdapter = GroupieAdapter()
|
||||
private var page: Int = 1
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
binding = FragmentFeedBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
arguments?.let {
|
||||
type = it.getSerializableCompat<ActivityType>("type") as ActivityType
|
||||
userId = it.getInt("userId")
|
||||
activityId = it.getInt("activityId")
|
||||
}
|
||||
binding.titleBar.visibility =
|
||||
if (type == ActivityType.OTHER_USER) View.VISIBLE else View.GONE
|
||||
binding.titleText.text =
|
||||
if (userId == Anilist.userid) getString(R.string.create_new_activity) else getString(R.string.write_a_message)
|
||||
binding.titleImage.setOnClickListener { handleTitleImageClick() }
|
||||
binding.listRecyclerView.adapter = adapter
|
||||
binding.listRecyclerView.layoutManager = LinearLayoutManager(context)
|
||||
binding.listProgressBar.isVisible = true
|
||||
|
||||
binding.feedRefresh.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin = navBarHeight
|
||||
}
|
||||
binding.emptyTextView.text = getString(R.string.no_activities)
|
||||
lifecycleScope.launch {
|
||||
getList()
|
||||
if (adapter.itemCount == 0) {
|
||||
binding.emptyTextView.isVisible = true
|
||||
}
|
||||
binding.listProgressBar.isVisible = false
|
||||
}
|
||||
binding.feedSwipeRefresh.setOnRefreshListener {
|
||||
lifecycleScope.launch {
|
||||
adapter.clear()
|
||||
page = 1
|
||||
getList()
|
||||
binding.feedSwipeRefresh.isRefreshing = false
|
||||
}
|
||||
}
|
||||
binding.listRecyclerView.addOnScrollListener(object :
|
||||
RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(recyclerView, dx, dy)
|
||||
if (shouldLoadMore()) {
|
||||
lifecycleScope.launch {
|
||||
binding.feedRefresh.isVisible = true
|
||||
getList()
|
||||
binding.feedRefresh.isVisible = false
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun handleTitleImageClick() {
|
||||
val intent = Intent(context, ActivityMarkdownCreator::class.java).apply {
|
||||
putExtra("type", if (userId == Anilist.userid) "activity" else "message")
|
||||
putExtra("userId", userId)
|
||||
}
|
||||
ContextCompat.startActivity(requireContext(), intent, null)
|
||||
}
|
||||
|
||||
private suspend fun getList() {
|
||||
val list = when (type) {
|
||||
ActivityType.GLOBAL -> getActivities(global = true)
|
||||
ActivityType.USER -> getActivities(filter = true)
|
||||
ActivityType.OTHER_USER -> getActivities(userId = userId)
|
||||
ActivityType.ONE -> getActivities(activityId = activityId)
|
||||
}
|
||||
adapter.addAll(list.map { ActivityItem(it, adapter, ::onActivityClick) })
|
||||
}
|
||||
|
||||
private suspend fun getActivities(
|
||||
global: Boolean = false,
|
||||
userId: Int? = null,
|
||||
activityId: Int? = null,
|
||||
filter: Boolean = false
|
||||
): List<Activity> {
|
||||
val res = Anilist.query.getFeed(userId, global, page, activityId)?.data?.page?.activities
|
||||
page += 1
|
||||
return res
|
||||
?.filter { if (Anilist.adult) true else it.media?.isAdult != true }
|
||||
?.filterNot { it.recipient?.id != null && it.recipient.id != Anilist.userid && filter }
|
||||
?: emptyList()
|
||||
}
|
||||
|
||||
private fun shouldLoadMore(): Boolean {
|
||||
val layoutManager =
|
||||
(binding.listRecyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
|
||||
val adapter = binding.listRecyclerView.adapter
|
||||
return !binding.listRecyclerView.canScrollVertically(1) &&
|
||||
!binding.feedRefresh.isVisible && adapter?.itemCount != 0 &&
|
||||
layoutManager == (adapter!!.itemCount - 1)
|
||||
|
||||
}
|
||||
|
||||
private fun onActivityClick(id: Int, type: String) {
|
||||
val intent = when (type) {
|
||||
"USER" -> Intent(requireContext(), ProfileActivity::class.java).putExtra("userId", id)
|
||||
"MEDIA" -> Intent(
|
||||
requireContext(),
|
||||
MediaDetailsActivity::class.java
|
||||
).putExtra("mediaId", id)
|
||||
|
||||
else -> return
|
||||
}
|
||||
ContextCompat.startActivity(requireContext(), intent, null)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (this::binding.isInitialized) {
|
||||
binding.root.requestLayout()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
enum class ActivityType { GLOBAL, USER, OTHER_USER, ONE }
|
||||
|
||||
fun newInstance(
|
||||
type: ActivityType,
|
||||
userId: Int? = null,
|
||||
activityId: Int? = null
|
||||
): ActivityFragment {
|
||||
return ActivityFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putSerializable("type", type)
|
||||
userId?.let { putInt("userId", it) }
|
||||
activityId?.let { putInt("activityId", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import android.view.View
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.blurImage
|
||||
import ani.dantotsu.buildMarkwon
|
||||
@@ -18,7 +17,7 @@ import ani.dantotsu.profile.UsersDialogFragment
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.AniMarkdown.Companion.getBasicAniHTML
|
||||
import ani.dantotsu.util.MarkdownCreatorActivity
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -29,23 +28,16 @@ import kotlinx.coroutines.withContext
|
||||
|
||||
class ActivityItem(
|
||||
private val activity: Activity,
|
||||
private val parentAdapter: GroupieAdapter,
|
||||
val clickCallback: (Int, type: String) -> Unit,
|
||||
private val fragActivity: FragmentActivity
|
||||
) : BindableItem<ItemActivityBinding>() {
|
||||
private lateinit var binding: ItemActivityBinding
|
||||
private lateinit var repliesAdapter: GroupieAdapter
|
||||
|
||||
override fun bind(viewBinding: ItemActivityBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
val context = binding.root.context
|
||||
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
setAnimation(binding.root.context, binding.root)
|
||||
|
||||
repliesAdapter = GroupieAdapter()
|
||||
binding.activityReplies.adapter = repliesAdapter
|
||||
binding.activityReplies.layoutManager = LinearLayoutManager(
|
||||
binding.root.context,
|
||||
LinearLayoutManager.VERTICAL,
|
||||
false
|
||||
)
|
||||
binding.activityUserName.text = activity.user?.name ?: activity.messenger?.name
|
||||
binding.activityUserAvatar.loadImage(
|
||||
activity.user?.avatar?.medium ?: activity.messenger?.avatar?.medium
|
||||
@@ -54,66 +46,29 @@ class ActivityItem(
|
||||
val likeColor = ContextCompat.getColor(binding.root.context, R.color.yt_red)
|
||||
val notLikeColor = ContextCompat.getColor(binding.root.context, R.color.bg_opp)
|
||||
binding.activityLike.setColorFilter(if (activity.isLiked == true) likeColor else notLikeColor)
|
||||
binding.commentTotalReplies.isVisible = activity.replyCount > 0
|
||||
binding.dot.isVisible = activity.replyCount > 0
|
||||
binding.commentTotalReplies.setOnClickListener {
|
||||
when (binding.activityReplies.visibility) {
|
||||
View.GONE -> {
|
||||
val replyItems = activity.replies?.map {
|
||||
ActivityReplyItem(it,fragActivity) { id, type ->
|
||||
clickCallback(
|
||||
id,
|
||||
type
|
||||
)
|
||||
}
|
||||
} ?: emptyList()
|
||||
repliesAdapter.addAll(replyItems)
|
||||
binding.activityReplies.visibility = View.VISIBLE
|
||||
binding.commentTotalReplies.setText(R.string.hide_replies)
|
||||
}
|
||||
|
||||
else -> {
|
||||
repliesAdapter.clear()
|
||||
binding.activityReplies.visibility = View.GONE
|
||||
binding.commentTotalReplies.setText(R.string.view_replies)
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
if (activity.isLocked != true) {
|
||||
binding.commentReply.setOnClickListener {
|
||||
val context = binding.root.context
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, MarkdownCreatorActivity::class.java)
|
||||
.putExtra("type", "replyActivity")
|
||||
.putExtra("parentId", activity.id),
|
||||
null
|
||||
)
|
||||
}
|
||||
} else {
|
||||
binding.commentReply.visibility = View.GONE
|
||||
binding.dot.visibility = View.GONE
|
||||
}
|
||||
val userList = arrayListOf<User>()
|
||||
activity.likes?.forEach { i ->
|
||||
userList.add(User(i.id, i.name.toString(), i.avatar?.medium, i.bannerImage))
|
||||
}
|
||||
binding.activityRepliesContainer.setOnClickListener {
|
||||
RepliesBottomDialog.newInstance(activity.id)
|
||||
.show((context as FragmentActivity).supportFragmentManager, "replies")
|
||||
}
|
||||
binding.replyCount.text = activity.replyCount.toString()
|
||||
binding.activityReplies.setColorFilter(ContextCompat.getColor(binding.root.context, R.color.bg_opp))
|
||||
binding.activityLikeContainer.setOnLongClickListener {
|
||||
UsersDialogFragment().apply {
|
||||
userList(userList)
|
||||
show(fragActivity.supportFragmentManager, "dialog")
|
||||
show((context as FragmentActivity).supportFragmentManager, "dialog")
|
||||
}
|
||||
true
|
||||
}
|
||||
binding.activityLikeCount.text = (activity.likeCount ?: 0).toString()
|
||||
binding.activityLikeContainer.setOnClickListener {
|
||||
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
scope.launch {
|
||||
val res = Anilist.query.toggleLike(activity.id, "ACTIVITY")
|
||||
val res = Anilist.mutation.toggleLike(activity.id, "ACTIVITY")
|
||||
withContext(Dispatchers.Main) {
|
||||
if (res != null) {
|
||||
|
||||
if (activity.isLiked == true) {
|
||||
activity.likeCount = activity.likeCount?.minus(1)
|
||||
} else {
|
||||
@@ -129,13 +84,27 @@ class ActivityItem(
|
||||
}
|
||||
}
|
||||
}
|
||||
val context = binding.root.context
|
||||
binding.activityDelete.isVisible = activity.userId == Anilist.userid || activity.messenger?.id == Anilist.userid
|
||||
binding.activityDelete.setOnClickListener {
|
||||
scope.launch {
|
||||
val res = Anilist.mutation.deleteActivity(activity.id)
|
||||
withContext(Dispatchers.Main) {
|
||||
if (res) {
|
||||
snackString("Deleted activity")
|
||||
parentAdapter.remove(this@ActivityItem)
|
||||
} else {
|
||||
snackString("Failed to delete activity")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
when (activity.typename) {
|
||||
"ListActivity" -> {
|
||||
val cover = activity.media?.coverImage?.large
|
||||
val banner = activity.media?.bannerImage
|
||||
binding.activityContent.visibility = View.GONE
|
||||
binding.activityBannerContainer.visibility = View.VISIBLE
|
||||
binding.activityPrivate.visibility = View.GONE
|
||||
binding.activityMediaName.text = activity.media?.title?.userPreferred
|
||||
val activityText = "${activity.user!!.name} ${activity.status} ${
|
||||
activity.progress
|
||||
@@ -156,11 +125,13 @@ class ActivityItem(
|
||||
binding.activityMediaName.setOnClickListener {
|
||||
clickCallback(activity.media?.id ?: -1, "MEDIA")
|
||||
}
|
||||
binding.activityEdit.isVisible = false
|
||||
}
|
||||
|
||||
"TextActivity" -> {
|
||||
binding.activityBannerContainer.visibility = View.GONE
|
||||
binding.activityContent.visibility = View.VISIBLE
|
||||
binding.activityPrivate.visibility = View.GONE
|
||||
if (!(context as android.app.Activity).isDestroyed) {
|
||||
val markwon = buildMarkwon(context, false)
|
||||
markwon.setMarkdown(
|
||||
@@ -174,11 +145,23 @@ class ActivityItem(
|
||||
binding.activityUserName.setOnClickListener {
|
||||
clickCallback(activity.userId ?: -1, "USER")
|
||||
}
|
||||
binding.activityEdit.isVisible = activity.userId == Anilist.userid
|
||||
binding.activityEdit.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "activity")
|
||||
.putExtra("other", activity.text)
|
||||
.putExtra("edit", activity.id),
|
||||
null
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"MessageActivity" -> {
|
||||
binding.activityBannerContainer.visibility = View.GONE
|
||||
binding.activityContent.visibility = View.VISIBLE
|
||||
binding.activityPrivate.visibility = if (activity.isPrivate == true) View.VISIBLE else View.GONE
|
||||
if (!(context as android.app.Activity).isDestroyed) {
|
||||
val markwon = buildMarkwon(context, false)
|
||||
markwon.setMarkdown(
|
||||
@@ -192,6 +175,19 @@ class ActivityItem(
|
||||
binding.activityUserName.setOnClickListener {
|
||||
clickCallback(activity.messengerId ?: -1, "USER")
|
||||
}
|
||||
binding.activityEdit.isVisible = false
|
||||
binding.activityEdit.isVisible = activity.messenger?.id == Anilist.userid
|
||||
binding.activityEdit.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "message")
|
||||
.putExtra("other", activity.message)
|
||||
.putExtra("edit", activity.id)
|
||||
.putExtra("userId", activity.recipientId),
|
||||
null
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package ani.dantotsu.profile.activity
|
||||
|
||||
import android.content.Intent
|
||||
import android.view.View
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.buildMarkwon
|
||||
@@ -13,6 +15,8 @@ import ani.dantotsu.profile.User
|
||||
import ani.dantotsu.profile.UsersDialogFragment
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.AniMarkdown.Companion.getBasicAniHTML
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -22,23 +26,27 @@ import kotlinx.coroutines.withContext
|
||||
|
||||
class ActivityReplyItem(
|
||||
private val reply: ActivityReply,
|
||||
private val parentId : Int,
|
||||
private val fragActivity: FragmentActivity,
|
||||
private val parentAdapter: GroupieAdapter,
|
||||
private val clickCallback: (Int, type: String) -> Unit,
|
||||
) : BindableItem<ItemActivityReplyBinding>() {
|
||||
private lateinit var binding: ItemActivityReplyBinding
|
||||
|
||||
override fun bind(viewBinding: ItemActivityReplyBinding, position: Int) {
|
||||
binding = viewBinding
|
||||
|
||||
val context = binding.root.context
|
||||
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
binding.activityUserAvatar.loadImage(reply.user.avatar?.medium)
|
||||
binding.activityUserName.text = reply.user.name
|
||||
binding.activityTime.text = ActivityItemBuilder.getDateTime(reply.createdAt)
|
||||
binding.activityLikeCount.text = reply.likeCount.toString()
|
||||
val likeColor = ContextCompat.getColor(binding.root.context, R.color.yt_red)
|
||||
val notLikeColor = ContextCompat.getColor(binding.root.context, R.color.bg_opp)
|
||||
val likeColor = ContextCompat.getColor(context, R.color.yt_red)
|
||||
val notLikeColor = ContextCompat.getColor(context, R.color.bg_opp)
|
||||
binding.activityLike.setColorFilter(if (reply.isLiked) likeColor else notLikeColor)
|
||||
val markwon = buildMarkwon(binding.root.context)
|
||||
val markwon = buildMarkwon(context)
|
||||
markwon.setMarkdown(binding.activityContent, getBasicAniHTML(reply.text))
|
||||
|
||||
val userList = arrayListOf<User>()
|
||||
reply.likes?.forEach { i ->
|
||||
userList.add(User(i.id, i.name.toString(), i.avatar?.medium, i.bannerImage))
|
||||
@@ -51,9 +59,8 @@ class ActivityReplyItem(
|
||||
true
|
||||
}
|
||||
binding.activityLikeContainer.setOnClickListener {
|
||||
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
scope.launch {
|
||||
val res = Anilist.query.toggleLike(reply.id, "ACTIVITY_REPLY")
|
||||
val res = Anilist.mutation.toggleLike(reply.id, "ACTIVITY_REPLY")
|
||||
withContext(Dispatchers.Main) {
|
||||
if (res != null) {
|
||||
if (reply.isLiked) {
|
||||
@@ -71,6 +78,42 @@ class ActivityReplyItem(
|
||||
}
|
||||
}
|
||||
}
|
||||
binding.activityReply.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "replyActivity")
|
||||
.putExtra("parentId", parentId)
|
||||
.putExtra("other", "@${reply.user.name} "),
|
||||
null
|
||||
)
|
||||
}
|
||||
binding.activityEdit.isVisible = reply.userId == Anilist.userid
|
||||
binding.activityEdit.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "replyActivity")
|
||||
.putExtra("parentId", parentId)
|
||||
.putExtra("other", reply.text)
|
||||
.putExtra("edit", reply.id),
|
||||
null
|
||||
)
|
||||
}
|
||||
binding.activityDelete.isVisible = reply.userId == Anilist.userid
|
||||
binding.activityDelete.setOnClickListener {
|
||||
scope.launch {
|
||||
val res = Anilist.mutation.deleteActivityReply(reply.id)
|
||||
withContext(Dispatchers.Main) {
|
||||
if (res) {
|
||||
snackString("Deleted")
|
||||
parentAdapter.remove(this@ActivityReplyItem)
|
||||
} else {
|
||||
snackString("Failed to delete")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
binding.activityAvatarContainer.setOnClickListener {
|
||||
clickCallback(reply.userId, "USER")
|
||||
|
||||
@@ -2,6 +2,7 @@ package ani.dantotsu.profile.activity
|
||||
|
||||
import android.content.res.Configuration
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.view.updateLayoutParams
|
||||
@@ -10,16 +11,20 @@ import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.ActivityFeedBinding
|
||||
import ani.dantotsu.databinding.ActivityNotificationBinding
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.profile.activity.ActivityFragment.Companion.ActivityType
|
||||
import ani.dantotsu.profile.notification.NotificationActivity
|
||||
import nl.joery.animatedbottombar.AnimatedBottomBar
|
||||
|
||||
class FeedActivity : AppCompatActivity() {
|
||||
private lateinit var binding: ActivityFeedBinding
|
||||
private lateinit var binding: ActivityNotificationBinding
|
||||
private var selected: Int = 0
|
||||
lateinit var navBar: AnimatedBottomBar
|
||||
|
||||
@@ -27,28 +32,28 @@ class FeedActivity : AppCompatActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
ThemeManager(this).applyTheme()
|
||||
initActivity(this)
|
||||
binding = ActivityFeedBinding.inflate(layoutInflater)
|
||||
binding = ActivityNotificationBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
navBar = binding.feedNavBar
|
||||
val navBarMargin = if (resources.configuration.orientation ==
|
||||
Configuration.ORIENTATION_LANDSCAPE
|
||||
) 0 else navBarHeight
|
||||
navBar.updateLayoutParams<ViewGroup.MarginLayoutParams> { bottomMargin = navBarMargin }
|
||||
val personalTab = navBar.createTab(R.drawable.ic_round_person_24, "Following")
|
||||
val globalTab = navBar.createTab(R.drawable.ic_globe_24, "Global")
|
||||
navBar.addTab(personalTab)
|
||||
navBar.addTab(globalTab)
|
||||
binding.listTitle.text = getString(R.string.activities)
|
||||
binding.feedViewPager.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin = navBarMargin
|
||||
topMargin += statusBarHeight
|
||||
binding.notificationTitle.text = getString(R.string.activities)
|
||||
binding.notificationToolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin = statusBarHeight
|
||||
}
|
||||
binding.listToolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin += statusBarHeight }
|
||||
val activityId = intent.getIntExtra("activityId", -1)
|
||||
binding.feedViewPager.adapter =
|
||||
ViewPagerAdapter(supportFragmentManager, lifecycle, activityId)
|
||||
binding.feedViewPager.setCurrentItem(selected, false)
|
||||
binding.feedViewPager.isUserInputEnabled = false
|
||||
navBar = binding.notificationNavBar
|
||||
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin = navBarHeight
|
||||
}
|
||||
val tabs = listOf(
|
||||
Pair(R.drawable.ic_round_person_24, "Following"),
|
||||
Pair(R.drawable.ic_globe_24, "Global"),
|
||||
)
|
||||
tabs.forEach { (icon, title) -> navBar.addTab(navBar.createTab(icon, title)) }
|
||||
|
||||
binding.notificationBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
|
||||
val getOne = intent.getIntExtra("activityId", -1)
|
||||
if (getOne != -1) { navBar.visibility = View.GONE }
|
||||
binding.notificationViewPager.adapter = ViewPagerAdapter(supportFragmentManager, lifecycle, getOne)
|
||||
binding.notificationViewPager.setOffscreenPageLimit(4)
|
||||
binding.notificationViewPager.setCurrentItem(selected, false)
|
||||
navBar.selectTabAt(selected)
|
||||
navBar.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener {
|
||||
override fun onTabSelected(
|
||||
@@ -58,24 +63,15 @@ class FeedActivity : AppCompatActivity() {
|
||||
newTab: AnimatedBottomBar.Tab
|
||||
) {
|
||||
selected = newIndex
|
||||
binding.feedViewPager.setCurrentItem(selected, true)
|
||||
binding.notificationViewPager.setCurrentItem(selected, true)
|
||||
}
|
||||
})
|
||||
binding.notificationViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
|
||||
override fun onPageSelected(position: Int) {
|
||||
super.onPageSelected(position)
|
||||
navBar.selectTabAt(position)
|
||||
}
|
||||
})
|
||||
binding.listBack.setOnClickListener {
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
val margin =
|
||||
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) 0 else navBarHeight
|
||||
val params: ViewGroup.MarginLayoutParams =
|
||||
binding.feedViewPager.layoutParams as ViewGroup.MarginLayoutParams
|
||||
val paramsNav: ViewGroup.MarginLayoutParams =
|
||||
navBar.layoutParams as ViewGroup.MarginLayoutParams
|
||||
params.updateMargins(bottom = margin)
|
||||
paramsNav.updateMargins(bottom = margin)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
@@ -88,12 +84,12 @@ class FeedActivity : AppCompatActivity() {
|
||||
lifecycle: Lifecycle,
|
||||
private val activityId: Int
|
||||
) : FragmentStateAdapter(fragmentManager, lifecycle) {
|
||||
override fun getItemCount(): Int = 2
|
||||
override fun getItemCount(): Int = if (activityId != -1) 1 else 2
|
||||
|
||||
override fun createFragment(position: Int): Fragment {
|
||||
return when (position) {
|
||||
0 -> FeedFragment.newInstance(null, false, activityId)
|
||||
else -> FeedFragment.newInstance(null, true, -1)
|
||||
0 -> ActivityFragment.newInstance(if (activityId != -1) ActivityType.ONE else ActivityType.USER, activityId = activityId)
|
||||
else -> ActivityFragment.newInstance(ActivityType.GLOBAL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
package ani.dantotsu.profile.activity
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.AnilistQueries
|
||||
import ani.dantotsu.connections.anilist.api.Activity
|
||||
import ani.dantotsu.databinding.FragmentFeedBinding
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.setBaseline
|
||||
import ani.dantotsu.util.Logger
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class FeedFragment : Fragment() {
|
||||
private lateinit var binding: FragmentFeedBinding
|
||||
private var adapter: GroupieAdapter = GroupieAdapter()
|
||||
private var activityList: List<Activity> = emptyList()
|
||||
private lateinit var activity: androidx.activity.ComponentActivity
|
||||
private var page: Int = 1
|
||||
private var loadedFirstTime = false
|
||||
private var userId: Int? = null
|
||||
private var global: Boolean = false
|
||||
private var activityId: Int = -1
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
binding = FragmentFeedBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
activity = requireActivity()
|
||||
|
||||
userId = arguments?.getInt("userId", -1)
|
||||
activityId = arguments?.getInt("activityId", -1) ?: -1
|
||||
if (userId == -1) userId = null
|
||||
global = arguments?.getBoolean("global", false) ?: false
|
||||
|
||||
val navBar = if (userId != null) {
|
||||
(activity as ProfileActivity).navBar
|
||||
} else {
|
||||
(activity as FeedActivity).navBar
|
||||
}
|
||||
binding.listRecyclerView.setBaseline(navBar)
|
||||
binding.listRecyclerView.adapter = adapter
|
||||
binding.listRecyclerView.layoutManager =
|
||||
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
|
||||
binding.listProgressBar.visibility = ViewGroup.VISIBLE
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (this::binding.isInitialized) {
|
||||
binding.root.requestLayout()
|
||||
val navBar = if (userId != null) {
|
||||
(activity as ProfileActivity).navBar
|
||||
} else {
|
||||
(activity as FeedActivity).navBar
|
||||
}
|
||||
binding.listRecyclerView.setBaseline(navBar)
|
||||
if (!loadedFirstTime) {
|
||||
activity.lifecycleScope.launch(Dispatchers.IO) {
|
||||
val nulledId = if (activityId == -1) null else activityId
|
||||
val res = Anilist.query.getFeed(userId, global, activityId = nulledId)
|
||||
withContext(Dispatchers.Main) {
|
||||
res?.data?.page?.activities?.let { activities ->
|
||||
activityList = activities
|
||||
val filtered =
|
||||
activityList.filterNot { //filter out messages that are not directed to the user
|
||||
it.recipient?.id != null && it.recipient.id != Anilist.userid
|
||||
}
|
||||
adapter.update(filtered.map {
|
||||
ActivityItem(
|
||||
it,
|
||||
::onActivityClick,
|
||||
requireActivity()
|
||||
)
|
||||
})
|
||||
}
|
||||
binding.listProgressBar.visibility = ViewGroup.GONE
|
||||
val scrollView = binding.listRecyclerView
|
||||
|
||||
binding.listRecyclerView.setOnTouchListener { _, event ->
|
||||
if (event?.action == MotionEvent.ACTION_UP) {
|
||||
if (activityList.size % AnilistQueries.ITEMS_PER_PAGE != 0 && !global) {
|
||||
//snackString("No more activities") fix spam?
|
||||
Logger.log("No more activities")
|
||||
} else if (!scrollView.canScrollVertically(1) && !binding.feedRefresh.isVisible
|
||||
&& binding.listRecyclerView.adapter!!.itemCount != 0 &&
|
||||
(binding.listRecyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() == (binding.listRecyclerView.adapter!!.itemCount - 1)
|
||||
) {
|
||||
page++
|
||||
binding.feedRefresh.visibility = ViewGroup.VISIBLE
|
||||
loadPage {
|
||||
binding.feedRefresh.visibility = ViewGroup.GONE
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
binding.feedSwipeRefresh.setOnRefreshListener {
|
||||
page = 1
|
||||
adapter.clear()
|
||||
activityList = emptyList()
|
||||
loadPage()
|
||||
}
|
||||
}
|
||||
}
|
||||
loadedFirstTime = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadPage(onFinish: () -> Unit = {}) {
|
||||
activity.lifecycleScope.launch(Dispatchers.IO) {
|
||||
val newRes = Anilist.query.getFeed(userId, global, page)
|
||||
withContext(Dispatchers.Main) {
|
||||
newRes?.data?.page?.activities?.let { activities ->
|
||||
activityList += activities
|
||||
val filtered = activities.filterNot {
|
||||
it.recipient?.id != null && it.recipient.id != Anilist.userid
|
||||
}
|
||||
adapter.addAll(filtered.map {
|
||||
ActivityItem(
|
||||
it,
|
||||
::onActivityClick,
|
||||
requireActivity()
|
||||
)
|
||||
})
|
||||
}
|
||||
binding.feedSwipeRefresh.isRefreshing = false
|
||||
onFinish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onActivityClick(id: Int, type: String) {
|
||||
when (type) {
|
||||
"USER" -> {
|
||||
ContextCompat.startActivity(
|
||||
activity, Intent(activity, ProfileActivity::class.java)
|
||||
.putExtra("userId", id), null
|
||||
)
|
||||
}
|
||||
|
||||
"MEDIA" -> {
|
||||
ContextCompat.startActivity(
|
||||
activity, Intent(activity, MediaDetailsActivity::class.java)
|
||||
.putExtra("mediaId", id), null
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun newInstance(userId: Int?, global: Boolean, activityId: Int): FeedFragment {
|
||||
val fragment = FeedFragment()
|
||||
val args = Bundle()
|
||||
args.putInt("userId", userId ?: -1)
|
||||
args.putBoolean("global", global)
|
||||
args.putInt("activityId", activityId)
|
||||
fragment.arguments = args
|
||||
return fragment
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
package ani.dantotsu.profile.activity
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewGroup
|
||||
import android.widget.CheckBox
|
||||
import android.widget.ImageButton
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.api.Notification
|
||||
import ani.dantotsu.connections.anilist.api.NotificationType
|
||||
import ani.dantotsu.connections.anilist.api.NotificationType.Companion.fromFormattedString
|
||||
import ani.dantotsu.currContext
|
||||
import ani.dantotsu.databinding.ActivityFollowBinding
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.notifications.comment.CommentStore
|
||||
import ani.dantotsu.notifications.subscription.SubscriptionStore
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.util.Logger
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class NotificationActivity : AppCompatActivity() {
|
||||
private lateinit var binding: ActivityFollowBinding
|
||||
private lateinit var commentStore: List<CommentStore>
|
||||
private lateinit var subscriptionStore: List<SubscriptionStore>
|
||||
private var adapter: GroupieAdapter = GroupieAdapter()
|
||||
private var notificationList: List<Notification> = emptyList()
|
||||
val filters = ArrayList<String>()
|
||||
private var currentPage: Int = 1
|
||||
private var hasNextPage: Boolean = true
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
ThemeManager(this).applyTheme()
|
||||
initActivity(this)
|
||||
binding = ActivityFollowBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
binding.listTitle.text = getString(R.string.notifications)
|
||||
binding.listToolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin = statusBarHeight
|
||||
}
|
||||
binding.listFrameLayout.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin = navBarHeight
|
||||
}
|
||||
binding.listRecyclerView.adapter = adapter
|
||||
binding.listRecyclerView.layoutManager =
|
||||
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||
binding.followerGrid.visibility = ViewGroup.GONE
|
||||
binding.followerList.visibility = ViewGroup.GONE
|
||||
binding.listBack.setOnClickListener {
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
binding.listProgressBar.visibility = ViewGroup.VISIBLE
|
||||
commentStore = PrefManager.getNullableVal<List<CommentStore>>(
|
||||
PrefName.CommentNotificationStore,
|
||||
null
|
||||
) ?: listOf()
|
||||
subscriptionStore = PrefManager.getNullableVal<List<SubscriptionStore>>(
|
||||
PrefName.SubscriptionNotificationStore,
|
||||
null
|
||||
) ?: listOf()
|
||||
|
||||
binding.followFilterButton.setOnClickListener {
|
||||
val dialogView = LayoutInflater.from(currContext()).inflate(R.layout.custom_dialog_layout, null)
|
||||
val checkboxContainer = dialogView.findViewById<LinearLayout>(R.id.checkboxContainer)
|
||||
val tickAllButton = dialogView.findViewById<ImageButton>(R.id.toggleButton)
|
||||
val title = dialogView.findViewById<TextView>(R.id.scantitle)
|
||||
title.visibility = ViewGroup.GONE
|
||||
fun getToggleImageResource(container: ViewGroup): Int {
|
||||
var allChecked = true
|
||||
var allUnchecked = true
|
||||
|
||||
for (i in 0 until container.childCount) {
|
||||
val checkBox = container.getChildAt(i) as CheckBox
|
||||
if (!checkBox.isChecked) {
|
||||
allChecked = false
|
||||
} else {
|
||||
allUnchecked = false
|
||||
}
|
||||
}
|
||||
return when {
|
||||
allChecked -> R.drawable.untick_all_boxes
|
||||
allUnchecked -> R.drawable.tick_all_boxes
|
||||
else -> R.drawable.invert_all_boxes
|
||||
}
|
||||
}
|
||||
NotificationType.entries.forEach { notificationType ->
|
||||
val checkBox = CheckBox(currContext())
|
||||
checkBox.text = notificationType.toFormattedString()
|
||||
checkBox.isChecked = !filters.contains(notificationType.value.fromFormattedString())
|
||||
checkBox.setOnCheckedChangeListener { _, isChecked ->
|
||||
if (isChecked) {
|
||||
filters.remove(notificationType.value.fromFormattedString())
|
||||
} else {
|
||||
filters.add(notificationType.value.fromFormattedString())
|
||||
}
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
}
|
||||
checkboxContainer.addView(checkBox)
|
||||
}
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
tickAllButton.setOnClickListener {
|
||||
for (i in 0 until checkboxContainer.childCount) {
|
||||
val checkBox = checkboxContainer.getChildAt(i) as CheckBox
|
||||
checkBox.isChecked = !checkBox.isChecked
|
||||
}
|
||||
|
||||
tickAllButton.setImageResource(getToggleImageResource(checkboxContainer))
|
||||
}
|
||||
val alertD = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
alertD.setTitle("Filter")
|
||||
alertD.setView(dialogView)
|
||||
alertD.setPositiveButton("OK") { _, _ ->
|
||||
currentPage = 1
|
||||
hasNextPage = true
|
||||
adapter.clear()
|
||||
adapter.addAll(notificationList.filter { notification ->
|
||||
!filters.contains(notification.notificationType)
|
||||
}.map {
|
||||
NotificationItem(
|
||||
it,
|
||||
::onNotificationClick
|
||||
)
|
||||
})
|
||||
loadPage(-1) {
|
||||
binding.followRefresh.visibility = ViewGroup.GONE
|
||||
}
|
||||
}
|
||||
alertD.setNegativeButton("Cancel") { _, _ -> }
|
||||
val dialog = alertD.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
}
|
||||
|
||||
val activityId = intent.getIntExtra("activityId", -1)
|
||||
lifecycleScope.launch {
|
||||
loadPage(activityId) {
|
||||
binding.listProgressBar.visibility = ViewGroup.GONE
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
binding.listProgressBar.visibility = ViewGroup.GONE
|
||||
binding.listRecyclerView.setOnTouchListener { _, event ->
|
||||
if (event?.action == MotionEvent.ACTION_UP) {
|
||||
if (hasNextPage && !binding.listRecyclerView.canScrollVertically(1) && !binding.followRefresh.isVisible
|
||||
&& binding.listRecyclerView.adapter!!.itemCount != 0 &&
|
||||
(binding.listRecyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() == (binding.listRecyclerView.adapter!!.itemCount - 1)
|
||||
) {
|
||||
binding.followRefresh.visibility = ViewGroup.VISIBLE
|
||||
loadPage(-1) {
|
||||
binding.followRefresh.visibility = ViewGroup.GONE
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
binding.followSwipeRefresh.setOnRefreshListener {
|
||||
currentPage = 1
|
||||
hasNextPage = true
|
||||
adapter.clear()
|
||||
notificationList = emptyList()
|
||||
loadPage(-1) {
|
||||
binding.followSwipeRefresh.isRefreshing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadPage(activityId: Int, onFinish: () -> Unit = {}) {
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val resetNotification = activityId == -1
|
||||
val res = Anilist.query.getNotifications(
|
||||
Anilist.userid ?: PrefManager.getVal<String>(PrefName.AnilistUserId).toIntOrNull()
|
||||
?: 0, currentPage, resetNotification = resetNotification
|
||||
)
|
||||
withContext(Dispatchers.Main) {
|
||||
val newNotifications: MutableList<Notification> = mutableListOf()
|
||||
res?.data?.page?.notifications?.let { notifications ->
|
||||
Logger.log("Notifications: $notifications")
|
||||
newNotifications += if (activityId != -1) {
|
||||
notifications.filter { it.id == activityId }
|
||||
} else {
|
||||
notifications
|
||||
}.toMutableList()
|
||||
}
|
||||
if (activityId == -1) {
|
||||
val furthestTime = newNotifications.minOfOrNull { it.createdAt } ?: 0
|
||||
commentStore.forEach {
|
||||
if ((it.time > furthestTime * 1000L || !hasNextPage) && notificationList.none { notification ->
|
||||
notification.commentId == it.commentId && notification.createdAt == (it.time / 1000L).toInt()
|
||||
}) {
|
||||
val notification = Notification(
|
||||
it.type.toString(),
|
||||
System.currentTimeMillis().toInt(),
|
||||
commentId = it.commentId,
|
||||
notificationType = it.type.toString(),
|
||||
mediaId = it.mediaId,
|
||||
context = it.title + "\n" + it.content,
|
||||
createdAt = (it.time / 1000L).toInt(),
|
||||
)
|
||||
newNotifications += notification
|
||||
}
|
||||
}
|
||||
subscriptionStore.forEach {
|
||||
if ((it.time > furthestTime * 1000L || !hasNextPage) && notificationList.none { notification ->
|
||||
notification.mediaId == it.mediaId && notification.createdAt == (it.time / 1000L).toInt()
|
||||
}) {
|
||||
val notification = Notification(
|
||||
it.type,
|
||||
System.currentTimeMillis().toInt(),
|
||||
commentId = it.mediaId,
|
||||
mediaId = it.mediaId,
|
||||
notificationType = it.type,
|
||||
context = it.content,
|
||||
createdAt = (it.time / 1000L).toInt(),
|
||||
)
|
||||
newNotifications += notification
|
||||
}
|
||||
}
|
||||
newNotifications.sortByDescending { it.createdAt }
|
||||
}
|
||||
|
||||
notificationList += newNotifications
|
||||
adapter.addAll(newNotifications.filter { notification ->
|
||||
!filters.contains(notification.notificationType)
|
||||
}.map {
|
||||
NotificationItem(
|
||||
it,
|
||||
::onNotificationClick
|
||||
)
|
||||
})
|
||||
currentPage = res?.data?.page?.pageInfo?.currentPage?.plus(1) ?: 1
|
||||
hasNextPage = res?.data?.page?.pageInfo?.hasNextPage ?: false
|
||||
binding.followSwipeRefresh.isRefreshing = false
|
||||
onFinish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onNotificationClick(id: Int, optional: Int?, type: NotificationClickType) {
|
||||
when (type) {
|
||||
NotificationClickType.USER -> {
|
||||
ContextCompat.startActivity(
|
||||
this, Intent(this, ProfileActivity::class.java)
|
||||
.putExtra("userId", id), null
|
||||
)
|
||||
}
|
||||
|
||||
NotificationClickType.MEDIA -> {
|
||||
ContextCompat.startActivity(
|
||||
this, Intent(this, MediaDetailsActivity::class.java)
|
||||
.putExtra("mediaId", id), null
|
||||
)
|
||||
}
|
||||
|
||||
NotificationClickType.ACTIVITY -> {
|
||||
ContextCompat.startActivity(
|
||||
this, Intent(this, FeedActivity::class.java)
|
||||
.putExtra("activityId", id), null
|
||||
)
|
||||
}
|
||||
|
||||
NotificationClickType.COMMENT -> {
|
||||
ContextCompat.startActivity(
|
||||
this, Intent(this, MediaDetailsActivity::class.java)
|
||||
.putExtra("FRAGMENT_TO_LOAD", "COMMENTS")
|
||||
.putExtra("mediaId", id)
|
||||
.putExtra("commentId", optional ?: -1),
|
||||
null
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
NotificationClickType.UNDEFINED -> {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
enum class NotificationClickType {
|
||||
USER, MEDIA, ACTIVITY, COMMENT, UNDEFINED
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package ani.dantotsu.home.status
|
||||
package ani.dantotsu.profile.activity
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
@@ -14,9 +14,8 @@ import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.api.ActivityReply
|
||||
import ani.dantotsu.databinding.BottomSheetRecyclerBinding
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.activity.ActivityReplyItem
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.MarkdownCreatorActivity
|
||||
import ani.dantotsu.util.ActivityMarkdownCreator
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -49,7 +48,7 @@ class RepliesBottomDialog : BottomSheetDialogFragment() {
|
||||
binding.replyButton.setOnClickListener {
|
||||
ContextCompat.startActivity(
|
||||
context,
|
||||
Intent(context, MarkdownCreatorActivity::class.java)
|
||||
Intent(context, ActivityMarkdownCreator::class.java)
|
||||
.putExtra("type", "replyActivity")
|
||||
.putExtra("parentId", activityId),
|
||||
null
|
||||
@@ -58,29 +57,30 @@ class RepliesBottomDialog : BottomSheetDialogFragment() {
|
||||
activityId = requireArguments().getInt("activityId")
|
||||
loading(true)
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
val response = Anilist.query.getReplies(activityId)
|
||||
withContext(Dispatchers.Main) {
|
||||
loading(false)
|
||||
if (response != null) {
|
||||
replies.clear()
|
||||
replies.addAll(response.data.page.activityReplies)
|
||||
adapter.update(
|
||||
replies.map {
|
||||
ActivityReplyItem(
|
||||
it,
|
||||
requireActivity(),
|
||||
clickCallback = { int, _ ->
|
||||
onClick(int)
|
||||
}
|
||||
)
|
||||
loadData()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun loadData() {
|
||||
val response = Anilist.query.getReplies(activityId)
|
||||
withContext(Dispatchers.Main) {
|
||||
loading(false)
|
||||
if (response != null) {
|
||||
replies.clear()
|
||||
replies.addAll(response.data.page.activityReplies)
|
||||
adapter.update(
|
||||
replies.map {
|
||||
ActivityReplyItem(
|
||||
it, activityId, requireActivity(), adapter,
|
||||
) { i, _ ->
|
||||
onClick(i)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
snackString("Failed to load replies")
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
snackString("Failed to load replies")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private fun onClick(int: Int) {
|
||||
@@ -101,6 +101,14 @@ class RepliesBottomDialog : BottomSheetDialogFragment() {
|
||||
super.onDestroyView()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
loading(true)
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
loadData()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun newInstance(activityId: Int): RepliesBottomDialog {
|
||||
return RepliesBottomDialog().apply {
|
||||
@@ -0,0 +1,93 @@
|
||||
package ani.dantotsu.profile.notification
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.ViewGroup
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.databinding.ActivityNotificationBinding
|
||||
import ani.dantotsu.initActivity
|
||||
import ani.dantotsu.navBarHeight
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.profile.notification.NotificationFragment.Companion.NotificationType
|
||||
import nl.joery.animatedbottombar.AnimatedBottomBar
|
||||
|
||||
class NotificationActivity : AppCompatActivity() {
|
||||
lateinit var binding: ActivityNotificationBinding
|
||||
private var selected: Int = 0
|
||||
lateinit var navBar: AnimatedBottomBar
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
ThemeManager(this).applyTheme()
|
||||
initActivity(this)
|
||||
binding = ActivityNotificationBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
binding.notificationTitle.text = getString(R.string.notifications)
|
||||
binding.notificationToolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin = statusBarHeight
|
||||
}
|
||||
navBar = binding.notificationNavBar
|
||||
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
bottomMargin = navBarHeight
|
||||
}
|
||||
val tabs = listOf(
|
||||
Pair(R.drawable.ic_round_person_24, "User"),
|
||||
Pair(R.drawable.ic_round_movie_filter_24, "Media"),
|
||||
Pair(R.drawable.ic_round_notifications_active_24, "Subs"),
|
||||
Pair(R.drawable.ic_round_comment_24, "Comments")
|
||||
)
|
||||
tabs.forEach { (icon, title) -> navBar.addTab(navBar.createTab(icon, title)) }
|
||||
|
||||
binding.notificationBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
|
||||
val getOne = intent.getIntExtra("activityId", -1)
|
||||
if (getOne != -1) navBar.isVisible = false
|
||||
binding.notificationViewPager.adapter = ViewPagerAdapter(supportFragmentManager, lifecycle, getOne)
|
||||
binding.notificationViewPager.setCurrentItem(selected, false)
|
||||
navBar.selectTabAt(selected)
|
||||
navBar.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener {
|
||||
override fun onTabSelected(
|
||||
lastIndex: Int,
|
||||
lastTab: AnimatedBottomBar.Tab?,
|
||||
newIndex: Int,
|
||||
newTab: AnimatedBottomBar.Tab
|
||||
) {
|
||||
selected = newIndex
|
||||
binding.notificationViewPager.setCurrentItem(selected, true)
|
||||
}
|
||||
})
|
||||
binding.notificationViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
|
||||
override fun onPageSelected(position: Int) {
|
||||
super.onPageSelected(position)
|
||||
navBar.selectTabAt(position)
|
||||
}
|
||||
})
|
||||
}
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (this::navBar.isInitialized) {
|
||||
navBar.selectTabAt(selected)
|
||||
}
|
||||
}
|
||||
private class ViewPagerAdapter(
|
||||
fragmentManager: FragmentManager,
|
||||
lifecycle: Lifecycle,
|
||||
val id: Int = -1
|
||||
) : FragmentStateAdapter(fragmentManager, lifecycle) {
|
||||
override fun getItemCount(): Int = if (id != -1) 1 else 4
|
||||
|
||||
override fun createFragment(position: Int): Fragment = when (position) {
|
||||
0 -> NotificationFragment.newInstance(NotificationType.USER)
|
||||
1 -> NotificationFragment.newInstance(if (id != -1) NotificationType.ONE else NotificationType.MEDIA, id)
|
||||
2 -> NotificationFragment.newInstance(NotificationType.SUBSCRIPTION)
|
||||
3 -> NotificationFragment.newInstance(NotificationType.COMMENT)
|
||||
else -> NotificationFragment.newInstance(NotificationType.MEDIA)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package ani.dantotsu.profile.notification
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.anilist.Anilist
|
||||
import ani.dantotsu.connections.anilist.api.Notification
|
||||
import ani.dantotsu.databinding.FragmentNotificationsBinding
|
||||
import ani.dantotsu.media.MediaDetailsActivity
|
||||
import ani.dantotsu.notifications.comment.CommentStore
|
||||
import ani.dantotsu.notifications.subscription.SubscriptionStore
|
||||
import ani.dantotsu.profile.ProfileActivity
|
||||
import ani.dantotsu.profile.activity.FeedActivity
|
||||
import ani.dantotsu.setBaseline
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import com.xwray.groupie.GroupieAdapter
|
||||
import eu.kanade.tachiyomi.util.system.getSerializableCompat
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
|
||||
class NotificationFragment : Fragment() {
|
||||
private lateinit var type : NotificationType
|
||||
private var getID : Int = -1
|
||||
private lateinit var binding: FragmentNotificationsBinding
|
||||
private var adapter: GroupieAdapter = GroupieAdapter()
|
||||
private var currentPage = 1
|
||||
private var hasNextPage = false
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
binding = FragmentNotificationsBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
arguments?.let {
|
||||
getID = it.getInt("id")
|
||||
type = it.getSerializableCompat<NotificationType>("type") as NotificationType
|
||||
}
|
||||
binding.notificationRecyclerView.adapter = adapter
|
||||
binding.notificationRecyclerView.layoutManager = LinearLayoutManager(context)
|
||||
binding.notificationProgressBar.isVisible = true
|
||||
binding.emptyTextView.text = getString(R.string.no_notifications)
|
||||
lifecycleScope.launch {
|
||||
getList()
|
||||
if (adapter.itemCount == 0) {
|
||||
binding.emptyTextView.isVisible = true
|
||||
}
|
||||
binding.notificationProgressBar.isVisible = false
|
||||
}
|
||||
binding.notificationSwipeRefresh.setOnRefreshListener {
|
||||
lifecycleScope.launch {
|
||||
adapter.clear()
|
||||
currentPage = 1
|
||||
getList()
|
||||
binding.notificationSwipeRefresh.isRefreshing = false
|
||||
}
|
||||
}
|
||||
binding.notificationRecyclerView.addOnScrollListener(object :
|
||||
RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(recyclerView, dx, dy)
|
||||
if (shouldLoadMore()) {
|
||||
lifecycleScope.launch {
|
||||
binding.notificationRefresh.isVisible = true
|
||||
getList()
|
||||
binding.notificationRefresh.isVisible = false
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
private suspend fun getList() {
|
||||
val list = when (type) {
|
||||
NotificationType.ONE -> getNotificationsFiltered(false) { it.id == getID }
|
||||
NotificationType.MEDIA -> getNotificationsFiltered(type = true) { it.media != null }
|
||||
NotificationType.USER -> getNotificationsFiltered { it.media == null }
|
||||
NotificationType.SUBSCRIPTION -> getSubscriptions()
|
||||
NotificationType.COMMENT -> getComments()
|
||||
}
|
||||
adapter.addAll(list.map { NotificationItem(it, ::onClick) })
|
||||
}
|
||||
|
||||
private suspend fun getNotificationsFiltered(
|
||||
reset: Boolean = true,
|
||||
type: Boolean? = null,
|
||||
filter: (Notification) -> Boolean
|
||||
): List<Notification> {
|
||||
val userId =
|
||||
Anilist.userid ?: PrefManager.getVal<String>(PrefName.AnilistUserId).toIntOrNull() ?: 0
|
||||
val res = Anilist.query.getNotifications(userId, currentPage, reset, type)?.data?.page
|
||||
currentPage = res?.pageInfo?.currentPage?.plus(1) ?: 1
|
||||
hasNextPage = res?.pageInfo?.hasNextPage ?: false
|
||||
return res?.notifications?.filter(filter) ?: listOf()
|
||||
}
|
||||
|
||||
private fun getSubscriptions(): List<Notification> {
|
||||
val list = PrefManager.getNullableVal<List<SubscriptionStore>>(
|
||||
PrefName.SubscriptionNotificationStore,
|
||||
null
|
||||
) ?: listOf()
|
||||
return list.sortedByDescending { (it.time / 1000L).toInt() }
|
||||
.filter { it.image != null }.map {
|
||||
Notification(
|
||||
it.type,
|
||||
System.currentTimeMillis().toInt(),
|
||||
commentId = it.mediaId,
|
||||
mediaId = it.mediaId,
|
||||
notificationType = it.type,
|
||||
context = it.title + ": " + it.content,
|
||||
createdAt = (it.time / 1000L).toInt(),
|
||||
image = it.image,
|
||||
banner = it.banner ?: it.image
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getComments(): List<Notification> {
|
||||
val list = PrefManager.getNullableVal<List<CommentStore>>(
|
||||
PrefName.CommentNotificationStore,
|
||||
null
|
||||
) ?: listOf()
|
||||
return list
|
||||
.sortedByDescending { (it.time / 1000L).toInt() }
|
||||
.map {
|
||||
Notification(
|
||||
it.type.toString(),
|
||||
System.currentTimeMillis().toInt(),
|
||||
commentId = it.commentId,
|
||||
notificationType = it.type.toString(),
|
||||
mediaId = it.mediaId,
|
||||
context = it.title + "\n" + it.content,
|
||||
createdAt = (it.time / 1000L).toInt(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldLoadMore(): Boolean {
|
||||
val layoutManager =
|
||||
(binding.notificationRecyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
|
||||
val adapter = binding.notificationRecyclerView.adapter
|
||||
|
||||
return hasNextPage && !binding.notificationRefresh.isVisible && adapter?.itemCount != 0 &&
|
||||
layoutManager == (adapter!!.itemCount - 1) &&
|
||||
!binding.notificationRecyclerView.canScrollVertically(1)
|
||||
}
|
||||
|
||||
fun onClick(id: Int, optional: Int?, type: NotificationClickType) {
|
||||
val intent = when (type) {
|
||||
NotificationClickType.USER -> Intent(requireContext(), ProfileActivity::class.java).apply {
|
||||
putExtra("userId", id)
|
||||
}
|
||||
|
||||
NotificationClickType.MEDIA -> Intent(requireContext(), MediaDetailsActivity::class.java).apply {
|
||||
putExtra("mediaId", id)
|
||||
}
|
||||
|
||||
NotificationClickType.ACTIVITY -> Intent(requireContext(), FeedActivity::class.java).apply {
|
||||
putExtra("activityId", id)
|
||||
}
|
||||
|
||||
NotificationClickType.COMMENT -> Intent(requireContext(), MediaDetailsActivity::class.java).apply {
|
||||
putExtra("FRAGMENT_TO_LOAD", "COMMENTS")
|
||||
putExtra("mediaId", id)
|
||||
putExtra("commentId", optional ?: -1)
|
||||
}
|
||||
|
||||
NotificationClickType.UNDEFINED -> null
|
||||
}
|
||||
|
||||
intent?.let {
|
||||
ContextCompat.startActivity(requireContext(), it, null)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (this::binding.isInitialized) {
|
||||
binding.root.requestLayout()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
enum class NotificationClickType { USER, MEDIA, ACTIVITY, COMMENT, UNDEFINED }
|
||||
enum class NotificationType { MEDIA, USER, SUBSCRIPTION, COMMENT, ONE }
|
||||
|
||||
fun newInstance(type: NotificationType, id: Int = -1): NotificationFragment {
|
||||
return NotificationFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putSerializable("type", type)
|
||||
putInt("id", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package ani.dantotsu.profile.activity
|
||||
package ani.dantotsu.profile.notification
|
||||
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
@@ -8,7 +8,8 @@ import ani.dantotsu.connections.anilist.api.Notification
|
||||
import ani.dantotsu.connections.anilist.api.NotificationType
|
||||
import ani.dantotsu.databinding.ItemNotificationBinding
|
||||
import ani.dantotsu.loadImage
|
||||
import ani.dantotsu.profile.activity.NotificationActivity.Companion.NotificationClickType
|
||||
import ani.dantotsu.profile.notification.NotificationFragment.Companion.NotificationClickType
|
||||
import ani.dantotsu.profile.activity.ActivityItemBuilder
|
||||
import ani.dantotsu.setAnimation
|
||||
import ani.dantotsu.toPx
|
||||
import com.xwray.groupie.viewbinding.BindableItem
|
||||
@@ -32,12 +33,12 @@ class NotificationItem(
|
||||
return ItemNotificationBinding.bind(view)
|
||||
}
|
||||
|
||||
private fun image(user: Boolean = false, commentNotification: Boolean = false) {
|
||||
private fun image(user: Boolean = false, commentNotification: Boolean = false, newRelease: Boolean = false) {
|
||||
|
||||
val cover = if (user) notification.user?.bannerImage
|
||||
?: notification.user?.avatar?.medium else notification.media?.bannerImage
|
||||
?: notification.media?.coverImage?.large
|
||||
blurImage(binding.notificationBannerImage, cover)
|
||||
blurImage(binding.notificationBannerImage, if (newRelease) notification.banner else cover)
|
||||
|
||||
val defaultHeight = 153.toPx
|
||||
|
||||
@@ -64,7 +65,7 @@ class NotificationItem(
|
||||
binding.notificationCover.visibility = View.VISIBLE
|
||||
binding.notificationCoverUser.visibility = View.VISIBLE
|
||||
binding.notificationCoverUserContainer.visibility = View.GONE
|
||||
binding.notificationCover.loadImage(notification.media?.coverImage?.large)
|
||||
binding.notificationCover.loadImage(if (newRelease) notification.image else notification.media?.coverImage?.large)
|
||||
binding.notificationBannerImage.layoutParams.height = defaultHeight
|
||||
binding.notificationGradiant.layoutParams.height = defaultHeight
|
||||
(binding.notificationTextContainer.layoutParams as ViewGroup.MarginLayoutParams).marginStart =
|
||||
@@ -334,7 +335,7 @@ class NotificationItem(
|
||||
}
|
||||
|
||||
NotificationType.SUBSCRIPTION -> {
|
||||
image(user = true, commentNotification = true)
|
||||
image(newRelease = true)
|
||||
binding.notificationCoverUser.setOnClickListener {
|
||||
clickCallback(
|
||||
notification.mediaId ?: 0, null, NotificationClickType.MEDIA
|
||||
@@ -35,6 +35,7 @@ import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.tabs.TabLayout
|
||||
import com.google.android.material.tabs.TabLayoutMediator
|
||||
import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager
|
||||
@@ -43,6 +44,7 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import uy.kohesive.injekt.injectLazy
|
||||
import java.util.Locale
|
||||
|
||||
class ExtensionsActivity : AppCompatActivity() {
|
||||
lateinit var binding: ActivityExtensionsBinding
|
||||
@@ -173,26 +175,24 @@ class ExtensionsActivity : AppCompatActivity() {
|
||||
initActivity(this)
|
||||
binding.languageselect.setOnClickListener {
|
||||
val languageOptions =
|
||||
LanguageMapper.Companion.Language.entries.map { it.name }.toTypedArray()
|
||||
val builder = AlertDialog.Builder(currContext(), R.style.MyPopup)
|
||||
LanguageMapper.Companion.Language.entries.map { entry ->
|
||||
entry.name.lowercase().replace("_", " ")
|
||||
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() }
|
||||
}.toTypedArray()
|
||||
val listOrder: String = PrefManager.getVal(PrefName.LangSort)
|
||||
val index = LanguageMapper.Companion.Language.entries.toTypedArray()
|
||||
.indexOfFirst { it.code == listOrder }
|
||||
builder.setTitle("Language")
|
||||
builder.setSingleChoiceItems(languageOptions, index) { dialog, i ->
|
||||
PrefManager.setVal(
|
||||
PrefName.LangSort,
|
||||
LanguageMapper.Companion.Language.entries[i].code
|
||||
)
|
||||
val currentFragment =
|
||||
supportFragmentManager.findFragmentByTag("f${viewPager.currentItem}")
|
||||
if (currentFragment is SearchQueryHandler) {
|
||||
currentFragment.notifyDataChanged()
|
||||
customAlertDialog().apply {
|
||||
setTitle("Language")
|
||||
singleChoiceItems(languageOptions, index) { selected ->
|
||||
PrefManager.setVal(PrefName.LangSort, LanguageMapper.Companion.Language.entries[selected].code)
|
||||
val currentFragment = supportFragmentManager.findFragmentByTag("f${viewPager.currentItem}")
|
||||
if (currentFragment is SearchQueryHandler) {
|
||||
currentFragment.notifyDataChanged()
|
||||
}
|
||||
}
|
||||
dialog.dismiss()
|
||||
show()
|
||||
}
|
||||
val dialog = builder.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
}
|
||||
binding.settingsContainer.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||
topMargin = statusBarHeight
|
||||
@@ -243,10 +243,10 @@ class ExtensionsActivity : AppCompatActivity() {
|
||||
)
|
||||
view.repositoryItem.text = item.removePrefix("https://raw.githubusercontent.com")
|
||||
view.repositoryItem.setOnClickListener {
|
||||
AlertDialog.Builder(this@ExtensionsActivity, R.style.MyPopup)
|
||||
.setTitle(R.string.rem_repository)
|
||||
.setMessage(item)
|
||||
.setPositiveButton(getString(R.string.ok)) { dialog, _ ->
|
||||
customAlertDialog().apply {
|
||||
setTitle(R.string.rem_repository)
|
||||
setMessage(item)
|
||||
setPosButton(R.string.ok) {
|
||||
val repos = PrefManager.getVal<Set<String>>(prefName).minus(item)
|
||||
PrefManager.setVal(prefName, repos)
|
||||
repoInventory.removeView(view.root)
|
||||
@@ -263,13 +263,10 @@ class ExtensionsActivity : AppCompatActivity() {
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
dialog.dismiss()
|
||||
}
|
||||
.setNegativeButton(getString(R.string.cancel)) { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
}
|
||||
.create()
|
||||
.show()
|
||||
setNegButton(R.string.cancel)
|
||||
show()
|
||||
}
|
||||
}
|
||||
view.repositoryItem.setOnLongClickListener {
|
||||
it.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||
@@ -320,20 +317,18 @@ class ExtensionsActivity : AppCompatActivity() {
|
||||
dialogView.repoInventory.apply {
|
||||
getSavedRepositories(this, type)
|
||||
}
|
||||
val alertDialog = AlertDialog.Builder(this@ExtensionsActivity, R.style.MyPopup)
|
||||
.setTitle(R.string.edit_repositories)
|
||||
.setView(dialogView.root)
|
||||
.setPositiveButton(getString(R.string.add)) { _, _ ->
|
||||
if (!dialogView.repositoryTextBox.text.isNullOrBlank())
|
||||
processUserInput(dialogView.repositoryTextBox.text.toString(), type)
|
||||
}
|
||||
.setNegativeButton(getString(R.string.close)) { dialog, _ ->
|
||||
dialog.dismiss()
|
||||
}
|
||||
.create()
|
||||
processEditorAction(dialogView.repositoryTextBox, type)
|
||||
alertDialog.show()
|
||||
alertDialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(R.string.edit_repositories)
|
||||
setCustomView(dialogView.root)
|
||||
setPosButton(R.string.add) {
|
||||
if (!dialogView.repositoryTextBox.text.isNullOrBlank()) {
|
||||
processUserInput(dialogView.repositoryTextBox.text.toString(), type)
|
||||
}
|
||||
}
|
||||
setNegButton(R.string.close)
|
||||
show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,11 @@ class FAQActivity : AppCompatActivity() {
|
||||
currContext()?.getString(R.string.question_5) ?: "",
|
||||
currContext()?.getString(R.string.answer_5) ?: ""
|
||||
),
|
||||
Triple(
|
||||
R.drawable.ic_anilist,
|
||||
currContext()?.getString(R.string.question_18) ?: "",
|
||||
currContext()?.getString(R.string.answer_18) ?: ""
|
||||
),
|
||||
Triple(
|
||||
R.drawable.ic_anilist,
|
||||
currContext()?.getString(R.string.question_6) ?: "",
|
||||
@@ -60,6 +65,11 @@ class FAQActivity : AppCompatActivity() {
|
||||
currContext()?.getString(R.string.question_7) ?: "",
|
||||
currContext()?.getString(R.string.answer_7) ?: ""
|
||||
),
|
||||
Triple(
|
||||
R.drawable.ic_round_magnet_24,
|
||||
currContext()?.getString(R.string.question_19) ?: "",
|
||||
currContext()?.getString(R.string.answer_19) ?: ""
|
||||
),
|
||||
Triple(
|
||||
R.drawable.ic_round_lock_open_24,
|
||||
currContext()?.getString(R.string.question_9) ?: "",
|
||||
|
||||
@@ -7,7 +7,6 @@ import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import ani.dantotsu.BottomSheetDialogFragment
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.github.Forks
|
||||
import ani.dantotsu.databinding.BottomSheetDevelopersBinding
|
||||
|
||||
class ForksDialogFragment : BottomSheetDialogFragment() {
|
||||
@@ -26,7 +25,16 @@ class ForksDialogFragment : BottomSheetDialogFragment() {
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
binding.devsTitle.setText(R.string.forks)
|
||||
binding.devsRecyclerView.adapter = DevelopersAdapter(Forks().getForks())
|
||||
binding.devsRecyclerView.adapter = DevelopersAdapter(
|
||||
arrayOf(
|
||||
Developer(
|
||||
"Awery",
|
||||
"https://avatars.githubusercontent.com/u/92123190?v=4",
|
||||
"MrBoomDeveloper",
|
||||
"https://github.com/MrBoomDeveloper/Awery"
|
||||
),
|
||||
)
|
||||
)
|
||||
binding.devsRecyclerView.layoutManager = LinearLayoutManager(requireContext())
|
||||
}
|
||||
|
||||
|
||||
@@ -25,13 +25,15 @@ import androidx.viewpager2.widget.ViewPager2
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.crashlytics.CrashlyticsInterface
|
||||
import ani.dantotsu.databinding.FragmentExtensionsBinding
|
||||
import ani.dantotsu.others.LanguageMapper
|
||||
import ani.dantotsu.others.LanguageMapper.Companion.getLanguageName
|
||||
import ani.dantotsu.parsers.AnimeSources
|
||||
import ani.dantotsu.settings.extensionprefs.AnimeSourcePreferencesFragment
|
||||
import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
|
||||
import com.google.android.material.tabs.TabLayout
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
|
||||
@@ -72,16 +74,15 @@ class InstalledAnimeExtensionsFragment : Fragment(), SearchQueryHandler {
|
||||
if (allSettings.isNotEmpty()) {
|
||||
var selectedSetting = allSettings[0]
|
||||
if (allSettings.size > 1) {
|
||||
val names = allSettings.map { LanguageMapper.getLanguageName(it.lang) }
|
||||
val names = allSettings.map { getLanguageName(it.lang) }
|
||||
.toTypedArray()
|
||||
var selectedIndex = 0
|
||||
val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
.setTitle("Select a Source")
|
||||
.setSingleChoiceItems(names, selectedIndex) { dialog, which ->
|
||||
requireContext().customAlertDialog().apply {
|
||||
setTitle("Select a Source")
|
||||
singleChoiceItems(names, selectedIndex) { which ->
|
||||
itemSelected = true
|
||||
selectedIndex = which
|
||||
selectedSetting = allSettings[selectedIndex]
|
||||
dialog.dismiss()
|
||||
|
||||
val fragment =
|
||||
AnimeSourcePreferencesFragment().getInstance(selectedSetting.id) {
|
||||
@@ -93,13 +94,13 @@ class InstalledAnimeExtensionsFragment : Fragment(), SearchQueryHandler {
|
||||
.addToBackStack(null)
|
||||
.commit()
|
||||
}
|
||||
.setOnDismissListener {
|
||||
onDismiss {
|
||||
if (!itemSelected) {
|
||||
changeUIVisibility(true)
|
||||
}
|
||||
}
|
||||
.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
// If there's only one setting, proceed with the fragment transaction
|
||||
val fragment =
|
||||
@@ -295,7 +296,7 @@ class InstalledAnimeExtensionsFragment : Fragment(), SearchQueryHandler {
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
val extension = getItem(position)
|
||||
val nsfw = if (extension.isNsfw) "(18+)" else ""
|
||||
val lang = LanguageMapper.getLanguageName(extension.lang)
|
||||
val lang = getLanguageName(extension.lang)
|
||||
holder.extensionNameTextView.text = extension.name
|
||||
val versionText = "$lang ${extension.versionName} $nsfw"
|
||||
holder.extensionVersionTextView.text = versionText
|
||||
|
||||
@@ -34,6 +34,7 @@ import ani.dantotsu.settings.saving.PrefManager
|
||||
import ani.dantotsu.settings.saving.PrefName
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.tabs.TabLayout
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import eu.kanade.tachiyomi.data.notification.Notifications
|
||||
@@ -74,13 +75,12 @@ class InstalledMangaExtensionsFragment : Fragment(), SearchQueryHandler {
|
||||
val names = allSettings.map { LanguageMapper.getLanguageName(it.lang) }
|
||||
.toTypedArray()
|
||||
var selectedIndex = 0
|
||||
val dialog = AlertDialog.Builder(requireContext(), R.style.MyPopup)
|
||||
.setTitle("Select a Source")
|
||||
.setSingleChoiceItems(names, selectedIndex) { dialog, which ->
|
||||
requireContext().customAlertDialog().apply {
|
||||
setTitle("Select a Source")
|
||||
singleChoiceItems(names, selectedIndex) { which ->
|
||||
itemSelected = true
|
||||
selectedIndex = which
|
||||
selectedSetting = allSettings[selectedIndex]
|
||||
dialog.dismiss()
|
||||
|
||||
// Move the fragment transaction here
|
||||
val fragment =
|
||||
@@ -93,13 +93,13 @@ class InstalledMangaExtensionsFragment : Fragment(), SearchQueryHandler {
|
||||
.addToBackStack(null)
|
||||
.commit()
|
||||
}
|
||||
.setOnDismissListener {
|
||||
onDismiss {
|
||||
if (!itemSelected) {
|
||||
changeUIVisibility(true)
|
||||
}
|
||||
}
|
||||
.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
show()
|
||||
}
|
||||
} else {
|
||||
// If there's only one setting, proceed with the fragment transaction
|
||||
val fragment =
|
||||
|
||||
@@ -6,6 +6,7 @@ import androidx.core.app.NotificationCompat
|
||||
import ani.dantotsu.R
|
||||
import ani.dantotsu.connections.crashlytics.CrashlyticsInterface
|
||||
import ani.dantotsu.snackString
|
||||
import ani.dantotsu.util.Logger
|
||||
import eu.kanade.tachiyomi.data.notification.Notifications
|
||||
import eu.kanade.tachiyomi.extension.InstallStep
|
||||
import uy.kohesive.injekt.Injekt
|
||||
@@ -30,6 +31,7 @@ class InstallerSteps(
|
||||
|
||||
fun onError(error: Throwable, extra: () -> Unit) {
|
||||
Injekt.get<CrashlyticsInterface>().logException(error)
|
||||
Logger.log(error)
|
||||
val builder = NotificationCompat.Builder(
|
||||
context,
|
||||
Notifications.CHANNEL_DOWNLOADER_ERROR
|
||||
|
||||
@@ -29,6 +29,7 @@ import ani.dantotsu.snackString
|
||||
import ani.dantotsu.statusBarHeight
|
||||
import ani.dantotsu.themes.ThemeManager
|
||||
import ani.dantotsu.toast
|
||||
import ani.dantotsu.util.customAlertDialog
|
||||
import com.google.android.material.slider.Slider.OnChangeListener
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -100,20 +101,19 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
R.string.default_playback_speed,
|
||||
speedsName[PrefManager.getVal(PrefName.DefaultSpeed)]
|
||||
)
|
||||
val speedDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.default_speed))
|
||||
binding.playerSettingsSpeed.setOnClickListener {
|
||||
val dialog =
|
||||
speedDialog.setSingleChoiceItems(
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.default_speed))
|
||||
singleChoiceItems(
|
||||
speedsName,
|
||||
PrefManager.getVal(PrefName.DefaultSpeed)
|
||||
) { dialog, i ->
|
||||
) { i ->
|
||||
PrefManager.setVal(PrefName.DefaultSpeed, i)
|
||||
binding.playerSettingsSpeed.text =
|
||||
getString(R.string.default_playback_speed, speedsName[i])
|
||||
dialog.dismiss()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
binding.playerSettingsCursedSpeeds.isChecked = PrefManager.getVal(PrefName.CursedSpeeds)
|
||||
@@ -278,17 +278,17 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
val resizeModes = arrayOf("Original", "Zoom", "Stretch")
|
||||
val resizeDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.default_resize_mode))
|
||||
binding.playerResizeMode.setOnClickListener {
|
||||
val dialog = resizeDialog.setSingleChoiceItems(
|
||||
resizeModes,
|
||||
PrefManager.getVal<Int>(PrefName.Resize)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.Resize, count)
|
||||
dialog.dismiss()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.default_resize_mode))
|
||||
singleChoiceItems(
|
||||
resizeModes,
|
||||
PrefManager.getVal<Int>(PrefName.Resize)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.Resize, count)
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleSubOptions(isChecked: Boolean) {
|
||||
@@ -387,18 +387,18 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
"Blue",
|
||||
"Magenta"
|
||||
)
|
||||
val primaryColorDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.primary_sub_color))
|
||||
binding.videoSubColorPrimary.setOnClickListener {
|
||||
val dialog = primaryColorDialog.setSingleChoiceItems(
|
||||
colorsPrimary,
|
||||
PrefManager.getVal(PrefName.PrimaryColor)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.PrimaryColor, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.primary_sub_color))
|
||||
singleChoiceItems(
|
||||
colorsPrimary,
|
||||
PrefManager.getVal(PrefName.PrimaryColor)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.PrimaryColor, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
val colorsSecondary = arrayOf(
|
||||
"Black",
|
||||
@@ -414,32 +414,32 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
"Magenta",
|
||||
"Transparent"
|
||||
)
|
||||
val secondaryColorDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.outline_sub_color))
|
||||
binding.videoSubColorSecondary.setOnClickListener {
|
||||
val dialog = secondaryColorDialog.setSingleChoiceItems(
|
||||
colorsSecondary,
|
||||
PrefManager.getVal(PrefName.SecondaryColor)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.SecondaryColor, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.outline_sub_color))
|
||||
singleChoiceItems(
|
||||
colorsSecondary,
|
||||
PrefManager.getVal(PrefName.SecondaryColor)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.SecondaryColor, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
val typesOutline = arrayOf("Outline", "Shine", "Drop Shadow", "None")
|
||||
val outlineDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.outline_type))
|
||||
binding.videoSubOutline.setOnClickListener {
|
||||
val dialog = outlineDialog.setSingleChoiceItems(
|
||||
typesOutline,
|
||||
PrefManager.getVal(PrefName.Outline)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.Outline, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.outline_type))
|
||||
singleChoiceItems(
|
||||
typesOutline,
|
||||
PrefManager.getVal(PrefName.Outline)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.Outline, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
val colorsSubBackground = arrayOf(
|
||||
"Transparent",
|
||||
@@ -455,18 +455,18 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
"Blue",
|
||||
"Magenta"
|
||||
)
|
||||
val subBackgroundDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.sub_background_color_select))
|
||||
binding.videoSubColorBackground.setOnClickListener {
|
||||
val dialog = subBackgroundDialog.setSingleChoiceItems(
|
||||
colorsSubBackground,
|
||||
PrefManager.getVal(PrefName.SubBackground)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.SubBackground, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.sub_background_color_select))
|
||||
singleChoiceItems(
|
||||
colorsSubBackground,
|
||||
PrefManager.getVal(PrefName.SubBackground)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.SubBackground, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
val colorsSubWindow = arrayOf(
|
||||
@@ -483,18 +483,18 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
"Blue",
|
||||
"Magenta"
|
||||
)
|
||||
val subWindowDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.sub_window_color_select))
|
||||
binding.videoSubColorWindow.setOnClickListener {
|
||||
val dialog = subWindowDialog.setSingleChoiceItems(
|
||||
colorsSubWindow,
|
||||
PrefManager.getVal(PrefName.SubWindow)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.SubWindow, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.sub_window_color_select))
|
||||
singleChoiceItems(
|
||||
colorsSubWindow,
|
||||
PrefManager.getVal(PrefName.SubWindow)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.SubWindow, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
|
||||
binding.videoSubAlpha.value = PrefManager.getVal(PrefName.SubAlpha)
|
||||
@@ -514,18 +514,18 @@ class PlayerSettingsActivity : AppCompatActivity() {
|
||||
"Levenim MT Bold",
|
||||
"Blocky"
|
||||
)
|
||||
val fontDialog = AlertDialog.Builder(this, R.style.MyPopup)
|
||||
.setTitle(getString(R.string.subtitle_font))
|
||||
binding.videoSubFont.setOnClickListener {
|
||||
val dialog = fontDialog.setSingleChoiceItems(
|
||||
fonts,
|
||||
PrefManager.getVal(PrefName.Font)
|
||||
) { dialog, count ->
|
||||
PrefManager.setVal(PrefName.Font, count)
|
||||
dialog.dismiss()
|
||||
updateSubPreview()
|
||||
}.show()
|
||||
dialog.window?.setDimAmount(0.8f)
|
||||
customAlertDialog().apply {
|
||||
setTitle(getString(R.string.subtitle_font))
|
||||
singleChoiceItems(
|
||||
fonts,
|
||||
PrefManager.getVal(PrefName.Font)
|
||||
) { count ->
|
||||
PrefManager.setVal(PrefName.Font, count)
|
||||
updateSubPreview()
|
||||
}
|
||||
show()
|
||||
}
|
||||
}
|
||||
binding.subtitleFontSize.setText(PrefManager.getVal<Int>(PrefName.FontSize).toString())
|
||||
binding.subtitleFontSize.setOnEditorActionListener { _, actionId, _ ->
|
||||
|
||||
@@ -147,6 +147,7 @@ class SettingsAccountActivity : AppCompatActivity() {
|
||||
"online" -> R.drawable.discord_status_online
|
||||
"idle" -> R.drawable.discord_status_idle
|
||||
"dnd" -> R.drawable.discord_status_dnd
|
||||
"invisible" -> R.drawable.discord_status_invisible
|
||||
else -> R.drawable.discord_status_online
|
||||
}
|
||||
settingsImageSwitcher.setImageResource(initialStatus)
|
||||
@@ -167,6 +168,11 @@ class SettingsAccountActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
R.drawable.discord_status_dnd -> {
|
||||
status = "invisible"
|
||||
R.drawable.discord_status_invisible
|
||||
}
|
||||
|
||||
R.drawable.discord_status_invisible -> {
|
||||
status = "online"
|
||||
R.drawable.discord_status_online
|
||||
}
|
||||
@@ -198,4 +204,4 @@ class SettingsAccountActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user