mirror of
https://github.com/recloudstream/cloudstream.git
synced 2026-10-23 18:24:20 +00:00
Compare commits
7 commits
master
...
fixobserve
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
519bea8117 |
||
|
|
62ed338c1d |
||
|
|
6fcb99489b |
||
|
|
1a77d2057d |
||
|
|
80acc5a6a2 |
||
|
|
35171b4a5d |
||
|
|
bcf04cfc09 |
603 changed files with 8289 additions and 47986 deletions
BIN
.github/images/download-cloudstream-pre.png
vendored
BIN
.github/images/download-cloudstream-pre.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 21 KiB |
3
.github/workflows/build_to_archive.yml
vendored
3
.github/workflows/build_to_archive.yml
vendored
|
|
@ -71,10 +71,7 @@ jobs:
|
||||||
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
|
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
|
||||||
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
|
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
|
||||||
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
|
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
|
||||||
TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
|
|
||||||
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
|
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
|
||||||
MAL_KEY: ${{ secrets.MAL_KEY }}
|
|
||||||
ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
|
|
||||||
|
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v6
|
||||||
with:
|
with:
|
||||||
|
|
|
||||||
105
.github/workflows/instrumented-tests.yml
vendored
105
.github/workflows/instrumented-tests.yml
vendored
|
|
@ -1,105 +0,0 @@
|
||||||
name: Instrumented Tests
|
|
||||||
|
|
||||||
on:
|
|
||||||
issue_comment:
|
|
||||||
types: [created]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
pull-requests: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
instrumented-tests:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: |
|
|
||||||
github.event.issue.pull_request &&
|
|
||||||
github.event.comment.body == '/run-tests'
|
|
||||||
steps:
|
|
||||||
- name: Check permission
|
|
||||||
uses: actions/github-script@v9
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
const login = context.payload.comment.user.login;
|
|
||||||
const association = context.payload.comment.author_association;
|
|
||||||
const allowed = ['OWNER', 'MEMBER'];
|
|
||||||
|
|
||||||
const isAllowed =
|
|
||||||
login === 'Luna712' ||
|
|
||||||
allowed.includes(association);
|
|
||||||
|
|
||||||
if (!isAllowed) {
|
|
||||||
core.setFailed(`User ${login} is not permitted to trigger this workflow.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
ref: refs/pull/${{ github.event.issue.number }}/head
|
|
||||||
|
|
||||||
- name: Post started comment
|
|
||||||
uses: actions/github-script@v9
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
github.rest.issues.createComment({
|
|
||||||
issue_number: context.issue.number,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
repo: context.repo.repo,
|
|
||||||
body: 'Instrumented tests are running. [View live progress](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
|
|
||||||
})
|
|
||||||
|
|
||||||
- name: Set up JDK 17
|
|
||||||
uses: actions/setup-java@v5
|
|
||||||
with:
|
|
||||||
distribution: temurin
|
|
||||||
java-version: 17
|
|
||||||
|
|
||||||
- name: Grant execute permission for gradlew
|
|
||||||
run: chmod +x gradlew
|
|
||||||
|
|
||||||
- name: Setup Gradle
|
|
||||||
uses: gradle/actions/setup-gradle@v5
|
|
||||||
with:
|
|
||||||
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
|
|
||||||
cache-read-only: false
|
|
||||||
|
|
||||||
- name: Get target SDK
|
|
||||||
id: sdk
|
|
||||||
run: |
|
|
||||||
TARGET_SDK=$(grep 'targetSdk' gradle/libs.versions.toml | grep -o '[0-9]\+' | head -1)
|
|
||||||
echo "version=$TARGET_SDK" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Enable KVM
|
|
||||||
run: |
|
|
||||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
|
||||||
sudo udevadm control --reload-rules
|
|
||||||
sudo udevadm trigger --name-match=kvm
|
|
||||||
|
|
||||||
- name: Run Instrumented Tests
|
|
||||||
id: tests
|
|
||||||
uses: reactivecircus/android-emulator-runner@v2
|
|
||||||
with:
|
|
||||||
api-level: ${{ steps.sdk.outputs.version }}
|
|
||||||
arch: x86_64
|
|
||||||
profile: Nexus 6
|
|
||||||
script: ./gradlew connectedPrereleaseDebugAndroidTest
|
|
||||||
|
|
||||||
- name: Upload Test Results
|
|
||||||
if: always()
|
|
||||||
uses: actions/upload-artifact@v7
|
|
||||||
with:
|
|
||||||
name: instrumented-test-results
|
|
||||||
path: '**/build/reports/androidTests/'
|
|
||||||
|
|
||||||
- name: Post finished comment
|
|
||||||
if: always()
|
|
||||||
uses: actions/github-script@v9
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
const success = '${{ steps.tests.outcome }}' === 'success';
|
|
||||||
github.rest.issues.createComment({
|
|
||||||
issue_number: context.issue.number,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
repo: context.repo.repo,
|
|
||||||
body: success
|
|
||||||
? 'Instrumented tests passed. [View results](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
|
|
||||||
: 'Instrumented tests failed. [View results](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
|
|
||||||
})
|
|
||||||
98
.github/workflows/issue_action.yml
vendored
Normal file
98
.github/workflows/issue_action.yml
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
name: Issue automatic actions
|
||||||
|
|
||||||
|
on:
|
||||||
|
issues:
|
||||||
|
types: [opened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
issues: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
issue-moderator:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Generate access token
|
||||||
|
id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v2
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_KEY }}
|
||||||
|
|
||||||
|
- name: Similarity analysis
|
||||||
|
id: similarity
|
||||||
|
uses: actions-cool/issues-similarity-analysis@v1
|
||||||
|
with:
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
filter-threshold: 0.60
|
||||||
|
title-excludes: ''
|
||||||
|
comment-title: |
|
||||||
|
### Your issue looks similar to these issues:
|
||||||
|
Please close if duplicate.
|
||||||
|
comment-body: '${index}. ${similarity} #${number}'
|
||||||
|
|
||||||
|
- name: Label if possible duplicate
|
||||||
|
if: steps.similarity.outputs.similar-issues-found =='true'
|
||||||
|
uses: actions/github-script@v9
|
||||||
|
with:
|
||||||
|
github-token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
script: |
|
||||||
|
github.rest.issues.addLabels({
|
||||||
|
issue_number: context.issue.number,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
labels: ["possible duplicate"]
|
||||||
|
})
|
||||||
|
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Automatically close issues that dont follow the issue template
|
||||||
|
uses: lucasbento/auto-close-issues@v1.0.2
|
||||||
|
with:
|
||||||
|
github-token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
issue-close-message: |
|
||||||
|
@${issue.user.login}: hello! :wave:
|
||||||
|
This issue is being automatically closed because it does not follow the issue template."
|
||||||
|
closed-issues-label: "invalid"
|
||||||
|
|
||||||
|
- name: Check if issue mentions a provider
|
||||||
|
id: provider_check
|
||||||
|
env:
|
||||||
|
GH_TEXT: "${{ github.event.issue.title }} ${{ github.event.issue.body }}"
|
||||||
|
run: |
|
||||||
|
wget --output-document check_issue.py "https://raw.githubusercontent.com/recloudstream/.github/master/.github/check_issue.py"
|
||||||
|
pip3 install httpx
|
||||||
|
RES="$(python3 ./check_issue.py)"
|
||||||
|
echo "name=${RES}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Comment if issue mentions a provider
|
||||||
|
if: steps.provider_check.outputs.name != 'none'
|
||||||
|
uses: actions-cool/issues-helper@v3
|
||||||
|
with:
|
||||||
|
actions: 'create-comment'
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
body: |
|
||||||
|
Hello ${{ github.event.issue.user.login }}.
|
||||||
|
Please do not report any provider bugs here. This repository does not contain any providers. Please find the appropriate repository and report your issue there or join the [discord](https://discord.gg/5Hus6fM).
|
||||||
|
|
||||||
|
Found provider name: `${{ steps.provider_check.outputs.name }}`
|
||||||
|
|
||||||
|
- name: Label if mentions provider
|
||||||
|
if: steps.provider_check.outputs.name != 'none'
|
||||||
|
uses: actions/github-script@v9
|
||||||
|
with:
|
||||||
|
github-token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
script: |
|
||||||
|
github.rest.issues.addLabels({
|
||||||
|
issue_number: context.issue.number,
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
labels: ["possible provider issue"]
|
||||||
|
})
|
||||||
|
|
||||||
|
- name: Add eyes reaction to all issues
|
||||||
|
uses: actions-cool/emoji-helper@v1.0.0
|
||||||
|
with:
|
||||||
|
type: 'issue'
|
||||||
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
|
emoji: 'eyes'
|
||||||
3
.github/workflows/prerelease.yml
vendored
3
.github/workflows/prerelease.yml
vendored
|
|
@ -62,10 +62,7 @@ jobs:
|
||||||
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
|
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
|
||||||
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
|
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
|
||||||
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
|
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
|
||||||
TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
|
|
||||||
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
|
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
|
||||||
MAL_KEY: ${{ secrets.MAL_KEY }}
|
|
||||||
ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
|
|
||||||
|
|
||||||
- name: Create pre-release
|
- name: Create pre-release
|
||||||
uses: marvinpinto/action-automatic-releases@latest
|
uses: marvinpinto/action-automatic-releases@latest
|
||||||
|
|
|
||||||
7
.github/workflows/pull_request.yml
vendored
7
.github/workflows/pull_request.yml
vendored
|
|
@ -26,13 +26,8 @@ jobs:
|
||||||
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
|
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
|
||||||
cache-read-only: false
|
cache-read-only: false
|
||||||
|
|
||||||
- name: Ensure binary compatibility
|
|
||||||
# This is to ensure that your code is backwards compatible.
|
|
||||||
# If this fails you need to add a @Prerelease annotation to new code.
|
|
||||||
run: ./gradlew library:checkKotlinAbi
|
|
||||||
|
|
||||||
- name: Run Gradle
|
- name: Run Gradle
|
||||||
run: ./gradlew assemblePrereleaseDebug lint check
|
run: ./gradlew assemblePrereleaseDebug lint
|
||||||
|
|
||||||
- name: Upload Artifact
|
- name: Upload Artifact
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
|
|
|
||||||
21
COMPOSE.md
21
COMPOSE.md
|
|
@ -1,21 +0,0 @@
|
||||||
# Migration guide to Compose
|
|
||||||
|
|
||||||
### 1. MVI instead of MVVM
|
|
||||||
|
|
||||||
The current design of CloudStream loosely uses the MVVM architecture.
|
|
||||||
|
|
||||||
This means that the UI invokes the viewmodel with function calls, and it responds with LiveData fields that are observed. While this has worked, it generates a lot of boilerplate and has created some friction.
|
|
||||||
|
|
||||||
To make it easier to work with Compose, the new architecture will be based on MVI. In short this means that the viewmodel exposes a singular immutable class that is observed, and receives all UI events with a singular event that is a sealed class. All the UI should be able to be recreated based on this singular state class, and all interactions should be able to be replayed using only the event callback.
|
|
||||||
|
|
||||||
For a more detailed overview, see: https://www.youtube.com/watch?v=b2z1jvD4VMQ
|
|
||||||
|
|
||||||
This is part of the effort to make CloudStream cross platform, as it allows us to decouple UI and logic.
|
|
||||||
|
|
||||||
### 2. KMP-compatible libraries
|
|
||||||
|
|
||||||
We plan to leverage Kotlin's KMP project to compile our code to different architectures. However, this requires us to only use KMP-compatible libraries, no Java. Therefore any pull requests must ensure that they use KMP-compatible libraries only.
|
|
||||||
|
|
||||||
### 3. UI Changes
|
|
||||||
|
|
||||||
While migrating to the new compose UI, you also have the opportunity to change the UI. However, this should only be to freshen up the UI, not completely redesign it. It is also important to stress that this process should not lose any features of the old UI, and be very conservative with adding new features.
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
# CloudStream
|
# CloudStream
|
||||||
|
|
||||||
**⚠️ Warning: By default, this app doesn't provide any video sources; you have to install extensions to add functionality to the app.**
|
**⚠️ Warning: By default, this app doesn't provide any video sources; you have to install extensions to add functionality to the app.**
|
||||||
<p align="left"><a href="https://github.com/recloudstream/cloudstream/releases/download/pre-release/app-prerelease-release.apk"><img src=".github/images/download-cloudstream-pre.png" alt="Download Cloudstream Pre-Release" width=430/></a></p>
|
|
||||||
|
|
||||||
[](https://discord.gg/5Hus6fM)
|
[](https://discord.gg/5Hus6fM)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,9 +8,6 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
alias(libs.plugins.dokka)
|
alias(libs.plugins.dokka)
|
||||||
alias(libs.plugins.kotlin.serialization)
|
|
||||||
alias(libs.plugins.compose.multiplatform)
|
|
||||||
alias(libs.plugins.compose.compiler)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val javaTarget = JvmTarget.fromTarget(libs.versions.jvmTarget.get())
|
val javaTarget = JvmTarget.fromTarget(libs.versions.jvmTarget.get())
|
||||||
|
|
@ -106,8 +103,8 @@ android {
|
||||||
applicationId = "com.lagradost.cloudstream3"
|
applicationId = "com.lagradost.cloudstream3"
|
||||||
minSdk = libs.versions.minSdk.get().toInt()
|
minSdk = libs.versions.minSdk.get().toInt()
|
||||||
targetSdk = libs.versions.targetSdk.get().toInt()
|
targetSdk = libs.versions.targetSdk.get().toInt()
|
||||||
versionCode = libs.versions.versionCode.get().toInt()
|
versionCode = 68
|
||||||
versionName = libs.versions.versionName.get()
|
versionName = "4.7.0"
|
||||||
|
|
||||||
manifestPlaceholders["target_sdk_version"] = libs.versions.targetSdk.get()
|
manifestPlaceholders["target_sdk_version"] = libs.versions.targetSdk.get()
|
||||||
|
|
||||||
|
|
@ -129,16 +126,6 @@ android {
|
||||||
"SIMKL_CLIENT_SECRET",
|
"SIMKL_CLIENT_SECRET",
|
||||||
"\"" + (System.getenv("SIMKL_CLIENT_SECRET") ?: localProperties["simkl.secret"]) + "\""
|
"\"" + (System.getenv("SIMKL_CLIENT_SECRET") ?: localProperties["simkl.secret"]) + "\""
|
||||||
)
|
)
|
||||||
buildConfigField(
|
|
||||||
"String",
|
|
||||||
"MAL_KEY",
|
|
||||||
"\"" + (System.getenv("MAL_KEY") ?: localProperties["mal.key"]) + "\""
|
|
||||||
)
|
|
||||||
buildConfigField(
|
|
||||||
"String",
|
|
||||||
"ANILIST_KEY",
|
|
||||||
"\"" + (System.getenv("ANILIST_KEY") ?: localProperties["anilist.key"]) + "\""
|
|
||||||
)
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -219,11 +206,9 @@ dependencies {
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
testImplementation(libs.json)
|
testImplementation(libs.json)
|
||||||
androidTestImplementation(libs.core)
|
androidTestImplementation(libs.core)
|
||||||
androidTestImplementation(libs.espresso.core)
|
implementation(libs.junit.ktx)
|
||||||
androidTestImplementation(libs.ext.junit)
|
androidTestImplementation(libs.ext.junit)
|
||||||
androidTestImplementation(libs.instancio.core)
|
androidTestImplementation(libs.espresso.core)
|
||||||
androidTestImplementation(libs.junit.ktx)
|
|
||||||
androidTestImplementation(libs.kotlin.test)
|
|
||||||
|
|
||||||
// Android Core & Lifecycle
|
// Android Core & Lifecycle
|
||||||
implementation(libs.core.ktx)
|
implementation(libs.core.ktx)
|
||||||
|
|
@ -234,7 +219,6 @@ dependencies {
|
||||||
implementation(libs.bundles.lifecycle)
|
implementation(libs.bundles.lifecycle)
|
||||||
implementation(libs.bundles.navigation)
|
implementation(libs.bundles.navigation)
|
||||||
implementation(libs.kotlinx.collections.immutable)
|
implementation(libs.kotlinx.collections.immutable)
|
||||||
implementation(libs.kotlinx.serialization.json) // JSON Parser
|
|
||||||
|
|
||||||
// Design & UI
|
// Design & UI
|
||||||
implementation(libs.preference.ktx)
|
implementation(libs.preference.ktx)
|
||||||
|
|
@ -270,19 +254,14 @@ dependencies {
|
||||||
|
|
||||||
// Extensions & Other Libs
|
// Extensions & Other Libs
|
||||||
implementation(libs.jsoup) // HTML Parser
|
implementation(libs.jsoup) // HTML Parser
|
||||||
implementation(libs.ksoup) // HTML Parser
|
|
||||||
implementation(libs.rhino) // Run JavaScript
|
implementation(libs.rhino) // Run JavaScript
|
||||||
|
implementation(libs.fuzzywuzzy) // Library/Ext Searching with Levenshtein Distance
|
||||||
implementation(libs.safefile) // To Prevent the URI File Fu*kery
|
implementation(libs.safefile) // To Prevent the URI File Fu*kery
|
||||||
coreLibraryDesugaring(libs.desugar.jdk.libs.nio) // NIO Flavor Needed for NewPipeExtractor
|
coreLibraryDesugaring(libs.desugar.jdk.libs.nio) // NIO Flavor Needed for NewPipeExtractor
|
||||||
implementation(libs.conscrypt.android) // To Fix SSL Fu*kery on Android 9
|
implementation(libs.conscrypt.android) // To Fix SSL Fu*kery on Android 9
|
||||||
implementation(libs.jackson.module.kotlin) // JSON Parser
|
implementation(libs.jackson.module.kotlin) // JSON Parser
|
||||||
implementation(libs.zipline)
|
implementation(libs.zipline)
|
||||||
|
|
||||||
// Temp/deprecated; will be removed once extensions have time to migrate from using it
|
|
||||||
implementation("com.google.code.gson:gson:2.11.0")
|
|
||||||
// Deprecated; will be removed once extensions have time to migrate from using it
|
|
||||||
implementation("me.xdrop:fuzzywuzzy:1.4.0")
|
|
||||||
|
|
||||||
// Torrent Support
|
// Torrent Support
|
||||||
implementation(libs.torrentserver)
|
implementation(libs.torrentserver)
|
||||||
|
|
||||||
|
|
@ -290,12 +269,7 @@ dependencies {
|
||||||
implementation(libs.work.runtime.ktx)
|
implementation(libs.work.runtime.ktx)
|
||||||
implementation(libs.nicehttp) // HTTP Lib
|
implementation(libs.nicehttp) // HTTP Lib
|
||||||
|
|
||||||
implementation(libs.bundles.compose)
|
|
||||||
implementation(libs.activity.compose)
|
|
||||||
implementation(libs.kotlinx.io.core) // Logcat parser
|
|
||||||
|
|
||||||
implementation(project(":library"))
|
implementation(project(":library"))
|
||||||
implementation(project(":shared"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.register<Jar>("androidSourcesJar") {
|
tasks.register<Jar>("androidSourcesJar") {
|
||||||
|
|
@ -332,6 +306,7 @@ tasks.withType<KotlinJvmCompile> {
|
||||||
compilerOptions {
|
compilerOptions {
|
||||||
jvmTarget.set(javaTarget)
|
jvmTarget.set(javaTarget)
|
||||||
jvmDefault.set(JvmDefaultMode.ENABLE)
|
jvmDefault.set(JvmDefaultMode.ENABLE)
|
||||||
|
freeCompilerArgs.add("-Xannotation-default-target=param-property")
|
||||||
optIn.addAll(
|
optIn.addAll(
|
||||||
"com.lagradost.cloudstream3.InternalAPI",
|
"com.lagradost.cloudstream3.InternalAPI",
|
||||||
"com.lagradost.cloudstream3.Prerelease",
|
"com.lagradost.cloudstream3.Prerelease",
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,12 @@ class ExampleInstrumentedTest {
|
||||||
return APIHolder.allProviders.toTypedArray() //.filter { !it.usesWebView }
|
return APIHolder.allProviders.toTypedArray() //.filter { !it.usesWebView }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun providersExist() {
|
||||||
|
Assert.assertTrue(getAllProviders().isNotEmpty())
|
||||||
|
println("Done providersExist")
|
||||||
|
}
|
||||||
|
|
||||||
@Throws
|
@Throws
|
||||||
private inline fun <reified T : ViewBinding> testAllLayouts(
|
private inline fun <reified T : ViewBinding> testAllLayouts(
|
||||||
activity: Activity,
|
activity: Activity,
|
||||||
|
|
@ -163,7 +169,7 @@ class ExampleInstrumentedTest {
|
||||||
TestingUtils.getDeferredProviderTests(
|
TestingUtils.getDeferredProviderTests(
|
||||||
this,
|
this,
|
||||||
getAllProviders(),
|
getAllProviders(),
|
||||||
) { _, _, _ -> }
|
) { _, _ -> }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,154 +0,0 @@
|
||||||
package com.lagradost.cloudstream3
|
|
||||||
|
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import com.lagradost.cloudstream3.SkipSerializationTest
|
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
|
||||||
import dalvik.system.DexFile
|
|
||||||
import kotlinx.serialization.ExperimentalSerializationApi
|
|
||||||
import kotlinx.serialization.InternalSerializationApi
|
|
||||||
import kotlinx.serialization.KSerializer
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import kotlinx.serialization.serializer
|
|
||||||
import kotlinx.serialization.serializerOrNull
|
|
||||||
import org.instancio.Instancio
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
import kotlin.reflect.KClass
|
|
||||||
import kotlin.reflect.jvm.jvmName
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertNotNull
|
|
||||||
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class SerializationClassTester {
|
|
||||||
// Same as app, or using app reference
|
|
||||||
val jacksonMapper = mapper
|
|
||||||
val kotlinxMapper = json
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun isIdenticalSerialization() {
|
|
||||||
val serializableClasses = findSerializableClasses("com.lagradost")
|
|
||||||
println("Number of serializable classes: ${serializableClasses.size}")
|
|
||||||
|
|
||||||
val failures = mutableListOf<String>()
|
|
||||||
|
|
||||||
serializableClasses.forEach { kClass ->
|
|
||||||
runCatching {
|
|
||||||
val instance = Instancio.of(kClass.java).withMaxDepth(10).create()
|
|
||||||
|
|
||||||
val jacksonJson = jacksonMapper.writeValueAsString(instance)
|
|
||||||
val kotlinxJson = serializeWithKotlinx(kClass, instance)
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
jacksonJson,
|
|
||||||
kotlinxJson,
|
|
||||||
"""
|
|
||||||
Serialization mismatch for:
|
|
||||||
${kClass.qualifiedName}
|
|
||||||
|
|
||||||
Jackson:
|
|
||||||
$jacksonJson
|
|
||||||
|
|
||||||
Kotlinx:
|
|
||||||
$kotlinxJson
|
|
||||||
|
|
||||||
""".trimIndent()
|
|
||||||
)
|
|
||||||
println("Identical serialization for: ${kClass.jvmName}")
|
|
||||||
}.onFailure { e ->
|
|
||||||
failures.add("FAILED ${kClass.qualifiedName}: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (failures.isNotEmpty()) {
|
|
||||||
throw AssertionError("${failures.size} class(es) failed:\n${failures.joinToString("\n")}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class)
|
|
||||||
@Test
|
|
||||||
fun isIdenticalDeserialization() {
|
|
||||||
val serializableClasses = findSerializableClasses("com.lagradost")
|
|
||||||
println("Number of serializable classes: ${serializableClasses.size}")
|
|
||||||
|
|
||||||
val failures = mutableListOf<String>()
|
|
||||||
|
|
||||||
serializableClasses.forEach { kClass ->
|
|
||||||
runCatching {
|
|
||||||
val instance = Instancio.of(kClass.java).withMaxDepth(10).create()
|
|
||||||
// Convert to JSON to get example JSON object
|
|
||||||
// We prefer jackson here because the app may have many jackson JSON strings in local storage
|
|
||||||
val originalJson = jacksonMapper.writeValueAsString(instance)
|
|
||||||
|
|
||||||
// Create an object from the JSON using kotlinx
|
|
||||||
val serializer =
|
|
||||||
kClass.serializerOrNull() ?: kotlinxMapper.serializersModule.getContextual(kClass)
|
|
||||||
assertNotNull(serializer, "The class: ${kClass.jvmName} must be serializable!")
|
|
||||||
val kotlinxDecoded = kotlinxMapper.decodeFromString(serializer, originalJson)
|
|
||||||
|
|
||||||
// Create an object from the JSON using jackson
|
|
||||||
val mapperDecoded = jacksonMapper.readValue(originalJson, kClass.java)
|
|
||||||
|
|
||||||
// Deep inspect both object using the mapper toJson function.
|
|
||||||
// This deep equality check can be performed using other methods, but this just works.
|
|
||||||
val jacksonJson = mapperDecoded.toJson()
|
|
||||||
val kotlinxJson = kotlinxDecoded.toJson()
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
jacksonJson,
|
|
||||||
kotlinxJson,
|
|
||||||
"""
|
|
||||||
Serialization mismatch for:
|
|
||||||
${kClass.qualifiedName}
|
|
||||||
|
|
||||||
Jackson:
|
|
||||||
$jacksonJson
|
|
||||||
|
|
||||||
Kotlinx:
|
|
||||||
$kotlinxJson
|
|
||||||
|
|
||||||
""".trimIndent()
|
|
||||||
)
|
|
||||||
println("Identical deserialization for: ${kClass.jvmName}")
|
|
||||||
}.onFailure { e ->
|
|
||||||
failures.add("FAILED ${kClass.qualifiedName}: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (failures.isNotEmpty()) {
|
|
||||||
throw AssertionError("${failures.size} class(es) failed:\n${failures.joinToString("\n")}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// DEX files are the best solution to read all our classes dynamically.
|
|
||||||
// classgraph could be used instead, but it only gives results on the JVM, not Android.
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
private fun findSerializableClasses(packageName: String): List<KClass<*>> {
|
|
||||||
val context = InstrumentationRegistry
|
|
||||||
.getInstrumentation()
|
|
||||||
.targetContext
|
|
||||||
|
|
||||||
val dexFile = DexFile(context.packageCodePath)
|
|
||||||
return dexFile.entries()
|
|
||||||
.toList()
|
|
||||||
.filter { it.startsWith(packageName) }
|
|
||||||
.mapNotNull {
|
|
||||||
runCatching { Class.forName(it).kotlin }.getOrNull()
|
|
||||||
}.filter { kClass ->
|
|
||||||
// Not possible to use .hasAnnotation() on newer Android versions.
|
|
||||||
kClass.java.annotations.any { it is Serializable }
|
|
||||||
&& kClass.java.annotations.none { it is SkipSerializationTest }
|
|
||||||
&& !kClass.isAbstract
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OptIn(InternalSerializationApi::class)
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
private fun serializeWithKotlinx(
|
|
||||||
kClass: KClass<*>,
|
|
||||||
value: Any
|
|
||||||
): String {
|
|
||||||
val serializer = kClass.serializer() as KSerializer<Any>
|
|
||||||
return kotlinxMapper.encodeToString(serializer, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.utils.serializers
|
|
||||||
|
|
||||||
import android.net.Uri
|
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class UriData(
|
|
||||||
@Serializable(with = UriSerializer::class)
|
|
||||||
@SerialName("uri") val uri: Uri = Uri.EMPTY,
|
|
||||||
)
|
|
||||||
|
|
||||||
class UriSerializerTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uriSerializerSerializesUriToString() {
|
|
||||||
val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
|
|
||||||
val result = data.toJson()
|
|
||||||
assertTrue(result.contains("https://example.com/path?query=1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uriSerializerDeserializesStringToUri() {
|
|
||||||
val input = """{"uri":"https://example.com/path?query=1"}"""
|
|
||||||
val result = parseJson<UriData>(input)
|
|
||||||
assertEquals(Uri.parse("https://example.com/path?query=1"), result.uri)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uriSerializerRoundtripsCorrectly() {
|
|
||||||
val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
|
|
||||||
val encoded = data.toJson()
|
|
||||||
val decoded = parseJson<UriData>(encoded)
|
|
||||||
assertEquals(data.uri, decoded.uri)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -22,47 +22,6 @@
|
||||||
android:name="android.permission.QUERY_ALL_PACKAGES"
|
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||||
tools:ignore="QueryAllPackagesPermission" />
|
tools:ignore="QueryAllPackagesPermission" />
|
||||||
|
|
||||||
<queries>
|
|
||||||
<!--
|
|
||||||
QUERY_ALL_PACKAGES does not work on some devices running Android 11+ (like Google TV 14),
|
|
||||||
so we must explicitly specify the packages and intent patterns we query to ensure visibility.
|
|
||||||
-->
|
|
||||||
<!-- For external video players -->
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
<data android:mimeType="video/*" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
<data android:mimeType="application/x-mpegURL" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
<data android:mimeType="application/vnd.apple.mpegurl" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
<data android:scheme="magnet" />
|
|
||||||
</intent>
|
|
||||||
|
|
||||||
<!-- Common players supported in actions/temp -->
|
|
||||||
<package android:name="org.videolan.vlc" />
|
|
||||||
<package android:name="org.videolan.vlc.debug" />
|
|
||||||
<package android:name="is.xyz.mpv" />
|
|
||||||
<package android:name="is.xyz.mpv.ytdl" />
|
|
||||||
<package android:name="app.marlboroadvance.mpvex" />
|
|
||||||
<package android:name="live.mehiz.mpvkt" />
|
|
||||||
<package android:name="live.mehiz.mpvkt.preview" />
|
|
||||||
<package android:name="com.brouken.player" />
|
|
||||||
<package android:name="dev.anilbeesetti.nextplayer" />
|
|
||||||
<package android:name="com.instantbits.cast.webvideo" />
|
|
||||||
<package android:name="com.gianlu.aria2android" />
|
|
||||||
|
|
||||||
<!-- Torrent clients -->
|
|
||||||
<package android:name="org.proninyaroslav.libretorrent" />
|
|
||||||
<package android:name="com.biglybt.android.client" />
|
|
||||||
</queries>
|
|
||||||
|
|
||||||
<!-- Fixes android tv fuckery -->
|
<!-- Fixes android tv fuckery -->
|
||||||
<uses-feature
|
<uses-feature
|
||||||
android:name="android.hardware.touchscreen"
|
android:name="android.hardware.touchscreen"
|
||||||
|
|
@ -161,7 +120,7 @@
|
||||||
android:supportsPictureInPicture="true" />
|
android:supportsPictureInPicture="true" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.account.AccountSelectActivity2"
|
android:name=".ui.account.AccountSelectActivity"
|
||||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
|
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
<intent-filter android:exported="true">
|
<intent-filter android:exported="true">
|
||||||
|
|
@ -253,10 +212,6 @@
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
<receiver
|
|
||||||
android:name=".receivers.PackageInstallerStatusReceiver"
|
|
||||||
android:exported="false" />
|
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".services.VideoDownloadService"
|
android:name=".services.VideoDownloadService"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ package com.lagradost.cloudstream3
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
class AcraApplication {
|
class AcraApplication {
|
||||||
companion object {
|
companion object {
|
||||||
|
|
@ -15,14 +15,14 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.context"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.context"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
val context get() = CloudStreamApp.context
|
val context get() = CloudStreamApp.context
|
||||||
|
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.removeKeys(folder)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.removeKeys(folder)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
fun removeKeys(folder: String): Int? =
|
fun removeKeys(folder: String): Int? =
|
||||||
CloudStreamApp.removeKeys(folder)
|
CloudStreamApp.removeKeys(folder)
|
||||||
|
|
@ -30,7 +30,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(path, value)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(path, value)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
fun <T> setKey(path: String, value: T) =
|
fun <T> setKey(path: String, value: T) =
|
||||||
CloudStreamApp.setKey(path, value)
|
CloudStreamApp.setKey(path, value)
|
||||||
|
|
@ -38,7 +38,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(folder, path, value)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(folder, path, value)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
fun <T> setKey(folder: String, path: String, value: T) =
|
fun <T> setKey(folder: String, path: String, value: T) =
|
||||||
CloudStreamApp.setKey(folder, path, value)
|
CloudStreamApp.setKey(folder, path, value)
|
||||||
|
|
@ -46,7 +46,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path, defVal)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path, defVal)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
inline fun <reified T : Any> getKey(path: String, defVal: T?): T? =
|
inline fun <reified T : Any> getKey(path: String, defVal: T?): T? =
|
||||||
CloudStreamApp.getKey(path, defVal)
|
CloudStreamApp.getKey(path, defVal)
|
||||||
|
|
@ -54,7 +54,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
inline fun <reified T : Any> getKey(path: String): T? =
|
inline fun <reified T : Any> getKey(path: String): T? =
|
||||||
CloudStreamApp.getKey(path)
|
CloudStreamApp.getKey(path)
|
||||||
|
|
@ -62,7 +62,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
inline fun <reified T : Any> getKey(folder: String, path: String): T? =
|
inline fun <reified T : Any> getKey(folder: String, path: String): T? =
|
||||||
CloudStreamApp.getKey(folder, path)
|
CloudStreamApp.getKey(folder, path)
|
||||||
|
|
@ -70,7 +70,7 @@ class AcraApplication {
|
||||||
@Deprecated(
|
@Deprecated(
|
||||||
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
message = "AcraApplication is deprecated, use CloudStreamApp instead",
|
||||||
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path, defVal)"),
|
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path, defVal)"),
|
||||||
level = DeprecationLevel.ERROR
|
level = DeprecationLevel.WARNING
|
||||||
)
|
)
|
||||||
inline fun <reified T : Any> getKey(folder: String, path: String, defVal: T?): T? =
|
inline fun <reified T : Any> getKey(folder: String, path: String, defVal: T?): T? =
|
||||||
CloudStreamApp.getKey(folder, path, defVal)
|
CloudStreamApp.getKey(folder, path, defVal)
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,7 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
|
||||||
get() = _context?.get()
|
get() = _context?.get()
|
||||||
private set(value) {
|
private set(value) {
|
||||||
_context = WeakReference(value)
|
_context = WeakReference(value)
|
||||||
setContext(value)
|
setContext(WeakReference(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <T : Any> getKeyClass(path: String, valueType: Class<T>): T? {
|
fun <T : Any> getKeyClass(path: String, valueType: Class<T>): T? {
|
||||||
|
|
@ -170,11 +170,11 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Will fall back to WebView if in TV or emulator layout. */
|
/** Will fall back to WebView if in TV or emulator layout. */
|
||||||
fun openBrowser(url: String, activity: Activity?) {
|
fun openBrowser(url: String, activity: FragmentActivity?) {
|
||||||
openBrowser(
|
openBrowser(
|
||||||
url,
|
url,
|
||||||
isLayout(TV or EMULATOR),
|
isLayout(TV or EMULATOR),
|
||||||
(activity as? FragmentActivity)?.supportFragmentManager?.fragments?.lastOrNull()
|
activity?.supportFragmentManager?.fragments?.lastOrNull()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
|
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
|
||||||
import com.lagradost.cloudstream3.ui.settings.extensions.PluginAdapter
|
import com.lagradost.cloudstream3.ui.settings.extensions.PluginAdapter
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
|
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.isAuthEnabled
|
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
import com.lagradost.cloudstream3.utils.Event
|
import com.lagradost.cloudstream3.utils.Event
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
|
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
|
||||||
|
|
@ -267,9 +266,7 @@ object CommonActivity {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ask for notification permissions on Android 13
|
// Ask for notification permissions on Android 13
|
||||||
// Not while biometric locked, the dialog cancels the biometric prompt
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
!isAuthEnabled(componentActivity) &&
|
|
||||||
ContextCompat.checkSelfPermission(
|
ContextCompat.checkSelfPermission(
|
||||||
componentActivity,
|
componentActivity,
|
||||||
Manifest.permission.POST_NOTIFICATIONS
|
Manifest.permission.POST_NOTIFICATIONS
|
||||||
|
|
@ -582,10 +579,8 @@ object CommonActivity {
|
||||||
|
|
||||||
// TODO: Figure out why removing the check for SearchAutoComplete seems
|
// TODO: Figure out why removing the check for SearchAutoComplete seems
|
||||||
// to break focus on TV as it shouldn't need to be used.
|
// to break focus on TV as it shouldn't need to be used.
|
||||||
// Also handle KEYCODE_ENTER here because some remotes (e.g. LG Magic Remote)
|
|
||||||
// send KEYCODE_ENTER instead of KEYCODE_DPAD_CENTER when clicking the OK button.
|
|
||||||
@SuppressLint("RestrictedApi")
|
@SuppressLint("RestrictedApi")
|
||||||
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) &&
|
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER &&
|
||||||
(act.currentFocus is SearchView || act.currentFocus is SearchView.SearchAutoComplete)
|
(act.currentFocus is SearchView || act.currentFocus is SearchView.SearchAutoComplete)
|
||||||
) {
|
) {
|
||||||
showInputMethod(act.currentFocus?.findFocus())
|
showInputMethod(act.currentFocus?.findFocus())
|
||||||
|
|
@ -606,4 +601,4 @@ object CommonActivity {
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -171,19 +171,13 @@ import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.requestRW
|
import com.lagradost.cloudstream3.utils.UIHelper.requestRW
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
|
import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
||||||
import com.lagradost.cloudstream3.utils.USER_PROVIDER_API
|
import com.lagradost.cloudstream3.utils.USER_PROVIDER_API
|
||||||
import com.lagradost.cloudstream3.utils.USER_SELECTED_HOMEPAGE_API
|
import com.lagradost.cloudstream3.utils.USER_SELECTED_HOMEPAGE_API
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
|
||||||
import com.lagradost.cloudstream3.utils.setText
|
import com.lagradost.cloudstream3.utils.setText
|
||||||
import com.lagradost.cloudstream3.utils.setTextHtml
|
import com.lagradost.cloudstream3.utils.setTextHtml
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import com.lagradost.cloudstream4.compose.CloudStreamThemeAppSettings
|
|
||||||
import com.lagradost.cloudstream4.theme.CloudStreamTheme
|
|
||||||
import com.lagradost.safefile.SafeFile
|
import com.lagradost.safefile.SafeFile
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
@ -193,8 +187,10 @@ import java.net.URLDecoder
|
||||||
import java.nio.charset.Charset
|
import java.nio.charset.Charset
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
import kotlin.math.absoluteValue
|
import kotlin.math.absoluteValue
|
||||||
import kotlin.reflect.full.createInstance
|
|
||||||
import kotlin.system.exitProcess
|
import kotlin.system.exitProcess
|
||||||
|
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCallback {
|
class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCallback {
|
||||||
companion object {
|
companion object {
|
||||||
|
|
@ -412,10 +408,13 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
val matchedApi = apis.filter { str.startsWith(it.mainUrl) }.firstOrNull()
|
synchronized(apis) {
|
||||||
if (matchedApi != null) {
|
for (api in apis) {
|
||||||
loadResult(str, matchedApi.name, "")
|
if (str.startsWith(api.mainUrl)) {
|
||||||
return true
|
loadResult(str, api.name, "")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -788,6 +787,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
|
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
|
||||||
.setEnterAnim(R.anim.enter_anim)
|
.setEnterAnim(R.anim.enter_anim)
|
||||||
.setExitAnim(R.anim.exit_anim)
|
.setExitAnim(R.anim.exit_anim)
|
||||||
|
|
@ -809,33 +809,32 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private val pluginsLock = Mutex()
|
private val pluginsLock = Mutex()
|
||||||
private fun onAllPluginsLoaded(success: Boolean = false) {
|
private fun onAllPluginsLoaded(success: Boolean = false) {
|
||||||
ioSafe {
|
ioSafe {
|
||||||
pluginsLock.withLock {
|
pluginsLock.withLock {
|
||||||
allProviders.withLock {
|
synchronized(allProviders) {
|
||||||
// Load cloned sites after plugins have been loaded since clones depend on plugins.
|
// Load cloned sites after plugins have been loaded since clones depend on plugins.
|
||||||
try {
|
try {
|
||||||
getKey<Array<SettingsGeneral.CustomSite>>(USER_PROVIDER_API)?.let { list ->
|
getKey<Array<SettingsGeneral.CustomSite>>(USER_PROVIDER_API)?.let { list ->
|
||||||
list.forEach { custom ->
|
list.forEach { custom ->
|
||||||
allProviders.firstOrNull {
|
allProviders.firstOrNull { it.javaClass.simpleName == custom.parentJavaClass }
|
||||||
it::class.simpleName == custom.parentClassName
|
?.let {
|
||||||
}?.let {
|
allProviders.add(
|
||||||
allProviders.add(
|
it.javaClass.getDeclaredConstructor().newInstance()
|
||||||
it::class.createInstance().apply {
|
.apply {
|
||||||
name = custom.name
|
name = custom.name
|
||||||
lang = custom.lang
|
lang = custom.lang
|
||||||
mainUrl = custom.url.trimEnd('/')
|
mainUrl = custom.url.trimEnd('/')
|
||||||
canBeOverridden = false
|
canBeOverridden = false
|
||||||
}
|
})
|
||||||
)
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// it.hashCode() is not enough to make sure they are distinct
|
// it.hashCode() is not enough to make sure they are distinct
|
||||||
apis = allProviders.distinctBy {
|
apis =
|
||||||
it.lang + it.name + it.mainUrl + it::class.qualifiedName
|
allProviders.distinctBy { it.lang + it.name + it.mainUrl + it.javaClass.name }
|
||||||
}
|
|
||||||
APIHolder.apiMap = null
|
APIHolder.apiMap = null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
logError(e)
|
logError(e)
|
||||||
|
|
@ -1217,7 +1216,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
// backup when we update the app, I don't trust myself to not boot lock users, might want to make this a setting?
|
// backup when we update the app, I don't trust myself to not boot lock users, might want to make this a setting?
|
||||||
safe {
|
safe {
|
||||||
val appVer = BuildConfig.VERSION_NAME
|
val appVer = BuildConfig.VERSION_NAME
|
||||||
val lastAppAutoBackup: String = getKey<String>("VERSION_NAME") ?: ""
|
val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
|
||||||
if (appVer != lastAppAutoBackup) {
|
if (appVer != lastAppAutoBackup) {
|
||||||
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
|
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
|
||||||
if (lastAppAutoBackup.isEmpty()) return@safe
|
if (lastAppAutoBackup.isEmpty()) return@safe
|
||||||
|
|
@ -1299,14 +1298,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
padRight = false,
|
padRight = false,
|
||||||
padTop = false
|
padTop = false
|
||||||
)
|
)
|
||||||
|
|
||||||
composeView.apply {
|
|
||||||
setContent {
|
|
||||||
CloudStreamThemeAppSettings {
|
|
||||||
MainActivityScreen.Content()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// overscan
|
// overscan
|
||||||
|
|
@ -1379,7 +1370,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
}
|
}
|
||||||
|
|
||||||
//Automatically download not existing plugins, using mode specified.
|
//Automatically download not existing plugins, using mode specified.
|
||||||
/*val autoDownloadPlugin = AutoDownloadMode.getEnum(
|
val autoDownloadPlugin = AutoDownloadMode.getEnum(
|
||||||
settingsManager.getInt(
|
settingsManager.getInt(
|
||||||
getString(R.string.auto_download_plugins_key),
|
getString(R.string.auto_download_plugins_key),
|
||||||
0
|
0
|
||||||
|
|
@ -1390,7 +1381,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
this@MainActivity,
|
this@MainActivity,
|
||||||
autoDownloadPlugin
|
autoDownloadPlugin
|
||||||
)
|
)
|
||||||
}*/
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ioSafe {
|
ioSafe {
|
||||||
|
|
@ -1439,9 +1430,8 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
resultviewPreviewBookmark.isEnabled = false
|
resultviewPreviewBookmark.isEnabled = false
|
||||||
resultviewPreviewBookmark.showProgress()
|
resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
|
||||||
//resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
|
resultviewPreviewBookmark.setText(R.string.loading)
|
||||||
//resultviewPreviewBookmark.setText(R.string.loading)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1667,7 +1657,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
ioSafe {
|
ioSafe {
|
||||||
initAll()
|
initAll()
|
||||||
// No duplicates (which can happen by registerMainAPI)
|
// No duplicates (which can happen by registerMainAPI)
|
||||||
apis = allProviders.distinctBy { it }
|
apis = synchronized(allProviders) {
|
||||||
|
allProviders.distinctBy { it }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// val navView: BottomNavigationView = findViewById(R.id.nav_view)
|
// val navView: BottomNavigationView = findViewById(R.id.nav_view)
|
||||||
|
|
@ -1975,7 +1967,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
|
|
||||||
if (BuildConfig.DEBUG) {
|
if (BuildConfig.DEBUG) {
|
||||||
var providersAndroidManifestString = "Current androidmanifest should be:\n"
|
var providersAndroidManifestString = "Current androidmanifest should be:\n"
|
||||||
allProviders.withLock {
|
synchronized(allProviders) {
|
||||||
for (api in allProviders) {
|
for (api in allProviders) {
|
||||||
providersAndroidManifestString += "<data android:scheme=\"https\" android:host=\"${
|
providersAndroidManifestString += "<data android:scheme=\"https\" android:host=\"${
|
||||||
api.mainUrl.removePrefix(
|
api.mainUrl.removePrefix(
|
||||||
|
|
@ -1989,9 +1981,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
|
|
||||||
handleAppIntent(intent)
|
handleAppIntent(intent)
|
||||||
|
|
||||||
//ioSafe {
|
ioSafe {
|
||||||
// runAutoUpdate()
|
runAutoUpdate()
|
||||||
//}
|
}
|
||||||
|
|
||||||
FcastManager().init(this, false)
|
FcastManager().init(this, false)
|
||||||
|
|
||||||
|
|
@ -2028,7 +2020,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (getKey<Boolean>(HAS_DONE_SETUP_KEY, false) != true) {
|
if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
|
||||||
navController.navigate(R.id.navigation_setup_language)
|
navController.navigate(R.id.navigation_setup_language)
|
||||||
// If no plugins bring up extensions screen
|
// If no plugins bring up extensions screen
|
||||||
} else if (PluginManager.getPluginsOnline().isEmpty()
|
} else if (PluginManager.getPluginsOnline().isEmpty()
|
||||||
|
|
|
||||||
|
|
@ -1,266 +0,0 @@
|
||||||
package com.lagradost.cloudstream3
|
|
||||||
|
|
||||||
import android.text.format.Formatter.formatFileSize
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.LocalActivity
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.window.DialogProperties
|
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
|
||||||
import com.lagradost.cloudstream3.mvvm.getStackTracePretty
|
|
||||||
import com.lagradost.cloudstream3.plugins.PluginManager
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.ApkUpdater
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.GithubReleases
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_CONTENT_TYPE
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_PRERELEASE
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_REPOSITORY
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_USERNAME
|
|
||||||
import com.lagradost.cloudstream3.utils.GitInfo.currentCommitHash
|
|
||||||
import com.lagradost.cloudstream3.utils.parseMarkdown
|
|
||||||
import com.lagradost.cloudstream4.compose.BlackButton
|
|
||||||
import com.lagradost.cloudstream4.compose.Screen
|
|
||||||
import com.lagradost.cloudstream4.compose.WhiteButton
|
|
||||||
import com.lagradost.cloudstream4.rememberAppSettings
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction.AutoSearchForUpdate
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction.Dismiss
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction.SearchForUpdate
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction.SkipUpdate
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubAction.Update
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubState
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubUpdateDialogState
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubViewModel
|
|
||||||
import com.mihon.material.padding
|
|
||||||
|
|
||||||
object MainActivityScreen : Screen {
|
|
||||||
private var hasSearchedForUpdate: Boolean = false
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun githubViewModel(): GithubViewModel? {
|
|
||||||
// By having the ComponentActivity as the owner we can have a singleton viewmodel
|
|
||||||
val activity = LocalActivity.current as? ComponentActivity ?: return null
|
|
||||||
val settings = rememberAppSettings()
|
|
||||||
return viewModel(viewModelStoreOwner = activity) {
|
|
||||||
GithubViewModel(
|
|
||||||
remoteUserName = APK_USERNAME,
|
|
||||||
remoteRepository = APK_REPOSITORY,
|
|
||||||
remotePrereleaseTag = APK_PRERELEASE,
|
|
||||||
remoteContentType = APK_CONTENT_TYPE,
|
|
||||||
versionName = BuildConfig.VERSION_NAME,
|
|
||||||
isPrerelease = BuildConfig.FLAVOR == "prerelease",
|
|
||||||
isDebug = BuildConfig.DEBUG,
|
|
||||||
buildSha = activity.currentCommitHash(),
|
|
||||||
settings = settings,
|
|
||||||
updater = ApkUpdater,
|
|
||||||
repository = GithubReleases,
|
|
||||||
).apply {
|
|
||||||
/** Only search once per session when not in safe mode */
|
|
||||||
if (!hasSearchedForUpdate && !PluginManager.isSafeMode()) {
|
|
||||||
hasSearchedForUpdate = true
|
|
||||||
onAction(AutoSearchForUpdate)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
override fun Content() {
|
|
||||||
GithubView()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun GithubView() {
|
|
||||||
val updateViewModel = githubViewModel() ?: return
|
|
||||||
val state by updateViewModel.state.collectAsState()
|
|
||||||
GithubState(state, updateViewModel::onAction)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun GithubState(updaterState: GithubState, onAction: (GithubAction) -> Unit) {
|
|
||||||
val dialog = updaterState.dialog ?: return
|
|
||||||
|
|
||||||
val title: String
|
|
||||||
val body: @Composable () -> Unit
|
|
||||||
val confirmButton: @Composable () -> Unit
|
|
||||||
val dismissButton: @Composable () -> Unit
|
|
||||||
val cancelable: Boolean
|
|
||||||
|
|
||||||
when (val state = dialog.state) {
|
|
||||||
is GithubUpdateDialogState.Error -> {
|
|
||||||
// Only show error if it is initialized by the user
|
|
||||||
if (!dialog.isFromUser) return
|
|
||||||
|
|
||||||
cancelable = true
|
|
||||||
title = stringResource(R.string.download_failed)
|
|
||||||
body = { Text(text = state.error.getStackTracePretty()) }
|
|
||||||
confirmButton = {
|
|
||||||
WhiteButton(text = stringResource(R.string.check_for_update), onClick = {
|
|
||||||
onAction(SearchForUpdate)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.ok), onClick = {
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
GithubUpdateDialogState.Loading -> {
|
|
||||||
// Only show loading if it is initialized by the user
|
|
||||||
if (!dialog.isFromUser) return
|
|
||||||
|
|
||||||
cancelable = true
|
|
||||||
title = stringResource(R.string.loading)
|
|
||||||
body = {
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
confirmButton = {}
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = {
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
GithubUpdateDialogState.NoUpdateFound -> {
|
|
||||||
// Only show error if it is initialized by the user
|
|
||||||
if (!dialog.isFromUser) return
|
|
||||||
|
|
||||||
cancelable = true
|
|
||||||
title = stringResource(R.string.no_update_found)
|
|
||||||
body = {}
|
|
||||||
confirmButton = {
|
|
||||||
WhiteButton(text = stringResource(R.string.ok), onClick = {
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
dismissButton = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
is GithubUpdateDialogState.UpdateFound -> {
|
|
||||||
cancelable = true
|
|
||||||
title = stringResource(
|
|
||||||
R.string.new_update_format,
|
|
||||||
(state.oldSha ?: BuildConfig.VERSION_NAME),
|
|
||||||
(state.newSha ?: state.file.displayName)
|
|
||||||
)
|
|
||||||
body = {
|
|
||||||
Text(
|
|
||||||
text = parseMarkdown(state.file.changeLog),
|
|
||||||
modifier = Modifier.verticalScroll(rememberScrollState())
|
|
||||||
)
|
|
||||||
}
|
|
||||||
confirmButton = {
|
|
||||||
WhiteButton(text = stringResource(R.string.update), onClick = {
|
|
||||||
onAction(Update(state.file))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.skip_update), onClick = {
|
|
||||||
onAction(SkipUpdate(state.file))
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = {
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is GithubUpdateDialogState.DownloadProgress -> {
|
|
||||||
cancelable = false
|
|
||||||
title = stringResource(R.string.update_notification_downloading)
|
|
||||||
body = {
|
|
||||||
val total = state.total
|
|
||||||
if (total != null) {
|
|
||||||
val progress =
|
|
||||||
(state.progress.toFloat() / total.toFloat()).coerceIn(0.0f, 1.0f)
|
|
||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
|
||||||
Text(
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
// Round down the progress to avoid 100%
|
|
||||||
text = "${(progress * 100.0f).toInt()}% (${
|
|
||||||
formatFileSize(
|
|
||||||
LocalContext.current,
|
|
||||||
state.progress
|
|
||||||
)
|
|
||||||
} / ${
|
|
||||||
formatFileSize(
|
|
||||||
LocalContext.current,
|
|
||||||
total
|
|
||||||
)
|
|
||||||
})"
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
progress = { progress }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
|
||||||
Text(
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
text = formatFileSize(
|
|
||||||
LocalContext.current,
|
|
||||||
state.progress
|
|
||||||
)
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
|
|
||||||
LinearProgressIndicator(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
confirmButton = {}
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = {
|
|
||||||
onAction(Dismiss)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AlertDialog(
|
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
onDismissRequest = {
|
|
||||||
if (cancelable) {
|
|
||||||
onAction(Dismiss)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
title = { Text(text = title) },
|
|
||||||
text = body,
|
|
||||||
confirmButton = confirmButton,
|
|
||||||
dismissButton = dismissButton
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -20,10 +20,8 @@ import com.lagradost.cloudstream3.actions.temp.MpvExPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.MpvKtPackage
|
import com.lagradost.cloudstream3.actions.temp.MpvKtPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.MpvKtPreviewPackage
|
import com.lagradost.cloudstream3.actions.temp.MpvKtPreviewPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.MpvPackage
|
import com.lagradost.cloudstream3.actions.temp.MpvPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.MpvRxPackage
|
|
||||||
import com.lagradost.cloudstream3.actions.temp.MpvYTDLPackage
|
import com.lagradost.cloudstream3.actions.temp.MpvYTDLPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.NextPlayerPackage
|
import com.lagradost.cloudstream3.actions.temp.NextPlayerPackage
|
||||||
import com.lagradost.cloudstream3.actions.temp.OnlyPlayer
|
|
||||||
import com.lagradost.cloudstream3.actions.temp.PlayInBrowserAction
|
import com.lagradost.cloudstream3.actions.temp.PlayInBrowserAction
|
||||||
import com.lagradost.cloudstream3.actions.temp.PlayMirrorAction
|
import com.lagradost.cloudstream3.actions.temp.PlayMirrorAction
|
||||||
import com.lagradost.cloudstream3.actions.temp.ViewM3U8Action
|
import com.lagradost.cloudstream3.actions.temp.ViewM3U8Action
|
||||||
|
|
@ -34,17 +32,18 @@ import com.lagradost.cloudstream3.actions.temp.fcast.FcastAction
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
|
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
|
||||||
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
|
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
|
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
||||||
import com.lagradost.cloudstream3.utils.UiText
|
import com.lagradost.cloudstream3.utils.UiText
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.util.concurrent.Callable
|
import java.util.concurrent.Callable
|
||||||
import java.util.concurrent.FutureTask
|
import java.util.concurrent.FutureTask
|
||||||
|
import kotlin.reflect.jvm.jvmName
|
||||||
|
|
||||||
object VideoClickActionHolder {
|
object VideoClickActionHolder {
|
||||||
val allVideoClickActions = atomicListOf(
|
val allVideoClickActions = threadSafeListOf(
|
||||||
// Default
|
// Default
|
||||||
PlayInBrowserAction(),
|
PlayInBrowserAction(),
|
||||||
CopyClipboardAction(),
|
CopyClipboardAction(),
|
||||||
|
|
@ -65,8 +64,6 @@ object VideoClickActionHolder {
|
||||||
MpvYTDLPackage(),
|
MpvYTDLPackage(),
|
||||||
MpvKtPackage(),
|
MpvKtPackage(),
|
||||||
MpvKtPreviewPackage(),
|
MpvKtPreviewPackage(),
|
||||||
OnlyPlayer(),
|
|
||||||
MpvRxPackage(),
|
|
||||||
// Always Ask option
|
// Always Ask option
|
||||||
AlwaysAskAction(),
|
AlwaysAskAction(),
|
||||||
// added by plugins
|
// added by plugins
|
||||||
|
|
@ -98,7 +95,7 @@ object VideoClickActionHolder {
|
||||||
?.second
|
?.second
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getPlayers(context: Context? = null) = allVideoClickActions.filter { it.isPlayer && it.shouldShowSafe(context, null) }
|
fun getPlayers(activity: Activity? = null) = allVideoClickActions.filter { it.isPlayer && it.shouldShowSafe(activity, null) }
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class VideoClickAction {
|
abstract class VideoClickAction {
|
||||||
|
|
@ -160,7 +157,7 @@ abstract class VideoClickAction {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun uniqueId() = "$sourcePlugin:${this::class.qualifiedName}"
|
fun uniqueId() = "$sourcePlugin:${this::class.jvmName}"
|
||||||
|
|
||||||
@Throws
|
@Throws
|
||||||
abstract fun shouldShow(context: Context?, video: ResultEpisode?): Boolean
|
abstract fun shouldShow(context: Context?, video: ResultEpisode?): Boolean
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import android.net.Uri
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.actions.OpenInAppAction
|
import com.lagradost.cloudstream3.actions.OpenInAppAction
|
||||||
import com.lagradost.cloudstream3.BuildConfig
|
import com.lagradost.cloudstream3.BuildConfig
|
||||||
import com.lagradost.cloudstream3.SkipSerializationTest
|
|
||||||
import com.lagradost.cloudstream3.ui.player.ExtractorUri
|
import com.lagradost.cloudstream3.ui.player.ExtractorUri
|
||||||
import com.lagradost.cloudstream3.ui.player.SubtitleData
|
import com.lagradost.cloudstream3.ui.player.SubtitleData
|
||||||
import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
|
import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
|
||||||
|
|
@ -23,10 +22,7 @@ import com.lagradost.cloudstream3.utils.newExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.Qualities
|
import com.lagradost.cloudstream3.utils.Qualities
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
|
||||||
import com.lagradost.cloudstream3.utils.serializers.UriSerializer
|
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If you want to support CloudStream 3 as an external player, then this shows how to play any video link
|
* If you want to support CloudStream 3 as an external player, then this shows how to play any video link
|
||||||
|
|
@ -53,17 +49,19 @@ class CloudStreamPackage : OpenInAppAction(
|
||||||
const val DURATION_EXTRA: String = "dur" // Duration time in MS (Long)
|
const val DURATION_EXTRA: String = "dur" // Duration time in MS (Long)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SkipSerializationTest //.Uri has issues with Jackson
|
|
||||||
data class MinimalVideoLink(
|
data class MinimalVideoLink(
|
||||||
@JsonProperty("uri") @SerialName("uri")
|
@JsonProperty("uri")
|
||||||
@Serializable(with = UriSerializer::class)
|
|
||||||
val uri: Uri?,
|
val uri: Uri?,
|
||||||
@JsonProperty("url") @SerialName("url") val url: String?,
|
@JsonProperty("url")
|
||||||
@JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "video/mp4",
|
val url: String?,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String?,
|
@JsonProperty("mimeType")
|
||||||
@JsonProperty("headers") @SerialName("headers") var headers: Map<String, String> = mapOf(),
|
val mimeType: String = "video/mp4",
|
||||||
@JsonProperty("quality") @SerialName("quality") val quality: Int?,
|
@JsonProperty("name")
|
||||||
|
val name: String?,
|
||||||
|
@JsonProperty("headers")
|
||||||
|
var headers: Map<String, String> = mapOf(),
|
||||||
|
@JsonProperty("quality")
|
||||||
|
val quality: Int?,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromExtractor(link: ExtractorLink): MinimalVideoLink = MinimalVideoLink(
|
fun fromExtractor(link: ExtractorLink): MinimalVideoLink = MinimalVideoLink(
|
||||||
|
|
@ -99,12 +97,16 @@ class CloudStreamPackage : OpenInAppAction(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MinimalSubtitleLink(
|
data class MinimalSubtitleLink(
|
||||||
@JsonProperty("url") @SerialName("url") val url: String,
|
@JsonProperty("url")
|
||||||
@JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "text/vtt",
|
val url: String,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String?,
|
@JsonProperty("mimeType")
|
||||||
@JsonProperty("headers") @SerialName("headers") var headers: Map<String, String> = mapOf(),
|
val mimeType: String = "text/vtt",
|
||||||
|
@JsonProperty("name")
|
||||||
|
val name: String?,
|
||||||
|
@JsonProperty("headers")
|
||||||
|
var headers: Map<String, String> = mapOf(),
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun fromSubtitle(sub: SubtitleData): MinimalSubtitleLink = MinimalSubtitleLink(
|
fun fromSubtitle(sub: SubtitleData): MinimalSubtitleLink = MinimalSubtitleLink(
|
||||||
|
|
@ -157,4 +159,4 @@ class CloudStreamPackage : OpenInAppAction(
|
||||||
override fun onResult(activity: Activity, intent: Intent?) {
|
override fun onResult(activity: Activity, intent: Intent?) {
|
||||||
// No results yet
|
// No results yet
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.actions.temp
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import androidx.core.net.toUri
|
|
||||||
import com.lagradost.api.Log
|
|
||||||
import com.lagradost.cloudstream3.actions.OpenInAppAction
|
|
||||||
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
|
|
||||||
import com.lagradost.cloudstream3.isEpisodeBased
|
|
||||||
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
|
|
||||||
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
|
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
|
||||||
|
|
||||||
/** https://github.com/Riteshp2001/mpvRx
|
|
||||||
*
|
|
||||||
* https://github.com/Riteshp2001/mpvRx/blob/00e0c5e803ab53e5757426cbf2248448ba1f49bf/app/src/main/java/app/gyrolet/mpvrx/utils/media/MediaUtils.kt#L132
|
|
||||||
* https://github.com/Riteshp2001/mpvRx/blob/00e0c5e803ab53e5757426cbf2248448ba1f49bf/app/src/main/java/app/gyrolet/mpvrx/utils/media/MediaUtils.kt#L56
|
|
||||||
* */
|
|
||||||
class MpvRxPackage : OpenInAppAction(
|
|
||||||
appName = txt("mpvRx"),
|
|
||||||
packageName = "app.gyrolet.mpvrx",
|
|
||||||
intentClass = "app.gyrolet.mpvrx.ui.player.PlayerActivity"
|
|
||||||
) {
|
|
||||||
override val oneSource = true
|
|
||||||
override suspend fun putExtra(
|
|
||||||
context: Context,
|
|
||||||
intent: Intent,
|
|
||||||
video: ResultEpisode,
|
|
||||||
result: LinkLoadingResult,
|
|
||||||
index: Int?
|
|
||||||
) {
|
|
||||||
intent.apply {
|
|
||||||
putExtra("title", video.name)
|
|
||||||
val link = result.links[index!!]
|
|
||||||
val headers = link.headers
|
|
||||||
|
|
||||||
setData(link.url.toUri())
|
|
||||||
if (headers.isNotEmpty()) {
|
|
||||||
// PlayerActivity expects a flat array: [key1, value1, key2, value2, ...]
|
|
||||||
val flat = headers.entries.flatMap { listOf(it.key, it.value) }.toTypedArray()
|
|
||||||
intent.putExtra("headers", flat)
|
|
||||||
}
|
|
||||||
/*val subs = result.subs // disabled due to https://github.com/Riteshp2001/mpvRx/issues/146
|
|
||||||
intent.putExtra("subs", subs.map { it.url.toUri() }.toTypedArray())
|
|
||||||
intent.putExtra(
|
|
||||||
"subs.titles",
|
|
||||||
subs.map { it.name }.toTypedArray(),
|
|
||||||
)
|
|
||||||
intent.putExtra(
|
|
||||||
"subs.langs",
|
|
||||||
subs.map { it.languageCode }.toTypedArray(),
|
|
||||||
)
|
|
||||||
val selected = subs.firstOrNull { it.matchesLanguageCode("en") }?.url?.toUri()
|
|
||||||
intent.putExtra("subs.enable", selected?.let { arrayOf(it) } ?: arrayOf<Uri>() )*/
|
|
||||||
|
|
||||||
if (video.tvType.isEpisodeBased()) {
|
|
||||||
video.season?.let { intent.putExtra("introdb_season", it) }
|
|
||||||
video.episode.let { intent.putExtra("introdb_episode", it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
val position = getViewPos(video.id)?.position
|
|
||||||
if (position != null)
|
|
||||||
putExtra("position", position.toInt())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResult(activity: Activity, intent: Intent?) {
|
|
||||||
val position = intent?.getIntExtra("position", -1) ?: -1
|
|
||||||
val duration = intent?.getIntExtra("duration", -1) ?: -1
|
|
||||||
Log.d("MPV", "Position: $position, Duration: $duration")
|
|
||||||
updateDurationAndPosition(position.toLong(), duration.toLong())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.actions.temp
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.core.net.toUri
|
|
||||||
import com.lagradost.cloudstream3.actions.OpenInAppAction
|
|
||||||
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
|
|
||||||
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
|
||||||
|
|
||||||
/** https://github.com/Kindness-Kismet/only_player/tree/main
|
|
||||||
* https://github.com/Kindness-Kismet/only_player/blob/main/feature/player/src/main/java/one/only/player/feature/player/PlayerActivity.kt */
|
|
||||||
class OnlyPlayer : OpenInAppAction(
|
|
||||||
txt("Only Player"),
|
|
||||||
"one.only.player",
|
|
||||||
intentClass = "one.only.player.feature.player.PlayerActivity"
|
|
||||||
) {
|
|
||||||
override val oneSource = true
|
|
||||||
override suspend fun putExtra(
|
|
||||||
context: Context,
|
|
||||||
intent: Intent,
|
|
||||||
video: ResultEpisode,
|
|
||||||
result: LinkLoadingResult,
|
|
||||||
index: Int?
|
|
||||||
) {
|
|
||||||
/** https://github.com/Kindness-Kismet/only_player/blob/d3f55049a2913fa762d31b311146073cc2da46cb/app/src/main/java/one/only/player/navigation/CloudNavGraph.kt#L39 */
|
|
||||||
intent.apply {
|
|
||||||
val link = result.links[index!!]
|
|
||||||
setData(link.url.toUri())
|
|
||||||
|
|
||||||
putExtra("headers", Bundle().apply {
|
|
||||||
for ((key, value) in link.headers) {
|
|
||||||
putExtra(key, value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResult(activity: Activity, intent: Intent?) {
|
|
||||||
/* onResult does not get called */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -60,7 +60,7 @@ open class VlcPackage: OpenInAppAction(
|
||||||
intent.putExtra("secure_uri", true)
|
intent.putExtra("secure_uri", true)
|
||||||
intent.putExtra("title", video.name)
|
intent.putExtra("title", video.name)
|
||||||
|
|
||||||
val subsLang = getKey<String>(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
|
val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
|
||||||
result.subs.firstOrNull {
|
result.subs.firstOrNull {
|
||||||
subsLang == it.languageCode
|
subsLang == it.languageCode
|
||||||
}?.let {
|
}?.let {
|
||||||
|
|
@ -74,4 +74,4 @@ open class VlcPackage: OpenInAppAction(
|
||||||
Log.d("VLC", "Position: $position, Duration: $duration")
|
Log.d("VLC", "Position: $position, Duration: $duration")
|
||||||
updateDurationAndPosition(position, duration)
|
updateDurationAndPosition(position, duration)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,9 +1,5 @@
|
||||||
package com.lagradost.cloudstream3.actions.temp.fcast
|
package com.lagradost.cloudstream3.actions.temp.fcast
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
// See https://gitlab.com/futo-org/fcast/-/wikis/Protocol-version-1
|
// See https://gitlab.com/futo-org/fcast/-/wikis/Protocol-version-1
|
||||||
enum class Opcode(val value: Byte) {
|
enum class Opcode(val value: Byte) {
|
||||||
None(0),
|
None(0),
|
||||||
|
|
@ -22,18 +18,18 @@ enum class Opcode(val value: Byte) {
|
||||||
Pong(13);
|
Pong(13);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class PlayMessage(
|
data class PlayMessage(
|
||||||
@JsonProperty("container") @SerialName("container") val container: String,
|
val container: String,
|
||||||
@JsonProperty("url") @SerialName("url") val url: String? = null,
|
val url: String? = null,
|
||||||
@JsonProperty("content") @SerialName("content") val content: String? = null,
|
val content: String? = null,
|
||||||
@JsonProperty("time") @SerialName("time") val time: Double? = null,
|
val time: Double? = null,
|
||||||
@JsonProperty("speed") @SerialName("speed") val speed: Double? = null,
|
val speed: Double? = null,
|
||||||
@JsonProperty("headers") @SerialName("headers") val headers: Map<String, String>? = null,
|
val headers: Map<String, String>? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
data class SeekMessage(
|
data class SeekMessage(
|
||||||
val time: Double,
|
val time: Double
|
||||||
)
|
)
|
||||||
|
|
||||||
data class PlaybackUpdateMessage(
|
data class PlaybackUpdateMessage(
|
||||||
|
|
@ -41,26 +37,26 @@ data class PlaybackUpdateMessage(
|
||||||
val time: Double,
|
val time: Double,
|
||||||
val duration: Double,
|
val duration: Double,
|
||||||
val state: Int,
|
val state: Int,
|
||||||
val speed: Double,
|
val speed: Double
|
||||||
)
|
)
|
||||||
|
|
||||||
data class VolumeUpdateMessage(
|
data class VolumeUpdateMessage(
|
||||||
val generationTime: Long,
|
val generationTime: Long,
|
||||||
val volume: Double,
|
val volume: Double
|
||||||
)
|
)
|
||||||
|
|
||||||
data class PlaybackErrorMessage(
|
data class PlaybackErrorMessage(
|
||||||
val message: String,
|
val message: String
|
||||||
)
|
)
|
||||||
|
|
||||||
data class SetSpeedMessage(
|
data class SetSpeedMessage(
|
||||||
val speed: Double,
|
val speed: Double
|
||||||
)
|
)
|
||||||
|
|
||||||
data class SetVolumeMessage(
|
data class SetVolumeMessage(
|
||||||
val volume: Double,
|
val volume: Double
|
||||||
)
|
)
|
||||||
|
|
||||||
data class VersionMessage(
|
data class VersionMessage(
|
||||||
val version: Long,
|
val version: Long
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ fun Requests.initClient(context: Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Only use ignoreSSL if you know what you are doing*/
|
/** Only use ignoreSSL if you know what you are doing*/
|
||||||
|
@Prerelease
|
||||||
fun Requests.initClient(context: Context, ignoreSSL: Boolean = false) {
|
fun Requests.initClient(context: Context, ignoreSSL: Boolean = false) {
|
||||||
this.baseClient = buildDefaultClient(context, ignoreSSL)
|
this.baseClient = buildDefaultClient(context, ignoreSSL)
|
||||||
}
|
}
|
||||||
|
|
@ -33,11 +34,12 @@ fun buildDefaultClient(context: Context): OkHttpClient {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Only use ignoreSSL if you know what you are doing*/
|
/** Only use ignoreSSL if you know what you are doing*/
|
||||||
|
@Prerelease
|
||||||
fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClient {
|
fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClient {
|
||||||
safe { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
|
safe { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
|
||||||
|
|
||||||
val settingsManager = PreferenceManager.getDefaultSharedPreferences(context)
|
val settingsManager = PreferenceManager.getDefaultSharedPreferences(context)
|
||||||
val dns = settingsManager.getInt(context.getString(R.string.dns_key), 0)
|
val dns = settingsManager.getInt(context.getString(R.string.dns_pref), 0)
|
||||||
val baseClient = OkHttpClient.Builder()
|
val baseClient = OkHttpClient.Builder()
|
||||||
.followRedirects(true)
|
.followRedirects(true)
|
||||||
.followSslRedirects(true)
|
.followSslRedirects(true)
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import com.lagradost.cloudstream3.actions.VideoClickAction
|
||||||
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
|
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
|
||||||
import kotlin.Throws
|
import kotlin.Throws
|
||||||
|
|
||||||
|
|
||||||
abstract class Plugin : BasePlugin() {
|
abstract class Plugin : BasePlugin() {
|
||||||
/**
|
/**
|
||||||
* Called when your Plugin is loaded
|
* Called when your Plugin is loaded
|
||||||
|
|
@ -25,7 +26,9 @@ abstract class Plugin : BasePlugin() {
|
||||||
fun registerVideoClickAction(element: VideoClickAction) {
|
fun registerVideoClickAction(element: VideoClickAction) {
|
||||||
Log.i(PLUGIN_TAG, "Adding ${element.name} VideoClickAction")
|
Log.i(PLUGIN_TAG, "Adding ${element.name} VideoClickAction")
|
||||||
element.sourcePlugin = this.filename
|
element.sourcePlugin = this.filename
|
||||||
VideoClickActionHolder.allVideoClickActions.add(element)
|
synchronized(VideoClickActionHolder.allVideoClickActions) {
|
||||||
|
VideoClickActionHolder.allVideoClickActions.add(element)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -37,4 +40,4 @@ abstract class Plugin : BasePlugin() {
|
||||||
* This will add a button in the settings allowing you to add custom settings
|
* This will add a button in the settings allowing you to add custom settings
|
||||||
*/
|
*/
|
||||||
var openSettings: ((context: Context) -> Unit)? = null
|
var openSettings: ((context: Context) -> Unit)? = null
|
||||||
}
|
}
|
||||||
|
|
@ -61,8 +61,6 @@ import com.lagradost.cloudstream3.utils.txt
|
||||||
import dalvik.system.PathClassLoader
|
import dalvik.system.PathClassLoader
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
|
|
||||||
|
|
@ -75,13 +73,12 @@ const val EXTENSIONS_CHANNEL_NAME = "Extensions"
|
||||||
const val EXTENSIONS_CHANNEL_DESCRIPT = "Extension notification channel"
|
const val EXTENSIONS_CHANNEL_DESCRIPT = "Extension notification channel"
|
||||||
|
|
||||||
// Data class for internal storage
|
// Data class for internal storage
|
||||||
@Serializable
|
|
||||||
data class PluginData(
|
data class PluginData(
|
||||||
@JsonProperty("internalName") @SerialName("internalName") val internalName: String,
|
@JsonProperty("internalName") val internalName: String,
|
||||||
@JsonProperty("url") @SerialName("url") val url: String?,
|
@JsonProperty("url") val url: String?,
|
||||||
@JsonProperty("isOnline") @SerialName("isOnline") val isOnline: Boolean,
|
@JsonProperty("isOnline") val isOnline: Boolean,
|
||||||
@JsonProperty("filePath") @SerialName("filePath") val filePath: String,
|
@JsonProperty("filePath") val filePath: String,
|
||||||
@JsonProperty("version") @SerialName("version") val version: Int,
|
@JsonProperty("version") val version: Int,
|
||||||
) {
|
) {
|
||||||
@WorkerThread
|
@WorkerThread
|
||||||
fun toSitePlugin(): SitePlugin {
|
fun toSitePlugin(): SitePlugin {
|
||||||
|
|
@ -176,11 +173,11 @@ object PluginManager {
|
||||||
|
|
||||||
|
|
||||||
fun getPluginsOnline(): Array<PluginData> {
|
fun getPluginsOnline(): Array<PluginData> {
|
||||||
return getKey<Array<PluginData>>(PLUGINS_KEY) ?: emptyArray()
|
return getKey(PLUGINS_KEY) ?: emptyArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getPluginsLocal(): Array<PluginData> {
|
fun getPluginsLocal(): Array<PluginData> {
|
||||||
return getKey<Array<PluginData>>(PLUGINS_KEY_LOCAL) ?: emptyArray()
|
return getKey(PLUGINS_KEY_LOCAL) ?: emptyArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
private val CLOUD_STREAM_FOLDER =
|
private val CLOUD_STREAM_FOLDER =
|
||||||
|
|
@ -224,17 +221,17 @@ object PluginManager {
|
||||||
// Helper class for updateAllOnlinePluginsAndLoadThem
|
// Helper class for updateAllOnlinePluginsAndLoadThem
|
||||||
data class OnlinePluginData(
|
data class OnlinePluginData(
|
||||||
val savedData: PluginData,
|
val savedData: PluginData,
|
||||||
val onlineData: PluginWrapper,
|
val onlineData: Pair<String, SitePlugin>,
|
||||||
) {
|
) {
|
||||||
val isOutdated =
|
val isOutdated =
|
||||||
onlineData.plugin.version > savedData.version || onlineData.plugin.version == PLUGIN_VERSION_ALWAYS_UPDATE
|
onlineData.second.version > savedData.version || onlineData.second.version == PLUGIN_VERSION_ALWAYS_UPDATE
|
||||||
val isDisabled = onlineData.plugin.status == PROVIDER_STATUS_DOWN
|
val isDisabled = onlineData.second.status == PROVIDER_STATUS_DOWN
|
||||||
|
|
||||||
fun validOnlineData(context: Context): Boolean {
|
fun validOnlineData(context: Context): Boolean {
|
||||||
return getPluginPath(
|
return getPluginPath(
|
||||||
context,
|
context,
|
||||||
savedData.internalName,
|
savedData.internalName,
|
||||||
onlineData.repositoryData.url
|
onlineData.first
|
||||||
).absolutePath == savedData.filePath
|
).absolutePath == savedData.filePath
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -282,19 +279,19 @@ object PluginManager {
|
||||||
?: emptyArray()) + PREBUILT_REPOSITORIES
|
?: emptyArray()) + PREBUILT_REPOSITORIES
|
||||||
|
|
||||||
val onlinePlugins = urls.toList().amap {
|
val onlinePlugins = urls.toList().amap {
|
||||||
getRepoPlugins(it) ?: emptyList()
|
getRepoPlugins(it.url)?.toList() ?: emptyList()
|
||||||
}.flatten().distinctBy { it.plugin.url }
|
}.flatten().distinctBy { it.second.url }
|
||||||
|
|
||||||
// Iterates over all offline plugins, compares to remote repo and returns the plugins which are outdated
|
// Iterates over all offline plugins, compares to remote repo and returns the plugins which are outdated
|
||||||
val outdatedPlugins = getPluginsOnline().map { savedData ->
|
val outdatedPlugins = getPluginsOnline().map { savedData ->
|
||||||
onlinePlugins
|
onlinePlugins
|
||||||
.filter { onlineData -> savedData.internalName == onlineData.plugin.internalName }
|
.filter { onlineData -> savedData.internalName == onlineData.second.internalName }
|
||||||
.map { onlineData ->
|
.map { onlineData ->
|
||||||
OnlinePluginData(savedData, onlineData)
|
OnlinePluginData(savedData, onlineData)
|
||||||
}.filter {
|
}.filter {
|
||||||
it.validOnlineData(activity)
|
it.validOnlineData(activity)
|
||||||
}
|
}
|
||||||
}.flatten().distinctBy { it.onlineData.plugin.url }
|
}.flatten().distinctBy { it.onlineData.second.url }
|
||||||
|
|
||||||
debugPrint {
|
debugPrint {
|
||||||
"Outdated plugins: ${outdatedPlugins.filter { it.isOutdated }}"
|
"Outdated plugins: ${outdatedPlugins.filter { it.isOutdated }}"
|
||||||
|
|
@ -309,14 +306,14 @@ object PluginManager {
|
||||||
} else if (pluginData.isOutdated) {
|
} else if (pluginData.isOutdated) {
|
||||||
downloadPlugin(
|
downloadPlugin(
|
||||||
activity,
|
activity,
|
||||||
pluginData.onlineData.plugin.url,
|
pluginData.onlineData.second.url,
|
||||||
pluginData.onlineData.plugin.fileHash,
|
pluginData.onlineData.second.fileHash,
|
||||||
pluginData.savedData.internalName,
|
pluginData.savedData.internalName,
|
||||||
File(pluginData.savedData.filePath),
|
File(pluginData.savedData.filePath),
|
||||||
true
|
true
|
||||||
).let { success ->
|
).let { success ->
|
||||||
if (success)
|
if (success)
|
||||||
updatedPlugins.add(pluginData.onlineData.plugin.name)
|
updatedPlugins.add(pluginData.onlineData.second.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -359,15 +356,15 @@ object PluginManager {
|
||||||
val urls = (getKey<Array<RepositoryData>>(REPOSITORIES_KEY)
|
val urls = (getKey<Array<RepositoryData>>(REPOSITORIES_KEY)
|
||||||
?: emptyArray()) + PREBUILT_REPOSITORIES
|
?: emptyArray()) + PREBUILT_REPOSITORIES
|
||||||
val onlinePlugins = urls.toList().amap {
|
val onlinePlugins = urls.toList().amap {
|
||||||
getRepoPlugins(it)?.toList() ?: emptyList()
|
getRepoPlugins(it.url)?.toList() ?: emptyList()
|
||||||
}.flatten().distinctBy { it.plugin.url }
|
}.flatten().distinctBy { it.second.url }
|
||||||
|
|
||||||
val providerLang = activity.getApiProviderLangSettings()
|
val providerLang = activity.getApiProviderLangSettings()
|
||||||
//Log.i(TAG, "providerLang => ${providerLang.toJson()}")
|
//Log.i(TAG, "providerLang => ${providerLang.toJson()}")
|
||||||
|
|
||||||
// Iterate online repos and returns not downloaded plugins
|
// Iterate online repos and returns not downloaded plugins
|
||||||
val notDownloadedPlugins = onlinePlugins.mapNotNull { onlineData ->
|
val notDownloadedPlugins = onlinePlugins.mapNotNull { onlineData ->
|
||||||
val sitePlugin = onlineData.plugin
|
val sitePlugin = onlineData.second
|
||||||
val tvtypes = sitePlugin.tvTypes ?: listOf()
|
val tvtypes = sitePlugin.tvTypes ?: listOf()
|
||||||
|
|
||||||
//Don't include empty urls
|
//Don't include empty urls
|
||||||
|
|
@ -379,7 +376,7 @@ object PluginManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
//Omit already existing plugins
|
//Omit already existing plugins
|
||||||
if (getPluginPath(activity, sitePlugin.internalName, onlineData.repositoryData.url).exists()) {
|
if (getPluginPath(activity, sitePlugin.internalName, onlineData.first).exists()) {
|
||||||
Log.i(TAG, "Skip > ${sitePlugin.internalName}")
|
Log.i(TAG, "Skip > ${sitePlugin.internalName}")
|
||||||
return@mapNotNull null
|
return@mapNotNull null
|
||||||
}
|
}
|
||||||
|
|
@ -421,14 +418,14 @@ object PluginManager {
|
||||||
notDownloadedPlugins.amap { pluginData ->
|
notDownloadedPlugins.amap { pluginData ->
|
||||||
downloadPlugin(
|
downloadPlugin(
|
||||||
activity,
|
activity,
|
||||||
pluginData.onlineData.plugin.url,
|
pluginData.onlineData.second.url,
|
||||||
pluginData.onlineData.plugin.fileHash,
|
pluginData.onlineData.second.fileHash,
|
||||||
pluginData.savedData.internalName,
|
pluginData.savedData.internalName,
|
||||||
pluginData.onlineData.repositoryData.url,
|
pluginData.onlineData.first,
|
||||||
!pluginData.isDisabled
|
!pluginData.isDisabled
|
||||||
).let { success ->
|
).let { success ->
|
||||||
if (success)
|
if (success)
|
||||||
newDownloadPlugins.add(pluginData.onlineData.plugin.name)
|
newDownloadPlugins.add(pluginData.onlineData.second.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -512,9 +509,6 @@ object PluginManager {
|
||||||
val res = dir.mkdirs()
|
val res = dir.mkdirs()
|
||||||
if (!res) {
|
if (!res) {
|
||||||
Log.w(TAG, "Failed to create local directories")
|
Log.w(TAG, "Failed to create local directories")
|
||||||
// We have tried to load local plugins, but exit early.
|
|
||||||
// This needs to be true to prevent the downloader waiting for plugins.
|
|
||||||
loadedLocalPlugins = true
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -590,7 +584,7 @@ object PluginManager {
|
||||||
/**
|
/**
|
||||||
* @return True if successful, false if not
|
* @return True if successful, false if not
|
||||||
* */
|
* */
|
||||||
internal suspend fun loadPlugin(context: Context, file: File, data: PluginData): Boolean {
|
private suspend fun loadPlugin(context: Context, file: File, data: PluginData): Boolean {
|
||||||
val fileName = file.nameWithoutExtension
|
val fileName = file.nameWithoutExtension
|
||||||
val filePath = file.absolutePath
|
val filePath = file.absolutePath
|
||||||
currentlyLoading = fileName
|
currentlyLoading = fileName
|
||||||
|
|
@ -616,7 +610,7 @@ object PluginManager {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
InputStreamReader(stream).use { reader ->
|
InputStreamReader(stream).use { reader ->
|
||||||
manifest = parseJson<BasePlugin.Manifest>(reader.readText())
|
manifest = parseJson(reader, BasePlugin.Manifest::class.java)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -657,15 +651,9 @@ object PluginManager {
|
||||||
context.resources.configuration
|
context.resources.configuration
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
synchronized(plugins) {
|
plugins[filePath] = pluginInstance
|
||||||
plugins[filePath] = pluginInstance
|
classLoaders[loader] = pluginInstance
|
||||||
}
|
urlPlugins[data.url ?: filePath] = pluginInstance
|
||||||
synchronized(classLoaders) {
|
|
||||||
classLoaders[loader] = pluginInstance
|
|
||||||
}
|
|
||||||
synchronized(urlPlugins) {
|
|
||||||
urlPlugins[data.url ?: filePath] = pluginInstance
|
|
||||||
}
|
|
||||||
if (pluginInstance is Plugin) {
|
if (pluginInstance is Plugin) {
|
||||||
pluginInstance.load(context)
|
pluginInstance.load(context)
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -701,20 +689,21 @@ object PluginManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove all registered apis
|
// remove all registered apis
|
||||||
APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
|
synchronized(APIHolder.apis) {
|
||||||
removePluginMapping(it)
|
APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
|
||||||
|
removePluginMapping(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
synchronized(APIHolder.allProviders) {
|
||||||
|
APIHolder.allProviders.removeIf { provider: MainAPI -> provider.sourcePlugin == plugin.filename }
|
||||||
}
|
}
|
||||||
|
|
||||||
APIHolder.allProviders.withLock {
|
synchronized(extractorApis) {
|
||||||
APIHolder.allProviders.removeAll { provider -> provider.sourcePlugin == plugin.filename }
|
extractorApis.removeIf { provider: ExtractorApi -> provider.sourcePlugin == plugin.filename }
|
||||||
}
|
}
|
||||||
|
|
||||||
extractorApis.withLock {
|
synchronized(VideoClickActionHolder.allVideoClickActions) {
|
||||||
extractorApis.removeAll { provider -> provider.sourcePlugin == plugin.filename }
|
VideoClickActionHolder.allVideoClickActions.removeIf { action: VideoClickAction -> action.sourcePlugin == plugin.filename }
|
||||||
}
|
|
||||||
|
|
||||||
VideoClickActionHolder.allVideoClickActions.withLock {
|
|
||||||
VideoClickActionHolder.allVideoClickActions.removeAll { action -> action.sourcePlugin == plugin.filename }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized(classLoaders) {
|
synchronized(classLoaders) {
|
||||||
|
|
@ -838,16 +827,16 @@ object PluginManager {
|
||||||
val urls = (getKey<Array<RepositoryData>>(REPOSITORIES_KEY)
|
val urls = (getKey<Array<RepositoryData>>(REPOSITORIES_KEY)
|
||||||
?: emptyArray()) + PREBUILT_REPOSITORIES
|
?: emptyArray()) + PREBUILT_REPOSITORIES
|
||||||
val onlinePlugins = urls.toList().amap {
|
val onlinePlugins = urls.toList().amap {
|
||||||
getRepoPlugins(it) ?: emptyList()
|
getRepoPlugins(it.url)?.toList() ?: emptyList()
|
||||||
}.flatten().distinctBy { it.plugin.url }
|
}.flatten().distinctBy { it.second.url }
|
||||||
|
|
||||||
val allPlugins = getPluginsOnline().flatMap { savedData ->
|
val allPlugins = getPluginsOnline().flatMap { savedData ->
|
||||||
onlinePlugins
|
onlinePlugins
|
||||||
.filter { it.plugin.internalName == savedData.internalName }
|
.filter { it.second.internalName == savedData.internalName }
|
||||||
.mapNotNull { onlineData ->
|
.mapNotNull { onlineData ->
|
||||||
OnlinePluginData(savedData, onlineData).takeIf { it.validOnlineData(activity) }
|
OnlinePluginData(savedData, onlineData).takeIf { it.validOnlineData(activity) }
|
||||||
}
|
}
|
||||||
}.distinctBy { it.onlineData.plugin.url }
|
}.distinctBy { it.onlineData.second.url }
|
||||||
|
|
||||||
val updatedPlugins = mutableListOf<String>()
|
val updatedPlugins = mutableListOf<String>()
|
||||||
|
|
||||||
|
|
@ -855,7 +844,7 @@ object PluginManager {
|
||||||
if (pluginData.isDisabled) {
|
if (pluginData.isDisabled) {
|
||||||
Log.e(
|
Log.e(
|
||||||
"PluginManager",
|
"PluginManager",
|
||||||
"Unloading disabled plugin: ${pluginData.onlineData.plugin.name}"
|
"Unloading disabled plugin: ${pluginData.onlineData.second.name}"
|
||||||
)
|
)
|
||||||
unloadPlugin(pluginData.savedData.filePath)
|
unloadPlugin(pluginData.savedData.filePath)
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -864,14 +853,14 @@ object PluginManager {
|
||||||
|
|
||||||
if (downloadPlugin(
|
if (downloadPlugin(
|
||||||
activity,
|
activity,
|
||||||
pluginData.onlineData.plugin.url,
|
pluginData.onlineData.second.url,
|
||||||
pluginData.onlineData.plugin.fileHash,
|
pluginData.onlineData.second.fileHash,
|
||||||
pluginData.savedData.internalName,
|
pluginData.savedData.internalName,
|
||||||
existingFile,
|
existingFile,
|
||||||
true
|
true
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
updatedPlugins.add(pluginData.onlineData.plugin.name)
|
updatedPlugins.add(pluginData.onlineData.second.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.also {
|
}.also {
|
||||||
|
|
|
||||||
|
|
@ -16,27 +16,26 @@ import com.lagradost.cloudstream3.plugins.PluginManager.getPluginSanitizedFileNa
|
||||||
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
|
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
|
||||||
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
|
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
|
||||||
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
|
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
|
||||||
|
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.nio.file.AtomicMoveNotSupportedException
|
import java.nio.file.AtomicMoveNotSupportedException
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.StandardCopyOption
|
import java.nio.file.StandardCopyOption
|
||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Comes with the app, always available in the app, non removable.
|
* Comes with the app, always available in the app, non removable.
|
||||||
*/
|
* */
|
||||||
@Serializable
|
|
||||||
data class Repository(
|
data class Repository(
|
||||||
@JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
|
@JsonProperty("iconUrl") val iconUrl: String?,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("description") @SerialName("description") val description: String?,
|
@JsonProperty("description") val description: String?,
|
||||||
@JsonProperty("manifestVersion") @SerialName("manifestVersion") val manifestVersion: Int,
|
@JsonProperty("manifestVersion") val manifestVersion: Int,
|
||||||
@JsonProperty("pluginLists") @SerialName("pluginLists") val pluginLists: List<String>,
|
@JsonProperty("pluginLists") val pluginLists: List<String>
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -45,60 +44,40 @@ data class Repository(
|
||||||
* 1: Ok
|
* 1: Ok
|
||||||
* 2: Slow
|
* 2: Slow
|
||||||
* 3: Beta only
|
* 3: Beta only
|
||||||
*/
|
* */
|
||||||
@Serializable
|
|
||||||
data class SitePlugin(
|
data class SitePlugin(
|
||||||
// Url to the .cs3 file
|
// Url to the .cs3 file
|
||||||
@JsonProperty("url") @SerialName("url") val url: String,
|
@JsonProperty("url") val url: String,
|
||||||
// Status to remotely disable the provider
|
// Status to remotely disable the provider
|
||||||
@JsonProperty("status") @SerialName("status") val status: Int,
|
@JsonProperty("status") val status: Int,
|
||||||
// Integer over 0, any change of this will trigger an auto update
|
// Integer over 0, any change of this will trigger an auto update
|
||||||
@JsonProperty("version") @SerialName("version") val version: Int,
|
@JsonProperty("version") val version: Int,
|
||||||
// Unused currently, used to make the api backwards compatible?
|
// Unused currently, used to make the api backwards compatible?
|
||||||
// Set to 1
|
// Set to 1
|
||||||
@JsonProperty("apiVersion") @SerialName("apiVersion") val apiVersion: Int,
|
@JsonProperty("apiVersion") val apiVersion: Int,
|
||||||
// Name to be shown in app
|
// Name to be shown in app
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
// Name to be referenced internally. Separate to make name and url changes possible
|
// Name to be referenced internally. Separate to make name and url changes possible
|
||||||
@JsonProperty("internalName") @SerialName("internalName") val internalName: String,
|
@JsonProperty("internalName") val internalName: String,
|
||||||
@JsonProperty("authors") @SerialName("authors") val authors: List<String>,
|
@JsonProperty("authors") val authors: List<String>,
|
||||||
@JsonProperty("description") @SerialName("description") val description: String?,
|
@JsonProperty("description") val description: String?,
|
||||||
// Might be used to go directly to the plugin repo in the future
|
// Might be used to go directly to the plugin repo in the future
|
||||||
@JsonProperty("repositoryUrl") @SerialName("repositoryUrl") val repositoryUrl: String?,
|
@JsonProperty("repositoryUrl") val repositoryUrl: String?,
|
||||||
// These types are yet to be mapped and used, ignore for now
|
// These types are yet to be mapped and used, ignore for now
|
||||||
@JsonProperty("tvTypes") @SerialName("tvTypes") val tvTypes: List<String>?,
|
@JsonProperty("tvTypes") val tvTypes: List<String>?,
|
||||||
// Most often a language tag like "en" or "zh-TW"
|
// Most often a language tag like "en" or "zh-TW"
|
||||||
@JsonProperty("language") @SerialName("language") val language: String?,
|
@JsonProperty("language") val language: String?,
|
||||||
@JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
|
@JsonProperty("iconUrl") val iconUrl: String?,
|
||||||
// Automatically generated by the gradle plugin
|
// Automatically generated by the gradle plugin
|
||||||
@JsonProperty("fileSize") @SerialName("fileSize") val fileSize: Long?,
|
@JsonProperty("fileSize") val fileSize: Long?,
|
||||||
@JsonProperty("fileHash") @SerialName("fileHash") val fileHash: String?,
|
@JsonProperty("fileHash") val fileHash: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class PluginWrapper(
|
|
||||||
@JsonProperty("repository") @SerialName("repository") val repository: Repository,
|
|
||||||
@JsonProperty("repositoryData") @SerialName("repositoryData") val repositoryData: RepositoryData,
|
|
||||||
@JsonProperty("plugin") @SerialName("plugin") val plugin: SitePlugin
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
private val localRepository = Repository("", "", "", 1, emptyList())
|
|
||||||
private val localRepositoryData = RepositoryData("", "", "")
|
|
||||||
fun getLocalPluginWrapper(plugin: SitePlugin): PluginWrapper {
|
|
||||||
return PluginWrapper(
|
|
||||||
localRepository,
|
|
||||||
localRepositoryData,
|
|
||||||
plugin
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
object RepositoryManager {
|
object RepositoryManager {
|
||||||
const val ONLINE_PLUGINS_FOLDER = "Extensions"
|
const val ONLINE_PLUGINS_FOLDER = "Extensions"
|
||||||
val PREBUILT_REPOSITORIES: Array<RepositoryData> by lazy {
|
val PREBUILT_REPOSITORIES: Array<RepositoryData> by lazy {
|
||||||
getKey<Array<RepositoryData>>("PREBUILT_REPOSITORIES") ?: emptyArray()
|
getKey("PREBUILT_REPOSITORIES") ?: emptyArray()
|
||||||
}
|
}
|
||||||
private val GH_REGEX =
|
private val GH_REGEX =
|
||||||
Regex("^https://raw.githubusercontent.com/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/(.*)$")
|
Regex("^https://raw.githubusercontent.com/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/(.*)$")
|
||||||
|
|
@ -141,18 +120,12 @@ object RepositoryManager {
|
||||||
}
|
}
|
||||||
} else if (fixedUrl.matches("^[a-zA-Z0-9!_-]+$".toRegex())) {
|
} else if (fixedUrl.matches("^[a-zA-Z0-9!_-]+$".toRegex())) {
|
||||||
safeAsync {
|
safeAsync {
|
||||||
if (fixedUrl.startsWith("!")) {
|
app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false).let { it2 ->
|
||||||
val response = app.get("https://py.md/${fixedUrl.removePrefix("!")}", allowRedirects = false)
|
it2.headers["Location"]?.let { url ->
|
||||||
val url = response.headers["Location"] ?: return@safeAsync null
|
if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
|
||||||
if (url.startsWith("https://py.md/404")) return@safeAsync null
|
if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
|
||||||
if (url.removeSuffix("/") == "https://py.md") return@safeAsync null
|
return@safeAsync url
|
||||||
return@safeAsync url
|
}
|
||||||
} else {
|
|
||||||
val response = app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false)
|
|
||||||
val url = response.headers["Location"] ?: return@safeAsync null
|
|
||||||
if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
|
|
||||||
if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
|
|
||||||
return@safeAsync url
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else null
|
} else null
|
||||||
|
|
@ -161,16 +134,17 @@ object RepositoryManager {
|
||||||
suspend fun parseRepository(url: String): Repository? {
|
suspend fun parseRepository(url: String): Repository? {
|
||||||
return safeAsync {
|
return safeAsync {
|
||||||
// Take manifestVersion and such into account later
|
// Take manifestVersion and such into account later
|
||||||
app.get(convertRawGitUrl(url), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
|
app.get(convertRawGitUrl(url)).parsedSafe()
|
||||||
.parsedSafe<Repository>()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun parsePlugins(pluginUrls: String): List<SitePlugin> {
|
private suspend fun parsePlugins(pluginUrls: String): List<SitePlugin> {
|
||||||
// Take manifestVersion and such into account later
|
// Take manifestVersion and such into account later
|
||||||
return try {
|
return try {
|
||||||
app.get(convertRawGitUrl(pluginUrls), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
|
val response = app.get(convertRawGitUrl(pluginUrls))
|
||||||
.parsed<Array<SitePlugin>>().toList()
|
// Normal parsed function not working?
|
||||||
|
// return response.parsedSafe()
|
||||||
|
tryParseJson<Array<SitePlugin>>(response.text)?.toList() ?: emptyList()
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
logError(t)
|
logError(t)
|
||||||
emptyList()
|
emptyList()
|
||||||
|
|
@ -179,17 +153,17 @@ object RepositoryManager {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets all plugins from repositories and pairs them with the repository url
|
* Gets all plugins from repositories and pairs them with the repository url
|
||||||
*/
|
* */
|
||||||
suspend fun getRepoPlugins(repositoryData: RepositoryData): List<PluginWrapper>? {
|
suspend fun getRepoPlugins(repositoryUrl: String): List<Pair<String, SitePlugin>>? {
|
||||||
val repo = parseRepository(repositoryData.url) ?: return null
|
val repo = parseRepository(repositoryUrl) ?: return null
|
||||||
val list = repo.pluginLists.amap { url ->
|
return repo.pluginLists.amap { url ->
|
||||||
parsePlugins(url).map {
|
parsePlugins(url).map {
|
||||||
PluginWrapper(repo, repositoryData, it)
|
repositoryUrl to it
|
||||||
}
|
}
|
||||||
}.flatten()
|
}.flatten()
|
||||||
return list
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
suspend fun downloadPluginToFile(
|
suspend fun downloadPluginToFile(
|
||||||
context: Context,
|
context: Context,
|
||||||
pluginUrl: String,
|
pluginUrl: String,
|
||||||
|
|
@ -240,29 +214,22 @@ object RepositoryManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getRepositories(): Array<RepositoryData> {
|
fun getRepositories(): Array<RepositoryData> {
|
||||||
return getKey<Array<RepositoryData>>(REPOSITORIES_KEY) ?: emptyArray()
|
return getKey(REPOSITORIES_KEY) ?: emptyArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't want to read before we write in another thread
|
// Don't want to read before we write in another thread
|
||||||
private val repoLock = Mutex()
|
private val repoLock = Mutex()
|
||||||
suspend fun addRepository(repository: RepositoryData) {
|
suspend fun addRepository(repository: RepositoryData) {
|
||||||
repoLock.withLock {
|
repoLock.withLock {
|
||||||
// No duplicates, but we want the new repository instead of the old one
|
val currentRepos = getRepositories()
|
||||||
var currentRepos = getRepositories()
|
// No duplicates
|
||||||
val index = currentRepos.indexOfFirst { it.url == repository.url }
|
setKey(REPOSITORIES_KEY, (currentRepos + repository).distinctBy { it.url })
|
||||||
if(index == -1) {
|
|
||||||
currentRepos += repository
|
|
||||||
} else {
|
|
||||||
/** We want to keep the ordering here, as that is the addition order */
|
|
||||||
currentRepos[index] = repository
|
|
||||||
}
|
|
||||||
setKey(REPOSITORIES_KEY, currentRepos)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Also deletes downloaded repository plugins
|
* Also deletes downloaded repository plugins
|
||||||
*/
|
* */
|
||||||
suspend fun removeRepository(context: Context, repository: RepositoryData) {
|
suspend fun removeRepository(context: Context, repository: RepositoryData) {
|
||||||
val extensionsDir = File(context.filesDir, ONLINE_PLUGINS_FOLDER)
|
val extensionsDir = File(context.filesDir, ONLINE_PLUGINS_FOLDER)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package com.lagradost.cloudstream3.plugins
|
||||||
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
|
|
@ -12,10 +11,9 @@ import com.lagradost.cloudstream3.app
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.main
|
import com.lagradost.cloudstream3.utils.Coroutines.main
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
object VotingApi {
|
object VotingApi {
|
||||||
|
|
||||||
private const val LOGKEY = "VotingApi"
|
private const val LOGKEY = "VotingApi"
|
||||||
private const val API_DOMAIN = "https://api.countify.xyz"
|
private const val API_DOMAIN = "https://api.countify.xyz"
|
||||||
|
|
||||||
|
|
@ -52,8 +50,8 @@ object VotingApi {
|
||||||
votesCache[pluginUrl] = it
|
votesCache[pluginUrl] = it
|
||||||
}
|
}
|
||||||
|
|
||||||
fun hasVoted(pluginUrl: String): Boolean =
|
fun hasVoted(pluginUrl: String) =
|
||||||
getKey<Boolean>("cs3-votes/${transformUrl(pluginUrl)}") ?: false
|
getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
|
||||||
|
|
||||||
fun canVote(pluginUrl: String): Boolean =
|
fun canVote(pluginUrl: String): Boolean =
|
||||||
PluginManager.urlPlugins.contains(pluginUrl)
|
PluginManager.urlPlugins.contains(pluginUrl)
|
||||||
|
|
@ -93,9 +91,8 @@ object VotingApi {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
private data class CountifyResult(
|
private data class CountifyResult(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String? = null,
|
val id: String? = null,
|
||||||
@JsonProperty("count") @SerialName("count") val count: Int? = null,
|
val count: Int? = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.receivers
|
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageInstaller
|
|
||||||
import com.lagradost.cloudstream3.utils.getSafeParcelableExtra
|
|
||||||
|
|
||||||
/** https://medium.com/@solrudev/painless-building-of-an-android-package-installer-app-d5a09b5df432 */
|
|
||||||
class PackageInstallerStatusReceiver : BroadcastReceiver() {
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)) {
|
|
||||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
|
||||||
intent.getSafeParcelableExtra<Intent>(Intent.EXTRA_INTENT)?.let { userAction->
|
|
||||||
userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
context.startActivity(userAction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PackageInstaller.STATUS_SUCCESS -> {
|
|
||||||
// do something on success
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
|
|
||||||
println("PackageInstallerStatusReceiver: status=$status, message=$message")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -36,7 +36,6 @@ import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.debounce
|
|
||||||
import kotlinx.coroutines.flow.takeWhile
|
import kotlinx.coroutines.flow.takeWhile
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.flow.updateAndGet
|
import kotlinx.coroutines.flow.updateAndGet
|
||||||
|
|
@ -187,16 +186,6 @@ class DownloadQueueService : Service() {
|
||||||
debugAssert({ timeTaken == null }, { "Downloader startup should not time out" })
|
debugAssert({ timeTaken == null }, { "Downloader startup should not time out" })
|
||||||
|
|
||||||
totalDownloadFlow
|
totalDownloadFlow
|
||||||
.debounce { (instances, queue) ->
|
|
||||||
// Filter away incorrect transient queue states.
|
|
||||||
// For example when we pop the queue and add a download instance there exists a transient state where
|
|
||||||
// there is no queue and no download instances (leading to an early exit)
|
|
||||||
if (instances.isEmpty() && queue.isEmpty()) {
|
|
||||||
500.milliseconds
|
|
||||||
} else {
|
|
||||||
0.milliseconds
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.takeWhile { (instances, queue) ->
|
.takeWhile { (instances, queue) ->
|
||||||
// Stop if destroyed
|
// Stop if destroyed
|
||||||
isRunning
|
isRunning
|
||||||
|
|
|
||||||
|
|
@ -70,8 +70,7 @@ abstract class AccountManager {
|
||||||
SubtitleRepo(openSubtitlesApi),
|
SubtitleRepo(openSubtitlesApi),
|
||||||
SubtitleRepo(addic7ed),
|
SubtitleRepo(addic7ed),
|
||||||
SubtitleRepo(subDlApi),
|
SubtitleRepo(subDlApi),
|
||||||
PlainAuthRepo(animeSkipApi),
|
PlainAuthRepo(animeSkipApi)
|
||||||
SubtitleRepo(subSourceApi)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
fun updateAccountIds() {
|
fun updateAccountIds() {
|
||||||
|
|
@ -121,8 +120,7 @@ abstract class AccountManager {
|
||||||
val subtitleProviders = arrayOf(
|
val subtitleProviders = arrayOf(
|
||||||
SubtitleRepo(openSubtitlesApi),
|
SubtitleRepo(openSubtitlesApi),
|
||||||
SubtitleRepo(addic7ed),
|
SubtitleRepo(addic7ed),
|
||||||
SubtitleRepo(subDlApi),
|
SubtitleRepo(subDlApi)
|
||||||
SubtitleRepo(subSourceApi)
|
|
||||||
)
|
)
|
||||||
val syncApis = arrayOf(
|
val syncApis = arrayOf(
|
||||||
SyncRepo(malApi),
|
SyncRepo(malApi),
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,50 @@
|
||||||
package com.lagradost.cloudstream3.syncproviders
|
package com.lagradost.cloudstream3.syncproviders
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonAlias
|
import android.util.Base64
|
||||||
|
import androidx.annotation.WorkerThread
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.APIHolder.unixTime
|
import com.lagradost.cloudstream3.APIHolder.unixTime
|
||||||
import com.lagradost.cloudstream3.APIHolder.unixTimeMS
|
import com.lagradost.cloudstream3.ActorData
|
||||||
import com.lagradost.cloudstream3.base64Encode
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.splitUrlParameters
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.openBrowser
|
||||||
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
|
import com.lagradost.cloudstream3.CommonActivity.showToast
|
||||||
|
import com.lagradost.cloudstream3.ErrorLoadingException
|
||||||
|
import com.lagradost.cloudstream3.LoadResponse
|
||||||
|
import com.lagradost.cloudstream3.NextAiring
|
||||||
|
import com.lagradost.cloudstream3.R
|
||||||
|
import com.lagradost.cloudstream3.Score
|
||||||
|
import com.lagradost.cloudstream3.SearchQuality
|
||||||
|
import com.lagradost.cloudstream3.SearchResponse
|
||||||
|
import com.lagradost.cloudstream3.ShowStatus
|
||||||
|
import com.lagradost.cloudstream3.TvType
|
||||||
|
import com.lagradost.cloudstream3.mvvm.Resource
|
||||||
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
|
import com.lagradost.cloudstream3.mvvm.safe
|
||||||
|
import com.lagradost.cloudstream3.mvvm.safeApiCall
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
|
||||||
import kotlinx.serialization.ExperimentalSerializationApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.NONE_ID
|
||||||
import kotlinx.serialization.SerialName
|
import com.lagradost.cloudstream3.syncproviders.providers.Addic7ed
|
||||||
import kotlinx.serialization.Serializable
|
import com.lagradost.cloudstream3.syncproviders.providers.AniListApi
|
||||||
import kotlinx.serialization.json.JsonNames
|
import com.lagradost.cloudstream3.syncproviders.providers.LocalList
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.MALApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.KitsuApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.OpenSubtitlesApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.SimklApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.SubDlApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.providers.SubSourceApi
|
||||||
|
import com.lagradost.cloudstream3.ui.SyncWatchType
|
||||||
|
import com.lagradost.cloudstream3.ui.library.ListSorting
|
||||||
|
import com.lagradost.cloudstream3.utils.AppContextUtils.splitQuery
|
||||||
|
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
|
||||||
|
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
||||||
|
import com.lagradost.cloudstream3.utils.UiText
|
||||||
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
|
import me.xdrop.fuzzywuzzy.FuzzySearch
|
||||||
|
import java.net.URL
|
||||||
import java.security.SecureRandom
|
import java.security.SecureRandom
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
data class AuthLoginPage(
|
data class AuthLoginPage(
|
||||||
/** The website to open to authenticate */
|
/** The website to open to authenticate */
|
||||||
|
|
@ -20,60 +52,55 @@ data class AuthLoginPage(
|
||||||
/**
|
/**
|
||||||
* State/control code to verify against the redirectUrl to make sure the request is valid.
|
* State/control code to verify against the redirectUrl to make sure the request is valid.
|
||||||
* This parameter will be saved, and then used in AuthAPI::login.
|
* This parameter will be saved, and then used in AuthAPI::login.
|
||||||
*/
|
* */
|
||||||
val payload: String? = null,
|
val payload: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AuthToken(
|
data class AuthToken(
|
||||||
/**
|
/**
|
||||||
* This is the general access tokens/api token representing a logged in user.
|
* This is the general access tokens/api token representing a logged in user.
|
||||||
* Access tokens are the thing that applications use to make API requests on behalf of a user.
|
*
|
||||||
*/
|
* `Access tokens are the thing that applications use to make API requests on behalf of a user.`
|
||||||
@JsonProperty("accessToken") @SerialName("accessToken")
|
* */
|
||||||
|
@JsonProperty("accessToken")
|
||||||
val accessToken: String? = null,
|
val accessToken: String? = null,
|
||||||
/** For OAuth a special refresh token is issues to refresh the access token. */
|
/**
|
||||||
@JsonProperty("refreshToken") @SerialName("refreshToken")
|
* For OAuth a special refresh token is issues to refresh the access token.
|
||||||
|
* */
|
||||||
|
@JsonProperty("refreshToken")
|
||||||
val refreshToken: String? = null,
|
val refreshToken: String? = null,
|
||||||
/** In UnixTime (sec) when it expires */
|
/** In UnixTime (sec) when it expires */
|
||||||
@JsonProperty("accessTokenLifetime") @SerialName("accessTokenLifetime")
|
@JsonProperty("accessTokenLifetime")
|
||||||
val accessTokenLifetime: Long? = null,
|
val accessTokenLifetime: Long? = null,
|
||||||
/** In UnixTime (sec) when it expires */
|
/** In UnixTime (sec) when it expires */
|
||||||
@JsonProperty("refreshTokenLifetime") @SerialName("refreshTokenLifetime")
|
@JsonProperty("refreshTokenLifetime")
|
||||||
val refreshTokenLifetime: Long? = null,
|
val refreshTokenLifetime: Long? = null,
|
||||||
/**
|
/** Sometimes AuthToken needs to be customized to store e.g. username/password,
|
||||||
* Sometimes AuthToken needs to be customized to store e.g. username/password,
|
* this acts as a catch all to store text or JSON data. */
|
||||||
* this acts as a catch all to store text or JSON data.
|
@JsonProperty("payload")
|
||||||
*/
|
|
||||||
@JsonProperty("payload") @SerialName("payload")
|
|
||||||
val payload: String? = null,
|
val payload: String? = null,
|
||||||
) {
|
) {
|
||||||
fun isAccessTokenExpired(marginSec: Long = 10L) =
|
fun isAccessTokenExpired(marginSec: Long = 10L) =
|
||||||
accessTokenLifetime != null && unixTime + marginSec >= accessTokenLifetime
|
accessTokenLifetime != null && (System.currentTimeMillis() / 1000) + marginSec >= accessTokenLifetime
|
||||||
|
|
||||||
fun isRefreshTokenExpired(marginSec: Long = 10L) =
|
fun isRefreshTokenExpired(marginSec: Long = 10L) =
|
||||||
refreshTokenLifetime != null && unixTime + marginSec >= refreshTokenLifetime
|
refreshTokenLifetime != null && (System.currentTimeMillis() / 1000) + marginSec >= refreshTokenLifetime
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalSerializationApi::class) // JsonNames is an experimental annotation for now
|
|
||||||
@Serializable
|
|
||||||
data class AuthUser(
|
data class AuthUser(
|
||||||
/** Account display-name, can also be email if name does not exist */
|
/** Account display-name, can also be email if name does not exist */
|
||||||
@JsonProperty("name") @SerialName("name")
|
@JsonProperty("name")
|
||||||
val name: String?,
|
val name: String?,
|
||||||
/**
|
/** Unique account identifier,
|
||||||
* Unique account identifier. If a subsequent login is done then it
|
* if a subsequent login is done then it will be refused if another account with the same id exists*/
|
||||||
* will be refused if another account with the same id exists.
|
@JsonProperty("id")
|
||||||
*/
|
|
||||||
@JsonProperty("id") @SerialName("id")
|
|
||||||
val id: Int,
|
val id: Int,
|
||||||
/** Profile picture URL */
|
/** Profile picture URL */
|
||||||
@JsonProperty("profilePicture") @SerialName("profilePicture")
|
@JsonProperty("profilePicture")
|
||||||
val profilePicture: String? = null,
|
val profilePicture: String? = null,
|
||||||
/** Profile picture Headers of the URL */
|
/** Profile picture Headers of the URL */
|
||||||
@JsonProperty("profilePictureHeaders") @JsonAlias("profilePictureHeader")
|
@JsonProperty("profilePictureHeader")
|
||||||
@SerialName("profilePictureHeaders") @JsonNames("profilePictureHeader")
|
val profilePictureHeaders: Map<String, String>? = null
|
||||||
val profilePictureHeaders: Map<String, String>? = null,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -83,11 +110,12 @@ data class AuthUser(
|
||||||
*
|
*
|
||||||
* Any local set/get key should use user.id.toString(),
|
* Any local set/get key should use user.id.toString(),
|
||||||
* as token.accessToken (even hashed) is unsecure, and will rotate.
|
* as token.accessToken (even hashed) is unsecure, and will rotate.
|
||||||
*/
|
* */
|
||||||
@Serializable
|
|
||||||
data class AuthData(
|
data class AuthData(
|
||||||
@JsonProperty("user") @SerialName("user") val user: AuthUser,
|
@JsonProperty("user")
|
||||||
@JsonProperty("token") @SerialName("token") val token: AuthToken,
|
val user: AuthUser,
|
||||||
|
@JsonProperty("token")
|
||||||
|
val token: AuthToken,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class AuthPinData(
|
data class AuthPinData(
|
||||||
|
|
@ -110,12 +138,15 @@ data class AuthLoginRequirement(
|
||||||
)
|
)
|
||||||
|
|
||||||
/** What the user responds to the AuthLoginRequirement */
|
/** What the user responds to the AuthLoginRequirement */
|
||||||
@Serializable
|
|
||||||
data class AuthLoginResponse(
|
data class AuthLoginResponse(
|
||||||
@JsonProperty("password") @SerialName("password") val password: String?,
|
@JsonProperty("password")
|
||||||
@JsonProperty("username") @SerialName("username") val username: String?,
|
val password: String?,
|
||||||
@JsonProperty("email") @SerialName("email") val email: String?,
|
@JsonProperty("username")
|
||||||
@JsonProperty("server") @SerialName("server") val server: String?,
|
val username: String?,
|
||||||
|
@JsonProperty("email")
|
||||||
|
val email: String?,
|
||||||
|
@JsonProperty("server")
|
||||||
|
val server: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Stateless Authentication class used for all personalized content */
|
/** Stateless Authentication class used for all personalized content */
|
||||||
|
|
@ -148,31 +179,16 @@ abstract class AuthAPI {
|
||||||
open val inAppLoginRequirement: AuthLoginRequirement? = null
|
open val inAppLoginRequirement: AuthLoginRequirement? = null
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@Deprecated(
|
|
||||||
message = "Use APIHolder.unixTime instead",
|
|
||||||
replaceWith = ReplaceWith(
|
|
||||||
expression = "APIHolder.unixTime",
|
|
||||||
imports = ["com.lagradost.cloudstream3.APIHolder"]
|
|
||||||
),
|
|
||||||
level = DeprecationLevel.WARNING,
|
|
||||||
)
|
|
||||||
val unixTime: Long
|
val unixTime: Long
|
||||||
get() = APIHolder.unixTime
|
get() = System.currentTimeMillis() / 1000L
|
||||||
|
|
||||||
@Deprecated(
|
|
||||||
message = "Use APIHolder.unixTimeMS instead",
|
|
||||||
replaceWith = ReplaceWith(
|
|
||||||
expression = "unixTimeMS",
|
|
||||||
imports = ["com.lagradost.cloudstream3.APIHolder.unixTimeMS"]
|
|
||||||
),
|
|
||||||
level = DeprecationLevel.WARNING,
|
|
||||||
)
|
|
||||||
val unixTimeMs: Long
|
val unixTimeMs: Long
|
||||||
get() = unixTimeMS
|
get() = System.currentTimeMillis()
|
||||||
|
|
||||||
fun splitRedirectUrl(redirectUrl: String): Map<String, String> {
|
fun splitRedirectUrl(redirectUrl: String): Map<String, String> {
|
||||||
return splitUrlParameters(
|
return splitQuery(
|
||||||
redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
|
URL(
|
||||||
|
redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -182,8 +198,9 @@ abstract class AuthAPI {
|
||||||
val secureRandom = SecureRandom()
|
val secureRandom = SecureRandom()
|
||||||
val codeVerifierBytes = ByteArray(96) // base64 has 6bit per char; (8/6)*96 = 128
|
val codeVerifierBytes = ByteArray(96) // base64 has 6bit per char; (8/6)*96 = 128
|
||||||
secureRandom.nextBytes(codeVerifierBytes)
|
secureRandom.nextBytes(codeVerifierBytes)
|
||||||
return base64Encode(codeVerifierBytes).trimEnd('=')
|
return Base64.encodeToString(codeVerifierBytes, Base64.DEFAULT).trimEnd('=')
|
||||||
.replace("+", "-").replace("/", "_").replace("\n", "")
|
.replace("+", "-")
|
||||||
|
.replace("/", "_").replace("\n", "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -226,7 +243,7 @@ abstract class AuthAPI {
|
||||||
*
|
*
|
||||||
* Note that this will currently only be called *once* on logout,
|
* Note that this will currently only be called *once* on logout,
|
||||||
* and as such any network issues it will fail silently, and the token will not be revoked.
|
* and as such any network issues it will fail silently, and the token will not be revoked.
|
||||||
*/
|
**/
|
||||||
@Throws
|
@Throws
|
||||||
open suspend fun invalidateToken(token: AuthToken): Nothing = throw NotImplementedError()
|
open suspend fun invalidateToken(token: AuthToken): Nothing = throw NotImplementedError()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,11 @@ package com.lagradost.cloudstream3.syncproviders
|
||||||
|
|
||||||
import androidx.annotation.WorkerThread
|
import androidx.annotation.WorkerThread
|
||||||
import com.lagradost.cloudstream3.APIHolder.unixTime
|
import com.lagradost.cloudstream3.APIHolder.unixTime
|
||||||
|
import com.lagradost.cloudstream3.ErrorLoadingException
|
||||||
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
|
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
|
||||||
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
|
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
|
||||||
import com.lagradost.cloudstream3.subtitles.SubtitleResource
|
import com.lagradost.cloudstream3.subtitles.SubtitleResource
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
|
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
|
||||||
|
|
||||||
/** Stateless safe abstraction of SubtitleAPI */
|
/** Stateless safe abstraction of SubtitleAPI */
|
||||||
class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
||||||
|
|
@ -13,8 +14,7 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
||||||
data class SavedSearchResponse(
|
data class SavedSearchResponse(
|
||||||
val unixTime: Long,
|
val unixTime: Long,
|
||||||
val response: List<SubtitleEntity>,
|
val response: List<SubtitleEntity>,
|
||||||
val query: SubtitleSearch,
|
val query: SubtitleSearch
|
||||||
val idPrefix: String,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
data class SavedResourceResponse(
|
data class SavedResourceResponse(
|
||||||
|
|
@ -24,30 +24,26 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
||||||
)
|
)
|
||||||
|
|
||||||
// maybe make this a generic struct? right now there is a lot of boilerplate
|
// maybe make this a generic struct? right now there is a lot of boilerplate
|
||||||
private val searchCache = atomicListOf<SavedSearchResponse>()
|
private val searchCache = threadSafeListOf<SavedSearchResponse>()
|
||||||
private var searchCacheIndex: Int = 0
|
private var searchCacheIndex: Int = 0
|
||||||
private val resourceCache = atomicListOf<SavedResourceResponse>()
|
private val resourceCache = threadSafeListOf<SavedResourceResponse>()
|
||||||
private var resourceCacheIndex: Int = 0
|
private var resourceCacheIndex: Int = 0
|
||||||
const val CACHE_SIZE = 20
|
const val CACHE_SIZE = 20
|
||||||
}
|
}
|
||||||
|
|
||||||
@WorkerThread
|
@WorkerThread
|
||||||
suspend fun resource(data: SubtitleEntity): Result<SubtitleResource> = runCatching {
|
suspend fun resource(data: SubtitleEntity): Result<SubtitleResource> = runCatching {
|
||||||
val cached = resourceCache.withLock {
|
synchronized(resourceCache) {
|
||||||
var found: SubtitleResource? = null
|
|
||||||
for (item in resourceCache) {
|
for (item in resourceCache) {
|
||||||
// 20 min save
|
// 20 min save
|
||||||
if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
|
if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
|
||||||
found = item.response
|
return@runCatching item.response
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
found
|
|
||||||
}
|
}
|
||||||
if (cached != null) return@runCatching cached
|
|
||||||
|
|
||||||
val returnValue = api.resource(freshAuth(), data)
|
val returnValue = api.resource(freshAuth(), data)
|
||||||
resourceCache.withLock {
|
synchronized(resourceCache) {
|
||||||
val add = SavedResourceResponse(unixTime, returnValue, data)
|
val add = SavedResourceResponse(unixTime, returnValue, data)
|
||||||
if (resourceCache.size > CACHE_SIZE) {
|
if (resourceCache.size > CACHE_SIZE) {
|
||||||
resourceCache[resourceCacheIndex] = add // rolling cache
|
resourceCache[resourceCacheIndex] = add // rolling cache
|
||||||
|
|
@ -62,25 +58,22 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
||||||
@WorkerThread
|
@WorkerThread
|
||||||
suspend fun search(query: SubtitleSearch): Result<List<SubtitleEntity>> {
|
suspend fun search(query: SubtitleSearch): Result<List<SubtitleEntity>> {
|
||||||
return runCatching {
|
return runCatching {
|
||||||
val cached = searchCache.withLock {
|
synchronized(searchCache) {
|
||||||
var found: List<SubtitleEntity>? = null
|
|
||||||
for (item in searchCache) {
|
for (item in searchCache) {
|
||||||
// 120 min save
|
// 120 min save
|
||||||
if (item.idPrefix == idPrefix && item.query == query && (unixTime - item.unixTime) < 60 * 120) {
|
if (item.query == query && (unixTime - item.unixTime) < 60 * 120) {
|
||||||
found = item.response
|
return@runCatching item.response
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
found
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cached != null) return@runCatching cached
|
val returnValue =
|
||||||
val returnValue = api.search(freshAuth(), query) ?: emptyList()
|
api.search(freshAuth(), query) ?: emptyList()
|
||||||
|
|
||||||
// only cache valid return values
|
// only cache valid return values
|
||||||
if (returnValue.isNotEmpty()) {
|
if (returnValue.isNotEmpty()) {
|
||||||
val add = SavedSearchResponse(unixTime, returnValue, query, idPrefix)
|
val add = SavedSearchResponse(unixTime, returnValue, query)
|
||||||
searchCache.withLock {
|
synchronized(searchCache) {
|
||||||
if (searchCache.size > CACHE_SIZE) {
|
if (searchCache.size > CACHE_SIZE) {
|
||||||
searchCache[searchCacheIndex] = add // rolling cache
|
searchCache[searchCacheIndex] = add // rolling cache
|
||||||
searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
|
searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
|
||||||
|
|
@ -93,3 +86,4 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ import com.lagradost.cloudstream3.ShowStatus
|
||||||
import com.lagradost.cloudstream3.TvType
|
import com.lagradost.cloudstream3.TvType
|
||||||
import com.lagradost.cloudstream3.ui.SyncWatchType
|
import com.lagradost.cloudstream3.ui.SyncWatchType
|
||||||
import com.lagradost.cloudstream3.ui.library.ListSorting
|
import com.lagradost.cloudstream3.ui.library.ListSorting
|
||||||
import com.lagradost.cloudstream3.utils.Levenshtein
|
|
||||||
import com.lagradost.cloudstream3.utils.UiText
|
import com.lagradost.cloudstream3.utils.UiText
|
||||||
|
import me.xdrop.fuzzywuzzy.FuzzySearch
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -138,7 +138,7 @@ abstract class SyncAPI : AuthAPI() {
|
||||||
ListSorting.Query ->
|
ListSorting.Query ->
|
||||||
if (query != null) {
|
if (query != null) {
|
||||||
items.sortedBy {
|
items.sortedBy {
|
||||||
-Levenshtein.partialRatio(
|
-FuzzySearch.partialRatio(
|
||||||
query.lowercase(), it.name.lowercase()
|
query.lowercase(), it.name.lowercase()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -191,4 +191,4 @@ abstract class SyncAPI : AuthAPI() {
|
||||||
override var score: Score? = null,
|
override var score: Score? = null,
|
||||||
val tags: List<String>? = null
|
val tags: List<String>? = null
|
||||||
) : SearchResponse
|
) : SearchResponse
|
||||||
}
|
}
|
||||||
|
|
@ -5,8 +5,6 @@ import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.Actor
|
import com.lagradost.cloudstream3.Actor
|
||||||
import com.lagradost.cloudstream3.ActorData
|
import com.lagradost.cloudstream3.ActorData
|
||||||
import com.lagradost.cloudstream3.ActorRole
|
import com.lagradost.cloudstream3.ActorRole
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.BuildConfig
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
import com.lagradost.cloudstream3.ErrorLoadingException
|
import com.lagradost.cloudstream3.ErrorLoadingException
|
||||||
|
|
@ -27,10 +25,9 @@ import com.lagradost.cloudstream3.ui.library.ListSorting
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
|
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
|
||||||
|
import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.toYear
|
import com.lagradost.cloudstream3.utils.DataStoreHelper.toYear
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.net.URLEncoder
|
import java.net.URLEncoder
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
|
|
@ -38,7 +35,7 @@ class AniListApi : SyncAPI() {
|
||||||
override var name = "AniList"
|
override var name = "AniList"
|
||||||
override val idPrefix = "anilist"
|
override val idPrefix = "anilist"
|
||||||
|
|
||||||
private val key = BuildConfig.ANILIST_KEY
|
val key = "6871"
|
||||||
override val redirectUrlIdentifier = "anilistlogin"
|
override val redirectUrlIdentifier = "anilistlogin"
|
||||||
override var requireLibraryRefresh = true
|
override var requireLibraryRefresh = true
|
||||||
override val hasOAuth2 = true
|
override val hasOAuth2 = true
|
||||||
|
|
@ -53,10 +50,9 @@ class AniListApi : SyncAPI() {
|
||||||
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
|
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
|
||||||
val sanitizer = splitRedirectUrl(redirectUrl)
|
val sanitizer = splitRedirectUrl(redirectUrl)
|
||||||
val token = AuthToken(
|
val token = AuthToken(
|
||||||
accessToken = sanitizer["access_token"]
|
accessToken = sanitizer["access_token"] ?: throw ErrorLoadingException("No access token"),
|
||||||
?: throw ErrorLoadingException("No access token"),
|
//refreshToken = sanitizer["refresh_token"],
|
||||||
// refreshToken = sanitizer["refresh_token"],
|
accessTokenLifetime = unixTime + sanitizer["expires_in"]!!.toLong(),
|
||||||
accessTokenLifetime = APIHolder.unixTime + sanitizer["expires_in"]!!.toLong(),
|
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
@ -82,12 +78,13 @@ class AniListApi : SyncAPI() {
|
||||||
override fun urlToId(url: String): String? =
|
override fun urlToId(url: String): String? =
|
||||||
url.removePrefix("$mainUrl/anime/").removeSuffix("/")
|
url.removePrefix("$mainUrl/anime/").removeSuffix("/")
|
||||||
|
|
||||||
|
|
||||||
private fun getUrlFromId(id: Int): String {
|
private fun getUrlFromId(id: Int): String {
|
||||||
return "$mainUrl/anime/$id"
|
return "$mainUrl/anime/$id"
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun search(auth: AuthData?, query: String): List<SyncAPI.SyncSearchResult>? {
|
override suspend fun search(auth : AuthData?, query: String): List<SyncAPI.SyncSearchResult>? {
|
||||||
val data = searchShows(query) ?: return null
|
val data = searchShows(name) ?: return null
|
||||||
return data.data?.page?.media?.map {
|
return data.data?.page?.media?.map {
|
||||||
SyncAPI.SyncSearchResult(
|
SyncAPI.SyncSearchResult(
|
||||||
it.title.romaji ?: return null,
|
it.title.romaji ?: return null,
|
||||||
|
|
@ -99,16 +96,17 @@ class AniListApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun load(auth: AuthData?, id: String): SyncAPI.SyncResult? {
|
override suspend fun load(auth : AuthData?, id: String): SyncAPI.SyncResult? {
|
||||||
val internalId = (Regex("anilist\\.co/anime/(\\d*)").find(id)?.groupValues?.getOrNull(1)
|
val internalId = (Regex("anilist\\.co/anime/(\\d*)").find(id)?.groupValues?.getOrNull(1)
|
||||||
?: id).toIntOrNull() ?: throw ErrorLoadingException("Invalid internalId")
|
?: id).toIntOrNull() ?: throw ErrorLoadingException("Invalid internalId")
|
||||||
val season = getSeason(internalId).data.media
|
val season = getSeason(internalId).data.media
|
||||||
|
|
||||||
return SyncAPI.SyncResult(
|
return SyncAPI.SyncResult(
|
||||||
season.id.toString(),
|
season.id.toString(),
|
||||||
nextAiring = season.nextAiringEpisode?.let {
|
nextAiring = season.nextAiringEpisode?.let {
|
||||||
NextAiring(
|
NextAiring(
|
||||||
it.episode ?: return@let null,
|
it.episode ?: return@let null,
|
||||||
(it.timeUntilAiring ?: return@let null) + APIHolder.unixTime
|
(it.timeUntilAiring ?: return@let null) + unixTime
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
title = season.title?.userPreferred,
|
title = season.title?.userPreferred,
|
||||||
|
|
@ -156,13 +154,14 @@ class AniListApi : SyncAPI() {
|
||||||
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
|
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
// TODO REST
|
//TODO REST
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun status(auth: AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
|
override suspend fun status(auth : AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
|
||||||
val internalId = id.toIntOrNull() ?: return null
|
val internalId = id.toIntOrNull() ?: return null
|
||||||
val data = getDataAboutId(auth ?: return null, internalId) ?: return null
|
val data = getDataAboutId(auth ?: return null, internalId) ?: return null
|
||||||
|
|
||||||
return SyncAPI.SyncStatus(
|
return SyncAPI.SyncStatus(
|
||||||
score = Score.from100(data.score),
|
score = Score.from100(data.score),
|
||||||
watchedEpisodes = data.progress,
|
watchedEpisodes = data.progress,
|
||||||
|
|
@ -258,24 +257,24 @@ class AniListApi : SyncAPI() {
|
||||||
val data =
|
val data =
|
||||||
mapOf(
|
mapOf(
|
||||||
"query" to query,
|
"query" to query,
|
||||||
"variables" to Variables(
|
"variables" to
|
||||||
search = name,
|
mapOf(
|
||||||
page = 1,
|
"search" to name,
|
||||||
type = "ANIME",
|
"page" to 1,
|
||||||
).toJson()
|
"type" to "ANIME"
|
||||||
|
).toJson()
|
||||||
)
|
)
|
||||||
|
|
||||||
val res = app.post(
|
val res = app.post(
|
||||||
"https://graphql.anilist.co/",
|
"https://graphql.anilist.co/",
|
||||||
// headers = mapOf(),
|
//headers = mapOf(),
|
||||||
data = data, // (if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
|
data = data,//(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
|
||||||
timeout = 5000 // REASONABLE TIMEOUT
|
timeout = 5000 // REASONABLE TIMEOUT
|
||||||
).text.replace("\\", "")
|
).text.replace("\\", "")
|
||||||
return parseJson<GetSearchRoot>(res)
|
return res.toKotlinObject()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
logError(e)
|
logError(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -298,7 +297,7 @@ class AniListApi : SyncAPI() {
|
||||||
.replace(")", "\\)")
|
.replace(")", "\\)")
|
||||||
})"""
|
})"""
|
||||||
)
|
)
|
||||||
// println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
|
//println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
|
||||||
val shows = searchShows(name.replace(blackListRegex, ""))
|
val shows = searchShows(name.replace(blackListRegex, ""))
|
||||||
|
|
||||||
shows?.data?.page?.media?.find {
|
shows?.data?.page?.media?.find {
|
||||||
|
|
@ -456,11 +455,11 @@ class AniListApi : SyncAPI() {
|
||||||
cacheTime = 0,
|
cacheTime = 0,
|
||||||
).text
|
).text
|
||||||
|
|
||||||
return tryParseJson<SeasonResponse>(data) ?: throw ErrorLoadingException("Error parsing $data")
|
return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getDataAboutId(auth: AuthData, id: Int): AniListTitleHolder? {
|
private suspend fun getDataAboutId(auth : AuthData, id: Int): AniListTitleHolder? {
|
||||||
val q =
|
val q =
|
||||||
"""query (${'$'}id: Int = $id) { # Define which variables will be used in the query (id)
|
"""query (${'$'}id: Int = $id) { # Define which variables will be used in the query (id)
|
||||||
Media (id: ${'$'}id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
|
Media (id: ${'$'}id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
|
||||||
|
|
@ -504,9 +503,10 @@ class AniListApi : SyncAPI() {
|
||||||
type = AniListStatusType.None,
|
type = AniListStatusType.None,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun postApi(token: AuthToken, q: String, cache: Boolean = false): String? {
|
private suspend fun postApi(token : AuthToken, q: String, cache: Boolean = false): String? {
|
||||||
return app.post(
|
return app.post(
|
||||||
"https://graphql.anilist.co/",
|
"https://graphql.anilist.co/",
|
||||||
headers = mapOf(
|
headers = mapOf(
|
||||||
|
|
@ -519,84 +519,71 @@ class AniListApi : SyncAPI() {
|
||||||
q,
|
q,
|
||||||
"UTF-8"
|
"UTF-8"
|
||||||
)
|
)
|
||||||
), // (if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
|
), //(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
|
||||||
timeout = 5 // REASONABLE TIMEOUT
|
timeout = 5 // REASONABLE TIMEOUT
|
||||||
).text.replace("\\/", "/")
|
).text.replace("\\/", "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Variables(
|
|
||||||
@JsonProperty("search") @SerialName("search") val search: String,
|
|
||||||
@JsonProperty("page") @SerialName("page") val page: Int,
|
|
||||||
@JsonProperty("type") @SerialName("type") val type: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaRecommendation(
|
data class MediaRecommendation(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("title") @SerialName("title") val title: Title?,
|
@JsonProperty("title") val title: Title?,
|
||||||
@JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
|
@JsonProperty("idMal") val idMal: Int?,
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage?,
|
@JsonProperty("coverImage") val coverImage: CoverImage?,
|
||||||
@JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
|
@JsonProperty("averageScore") val averageScore: Int?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class FullAnilistList(
|
data class FullAnilistList(
|
||||||
@JsonProperty("data") @SerialName("data") val data: Data?,
|
@JsonProperty("data") val data: Data?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CompletedAt(
|
data class CompletedAt(
|
||||||
@JsonProperty("year") @SerialName("year") val year: Int,
|
@JsonProperty("year") val year: Int,
|
||||||
@JsonProperty("month") @SerialName("month") val month: Int,
|
@JsonProperty("month") val month: Int,
|
||||||
@JsonProperty("day") @SerialName("day") val day: Int,
|
@JsonProperty("day") val day: Int
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class StartedAt(
|
data class StartedAt(
|
||||||
@JsonProperty("year") @SerialName("year") val year: String?,
|
@JsonProperty("year") val year: String?,
|
||||||
@JsonProperty("month") @SerialName("month") val month: String?,
|
@JsonProperty("month") val month: String?,
|
||||||
@JsonProperty("day") @SerialName("day") val day: String?,
|
@JsonProperty("day") val day: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Title(
|
data class Title(
|
||||||
@JsonProperty("english") @SerialName("english") val english: String?,
|
@JsonProperty("english") val english: String?,
|
||||||
@JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
|
@JsonProperty("romaji") val romaji: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CoverImage(
|
data class CoverImage(
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("extraLarge") @SerialName("extraLarge") val extraLarge: String?,
|
@JsonProperty("extraLarge") val extraLarge: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Media(
|
data class Media(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
|
@JsonProperty("idMal") val idMal: Int?,
|
||||||
@JsonProperty("season") @SerialName("season") val season: String?,
|
@JsonProperty("season") val season: String?,
|
||||||
@JsonProperty("seasonYear") @SerialName("seasonYear") val seasonYear: Int,
|
@JsonProperty("seasonYear") val seasonYear: Int,
|
||||||
@JsonProperty("format") @SerialName("format") val format: String?,
|
@JsonProperty("format") val format: String?,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: Int,
|
//@JsonProperty("source") val source: String,
|
||||||
@JsonProperty("title") @SerialName("title") val title: Title,
|
@JsonProperty("episodes") val episodes: Int,
|
||||||
@JsonProperty("description") @SerialName("description") val description: String?,
|
@JsonProperty("title") val title: Title,
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage,
|
@JsonProperty("description") val description: String?,
|
||||||
@JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List<String>,
|
@JsonProperty("coverImage") val coverImage: CoverImage,
|
||||||
@JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
@JsonProperty("synonyms") val synonyms: List<String>,
|
||||||
|
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Entries(
|
data class Entries(
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("completedAt") @SerialName("completedAt") val completedAt: CompletedAt,
|
@JsonProperty("completedAt") val completedAt: CompletedAt,
|
||||||
@JsonProperty("startedAt") @SerialName("startedAt") val startedAt: StartedAt,
|
@JsonProperty("startedAt") val startedAt: StartedAt,
|
||||||
@JsonProperty("updatedAt") @SerialName("updatedAt") val updatedAt: Int,
|
@JsonProperty("updatedAt") val updatedAt: Int,
|
||||||
@JsonProperty("progress") @SerialName("progress") val progress: Int,
|
@JsonProperty("progress") val progress: Int,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int,
|
@JsonProperty("score") val score: Int,
|
||||||
@JsonProperty("private") @SerialName("private") val private: Boolean,
|
@JsonProperty("private") val private: Boolean,
|
||||||
@JsonProperty("media") @SerialName("media") val media: Media,
|
@JsonProperty("media") val media: Media
|
||||||
) {
|
) {
|
||||||
fun toLibraryItem(): SyncAPI.LibraryItem {
|
fun toLibraryItem(): SyncAPI.LibraryItem {
|
||||||
return SyncAPI.LibraryItem(
|
return SyncAPI.LibraryItem(
|
||||||
|
|
@ -623,20 +610,17 @@ class AniListApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Lists(
|
data class Lists(
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("entries") @SerialName("entries") val entries: List<Entries>,
|
@JsonProperty("entries") val entries: List<Entries>
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaListCollection(
|
data class MediaListCollection(
|
||||||
@JsonProperty("lists") @SerialName("lists") val lists: List<Lists>,
|
@JsonProperty("lists") val lists: List<Lists>
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Data(
|
data class Data(
|
||||||
@JsonProperty("MediaListCollection") @SerialName("MediaListCollection") val mediaListCollection: MediaListCollection,
|
@JsonProperty("MediaListCollection") val mediaListCollection: MediaListCollection
|
||||||
)
|
)
|
||||||
|
|
||||||
private suspend fun getAniListAnimeListSmart(auth: AuthData): Array<Lists>? {
|
private suspend fun getAniListAnimeListSmart(auth: AuthData): Array<Lists>? {
|
||||||
|
|
@ -654,7 +638,7 @@ class AniListApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun library(auth: AuthData?): SyncAPI.LibraryMetadata? {
|
override suspend fun library(auth : AuthData?): SyncAPI.LibraryMetadata? {
|
||||||
val list = getAniListAnimeListSmart(auth ?: return null)?.groupBy {
|
val list = getAniListAnimeListSmart(auth ?: return null)?.groupBy {
|
||||||
convertAniListStringToStatus(it.status ?: "").stringRes
|
convertAniListStringToStatus(it.status ?: "").stringRes
|
||||||
}?.mapValues { group ->
|
}?.mapValues { group ->
|
||||||
|
|
@ -682,9 +666,10 @@ class AniListApi : SyncAPI() {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getFullAniListList(auth: AuthData): FullAnilistList? {
|
private suspend fun getFullAniListList(auth : AuthData): FullAnilistList? {
|
||||||
val userID = auth.user.id
|
val userID = auth.user.id
|
||||||
val mediaType = "ANIME"
|
val mediaType = "ANIME"
|
||||||
|
|
||||||
val query = """
|
val query = """
|
||||||
query (${'$'}userID: Int = $userID, ${'$'}MEDIA: MediaType = $mediaType) {
|
query (${'$'}userID: Int = $userID, ${'$'}MEDIA: MediaType = $mediaType) {
|
||||||
MediaListCollection (userId: ${'$'}userID, type: ${'$'}MEDIA) {
|
MediaListCollection (userId: ${'$'}userID, type: ${'$'}MEDIA) {
|
||||||
|
|
@ -723,53 +708,43 @@ class AniListApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
val text = postApi(auth.token, query)
|
val text = postApi(auth.token, query)
|
||||||
return tryParseJson<FullAnilistList>(text)
|
return text?.toKotlinObject()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun toggleLike(auth: AuthData, id: Int): Boolean {
|
suspend fun toggleLike(auth : AuthData, id: Int): Boolean {
|
||||||
val q = """mutation (${'$'}animeId: Int = $id) {
|
val q = """mutation (${'$'}animeId: Int = $id) {
|
||||||
ToggleFavourite (animeId: ${'$'}animeId) {
|
ToggleFavourite (animeId: ${'$'}animeId) {
|
||||||
anime {
|
anime {
|
||||||
nodes {
|
nodes {
|
||||||
id
|
id
|
||||||
title {
|
title {
|
||||||
romaji
|
romaji
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}"""
|
}"""
|
||||||
val data = postApi(auth.token, q)
|
val data = postApi(auth.token, q)
|
||||||
return data != ""
|
return data != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Used to query a saved MediaItem on the list to get the id for removal */
|
/** Used to query a saved MediaItem on the list to get the id for removal */
|
||||||
@Serializable
|
data class MediaListItemRoot(@JsonProperty("data") val data: MediaListItem? = null)
|
||||||
data class MediaListItemRoot(
|
data class MediaListItem(@JsonProperty("MediaList") val mediaList: MediaListId? = null)
|
||||||
@JsonProperty("data") @SerialName("data") val data: MediaListItem? = null,
|
data class MediaListId(@JsonProperty("id") val id: Long? = null)
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaListItem(
|
|
||||||
@JsonProperty("MediaList") @SerialName("MediaList") val mediaList: MediaListId? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaListId(
|
|
||||||
@JsonProperty("id") @SerialName("id") val id: Long? = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
private suspend fun postDataAboutId(
|
private suspend fun postDataAboutId(
|
||||||
auth: AuthData,
|
auth : AuthData,
|
||||||
id: Int,
|
id: Int,
|
||||||
type: AniListStatusType,
|
type: AniListStatusType,
|
||||||
score: Score?,
|
score: Score?,
|
||||||
progress: Int?
|
progress: Int?
|
||||||
): Boolean {
|
): Boolean {
|
||||||
val userID = auth.user.id
|
val userID = auth.user.id
|
||||||
|
|
||||||
val q =
|
val q =
|
||||||
// Delete item if status type is None
|
// Delete item if status type is None
|
||||||
if (type == AniListStatusType.None) {
|
if (type == AniListStatusType.None) {
|
||||||
|
|
@ -811,24 +786,24 @@ class AniListApi : SyncAPI() {
|
||||||
return data != ""
|
return data != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getUser(token: AuthToken): AniListUser? {
|
private suspend fun getUser(token : AuthToken): AniListUser? {
|
||||||
val q = """
|
val q = """
|
||||||
{
|
{
|
||||||
Viewer {
|
Viewer {
|
||||||
id
|
id
|
||||||
name
|
name
|
||||||
avatar {
|
avatar {
|
||||||
large
|
large
|
||||||
}
|
}
|
||||||
favourites {
|
favourites {
|
||||||
anime {
|
anime {
|
||||||
nodes {
|
nodes {
|
||||||
id
|
id
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}"""
|
||||||
}"""
|
|
||||||
val data = postApi(token, q)
|
val data = postApi(token, q)
|
||||||
if (data.isNullOrBlank()) return null
|
if (data.isNullOrBlank()) return null
|
||||||
val userData = parseJson<AniListRoot>(data)
|
val userData = parseJson<AniListRoot>(data)
|
||||||
|
|
@ -861,356 +836,305 @@ class AniListApi : SyncAPI() {
|
||||||
return seasons.toList()
|
return seasons.toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonResponse(
|
data class SeasonResponse(
|
||||||
@JsonProperty("data") @SerialName("data") val data: SeasonData,
|
@JsonProperty("data") val data: SeasonData,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonData(
|
data class SeasonData(
|
||||||
@JsonProperty("Media") @SerialName("Media") val media: SeasonMedia,
|
@JsonProperty("Media") val media: SeasonMedia,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class RecommendedMedia(
|
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
|
||||||
@JsonProperty("title") @SerialName("title") val title: MediaTitle?,
|
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CharacterMedia(
|
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
|
||||||
@JsonProperty("title") @SerialName("title") val title: MediaTitle?,
|
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonMedia(
|
data class SeasonMedia(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
@JsonProperty("title") @SerialName("title") val title: MediaTitle?,
|
@JsonProperty("title") val title: MediaTitle?,
|
||||||
@JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
|
@JsonProperty("idMal") val idMal: Int?,
|
||||||
@JsonProperty("format") @SerialName("format") val format: String?,
|
@JsonProperty("format") val format: String?,
|
||||||
@JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
||||||
@JsonProperty("relations") @SerialName("relations") val relations: SeasonEdges?,
|
@JsonProperty("relations") val relations: SeasonEdges?,
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
|
@JsonProperty("coverImage") val coverImage: MediaCoverImage?,
|
||||||
@JsonProperty("duration") @SerialName("duration") val duration: Int?,
|
@JsonProperty("duration") val duration: Int?,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
|
@JsonProperty("episodes") val episodes: Int?,
|
||||||
@JsonProperty("genres") @SerialName("genres") val genres: List<String>?,
|
@JsonProperty("genres") val genres: List<String>?,
|
||||||
@JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List<String>?,
|
@JsonProperty("synonyms") val synonyms: List<String>?,
|
||||||
@JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
|
@JsonProperty("averageScore") val averageScore: Int?,
|
||||||
@JsonProperty("isAdult") @SerialName("isAdult") val isAdult: Boolean?,
|
@JsonProperty("isAdult") val isAdult: Boolean?,
|
||||||
@JsonProperty("trailer") @SerialName("trailer") val trailer: MediaTrailer?,
|
@JsonProperty("trailer") val trailer: MediaTrailer?,
|
||||||
@JsonProperty("description") @SerialName("description") val description: String?,
|
@JsonProperty("description") val description: String?,
|
||||||
@JsonProperty("characters") @SerialName("characters") val characters: CharacterConnection?,
|
@JsonProperty("characters") val characters: CharacterConnection?,
|
||||||
@JsonProperty("recommendations") @SerialName("recommendations") val recommendations: RecommendationConnection?,
|
@JsonProperty("recommendations") val recommendations: RecommendationConnection?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class RecommendationConnection(
|
data class RecommendationConnection(
|
||||||
@JsonProperty("edges") @SerialName("edges") val edges: List<RecommendationEdge> = emptyList(),
|
@JsonProperty("edges") val edges: List<RecommendationEdge> = emptyList(),
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<Recommendation> = emptyList(),
|
@JsonProperty("nodes") val nodes: List<Recommendation> = emptyList(),
|
||||||
|
//@JsonProperty("pageInfo") val pageInfo: PageInfo,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class RecommendationEdge(
|
data class RecommendationEdge(
|
||||||
@JsonProperty("node") @SerialName("node") val node: Recommendation,
|
//@JsonProperty("rating") val rating: Int,
|
||||||
|
@JsonProperty("node") val node: Recommendation,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Recommendation(
|
data class Recommendation(
|
||||||
@JsonProperty("mediaRecommendation") @SerialName("mediaRecommendation") val mediaRecommendation: RecommendedMedia?,
|
val id: Long,
|
||||||
|
@JsonProperty("mediaRecommendation") val mediaRecommendation: SeasonMedia?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CharacterName(
|
data class CharacterName(
|
||||||
@JsonProperty("name") @SerialName("name") val first: String?,
|
@JsonProperty("name") val first: String?,
|
||||||
@JsonProperty("middle") @SerialName("middle") val middle: String?,
|
@JsonProperty("middle") val middle: String?,
|
||||||
@JsonProperty("last") @SerialName("last") val last: String?,
|
@JsonProperty("last") val last: String?,
|
||||||
@JsonProperty("full") @SerialName("full") val full: String?,
|
@JsonProperty("full") val full: String?,
|
||||||
@JsonProperty("native") @SerialName("native") val native: String?,
|
@JsonProperty("native") val native: String?,
|
||||||
@JsonProperty("alternative") @SerialName("alternative") val alternative: List<String>?,
|
@JsonProperty("alternative") val alternative: List<String>?,
|
||||||
@JsonProperty("alternativeSpoiler") @SerialName("alternativeSpoiler") val alternativeSpoiler: List<String>?,
|
@JsonProperty("alternativeSpoiler") val alternativeSpoiler: List<String>?,
|
||||||
@JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
|
@JsonProperty("userPreferred") val userPreferred: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CharacterImage(
|
data class CharacterImage(
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Character(
|
data class Character(
|
||||||
@JsonProperty("name") @SerialName("name") val name: CharacterName?,
|
@JsonProperty("name") val name: CharacterName?,
|
||||||
@JsonProperty("age") @SerialName("age") val age: String?,
|
@JsonProperty("age") val age: String?,
|
||||||
@JsonProperty("image") @SerialName("image") val image: CharacterImage?,
|
@JsonProperty("image") val image: CharacterImage?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CharacterEdge(
|
data class CharacterEdge(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
/**
|
/**
|
||||||
* MAIN - A primary character role in the media
|
MAIN
|
||||||
* SUPPORTING - A supporting character role in the media
|
A primary character role in the media
|
||||||
* BACKGROUND - A background character in the media
|
|
||||||
|
SUPPORTING
|
||||||
|
A supporting character role in the media
|
||||||
|
|
||||||
|
BACKGROUND
|
||||||
|
A background character in the media
|
||||||
*/
|
*/
|
||||||
@JsonProperty("role") @SerialName("role") val role: String?,
|
@JsonProperty("role") val role: String?,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String?,
|
@JsonProperty("name") val name: String?,
|
||||||
@JsonProperty("voiceActors") @SerialName("voiceActors") val voiceActors: List<Staff>?,
|
@JsonProperty("voiceActors") val voiceActors: List<Staff>?,
|
||||||
@JsonProperty("favouriteOrder") @SerialName("favouriteOrder") val favouriteOrder: Int?,
|
@JsonProperty("favouriteOrder") val favouriteOrder: Int?,
|
||||||
@JsonProperty("media") @SerialName("media") val media: List<CharacterMedia>?,
|
@JsonProperty("media") val media: List<SeasonMedia>?,
|
||||||
@JsonProperty("node") @SerialName("node") val node: Character?,
|
@JsonProperty("node") val node: Character?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class StaffImage(
|
data class StaffImage(
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class StaffName(
|
data class StaffName(
|
||||||
@JsonProperty("name") @SerialName("name") val first: String?,
|
@JsonProperty("name") val first: String?,
|
||||||
@JsonProperty("middle") @SerialName("middle") val middle: String?,
|
@JsonProperty("middle") val middle: String?,
|
||||||
@JsonProperty("last") @SerialName("last") val last: String?,
|
@JsonProperty("last") val last: String?,
|
||||||
@JsonProperty("full") @SerialName("full") val full: String?,
|
@JsonProperty("full") val full: String?,
|
||||||
@JsonProperty("native") @SerialName("native") val native: String?,
|
@JsonProperty("native") val native: String?,
|
||||||
@JsonProperty("alternative") @SerialName("alternative") val alternative: List<String>?,
|
@JsonProperty("alternative") val alternative: List<String>?,
|
||||||
@JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
|
@JsonProperty("userPreferred") val userPreferred: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Staff(
|
data class Staff(
|
||||||
@JsonProperty("image") @SerialName("image") val image: StaffImage?,
|
@JsonProperty("image") val image: StaffImage?,
|
||||||
@JsonProperty("name") @SerialName("name") val name: StaffName?,
|
@JsonProperty("name") val name: StaffName?,
|
||||||
@JsonProperty("age") @SerialName("age") val age: Int?,
|
@JsonProperty("age") val age: Int?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CharacterConnection(
|
data class CharacterConnection(
|
||||||
@JsonProperty("edges") @SerialName("edges") val edges: List<CharacterEdge>?,
|
@JsonProperty("edges") val edges: List<CharacterEdge>?,
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<Character>?,
|
@JsonProperty("nodes") val nodes: List<Character>?,
|
||||||
|
//@JsonProperty("pageInfo") pageInfo: PageInfo
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaTrailer(
|
data class MediaTrailer(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String?,
|
@JsonProperty("id") val id: String?,
|
||||||
@JsonProperty("site") @SerialName("site") val site: String?,
|
@JsonProperty("site") val site: String?,
|
||||||
@JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: String?,
|
@JsonProperty("thumbnail") val thumbnail: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaCoverImage(
|
data class MediaCoverImage(
|
||||||
@JsonProperty("extraLarge") @SerialName("extraLarge") val extraLarge: String?,
|
@JsonProperty("extraLarge") val extraLarge: String?,
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
@JsonProperty("color") @SerialName("color") val color: String?,
|
@JsonProperty("color") val color: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonNextAiringEpisode(
|
data class SeasonNextAiringEpisode(
|
||||||
@JsonProperty("episode") @SerialName("episode") val episode: Int?,
|
@JsonProperty("episode") val episode: Int?,
|
||||||
@JsonProperty("timeUntilAiring") @SerialName("timeUntilAiring") val timeUntilAiring: Int?,
|
@JsonProperty("timeUntilAiring") val timeUntilAiring: Int?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonEdges(
|
data class SeasonEdges(
|
||||||
@JsonProperty("edges") @SerialName("edges") val edges: List<SeasonEdge>?,
|
@JsonProperty("edges") val edges: List<SeasonEdge>?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonEdge(
|
data class SeasonEdge(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
@JsonProperty("relationType") @SerialName("relationType") val relationType: String?,
|
@JsonProperty("relationType") val relationType: String?,
|
||||||
@JsonProperty("node") @SerialName("node") val node: SeasonNode?,
|
@JsonProperty("node") val node: SeasonNode?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListFavoritesMediaConnection(
|
data class AniListFavoritesMediaConnection(
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<LikeNode>,
|
@JsonProperty("nodes") val nodes: List<LikeNode>,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListFavourites(
|
data class AniListFavourites(
|
||||||
@JsonProperty("anime") @SerialName("anime") val anime: AniListFavoritesMediaConnection,
|
@JsonProperty("anime") val anime: AniListFavoritesMediaConnection,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MediaTitle(
|
data class MediaTitle(
|
||||||
@JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
|
@JsonProperty("romaji") val romaji: String?,
|
||||||
@JsonProperty("english") @SerialName("english") val english: String?,
|
@JsonProperty("english") val english: String?,
|
||||||
@JsonProperty("native") @SerialName("native") val native: String?,
|
@JsonProperty("native") val native: String?,
|
||||||
@JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
|
@JsonProperty("userPreferred") val userPreferred: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SeasonNode(
|
data class SeasonNode(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("format") @SerialName("format") val format: String?,
|
@JsonProperty("format") val format: String?,
|
||||||
@JsonProperty("title") @SerialName("title") val title: Title?,
|
@JsonProperty("title") val title: Title?,
|
||||||
@JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
|
@JsonProperty("idMal") val idMal: Int?,
|
||||||
@JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage?,
|
@JsonProperty("coverImage") val coverImage: CoverImage?,
|
||||||
@JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
|
@JsonProperty("averageScore") val averageScore: Int?
|
||||||
|
// @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListAvatar(
|
data class AniListAvatar(
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListViewer(
|
data class AniListViewer(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("avatar") @SerialName("avatar") val avatar: AniListAvatar?,
|
@JsonProperty("avatar") val avatar: AniListAvatar?,
|
||||||
@JsonProperty("favourites") @SerialName("favourites") val favourites: AniListFavourites?,
|
@JsonProperty("favourites") val favourites: AniListFavourites?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListData(
|
data class AniListData(
|
||||||
@JsonProperty("Viewer") @SerialName("Viewer") val viewer: AniListViewer?,
|
@JsonProperty("Viewer") val viewer: AniListViewer?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListRoot(
|
data class AniListRoot(
|
||||||
@JsonProperty("data") @SerialName("data") val data: AniListData?,
|
@JsonProperty("data") val data: AniListData?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListUser(
|
data class AniListUser(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("picture") @SerialName("picture") val picture: String?,
|
@JsonProperty("picture") val picture: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeNode(
|
data class LikeNode(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
|
//@JsonProperty("idMal") public int idMal;
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikePageInfo(
|
data class LikePageInfo(
|
||||||
@JsonProperty("total") @SerialName("total") val total: Int?,
|
@JsonProperty("total") val total: Int?,
|
||||||
@JsonProperty("currentPage") @SerialName("currentPage") val currentPage: Int?,
|
@JsonProperty("currentPage") val currentPage: Int?,
|
||||||
@JsonProperty("lastPage") @SerialName("lastPage") val lastPage: Int?,
|
@JsonProperty("lastPage") val lastPage: Int?,
|
||||||
@JsonProperty("perPage") @SerialName("perPage") val perPage: Int?,
|
@JsonProperty("perPage") val perPage: Int?,
|
||||||
@JsonProperty("hasNextPage") @SerialName("hasNextPage") val hasNextPage: Boolean?,
|
@JsonProperty("hasNextPage") val hasNextPage: Boolean?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeAnime(
|
data class LikeAnime(
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<LikeNode>?,
|
@JsonProperty("nodes") val nodes: List<LikeNode>?,
|
||||||
@JsonProperty("pageInfo") @SerialName("pageInfo") val pageInfo: LikePageInfo?,
|
@JsonProperty("pageInfo") val pageInfo: LikePageInfo?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeFavourites(
|
data class LikeFavourites(
|
||||||
@JsonProperty("anime") @SerialName("anime") val anime: LikeAnime?,
|
@JsonProperty("anime") val anime: LikeAnime?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeViewer(
|
data class LikeViewer(
|
||||||
@JsonProperty("favourites") @SerialName("favourites") val favourites: LikeFavourites?,
|
@JsonProperty("favourites") val favourites: LikeFavourites?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeData(
|
data class LikeData(
|
||||||
@JsonProperty("Viewer") @SerialName("Viewer") val viewer: LikeViewer?,
|
@JsonProperty("Viewer") val viewer: LikeViewer?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LikeRoot(
|
data class LikeRoot(
|
||||||
@JsonProperty("data") @SerialName("data") val data: LikeData?,
|
@JsonProperty("data") val data: LikeData?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AniListTitleHolder(
|
data class AniListTitleHolder(
|
||||||
@JsonProperty("title") @SerialName("title") val title: Title?,
|
@JsonProperty("title") val title: Title?,
|
||||||
@JsonProperty("isFavourite") @SerialName("isFavourite") val isFavourite: Boolean?,
|
@JsonProperty("isFavourite") val isFavourite: Boolean?,
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
@JsonProperty("progress") @SerialName("progress") val progress: Int?,
|
@JsonProperty("progress") val progress: Int?,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
|
@JsonProperty("episodes") val episodes: Int?,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int?,
|
@JsonProperty("score") val score: Int?,
|
||||||
@JsonProperty("type") @SerialName("type") val type: AniListStatusType?,
|
@JsonProperty("type") val type: AniListStatusType?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetDataMediaListEntry(
|
data class GetDataMediaListEntry(
|
||||||
@JsonProperty("progress") @SerialName("progress") val progress: Int?,
|
@JsonProperty("progress") val progress: Int?,
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int?,
|
@JsonProperty("score") val score: Int?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Nodes(
|
data class Nodes(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
@JsonProperty("mediaRecommendation") @SerialName("mediaRecommendation") val mediaRecommendation: MediaRecommendation?,
|
@JsonProperty("mediaRecommendation") val mediaRecommendation: MediaRecommendation?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetDataMedia(
|
data class GetDataMedia(
|
||||||
@JsonProperty("isFavourite") @SerialName("isFavourite") val isFavourite: Boolean?,
|
@JsonProperty("isFavourite") val isFavourite: Boolean?,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
|
@JsonProperty("episodes") val episodes: Int?,
|
||||||
@JsonProperty("title") @SerialName("title") val title: Title?,
|
@JsonProperty("title") val title: Title?,
|
||||||
@JsonProperty("mediaListEntry") @SerialName("mediaListEntry") val mediaListEntry: GetDataMediaListEntry?,
|
@JsonProperty("mediaListEntry") val mediaListEntry: GetDataMediaListEntry?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Recommendations(
|
data class Recommendations(
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<Nodes>?,
|
@JsonProperty("nodes") val nodes: List<Nodes>?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetDataData(
|
data class GetDataData(
|
||||||
@JsonProperty("Media") @SerialName("Media") val media: GetDataMedia?,
|
@JsonProperty("Media") val media: GetDataMedia?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetDataRoot(
|
data class GetDataRoot(
|
||||||
@JsonProperty("data") @SerialName("data") val data: GetDataData?,
|
@JsonProperty("data") val data: GetDataData?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetSearchTitle(
|
data class GetSearchTitle(
|
||||||
@JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
|
@JsonProperty("romaji") val romaji: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class TrailerObject(
|
data class TrailerObject(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String?,
|
@JsonProperty("id") val id: String?,
|
||||||
@JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: String?,
|
@JsonProperty("thumbnail") val thumbnail: String?,
|
||||||
@JsonProperty("site") @SerialName("site") val site: String?,
|
@JsonProperty("site") val site: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetSearchMedia(
|
data class GetSearchMedia(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
|
@JsonProperty("idMal") val idMal: Int?,
|
||||||
@JsonProperty("seasonYear") @SerialName("seasonYear") val seasonYear: Int,
|
@JsonProperty("seasonYear") val seasonYear: Int,
|
||||||
@JsonProperty("title") @SerialName("title") val title: GetSearchTitle,
|
@JsonProperty("title") val title: GetSearchTitle,
|
||||||
@JsonProperty("startDate") @SerialName("startDate") val startDate: StartedAt,
|
@JsonProperty("startDate") val startDate: StartedAt,
|
||||||
@JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
|
@JsonProperty("averageScore") val averageScore: Int?,
|
||||||
@JsonProperty("meanScore") @SerialName("meanScore") val meanScore: Int?,
|
@JsonProperty("meanScore") val meanScore: Int?,
|
||||||
@JsonProperty("bannerImage") @SerialName("bannerImage") val bannerImage: String?,
|
@JsonProperty("bannerImage") val bannerImage: String?,
|
||||||
@JsonProperty("trailer") @SerialName("trailer") val trailer: TrailerObject?,
|
@JsonProperty("trailer") val trailer: TrailerObject?,
|
||||||
@JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
|
||||||
@JsonProperty("recommendations") @SerialName("recommendations") val recommendations: Recommendations?,
|
@JsonProperty("recommendations") val recommendations: Recommendations?,
|
||||||
@JsonProperty("relations") @SerialName("relations") val relations: SeasonEdges?,
|
@JsonProperty("relations") val relations: SeasonEdges?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetSearchPage(
|
data class GetSearchPage(
|
||||||
@JsonProperty("Page") @SerialName("Page") val page: GetSearchData?,
|
@JsonProperty("Page") val page: GetSearchData?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetSearchData(
|
data class GetSearchData(
|
||||||
@JsonProperty("media") @SerialName("media") val media: List<GetSearchMedia>?,
|
@JsonProperty("media") val media: List<GetSearchMedia>?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class GetSearchRoot(
|
data class GetSearchRoot(
|
||||||
@JsonProperty("data") @SerialName("data") val data: GetSearchPage?,
|
@JsonProperty("data") val data: GetSearchPage?,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
package com.lagradost.cloudstream3.syncproviders.providers
|
package com.lagradost.cloudstream3.syncproviders.providers
|
||||||
|
|
||||||
|
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
|
|
@ -22,15 +22,14 @@ import com.lagradost.cloudstream3.ui.SyncWatchType
|
||||||
import com.lagradost.cloudstream3.ui.library.ListSorting
|
import com.lagradost.cloudstream3.ui.library.ListSorting
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
|
import java.time.Instant
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.ZoneId
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
|
|
@ -69,9 +68,13 @@ class KitsuApi: SyncAPI() {
|
||||||
val request: Request = chain.request()
|
val request: Request = chain.request()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
val response = chain.proceed(request);
|
val response = chain.proceed(request);
|
||||||
|
|
||||||
if (response.isSuccessful) return response
|
if (response.isSuccessful) return response
|
||||||
|
|
||||||
response.close()
|
response.close()
|
||||||
|
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -80,6 +83,7 @@ class KitsuApi: SyncAPI() {
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
return chain.proceed(fallbackRequest)
|
return chain.proceed(fallbackRequest)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -103,7 +107,7 @@ class KitsuApi: SyncAPI() {
|
||||||
).parsed<ResponseToken>()
|
).parsed<ResponseToken>()
|
||||||
|
|
||||||
return AuthToken(
|
return AuthToken(
|
||||||
accessTokenLifetime = APIHolder.unixTime + token.expiresIn.toLong(),
|
accessTokenLifetime = unixTime + token.expiresIn.toLong(),
|
||||||
refreshToken = token.refreshToken,
|
refreshToken = token.refreshToken,
|
||||||
accessToken = token.accessToken,
|
accessToken = token.accessToken,
|
||||||
)
|
)
|
||||||
|
|
@ -122,7 +126,7 @@ class KitsuApi: SyncAPI() {
|
||||||
return AuthToken(
|
return AuthToken(
|
||||||
accessToken = res.accessToken,
|
accessToken = res.accessToken,
|
||||||
refreshToken = res.refreshToken,
|
refreshToken = res.refreshToken,
|
||||||
accessTokenLifetime = APIHolder.unixTime + res.expiresIn.toLong()
|
accessTokenLifetime = unixTime + res.expiresIn.toLong()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -179,9 +183,9 @@ class KitsuApi: SyncAPI() {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuResponse(
|
data class KitsuResponse(
|
||||||
@JsonProperty("data") @SerialName("data") val data: KitsuNode,
|
@field:JsonProperty(value = "data")
|
||||||
|
val data: KitsuNode,
|
||||||
)
|
)
|
||||||
|
|
||||||
val url =
|
val url =
|
||||||
|
|
@ -198,10 +202,10 @@ class KitsuApi: SyncAPI() {
|
||||||
id = id,
|
id = id,
|
||||||
totalEpisodes = anime.episodeCount,
|
totalEpisodes = anime.episodeCount,
|
||||||
title = anime.canonicalTitle ?: anime.titles?.enJp ?: anime.titles?.jaJp.orEmpty(),
|
title = anime.canonicalTitle ?: anime.titles?.enJp ?: anime.titles?.jaJp.orEmpty(),
|
||||||
publicScore = Score.from(anime.ratingTwenty, 20),
|
publicScore = Score.from(anime.ratingTwenty.toString(), 20),
|
||||||
duration = anime.episodeLength,
|
duration = anime.episodeLength,
|
||||||
synopsis = anime.synopsis,
|
synopsis = anime.synopsis,
|
||||||
airStatus = when (anime.status) {
|
airStatus = when(anime.status) {
|
||||||
"finished" -> ShowStatus.Completed
|
"finished" -> ShowStatus.Completed
|
||||||
"current" -> ShowStatus.Ongoing
|
"current" -> ShowStatus.Ongoing
|
||||||
else -> null
|
else -> null
|
||||||
|
|
@ -217,6 +221,7 @@ class KitsuApi: SyncAPI() {
|
||||||
prevSeason = null,
|
prevSeason = null,
|
||||||
actors = null,
|
actors = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun status(auth : AuthData?, id: String): AbstractSyncStatus? {
|
override suspend fun status(auth : AuthData?, id: String): AbstractSyncStatus? {
|
||||||
|
|
@ -245,19 +250,21 @@ class KitsuApi: SyncAPI() {
|
||||||
}
|
}
|
||||||
|
|
||||||
return SyncStatus(
|
return SyncStatus(
|
||||||
score = Score.from(anime.ratingTwenty, 20),
|
score = Score.from(anime.ratingTwenty.toString(), 20),
|
||||||
status = SyncWatchType.fromInternalId(kitsuStatusAsString.indexOf(anime.status)),
|
status = SyncWatchType.fromInternalId(kitsuStatusAsString.indexOf(anime.status)),
|
||||||
isFavorite = null,
|
isFavorite = null,
|
||||||
watchedEpisodes = anime.progress,
|
watchedEpisodes = anime.progress,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun getAnimeIdByTitle(title: String): String? {
|
suspend fun getAnimeIdByTitle(title: String): String? {
|
||||||
|
|
||||||
val animeSelectedFields = arrayOf("titles","canonicalTitle")
|
val animeSelectedFields = arrayOf("titles","canonicalTitle")
|
||||||
val url = "$apiUrl/anime?filter[text]=$title&page[limit]=$KITSU_MAX_SEARCH_LIMIT&fields[anime]=${animeSelectedFields.joinToString(",")}"
|
val url = "$apiUrl/anime?filter[text]=$title&page[limit]=$KITSU_MAX_SEARCH_LIMIT&fields[anime]=${animeSelectedFields.joinToString(",")}"
|
||||||
|
|
||||||
val res = app.get(url, interceptor = apiFallbackInterceptor).parsed<KitsuResponse>()
|
val res = app.get(url, interceptor = apiFallbackInterceptor).parsed<KitsuResponse>()
|
||||||
|
|
||||||
return res.data.firstOrNull()?.id
|
return res.data.firstOrNull()?.id
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun urlToId(url: String): String? =
|
override fun urlToId(url: String): String? =
|
||||||
|
|
@ -268,6 +275,7 @@ class KitsuApi: SyncAPI() {
|
||||||
id: String,
|
id: String,
|
||||||
newStatus: AbstractSyncStatus
|
newStatus: AbstractSyncStatus
|
||||||
): Boolean {
|
): Boolean {
|
||||||
|
|
||||||
return setScoreRequest(
|
return setScoreRequest(
|
||||||
auth ?: return false,
|
auth ?: return false,
|
||||||
id.toIntOrNull() ?: return false,
|
id.toIntOrNull() ?: return false,
|
||||||
|
|
@ -278,18 +286,21 @@ class KitsuApi: SyncAPI() {
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun setScoreRequest(
|
private suspend fun setScoreRequest(
|
||||||
auth: AuthData,
|
auth : AuthData,
|
||||||
id: Int,
|
id: Int,
|
||||||
status: KitsuStatusType? = null,
|
status: KitsuStatusType? = null,
|
||||||
score: Int? = null,
|
score: Int? = null,
|
||||||
numWatchedEpisodes: Int? = null,
|
numWatchedEpisodes: Int? = null,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
|
|
||||||
val libraryEntryId = getAnimeLibraryEntryId(auth, id)
|
val libraryEntryId = getAnimeLibraryEntryId(auth, id)
|
||||||
|
|
||||||
// Exists entry for anime in library
|
// Exists entry for anime in library
|
||||||
if (libraryEntryId != null) {
|
if (libraryEntryId != null) {
|
||||||
|
|
||||||
// Delete anime from library
|
// Delete anime from library
|
||||||
if (status == null || status == KitsuStatusType.None) {
|
if (status == null || status == KitsuStatusType.None) {
|
||||||
|
|
||||||
val res = app.delete(
|
val res = app.delete(
|
||||||
"$apiUrl/library-entries/$libraryEntryId",
|
"$apiUrl/library-entries/$libraryEntryId",
|
||||||
headers = mapOf(
|
headers = mapOf(
|
||||||
|
|
@ -298,7 +309,9 @@ class KitsuApi: SyncAPI() {
|
||||||
interceptor = apiFallbackInterceptor
|
interceptor = apiFallbackInterceptor
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
return res.isSuccessful
|
return res.isSuccessful
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return setScoreRequest(
|
return setScoreRequest(
|
||||||
|
|
@ -308,6 +321,7 @@ class KitsuApi: SyncAPI() {
|
||||||
score,
|
score,
|
||||||
numWatchedEpisodes
|
numWatchedEpisodes
|
||||||
)
|
)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val data = mapOf(
|
val data = mapOf(
|
||||||
|
|
@ -346,6 +360,7 @@ class KitsuApi: SyncAPI() {
|
||||||
)
|
)
|
||||||
|
|
||||||
return res.isSuccessful
|
return res.isSuccessful
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
|
@ -378,11 +393,15 @@ class KitsuApi: SyncAPI() {
|
||||||
interceptor = apiFallbackInterceptor
|
interceptor = apiFallbackInterceptor
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
return res.isSuccessful
|
return res.isSuccessful
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getAnimeLibraryEntryId(auth: AuthData, id: Int): Int? {
|
private suspend fun getAnimeLibraryEntryId(auth: AuthData, id: Int): Int? {
|
||||||
|
|
||||||
val userId = auth.user.id
|
val userId = auth.user.id
|
||||||
|
|
||||||
val res = app.get(
|
val res = app.get(
|
||||||
"$apiUrl/library-entries?filter[userId]=$userId&filter[animeId]=$id",
|
"$apiUrl/library-entries?filter[userId]=$userId&filter[animeId]=$id",
|
||||||
headers = mapOf(
|
headers = mapOf(
|
||||||
|
|
@ -392,6 +411,7 @@ class KitsuApi: SyncAPI() {
|
||||||
).parsed<KitsuResponse>().data.firstOrNull() ?: return null
|
).parsed<KitsuResponse>().data.firstOrNull() ?: return null
|
||||||
|
|
||||||
return res.id.toInt()
|
return res.id.toInt()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun library(auth : AuthData?): LibraryMetadata? {
|
override suspend fun library(auth : AuthData?): LibraryMetadata? {
|
||||||
|
|
@ -433,52 +453,58 @@ class KitsuApi: SyncAPI() {
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getKitsuAnimeList(token: AuthToken, userId: Int): Array<KitsuNode> {
|
private suspend fun getKitsuAnimeList(token: AuthToken, userId: Int): Array<KitsuNode> {
|
||||||
val animeSelectedFields = arrayOf("titles","canonicalTitle","posterImage","synopsis","startDate","endDate","episodeCount")
|
|
||||||
val libraryEntriesSelectedFields = arrayOf("progress","ratingTwenty","updatedAt", "status")
|
val animeSelectedFields = arrayOf("titles","canonicalTitle","posterImage","synopsis","startDate","episodeCount")
|
||||||
|
val libraryEntriesSelectedFields = arrayOf("progress","rating","updatedAt", "status")
|
||||||
val limit = 500
|
val limit = 500
|
||||||
var url = "$apiUrl/library-entries?filter[userId]=$userId&filter[kind]=anime&include=anime&page[limit]=$limit&page[offset]=0&fields[anime]=${animeSelectedFields.joinToString(",")}&fields[libraryEntries]=${libraryEntriesSelectedFields.joinToString(",")}"
|
var url = "$apiUrl/library-entries?filter[userId]=$userId&filter[kind]=anime&include=anime&page[limit]=$limit&page[offset]=0&fields[anime]=${animeSelectedFields.joinToString(",")}&fields[libraryEntries]=${libraryEntriesSelectedFields.joinToString(",")}"
|
||||||
|
|
||||||
val fullList = mutableListOf<KitsuNode>()
|
val fullList = mutableListOf<KitsuNode>()
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
|
||||||
val data: KitsuResponse = getKitsuAnimeListSlice(token, url)
|
val data: KitsuResponse = getKitsuAnimeListSlice(token, url)
|
||||||
|
|
||||||
data.data.forEachIndexed { index, value ->
|
data.data.forEachIndexed { index, value ->
|
||||||
value.anime = data.included?.get(index)
|
value.anime = data.included?.get(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
fullList.addAll(data.data)
|
fullList.addAll(data.data)
|
||||||
|
|
||||||
url = data.links?.next ?: break
|
url = data.links?.next ?: break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return fullList.toTypedArray()
|
return fullList.toTypedArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getKitsuAnimeListSlice(token: AuthToken, url: String): KitsuResponse {
|
private suspend fun getKitsuAnimeListSlice(token: AuthToken, url: String): KitsuResponse {
|
||||||
return app.get(
|
val res = app.get(
|
||||||
url, headers = mapOf(
|
url, headers = mapOf(
|
||||||
"Authorization" to "Bearer ${token.accessToken}",
|
"Authorization" to "Bearer ${token.accessToken}",
|
||||||
),
|
),
|
||||||
interceptor = apiFallbackInterceptor
|
interceptor = apiFallbackInterceptor
|
||||||
).parsed<KitsuResponse>()
|
).parsed<KitsuResponse>()
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResponseToken(
|
data class ResponseToken(
|
||||||
@JsonProperty("token_type") @SerialName("token_type") val tokenType: String,
|
@JsonProperty("token_type") val tokenType: String,
|
||||||
@JsonProperty("expires_in") @SerialName("expires_in") val expiresIn: Int,
|
@JsonProperty("expires_in") val expiresIn: Int,
|
||||||
@JsonProperty("access_token") @SerialName("access_token") val accessToken: String,
|
@JsonProperty("access_token") val accessToken: String,
|
||||||
@JsonProperty("refresh_token") @SerialName("refresh_token") val refreshToken: String,
|
@JsonProperty("refresh_token") val refreshToken: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuNode(
|
data class KitsuNode(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String,
|
@JsonProperty("id") val id: String,
|
||||||
@JsonProperty("attributes") @SerialName("attributes") val attributes: KitsuNodeAttributes,
|
@JsonProperty("attributes") val attributes: KitsuNodeAttributes,
|
||||||
/* User list anime node */
|
/* User list anime node */
|
||||||
@JsonProperty("relationships") @SerialName("relationships") val relationships: KitsuRelationships?,
|
@JsonProperty("relationships") val relationships: KitsuRelationships?,
|
||||||
@JsonProperty("anime") @SerialName("anime") var anime: KitsuAnimeData?,
|
var anime: KitsuAnimeData?
|
||||||
) {
|
) {
|
||||||
fun toLibraryItem(): LibraryItem {
|
fun toLibraryItem(): LibraryItem {
|
||||||
|
|
||||||
val animeItem = this.anime
|
val animeItem = this.anime
|
||||||
|
|
||||||
val numEpisodes = animeItem?.attributes?.episodeCount
|
val numEpisodes = animeItem?.attributes?.episodeCount
|
||||||
|
|
@ -500,7 +526,7 @@ class KitsuApi: SyncAPI() {
|
||||||
this.id,
|
this.id,
|
||||||
this.attributes.progress,
|
this.attributes.progress,
|
||||||
numEpisodes,
|
numEpisodes,
|
||||||
Score.from(this.attributes.ratingTwenty, 20),
|
Score.from(this.attributes.ratingTwenty.toString(), 20),
|
||||||
parseDateLong(this.attributes.updatedAt),
|
parseDateLong(this.attributes.updatedAt),
|
||||||
"Kitsu",
|
"Kitsu",
|
||||||
TvType.Anime,
|
TvType.Anime,
|
||||||
|
|
@ -509,9 +535,12 @@ class KitsuApi: SyncAPI() {
|
||||||
null,
|
null,
|
||||||
plot = synopsis,
|
plot = synopsis,
|
||||||
releaseDate = if (startDate == null) null else try {
|
releaseDate = if (startDate == null) null else try {
|
||||||
Date.from(LocalDate.parse(startDate).atStartOfDay()
|
Date.from(
|
||||||
.atZone(ZoneId.systemDefault())
|
Instant.from(
|
||||||
.toInstant())
|
DateTimeFormatter.ofPattern(if (startDate.length == 4) "yyyy" else if (startDate.length == 7) "yyyy-MM" else "yyyy-MM-dd")
|
||||||
|
.parse(startDate)
|
||||||
|
)
|
||||||
|
)
|
||||||
} catch (_: RuntimeException) {
|
} catch (_: RuntimeException) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
|
|
@ -520,100 +549,93 @@ class KitsuApi: SyncAPI() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuAnimeAttributes(
|
data class KitsuAnimeAttributes(
|
||||||
@JsonProperty("titles") @SerialName("titles") val titles: KitsuTitles?,
|
@JsonProperty("titles") val titles: KitsuTitles?,
|
||||||
@JsonProperty("canonicalTitle") @SerialName("canonicalTitle") val canonicalTitle: String?,
|
@JsonProperty("canonicalTitle") val canonicalTitle: String?,
|
||||||
@JsonProperty("posterImage") @SerialName("posterImage") val posterImage: KitsuPosterImage?,
|
@JsonProperty("posterImage") val posterImage: KitsuPosterImage?,
|
||||||
@JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
|
@JsonProperty("synopsis") val synopsis: String?,
|
||||||
@JsonProperty("startDate") @SerialName("startDate") val startDate: String?,
|
@JsonProperty("startDate") val startDate: String?,
|
||||||
@JsonProperty("endDate") @SerialName("endDate") val endDate: String?,
|
@JsonProperty("endDate") val endDate: String?,
|
||||||
@JsonProperty("episodeCount") @SerialName("episodeCount") val episodeCount: Int?,
|
@JsonProperty("episodeCount") val episodeCount: Int?,
|
||||||
@JsonProperty("episodeLength") @SerialName("episodeLength") val episodeLength: Int?,
|
@JsonProperty("episodeLength") val episodeLength: Int?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuAnimeData(
|
data class KitsuAnimeData(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String,
|
@JsonProperty("id") val id: String,
|
||||||
@JsonProperty("attributes") @SerialName("attributes") val attributes: KitsuAnimeAttributes,
|
@JsonProperty("attributes") val attributes: KitsuAnimeAttributes,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuNodeAttributes(
|
data class KitsuNodeAttributes(
|
||||||
/* General attributes */
|
/* General attributes */
|
||||||
@JsonProperty("titles") @SerialName("titles") val titles: KitsuTitles?,
|
@JsonProperty("titles") val titles: KitsuTitles?,
|
||||||
@JsonProperty("canonicalTitle") @SerialName("canonicalTitle") val canonicalTitle: String?,
|
@JsonProperty("canonicalTitle") val canonicalTitle: String?,
|
||||||
@JsonProperty("posterImage") @SerialName("posterImage") val posterImage: KitsuPosterImage?,
|
@JsonProperty("posterImage") val posterImage: KitsuPosterImage?,
|
||||||
@JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
|
@JsonProperty("synopsis") val synopsis: String?,
|
||||||
@JsonProperty("startDate") @SerialName("startDate") val startDate: String?,
|
@JsonProperty("startDate") val startDate: String?,
|
||||||
@JsonProperty("endDate") @SerialName("endDate") val endDate: String?,
|
@JsonProperty("endDate") val endDate: String?,
|
||||||
@JsonProperty("episodeCount") @SerialName("episodeCount") val episodeCount: Int?,
|
@JsonProperty("episodeCount") val episodeCount: Int?,
|
||||||
@JsonProperty("episodeLength") @SerialName("episodeLength") val episodeLength: Int?,
|
@JsonProperty("episodeLength") val episodeLength: Int?,
|
||||||
/* User attributes */
|
/* User attributes */
|
||||||
@JsonProperty("name") @SerialName("name") val name: String?,
|
@JsonProperty("name") val name: String?,
|
||||||
@JsonProperty("location") @SerialName("location") val location: String?,
|
@JsonProperty("location") val location: String?,
|
||||||
@JsonProperty("createdAt") @SerialName("createdAt") val createdAt: String?,
|
@JsonProperty("createdAt") val createdAt: String?,
|
||||||
@JsonProperty("avatar") @SerialName("avatar") val avatar: KitsuUserAvatar?,
|
@JsonProperty("avatar") val avatar: KitsuUserAvatar?,
|
||||||
/* User list anime attributes */
|
/* User list anime attributes */
|
||||||
@JsonProperty("progress") @SerialName("progress") val progress: Int?,
|
@JsonProperty("progress") val progress: Int?,
|
||||||
@JsonProperty("ratingTwenty") @SerialName("ratingTwenty") val ratingTwenty: Int?,
|
@JsonProperty("ratingTwenty") val ratingTwenty: Float?,
|
||||||
@JsonProperty("updatedAt") @SerialName("updatedAt") val updatedAt: String?,
|
@JsonProperty("updatedAt") val updatedAt: String?,
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuRelationships(
|
data class KitsuRelationships(
|
||||||
@JsonProperty("anime") @SerialName("anime") val anime: KitsuRelationshipsAnime?,
|
@JsonProperty("anime") val anime: KitsuRelationshipsAnime?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuRelationshipsAnime(
|
data class KitsuRelationshipsAnime(
|
||||||
@JsonProperty("links") @SerialName("links") val links: KitsuLinks?,
|
@JsonProperty("links") val links: KitsuLinks?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuPosterImage(
|
data class KitsuPosterImage(
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuTitles(
|
data class KitsuTitles(
|
||||||
@JsonProperty("en_jp") @SerialName("en_jp") val enJp: String?,
|
@JsonProperty("en_jp") val enJp: String?,
|
||||||
@JsonProperty("ja_jp") @SerialName("ja_jp") val jaJp: String?,
|
@JsonProperty("ja_jp") val jaJp: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuUserAvatar(
|
data class KitsuUserAvatar(
|
||||||
@JsonProperty("original") @SerialName("original") val original: String?,
|
@JsonProperty("original") val original: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuLinks(
|
data class KitsuLinks(
|
||||||
/* Pagination */
|
/* Pagination */
|
||||||
@JsonProperty("first") @SerialName("first") val first: String?,
|
@JsonProperty("first") val first: String?,
|
||||||
@JsonProperty("next") @SerialName("next") val next: String?,
|
@JsonProperty("next") val next: String?,
|
||||||
@JsonProperty("last") @SerialName("last") val last: String?,
|
@JsonProperty("last") val last: String?,
|
||||||
/* Relationships */
|
/* Relationships */
|
||||||
@JsonProperty("related") @SerialName("related") val related: String?,
|
@JsonProperty("related") val related: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuResponse(
|
data class KitsuResponse(
|
||||||
@JsonProperty("links") @SerialName("links") val links: KitsuLinks?,
|
@JsonProperty("links") val links: KitsuLinks?,
|
||||||
@JsonProperty("data") @SerialName("data") val data: List<KitsuNode>,
|
@JsonProperty("data") val data: List<KitsuNode>,
|
||||||
/* When requesting related info (User library entry -> anime) */
|
/* When requesting related info (User library entry -> anime) */
|
||||||
@JsonProperty("included") @SerialName("included") val included: List<KitsuAnimeData>?,
|
@JsonProperty("included") val included: List<KitsuAnimeData>?,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
const val KITSU_CACHED_LIST: String = "kitsu_cached_list"
|
const val KITSU_CACHED_LIST: String = "kitsu_cached_list"
|
||||||
private fun parseDateLong(string: String?): Long? {
|
private fun parseDateLong(string: String?): Long? {
|
||||||
return try {
|
return try {
|
||||||
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()).parse(
|
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()).parse(
|
||||||
string ?: return null
|
string ?: return null
|
||||||
)?.time?.div(1000)
|
)?.time?.div(1000)
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -622,13 +644,13 @@ class KitsuApi: SyncAPI() {
|
||||||
arrayOf("current", "completed", "on_hold", "dropped", "planned")
|
arrayOf("current", "completed", "on_hold", "dropped", "planned")
|
||||||
private fun fromIntToAnimeStatus(inp: SyncWatchType): KitsuStatusType {
|
private fun fromIntToAnimeStatus(inp: SyncWatchType): KitsuStatusType {
|
||||||
return when (inp) {
|
return when (inp) {
|
||||||
SyncWatchType.NONE -> KitsuStatusType.None
|
SyncWatchType.NONE -> KitsuStatusType.None
|
||||||
SyncWatchType.WATCHING -> KitsuStatusType.Watching
|
SyncWatchType.WATCHING -> KitsuStatusType.Watching
|
||||||
SyncWatchType.COMPLETED -> KitsuStatusType.Completed
|
SyncWatchType.COMPLETED -> KitsuStatusType.Completed
|
||||||
SyncWatchType.ONHOLD -> KitsuStatusType.OnHold
|
SyncWatchType.ONHOLD -> KitsuStatusType.OnHold
|
||||||
SyncWatchType.DROPPED -> KitsuStatusType.Dropped
|
SyncWatchType.DROPPED -> KitsuStatusType.Dropped
|
||||||
SyncWatchType.PLANTOWATCH -> KitsuStatusType.PlanToWatch
|
SyncWatchType.PLANTOWATCH -> KitsuStatusType.PlanToWatch
|
||||||
SyncWatchType.REWATCHING -> KitsuStatusType.Watching
|
SyncWatchType.REWATCHING -> KitsuStatusType.Watching
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -643,12 +665,12 @@ class KitsuApi: SyncAPI() {
|
||||||
|
|
||||||
private fun convertToStatus(string: String): KitsuStatusType {
|
private fun convertToStatus(string: String): KitsuStatusType {
|
||||||
return when (string) {
|
return when (string) {
|
||||||
"current" -> KitsuStatusType.Watching
|
"current" -> KitsuStatusType.Watching
|
||||||
"completed" -> KitsuStatusType.Completed
|
"completed" -> KitsuStatusType.Completed
|
||||||
"on_hold" -> KitsuStatusType.OnHold
|
"on_hold" -> KitsuStatusType.OnHold
|
||||||
"dropped" -> KitsuStatusType.Dropped
|
"dropped" -> KitsuStatusType.Dropped
|
||||||
"planned" -> KitsuStatusType.PlanToWatch
|
"planned" -> KitsuStatusType.PlanToWatch
|
||||||
else -> KitsuStatusType.None
|
else -> KitsuStatusType.None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -670,7 +692,7 @@ object Kitsu {
|
||||||
"https://kitsu.io/api/graphql",
|
"https://kitsu.io/api/graphql",
|
||||||
headers = headers,
|
headers = headers,
|
||||||
data = mapOf("query" to query)
|
data = mapOf("query" to query)
|
||||||
).parsed<KitsuResponse>()
|
).parsed()
|
||||||
}
|
}
|
||||||
|
|
||||||
private val cache: MutableMap<Pair<String, String>, Map<Int, KitsuResponse.Node>> =
|
private val cache: MutableMap<Pair<String, String>, Map<Int, KitsuResponse.Node>> =
|
||||||
|
|
@ -752,52 +774,44 @@ query {
|
||||||
return map
|
return map
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class KitsuResponse(
|
data class KitsuResponse(
|
||||||
@JsonProperty("data") @SerialName("data") val data: Data? = null,
|
val data: Data? = null
|
||||||
) {
|
) {
|
||||||
@Serializable
|
|
||||||
data class Data(
|
data class Data(
|
||||||
@JsonProperty("lookupMapping") @SerialName("lookupMapping") val lookupMapping: LookupMapping? = null,
|
val lookupMapping: LookupMapping? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class LookupMapping(
|
data class LookupMapping(
|
||||||
@JsonProperty("id") @SerialName("id") val id: String? = null,
|
val id: String? = null,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: Episodes? = null,
|
val episodes: Episodes? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Episodes(
|
data class Episodes(
|
||||||
@JsonProperty("nodes") @SerialName("nodes") val nodes: List<Node?>? = null,
|
val nodes: List<Node?>? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Node(
|
data class Node(
|
||||||
@JsonProperty("number") @SerialName("number") val num: Int? = null,
|
@JsonProperty("number")
|
||||||
@JsonProperty("titles") @SerialName("titles") val titles: Titles? = null,
|
val num: Int? = null,
|
||||||
@JsonProperty("description") @SerialName("description") val description: Description? = null,
|
val titles: Titles? = null,
|
||||||
@JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: Thumbnail? = null,
|
val description: Description? = null,
|
||||||
|
val thumbnail: Thumbnail? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Description(
|
data class Description(
|
||||||
@JsonProperty("en") @SerialName("en") val en: String? = null,
|
val en: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Thumbnail(
|
data class Thumbnail(
|
||||||
@JsonProperty("original") @SerialName("original") val original: Original? = null,
|
val original: Original? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Original(
|
data class Original(
|
||||||
@JsonProperty("url") @SerialName("url") val url: String? = null,
|
val url: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Titles(
|
data class Titles(
|
||||||
@JsonProperty("canonical") @SerialName("canonical") val canonical: String? = null,
|
val canonical: String? = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@ package com.lagradost.cloudstream3.syncproviders.providers
|
||||||
|
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.BuildConfig
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
|
|
@ -21,9 +19,8 @@ import com.lagradost.cloudstream3.ui.SyncWatchType
|
||||||
import com.lagradost.cloudstream3.ui.library.ListSorting
|
import com.lagradost.cloudstream3.ui.library.ListSorting
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
|
import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
@ -37,7 +34,7 @@ class MALApi : SyncAPI() {
|
||||||
override var name = "MAL"
|
override var name = "MAL"
|
||||||
override val idPrefix = "mal"
|
override val idPrefix = "mal"
|
||||||
|
|
||||||
private val key = BuildConfig.MAL_KEY
|
val key = "1714d6f2f4f7cc19644384f8c4629910"
|
||||||
private val apiUrl = "https://api.myanimelist.net"
|
private val apiUrl = "https://api.myanimelist.net"
|
||||||
override val hasOAuth2 = true
|
override val hasOAuth2 = true
|
||||||
override val redirectUrlIdentifier: String? = "mallogin"
|
override val redirectUrlIdentifier: String? = "mallogin"
|
||||||
|
|
@ -52,17 +49,16 @@ class MALApi : SyncAPI() {
|
||||||
SyncWatchType.PLANTOWATCH,
|
SyncWatchType.PLANTOWATCH,
|
||||||
SyncWatchType.DROPPED,
|
SyncWatchType.DROPPED,
|
||||||
SyncWatchType.ONHOLD,
|
SyncWatchType.ONHOLD,
|
||||||
SyncWatchType.NONE,
|
SyncWatchType.NONE
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class PayLoad(
|
||||||
data class Payload(
|
val requestId: Int,
|
||||||
@JsonProperty("requestId") @SerialName("requestId") val requestId: Int,
|
val codeVerifier: String
|
||||||
@JsonProperty("codeVerifier") @SerialName("codeVerifier") val codeVerifier: String,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
|
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
|
||||||
val payloadData = parseJson<Payload>(payload!!)
|
val payloadData = parseJson<PayLoad>(payload!!)
|
||||||
val sanitizer = splitRedirectUrl(redirectUrl)
|
val sanitizer = splitRedirectUrl(redirectUrl)
|
||||||
val state = sanitizer["state"]!!
|
val state = sanitizer["state"]!!
|
||||||
|
|
||||||
|
|
@ -78,13 +74,13 @@ class MALApi : SyncAPI() {
|
||||||
"client_id" to key,
|
"client_id" to key,
|
||||||
"code" to currentCode,
|
"code" to currentCode,
|
||||||
"code_verifier" to payloadData.codeVerifier,
|
"code_verifier" to payloadData.codeVerifier,
|
||||||
"grant_type" to "authorization_code",
|
"grant_type" to "authorization_code"
|
||||||
)
|
)
|
||||||
).parsed<ResponseToken>()
|
).parsed<ResponseToken>()
|
||||||
return AuthToken(
|
return AuthToken(
|
||||||
accessTokenLifetime = APIHolder.unixTime + token.expiresIn.toLong(),
|
accessTokenLifetime = unixTime + token.expiresIn.toLong(),
|
||||||
refreshToken = token.refreshToken,
|
refreshToken = token.refreshToken,
|
||||||
accessToken = token.accessToken,
|
accessToken = token.accessToken
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -98,13 +94,13 @@ class MALApi : SyncAPI() {
|
||||||
return AuthUser(
|
return AuthUser(
|
||||||
id = user.id,
|
id = user.id,
|
||||||
name = user.name,
|
name = user.name,
|
||||||
profilePicture = user.picture,
|
profilePicture = user.picture
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun search(auth: AuthData?, query: String): List<SyncAPI.SyncSearchResult>? {
|
override suspend fun search(auth : AuthData?, query: String): List<SyncAPI.SyncSearchResult>? {
|
||||||
val auth = auth?.token?.accessToken ?: return null
|
val auth = auth?.token?.accessToken ?: return null
|
||||||
val url = "$apiUrl/v2/anime?q=$query&limit=$MAL_MAX_SEARCH_LIMIT"
|
val url = "$apiUrl/v2/anime?q=$name&limit=$MAL_MAX_SEARCH_LIMIT"
|
||||||
val res = app.get(
|
val res = app.get(
|
||||||
url, headers = mapOf(
|
url, headers = mapOf(
|
||||||
"Authorization" to "Bearer $auth",
|
"Authorization" to "Bearer $auth",
|
||||||
|
|
@ -117,7 +113,7 @@ class MALApi : SyncAPI() {
|
||||||
this.name,
|
this.name,
|
||||||
node.id.toString(),
|
node.id.toString(),
|
||||||
"$mainUrl/anime/${node.id}/",
|
"$mainUrl/anime/${node.id}/",
|
||||||
node.mainPicture?.large ?: node.mainPicture?.medium,
|
node.mainPicture?.large ?: node.mainPicture?.medium
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -126,7 +122,7 @@ class MALApi : SyncAPI() {
|
||||||
Regex("""/anime/((.*)/|(.*))""").find(url)!!.groupValues.first()
|
Regex("""/anime/((.*)/|(.*))""").find(url)!!.groupValues.first()
|
||||||
|
|
||||||
override suspend fun updateStatus(
|
override suspend fun updateStatus(
|
||||||
auth: AuthData?,
|
auth : AuthData?,
|
||||||
id: String,
|
id: String,
|
||||||
newStatus: SyncAPI.AbstractSyncStatus
|
newStatus: SyncAPI.AbstractSyncStatus
|
||||||
): Boolean {
|
): Boolean {
|
||||||
|
|
@ -139,89 +135,82 @@ class MALApi : SyncAPI() {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalAnime(
|
data class MalAnime(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id") val id: Int?,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String?,
|
@JsonProperty("title") val title: String?,
|
||||||
@JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MainPicture?,
|
@JsonProperty("main_picture") val mainPicture: MainPicture?,
|
||||||
@JsonProperty("alternative_titles") @SerialName("alternative_titles") val alternativeTitles: AlternativeTitles?,
|
@JsonProperty("alternative_titles") val alternativeTitles: AlternativeTitles?,
|
||||||
@JsonProperty("start_date") @SerialName("start_date") val startDate: String?,
|
@JsonProperty("start_date") val startDate: String?,
|
||||||
@JsonProperty("end_date") @SerialName("end_date") val endDate: String?,
|
@JsonProperty("end_date") val endDate: String?,
|
||||||
@JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
|
@JsonProperty("synopsis") val synopsis: String?,
|
||||||
@JsonProperty("mean") @SerialName("mean") val mean: Double?,
|
@JsonProperty("mean") val mean: Double?,
|
||||||
@JsonProperty("rank") @SerialName("rank") val rank: Int?,
|
@JsonProperty("rank") val rank: Int?,
|
||||||
@JsonProperty("popularity") @SerialName("popularity") val popularity: Int?,
|
@JsonProperty("popularity") val popularity: Int?,
|
||||||
@JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int?,
|
@JsonProperty("num_list_users") val numListUsers: Int?,
|
||||||
@JsonProperty("num_scoring_users") @SerialName("num_scoring_users") val numScoringUsers: Int?,
|
@JsonProperty("num_scoring_users") val numScoringUsers: Int?,
|
||||||
@JsonProperty("nsfw") @SerialName("nsfw") val nsfw: String?,
|
@JsonProperty("nsfw") val nsfw: String?,
|
||||||
@JsonProperty("created_at") @SerialName("created_at") val createdAt: String?,
|
@JsonProperty("created_at") val createdAt: String?,
|
||||||
@JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String?,
|
@JsonProperty("updated_at") val updatedAt: String?,
|
||||||
@JsonProperty("media_type") @SerialName("media_type") val mediaType: String?,
|
@JsonProperty("media_type") val mediaType: String?,
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("genres") @SerialName("genres") val genres: ArrayList<Genres>?,
|
@JsonProperty("genres") val genres: ArrayList<Genres>?,
|
||||||
@JsonProperty("my_list_status") @SerialName("my_list_status") val myListStatus: MyListStatus?,
|
@JsonProperty("my_list_status") val myListStatus: MyListStatus?,
|
||||||
@JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int?,
|
@JsonProperty("num_episodes") val numEpisodes: Int?,
|
||||||
@JsonProperty("start_season") @SerialName("start_season") val startSeason: StartSeason?,
|
@JsonProperty("start_season") val startSeason: StartSeason?,
|
||||||
@JsonProperty("broadcast") @SerialName("broadcast") val broadcast: Broadcast?,
|
@JsonProperty("broadcast") val broadcast: Broadcast?,
|
||||||
@JsonProperty("source") @SerialName("source") val source: String?,
|
@JsonProperty("source") val source: String?,
|
||||||
@JsonProperty("average_episode_duration") @SerialName("average_episode_duration") val averageEpisodeDuration: Int?,
|
@JsonProperty("average_episode_duration") val averageEpisodeDuration: Int?,
|
||||||
@JsonProperty("rating") @SerialName("rating") val rating: String?,
|
@JsonProperty("rating") val rating: String?,
|
||||||
@JsonProperty("pictures") @SerialName("pictures") val pictures: ArrayList<MainPicture>?,
|
@JsonProperty("pictures") val pictures: ArrayList<MainPicture>?,
|
||||||
@JsonProperty("background") @SerialName("background") val background: String?,
|
@JsonProperty("background") val background: String?,
|
||||||
@JsonProperty("related_anime") @SerialName("related_anime") val relatedAnime: ArrayList<RelatedAnime>?,
|
@JsonProperty("related_anime") val relatedAnime: ArrayList<RelatedAnime>?,
|
||||||
@JsonProperty("related_manga") @SerialName("related_manga") val relatedManga: ArrayList<String>?,
|
@JsonProperty("related_manga") val relatedManga: ArrayList<String>?,
|
||||||
@JsonProperty("recommendations") @SerialName("recommendations") val recommendations: ArrayList<Recommendations>?,
|
@JsonProperty("recommendations") val recommendations: ArrayList<Recommendations>?,
|
||||||
@JsonProperty("studios") @SerialName("studios") val studios: ArrayList<Studios>?,
|
@JsonProperty("studios") val studios: ArrayList<Studios>?,
|
||||||
@JsonProperty("statistics") @SerialName("statistics") val statistics: Statistics?,
|
@JsonProperty("statistics") val statistics: Statistics?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Recommendations(
|
data class Recommendations(
|
||||||
@JsonProperty("node") @SerialName("node") val node: Node? = null,
|
@JsonProperty("node") val node: Node? = null,
|
||||||
@JsonProperty("num_recommendations") @SerialName("num_recommendations") val numRecommendations: Int? = null,
|
@JsonProperty("num_recommendations") val numRecommendations: Int? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Studios(
|
data class Studios(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int? = null,
|
@JsonProperty("id") val id: Int? = null,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String? = null,
|
@JsonProperty("name") val name: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MyListStatus(
|
data class MyListStatus(
|
||||||
@JsonProperty("status") @SerialName("status") val status: String? = null,
|
@JsonProperty("status") val status: String? = null,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int? = null,
|
@JsonProperty("score") val score: Int? = null,
|
||||||
@JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int? = null,
|
@JsonProperty("num_episodes_watched") val numEpisodesWatched: Int? = null,
|
||||||
@JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean? = null,
|
@JsonProperty("is_rewatching") val isRewatching: Boolean? = null,
|
||||||
@JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String? = null,
|
@JsonProperty("updated_at") val updatedAt: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class RelatedAnime(
|
data class RelatedAnime(
|
||||||
@JsonProperty("node") @SerialName("node") val node: Node? = null,
|
@JsonProperty("node") val node: Node? = null,
|
||||||
@JsonProperty("relation_type") @SerialName("relation_type") val relationType: String? = null,
|
@JsonProperty("relation_type") val relationType: String? = null,
|
||||||
@JsonProperty("relation_type_formatted") @SerialName("relation_type_formatted") val relationTypeFormatted: String? = null,
|
@JsonProperty("relation_type_formatted") val relationTypeFormatted: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Status(
|
data class Status(
|
||||||
@JsonProperty("watching") @SerialName("watching") val watching: String? = null,
|
@JsonProperty("watching") val watching: String? = null,
|
||||||
@JsonProperty("completed") @SerialName("completed") val completed: String? = null,
|
@JsonProperty("completed") val completed: String? = null,
|
||||||
@JsonProperty("on_hold") @SerialName("on_hold") val onHold: String? = null,
|
@JsonProperty("on_hold") val onHold: String? = null,
|
||||||
@JsonProperty("dropped") @SerialName("dropped") val dropped: String? = null,
|
@JsonProperty("dropped") val dropped: String? = null,
|
||||||
@JsonProperty("plan_to_watch") @SerialName("plan_to_watch") val planToWatch: String? = null,
|
@JsonProperty("plan_to_watch") val planToWatch: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Statistics(
|
data class Statistics(
|
||||||
@JsonProperty("status") @SerialName("status") val status: Status? = null,
|
@JsonProperty("status") val status: Status? = null,
|
||||||
@JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int? = null,
|
@JsonProperty("num_list_users") val numListUsers: Int? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun parseDate(string: String?): Long? {
|
private fun parseDate(string: String?): Long? {
|
||||||
return try {
|
return try {
|
||||||
SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(string ?: return null)?.time
|
SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(string ?: return null)?.time
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -232,11 +221,11 @@ class MALApi : SyncAPI() {
|
||||||
apiName = this.name,
|
apiName = this.name,
|
||||||
syncId = node.id.toString(),
|
syncId = node.id.toString(),
|
||||||
url = "$mainUrl/anime/${node.id}",
|
url = "$mainUrl/anime/${node.id}",
|
||||||
posterUrl = node.mainPicture?.large,
|
posterUrl = node.mainPicture?.large
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun load(auth: AuthData?, id: String): SyncAPI.SyncResult? {
|
override suspend fun load(auth : AuthData?, id: String): SyncAPI.SyncResult? {
|
||||||
val auth = auth?.token?.accessToken ?: return null
|
val auth = auth?.token?.accessToken ?: return null
|
||||||
val internalId = id.toIntOrNull() ?: return null
|
val internalId = id.toIntOrNull() ?: return null
|
||||||
val url =
|
val url =
|
||||||
|
|
@ -258,7 +247,7 @@ class MALApi : SyncAPI() {
|
||||||
airStatus = when (malAnime.status) {
|
airStatus = when (malAnime.status) {
|
||||||
"finished_airing" -> ShowStatus.Completed
|
"finished_airing" -> ShowStatus.Completed
|
||||||
"currently_airing" -> ShowStatus.Ongoing
|
"currently_airing" -> ShowStatus.Ongoing
|
||||||
// "not_yet_aired"
|
//"not_yet_aired"
|
||||||
else -> null
|
else -> null
|
||||||
},
|
},
|
||||||
nextAiring = null,
|
nextAiring = null,
|
||||||
|
|
@ -282,7 +271,7 @@ class MALApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun status(auth: AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
|
override suspend fun status(auth : AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
|
||||||
val auth = auth?.token?.accessToken ?: return null
|
val auth = auth?.token?.accessToken ?: return null
|
||||||
|
|
||||||
// https://myanimelist.net/apiconfig/references/api/v2#operation/anime_anime_id_get
|
// https://myanimelist.net/apiconfig/references/api/v2#operation/anime_anime_id_get
|
||||||
|
|
@ -345,7 +334,7 @@ class MALApi : SyncAPI() {
|
||||||
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()).parse(
|
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()).parse(
|
||||||
string ?: return null
|
string ?: return null
|
||||||
)?.time?.div(1000)
|
)?.time?.div(1000)
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -355,10 +344,12 @@ class MALApi : SyncAPI() {
|
||||||
val codeVerifier = generateCodeVerifier()
|
val codeVerifier = generateCodeVerifier()
|
||||||
val requestId = ++requestIdCounter
|
val requestId = ++requestIdCounter
|
||||||
val codeChallenge = codeVerifier
|
val codeChallenge = codeVerifier
|
||||||
val request = "$mainUrl/v1/oauth2/authorize?response_type=code&client_id=$key&code_challenge=$codeChallenge&state=RequestID$requestId"
|
val request =
|
||||||
|
"$mainUrl/v1/oauth2/authorize?response_type=code&client_id=$key&code_challenge=$codeChallenge&state=RequestID$requestId"
|
||||||
|
|
||||||
return AuthLoginPage(
|
return AuthLoginPage(
|
||||||
url = request,
|
url = request,
|
||||||
payload = Payload(requestId, codeVerifier).toJson(),
|
payload = PayLoad(requestId, codeVerifier).toJson()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -368,71 +359,69 @@ class MALApi : SyncAPI() {
|
||||||
data = mapOf(
|
data = mapOf(
|
||||||
"client_id" to key,
|
"client_id" to key,
|
||||||
"grant_type" to "refresh_token",
|
"grant_type" to "refresh_token",
|
||||||
"refresh_token" to token.refreshToken!!,
|
"refresh_token" to token.refreshToken!!
|
||||||
)
|
)
|
||||||
).parsed<ResponseToken>()
|
).parsed<ResponseToken>()
|
||||||
|
|
||||||
return AuthToken(
|
return AuthToken(
|
||||||
accessToken = res.accessToken,
|
accessToken = res.accessToken,
|
||||||
refreshToken = res.refreshToken,
|
refreshToken = res.refreshToken,
|
||||||
accessTokenLifetime = APIHolder.unixTime + res.expiresIn.toLong(),
|
accessTokenLifetime = unixTime + res.expiresIn.toLong()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var requestIdCounter = 0
|
private var requestIdCounter = 0
|
||||||
|
|
||||||
|
|
||||||
private val allTitles = hashMapOf<Int, MalTitleHolder>()
|
private val allTitles = hashMapOf<Int, MalTitleHolder>()
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalList(
|
data class MalList(
|
||||||
@JsonProperty("data") @SerialName("data") val data: List<Data>,
|
@JsonProperty("data") val data: List<Data>,
|
||||||
@JsonProperty("paging") @SerialName("paging") val paging: Paging,
|
@JsonProperty("paging") val paging: Paging
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MainPicture(
|
data class MainPicture(
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String,
|
@JsonProperty("medium") val medium: String,
|
||||||
@JsonProperty("large") @SerialName("large") val large: String,
|
@JsonProperty("large") val large: String
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Node(
|
data class Node(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String,
|
@JsonProperty("title") val title: String,
|
||||||
@JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MainPicture?,
|
@JsonProperty("main_picture") val mainPicture: MainPicture?,
|
||||||
@JsonProperty("alternative_titles") @SerialName("alternative_titles") val alternativeTitles: AlternativeTitles?,
|
@JsonProperty("alternative_titles") val alternativeTitles: AlternativeTitles?,
|
||||||
@JsonProperty("media_type") @SerialName("media_type") val mediaType: String?,
|
@JsonProperty("media_type") val mediaType: String?,
|
||||||
@JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int?,
|
@JsonProperty("num_episodes") val numEpisodes: Int?,
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("start_date") @SerialName("start_date") val startDate: String?,
|
@JsonProperty("start_date") val startDate: String?,
|
||||||
@JsonProperty("end_date") @SerialName("end_date") val endDate: String?,
|
@JsonProperty("end_date") val endDate: String?,
|
||||||
@JsonProperty("average_episode_duration") @SerialName("average_episode_duration") val averageEpisodeDuration: Int?,
|
@JsonProperty("average_episode_duration") val averageEpisodeDuration: Int?,
|
||||||
@JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
|
@JsonProperty("synopsis") val synopsis: String?,
|
||||||
@JsonProperty("mean") @SerialName("mean") val mean: Double?,
|
@JsonProperty("mean") val mean: Double?,
|
||||||
@JsonProperty("genres") @SerialName("genres") val genres: List<Genres>?,
|
@JsonProperty("genres") val genres: List<Genres>?,
|
||||||
@JsonProperty("rank") @SerialName("rank") val rank: Int?,
|
@JsonProperty("rank") val rank: Int?,
|
||||||
@JsonProperty("popularity") @SerialName("popularity") val popularity: Int?,
|
@JsonProperty("popularity") val popularity: Int?,
|
||||||
@JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int?,
|
@JsonProperty("num_list_users") val numListUsers: Int?,
|
||||||
@JsonProperty("num_favorites") @SerialName("num_favorites") val numFavorites: Int?,
|
@JsonProperty("num_favorites") val numFavorites: Int?,
|
||||||
@JsonProperty("num_scoring_users") @SerialName("num_scoring_users") val numScoringUsers: Int?,
|
@JsonProperty("num_scoring_users") val numScoringUsers: Int?,
|
||||||
@JsonProperty("start_season") @SerialName("start_season") val startSeason: StartSeason?,
|
@JsonProperty("start_season") val startSeason: StartSeason?,
|
||||||
@JsonProperty("broadcast") @SerialName("broadcast") val broadcast: Broadcast?,
|
@JsonProperty("broadcast") val broadcast: Broadcast?,
|
||||||
@JsonProperty("nsfw") @SerialName("nsfw") val nsfw: String?,
|
@JsonProperty("nsfw") val nsfw: String?,
|
||||||
@JsonProperty("created_at") @SerialName("created_at") val createdAt: String?,
|
@JsonProperty("created_at") val createdAt: String?,
|
||||||
@JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String?,
|
@JsonProperty("updated_at") val updatedAt: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ListStatus(
|
data class ListStatus(
|
||||||
@JsonProperty("status") @SerialName("status") val status: String?,
|
@JsonProperty("status") val status: String?,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int,
|
@JsonProperty("score") val score: Int,
|
||||||
@JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int,
|
@JsonProperty("num_episodes_watched") val numEpisodesWatched: Int,
|
||||||
@JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean,
|
@JsonProperty("is_rewatching") val isRewatching: Boolean,
|
||||||
@JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String,
|
@JsonProperty("updated_at") val updatedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Data(
|
data class Data(
|
||||||
@JsonProperty("node") @SerialName("node") val node: Node,
|
@JsonProperty("node") val node: Node,
|
||||||
@JsonProperty("list_status") @SerialName("list_status") val listStatus: ListStatus?,
|
@JsonProperty("list_status") val listStatus: ListStatus?,
|
||||||
) {
|
) {
|
||||||
fun toLibraryItem(): SyncAPI.LibraryItem {
|
fun toLibraryItem(): SyncAPI.LibraryItem {
|
||||||
return SyncAPI.LibraryItem(
|
return SyncAPI.LibraryItem(
|
||||||
|
|
@ -463,37 +452,32 @@ class MALApi : SyncAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Paging(
|
data class Paging(
|
||||||
@JsonProperty("next") @SerialName("next") val next: String?,
|
@JsonProperty("next") val next: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class AlternativeTitles(
|
data class AlternativeTitles(
|
||||||
@JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List<String>,
|
@JsonProperty("synonyms") val synonyms: List<String>,
|
||||||
@JsonProperty("en") @SerialName("en") val en: String,
|
@JsonProperty("en") val en: String,
|
||||||
@JsonProperty("ja") @SerialName("ja") val ja: String,
|
@JsonProperty("ja") val ja: String
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Genres(
|
data class Genres(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class StartSeason(
|
data class StartSeason(
|
||||||
@JsonProperty("year") @SerialName("year") val year: Int,
|
@JsonProperty("year") val year: Int,
|
||||||
@JsonProperty("season") @SerialName("season") val season: String,
|
@JsonProperty("season") val season: String
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Broadcast(
|
data class Broadcast(
|
||||||
@JsonProperty("day_of_the_week") @SerialName("day_of_the_week") val dayOfTheWeek: String?,
|
@JsonProperty("day_of_the_week") val dayOfTheWeek: String?,
|
||||||
@JsonProperty("start_time") @SerialName("start_time") val startTime: String?,
|
@JsonProperty("start_time") val startTime: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
override suspend fun library(auth: AuthData?): LibraryMetadata? {
|
override suspend fun library(auth : AuthData?): LibraryMetadata? {
|
||||||
val list = getMalAnimeListSmart(auth ?: return null)?.groupBy {
|
val list = getMalAnimeListSmart(auth ?: return null)?.groupBy {
|
||||||
convertToStatus(it.listStatus?.status ?: "").stringRes
|
convertToStatus(it.listStatus?.status ?: "").stringRes
|
||||||
}?.mapValues { group ->
|
}?.mapValues { group ->
|
||||||
|
|
@ -521,7 +505,7 @@ class MALApi : SyncAPI() {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getMalAnimeListSmart(auth: AuthData): Array<Data>? {
|
private suspend fun getMalAnimeListSmart(auth : AuthData): Array<Data>? {
|
||||||
return if (requireLibraryRefresh) {
|
return if (requireLibraryRefresh) {
|
||||||
val list = getMalAnimeList(auth.token)
|
val list = getMalAnimeList(auth.token)
|
||||||
setKey(MAL_CACHED_LIST, auth.user.id.toString(), list)
|
setKey(MAL_CACHED_LIST, auth.user.id.toString(), list)
|
||||||
|
|
@ -536,7 +520,7 @@ class MALApi : SyncAPI() {
|
||||||
val fullList = mutableListOf<Data>()
|
val fullList = mutableListOf<Data>()
|
||||||
val offsetRegex = Regex("""offset=(\d+)""")
|
val offsetRegex = Regex("""offset=(\d+)""")
|
||||||
while (true) {
|
while (true) {
|
||||||
val data: MalList = getMalAnimeListSlice(token, offset)
|
val data: MalList = getMalAnimeListSlice(token, offset) ?: break
|
||||||
fullList.addAll(data.data)
|
fullList.addAll(data.data)
|
||||||
offset =
|
offset =
|
||||||
data.paging.next?.let { offsetRegex.find(it)?.groupValues?.get(1)?.toInt() }
|
data.paging.next?.let { offsetRegex.find(it)?.groupValues?.get(1)?.toInt() }
|
||||||
|
|
@ -545,17 +529,18 @@ class MALApi : SyncAPI() {
|
||||||
return fullList.toTypedArray()
|
return fullList.toTypedArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun getMalAnimeListSlice(token: AuthToken, offset: Int = 0): MalList {
|
private suspend fun getMalAnimeListSlice(token: AuthToken, offset: Int = 0): MalList? {
|
||||||
val user = "@me"
|
val user = "@me"
|
||||||
// Very lackluster docs
|
// Very lackluster docs
|
||||||
// https://myanimelist.net/apiconfig/references/api/v2#operation/users_user_id_animelist_get
|
// https://myanimelist.net/apiconfig/references/api/v2#operation/users_user_id_animelist_get
|
||||||
val url = "$apiUrl/v2/users/$user/animelist?fields=list_status,num_episodes,media_type,status,start_date,end_date,synopsis,alternative_titles,mean,genres,rank,num_list_users,nsfw,average_episode_duration,num_favorites,popularity,num_scoring_users,start_season,favorites_info,broadcast,created_at,updated_at&nsfw=1&limit=100&offset=$offset"
|
val url =
|
||||||
|
"$apiUrl/v2/users/$user/animelist?fields=list_status,num_episodes,media_type,status,start_date,end_date,synopsis,alternative_titles,mean,genres,rank,num_list_users,nsfw,average_episode_duration,num_favorites,popularity,num_scoring_users,start_season,favorites_info,broadcast,created_at,updated_at&nsfw=1&limit=100&offset=$offset"
|
||||||
val res = app.get(
|
val res = app.get(
|
||||||
url, headers = mapOf(
|
url, headers = mapOf(
|
||||||
"Authorization" to "Bearer ${token.accessToken}",
|
"Authorization" to "Bearer ${token.accessToken}",
|
||||||
), cacheTime = 0
|
), cacheTime = 0
|
||||||
).text
|
).text
|
||||||
return parseJson<MalList>(res)
|
return res.toKotlinObject()
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun setScoreRequest(
|
private suspend fun setScoreRequest(
|
||||||
|
|
@ -598,7 +583,7 @@ class MALApi : SyncAPI() {
|
||||||
val data = mapOf(
|
val data = mapOf(
|
||||||
"status" to status,
|
"status" to status,
|
||||||
"score" to score?.toString(),
|
"score" to score?.toString(),
|
||||||
"num_watched_episodes" to numWatchedEpisodes?.toString(),
|
"num_watched_episodes" to numWatchedEpisodes?.toString()
|
||||||
).filterValues { it != null } as Map<String, String>
|
).filterValues { it != null } as Map<String, String>
|
||||||
|
|
||||||
return app.put(
|
return app.put(
|
||||||
|
|
@ -610,74 +595,71 @@ class MALApi : SyncAPI() {
|
||||||
).text
|
).text
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResponseToken(
|
data class ResponseToken(
|
||||||
@JsonProperty("token_type") @SerialName("token_type") val tokenType: String,
|
@JsonProperty("token_type") val tokenType: String,
|
||||||
@JsonProperty("expires_in") @SerialName("expires_in") val expiresIn: Int,
|
@JsonProperty("expires_in") val expiresIn: Int,
|
||||||
@JsonProperty("access_token") @SerialName("access_token") val accessToken: String,
|
@JsonProperty("access_token") val accessToken: String,
|
||||||
@JsonProperty("refresh_token") @SerialName("refresh_token") val refreshToken: String,
|
@JsonProperty("refresh_token") val refreshToken: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalRoot(
|
data class MalRoot(
|
||||||
@JsonProperty("data") @SerialName("data") val data: List<MalDatum>,
|
@JsonProperty("data") val data: List<MalDatum>,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalDatum(
|
data class MalDatum(
|
||||||
@JsonProperty("node") @SerialName("node") val node: MalNode,
|
@JsonProperty("node") val node: MalNode,
|
||||||
@JsonProperty("list_status") @SerialName("list_status") val listStatus: MalStatus,
|
@JsonProperty("list_status") val listStatus: MalStatus,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalNode(
|
data class MalNode(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String,
|
@JsonProperty("title") val title: String,
|
||||||
|
/*
|
||||||
|
also, but not used
|
||||||
|
main_picture ->
|
||||||
|
public string medium;
|
||||||
|
public string large;
|
||||||
|
*/
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalStatus(
|
data class MalStatus(
|
||||||
@JsonProperty("status") @SerialName("status") val status: String,
|
@JsonProperty("status") val status: String,
|
||||||
@JsonProperty("score") @SerialName("score") val score: Int,
|
@JsonProperty("score") val score: Int,
|
||||||
@JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int,
|
@JsonProperty("num_episodes_watched") val numEpisodesWatched: Int,
|
||||||
@JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean,
|
@JsonProperty("is_rewatching") val isRewatching: Boolean,
|
||||||
@JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String,
|
@JsonProperty("updated_at") val updatedAt: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalUser(
|
data class MalUser(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("location") @SerialName("location") val location: String,
|
@JsonProperty("location") val location: String,
|
||||||
@JsonProperty("joined_at") @SerialName("joined_at") val joinedAt: String,
|
@JsonProperty("joined_at") val joinedAt: String,
|
||||||
@JsonProperty("picture") @SerialName("picture") val picture: String?,
|
@JsonProperty("picture") val picture: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalMainPicture(
|
data class MalMainPicture(
|
||||||
@JsonProperty("large") @SerialName("large") val large: String?,
|
@JsonProperty("large") val large: String?,
|
||||||
@JsonProperty("medium") @SerialName("medium") val medium: String?,
|
@JsonProperty("medium") val medium: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Used for getDataAboutId()
|
// Used for getDataAboutId()
|
||||||
@Serializable
|
|
||||||
data class SmallMalAnime(
|
data class SmallMalAnime(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int,
|
@JsonProperty("id") val id: Int,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String?,
|
@JsonProperty("title") val title: String?,
|
||||||
@JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int,
|
@JsonProperty("num_episodes") val numEpisodes: Int,
|
||||||
@JsonProperty("my_list_status") @SerialName("my_list_status") val myListStatus: MalStatus?,
|
@JsonProperty("my_list_status") val myListStatus: MalStatus?,
|
||||||
@JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MalMainPicture?,
|
@JsonProperty("main_picture") val mainPicture: MalMainPicture?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalSearchNode(
|
data class MalSearchNode(
|
||||||
@JsonProperty("node") @SerialName("node") val node: Node,
|
@JsonProperty("node") val node: Node,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MalSearch(
|
data class MalSearch(
|
||||||
@JsonProperty("data") @SerialName("data") val data: List<MalSearchNode>,
|
@JsonProperty("data") val data: List<MalSearchNode>,
|
||||||
// paging
|
//paging
|
||||||
)
|
)
|
||||||
|
|
||||||
data class MalTitleHolder(
|
data class MalTitleHolder(
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,9 @@ package com.lagradost.cloudstream3.syncproviders.providers
|
||||||
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
import com.lagradost.cloudstream3.app
|
||||||
import com.lagradost.cloudstream3.APIHolder.unixTimeMS
|
|
||||||
import com.lagradost.cloudstream3.ErrorLoadingException
|
import com.lagradost.cloudstream3.ErrorLoadingException
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
import com.lagradost.cloudstream3.app
|
|
||||||
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
|
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
|
||||||
import com.lagradost.cloudstream3.syncproviders.AuthData
|
import com.lagradost.cloudstream3.syncproviders.AuthData
|
||||||
import com.lagradost.cloudstream3.syncproviders.AuthLoginRequirement
|
import com.lagradost.cloudstream3.syncproviders.AuthLoginRequirement
|
||||||
|
|
@ -20,8 +18,6 @@ import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToOpenSubtitlesTag
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToOpenSubtitlesTag
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
class OpenSubtitlesApi : SubtitleAPI() {
|
class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
override val name = "OpenSubtitles"
|
override val name = "OpenSubtitles"
|
||||||
|
|
@ -47,17 +43,17 @@ class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun canDoRequest(): Boolean {
|
private fun canDoRequest(): Boolean {
|
||||||
return unixTimeMS > currentCoolDown
|
return unixTimeMs > currentCoolDown
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun throwIfCantDoRequest() {
|
private fun throwIfCantDoRequest() {
|
||||||
if (!canDoRequest()) {
|
if (!canDoRequest()) {
|
||||||
throw ErrorLoadingException("Too many requests wait for ${(currentCoolDown - unixTimeMS) / 1000L}s")
|
throw ErrorLoadingException("Too many requests wait for ${(currentCoolDown - unixTimeMs) / 1000L}s")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun throwGotTooManyRequests() {
|
private fun throwGotTooManyRequests() {
|
||||||
currentCoolDown = unixTimeMS + COOLDOWN_DURATION
|
currentCoolDown = unixTimeMs + COOLDOWN_DURATION
|
||||||
throw ErrorLoadingException("Too many requests")
|
throw ErrorLoadingException("Too many requests")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -93,7 +89,7 @@ class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
accessToken = response.token
|
accessToken = response.token
|
||||||
?: throw ErrorLoadingException("Invalid password or username"),
|
?: throw ErrorLoadingException("Invalid password or username"),
|
||||||
/// JWT token is valid 24 hours after successfully authentication of user
|
/// JWT token is valid 24 hours after successfully authentication of user
|
||||||
accessTokenLifetime = APIHolder.unixTime + 60 * 60 * 24,
|
accessTokenLifetime = unixTime + 60 * 60 * 24,
|
||||||
payload = form.toJson()
|
payload = form.toJson()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -101,7 +97,7 @@ class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
/**
|
/**
|
||||||
* Fetch subtitles using token authenticated on previous method (see authorize).
|
* Fetch subtitles using token authenticated on previous method (see authorize).
|
||||||
* Returns list of Subtitles which user can select to download (see load).
|
* Returns list of Subtitles which user can select to download (see load).
|
||||||
*/
|
* */
|
||||||
override suspend fun search(
|
override suspend fun search(
|
||||||
auth : AuthData?,
|
auth : AuthData?,
|
||||||
query: AbstractSubtitleEntities.SubtitleSearch
|
query: AbstractSubtitleEntities.SubtitleSearch
|
||||||
|
|
@ -181,15 +177,16 @@ class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
return results
|
return results
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/*
|
||||||
* Process data returned from search.
|
Process data returned from search.
|
||||||
* Returns string url for the subtitle file.
|
Returns string url for the subtitle file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
override suspend fun load(
|
override suspend fun load(
|
||||||
auth : AuthData?,
|
auth : AuthData?,
|
||||||
subtitle: AbstractSubtitleEntities.SubtitleEntity
|
subtitle: AbstractSubtitleEntities.SubtitleEntity
|
||||||
): String? {
|
): String? {
|
||||||
if (auth == null) return null
|
if(auth == null) return null
|
||||||
throwIfCantDoRequest()
|
throwIfCantDoRequest()
|
||||||
|
|
||||||
val req = app.post(
|
val req = app.post(
|
||||||
|
|
@ -221,64 +218,57 @@ class OpenSubtitlesApi : SubtitleAPI() {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class OAuthToken(
|
data class OAuthToken(
|
||||||
@JsonProperty("token") @SerialName("token") var token: String? = null,
|
@JsonProperty("token") var token: String? = null,
|
||||||
@JsonProperty("status") @SerialName("status") var status: Int? = null,
|
@JsonProperty("status") var status: Int? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Results(
|
data class Results(
|
||||||
@JsonProperty("data") @SerialName("data") var data: List<ResultData>? = listOf(),
|
@JsonProperty("data") var data: List<ResultData>? = listOf()
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultData(
|
data class ResultData(
|
||||||
@JsonProperty("id") @SerialName("id") var id: String? = null,
|
@JsonProperty("id") var id: String? = null,
|
||||||
@JsonProperty("type") @SerialName("type") var type: String? = null,
|
@JsonProperty("type") var type: String? = null,
|
||||||
@JsonProperty("attributes") @SerialName("attributes") var attributes: ResultAttributes? = ResultAttributes(),
|
@JsonProperty("attributes") var attributes: ResultAttributes? = ResultAttributes()
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultAttributes(
|
data class ResultAttributes(
|
||||||
@JsonProperty("subtitle_id") @SerialName("subtitle_id") var subtitleId: String? = null,
|
@JsonProperty("subtitle_id") var subtitleId: String? = null,
|
||||||
@JsonProperty("language") @SerialName("language") var language: String? = null,
|
@JsonProperty("language") var language: String? = null,
|
||||||
@JsonProperty("release") @SerialName("release") var release: String? = null,
|
@JsonProperty("release") var release: String? = null,
|
||||||
@JsonProperty("url") @SerialName("url") var url: String? = null,
|
@JsonProperty("url") var url: String? = null,
|
||||||
@JsonProperty("files") @SerialName("files") var files: List<ResultFiles>? = listOf(),
|
@JsonProperty("files") var files: List<ResultFiles>? = listOf(),
|
||||||
@JsonProperty("feature_details") @SerialName("feature_details") var featDetails: ResultFeatureDetails? = ResultFeatureDetails(),
|
@JsonProperty("feature_details") var featDetails: ResultFeatureDetails? = ResultFeatureDetails(),
|
||||||
@JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Boolean? = null,
|
@JsonProperty("hearing_impaired") var hearingImpaired: Boolean? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultFiles(
|
data class ResultFiles(
|
||||||
@JsonProperty("file_id") @SerialName("file_id") var fileId: Int? = null,
|
@JsonProperty("file_id") var fileId: Int? = null,
|
||||||
@JsonProperty("file_name") @SerialName("file_name") var fileName: String? = null,
|
@JsonProperty("file_name") var fileName: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultDownloadLink(
|
data class ResultDownloadLink(
|
||||||
@JsonProperty("link") @SerialName("link") var link: String? = null,
|
@JsonProperty("link") var link: String? = null,
|
||||||
@JsonProperty("file_name") @SerialName("file_name") var fileName: String? = null,
|
@JsonProperty("file_name") var fileName: String? = null,
|
||||||
@JsonProperty("requests") @SerialName("requests") var requests: Int? = null,
|
@JsonProperty("requests") var requests: Int? = null,
|
||||||
@JsonProperty("remaining") @SerialName("remaining") var remaining: Int? = null,
|
@JsonProperty("remaining") var remaining: Int? = null,
|
||||||
@JsonProperty("message") @SerialName("message") var message: String? = null,
|
@JsonProperty("message") var message: String? = null,
|
||||||
@JsonProperty("reset_time") @SerialName("reset_time") var resetTime: String? = null,
|
@JsonProperty("reset_time") var resetTime: String? = null,
|
||||||
@JsonProperty("reset_time_utc") @SerialName("reset_time_utc") var resetTimeUtc: String? = null,
|
@JsonProperty("reset_time_utc") var resetTimeUtc: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultFeatureDetails(
|
data class ResultFeatureDetails(
|
||||||
@JsonProperty("year") @SerialName("year") var year: Int? = null,
|
@JsonProperty("year") var year: Int? = null,
|
||||||
@JsonProperty("title") @SerialName("title") var title: String? = null,
|
@JsonProperty("title") var title: String? = null,
|
||||||
@JsonProperty("movie_name") @SerialName("movie_name") var movieName: String? = null,
|
@JsonProperty("movie_name") var movieName: String? = null,
|
||||||
@JsonProperty("imdb_id") @SerialName("imdb_id") var imdbId: Int? = null,
|
@JsonProperty("imdb_id") var imdbId: Int? = null,
|
||||||
@JsonProperty("tmdb_id") @SerialName("tmdb_id") var tmdbId: Int? = null,
|
@JsonProperty("tmdb_id") var tmdbId: Int? = null,
|
||||||
@JsonProperty("season_number") @SerialName("season_number") var seasonNumber: Int? = null,
|
@JsonProperty("season_number") var seasonNumber: Int? = null,
|
||||||
@JsonProperty("episode_number") @SerialName("episode_number") var episodeNumber: Int? = null,
|
@JsonProperty("episode_number") var episodeNumber: Int? = null,
|
||||||
@JsonProperty("parent_imdb_id") @SerialName("parent_imdb_id") var parentImdbId: Int? = null,
|
@JsonProperty("parent_imdb_id") var parentImdbId: Int? = null,
|
||||||
@JsonProperty("parent_title") @SerialName("parent_title") var parentTitle: String? = null,
|
@JsonProperty("parent_title") var parentTitle: String? = null,
|
||||||
@JsonProperty("parent_tmdb_id") @SerialName("parent_tmdb_id") var parentTmdbId: Int? = null,
|
@JsonProperty("parent_tmdb_id") var parentTmdbId: Int? = null,
|
||||||
@JsonProperty("parent_feature_id") @SerialName("parent_feature_id") var parentFeatureId: Int? = null,
|
@JsonProperty("parent_feature_id") var parentFeatureId: Int? = null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -7,10 +7,9 @@ import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
|
||||||
import com.lagradost.cloudstream3.subtitles.SubtitleResource
|
import com.lagradost.cloudstream3.subtitles.SubtitleResource
|
||||||
import com.lagradost.cloudstream3.syncproviders.AuthData
|
import com.lagradost.cloudstream3.syncproviders.AuthData
|
||||||
import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
|
import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
|
||||||
|
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
||||||
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper
|
import com.lagradost.cloudstream3.utils.SubtitleHelper
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
class SubSourceApi : SubtitleAPI() {
|
class SubSourceApi : SubtitleAPI() {
|
||||||
override val name = "SubSource"
|
override val name = "SubSource"
|
||||||
|
|
@ -19,70 +18,77 @@ class SubSourceApi : SubtitleAPI() {
|
||||||
override val requiresLogin = false
|
override val requiresLogin = false
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val APIURL = "https://api.subsource.net/v1"
|
const val APIURL = "https://api.subsource.net/api"
|
||||||
|
const val DOWNLOADENDPOINT = "https://api.subsource.net/api/downloadSub"
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun search(
|
override suspend fun search(
|
||||||
auth: AuthData?,
|
auth: AuthData?,
|
||||||
query: AbstractSubtitleEntities.SubtitleSearch
|
query: AbstractSubtitleEntities.SubtitleSearch
|
||||||
): List<AbstractSubtitleEntities.SubtitleEntity>? {
|
): List<AbstractSubtitleEntities.SubtitleEntity>? {
|
||||||
|
|
||||||
//Only supports Imdb Id search for now
|
//Only supports Imdb Id search for now
|
||||||
if (query.imdbId == null) return null
|
if (query.imdbId == null) return null
|
||||||
val queryLang = SubtitleHelper.fromTagToEnglishLanguageName(query.lang)
|
val queryLang = SubtitleHelper.fromTagToEnglishLanguageName(query.lang)
|
||||||
val type = if ((query.seasonNumber ?: 0) > 0) TvType.TvSeries else TvType.Movie
|
val type = if ((query.seasonNumber ?: 0) > 0) TvType.TvSeries else TvType.Movie
|
||||||
|
|
||||||
val searchResponse = app.post(
|
val searchRes = app.post(
|
||||||
url = "$APIURL/movie/search",
|
url = "$APIURL/searchMovie",
|
||||||
json = mapOf(
|
data = mapOf(
|
||||||
"includeSeasons" to false,
|
"query" to query.imdbId!!
|
||||||
"limit" to 15,
|
)
|
||||||
"query" to query.imdbId!!,
|
).parsedSafe<ApiSearch>() ?: return null
|
||||||
"signal" to "{}"
|
|
||||||
),
|
val postData = if (type == TvType.TvSeries) {
|
||||||
cacheTime = 120,
|
mapOf(
|
||||||
cacheUnit = TimeUnit.MINUTES,
|
"langs" to "[]",
|
||||||
).parsedSafe<SearchRoot>() ?: return null
|
"movieName" to searchRes.found.first().linkName,
|
||||||
|
"season" to "season-${query.seasonNumber}"
|
||||||
val firstResult = searchResponse.results.firstOrNull() ?: return null
|
)
|
||||||
|
} else {
|
||||||
val apiResponse = app.get(
|
mapOf(
|
||||||
url = "$APIURL${firstResult.link.replace("series", "subtitles")}",
|
"langs" to "[]",
|
||||||
cacheTime = 120,
|
"movieName" to searchRes.found.first().linkName,
|
||||||
cacheUnit = TimeUnit.MINUTES,
|
|
||||||
).parsedSafe<ItemRoot>() ?: return null
|
|
||||||
|
|
||||||
val filteredSubtitles = apiResponse.subtitles.filter { sub ->
|
|
||||||
sub.releaseType != "trailer" &&
|
|
||||||
sub.language.equals(queryLang, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// api doesn't has episode number or lang filtering
|
|
||||||
val subtitles = if (type == TvType.Movie) {
|
|
||||||
filteredSubtitles
|
|
||||||
} else {
|
|
||||||
val shouldContain = String.format(
|
|
||||||
null,
|
|
||||||
"E%02d",
|
|
||||||
query.epNumber
|
|
||||||
)
|
)
|
||||||
filteredSubtitles.filter { sub ->
|
|
||||||
sub.releaseInfo.contains(
|
|
||||||
shouldContain
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return subtitles.map { subtitle ->
|
val getMovieRes = app.post(
|
||||||
|
url = "$APIURL/getMovie",
|
||||||
|
data = postData
|
||||||
|
).parsedSafe<ApiResponse>().let {
|
||||||
|
// api doesn't has episode number or lang filtering
|
||||||
|
if (type == TvType.Movie) {
|
||||||
|
it?.subs?.filter { sub ->
|
||||||
|
sub.lang == queryLang
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
it?.subs?.filter { sub ->
|
||||||
|
sub.releaseName!!.contains(
|
||||||
|
String.format(
|
||||||
|
null,
|
||||||
|
"E%02d",
|
||||||
|
query.epNumber
|
||||||
|
)
|
||||||
|
) && sub.lang == queryLang
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} ?: return null
|
||||||
|
|
||||||
|
return getMovieRes.map { subtitle ->
|
||||||
AbstractSubtitleEntities.SubtitleEntity(
|
AbstractSubtitleEntities.SubtitleEntity(
|
||||||
idPrefix = this.idPrefix,
|
idPrefix = this.idPrefix,
|
||||||
name = subtitle.releaseInfo,
|
name = subtitle.releaseName!!,
|
||||||
lang = subtitle.language,
|
lang = subtitle.lang!!,
|
||||||
data = subtitle.link,
|
data = SubData(
|
||||||
|
movie = subtitle.linkName!!,
|
||||||
|
lang = subtitle.lang,
|
||||||
|
id = subtitle.subId.toString(),
|
||||||
|
).toJson(),
|
||||||
type = type,
|
type = type,
|
||||||
source = this.name,
|
source = this.name,
|
||||||
epNumber = query.epNumber,
|
epNumber = query.epNumber,
|
||||||
seasonNumber = query.seasonNumber,
|
seasonNumber = query.seasonNumber,
|
||||||
isHearingImpaired = subtitle.hearingImpaired == 1,
|
isHearingImpaired = subtitle.hi == 1,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -91,114 +97,71 @@ class SubSourceApi : SubtitleAPI() {
|
||||||
auth: AuthData?,
|
auth: AuthData?,
|
||||||
subtitle: AbstractSubtitleEntities.SubtitleEntity
|
subtitle: AbstractSubtitleEntities.SubtitleEntity
|
||||||
) {
|
) {
|
||||||
val data = app.get("$APIURL/subtitle/${subtitle.data}")
|
val parsedSub = parseJson<SubData>(subtitle.data)
|
||||||
.parsedSafe<DownloadRoot>()
|
|
||||||
?: return
|
val subRes = app.post(
|
||||||
|
url = "$APIURL/getSub",
|
||||||
|
data = mapOf(
|
||||||
|
"movie" to parsedSub.movie,
|
||||||
|
"lang" to subtitle.lang,
|
||||||
|
"id" to parsedSub.id
|
||||||
|
)
|
||||||
|
).parsedSafe<SubTitleLink>() ?: return
|
||||||
|
|
||||||
this.addZipUrl(
|
this.addZipUrl(
|
||||||
"$APIURL/subtitle/download/${data.subtitle.downloadToken}"
|
"$DOWNLOADENDPOINT/${subRes.sub.downloadToken}"
|
||||||
) { name, _ ->
|
) { name, _ ->
|
||||||
name
|
name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data class ApiSearch(
|
||||||
@Serializable
|
@JsonProperty("success") val success: Boolean,
|
||||||
data class SearchRoot(
|
@JsonProperty("found") val found: List<Found>,
|
||||||
@JsonProperty("success") @SerialName("success") var success: Boolean? = null,
|
|
||||||
@JsonProperty("results") @SerialName("results") var results: ArrayList<Results> = arrayListOf(),
|
|
||||||
@JsonProperty("users") @SerialName("users") var users: ArrayList<Users> = arrayListOf()
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class Found(
|
||||||
data class Users(
|
@JsonProperty("id") val id: Long,
|
||||||
|
@JsonProperty("title") val title: String,
|
||||||
@JsonProperty("id") @SerialName("id") var id: Int? = null,
|
@JsonProperty("seasons") val seasons: Long,
|
||||||
@JsonProperty("displayname") @SerialName("displayname") var displayname: String? = null,
|
@JsonProperty("type") val type: String,
|
||||||
@JsonProperty("avatar") @SerialName("avatar") var avatar: String? = null,
|
@JsonProperty("releaseYear") val releaseYear: Long,
|
||||||
@JsonProperty("badges") @SerialName("badges") var badges: ArrayList<String> = arrayListOf()
|
@JsonProperty("linkName") val linkName: String,
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class ApiResponse(
|
||||||
data class Results(
|
@JsonProperty("success") val success: Boolean,
|
||||||
@JsonProperty("id") @SerialName("id") var id: Int? = null,
|
@JsonProperty("movie") val movie: Movie,
|
||||||
@JsonProperty("title") @SerialName("title") var title: String? = null,
|
@JsonProperty("subs") val subs: List<Sub>,
|
||||||
@JsonProperty("type") @SerialName("type") var type: String? = null,
|
|
||||||
@JsonProperty("link") @SerialName("link") var link: String,
|
|
||||||
@JsonProperty("releaseYear") @SerialName("releaseYear") var releaseYear: Int? = null,
|
|
||||||
@JsonProperty("poster") @SerialName("poster") var poster: String? = null,
|
|
||||||
@JsonProperty("subtitleCount") @SerialName("subtitleCount") var subtitleCount: String? = null,
|
|
||||||
@JsonProperty("rating") @SerialName("rating") var rating: Double? = null,
|
|
||||||
@JsonProperty("cast") @SerialName("cast") var cast: ArrayList<String> = arrayListOf(),
|
|
||||||
@JsonProperty("genres") @SerialName("genres") var genres: ArrayList<String> = arrayListOf(),
|
|
||||||
@JsonProperty("score") @SerialName("score") var score: Double? = null
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class Movie(
|
||||||
|
@JsonProperty("id") val id: Long? = null,
|
||||||
data class ItemRoot(
|
@JsonProperty("type") val type: String? = null,
|
||||||
|
@JsonProperty("year") val year: Long? = null,
|
||||||
// @SerialName("media_type" ) var mediaType : String? = null,
|
@JsonProperty("fullName") val fullName: String? = null,
|
||||||
@JsonProperty("subtitles") @SerialName("subtitles") var subtitles: ArrayList<Subtitles>,
|
|
||||||
//@SerialName("movie" ) var movie : Movie? = Movie()
|
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class Sub(
|
||||||
data class Subtitles(
|
@JsonProperty("hi") val hi: Int? = null,
|
||||||
|
@JsonProperty("fullLink") val fullLink: String? = null,
|
||||||
@JsonProperty("id") @SerialName("id") var id: Int? = null,
|
@JsonProperty("linkName") val linkName: String? = null,
|
||||||
@JsonProperty("language") @SerialName("language") var language: String,
|
@JsonProperty("lang") val lang: String? = null,
|
||||||
@JsonProperty("release_type") @SerialName("release_type") var releaseType: String? = null,
|
@JsonProperty("releaseName") val releaseName: String? = null,
|
||||||
@JsonProperty("release_info") @SerialName("release_info") var releaseInfo: String,
|
@JsonProperty("subId") val subId: Long? = null,
|
||||||
@JsonProperty("upload_date") @SerialName("upload_date") var uploadDate: String? = null,
|
|
||||||
@JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Int? = null,
|
|
||||||
@JsonProperty("caption") @SerialName("caption") var caption: String? = null,
|
|
||||||
@JsonProperty("rating") @SerialName("rating") var rating: String? = null,
|
|
||||||
@JsonProperty("uploader_id") @SerialName("uploader_id") var uploaderId: Int? = null,
|
|
||||||
@JsonProperty("uploader_displayname") @SerialName("uploader_displayname") var uploaderDisplayname: String? = null,
|
|
||||||
@JsonProperty("uploader_badges") @SerialName("uploader_badges") var uploaderBadges: ArrayList<String> = arrayListOf(),
|
|
||||||
@JsonProperty("link") @SerialName("link") var link: String,
|
|
||||||
@JsonProperty("production_type") @SerialName("production_type") var productionType: String? = null,
|
|
||||||
@JsonProperty("last_subtitle") @SerialName("last_subtitle") var lastSubtitle: Boolean? = null
|
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class SubData(
|
||||||
data class DownloadRoot(
|
@JsonProperty("movie") val movie: String,
|
||||||
@JsonProperty("subtitle") @SerialName("subtitle") var subtitle: Subtitle,
|
@JsonProperty("lang") val lang: String,
|
||||||
//@SerializedName("movie" ) var movie : Movie? = Movie(),
|
@JsonProperty("id") val id: String,
|
||||||
//@SerializedName("donationLinks" ) var donationLinks : DonationLinks? = DonationLinks(),
|
|
||||||
//@SerializedName("isDownloaded" ) var isDownloaded : Boolean? = null,
|
|
||||||
//@SerializedName("user_rated" ) var userRated : String? = null
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
data class SubTitleLink(
|
||||||
data class Subtitle(
|
@JsonProperty("sub") val sub: SubToken,
|
||||||
|
|
||||||
@JsonProperty("id") @SerialName("id") var id: Int? = null,
|
|
||||||
@JsonProperty("uploaded_at") @SerialName("uploaded_at") var uploadedAt: String? = null,
|
|
||||||
@JsonProperty("language") @SerialName("language") var language: String? = null,
|
|
||||||
@JsonProperty("rating") @SerialName("rating") var rating: String? = null,
|
|
||||||
//SerialName("rates" ) var rates : Rates? = Rates(),
|
|
||||||
@JsonProperty("uploaded_by") @SerialName("uploaded_by") var uploadedBy: Int? = null,
|
|
||||||
//@SerialName("contribs" ) var contribs : ArrayList<Contribs> = arrayListOf(),
|
|
||||||
@JsonProperty("release_info") @SerialName("release_info") var releaseInfo: ArrayList<String> = arrayListOf(),
|
|
||||||
@JsonProperty("commentary") @SerialName("commentary") var commentary: String? = null,
|
|
||||||
@JsonProperty("files") @SerialName("files") var files: String? = null,
|
|
||||||
@JsonProperty("size") @SerialName("size") var size: String? = null,
|
|
||||||
@JsonProperty("downloads") @SerialName("downloads") var downloads: Int? = null,
|
|
||||||
@JsonProperty("comments") @SerialName("comments") var comments: Int? = null,
|
|
||||||
@JsonProperty("production_type") @SerialName("production_type") var productionType: String? = null,
|
|
||||||
@JsonProperty("release_type") @SerialName("release_type") var releaseType: String? = null,
|
|
||||||
@JsonProperty("episode") @SerialName("episode") var episode: String? = null,
|
|
||||||
@JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Int? = null,
|
|
||||||
@JsonProperty("foreign_parts") @SerialName("foreign_parts") var foreignParts: String? = null,
|
|
||||||
@JsonProperty("framerate") @SerialName("framerate") var framerate: String? = null,
|
|
||||||
@JsonProperty("preview") @SerialName("preview") var preview: String? = null,
|
|
||||||
@JsonProperty("user_uploaded") @SerialName("user_uploaded") var userUploaded: Boolean? = null,
|
|
||||||
@JsonProperty("download_token") @SerialName("download_token") var downloadToken: String
|
|
||||||
|
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
data class SubToken(
|
||||||
|
@JsonProperty("downloadToken") val downloadToken: String,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -12,8 +12,6 @@ import com.lagradost.cloudstream3.syncproviders.AuthToken
|
||||||
import com.lagradost.cloudstream3.syncproviders.AuthUser
|
import com.lagradost.cloudstream3.syncproviders.AuthUser
|
||||||
import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
|
import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
|
||||||
import com.lagradost.cloudstream3.TvType
|
import com.lagradost.cloudstream3.TvType
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
class SubDlApi : SubtitleAPI() {
|
class SubDlApi : SubtitleAPI() {
|
||||||
override val name = "SubDL"
|
override val name = "SubDL"
|
||||||
|
|
@ -26,7 +24,7 @@ class SubDlApi : SubtitleAPI() {
|
||||||
override val createAccountUrl = "https://subdl.com/panel/register"
|
override val createAccountUrl = "https://subdl.com/panel/register"
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val APIURL = "https://api.subdl.com"
|
const val APIURL = "https://apiold.subdl.com"
|
||||||
const val APIENDPOINT = "$APIURL/api/v1/subtitles"
|
const val APIENDPOINT = "$APIURL/api/v1/subtitles"
|
||||||
const val DOWNLOADENDPOINT = "https://dl.subdl.com"
|
const val DOWNLOADENDPOINT = "https://dl.subdl.com"
|
||||||
}
|
}
|
||||||
|
|
@ -124,80 +122,72 @@ class SubDlApi : SubtitleAPI() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SubtitleOAuthEntity(
|
data class SubtitleOAuthEntity(
|
||||||
@JsonProperty("userEmail") @SerialName("userEmail") var userEmail: String,
|
@JsonProperty("userEmail") var userEmail: String,
|
||||||
@JsonProperty("pass") @SerialName("pass") var pass: String,
|
@JsonProperty("pass") var pass: String,
|
||||||
@JsonProperty("name") @SerialName("name") var name: String? = null,
|
@JsonProperty("name") var name: String? = null,
|
||||||
@JsonProperty("accessToken") @SerialName("accessToken") var accessToken: String? = null,
|
@JsonProperty("accessToken") var accessToken: String? = null,
|
||||||
@JsonProperty("apiKey") @SerialName("apiKey") var apiKey: String? = null,
|
@JsonProperty("apiKey") var apiKey: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class OAuthTokenResponse(
|
data class OAuthTokenResponse(
|
||||||
@JsonProperty("token") @SerialName("token") val token: String,
|
@JsonProperty("token") val token: String,
|
||||||
@JsonProperty("userData") @SerialName("userData") val userData: UserData? = null,
|
@JsonProperty("userData") val userData: UserData? = null,
|
||||||
@JsonProperty("status") @SerialName("status") val status: Boolean? = null,
|
@JsonProperty("status") val status: Boolean? = null,
|
||||||
@JsonProperty("message") @SerialName("message") val message: String? = null,
|
@JsonProperty("message") val message: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class UserData(
|
data class UserData(
|
||||||
@JsonProperty("email") @SerialName("email") val email: String,
|
@JsonProperty("email") val email: String,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("country") @SerialName("country") val country: String,
|
@JsonProperty("country") val country: String,
|
||||||
@JsonProperty("scStepCode") @SerialName("scStepCode") val scStepCode: String,
|
@JsonProperty("scStepCode") val scStepCode: String,
|
||||||
@JsonProperty("scVerified") @SerialName("scVerified") val scVerified: Boolean,
|
@JsonProperty("scVerified") val scVerified: Boolean,
|
||||||
@JsonProperty("username") @SerialName("username") val username: String? = null,
|
@JsonProperty("username") val username: String? = null,
|
||||||
@JsonProperty("scUsername") @SerialName("scUsername") val scUsername: String,
|
@JsonProperty("scUsername") val scUsername: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ApiKeyResponse(
|
data class ApiKeyResponse(
|
||||||
@JsonProperty("ok") @SerialName("ok") val ok: Boolean? = false,
|
@JsonProperty("ok") val ok: Boolean? = false,
|
||||||
@JsonProperty("api_key") @SerialName("api_key") val apiKey: String,
|
@JsonProperty("api_key") val apiKey: String,
|
||||||
@JsonProperty("usage") @SerialName("usage") val usage: Usage? = null,
|
@JsonProperty("usage") val usage: Usage? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Usage(
|
data class Usage(
|
||||||
@JsonProperty("total") @SerialName("total") val total: Long? = 0,
|
@JsonProperty("total") val total: Long? = 0,
|
||||||
@JsonProperty("today") @SerialName("today") val today: Long? = 0,
|
@JsonProperty("today") val today: Long? = 0,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ApiResponse(
|
data class ApiResponse(
|
||||||
@JsonProperty("status") @SerialName("status") val status: Boolean? = null,
|
@JsonProperty("status") val status: Boolean? = null,
|
||||||
@JsonProperty("results") @SerialName("results") val results: List<Result>? = null,
|
@JsonProperty("results") val results: List<Result>? = null,
|
||||||
@JsonProperty("subtitles") @SerialName("subtitles") val subtitles: List<Subtitle>? = null,
|
@JsonProperty("subtitles") val subtitles: List<Subtitle>? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Result(
|
data class Result(
|
||||||
@JsonProperty("sd_id") @SerialName("sd_id") val sdId: Int? = null,
|
@JsonProperty("sd_id") val sdId: Int? = null,
|
||||||
@JsonProperty("type") @SerialName("type") val type: String? = null,
|
@JsonProperty("type") val type: String? = null,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String? = null,
|
@JsonProperty("name") val name: String? = null,
|
||||||
@JsonProperty("imdb_id") @SerialName("imdb_id") val imdbId: String? = null,
|
@JsonProperty("imdb_id") val imdbId: String? = null,
|
||||||
@JsonProperty("tmdb_id") @SerialName("tmdb_id") val tmdbId: Long? = null,
|
@JsonProperty("tmdb_id") val tmdbId: Long? = null,
|
||||||
@JsonProperty("first_air_date") @SerialName("first_air_date") val firstAirDate: String? = null,
|
@JsonProperty("first_air_date") val firstAirDate: String? = null,
|
||||||
@JsonProperty("year") @SerialName("year") val year: Int? = null,
|
@JsonProperty("year") val year: Int? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class Subtitle(
|
data class Subtitle(
|
||||||
@JsonProperty("release_name") @SerialName("release_name") val releaseName: String,
|
@JsonProperty("release_name") val releaseName: String,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
@JsonProperty("name") val name: String,
|
||||||
@JsonProperty("lang") @SerialName("lang") val lang: String, // subdl language code
|
@JsonProperty("lang") val lang: String, // subdl language code
|
||||||
@JsonProperty("author") @SerialName("author") val author: String? = null,
|
@JsonProperty("author") val author: String? = null,
|
||||||
@JsonProperty("url") @SerialName("url") val url: String? = null,
|
@JsonProperty("url") val url: String? = null,
|
||||||
@JsonProperty("subtitlePage") @SerialName("subtitlePage") val subtitlePage: String? = null,
|
@JsonProperty("subtitlePage") val subtitlePage: String? = null,
|
||||||
@JsonProperty("season") @SerialName("season") val season: Int? = null,
|
@JsonProperty("season") val season: Int? = null,
|
||||||
@JsonProperty("episode") @SerialName("episode") val episode: Int? = null,
|
@JsonProperty("episode") val episode: Int? = null,
|
||||||
@JsonProperty("language") @SerialName("language") val language: String? = null, // full language name
|
@JsonProperty("language") val language: String? = null, // full language name
|
||||||
@JsonProperty("hi") @SerialName("hi") val hearingImpaired: Boolean? = null,
|
@JsonProperty("hi") val hearingImpaired: Boolean? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://subdl.com/api-files/language_list.json
|
// https://subdl.com/api-files/language_list.json
|
||||||
// most of it is IETF BPC 47 conformant tag
|
// most of it is IETF BPC 47 conformant tag
|
||||||
// but there are some exceptions
|
// but there are some exceptions
|
||||||
private val langTagIETF2subdl = mapOf(
|
private val langTagIETF2subdl = mapOf(
|
||||||
|
|
@ -207,63 +197,63 @@ class SubDlApi : SubtitleAPI() {
|
||||||
"en-nl" to "NL_EN", // "Dutch_English"
|
"en-nl" to "NL_EN", // "Dutch_English"
|
||||||
"pt-br" to "BR_PT", // "Brazillian Portuguese"
|
"pt-br" to "BR_PT", // "Brazillian Portuguese"
|
||||||
"zh-hant" to "ZH_BG", // "Big 5 code" -> traditional Chinese (?_?)
|
"zh-hant" to "ZH_BG", // "Big 5 code" -> traditional Chinese (?_?)
|
||||||
// "ar" to "AR", // "Arabic"
|
// "ar" to "AR", // "Arabic"
|
||||||
// "az" to "AZ", // "Azerbaijani"
|
// "az" to "AZ", // "Azerbaijani"
|
||||||
// "be" to "BE", // "Belarusian"
|
// "be" to "BE", // "Belarusian"
|
||||||
// "bg" to "BG", // "Bulgarian"
|
// "bg" to "BG", // "Bulgarian"
|
||||||
// "bn" to "BN", // "Bengali"
|
// "bn" to "BN", // "Bengali"
|
||||||
// "bs" to "BS", // "Bosnian"
|
// "bs" to "BS", // "Bosnian"
|
||||||
// "ca" to "CA", // "Catalan"
|
// "ca" to "CA", // "Catalan"
|
||||||
// "cs" to "CS", // "Czech"
|
// "cs" to "CS", // "Czech"
|
||||||
// "da" to "DA", // "Danish"
|
// "da" to "DA", // "Danish"
|
||||||
// "de" to "DE", // "German"
|
// "de" to "DE", // "German"
|
||||||
// "el" to "EL", // "Greek"
|
// "el" to "EL", // "Greek"
|
||||||
// "en" to "EN", // "English"
|
// "en" to "EN", // "English"
|
||||||
// "eo" to "EO", // "Esperanto"
|
// "eo" to "EO", // "Esperanto"
|
||||||
// "es" to "ES", // "Spanish"
|
// "es" to "ES", // "Spanish"
|
||||||
// "et" to "ET", // "Estonian"
|
// "et" to "ET", // "Estonian"
|
||||||
// "fa" to "FA", // "Farsi_Persian"
|
// "fa" to "FA", // "Farsi_Persian"
|
||||||
// "fi" to "FI", // "Finnish"
|
// "fi" to "FI", // "Finnish"
|
||||||
// "fr" to "FR", // "French"
|
// "fr" to "FR", // "French"
|
||||||
// "he" to "HE", // "Hebrew"
|
// "he" to "HE", // "Hebrew"
|
||||||
// "hi" to "HI", // "Hindi"
|
// "hi" to "HI", // "Hindi"
|
||||||
// "hr" to "HR", // "Croatian"
|
// "hr" to "HR", // "Croatian"
|
||||||
// "hu" to "HU", // "Hungarian"
|
// "hu" to "HU", // "Hungarian"
|
||||||
// "id" to "ID", // "Indonesian"
|
// "id" to "ID", // "Indonesian"
|
||||||
// "is" to "IS", // "Icelandic"
|
// "is" to "IS", // "Icelandic"
|
||||||
// "it" to "IT", // "Italian"
|
// "it" to "IT", // "Italian"
|
||||||
// "ja" to "JA", // "Japanese"
|
// "ja" to "JA", // "Japanese"
|
||||||
// "ka" to "KA", // "Georgian"
|
// "ka" to "KA", // "Georgian"
|
||||||
// "kl" to "KL", // "Greenlandic"
|
// "kl" to "KL", // "Greenlandic"
|
||||||
// "ko" to "KO", // "Korean"
|
// "ko" to "KO", // "Korean"
|
||||||
// "ku" to "KU", // "Kurdish"
|
// "ku" to "KU", // "Kurdish"
|
||||||
// "lt" to "LT", // "Lithuanian"
|
// "lt" to "LT", // "Lithuanian"
|
||||||
// "lv" to "LV", // "Latvian"
|
// "lv" to "LV", // "Latvian"
|
||||||
// "mk" to "MK", // "Macedonian"
|
// "mk" to "MK", // "Macedonian"
|
||||||
// "ml" to "ML", // "Malayalam"
|
// "ml" to "ML", // "Malayalam"
|
||||||
// "mni" to "MNI", // "Manipuri"
|
// "mni" to "MNI", // "Manipuri"
|
||||||
// "ms" to "MS", // "Malay"
|
// "ms" to "MS", // "Malay"
|
||||||
// "my" to "MY", // "Burmese"
|
// "my" to "MY", // "Burmese"
|
||||||
// "nl" to "NL", // "Dutch"
|
// "nl" to "NL", // "Dutch"
|
||||||
// "no" to "NO", // "Norwegian"
|
// "no" to "NO", // "Norwegian"
|
||||||
// "pl" to "PL", // "Polish"
|
// "pl" to "PL", // "Polish"
|
||||||
// "pt" to "PT", // "Portuguese"
|
// "pt" to "PT", // "Portuguese"
|
||||||
// "ro" to "RO", // "Romanian"
|
// "ro" to "RO", // "Romanian"
|
||||||
// "ru" to "RU", // "Russian"
|
// "ru" to "RU", // "Russian"
|
||||||
// "si" to "SI", // "Sinhala"
|
// "si" to "SI", // "Sinhala"
|
||||||
// "sk" to "SK", // "Slovak"
|
// "sk" to "SK", // "Slovak"
|
||||||
// "sl" to "SL", // "Slovenian"
|
// "sl" to "SL", // "Slovenian"
|
||||||
// "sq" to "SQ", // "Albanian"
|
// "sq" to "SQ", // "Albanian"
|
||||||
// "sr" to "SR", // "Serbian"
|
// "sr" to "SR", // "Serbian"
|
||||||
// "sv" to "SV", // "Swedish"
|
// "sv" to "SV", // "Swedish"
|
||||||
// "ta" to "TA", // "Tamil"
|
// "ta" to "TA", // "Tamil"
|
||||||
// "te" to "TE", // "Telugu"
|
// "te" to "TE", // "Telugu"
|
||||||
// "th" to "TH", // "Thai"
|
// "th" to "TH", // "Thai"
|
||||||
// "tl" to "TL", // "Tagalog"
|
// "tl" to "TL", // "Tagalog"
|
||||||
// "tr" to "TR", // "Turkish"
|
// "tr" to "TR", // "Turkish"
|
||||||
// "uk" to "UK", // "Ukranian"
|
// "uk" to "UK", // "Ukranian"
|
||||||
// "ur" to "UR", // "Urdu"
|
// "ur" to "UR", // "Urdu"
|
||||||
// "vi" to "VI", // "Vietnamese"
|
// "vi" to "VI", // "Vietnamese"
|
||||||
// "zh" to "ZH", // "Chinese BG code"
|
// "zh" to "ZH", // "Chinese BG code"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ import com.lagradost.cloudstream3.mvvm.Resource
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.mvvm.safeApiCall
|
import com.lagradost.cloudstream3.mvvm.safeApiCall
|
||||||
import com.lagradost.cloudstream3.newSearchResponseList
|
import com.lagradost.cloudstream3.newSearchResponseList
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
|
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLink
|
import com.lagradost.cloudstream3.utils.ExtractorLink
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.async
|
||||||
|
|
@ -55,7 +55,7 @@ class APIRepository(val api: MainAPI) {
|
||||||
val hash: Pair<String, String>
|
val hash: Pair<String, String>
|
||||||
)
|
)
|
||||||
|
|
||||||
private val cache = atomicListOf<SavedLoadResponse>()
|
private val cache = threadSafeListOf<SavedLoadResponse>()
|
||||||
private var cacheIndex: Int = 0
|
private var cacheIndex: Int = 0
|
||||||
const val CACHE_SIZE = 20
|
const val CACHE_SIZE = 20
|
||||||
|
|
||||||
|
|
@ -66,7 +66,9 @@ class APIRepository(val api: MainAPI) {
|
||||||
|
|
||||||
private fun afterPluginsLoaded(forceReload: Boolean) {
|
private fun afterPluginsLoaded(forceReload: Boolean) {
|
||||||
if (forceReload) {
|
if (forceReload) {
|
||||||
cache.clear()
|
synchronized(cache) {
|
||||||
|
cache.clear()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -89,25 +91,21 @@ class APIRepository(val api: MainAPI) {
|
||||||
val fixedUrl = api.fixUrl(url)
|
val fixedUrl = api.fixUrl(url)
|
||||||
val lookingForHash = Pair(api.name, fixedUrl)
|
val lookingForHash = Pair(api.name, fixedUrl)
|
||||||
|
|
||||||
val cached = cache.withLock {
|
synchronized(cache) {
|
||||||
var found: LoadResponse? = null
|
|
||||||
for (item in cache) {
|
for (item in cache) {
|
||||||
// 10 min save
|
// 10 min save
|
||||||
if (item.hash == lookingForHash && (unixTime - item.unixTime) < 60 * 10) {
|
if (item.hash == lookingForHash && (unixTime - item.unixTime) < 60 * 10) {
|
||||||
found = item.response
|
return@withTimeout item.response
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
found
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cached != null) return@withTimeout cached
|
|
||||||
api.load(fixedUrl)?.also { response ->
|
api.load(fixedUrl)?.also { response ->
|
||||||
// Remove all blank tags as early as possible
|
// Remove all blank tags as early as possible
|
||||||
response.tags = response.tags?.filter { it.isNotBlank() }
|
response.tags = response.tags?.filter { it.isNotBlank() }
|
||||||
val add = SavedLoadResponse(unixTime, response, lookingForHash)
|
val add = SavedLoadResponse(unixTime, response, lookingForHash)
|
||||||
|
|
||||||
cache.withLock {
|
synchronized(cache) {
|
||||||
if (cache.size > CACHE_SIZE) {
|
if (cache.size > CACHE_SIZE) {
|
||||||
cache[cacheIndex] = add // rolling cache
|
cache[cacheIndex] = add // rolling cache
|
||||||
cacheIndex = (cacheIndex + 1) % CACHE_SIZE
|
cacheIndex = (cacheIndex + 1) % CACHE_SIZE
|
||||||
|
|
@ -217,4 +215,4 @@ class APIRepository(val api: MainAPI) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -12,7 +12,9 @@ import android.widget.ImageView
|
||||||
import android.widget.LinearLayout
|
import android.widget.LinearLayout
|
||||||
import android.widget.ListView
|
import android.widget.ListView
|
||||||
import androidx.appcompat.app.AlertDialog
|
import androidx.appcompat.app.AlertDialog
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.databind.DeserializationFeature
|
||||||
|
import com.fasterxml.jackson.databind.json.JsonMapper
|
||||||
|
import com.fasterxml.jackson.module.kotlin.kotlinModule
|
||||||
import com.google.android.gms.cast.MediaLoadOptions
|
import com.google.android.gms.cast.MediaLoadOptions
|
||||||
import com.google.android.gms.cast.MediaQueueItem
|
import com.google.android.gms.cast.MediaQueueItem
|
||||||
import com.google.android.gms.cast.MediaSeekOptions
|
import com.google.android.gms.cast.MediaSeekOptions
|
||||||
|
|
@ -35,24 +37,35 @@ import com.lagradost.cloudstream3.ui.player.SubtitleData
|
||||||
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment
|
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
|
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
||||||
import com.lagradost.cloudstream3.utils.CastHelper.awaitLinks
|
import com.lagradost.cloudstream3.utils.CastHelper.awaitLinks
|
||||||
import com.lagradost.cloudstream3.utils.CastHelper.getMediaInfo
|
import com.lagradost.cloudstream3.utils.CastHelper.getMediaInfo
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
|
import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLink
|
import com.lagradost.cloudstream3.utils.ExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.Qualities
|
import com.lagradost.cloudstream3.utils.Qualities
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/*class SkipOpController(val view: ImageView) : UIController() {
|
||||||
|
init {
|
||||||
|
view.setImageResource(R.drawable.exo_controls_fastforward)
|
||||||
|
view.setOnClickListener {
|
||||||
|
remoteMediaClient?.let {
|
||||||
|
val options = MediaSeekOptions.Builder()
|
||||||
|
.setPosition(it.approximateStreamPosition + 85000)
|
||||||
|
it.seek(options.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
|
||||||
private fun RemoteMediaClient.getItemIndex(): Int? {
|
private fun RemoteMediaClient.getItemIndex(): Int? {
|
||||||
return try {
|
return try {
|
||||||
val index = this.mediaQueue.itemIds.indexOf(this.currentItem?.itemId ?: 0)
|
val index = this.mediaQueue.itemIds.indexOf(this.currentItem?.itemId ?: 0)
|
||||||
if (index < 0) null else index
|
if (index < 0) null else index
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -79,41 +92,51 @@ class SkipNextEpisodeController(val view: ImageView) : UIController() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class MetadataHolder(
|
data class MetadataHolder(
|
||||||
@JsonProperty("apiName") @SerialName("apiName") val apiName: String,
|
val apiName: String,
|
||||||
@JsonProperty("isMovie") @SerialName("isMovie") val isMovie: Boolean,
|
val isMovie: Boolean,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String?,
|
val title: String?,
|
||||||
@JsonProperty("poster") @SerialName("poster") val poster: String?,
|
val poster: String?,
|
||||||
@JsonProperty("currentEpisodeIndex") @SerialName("currentEpisodeIndex") val currentEpisodeIndex: Int,
|
val currentEpisodeIndex: Int,
|
||||||
@JsonProperty("episodes") @SerialName("episodes") val episodes: List<ResultEpisode>,
|
val episodes: List<ResultEpisode>,
|
||||||
@JsonProperty("currentLinks") @SerialName("currentLinks") val currentLinks: List<ExtractorLink>,
|
val currentLinks: List<ExtractorLink>,
|
||||||
@JsonProperty("currentSubtitles") @SerialName("currentSubtitles") val currentSubtitles: List<SubtitleData>,
|
val currentSubtitles: List<SubtitleData>
|
||||||
)
|
)
|
||||||
|
|
||||||
class SelectSourceController(val view: ImageView, val activity: ControllerActivity) : UIController() {
|
class SelectSourceController(val view: ImageView, val activity: ControllerActivity) :
|
||||||
|
UIController() {
|
||||||
|
private val mapper: JsonMapper = JsonMapper.builder().addModule(kotlinModule())
|
||||||
|
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
view.setImageResource(R.drawable.ic_baseline_playlist_play_24)
|
view.setImageResource(R.drawable.ic_baseline_playlist_play_24)
|
||||||
view.setOnClickListener {
|
view.setOnClickListener {
|
||||||
|
// lateinit var dialog: AlertDialog
|
||||||
val holder = getCurrentMetaData()
|
val holder = getCurrentMetaData()
|
||||||
|
|
||||||
if (holder != null) {
|
if (holder != null) {
|
||||||
val items = holder.currentLinks
|
val items = holder.currentLinks
|
||||||
if (items.isNotEmpty() && remoteMediaClient?.currentItem != null) {
|
if (items.isNotEmpty() && remoteMediaClient?.currentItem != null) {
|
||||||
val subTracks = remoteMediaClient?.mediaInfo?.mediaTracks?.filter { it.type == MediaTrack.TYPE_TEXT }
|
val subTracks =
|
||||||
?: ArrayList()
|
remoteMediaClient?.mediaInfo?.mediaTracks?.filter { it.type == MediaTrack.TYPE_TEXT }
|
||||||
|
?: ArrayList()
|
||||||
|
|
||||||
val bottomSheetDialogBuilder = AlertDialog.Builder(view.context, R.style.AlertDialogCustomBlack)
|
val bottomSheetDialogBuilder =
|
||||||
|
AlertDialog.Builder(view.context, R.style.AlertDialogCustomBlack)
|
||||||
bottomSheetDialogBuilder.setView(R.layout.sort_bottom_sheet)
|
bottomSheetDialogBuilder.setView(R.layout.sort_bottom_sheet)
|
||||||
|
|
||||||
val bottomSheetDialog = bottomSheetDialogBuilder.create()
|
val bottomSheetDialog = bottomSheetDialogBuilder.create()
|
||||||
bottomSheetDialog.show()
|
bottomSheetDialog.show()
|
||||||
|
// bottomSheetDialog.setContentView(R.layout.sort_bottom_sheet)
|
||||||
val providerList = bottomSheetDialog.findViewById<ListView>(R.id.sort_providers)!!
|
val providerList =
|
||||||
val subtitleList = bottomSheetDialog.findViewById<ListView>(R.id.sort_subtitles)!!
|
bottomSheetDialog.findViewById<ListView>(R.id.sort_providers)!!
|
||||||
|
val subtitleList =
|
||||||
|
bottomSheetDialog.findViewById<ListView>(R.id.sort_subtitles)!!
|
||||||
if (subTracks.isEmpty()) {
|
if (subTracks.isEmpty()) {
|
||||||
bottomSheetDialog.findViewById<LinearLayout>(R.id.sort_subtitles_holder)?.visibility = GONE
|
bottomSheetDialog.findViewById<LinearLayout>(R.id.sort_subtitles_holder)?.visibility =
|
||||||
|
GONE
|
||||||
} else {
|
} else {
|
||||||
val arrayAdapter = ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
|
val arrayAdapter =
|
||||||
|
ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
|
||||||
arrayAdapter.add(view.context.getString(R.string.no_subtitles))
|
arrayAdapter.add(view.context.getString(R.string.no_subtitles))
|
||||||
arrayAdapter.addAll(subTracks.mapNotNull { it.name })
|
arrayAdapter.addAll(subTracks.mapNotNull { it.name })
|
||||||
|
|
||||||
|
|
@ -121,8 +144,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
subtitleList.adapter = arrayAdapter
|
subtitleList.adapter = arrayAdapter
|
||||||
|
|
||||||
val currentTracks = remoteMediaClient?.mediaStatus?.activeTrackIds
|
val currentTracks = remoteMediaClient?.mediaStatus?.activeTrackIds
|
||||||
val subtitleIndex = if (currentTracks == null) 0 else subTracks.map { it.id }
|
|
||||||
.indexOfFirst { currentTracks.contains(it) } + 1
|
val subtitleIndex =
|
||||||
|
if (currentTracks == null) 0 else subTracks.map { it.id }
|
||||||
|
.indexOfFirst { currentTracks.contains(it) } + 1
|
||||||
|
|
||||||
subtitleList.setSelection(subtitleIndex)
|
subtitleList.setSelection(subtitleIndex)
|
||||||
subtitleList.setItemChecked(subtitleIndex, true)
|
subtitleList.setItemChecked(subtitleIndex, true)
|
||||||
|
|
@ -134,7 +159,9 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
ChromecastSubtitlesFragment.getCurrentSavedStyle().apply {
|
ChromecastSubtitlesFragment.getCurrentSavedStyle().apply {
|
||||||
val font = TextTrackStyle()
|
val font = TextTrackStyle()
|
||||||
font.setFontFamily(fontFamily ?: "Google Sans")
|
font.setFontFamily(fontFamily ?: "Google Sans")
|
||||||
fontGenericFamily?.let { font.fontGenericFamily = it }
|
fontGenericFamily?.let {
|
||||||
|
font.fontGenericFamily = it
|
||||||
|
}
|
||||||
font.windowColor = windowColor
|
font.windowColor = windowColor
|
||||||
font.backgroundColor = backgroundColor
|
font.backgroundColor = backgroundColor
|
||||||
|
|
||||||
|
|
@ -151,7 +178,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
if (!it.status.isSuccess) {
|
if (!it.status.isSuccess) {
|
||||||
Log.e(
|
Log.e(
|
||||||
"CHROMECAST", "Failed with status code:" +
|
"CHROMECAST", "Failed with status code:" +
|
||||||
it.status.statusCode + " > " + it.status.statusMessage
|
it.status.statusCode + " > " + it.status.statusMessage
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -160,15 +187,17 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.MediaInformation
|
//https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.MediaInformation
|
||||||
val contentUrl = (remoteMediaClient?.currentItem?.media?.contentUrl
|
val contentUrl = (remoteMediaClient?.currentItem?.media?.contentUrl
|
||||||
?: remoteMediaClient?.currentItem?.media?.contentId)
|
?: remoteMediaClient?.currentItem?.media?.contentId)
|
||||||
|
|
||||||
val sortingMethods = items.map { "${it.name} ${Qualities.getStringByInt(it.quality)}" }
|
val sortingMethods =
|
||||||
.toTypedArray()
|
items.map { "${it.name} ${Qualities.getStringByInt(it.quality)}" }
|
||||||
|
.toTypedArray()
|
||||||
val sotringIndex = items.indexOfFirst { it.url == contentUrl }
|
val sotringIndex = items.indexOfFirst { it.url == contentUrl }
|
||||||
|
|
||||||
val arrayAdapter = ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
|
val arrayAdapter =
|
||||||
|
ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
|
||||||
arrayAdapter.addAll(sortingMethods.toMutableList())
|
arrayAdapter.addAll(sortingMethods.toMutableList())
|
||||||
|
|
||||||
providerList.choiceMode = AbsListView.CHOICE_MODE_SINGLE
|
providerList.choiceMode = AbsListView.CHOICE_MODE_SINGLE
|
||||||
|
|
@ -178,8 +207,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
|
|
||||||
providerList.setOnItemClickListener { _, _, which, _ ->
|
providerList.setOnItemClickListener { _, _, which, _ ->
|
||||||
val epData = holder.episodes[holder.currentEpisodeIndex]
|
val epData = holder.episodes[holder.currentEpisodeIndex]
|
||||||
|
|
||||||
fun loadMirror(index: Int) {
|
fun loadMirror(index: Int) {
|
||||||
if (holder.currentLinks.size <= index) return
|
if (holder.currentLinks.size <= index) return
|
||||||
|
|
||||||
val mediaItem = getMediaInfo(
|
val mediaItem = getMediaInfo(
|
||||||
epData,
|
epData,
|
||||||
holder,
|
holder,
|
||||||
|
|
@ -189,21 +220,25 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
)
|
)
|
||||||
|
|
||||||
val startAt = remoteMediaClient?.approximateStreamPosition ?: 0
|
val startAt = remoteMediaClient?.approximateStreamPosition ?: 0
|
||||||
|
|
||||||
|
//remoteMediaClient.load(mediaItem, true, startAt)
|
||||||
try { // THIS IS VERY IMPORTANT BECAUSE WE NEVER WANT TO AUTOLOAD THE NEXT EPISODE
|
try { // THIS IS VERY IMPORTANT BECAUSE WE NEVER WANT TO AUTOLOAD THE NEXT EPISODE
|
||||||
val currentIdIndex = remoteMediaClient?.getItemIndex()
|
val currentIdIndex = remoteMediaClient?.getItemIndex()
|
||||||
|
|
||||||
val nextId = remoteMediaClient?.mediaQueue?.itemIds?.get(
|
val nextId = remoteMediaClient?.mediaQueue?.itemIds?.get(
|
||||||
currentIdIndex?.plus(1) ?: 0
|
currentIdIndex?.plus(1) ?: 0
|
||||||
)
|
)
|
||||||
|
|
||||||
if (currentIdIndex == null && nextId != null) {
|
if (currentIdIndex == null && nextId != null) {
|
||||||
awaitLinks(
|
awaitLinks(
|
||||||
remoteMediaClient?.queueInsertAndPlayItem(
|
remoteMediaClient?.queueInsertAndPlayItem(
|
||||||
MediaQueueItem.Builder(mediaItem).build(),
|
MediaQueueItem.Builder(mediaItem).build(),
|
||||||
nextId,
|
nextId,
|
||||||
startAt,
|
startAt,
|
||||||
JSONObject(),
|
JSONObject()
|
||||||
)
|
)
|
||||||
) { loadMirror(index + 1) }
|
) {
|
||||||
|
loadMirror(index + 1)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
val mediaLoadOptions =
|
val mediaLoadOptions =
|
||||||
MediaLoadOptions.Builder()
|
MediaLoadOptions.Builder()
|
||||||
|
|
@ -215,9 +250,11 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
mediaItem,
|
mediaItem,
|
||||||
mediaLoadOptions
|
mediaLoadOptions
|
||||||
)
|
)
|
||||||
) { loadMirror(index + 1) }
|
) {
|
||||||
|
loadMirror(index + 1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
val mediaLoadOptions =
|
val mediaLoadOptions =
|
||||||
MediaLoadOptions.Builder()
|
MediaLoadOptions.Builder()
|
||||||
.setPlayPosition(startAt)
|
.setPlayPosition(startAt)
|
||||||
|
|
@ -228,8 +265,8 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
loadMirror(which)
|
loadMirror(which)
|
||||||
|
|
||||||
bottomSheetDialog.dismissSafe(activity)
|
bottomSheetDialog.dismissSafe(activity)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -239,19 +276,23 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
|
|
||||||
private fun getCurrentMetaData(): MetadataHolder? {
|
private fun getCurrentMetaData(): MetadataHolder? {
|
||||||
return try {
|
return try {
|
||||||
val data = remoteMediaClient?.mediaInfo?.customData?.toString() ?: return null
|
val data = remoteMediaClient?.mediaInfo?.customData?.toString()
|
||||||
parseJson<MetadataHolder>(data)
|
data?.toKotlinObject()
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var isLoadingMore = false
|
var isLoadingMore = false
|
||||||
|
|
||||||
|
|
||||||
override fun onMediaStatusUpdated() {
|
override fun onMediaStatusUpdated() {
|
||||||
super.onMediaStatusUpdated()
|
super.onMediaStatusUpdated()
|
||||||
val meta = getCurrentMetaData()
|
val meta = getCurrentMetaData()
|
||||||
view.visibility = if ((meta?.currentLinks?.size ?: 0) > 1) VISIBLE else INVISIBLE
|
|
||||||
|
|
||||||
|
view.visibility = if ((meta?.currentLinks?.size
|
||||||
|
?: 0) > 1
|
||||||
|
) VISIBLE else INVISIBLE
|
||||||
try {
|
try {
|
||||||
if (meta != null && meta.episodes.size > meta.currentEpisodeIndex + 1) {
|
if (meta != null && meta.episodes.size > meta.currentEpisodeIndex + 1) {
|
||||||
val currentIdIndex = remoteMediaClient?.getItemIndex() ?: return
|
val currentIdIndex = remoteMediaClient?.getItemIndex() ?: return
|
||||||
|
|
@ -268,7 +309,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
currentPosition,
|
currentPosition,
|
||||||
currentDuration,
|
currentDuration,
|
||||||
epData,
|
epData,
|
||||||
meta.episodes.getOrNull(index + 1),
|
meta.episodes.getOrNull(index + 1)
|
||||||
)
|
)
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
logError(t)
|
logError(t)
|
||||||
|
|
@ -279,7 +320,9 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
ioSafe {
|
ioSafe {
|
||||||
val currentLinks = mutableSetOf<ExtractorLink>()
|
val currentLinks = mutableSetOf<ExtractorLink>()
|
||||||
val currentSubs = mutableSetOf<SubtitleData>()
|
val currentSubs = mutableSetOf<SubtitleData>()
|
||||||
|
|
||||||
val generator = RepoLinkGenerator(listOf(epData))
|
val generator = RepoLinkGenerator(listOf(epData))
|
||||||
|
|
||||||
val isSuccessful = safeApiCall {
|
val isSuccessful = safeApiCall {
|
||||||
generator.generateLinks(
|
generator.generateLinks(
|
||||||
clearCache = false,
|
clearCache = false,
|
||||||
|
|
@ -292,7 +335,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
currentSubs.add(it)
|
currentSubs.add(it)
|
||||||
},
|
},
|
||||||
offset = 0,
|
offset = 0,
|
||||||
isCasting = true,
|
isCasting = true
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -303,18 +346,32 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
val jsonCopy = meta.copy(
|
val jsonCopy = meta.copy(
|
||||||
currentLinks = sortedLinks,
|
currentLinks = sortedLinks,
|
||||||
currentSubtitles = sortedSubs,
|
currentSubtitles = sortedSubs,
|
||||||
currentEpisodeIndex = index,
|
currentEpisodeIndex = index
|
||||||
)
|
)
|
||||||
|
|
||||||
val done = JSONObject(jsonCopy.toJson())
|
val done =
|
||||||
|
JSONObject(jsonCopy.toJson())
|
||||||
|
|
||||||
val mediaInfo = getMediaInfo(
|
val mediaInfo = getMediaInfo(
|
||||||
epData,
|
epData,
|
||||||
jsonCopy,
|
jsonCopy,
|
||||||
0,
|
0,
|
||||||
done,
|
done,
|
||||||
sortedSubs,
|
sortedSubs
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/*fun loadIndex(index: Int) {
|
||||||
|
println("LOAD INDEX::::: $index")
|
||||||
|
if (meta.currentLinks.size <= index) return
|
||||||
|
val info = getMediaInfo(
|
||||||
|
epData,
|
||||||
|
meta,
|
||||||
|
index,
|
||||||
|
done)
|
||||||
|
awaitLinks(remoteMediaClient?.load(info, true, 0)) {
|
||||||
|
loadIndex(index + 1)
|
||||||
|
}
|
||||||
|
}*/
|
||||||
activity.runOnUiThread {
|
activity.runOnUiThread {
|
||||||
awaitLinks(
|
awaitLinks(
|
||||||
remoteMediaClient?.queueAppendItem(
|
remoteMediaClient?.queueAppendItem(
|
||||||
|
|
@ -323,6 +380,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
println("FAILED TO LOAD NEXT ITEM")
|
println("FAILED TO LOAD NEXT ITEM")
|
||||||
|
// loadIndex(1)
|
||||||
}
|
}
|
||||||
isLoadingMore = false
|
isLoadingMore = false
|
||||||
}
|
}
|
||||||
|
|
@ -345,7 +403,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
|
||||||
|
|
||||||
class SkipTimeController(val view: ImageView, forwards: Boolean) : UIController() {
|
class SkipTimeController(val view: ImageView, forwards: Boolean) : UIController() {
|
||||||
init {
|
init {
|
||||||
|
//val settingsManager = PreferenceManager.getDefaultSharedPreferences()
|
||||||
|
//val time = settingsManager?.getInt("chromecast_tap_time", 30) ?: 30
|
||||||
val time = 30
|
val time = 30
|
||||||
|
//view.setImageResource(if (forwards) R.drawable.netflix_skip_forward else R.drawable.netflix_skip_back)
|
||||||
view.setImageResource(if (forwards) R.drawable.go_forward_30 else R.drawable.go_back_30)
|
view.setImageResource(if (forwards) R.drawable.go_forward_30 else R.drawable.go_back_30)
|
||||||
view.setOnClickListener {
|
view.setOnClickListener {
|
||||||
remoteMediaClient?.let {
|
remoteMediaClient?.let {
|
||||||
|
|
@ -388,4 +449,4 @@ class ControllerActivity : ExpandedControllerActivity() {
|
||||||
SkipNextEpisodeController(skipOpButton)
|
SkipNextEpisodeController(skipOpButton)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,8 +1,11 @@
|
||||||
package com.lagradost.cloudstream3.ui.account
|
package com.lagradost.cloudstream3.ui.account
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
|
import coil3.transform.RoundedCornersTransformation
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
import com.lagradost.cloudstream3.databinding.AccountListItemAddBinding
|
import com.lagradost.cloudstream3.databinding.AccountListItemAddBinding
|
||||||
import com.lagradost.cloudstream3.databinding.AccountListItemBinding
|
import com.lagradost.cloudstream3.databinding.AccountListItemBinding
|
||||||
|
|
@ -15,8 +18,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
||||||
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
||||||
import android.util.TypedValue
|
|
||||||
import android.view.View
|
|
||||||
|
|
||||||
class AccountAdapter(
|
class AccountAdapter(
|
||||||
private val accountSelectCallback: (DataStoreHelper.Account) -> Unit,
|
private val accountSelectCallback: (DataStoreHelper.Account) -> Unit,
|
||||||
|
|
@ -28,12 +29,6 @@ class AccountAdapter(
|
||||||
companion object {
|
companion object {
|
||||||
const val VIEW_TYPE_SELECT_ACCOUNT = 0
|
const val VIEW_TYPE_SELECT_ACCOUNT = 0
|
||||||
const val VIEW_TYPE_EDIT_ACCOUNT = 2
|
const val VIEW_TYPE_EDIT_ACCOUNT = 2
|
||||||
|
|
||||||
fun View.setRippleForeground() {
|
|
||||||
val outValue = TypedValue()
|
|
||||||
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true)
|
|
||||||
foreground = context.getDrawable(outValue.resourceId)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -52,25 +47,45 @@ class AccountAdapter(
|
||||||
when (val binding = holder.view) {
|
when (val binding = holder.view) {
|
||||||
is AccountListItemBinding -> binding.apply {
|
is AccountListItemBinding -> binding.apply {
|
||||||
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
|
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
|
||||||
|
|
||||||
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
|
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
|
||||||
|
|
||||||
accountName.text = item.name
|
accountName.text = item.name
|
||||||
accountImage.loadImage(item.image)
|
accountImage.loadImage(item.image)
|
||||||
lockIcon.isVisible = item.lockPin != null
|
lockIcon.isVisible = item.lockPin != null
|
||||||
root.isSelected = isLastUsedAccount
|
outline.isVisible = !isTv && isLastUsedAccount
|
||||||
cardView.isSelected = isLastUsedAccount
|
|
||||||
|
|
||||||
if (!isTv) cardView.setRippleForeground()
|
if (isTv) {
|
||||||
|
// For emulator but this is fine on TV also
|
||||||
|
root.isFocusableInTouchMode = true
|
||||||
|
if (isLastUsedAccount) {
|
||||||
|
root.requestFocus()
|
||||||
|
}
|
||||||
|
|
||||||
if (!isTv) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
root.foreground = ContextCompat.getDrawable(
|
||||||
|
root.context,
|
||||||
|
R.drawable.outline_drawable
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
root.setOnLongClickListener {
|
root.setOnLongClickListener {
|
||||||
showAccountEditDialog(
|
showAccountEditDialog(
|
||||||
context = root.context,
|
context = root.context,
|
||||||
account = item,
|
account = item,
|
||||||
isNewAccount = false,
|
isNewAccount = false,
|
||||||
accountEditCallback = { account -> accountEditCallback.invoke(account) },
|
accountEditCallback = { account ->
|
||||||
accountDeleteCallback = { account -> accountDeleteCallback.invoke(account) }
|
accountEditCallback.invoke(
|
||||||
|
account
|
||||||
|
)
|
||||||
|
},
|
||||||
|
accountDeleteCallback = { account ->
|
||||||
|
accountDeleteCallback.invoke(
|
||||||
|
account
|
||||||
|
)
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -82,15 +97,30 @@ class AccountAdapter(
|
||||||
|
|
||||||
is AccountListItemEditBinding -> binding.apply {
|
is AccountListItemEditBinding -> binding.apply {
|
||||||
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
|
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
|
||||||
|
|
||||||
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
|
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
|
||||||
|
|
||||||
accountName.text = item.name
|
accountName.text = item.name
|
||||||
accountImage.loadImage(item.image)
|
accountImage.loadImage(item.image) {
|
||||||
|
RoundedCornersTransformation(10f)
|
||||||
|
}
|
||||||
lockIcon.isVisible = item.lockPin != null
|
lockIcon.isVisible = item.lockPin != null
|
||||||
root.isSelected = isLastUsedAccount
|
outline.isVisible = !isTv && isLastUsedAccount
|
||||||
cardView.isSelected = isLastUsedAccount
|
|
||||||
|
|
||||||
if (!isTv) cardView.setRippleForeground()
|
if (isTv) {
|
||||||
|
// For emulator but this is fine on TV also
|
||||||
|
root.isFocusableInTouchMode = true
|
||||||
|
if (isLastUsedAccount) {
|
||||||
|
root.requestFocus()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
root.foreground = ContextCompat.getDrawable(
|
||||||
|
root.context,
|
||||||
|
R.drawable.outline_drawable
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
root.setOnClickListener {
|
root.setOnClickListener {
|
||||||
showAccountEditDialog(
|
showAccountEditDialog(
|
||||||
|
|
@ -98,7 +128,11 @@ class AccountAdapter(
|
||||||
account = item,
|
account = item,
|
||||||
isNewAccount = false,
|
isNewAccount = false,
|
||||||
accountEditCallback = { account -> accountEditCallback.invoke(account) },
|
accountEditCallback = { account -> accountEditCallback.invoke(account) },
|
||||||
accountDeleteCallback = { account -> accountDeleteCallback.invoke(account) }
|
accountDeleteCallback = { account ->
|
||||||
|
accountDeleteCallback.invoke(
|
||||||
|
account
|
||||||
|
)
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -108,9 +142,6 @@ class AccountAdapter(
|
||||||
override fun onBindFooter(holder: ViewHolderState<Any>) {
|
override fun onBindFooter(holder: ViewHolderState<Any>) {
|
||||||
val binding = holder.view as? AccountListItemAddBinding ?: return
|
val binding = holder.view as? AccountListItemAddBinding ?: return
|
||||||
binding.apply {
|
binding.apply {
|
||||||
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
|
|
||||||
if (!isTv) cardView.setRippleForeground()
|
|
||||||
|
|
||||||
root.setOnClickListener {
|
root.setOnClickListener {
|
||||||
val accounts = this@AccountAdapter.immutableCurrentList
|
val accounts = this@AccountAdapter.immutableCurrentList
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,14 +37,8 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.getDefaultAccount
|
import com.lagradost.cloudstream3.utils.DataStoreHelper.getDefaultAccount
|
||||||
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.hideProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
|
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showProgress
|
|
||||||
import com.lagradost.cloudstream3.ui.account.AccountAdapter.Companion.setRippleForeground
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
|
||||||
|
|
||||||
object AccountHelper {
|
object AccountHelper {
|
||||||
fun showAccountEditDialog(
|
fun showAccountEditDialog(
|
||||||
|
|
@ -60,12 +54,6 @@ object AccountHelper {
|
||||||
|
|
||||||
var currentEditAccount = account
|
var currentEditAccount = account
|
||||||
val dialog = builder.show()
|
val dialog = builder.show()
|
||||||
binding.accountImageHolder.requestFocus()
|
|
||||||
|
|
||||||
if (!isLayout(TV or EMULATOR)) {
|
|
||||||
binding.accountImageHolder.setRippleForeground()
|
|
||||||
binding.editProfilePhotoButtonHolder.setRippleForeground()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isNewAccount) binding.title.setText(R.string.edit_account)
|
if (!isNewAccount) binding.title.setText(R.string.edit_account)
|
||||||
|
|
||||||
|
|
@ -110,7 +98,7 @@ object AccountHelper {
|
||||||
|
|
||||||
// Handle the profile picture and its interactions
|
// Handle the profile picture and its interactions
|
||||||
binding.accountImage.loadImage(account.image)
|
binding.accountImage.loadImage(account.image)
|
||||||
binding.accountImageHolder.setOnClickListener {
|
binding.accountImage.setOnClickListener {
|
||||||
// Roll the image forwards once
|
// Roll the image forwards once
|
||||||
currentEditAccount = currentEditAccount.copy(customImage = null)
|
currentEditAccount = currentEditAccount.copy(customImage = null)
|
||||||
currentEditAccount =
|
currentEditAccount =
|
||||||
|
|
@ -176,57 +164,52 @@ object AccountHelper {
|
||||||
|
|
||||||
canSetPin = true
|
canSetPin = true
|
||||||
|
|
||||||
binding.editProfilePhotoButtonHolder.setOnClickListener {
|
binding.editProfilePhotoButton.setOnClickListener({
|
||||||
val builder = AlertDialog.Builder(context, R.style.AlertDialogCustom)
|
val bottomSheetDialog = BottomSheetDialog(context)
|
||||||
val sheetBinding = BottomInputDialogBinding.inflate(LayoutInflater.from(context))
|
val sheetBinding = BottomInputDialogBinding.inflate(LayoutInflater.from(context))
|
||||||
builder.setView(sheetBinding.root)
|
bottomSheetDialog.setContentView(sheetBinding.root)
|
||||||
val dialog = builder.create()
|
bottomSheetDialog.show()
|
||||||
dialog.show()
|
|
||||||
|
|
||||||
sheetBinding.apply {
|
sheetBinding.apply {
|
||||||
text1.text = context.getString(R.string.edit_profile_image_title)
|
text1.text = context.getString(R.string.edit_profile_image_title)
|
||||||
nginxTextInput.hint = context.getString(R.string.edit_profile_image_hint)
|
nginxTextInput.hint = context.getString(R.string.edit_profile_image_hint)
|
||||||
|
|
||||||
applyBtt.setOnClickListener {
|
applyBtt.setOnClickListener({
|
||||||
val url = sheetBinding.nginxTextInput.text.toString()
|
val url = sheetBinding.nginxTextInput.text.toString()
|
||||||
if (url.isEmpty()) {
|
if (url.isNotEmpty()) {
|
||||||
|
val imageLoader = ImageLoader(context)
|
||||||
|
val request = ImageRequest.Builder(context)
|
||||||
|
.data(url)
|
||||||
|
.allowHardware(false)
|
||||||
|
.listener(
|
||||||
|
onSuccess = { _, _ ->
|
||||||
|
currentEditAccount = currentEditAccount.copy(customImage = url)
|
||||||
|
binding.accountImage.loadImage(url)
|
||||||
|
showToast(
|
||||||
|
R.string.edit_profile_image_success,
|
||||||
|
Toast.LENGTH_SHORT
|
||||||
|
)
|
||||||
|
bottomSheetDialog.dismiss()
|
||||||
|
},
|
||||||
|
onError = { _, _ ->
|
||||||
|
showToast(
|
||||||
|
R.string.edit_profile_image_error_invalid,
|
||||||
|
Toast.LENGTH_SHORT
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
imageLoader.enqueue(request)
|
||||||
|
} else {
|
||||||
showToast(R.string.edit_profile_image_error_empty, Toast.LENGTH_SHORT)
|
showToast(R.string.edit_profile_image_error_empty, Toast.LENGTH_SHORT)
|
||||||
return@setOnClickListener
|
|
||||||
}
|
}
|
||||||
applyBtt.showProgress()
|
bottomSheetDialog.dismissSafe()
|
||||||
val imageLoader = ImageLoader(context)
|
})
|
||||||
val request = ImageRequest.Builder(context)
|
sheetBinding.cancelBtt.setOnClickListener({
|
||||||
.data(url)
|
bottomSheetDialog.dismissSafe()
|
||||||
.allowHardware(false)
|
})
|
||||||
.listener(
|
|
||||||
onSuccess = { _, _ ->
|
|
||||||
currentEditAccount = currentEditAccount.copy(customImage = url)
|
|
||||||
binding.accountImage.loadImage(url)
|
|
||||||
showToast(
|
|
||||||
R.string.edit_profile_image_success,
|
|
||||||
Toast.LENGTH_SHORT
|
|
||||||
)
|
|
||||||
dialog.dismissSafe()
|
|
||||||
},
|
|
||||||
onError = { _, _ ->
|
|
||||||
showToast(
|
|
||||||
R.string.edit_profile_image_error_invalid,
|
|
||||||
Toast.LENGTH_SHORT
|
|
||||||
)
|
|
||||||
applyBtt.hideProgress()
|
|
||||||
},
|
|
||||||
onCancel = {
|
|
||||||
applyBtt.hideProgress()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.build()
|
|
||||||
imageLoader.enqueue(request)
|
|
||||||
}
|
|
||||||
sheetBinding.cancelBtt.setOnClickListener {
|
|
||||||
dialog.dismissSafe()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fun showPinInputDialog(
|
fun showPinInputDialog(
|
||||||
|
|
@ -368,11 +351,6 @@ object AccountHelper {
|
||||||
|
|
||||||
fun Activity?.showAccountSelectLinear() {
|
fun Activity?.showAccountSelectLinear() {
|
||||||
val activity = this as? MainActivity ?: return
|
val activity = this as? MainActivity ?: return
|
||||||
activity.navigate(
|
|
||||||
R.id.accountSelectActivity,
|
|
||||||
Bundle().apply { putBoolean(AccountSelectActivity2.IS_FROM_MAIN_ACTIVITY, true) }
|
|
||||||
)
|
|
||||||
/*
|
|
||||||
val viewModel = ViewModelProvider(activity)[AccountViewModel::class.java]
|
val viewModel = ViewModelProvider(activity)[AccountViewModel::class.java]
|
||||||
|
|
||||||
val binding: AccountSelectLinearBinding = AccountSelectLinearBinding.inflate(
|
val binding: AccountSelectLinearBinding = AccountSelectLinearBinding.inflate(
|
||||||
|
|
@ -430,6 +408,6 @@ object AccountHelper {
|
||||||
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
|
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
|
||||||
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
|
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
|
||||||
}
|
}
|
||||||
}*/
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,872 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.account
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
|
||||||
import androidx.compose.animation.core.animateDpAsState
|
|
||||||
import androidx.compose.animation.fadeIn
|
|
||||||
import androidx.compose.animation.fadeOut
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.border
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.combinedClickable
|
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.indication
|
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.FlowRow
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.layout.width
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.DropdownMenu
|
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Scaffold
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.ripple
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
|
||||||
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component2
|
|
||||||
import androidx.compose.ui.focus.focusProperties
|
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.tooling.preview.PreviewLightDark
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.window.DialogProperties
|
|
||||||
import coil3.compose.AsyncImage
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.Account
|
|
||||||
import com.lagradost.cloudstream4.compose.ActionDialog
|
|
||||||
import com.lagradost.cloudstream4.compose.BlackButton
|
|
||||||
import com.lagradost.cloudstream4.compose.BlackTextField
|
|
||||||
import com.lagradost.cloudstream4.compose.EMULATOR
|
|
||||||
import com.lagradost.cloudstream4.compose.PHONE
|
|
||||||
import com.lagradost.cloudstream4.compose.RoundedShape
|
|
||||||
import com.lagradost.cloudstream4.compose.TV
|
|
||||||
import com.lagradost.cloudstream4.compose.WhiteButton
|
|
||||||
import com.lagradost.cloudstream4.compose.circle
|
|
||||||
import com.lagradost.cloudstream4.compose.circleBorder
|
|
||||||
import com.lagradost.cloudstream4.compose.focusOutline
|
|
||||||
import com.lagradost.cloudstream4.compose.isLayout
|
|
||||||
import com.lagradost.cloudstream4.compose.rounded
|
|
||||||
import com.lagradost.cloudstream4.compose.whiteOutline
|
|
||||||
import com.lagradost.cloudstream4.state.SearchableData
|
|
||||||
import com.lagradost.cloudstream4.state.sortByInt
|
|
||||||
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
|
|
||||||
import com.mihon.material.padding
|
|
||||||
import com.mihon.presentation.settings.widget.SwitchPreferenceWidget
|
|
||||||
import com.mihon.presentation.settings.widget.TextPreferenceWidget
|
|
||||||
import kotlinx.collections.immutable.toPersistentMap
|
|
||||||
|
|
||||||
@PreviewLightDark
|
|
||||||
@Composable
|
|
||||||
fun Preview() {
|
|
||||||
CloudStreamPreviewTheme {
|
|
||||||
AccountScreen.Content(
|
|
||||||
state = AccountState(
|
|
||||||
canEditAccount = false,
|
|
||||||
editAccount = Account(
|
|
||||||
keyIndex = 1,
|
|
||||||
name = "Hello world",
|
|
||||||
defaultImageIndex = 2,
|
|
||||||
lockPin = "1234"
|
|
||||||
),
|
|
||||||
accounts = SearchableData.from(
|
|
||||||
data =
|
|
||||||
(0..7).associateWith { index ->
|
|
||||||
Account(
|
|
||||||
keyIndex = index,
|
|
||||||
name = "hello $index",
|
|
||||||
defaultImageIndex = index,
|
|
||||||
lockPin = if (index % 2 == 1) {
|
|
||||||
"1234"
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}.toPersistentMap(),
|
|
||||||
sortedBy = sortByInt { it.keyIndex },
|
|
||||||
),
|
|
||||||
), onAction = {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
object AccountScreen {
|
|
||||||
@Composable
|
|
||||||
fun Content(
|
|
||||||
state: AccountState,
|
|
||||||
onAction: (AccountAction) -> Unit
|
|
||||||
) {
|
|
||||||
if (state.editAccount != null) {
|
|
||||||
EditAccountDialog(
|
|
||||||
exists = state.accounts.data.containsKey(state.editAccount.keyIndex),
|
|
||||||
account = state.editAccount,
|
|
||||||
onAction = onAction
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Scaffold { contentPadding ->
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(contentPadding),
|
|
||||||
horizontalAlignment = Alignment.End
|
|
||||||
) {
|
|
||||||
val (edit, accounts) = remember { FocusRequester.createRefs() }
|
|
||||||
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
onAction(AccountAction.SetEditMode(!state.canEditAccount))
|
|
||||||
}, modifier = Modifier
|
|
||||||
.focusRequester(edit)
|
|
||||||
.focusProperties {
|
|
||||||
down = accounts
|
|
||||||
}
|
|
||||||
.focusOutline(shape = CircleShape)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painter = if (state.canEditAccount) {
|
|
||||||
painterResource(R.drawable.close_24px)
|
|
||||||
} else {
|
|
||||||
painterResource(R.drawable.edit_24px)
|
|
||||||
},
|
|
||||||
contentDescription = stringResource(R.string.manage_accounts)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.verticalScroll(rememberScrollState()),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Center
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = if (state.canEditAccount) stringResource(R.string.manage_accounts) else stringResource(
|
|
||||||
R.string.select_an_account
|
|
||||||
),
|
|
||||||
style = MaterialTheme.typography.headlineMedium,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
modifier = Modifier.padding(MaterialTheme.padding.large)
|
|
||||||
)
|
|
||||||
|
|
||||||
AccountsRow(
|
|
||||||
state = state, onAction = onAction,
|
|
||||||
modifier = Modifier
|
|
||||||
.focusRequester(accounts)
|
|
||||||
.focusProperties {
|
|
||||||
up = edit
|
|
||||||
})
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(100.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum class WaitForDialogType {
|
|
||||||
RemoveLock,
|
|
||||||
NewPassword,
|
|
||||||
DeleteAccount,
|
|
||||||
NewProfileUrl,
|
|
||||||
NewProfilePicture,
|
|
||||||
Login,
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun WaitForDialog(
|
|
||||||
type: WaitForDialogType,
|
|
||||||
onDismissRequest: () -> Unit,
|
|
||||||
account: Account,
|
|
||||||
onAction: (AccountAction) -> Unit
|
|
||||||
) {
|
|
||||||
when (type) {
|
|
||||||
WaitForDialogType.RemoveLock -> {
|
|
||||||
if (account.lockPin != null) {
|
|
||||||
EnterPinDialog(
|
|
||||||
expected = account.lockPin,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
onCorrect = {
|
|
||||||
onAction(AccountAction.EditAccount(account.copy(lockPin = null)))
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForDialogType.Login -> {
|
|
||||||
if (account.lockPin != null) {
|
|
||||||
EnterPinDialog(
|
|
||||||
expected = account.lockPin,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
onCorrect = {
|
|
||||||
onAction(AccountAction.SaveAccount(account))
|
|
||||||
onAction(AccountAction.EditAccount(null))
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForDialogType.NewPassword -> {
|
|
||||||
SetPinDialog(
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
onSet = { newLockPin ->
|
|
||||||
onAction(AccountAction.EditAccount(account.copy(lockPin = newLockPin)))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForDialogType.DeleteAccount -> {
|
|
||||||
ActionDialog(
|
|
||||||
title = stringResource(R.string.delete),
|
|
||||||
text = stringResource(R.string.delete_message, account.name),
|
|
||||||
confirm = {
|
|
||||||
onAction(AccountAction.DeleteAccount(account.keyIndex))
|
|
||||||
onAction(AccountAction.EditAccount(null))
|
|
||||||
onDismissRequest()
|
|
||||||
},
|
|
||||||
dismiss = onDismissRequest,
|
|
||||||
confirmText = stringResource(R.string.delete),
|
|
||||||
dismissText = stringResource(R.string.cancel)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForDialogType.NewProfilePicture -> {
|
|
||||||
SetPictureDialog(
|
|
||||||
account = account,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
onSet = { newImage ->
|
|
||||||
onAction(
|
|
||||||
AccountAction.EditAccount(
|
|
||||||
account.copy(
|
|
||||||
defaultImageIndex = newImage,
|
|
||||||
customImage = null
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
onDismissRequest()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForDialogType.NewProfileUrl -> {
|
|
||||||
SetUrlDialog(onDismissRequest = onDismissRequest, onSet = { newImage ->
|
|
||||||
onAction(AccountAction.EditAccount(account.copy(customImage = newImage)))
|
|
||||||
onDismissRequest()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun EditAccountDialog(
|
|
||||||
exists: Boolean,
|
|
||||||
account: Account,
|
|
||||||
onAction: (AccountAction) -> Unit
|
|
||||||
) {
|
|
||||||
val selectFileSelector =
|
|
||||||
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
|
||||||
// It lies, it can be null if file manager quits.
|
|
||||||
if (uri == null) return@rememberLauncherForActivityResult
|
|
||||||
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
|
|
||||||
|
|
||||||
try {
|
|
||||||
context.contentResolver.takePersistableUriPermission(
|
|
||||||
uri,
|
|
||||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
|
||||||
)
|
|
||||||
onAction(AccountAction.EditAccount(account = account.copy(customImage = uri.toString())))
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
logError(t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var pendingDialog by remember { mutableStateOf<WaitForDialogType?>(null) }
|
|
||||||
pendingDialog?.let { waitType ->
|
|
||||||
WaitForDialog(
|
|
||||||
type = waitType,
|
|
||||||
onDismissRequest = { pendingDialog = null },
|
|
||||||
account = account,
|
|
||||||
onAction = onAction
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val focusRequester = remember { FocusRequester() }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
focusRequester.requestFocus()
|
|
||||||
}
|
|
||||||
|
|
||||||
val isTv = isLayout(TV)
|
|
||||||
AlertDialog(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
confirmButton = {
|
|
||||||
if (exists) {
|
|
||||||
WhiteButton(text = stringResource(R.string.delete)) {
|
|
||||||
pendingDialog = WaitForDialogType.DeleteAccount
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WhiteButton(text = stringResource(R.string.sort_apply)) {
|
|
||||||
if (account.lockPin == null) {
|
|
||||||
onAction(AccountAction.SaveAccount(account))
|
|
||||||
onAction(AccountAction.EditAccount(null))
|
|
||||||
} else {
|
|
||||||
pendingDialog = WaitForDialogType.Login
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(
|
|
||||||
text = stringResource(R.string.cancel),
|
|
||||||
modifier = Modifier.focusRequester(focusRequester)
|
|
||||||
) {
|
|
||||||
onAction(AccountAction.EditAccount(null))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onDismissRequest = {
|
|
||||||
/**
|
|
||||||
* For UX reasons we can only dismiss it with the cancel button,
|
|
||||||
* but does not have those issues
|
|
||||||
* */
|
|
||||||
if (isTv) {
|
|
||||||
onAction(AccountAction.EditAccount(null))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
text = {
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
modifier = Modifier.verticalScroll(rememberScrollState())
|
|
||||||
) {
|
|
||||||
AccountImage(
|
|
||||||
selected = false,
|
|
||||||
edit = false,
|
|
||||||
account = account,
|
|
||||||
onClick = {
|
|
||||||
onAction(
|
|
||||||
AccountAction.EditAccount(
|
|
||||||
account.copy(
|
|
||||||
customImage = null,
|
|
||||||
defaultImageIndex = (account.defaultImageIndex + 1) % DataStoreHelper.profileImages.size
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onLongClick = {})
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
|
|
||||||
|
|
||||||
BlackTextField(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
value = account.name,
|
|
||||||
onValueChange = { newText ->
|
|
||||||
val newName = if (newText.length <= 100) {
|
|
||||||
newText
|
|
||||||
} else {
|
|
||||||
newText.substring(0, 100)
|
|
||||||
}
|
|
||||||
onAction(
|
|
||||||
AccountAction.EditAccount(
|
|
||||||
account.copy(
|
|
||||||
name = newName
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
keyboardOptions = KeyboardOptions.Default.copy(
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
keyboardType = KeyboardType.PersonName,
|
|
||||||
),
|
|
||||||
placeHolder = stringResource(R.string.name)
|
|
||||||
)
|
|
||||||
|
|
||||||
var selectProfileImage by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
|
|
||||||
TextPreferenceWidget(
|
|
||||||
modifier = Modifier
|
|
||||||
.rounded()
|
|
||||||
.focusOutline(),
|
|
||||||
title = stringResource(R.string.edit_profile_image_title),
|
|
||||||
widget = {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.add_photo_alternate_24px),
|
|
||||||
contentDescription = null
|
|
||||||
)
|
|
||||||
DropdownMenu(expanded = selectProfileImage, onDismissRequest = {
|
|
||||||
selectProfileImage = false
|
|
||||||
}, shape = RoundedShape()) {
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text(text = stringResource(R.string.edit_profile_image_url)) },
|
|
||||||
onClick = {
|
|
||||||
pendingDialog = WaitForDialogType.NewProfileUrl
|
|
||||||
selectProfileImage = false
|
|
||||||
}
|
|
||||||
)
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text(text = stringResource(R.string.edit_profile_image_picker)) },
|
|
||||||
onClick = {
|
|
||||||
selectFileSelector.launch(arrayOf("image/*"))
|
|
||||||
selectProfileImage = false
|
|
||||||
}
|
|
||||||
)
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text(text = stringResource(R.string.edit_profile_image_default)) },
|
|
||||||
onClick = {
|
|
||||||
pendingDialog = WaitForDialogType.NewProfilePicture
|
|
||||||
selectProfileImage = false
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onPreferenceClick = {
|
|
||||||
selectProfileImage = true
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
if (account.keyIndex != 0) {
|
|
||||||
SwitchPreferenceWidget(
|
|
||||||
modifier = Modifier
|
|
||||||
.rounded()
|
|
||||||
.focusOutline(),
|
|
||||||
title = stringResource(R.string.lock_profile),
|
|
||||||
checked = account.lockPin != null,
|
|
||||||
onCheckedChanged = {
|
|
||||||
pendingDialog = if (account.lockPin == null) {
|
|
||||||
WaitForDialogType.NewPassword
|
|
||||||
} else {
|
|
||||||
WaitForDialogType.RemoveLock
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun AccountsRow(
|
|
||||||
state: AccountState,
|
|
||||||
onAction: (AccountAction) -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
FlowRow(
|
|
||||||
modifier = modifier.focusGroup(),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(
|
|
||||||
MaterialTheme.padding.medium,
|
|
||||||
alignment = Alignment.Start
|
|
||||||
),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(
|
|
||||||
MaterialTheme.padding.medium,
|
|
||||||
alignment = Alignment.CenterVertically
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
state.accounts.sorted.forEach { key ->
|
|
||||||
val account = state.accounts.data[key]!!
|
|
||||||
Account(
|
|
||||||
edit = state.canEditAccount,
|
|
||||||
account = account,
|
|
||||||
onAction = onAction,
|
|
||||||
selected = state.lastLoginKeyIndex == account.keyIndex
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var hasFocus by remember { mutableStateOf(false) }
|
|
||||||
val size = 100.dp
|
|
||||||
val innerPadding by animateDpAsState(
|
|
||||||
targetValue = if (hasFocus || isLayout(PHONE or EMULATOR)) 0.dp else MaterialTheme.padding.extraSmall,
|
|
||||||
)
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
modifier = Modifier
|
|
||||||
.width(size)
|
|
||||||
.onFocusChanged { newFocus ->
|
|
||||||
hasFocus = newFocus.hasFocus
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
val interactionSource = remember { MutableInteractionSource() }
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.clickable(interactionSource = interactionSource, indication = null) {
|
|
||||||
onAction(AccountAction.NewAccount)
|
|
||||||
}
|
|
||||||
.size(size)
|
|
||||||
.padding(innerPadding)
|
|
||||||
.border(
|
|
||||||
2.dp,
|
|
||||||
MaterialTheme.colorScheme.onBackground.copy(alpha = 0.2f),
|
|
||||||
CircleShape
|
|
||||||
)
|
|
||||||
.circle()
|
|
||||||
.background(MaterialTheme.colorScheme.surfaceVariant)
|
|
||||||
.whiteOutline(hasFocus = hasFocus, shape = CircleShape)
|
|
||||||
.indication(
|
|
||||||
interactionSource = interactionSource,
|
|
||||||
indication = ripple()
|
|
||||||
),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.add_24px),
|
|
||||||
contentDescription = stringResource(R.string.add_account),
|
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
|
||||||
modifier = Modifier.size(36.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.height(MaterialTheme.padding.small))
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.add_account),
|
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun PinTextField(value: String, onValueChange: (String) -> Unit) {
|
|
||||||
BlackTextField(
|
|
||||||
value = value, keyboardOptions = KeyboardOptions.Default.copy(
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
autoCorrectEnabled = false,
|
|
||||||
keyboardType = KeyboardType.NumberPassword,
|
|
||||||
), placeHolder = stringResource(R.string.pin), onValueChange = onValueChange
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun EnterPinDialog(expected: String, onDismissRequest: (() -> Unit), onCorrect: (() -> Unit)) {
|
|
||||||
AlertDialog(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
confirmButton = {},
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
|
|
||||||
},
|
|
||||||
text = {
|
|
||||||
var inputText by remember { mutableStateOf("") }
|
|
||||||
var hasError by remember { mutableStateOf(false) }
|
|
||||||
Column {
|
|
||||||
PinTextField(
|
|
||||||
value = inputText,
|
|
||||||
onValueChange = { newText ->
|
|
||||||
if (newText.length == expected.length) {
|
|
||||||
if (newText == expected) {
|
|
||||||
onCorrect()
|
|
||||||
onDismissRequest()
|
|
||||||
} else {
|
|
||||||
inputText = ""
|
|
||||||
hasError = true
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
inputText = newText
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
|
|
||||||
if (hasError) {
|
|
||||||
Text(text = stringResource(R.string.pin_error_incorrect))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
title = {
|
|
||||||
Text(text = stringResource(R.string.enter_pin))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun SetPinDialog(onDismissRequest: (() -> Unit), onSet: ((String) -> Unit)) {
|
|
||||||
var inputText by remember { mutableStateOf("") }
|
|
||||||
AlertDialog(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
confirmButton = {
|
|
||||||
if (inputText.length == 4) {
|
|
||||||
WhiteButton(
|
|
||||||
text = stringResource(R.string.sort_apply),
|
|
||||||
onClick = {
|
|
||||||
onSet(inputText)
|
|
||||||
onDismissRequest()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
|
|
||||||
},
|
|
||||||
text = {
|
|
||||||
PinTextField(
|
|
||||||
value = inputText,
|
|
||||||
onValueChange = { newText ->
|
|
||||||
/**
|
|
||||||
* We require isDigit for SetPin,
|
|
||||||
* but do not for the EnterPin to avoid inaccessable accounts
|
|
||||||
* */
|
|
||||||
val newTextFilter = if (newText.all(Char::isDigit)) {
|
|
||||||
newText
|
|
||||||
} else {
|
|
||||||
newText.filter(Char::isDigit)
|
|
||||||
}
|
|
||||||
|
|
||||||
inputText = if (newTextFilter.length <= 4) {
|
|
||||||
newTextFilter
|
|
||||||
} else {
|
|
||||||
newTextFilter.substring(0, 4)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
title = {
|
|
||||||
Text(text = stringResource(R.string.enter_pin))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun SetUrlDialog(onDismissRequest: (() -> Unit), onSet: ((String) -> Unit)) {
|
|
||||||
var inputText by remember { mutableStateOf("") }
|
|
||||||
AlertDialog(
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
confirmButton = {
|
|
||||||
WhiteButton(
|
|
||||||
text = stringResource(R.string.sort_apply),
|
|
||||||
onClick = {
|
|
||||||
onSet(inputText)
|
|
||||||
onDismissRequest()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
|
|
||||||
},
|
|
||||||
text = {
|
|
||||||
BlackTextField(
|
|
||||||
value = inputText,
|
|
||||||
onValueChange = { newText ->
|
|
||||||
inputText = newText
|
|
||||||
},
|
|
||||||
placeHolder = stringResource(R.string.edit_profile_image_hint)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
title = {
|
|
||||||
Text(text = stringResource(R.string.edit_profile_image_title))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun SetPictureDialog(
|
|
||||||
account: Account,
|
|
||||||
onDismissRequest: (() -> Unit),
|
|
||||||
onSet: ((Int) -> Unit)
|
|
||||||
) {
|
|
||||||
AlertDialog(
|
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
onDismissRequest = onDismissRequest,
|
|
||||||
confirmButton = { },
|
|
||||||
dismissButton = {
|
|
||||||
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
|
|
||||||
},
|
|
||||||
text = {
|
|
||||||
FlowRow(
|
|
||||||
modifier = Modifier.focusGroup(),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(
|
|
||||||
MaterialTheme.padding.medium,
|
|
||||||
alignment = Alignment.Start
|
|
||||||
),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(
|
|
||||||
MaterialTheme.padding.medium,
|
|
||||||
alignment = Alignment.CenterVertically
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
for (i in DataStoreHelper.profileImages.indices) {
|
|
||||||
AccountImage(
|
|
||||||
edit = false,
|
|
||||||
showName = false,
|
|
||||||
selected = account.defaultImageIndex == i,
|
|
||||||
account = account.copy(
|
|
||||||
customImage = null,
|
|
||||||
defaultImageIndex = i,
|
|
||||||
lockPin = null
|
|
||||||
),
|
|
||||||
onClick = {
|
|
||||||
onSet(i)
|
|
||||||
},
|
|
||||||
onLongClick = {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
title = {
|
|
||||||
Text(text = stringResource(R.string.edit_profile_image_title))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun AccountImage(
|
|
||||||
/** If we should show the edit pen */
|
|
||||||
edit: Boolean,
|
|
||||||
/** If this element should have focus */
|
|
||||||
selected: Boolean,
|
|
||||||
/** If we should show the name under the picture */
|
|
||||||
showName: Boolean = true,
|
|
||||||
account: Account,
|
|
||||||
onClick: () -> Unit,
|
|
||||||
onLongClick: () -> Unit
|
|
||||||
) {
|
|
||||||
val image = account.customImage
|
|
||||||
?: DataStoreHelper.profileImages[account.defaultImageIndex % DataStoreHelper.profileImages.size]
|
|
||||||
|
|
||||||
val interactionSource = remember { MutableInteractionSource() }
|
|
||||||
var hasFocus by remember { mutableStateOf(false) }
|
|
||||||
val size = 100.dp
|
|
||||||
val innerPadding by animateDpAsState(
|
|
||||||
targetValue = if (hasFocus || isLayout(PHONE or EMULATOR)) 0.dp else MaterialTheme.padding.extraSmall,
|
|
||||||
)
|
|
||||||
val focusRequester = remember { FocusRequester() }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
if (selected) {
|
|
||||||
focusRequester.requestFocus()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
modifier = Modifier
|
|
||||||
.width(size)
|
|
||||||
.focusRequester(focusRequester)
|
|
||||||
.onFocusChanged { newFocus ->
|
|
||||||
hasFocus = newFocus.hasFocus
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.size(size)
|
|
||||||
.combinedClickable(
|
|
||||||
interactionSource = interactionSource,
|
|
||||||
indication = null,
|
|
||||||
onClick = onClick,
|
|
||||||
onLongClick = onLongClick
|
|
||||||
)
|
|
||||||
.padding(innerPadding),
|
|
||||||
contentAlignment = Alignment.Center
|
|
||||||
) {
|
|
||||||
AsyncImage(
|
|
||||||
model = image,
|
|
||||||
modifier = Modifier
|
|
||||||
.circleBorder(size)
|
|
||||||
.whiteOutline(hasFocus = hasFocus, shape = CircleShape)
|
|
||||||
.indication(interactionSource = interactionSource, indication = ripple()),
|
|
||||||
contentDescription = account.name,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
alpha = if (edit) {
|
|
||||||
0.6f
|
|
||||||
} else {
|
|
||||||
1.0f
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
if (account.lockPin != null) {
|
|
||||||
Box(
|
|
||||||
contentAlignment = Alignment.TopEnd, modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(
|
|
||||||
MaterialTheme.padding.extraSmall
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.video_locked),
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
|
||||||
modifier = Modifier
|
|
||||||
.size(22.dp + MaterialTheme.padding.extraSmall * 2)
|
|
||||||
.background(
|
|
||||||
MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
shape = CircleShape
|
|
||||||
)
|
|
||||||
.padding(MaterialTheme.padding.extraSmall)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this@Column.AnimatedVisibility(
|
|
||||||
visible = edit,
|
|
||||||
enter = fadeIn(),
|
|
||||||
exit = fadeOut()
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.edit_24px),
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.onBackground,
|
|
||||||
modifier = Modifier.size(36.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (showName) {
|
|
||||||
Spacer(Modifier.height(MaterialTheme.padding.small))
|
|
||||||
Text(
|
|
||||||
text = account.name,
|
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
maxLines = 2,
|
|
||||||
overflow = TextOverflow.Ellipsis
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun Account(
|
|
||||||
edit: Boolean,
|
|
||||||
selected: Boolean,
|
|
||||||
account: Account,
|
|
||||||
onAction: (AccountAction) -> Unit
|
|
||||||
) {
|
|
||||||
var waitForLock by remember { mutableStateOf(false) }
|
|
||||||
if (waitForLock && account.lockPin != null) {
|
|
||||||
EnterPinDialog(
|
|
||||||
expected = account.lockPin,
|
|
||||||
onDismissRequest = {
|
|
||||||
waitForLock = false
|
|
||||||
}, onCorrect = {
|
|
||||||
onAction(AccountAction.LoginWithAccount(account.keyIndex))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
AccountImage(selected = selected, edit = edit, account = account, onClick = {
|
|
||||||
if (edit) {
|
|
||||||
onAction(AccountAction.EditAccount(account))
|
|
||||||
} else if (account.lockPin != null) {
|
|
||||||
waitForLock = true
|
|
||||||
} else {
|
|
||||||
onAction(AccountAction.LoginWithAccount(account.keyIndex))
|
|
||||||
}
|
|
||||||
}, onLongClick = {
|
|
||||||
/** Long click -> edit without having to press the edit button for better UX */
|
|
||||||
onAction(AccountAction.EditAccount(account))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -54,15 +54,10 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
|
||||||
false
|
false
|
||||||
)
|
)
|
||||||
|
|
||||||
val isFromMainActivity = intent.getBooleanExtra(
|
|
||||||
"isFromMainActivity",
|
|
||||||
false
|
|
||||||
)
|
|
||||||
|
|
||||||
// Sometimes we start this activity when we have already logged in
|
// Sometimes we start this activity when we have already logged in
|
||||||
// For example when using cloudstreamsearch://
|
// For example when using cloudstreamsearch://
|
||||||
// In those cases we want to just go to the main activity instantly
|
// In those cases we want to just go to the main activity instantly
|
||||||
if (hasLoggedIn && !isEditingFromMainActivity && !isFromMainActivity) {
|
if (hasLoggedIn && !isEditingFromMainActivity) {
|
||||||
navigateToMainActivity()
|
navigateToMainActivity()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -103,7 +98,7 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
|
||||||
|
|
||||||
// Don't show account selection if there is only
|
// Don't show account selection if there is only
|
||||||
// one account that exists
|
// one account that exists
|
||||||
if (!isFromMainActivity && !isEditingFromMainActivity && skipStartup) {
|
if (!isEditingFromMainActivity && skipStartup) {
|
||||||
val currentAccount = accounts.firstOrNull { it.keyIndex == selectedKeyIndex }
|
val currentAccount = accounts.firstOrNull { it.keyIndex == selectedKeyIndex }
|
||||||
if (currentAccount?.lockPin != null) {
|
if (currentAccount?.lockPin != null) {
|
||||||
CommonActivity.init(this)
|
CommonActivity.init(this)
|
||||||
|
|
@ -165,11 +160,6 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
|
||||||
// Scroll to current account (which is focused by default)
|
// Scroll to current account (which is focused by default)
|
||||||
val layoutManager = recyclerView.layoutManager as GridLayoutManager
|
val layoutManager = recyclerView.layoutManager as GridLayoutManager
|
||||||
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
|
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
|
||||||
if (isLayout(TV or EMULATOR)) {
|
|
||||||
recyclerView.post {
|
|
||||||
layoutManager.findViewByPosition(selectedKeyIndex)?.requestFocus()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
observe(accountViewModel.isEditing) { isEditing ->
|
observe(accountViewModel.isEditing) { isEditing ->
|
||||||
|
|
|
||||||
|
|
@ -1,180 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.account
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.fragment.app.FragmentActivity
|
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.loadThemes
|
|
||||||
import com.lagradost.cloudstream3.MainActivity
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.BiometricCallback
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.biometricPrompt
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.deviceHasPasswordPinLock
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.promptInfo
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.startBiometricAuthentication
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.Account
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.enableEdgeToEdgeCompat
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.openActivity
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
|
|
||||||
import com.lagradost.cloudstream4.AppSettings
|
|
||||||
import com.lagradost.cloudstream4.compose.CloudStreamThemeAppSettings
|
|
||||||
import com.lagradost.cloudstream4.state.SearchableData
|
|
||||||
import com.lagradost.cloudstream4.state.sortByInt
|
|
||||||
import kotlinx.collections.immutable.persistentMapOf
|
|
||||||
|
|
||||||
class AccountSelectActivity2 : FragmentActivity(), BiometricCallback {
|
|
||||||
companion object {
|
|
||||||
var hasLoggedIn: Boolean = false
|
|
||||||
const val IS_FROM_MAIN_ACTIVITY = "isFromMainActivity"
|
|
||||||
const val IS_EDITING_FROM_MAIN_ACTIVITY = "isEditingFromMainActivity"
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
|
|
||||||
// Are we editing and coming from MainActivity?
|
|
||||||
val isEditingFromMainActivity = intent.getBooleanExtra(IS_EDITING_FROM_MAIN_ACTIVITY, false)
|
|
||||||
|
|
||||||
// Are we invoked from the main activity to edit it?
|
|
||||||
val isFromMainActivity = intent.getBooleanExtra(IS_FROM_MAIN_ACTIVITY, false)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sometimes we start this activity when we have already logged in
|
|
||||||
* For example when using cloudstreamsearch://
|
|
||||||
*
|
|
||||||
* In those cases we want to just go to the main activity instantly
|
|
||||||
**/
|
|
||||||
if (hasLoggedIn && !isEditingFromMainActivity && !isFromMainActivity) {
|
|
||||||
navigateToMainActivity()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Here we set the themes, this *can* be deferred for faster instant login,
|
|
||||||
* but has some consequences that makes it undesirable even if it is slower
|
|
||||||
*
|
|
||||||
* CommonActivity.init : loads the correct locale for default_account
|
|
||||||
* loadThemes : loads the correct color on the toast when logging in
|
|
||||||
* */
|
|
||||||
CommonActivity.init(this)
|
|
||||||
loadThemes(this)
|
|
||||||
enableEdgeToEdgeCompat()
|
|
||||||
setNavigationBarColorCompat(R.attr.primaryBlackBackground)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* To avoid touching the UI layer, we use the raw state before the viewmodel is created
|
|
||||||
* to enable us to skip account selection but still use the ergonomics of AccountState
|
|
||||||
* */
|
|
||||||
val defaultName = getString(R.string.default_account)
|
|
||||||
val defaultAccount = Account(
|
|
||||||
keyIndex = 0,
|
|
||||||
name = defaultName,
|
|
||||||
defaultImageIndex = 0,
|
|
||||||
)
|
|
||||||
val initialState = AccountState(
|
|
||||||
canEditAccount = isEditingFromMainActivity,
|
|
||||||
lastLoginKeyIndex = DataStoreHelper.selectedKeyIndex,
|
|
||||||
accounts = SearchableData.from(
|
|
||||||
/** We must always have a default account
|
|
||||||
* even if DataStoreHelper.accounts.size = 0 */
|
|
||||||
data = persistentMapOf(defaultAccount.keyIndex to defaultAccount)
|
|
||||||
.puttingAll(DataStoreHelper.accounts.associateBy { it.keyIndex }),
|
|
||||||
sortedBy = sortByInt { it.keyIndex }
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
val settings = AppSettings(this)
|
|
||||||
val skipAccountSelection = settings.security.skipAccountSelection.get()
|
|
||||||
|
|
||||||
/** Don't show account selection if there is only one account that exists */
|
|
||||||
if (
|
|
||||||
!isFromMainActivity &&
|
|
||||||
!isEditingFromMainActivity &&
|
|
||||||
(skipAccountSelection || initialState.accounts.data.size == 1)
|
|
||||||
) {
|
|
||||||
/** We must have an account without a pin */
|
|
||||||
val currentAccount = initialState.accounts.data[initialState.lastLoginKeyIndex]
|
|
||||||
if (
|
|
||||||
currentAccount != null &&
|
|
||||||
currentAccount.lockPin == null
|
|
||||||
) {
|
|
||||||
/**
|
|
||||||
* Show toast if we have many accounts,
|
|
||||||
* as it is unnecessary for 1 account
|
|
||||||
* */
|
|
||||||
DataStoreHelper.setAccount(
|
|
||||||
currentAccount,
|
|
||||||
showToast = initialState.accounts.data.size > 1
|
|
||||||
)
|
|
||||||
/**
|
|
||||||
* We avoid using the viewmodel Login as we
|
|
||||||
* can return *before* we load Compose code!
|
|
||||||
* */
|
|
||||||
navigateToMainActivity()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If this app is locked with biometrics,
|
|
||||||
* then require that on a startup that is not skipped!
|
|
||||||
* */
|
|
||||||
if (
|
|
||||||
!isFromMainActivity &&
|
|
||||||
!isEditingFromMainActivity &&
|
|
||||||
isLayout(PHONE) &&
|
|
||||||
settings.security.biometrics.get() &&
|
|
||||||
deviceHasPasswordPinLock(this)
|
|
||||||
) {
|
|
||||||
startBiometricAuthentication(
|
|
||||||
this,
|
|
||||||
R.string.biometric_authentication_title,
|
|
||||||
false
|
|
||||||
)
|
|
||||||
promptInfo?.let { prompt ->
|
|
||||||
biometricPrompt?.authenticate(prompt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setContent {
|
|
||||||
val viewModel = viewModel<AccountViewModel2> {
|
|
||||||
AccountViewModel2(
|
|
||||||
defaultAccount = defaultAccount,
|
|
||||||
initialState = initialState
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val state by viewModel.state.collectAsState()
|
|
||||||
if (state.loggedInWith != null) {
|
|
||||||
navigateToMainActivity()
|
|
||||||
}
|
|
||||||
CloudStreamThemeAppSettings {
|
|
||||||
AccountScreen.Content(state, viewModel::onAction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("UnsafeIntentLaunch")
|
|
||||||
private fun navigateToMainActivity() {
|
|
||||||
hasLoggedIn = true
|
|
||||||
// We want to propagate any intent we get here to MainActivity since this is just an intermediary
|
|
||||||
openActivity(MainActivity::class.java, baseIntent = intent)
|
|
||||||
finish() // Finish the account selection activity
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAuthenticationSuccess() {
|
|
||||||
Log.i(BiometricAuthenticator.TAG, "Authentication successful in AccountSelectActivity")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAuthenticationError() {
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -8,7 +8,7 @@ class AccountSelectLinearItemDecoration(private val size: Int) : RecyclerView.It
|
||||||
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
|
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
|
||||||
val layoutParams = view.layoutParams as RecyclerView.LayoutParams
|
val layoutParams = view.layoutParams as RecyclerView.LayoutParams
|
||||||
layoutParams.width = size
|
layoutParams.width = size
|
||||||
layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT
|
layoutParams.height = size
|
||||||
view.layoutParams = layoutParams
|
view.layoutParams = layoutParams
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,141 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.account
|
|
||||||
|
|
||||||
import androidx.compose.runtime.Immutable
|
|
||||||
import androidx.lifecycle.ViewModel
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKeys
|
|
||||||
import com.lagradost.cloudstream3.MainActivity
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
|
||||||
import com.lagradost.cloudstream4.state.ActionHandler
|
|
||||||
import com.lagradost.cloudstream4.state.DefaultStateContainer
|
|
||||||
import com.lagradost.cloudstream4.state.SearchableData
|
|
||||||
import com.lagradost.cloudstream4.state.StateContainer
|
|
||||||
import com.lagradost.cloudstream4.state.sortByInt
|
|
||||||
import kotlinx.collections.immutable.persistentMapOf
|
|
||||||
import kotlin.random.Random
|
|
||||||
import kotlin.random.nextInt
|
|
||||||
|
|
||||||
@Immutable
|
|
||||||
data class AccountState(
|
|
||||||
/** Mostly used for focus stuff on TV */
|
|
||||||
val lastLoginKeyIndex : Int = 0,
|
|
||||||
|
|
||||||
/** Is currently open to editing */
|
|
||||||
val canEditAccount: Boolean = false,
|
|
||||||
|
|
||||||
/** keyIndex -> DataStoreHelper.Account sorted by keyIndex as keyIndex is unique and in add order */
|
|
||||||
val accounts: SearchableData<Int, DataStoreHelper.Account> = SearchableData.from(
|
|
||||||
data = persistentMapOf(),
|
|
||||||
/** This will cause bugs if changed! */
|
|
||||||
sortedBy = sortByInt { it.keyIndex }
|
|
||||||
),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* We are currectly editing this account with this value, it may be an existing/new account
|
|
||||||
* non-null = editing, null = not editing
|
|
||||||
* */
|
|
||||||
val editAccount: DataStoreHelper.Account? = null,
|
|
||||||
|
|
||||||
/** We are currently logged in with this account, we use state instead of effect to prevent bugs */
|
|
||||||
val loggedInWith: Int? = null
|
|
||||||
)
|
|
||||||
|
|
||||||
@Immutable
|
|
||||||
sealed class AccountAction {
|
|
||||||
data class SetEditMode(val canEditAccount: Boolean) : AccountAction()
|
|
||||||
object NewAccount : AccountAction()
|
|
||||||
data class EditAccount(val account: DataStoreHelper.Account?) : AccountAction()
|
|
||||||
data class SaveAccount(val account: DataStoreHelper.Account) : AccountAction()
|
|
||||||
data class LoginWithAccount(val accountKeyIndex: Int) : AccountAction()
|
|
||||||
data class DeleteAccount(val accountKeyIndex: Int) : AccountAction()
|
|
||||||
}
|
|
||||||
|
|
||||||
class AccountViewModel2(
|
|
||||||
val defaultAccount: DataStoreHelper.Account,
|
|
||||||
initialState : AccountState,
|
|
||||||
) : ViewModel(), StateContainer<AccountState> by DefaultStateContainer(initialState), ActionHandler<AccountAction> {
|
|
||||||
fun updateAccount(
|
|
||||||
updater: (SearchableData<Int, DataStoreHelper.Account>) -> SearchableData<Int, DataStoreHelper.Account>
|
|
||||||
) {
|
|
||||||
updateState {
|
|
||||||
/** `adding` has will "Replace" on same key, and "Add" on a new key */
|
|
||||||
val newAccounts = updater(accounts)
|
|
||||||
DataStoreHelper.accounts =
|
|
||||||
Array(newAccounts.sorted.size) { i ->
|
|
||||||
/** i -> keyIndex -> Account; As keyIndex != index */
|
|
||||||
newAccounts.data[newAccounts.sorted[i]]!!
|
|
||||||
}
|
|
||||||
copy(accounts = newAccounts)
|
|
||||||
}
|
|
||||||
|
|
||||||
MainActivity.reloadAccountEvent(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAction(action: AccountAction) {
|
|
||||||
when (action) {
|
|
||||||
is AccountAction.SetEditMode -> {
|
|
||||||
updateState { copy(canEditAccount = action.canEditAccount) }
|
|
||||||
}
|
|
||||||
|
|
||||||
is AccountAction.NewAccount -> {
|
|
||||||
updateState {
|
|
||||||
copy(
|
|
||||||
editAccount = DataStoreHelper.Account(
|
|
||||||
/** Last => maxOf, this WILL break if we allow other sorting orders */
|
|
||||||
keyIndex = (accounts.sorted.lastOrNull() ?: 0) + 1,
|
|
||||||
/** This is not "translated", but that should not really be a problem */
|
|
||||||
name = "Account ${accounts.data.size + 1}",
|
|
||||||
customImage = null,
|
|
||||||
defaultImageIndex = Random.nextInt(DataStoreHelper.profileImages.indices),
|
|
||||||
lockPin = null,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is AccountAction.DeleteAccount -> {
|
|
||||||
removeKeys(action.accountKeyIndex.toString())
|
|
||||||
|
|
||||||
/** If we remove the logged in account,
|
|
||||||
* then we switch to the default account */
|
|
||||||
if (action.accountKeyIndex == DataStoreHelper.selectedKeyIndex) {
|
|
||||||
val nextAccount = state.value.accounts.data[defaultAccount.keyIndex]
|
|
||||||
/** This should never be non-null, but just in case! */
|
|
||||||
?: defaultAccount
|
|
||||||
DataStoreHelper.setAccount(nextAccount)
|
|
||||||
updateState { copy(lastLoginKeyIndex = nextAccount.keyIndex) }
|
|
||||||
}
|
|
||||||
|
|
||||||
updateAccount { accounts ->
|
|
||||||
val pendingAccounts = accounts.removing(action.accountKeyIndex)
|
|
||||||
|
|
||||||
/** We must always have a default account */
|
|
||||||
if (pendingAccounts.data.containsKey(defaultAccount.keyIndex)) {
|
|
||||||
pendingAccounts
|
|
||||||
} else {
|
|
||||||
pendingAccounts.adding(defaultAccount.keyIndex, defaultAccount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is AccountAction.SaveAccount -> {
|
|
||||||
updateAccount { accounts ->
|
|
||||||
/** `adding` has will "Replace" on same key, and "Add" on a new key */
|
|
||||||
accounts.adding(action.account.keyIndex, action.account)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is AccountAction.LoginWithAccount -> {
|
|
||||||
val accounts = state.value.accounts
|
|
||||||
val loginAccount = accounts.data[action.accountKeyIndex] ?: return
|
|
||||||
// Show toast if we have many accounts, as it is unnecessary for 1 account
|
|
||||||
DataStoreHelper.setAccount(loginAccount, showToast = accounts.data.size > 1)
|
|
||||||
MainActivity.reloadAccountEvent(true)
|
|
||||||
updateState { copy(loggedInWith = loginAccount.keyIndex, lastLoginKeyIndex = loginAccount.keyIndex) }
|
|
||||||
}
|
|
||||||
|
|
||||||
is AccountAction.EditAccount -> {
|
|
||||||
updateState { copy(editAccount = action.account) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -10,7 +10,6 @@ import androidx.lifecycle.LiveData
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.lagradost.api.Log
|
import com.lagradost.api.Log
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp
|
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
import com.lagradost.cloudstream3.isEpisodeBased
|
import com.lagradost.cloudstream3.isEpisodeBased
|
||||||
import com.lagradost.cloudstream3.mvvm.Resource
|
import com.lagradost.cloudstream3.mvvm.Resource
|
||||||
|
|
@ -37,7 +36,6 @@ import com.lagradost.cloudstream3.utils.ResourceLiveData
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadObjects
|
import com.lagradost.cloudstream3.utils.downloader.DownloadObjects
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
||||||
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.deleteFilesAndUpdateSettings
|
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.deleteFilesAndUpdateSettings
|
||||||
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.downloadDeleteEvent
|
|
||||||
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.getDownloadFileInfo
|
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.getDownloadFileInfo
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
@ -69,17 +67,6 @@ class DownloadViewModel : ViewModel() {
|
||||||
private val _selectedItemIds = ConsistentLiveData<Set<Int>?>(null)
|
private val _selectedItemIds = ConsistentLiveData<Set<Int>?>(null)
|
||||||
val selectedItemIds: LiveData<Set<Int>?> = _selectedItemIds
|
val selectedItemIds: LiveData<Set<Int>?> = _selectedItemIds
|
||||||
|
|
||||||
init {
|
|
||||||
// Keep the Downloads list in sync when a download is deleted/cancelled from
|
|
||||||
// anywhere in the app (result page button, queue, notification, etc.). See
|
|
||||||
// onDownloadDeleted for the rationale (issue #1227).
|
|
||||||
downloadDeleteEvent += ::onDownloadDeleted
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCleared() {
|
|
||||||
downloadDeleteEvent -= ::onDownloadDeleted
|
|
||||||
super.onCleared()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cancelSelection() {
|
fun cancelSelection() {
|
||||||
updateSelectedItems { null }
|
updateSelectedItems { null }
|
||||||
|
|
@ -402,18 +389,6 @@ class DownloadViewModel : ViewModel() {
|
||||||
postChildren(_childCards.success?.filter { it.data.id !in idsToRemove })
|
postChildren(_childCards.success?.filter { it.data.id !in idsToRemove })
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Refreshes the Downloads screen in real time when a download is deleted/cancelled.
|
|
||||||
*/
|
|
||||||
private fun onDownloadDeleted(id: Int) {
|
|
||||||
// Keep multi-select state consistent: forget the removed id if it was selected.
|
|
||||||
updateSelectedItems { it?.minus(id) }
|
|
||||||
|
|
||||||
val context = CloudStreamApp.context ?: return
|
|
||||||
updateHeaderList(context)
|
|
||||||
postChildren(_childCards.success?.filterNot { it.data.id == id })
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun updateStorageStats(visual: List<VisualDownloadCached.Header>) {
|
private fun updateStorageStats(visual: List<VisualDownloadCached.Header>) {
|
||||||
try {
|
try {
|
||||||
val stat = StatFs(Environment.getExternalStorageDirectory().path)
|
val stat = StatFs(Environment.getExternalStorageDirectory().path)
|
||||||
|
|
@ -609,4 +584,4 @@ class DownloadViewModel : ViewModel() {
|
||||||
val names: List<String>,
|
val names: List<String>,
|
||||||
val parentName: String?
|
val parentName: String?
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -164,11 +164,9 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun downloadDeleteEvent(data: Int) {
|
/*fun downloadDeleteEvent(data: Int) {
|
||||||
if (data == persistentId) {
|
|
||||||
resetView()
|
}*/
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*fun downloadEvent(data: Pair<Int, VideoDownloadManager.DownloadActionType>) {
|
/*fun downloadEvent(data: Pair<Int, VideoDownloadManager.DownloadActionType>) {
|
||||||
val (id, action) = data
|
val (id, action) = data
|
||||||
|
|
@ -187,7 +185,7 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
|
||||||
|
|
||||||
override fun onAttachedToWindow() {
|
override fun onAttachedToWindow() {
|
||||||
VideoDownloadManager.downloadStatusEvent += ::downloadStatusEvent
|
VideoDownloadManager.downloadStatusEvent += ::downloadStatusEvent
|
||||||
VideoDownloadManager.downloadDeleteEvent += ::downloadDeleteEvent
|
// VideoDownloadManager.downloadDeleteEvent += ::downloadDeleteEvent
|
||||||
// VideoDownloadManager.downloadEvent += ::downloadEvent
|
// VideoDownloadManager.downloadEvent += ::downloadEvent
|
||||||
VideoDownloadManager.downloadProgressEvent += ::downloadProgressEvent
|
VideoDownloadManager.downloadProgressEvent += ::downloadProgressEvent
|
||||||
|
|
||||||
|
|
@ -202,7 +200,7 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
|
||||||
|
|
||||||
override fun onDetachedFromWindow() {
|
override fun onDetachedFromWindow() {
|
||||||
VideoDownloadManager.downloadStatusEvent -= ::downloadStatusEvent
|
VideoDownloadManager.downloadStatusEvent -= ::downloadStatusEvent
|
||||||
VideoDownloadManager.downloadDeleteEvent -= ::downloadDeleteEvent
|
// VideoDownloadManager.downloadDeleteEvent -= ::downloadDeleteEvent
|
||||||
// VideoDownloadManager.downloadEvent -= ::downloadEvent
|
// VideoDownloadManager.downloadEvent -= ::downloadEvent
|
||||||
VideoDownloadManager.downloadProgressEvent -= ::downloadProgressEvent
|
VideoDownloadManager.downloadProgressEvent -= ::downloadProgressEvent
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,22 +18,17 @@ import android.widget.Toast
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.appcompat.app.AlertDialog
|
import androidx.appcompat.app.AlertDialog
|
||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
import androidx.core.view.doOnLayout
|
|
||||||
import androidx.core.view.isGone
|
import androidx.core.view.isGone
|
||||||
import androidx.core.view.isInvisible
|
import androidx.core.view.isInvisible
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
import androidx.fragment.app.activityViewModels
|
import androidx.fragment.app.activityViewModels
|
||||||
import androidx.preference.PreferenceManager
|
import androidx.preference.PreferenceManager
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
import com.lagradost.cloudstream3.plugins.PluginManager
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getActivity
|
|
||||||
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
||||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||||
import com.google.android.material.chip.Chip
|
import com.google.android.material.chip.Chip
|
||||||
import com.lagradost.api.Log
|
import com.lagradost.api.Log
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.APIHolder.apis
|
import com.lagradost.cloudstream3.APIHolder.apis
|
||||||
import com.lagradost.cloudstream3.APIHolder.getApiFromNameNull
|
|
||||||
import com.lagradost.cloudstream3.AllLanguagesName
|
import com.lagradost.cloudstream3.AllLanguagesName
|
||||||
import com.lagradost.cloudstream3.CommonActivity.showToast
|
import com.lagradost.cloudstream3.CommonActivity.showToast
|
||||||
import com.lagradost.cloudstream3.MainAPI
|
import com.lagradost.cloudstream3.MainAPI
|
||||||
|
|
@ -48,7 +43,6 @@ import com.lagradost.cloudstream3.mvvm.Resource
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.mvvm.observe
|
import com.lagradost.cloudstream3.mvvm.observe
|
||||||
import com.lagradost.cloudstream3.mvvm.observeNullable
|
import com.lagradost.cloudstream3.mvvm.observeNullable
|
||||||
import com.lagradost.cloudstream3.plugins.Plugin
|
|
||||||
import com.lagradost.cloudstream3.ui.APIRepository.Companion.noneApi
|
import com.lagradost.cloudstream3.ui.APIRepository.Companion.noneApi
|
||||||
import com.lagradost.cloudstream3.ui.APIRepository.Companion.randomApi
|
import com.lagradost.cloudstream3.ui.APIRepository.Companion.randomApi
|
||||||
import com.lagradost.cloudstream3.ui.BaseFragment
|
import com.lagradost.cloudstream3.ui.BaseFragment
|
||||||
|
|
@ -69,7 +63,6 @@ import com.lagradost.cloudstream3.utils.AppContextUtils.getApiProviderLangSettin
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.isNetworkAvailable
|
import com.lagradost.cloudstream3.utils.AppContextUtils.isNetworkAvailable
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.isRecyclerScrollable
|
import com.lagradost.cloudstream3.utils.AppContextUtils.isRecyclerScrollable
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.loadSearchResult
|
import com.lagradost.cloudstream3.utils.AppContextUtils.loadSearchResult
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.openBrowser
|
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.ownHide
|
import com.lagradost.cloudstream3.utils.AppContextUtils.ownHide
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.ownShow
|
import com.lagradost.cloudstream3.utils.AppContextUtils.ownShow
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
||||||
|
|
@ -113,14 +106,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
|
|
||||||
val errorProfilePic = errorProfilePics.random()
|
val errorProfilePic = errorProfilePics.random()
|
||||||
|
|
||||||
fun Context.getDisplayName(apiName: String?): String? {
|
|
||||||
return when (apiName) {
|
|
||||||
noneApi.name -> getString(R.string.none)
|
|
||||||
randomApi.name -> getString(R.string.home_random)
|
|
||||||
else -> apiName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//fun Activity.loadHomepageList(
|
//fun Activity.loadHomepageList(
|
||||||
// item: HomePageList,
|
// item: HomePageList,
|
||||||
// deleteCallback: (() -> Unit)? = null,
|
// deleteCallback: (() -> Unit)? = null,
|
||||||
|
|
@ -439,30 +424,11 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
.inflate(R.layout.sort_bottom_single_provider_choice, parent, false)
|
.inflate(R.layout.sort_bottom_single_provider_choice, parent, false)
|
||||||
val titleText = view.findViewById<TextView>(R.id.text1)
|
val titleText = view.findViewById<TextView>(R.id.text1)
|
||||||
val pinIcon = view.findViewById<ImageView>(R.id.pinicon)
|
val pinIcon = view.findViewById<ImageView>(R.id.pinicon)
|
||||||
val settingsIcon = view.findViewById<ImageView>(R.id.action_settings)
|
|
||||||
|
|
||||||
val name = getItem(position)
|
val name = getItem(position)
|
||||||
titleText?.text = name
|
titleText?.text = name
|
||||||
val providerApi = currentValidApis[position]
|
|
||||||
val isPinned =
|
val isPinned =
|
||||||
pinnedphashset.contains(providerApi.name)
|
pinnedphashset.contains(currentValidApis[position].name)
|
||||||
pinIcon.visibility = if (isPinned) View.VISIBLE else View.GONE
|
pinIcon.visibility = if (isPinned) View.VISIBLE else View.GONE
|
||||||
|
|
||||||
val pluginInstance = providerApi.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
|
|
||||||
val isDownloadedPluginWithSettings = pluginInstance?.openSettings != null && !isLayout(TV)
|
|
||||||
|
|
||||||
settingsIcon.visibility = if (isDownloadedPluginWithSettings) View.VISIBLE else View.GONE
|
|
||||||
if (isDownloadedPluginWithSettings) {
|
|
||||||
settingsIcon.setOnClickListener {
|
|
||||||
try {
|
|
||||||
val activityContext = it.context.getActivity() ?: it.context
|
|
||||||
pluginInstance.openSettings?.invoke(activityContext)
|
|
||||||
} catch (e: Throwable) {
|
|
||||||
logError(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return view
|
return view
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -485,14 +451,7 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
arrayAdapter.clear()
|
arrayAdapter.clear()
|
||||||
val sortedApis = validAPIs
|
val sortedApis = validAPIs
|
||||||
.filter {
|
.filter {
|
||||||
val isPinned = pinnedphashset.contains(it.name)
|
it.hasMainPage && (pinnedphashset.contains(it.name) || it.supportedTypes.any(
|
||||||
|
|
||||||
// Hide pinned NSFW when NSFW not selected. NSFW is distracting when not chosen.
|
|
||||||
if (isPinned && !preSelectedTypes.contains(TvType.NSFW)) {
|
|
||||||
if (it.supportedTypes.all { type -> type == TvType.NSFW }) return@filter false
|
|
||||||
}
|
|
||||||
|
|
||||||
it.hasMainPage && (isPinned || it.supportedTypes.any(
|
|
||||||
preSelectedTypes::contains
|
preSelectedTypes::contains
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
@ -514,10 +473,8 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
addAll(remainingApis)
|
addAll(remainingApis)
|
||||||
}
|
}
|
||||||
|
|
||||||
val names = currentValidApis.map {
|
val names =
|
||||||
val displayName = getDisplayName(it.name)
|
currentValidApis.map { if (isMultiLang) "${getFlagFromIso(it.lang)?.plus(" ") ?: ""}${it.name}" else it.name }
|
||||||
if (isMultiLang) "${getFlagFromIso(it.lang)?.plus(" ") ?: ""}$displayName" else displayName
|
|
||||||
}
|
|
||||||
val index = currentValidApis.map { it.name }.indexOf(currentApiName)
|
val index = currentValidApis.map { it.name }.indexOf(currentApiName)
|
||||||
listView?.setItemChecked(index, true)
|
listView?.setItemChecked(index, true)
|
||||||
arrayAdapter.addAll(names)
|
arrayAdapter.addAll(names)
|
||||||
|
|
@ -708,6 +665,7 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
fromUI = true
|
fromUI = true
|
||||||
)
|
)
|
||||||
showToast(R.string.action_reload, Toast.LENGTH_SHORT)
|
showToast(R.string.action_reload, Toast.LENGTH_SHORT)
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
homePreviewSearchButton.setOnClickListener { _ ->
|
homePreviewSearchButton.setOnClickListener { _ ->
|
||||||
|
|
@ -715,38 +673,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
homeViewModel.queryTextSubmit("")
|
homeViewModel.queryTextSubmit("")
|
||||||
}
|
}
|
||||||
|
|
||||||
homePreviewSettingsButton.setOnClickListener { view ->
|
|
||||||
val apiName = homeViewModel.apiName.value
|
|
||||||
val plugin = APIHolder.getApiFromNameNull(apiName)
|
|
||||||
?.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
|
|
||||||
val openSettings = plugin?.openSettings
|
|
||||||
if (openSettings != null) {
|
|
||||||
try {
|
|
||||||
val activityContext = view.context.getActivity() ?: view.context
|
|
||||||
openSettings.invoke(activityContext)
|
|
||||||
} catch (e: Throwable) {
|
|
||||||
logError(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load value for toggling Tv layout real time clock. Hide by default at startup
|
|
||||||
// set visibility first, to apply a scroll effect later
|
|
||||||
context?.let {
|
|
||||||
if (isLayout(TV)) {
|
|
||||||
val settingsManager = PreferenceManager.getDefaultSharedPreferences(it)
|
|
||||||
val toggleClock =
|
|
||||||
settingsManager.getBoolean(
|
|
||||||
getString(R.string.tv_layout_clock_key),
|
|
||||||
false
|
|
||||||
)
|
|
||||||
binding.homeClock.isVisible = toggleClock
|
|
||||||
} else {
|
|
||||||
binding.homeClock.isVisible = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
homeMasterRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
homeMasterRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||||
if (isLayout(PHONE)) {
|
if (isLayout(PHONE)) {
|
||||||
|
|
@ -786,26 +712,12 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
view.getLocationInWindow(rect)
|
view.getLocationInWindow(rect)
|
||||||
scrollParent.isVisible = true
|
scrollParent.isVisible = true
|
||||||
scrollParent.translationY = rect[1].toFloat() - 60.toPx
|
scrollParent.translationY = rect[1].toFloat() - 60.toPx
|
||||||
|
|
||||||
// Move the TV layout real time clock out of the way too
|
|
||||||
// We check if we have the correct layout and if the clock is enabled
|
|
||||||
if(isLayout(TV) && binding.homeClock.isVisible) {
|
|
||||||
val scrollParent = binding.homeClock
|
|
||||||
|
|
||||||
val rect = IntArray(2)
|
|
||||||
view.getLocationInWindow(rect)
|
|
||||||
scrollParent.isVisible = true
|
|
||||||
scrollParent.translationY = rect[1].toFloat() - 60.toPx
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
super.onScrolled(recyclerView, dx, dy)
|
super.onScrolled(recyclerView, dx, dy)
|
||||||
updateTvRailFocus()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
homeMasterRecycler.doOnLayout { updateTvRailFocus() }
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Load value for toggling Random button. Hide at startup
|
//Load value for toggling Random button. Hide at startup
|
||||||
|
|
@ -822,10 +734,9 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
|
|
||||||
observe(homeViewModel.apiName) { apiName ->
|
observe(homeViewModel.apiName) { apiName ->
|
||||||
currentApiName = apiName
|
currentApiName = apiName
|
||||||
val displayApiName = context?.getDisplayName(apiName) ?: apiName
|
|
||||||
binding.apply {
|
binding.apply {
|
||||||
homeApiFab.text = displayApiName
|
homeApiFab.text = apiName
|
||||||
homeChangeApi.text = displayApiName
|
homeChangeApi.text = apiName
|
||||||
homePreviewReloadProvider.isGone = (apiName == noneApi.name)
|
homePreviewReloadProvider.isGone = (apiName == noneApi.name)
|
||||||
homePreviewSearchButton.isGone = (apiName == noneApi.name)
|
homePreviewSearchButton.isGone = (apiName == noneApi.name)
|
||||||
}
|
}
|
||||||
|
|
@ -833,12 +744,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
|
|
||||||
observe(homeViewModel.page) { data ->
|
observe(homeViewModel.page) { data ->
|
||||||
binding.apply {
|
binding.apply {
|
||||||
if (isLayout(TV or EMULATOR)) {
|
|
||||||
val plugin = APIHolder.getApiFromNameNull(homeViewModel.apiName.value)
|
|
||||||
?.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
|
|
||||||
homePreviewSettingsButton.isGone = plugin?.openSettings == null
|
|
||||||
}
|
|
||||||
|
|
||||||
when (data) {
|
when (data) {
|
||||||
is Resource.Success -> {
|
is Resource.Success -> {
|
||||||
val d = data.value
|
val d = data.value
|
||||||
|
|
@ -854,7 +759,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
homeLoadingError.isVisible = false
|
homeLoadingError.isVisible = false
|
||||||
homeMasterRecycler.isVisible = true
|
homeMasterRecycler.isVisible = true
|
||||||
homeLoadingShimmer.stopShimmer()
|
homeLoadingShimmer.stopShimmer()
|
||||||
|
|
||||||
//home_loaded?.isVisible = true
|
//home_loaded?.isVisible = true
|
||||||
if (toggleRandomButton) {
|
if (toggleRandomButton) {
|
||||||
val distinct = d.values
|
val distinct = d.values
|
||||||
|
|
@ -875,16 +779,26 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
homeRandomButtonTv.isGone = true
|
homeRandomButtonTv.isGone = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Open browser directly, without a menu.
|
|
||||||
is Resource.Failure -> {
|
is Resource.Failure -> {
|
||||||
homeLoadingShimmer.stopShimmer()
|
homeLoadingShimmer.stopShimmer()
|
||||||
homeReloadConnectionerror.setOnClickListener(apiChangeClickListener)
|
homeReloadConnectionerror.setOnClickListener(apiChangeClickListener)
|
||||||
homeReloadConnectionOpenInBrowser.setOnClickListener {
|
homeReloadConnectionOpenInBrowser.setOnClickListener { view ->
|
||||||
val currentApi = currentApiName?.let { getApiFromNameNull(it) }
|
val validAPIs = apis//.filter { api -> api.hasMainPage }
|
||||||
?: homeViewModel.apiName.value?.let { getApiFromNameNull(it) }
|
|
||||||
val mainUrl = currentApi?.mainUrl
|
view.popupMenuNoIconsAndNoStringRes(validAPIs.mapIndexed { index, api ->
|
||||||
if (!mainUrl.isNullOrBlank()) {
|
Pair(
|
||||||
context?.openBrowser(mainUrl)
|
index,
|
||||||
|
api.name
|
||||||
|
)
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
val i = Intent(Intent.ACTION_VIEW)
|
||||||
|
i.data = validAPIs[itemId].mainUrl.toUri()
|
||||||
|
startActivity(i)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
logError(e)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -979,29 +893,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
|
||||||
}*/
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun updateTvRailFocus() {
|
|
||||||
if (!isLayout(TV or EMULATOR)) return
|
|
||||||
// home_api_holder is glued to the header row's top by the mirror logic in
|
|
||||||
// the scroll listener above. Only target the provider button while the
|
|
||||||
// holder is actually on screen; once the header scrolls off (y < 0) let
|
|
||||||
// the rail fall back to default focus search so RIGHT enters content rows
|
|
||||||
val holder = binding?.homeApiHolder
|
|
||||||
val target =
|
|
||||||
if (holder != null && holder.isVisible && holder.y >= 0f) R.id.home_change_api
|
|
||||||
else View.NO_ID
|
|
||||||
val rail = activity?.findViewById<View>(R.id.nav_rail_view) ?: return
|
|
||||||
rail.nextFocusRightId = target
|
|
||||||
for (focusView in arrayOf(
|
|
||||||
R.id.navigation_downloads,
|
|
||||||
R.id.navigation_home,
|
|
||||||
R.id.navigation_search,
|
|
||||||
R.id.navigation_library,
|
|
||||||
R.id.navigation_settings,
|
|
||||||
)) {
|
|
||||||
rail.findViewById<View>(focusView)?.nextFocusRightId = target
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun handleTvBackPress(helper: BackPressedCallbackHelper.CallbackHelper) {
|
private fun handleTvBackPress(helper: BackPressedCallbackHelper.CallbackHelper) {
|
||||||
// Only apply custom behavior on TV interface
|
// Only apply custom behavior on TV interface
|
||||||
if (!isLayout(TV)) {
|
if (!isLayout(TV)) {
|
||||||
|
|
|
||||||
|
|
@ -159,7 +159,7 @@ open class ParentItemAdapter(
|
||||||
})
|
})
|
||||||
|
|
||||||
//(recyclerView.adapter as HomeChildItemAdapter).notifyDataSetChanged()
|
//(recyclerView.adapter as HomeChildItemAdapter).notifyDataSetChanged()
|
||||||
if (isLayout(PHONE or EMULATOR)) {
|
if (isLayout(PHONE)) {
|
||||||
homeChildMoreInfo.setOnClickListener {
|
homeChildMoreInfo.setOnClickListener {
|
||||||
moreInfoClickCallback.invoke(item)
|
moreInfoClickCallback.invoke(item)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -310,9 +310,6 @@ class HomeParentItemAdapterPreview(
|
||||||
private val previewViewpager: ViewPager2 =
|
private val previewViewpager: ViewPager2 =
|
||||||
itemView.findViewById(R.id.home_preview_viewpager)
|
itemView.findViewById(R.id.home_preview_viewpager)
|
||||||
|
|
||||||
private val homePreviewShimmer: com.facebook.shimmer.ShimmerFrameLayout? =
|
|
||||||
itemView.findViewById(R.id.home_preview_shimmer)
|
|
||||||
|
|
||||||
private val previewViewpagerText: ViewGroup =
|
private val previewViewpagerText: ViewGroup =
|
||||||
itemView.findViewById(R.id.home_preview_viewpager_text)
|
itemView.findViewById(R.id.home_preview_viewpager_text)
|
||||||
|
|
||||||
|
|
@ -665,8 +662,6 @@ class HomeParentItemAdapterPreview(
|
||||||
|
|
||||||
when (preview) {
|
when (preview) {
|
||||||
is Resource.Success -> {
|
is Resource.Success -> {
|
||||||
homePreviewShimmer?.stopShimmer()
|
|
||||||
homePreviewShimmer?.isGone = true
|
|
||||||
previewAdapter.submitList(preview.value.second)
|
previewAdapter.submitList(preview.value.second)
|
||||||
previewAdapter.hasMoreItems = preview.value.first
|
previewAdapter.hasMoreItems = preview.value.first
|
||||||
/*if (!.setItems(
|
/*if (!.setItems(
|
||||||
|
|
@ -698,16 +693,7 @@ class HomeParentItemAdapterPreview(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
is Resource.Loading -> {
|
|
||||||
previewViewpager.isGone = true
|
|
||||||
previewViewpagerText.isGone = true
|
|
||||||
homePreviewShimmer?.isVisible = true
|
|
||||||
homePreviewShimmer?.startShimmer()
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
homePreviewShimmer?.stopShimmer()
|
|
||||||
homePreviewShimmer?.isGone = true
|
|
||||||
previewAdapter.submitList(listOf())
|
previewAdapter.submitList(listOf())
|
||||||
previewViewpager.setCurrentItem(0, false)
|
previewViewpager.setCurrentItem(0, false)
|
||||||
previewViewpager.isVisible = false
|
previewViewpager.isVisible = false
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,7 @@ class HomeScrollAdapter(
|
||||||
|
|
||||||
when (binding) {
|
when (binding) {
|
||||||
is HomeScrollViewBinding -> {
|
is HomeScrollViewBinding -> {
|
||||||
binding.homeScrollPreview.loadImage(posterUrl, item.posterHeaders)
|
binding.homeScrollPreview.loadImage(posterUrl)
|
||||||
binding.homeScrollPreviewTags.apply {
|
binding.homeScrollPreviewTags.apply {
|
||||||
text = item.tags?.joinToString(" • ") ?: ""
|
text = item.tags?.joinToString(" • ") ?: ""
|
||||||
isGone = item.tags.isNullOrEmpty()
|
isGone = item.tags.isNullOrEmpty()
|
||||||
|
|
@ -79,8 +79,8 @@ class HomeScrollAdapter(
|
||||||
binding.homeScrollPreview.setOnClickListener { view ->
|
binding.homeScrollPreview.setOnClickListener { view ->
|
||||||
callback.invoke(view ?: return@setOnClickListener, position, item)
|
callback.invoke(view ?: return@setOnClickListener, position, item)
|
||||||
}
|
}
|
||||||
binding.homeScrollPreview.loadImage(posterUrl, item.posterHeaders)
|
binding.homeScrollPreview.loadImage(posterUrl)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -133,7 +133,7 @@ class HomeViewModel : ViewModel() {
|
||||||
private var currentShuffledList: List<SearchResponse> = listOf()
|
private var currentShuffledList: List<SearchResponse> = listOf()
|
||||||
|
|
||||||
private fun autoloadRepo(): APIRepository {
|
private fun autoloadRepo(): APIRepository {
|
||||||
return APIRepository(apis.withLock { apis.first { it.hasMainPage } })
|
return APIRepository(synchronized(apis) { apis.first { it.hasMainPage } })
|
||||||
}
|
}
|
||||||
|
|
||||||
private val _availableWatchStatusTypes =
|
private val _availableWatchStatusTypes =
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,6 @@ import androidx.core.view.isVisible
|
||||||
import androidx.fragment.app.activityViewModels
|
import androidx.fragment.app.activityViewModels
|
||||||
import androidx.preference.PreferenceManager
|
import androidx.preference.PreferenceManager
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
|
||||||
import com.google.android.material.tabs.TabLayout
|
import com.google.android.material.tabs.TabLayout
|
||||||
import com.google.android.material.tabs.TabLayoutMediator
|
import com.google.android.material.tabs.TabLayoutMediator
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
import com.lagradost.cloudstream3.APIHolder
|
||||||
|
|
@ -53,13 +52,12 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
|
||||||
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
|
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.getSpanCount
|
import com.lagradost.cloudstream3.utils.UIHelper.getSpanCount
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
const val LIBRARY_FOLDER = "library_folder"
|
const val LIBRARY_FOLDER = "library_folder"
|
||||||
|
|
||||||
|
|
||||||
enum class LibraryOpenerType(@StringRes val stringRes: Int) {
|
enum class LibraryOpenerType(@StringRes val stringRes: Int) {
|
||||||
Default(R.string.action_default),
|
Default(R.string.action_default),
|
||||||
Provider(R.string.none),
|
Provider(R.string.none),
|
||||||
|
|
@ -69,15 +67,13 @@ enum class LibraryOpenerType(@StringRes val stringRes: Int) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Used to store how the user wants to open said poster */
|
/** Used to store how the user wants to open said poster */
|
||||||
@Serializable
|
|
||||||
data class LibraryOpener(
|
data class LibraryOpener(
|
||||||
@JsonProperty("openType") @SerialName("openType") val openType: LibraryOpenerType,
|
val openType: LibraryOpenerType,
|
||||||
@JsonProperty("providerData") @SerialName("providerData") val providerData: ProviderLibraryData?,
|
val providerData: ProviderLibraryData?,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ProviderLibraryData(
|
data class ProviderLibraryData(
|
||||||
@JsonProperty("apiName") @SerialName("apiName") val apiName: String,
|
val apiName: String
|
||||||
)
|
)
|
||||||
|
|
||||||
class LibraryFragment : BaseFragment<FragmentLibraryBinding>(
|
class LibraryFragment : BaseFragment<FragmentLibraryBinding>(
|
||||||
|
|
@ -214,13 +210,14 @@ class LibraryFragment : BaseFragment<FragmentLibraryBinding>(
|
||||||
syncId: SyncIdName,
|
syncId: SyncIdName,
|
||||||
apiName: String? = null,
|
apiName: String? = null,
|
||||||
) {
|
) {
|
||||||
val availableProviders = allProviders.filter {
|
val availableProviders = synchronized(allProviders) {
|
||||||
it.supportedSyncNames.contains(syncId)
|
allProviders.filter {
|
||||||
}.map { it.name } +
|
it.supportedSyncNames.contains(syncId)
|
||||||
// Add the api if it exists
|
}.map { it.name } +
|
||||||
(APIHolder.getApiFromNameNull(apiName)?.let { listOf(it.name) }
|
// Add the api if it exists
|
||||||
?: emptyList())
|
(APIHolder.getApiFromNameNull(apiName)?.let { listOf(it.name) }
|
||||||
|
?: emptyList())
|
||||||
|
}
|
||||||
val baseOptions = listOf(
|
val baseOptions = listOf(
|
||||||
LibraryOpenerType.Default,
|
LibraryOpenerType.Default,
|
||||||
LibraryOpenerType.None,
|
LibraryOpenerType.None,
|
||||||
|
|
@ -572,4 +569,4 @@ class LibraryFragment : BaseFragment<FragmentLibraryBinding>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MenuSearchView(context: Context) : SearchView(context)
|
class MenuSearchView(context: Context) : SearchView(context)
|
||||||
|
|
@ -46,9 +46,7 @@ import androidx.media3.exoplayer.DecoderCounters
|
||||||
import androidx.media3.exoplayer.DecoderReuseEvaluation
|
import androidx.media3.exoplayer.DecoderReuseEvaluation
|
||||||
import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
|
import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
|
||||||
import androidx.media3.exoplayer.DefaultLoadControl
|
import androidx.media3.exoplayer.DefaultLoadControl
|
||||||
import androidx.media3.common.audio.AudioProcessor
|
|
||||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
import androidx.media3.exoplayer.Renderer.STATE_ENABLED
|
import androidx.media3.exoplayer.Renderer.STATE_ENABLED
|
||||||
import androidx.media3.exoplayer.Renderer.STATE_STARTED
|
import androidx.media3.exoplayer.Renderer.STATE_STARTED
|
||||||
|
|
@ -98,7 +96,7 @@ import com.lagradost.cloudstream3.ui.subtitles.SaveCaptionStyle
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.applyStyle
|
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.applyStyle
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.isUsingMobileData
|
import com.lagradost.cloudstream3.utils.AppContextUtils.isUsingMobileData
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
||||||
import com.lagradost.cloudstream3.utils.CLEARKEY_DRM_UUID
|
import com.lagradost.cloudstream3.utils.CLEARKEY_UUID
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
|
import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
|
import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
|
||||||
|
|
@ -106,11 +104,10 @@ import com.lagradost.cloudstream3.utils.DrmExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLink
|
import com.lagradost.cloudstream3.utils.ExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLinkPlayList
|
import com.lagradost.cloudstream3.utils.ExtractorLinkPlayList
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
||||||
import com.lagradost.cloudstream3.utils.PLAYREADY_DRM_UUID
|
import com.lagradost.cloudstream3.utils.PLAYREADY_UUID
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
|
||||||
import com.lagradost.cloudstream3.utils.WIDEVINE_DRM_UUID
|
import com.lagradost.cloudstream3.utils.WIDEVINE_UUID
|
||||||
import com.lagradost.cloudstream3.utils.videoskip.VideoSkipStamp
|
import com.lagradost.cloudstream3.utils.videoskip.VideoSkipStamp
|
||||||
import com.lagradost.cloudstream4.AppSettings
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
import org.chromium.net.CronetEngine
|
import org.chromium.net.CronetEngine
|
||||||
|
|
@ -121,7 +118,6 @@ import java.util.concurrent.Executors
|
||||||
import javax.net.ssl.HttpsURLConnection
|
import javax.net.ssl.HttpsURLConnection
|
||||||
import javax.net.ssl.SSLContext
|
import javax.net.ssl.SSLContext
|
||||||
import javax.net.ssl.SSLSession
|
import javax.net.ssl.SSLSession
|
||||||
import kotlin.uuid.toJavaUuid
|
|
||||||
|
|
||||||
const val TAG = "CS3ExoPlayer"
|
const val TAG = "CS3ExoPlayer"
|
||||||
const val PREFERRED_AUDIO_LANGUAGE_KEY = "preferred_audio_language"
|
const val PREFERRED_AUDIO_LANGUAGE_KEY = "preferred_audio_language"
|
||||||
|
|
@ -164,14 +160,6 @@ class CS3IPlayer : IPlayer {
|
||||||
private var ignoreSSL: Boolean = true
|
private var ignoreSSL: Boolean = true
|
||||||
private var playBackSpeed: Float = 1.0f
|
private var playBackSpeed: Float = 1.0f
|
||||||
|
|
||||||
/**
|
|
||||||
* Shared compressor instance — only created when the setting is enabled.
|
|
||||||
* When disabled, this stays null and the audio pipeline is completely
|
|
||||||
* unmodified (no custom AudioProcessor, no custom AudioSink at all).
|
|
||||||
*/
|
|
||||||
var compressor: DynamicRangeCompressor? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
private var lastMuteVolume: Float = 1.0f
|
private var lastMuteVolume: Float = 1.0f
|
||||||
|
|
||||||
private var currentLink: ExtractorLink? = null
|
private var currentLink: ExtractorLink? = null
|
||||||
|
|
@ -730,7 +718,7 @@ class CS3IPlayer : IPlayer {
|
||||||
**/
|
**/
|
||||||
var preferredAudioTrackLanguage: String? = null
|
var preferredAudioTrackLanguage: String? = null
|
||||||
get() {
|
get() {
|
||||||
return field ?: getKey<String>(
|
return field ?: getKey(
|
||||||
"$currentAccount/$PREFERRED_AUDIO_LANGUAGE_KEY",
|
"$currentAccount/$PREFERRED_AUDIO_LANGUAGE_KEY",
|
||||||
field
|
field
|
||||||
)?.also {
|
)?.also {
|
||||||
|
|
@ -1120,17 +1108,8 @@ class CS3IPlayer : IPlayer {
|
||||||
else -> isLayout(PHONE or EMULATOR) to false
|
else -> isLayout(PHONE or EMULATOR) to false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only create the compressor when the setting is actually enabled.
|
|
||||||
// When it's off, `compressor` stays null and nothing about the audio
|
|
||||||
// pipeline is touched — same behaviour as before this feature existed.
|
|
||||||
val isCompressorEnabled = settingsManager.getBoolean(
|
|
||||||
context.getString(R.string.compressor_enabled_key),
|
|
||||||
false
|
|
||||||
)
|
|
||||||
compressor = if (isCompressorEnabled) DynamicRangeCompressor().apply { restoreSavedSettings() } else null
|
|
||||||
|
|
||||||
val factory = if (isSoftwareDecodingEnabled) {
|
val factory = if (isSoftwareDecodingEnabled) {
|
||||||
FixedNextRenderersFactory(context, compressor).apply {
|
FixedNextRenderersFactory(context).apply {
|
||||||
setEnableDecoderFallback(true)
|
setEnableDecoderFallback(true)
|
||||||
setExtensionRendererMode(
|
setExtensionRendererMode(
|
||||||
if (isSoftwareDecodingPreferred)
|
if (isSoftwareDecodingPreferred)
|
||||||
|
|
@ -1140,24 +1119,8 @@ class CS3IPlayer : IPlayer {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val activeCompressor = compressor
|
// no nextlib = EXTENSION_RENDERER_MODE_OFF
|
||||||
if (activeCompressor == null) {
|
DefaultRenderersFactory(context)
|
||||||
// no nextlib = EXTENSION_RENDERER_MODE_OFF, no compressor = fully default sink
|
|
||||||
DefaultRenderersFactory(context)
|
|
||||||
} else {
|
|
||||||
object : DefaultRenderersFactory(context) {
|
|
||||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
|
||||||
override fun buildAudioSink(
|
|
||||||
ctx: Context,
|
|
||||||
enableFloatOutput: Boolean,
|
|
||||||
enableAudioTrackPlaybackParams: Boolean
|
|
||||||
) = DefaultAudioSink.Builder(ctx)
|
|
||||||
.setEnableFloatOutput(enableFloatOutput)
|
|
||||||
.setEnableAudioOutputPlaybackParameters(enableAudioTrackPlaybackParams)
|
|
||||||
.setAudioProcessors(arrayOf<AudioProcessor>(activeCompressor))
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val style = CustomDecoder.style
|
val style = CustomDecoder.style
|
||||||
|
|
@ -1315,7 +1278,7 @@ class CS3IPlayer : IPlayer {
|
||||||
|
|
||||||
item.drm?.let { drm ->
|
item.drm?.let { drm ->
|
||||||
when (drm.uuid) {
|
when (drm.uuid) {
|
||||||
CLEARKEY_DRM_UUID.toJavaUuid() -> {
|
CLEARKEY_UUID -> {
|
||||||
// Use headers from DrmMetadata for media requests
|
// Use headers from DrmMetadata for media requests
|
||||||
val client = dataSourceFactory
|
val client = dataSourceFactory
|
||||||
?: throw IllegalArgumentException("Must supply onlineSource")
|
?: throw IllegalArgumentException("Must supply onlineSource")
|
||||||
|
|
@ -1336,8 +1299,8 @@ class CS3IPlayer : IPlayer {
|
||||||
.createMediaSource(item.mediaItem)
|
.createMediaSource(item.mediaItem)
|
||||||
}
|
}
|
||||||
|
|
||||||
WIDEVINE_DRM_UUID.toJavaUuid(),
|
WIDEVINE_UUID,
|
||||||
PLAYREADY_DRM_UUID.toJavaUuid() -> {
|
PLAYREADY_UUID -> {
|
||||||
// Use headers from DrmMetadata for media requests
|
// Use headers from DrmMetadata for media requests
|
||||||
val client = dataSourceFactory
|
val client = dataSourceFactory
|
||||||
?: throw IllegalArgumentException("Must supply onlineSource")
|
?: throw IllegalArgumentException("Must supply onlineSource")
|
||||||
|
|
@ -1425,17 +1388,10 @@ class CS3IPlayer : IPlayer {
|
||||||
context.getString(if (context.isUsingMobileData()) R.string.quality_pref_mobile_data_key else R.string.quality_pref_key),
|
context.getString(if (context.isUsingMobileData()) R.string.quality_pref_mobile_data_key else R.string.quality_pref_key),
|
||||||
Int.MAX_VALUE
|
Int.MAX_VALUE
|
||||||
)
|
)
|
||||||
val settings = AppSettings(context)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
hasUsedFirstRender = false
|
hasUsedFirstRender = false
|
||||||
|
|
||||||
val playWhenReady = if (settings.player.startPaused.get()) {
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
isPlaying // this keep the current state of the player
|
|
||||||
}
|
|
||||||
|
|
||||||
// ye this has to be a val for whatever reason
|
// ye this has to be a val for whatever reason
|
||||||
// this makes no sense
|
// this makes no sense
|
||||||
exoPlayer = buildExoPlayer(
|
exoPlayer = buildExoPlayer(
|
||||||
|
|
@ -1447,7 +1403,7 @@ class CS3IPlayer : IPlayer {
|
||||||
playBackSpeed,
|
playBackSpeed,
|
||||||
cacheSize = cacheSize,
|
cacheSize = cacheSize,
|
||||||
videoBufferMs = videoBufferMs,
|
videoBufferMs = videoBufferMs,
|
||||||
playWhenReady = playWhenReady,
|
playWhenReady = isPlaying, // this keep the current state of the player
|
||||||
subtitleOffset = currentSubtitleOffset,
|
subtitleOffset = currentSubtitleOffset,
|
||||||
maxVideoHeight = maxVideoHeight,
|
maxVideoHeight = maxVideoHeight,
|
||||||
audioSources = audioSources,
|
audioSources = audioSources,
|
||||||
|
|
@ -1958,7 +1914,7 @@ class CS3IPlayer : IPlayer {
|
||||||
drm = DrmMetadata(
|
drm = DrmMetadata(
|
||||||
kid = link.kid,
|
kid = link.kid,
|
||||||
key = link.key,
|
key = link.key,
|
||||||
uuid = link.uuid.toJavaUuid(),
|
uuid = link.uuid,
|
||||||
kty = link.kty,
|
kty = link.kty,
|
||||||
licenseUrl = link.licenseUrl,
|
licenseUrl = link.licenseUrl,
|
||||||
keyRequestParameters = link.keyRequestParameters,
|
keyRequestParameters = link.keyRequestParameters,
|
||||||
|
|
|
||||||
|
|
@ -58,23 +58,9 @@ class DownloadedPlayerActivity : AppCompatActivity() {
|
||||||
enableEdgeToEdgeCompat()
|
enableEdgeToEdgeCompat()
|
||||||
setContentView(R.layout.empty_layout)
|
setContentView(R.layout.empty_layout)
|
||||||
Log.i(TAG, "onCreate")
|
Log.i(TAG, "onCreate")
|
||||||
handleIntent(intent)
|
|
||||||
|
|
||||||
/**
|
handleIntent(intent)
|
||||||
* Use moveTaskToBack instead of finish() so there is always exactly one task
|
attachBackPressedCallback("DownloadedPlayerActivity") { finish() }
|
||||||
* entry in recents, always reflecting the current file.
|
|
||||||
*
|
|
||||||
* finish() destroys the Activity but may leave the task in recents. Each new file
|
|
||||||
* open can create a new task entry, so recents accumulates stale entries for old
|
|
||||||
* files. The user then taps a stale entry and gets the wrong file.
|
|
||||||
*
|
|
||||||
* moveTaskToBack keeps the Activity alive in the background. There is only ever
|
|
||||||
* one task entry in recents. New files opened from the file manager arrive via
|
|
||||||
* onNewIntent on the live instance, updating the player immediately. The single
|
|
||||||
* recents entry always reflects the current state, ensuring we load the
|
|
||||||
* correct file.
|
|
||||||
*/
|
|
||||||
attachBackPressedCallback("DownloadedPlayerActivity") { moveTaskToBack(true) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleIntent(intent: Intent) {
|
private fun handleIntent(intent: Intent) {
|
||||||
|
|
@ -97,11 +83,11 @@ class DownloadedPlayerActivity : AppCompatActivity() {
|
||||||
url != null -> playLink(this, url)
|
url != null -> playLink(this, url)
|
||||||
data != null -> playUri(this, data)
|
data != null -> playUri(this, data)
|
||||||
extraText != null -> playLink(this, extraText)
|
extraText != null -> playLink(this, extraText)
|
||||||
else -> finishAndRemoveTask()
|
else -> { finish(); return }
|
||||||
}
|
}
|
||||||
} else if (data?.scheme == "content") {
|
} else if (data?.scheme == "content") {
|
||||||
playUri(this, data)
|
playUri(this, data)
|
||||||
} else finishAndRemoveTask()
|
} else finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
|
|
|
||||||
|
|
@ -1,266 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.player
|
|
||||||
|
|
||||||
import androidx.annotation.OptIn
|
|
||||||
import androidx.media3.common.C
|
|
||||||
import androidx.media3.common.audio.AudioProcessor
|
|
||||||
import androidx.media3.common.audio.AudioProcessor.AudioFormat
|
|
||||||
import androidx.media3.common.util.UnstableApi
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.ByteOrder
|
|
||||||
import kotlin.math.exp
|
|
||||||
import kotlin.math.ln
|
|
||||||
import kotlin.math.pow
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A dynamic range compressor for the audio player.
|
|
||||||
*
|
|
||||||
* ## What it does
|
|
||||||
* A dynamic range compressor automatically turns down loud sounds and turns up
|
|
||||||
* quiet ones, narrowing the gap between the loudest and quietest moments.
|
|
||||||
* This is useful for watching movies or TV shows where action/explosion scenes
|
|
||||||
* are very loud but dialogue scenes are very quiet — the compressor brings
|
|
||||||
* everything to a more comfortable, even volume.
|
|
||||||
*
|
|
||||||
* ## Algorithm
|
|
||||||
* Implements a standard single-band feed-forward peak compressor using a
|
|
||||||
* 1-pole IIR envelope follower. This is the same algorithm used in most
|
|
||||||
* audio software (Audacity, VLC, etc.) and is well-established DSP. It is
|
|
||||||
* NOT a port or derivative of any specific implementation — the math is
|
|
||||||
* standard and covered extensively in audio engineering literature
|
|
||||||
* (e.g. Zölzer "Digital Audio Signal Processing").
|
|
||||||
*
|
|
||||||
* Uses a single shared envelope across all channels so left and right always
|
|
||||||
* receive identical gain — independent per-channel envelopes would destroy
|
|
||||||
* the stereo image.
|
|
||||||
*
|
|
||||||
* Handles both PCM_16BIT and PCM_FLOAT (both are used by ExoPlayer depending
|
|
||||||
* on the source and device). Always stays "active" in the pipeline so that
|
|
||||||
* enable/disable works instantly without reloading the player — when disabled,
|
|
||||||
* samples are copied unchanged (passthrough).
|
|
||||||
*/
|
|
||||||
internal const val COMPRESSOR_ENABLED_KEY = "player_compressor_enabled"
|
|
||||||
internal const val COMPRESSOR_THRESHOLD_KEY = "player_compressor_threshold"
|
|
||||||
internal const val COMPRESSOR_RATIO_KEY = "player_compressor_ratio"
|
|
||||||
internal const val COMPRESSOR_ATTACK_KEY = "player_compressor_attack"
|
|
||||||
internal const val COMPRESSOR_RELEASE_KEY = "player_compressor_release"
|
|
||||||
internal const val COMPRESSOR_MAKEUP_KEY = "player_compressor_makeup"
|
|
||||||
|
|
||||||
@OptIn(UnstableApi::class)
|
|
||||||
class DynamicRangeCompressor : AudioProcessor {
|
|
||||||
|
|
||||||
@Volatile var enabled: Boolean = false
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The level (in dB) above which compression kicks in. Signals quieter than
|
|
||||||
* this pass through unchanged; louder signals get compressed.
|
|
||||||
* Lower = compresses more content (including quieter sounds like dialogue).
|
|
||||||
* -24 dB is a good starting point for movies: it catches action peaks
|
|
||||||
* while leaving quiet dialogue mostly untouched before makeup gain.
|
|
||||||
*/
|
|
||||||
@Volatile var threshold: Float = -24f // dB, range -30..0
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How aggressively to compress sounds that exceed the threshold.
|
|
||||||
* A ratio of 8:1 means an 8 dB increase above the threshold becomes only
|
|
||||||
* 1 dB in the output. Higher = more "squashed" dynamic range.
|
|
||||||
* Below ~2 is barely noticeable; above ~10 sounds very processed/radio-like.
|
|
||||||
*/
|
|
||||||
@Volatile var ratio: Float = 8f // n:1, range 1..20
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How quickly (in ms) the compressor clamps down when a loud sound starts.
|
|
||||||
* Too low (< 1 ms): no transient punch, sounds dull.
|
|
||||||
* Too high (> 50 ms): loud transients slip through before gain reduces.
|
|
||||||
* 5 ms preserves punch while still catching most action scene peaks.
|
|
||||||
*/
|
|
||||||
@Volatile var attackMs: Float = 5f // ms, range 1..400
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How quickly (in ms) the compressor lets go after a loud sound ends.
|
|
||||||
* Too low (< 50 ms): audible "pumping" — volume visibly breathes up/down.
|
|
||||||
* Too high (> 800 ms): gain stays low too long, quieter sounds after
|
|
||||||
* an action scene stay suppressed for a noticeable time.
|
|
||||||
* 400 ms is slow enough to be transparent on most movie content.
|
|
||||||
*/
|
|
||||||
@Volatile var releaseMs: Float = 400f // ms, range 2..800
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Output gain (in dB) applied after compression.
|
|
||||||
* Compression reduces overall loudness so makeup gain brings it back up.
|
|
||||||
* +12 dB compensates for the typical reduction at a 8:1 ratio with a
|
|
||||||
* -24 dB threshold, and also lifts quiet dialogue to a more audible level.
|
|
||||||
* Too high risks clipping on uncompressed peaks below the threshold.
|
|
||||||
*/
|
|
||||||
@Volatile var makeupGain: Float = 12f // dB, range 0..24
|
|
||||||
|
|
||||||
fun restoreSavedSettings() {
|
|
||||||
enabled = getKey<Boolean>(COMPRESSOR_ENABLED_KEY) ?: false
|
|
||||||
threshold = getKey<Float>(COMPRESSOR_THRESHOLD_KEY) ?: -24f
|
|
||||||
ratio = getKey<Float>(COMPRESSOR_RATIO_KEY) ?: 8f
|
|
||||||
attackMs = getKey<Float>(COMPRESSOR_ATTACK_KEY) ?: 5f
|
|
||||||
releaseMs = getKey<Float>(COMPRESSOR_RELEASE_KEY) ?: 400f
|
|
||||||
makeupGain = getKey<Float>(COMPRESSOR_MAKEUP_KEY) ?: 12f
|
|
||||||
}
|
|
||||||
|
|
||||||
private var format = AudioFormat.NOT_SET
|
|
||||||
private var isFloat = false
|
|
||||||
private var sampleRate = 44100
|
|
||||||
private var channelCount = 2
|
|
||||||
|
|
||||||
// Single shared envelope across all channels — keeps L/R gain identical
|
|
||||||
// so stereo image is preserved and no crackling from gain mismatch.
|
|
||||||
private var envelope = 0f
|
|
||||||
|
|
||||||
private var attackCoeff = 0f
|
|
||||||
private var releaseCoeff = 0f
|
|
||||||
private var lastAttackMs = -1f
|
|
||||||
private var lastReleaseMs = -1f
|
|
||||||
private var lastSampleRate = -1
|
|
||||||
|
|
||||||
private var outputBuffer: ByteBuffer = AudioProcessor.EMPTY_BUFFER
|
|
||||||
private var inputEnded = false
|
|
||||||
|
|
||||||
// ── AudioProcessor ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
override fun configure(inputAudioFormat: AudioFormat): AudioFormat {
|
|
||||||
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT &&
|
|
||||||
inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {
|
|
||||||
return inputAudioFormat // pass unsupported formats through unchanged
|
|
||||||
}
|
|
||||||
format = inputAudioFormat
|
|
||||||
isFloat = inputAudioFormat.encoding == C.ENCODING_PCM_FLOAT
|
|
||||||
sampleRate = inputAudioFormat.sampleRate
|
|
||||||
channelCount = inputAudioFormat.channelCount
|
|
||||||
envelope = 0f
|
|
||||||
return inputAudioFormat
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always active when format is set — toggling isActive() mid-stream has no
|
|
||||||
// effect in media3 (only checked at configure() time). We do passthrough
|
|
||||||
// in queueInput() instead so enable/disable works immediately.
|
|
||||||
override fun isActive(): Boolean =
|
|
||||||
format != AudioFormat.NOT_SET &&
|
|
||||||
(format.encoding == C.ENCODING_PCM_16BIT || format.encoding == C.ENCODING_PCM_FLOAT)
|
|
||||||
|
|
||||||
override fun queueInput(inputBuffer: ByteBuffer) {
|
|
||||||
if (!inputBuffer.hasRemaining()) return
|
|
||||||
val remaining = inputBuffer.remaining()
|
|
||||||
val out = replaceOutputBuffer(remaining)
|
|
||||||
if (!enabled) { out.put(inputBuffer); out.flip(); return }
|
|
||||||
updateCoefficients()
|
|
||||||
val makeupLinear = dbToLinear(makeupGain)
|
|
||||||
val threshLinear = dbToLinear(threshold)
|
|
||||||
val bytesPerSample = if (isFloat) 4 else 2
|
|
||||||
val frameCount = remaining / (channelCount * bytesPerSample)
|
|
||||||
if (isFloat) processFloat(inputBuffer, out, frameCount, threshLinear, makeupLinear)
|
|
||||||
else processShort(inputBuffer, out, frameCount, threshLinear, makeupLinear)
|
|
||||||
out.flip()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Processes PCM_FLOAT frames. Two-pass: peak detection then gain application. */
|
|
||||||
private fun processFloat(
|
|
||||||
input: ByteBuffer, out: ByteBuffer,
|
|
||||||
frameCount: Int, threshLinear: Float, makeupLinear: Float
|
|
||||||
) {
|
|
||||||
repeat(frameCount) {
|
|
||||||
val frameStart = input.position()
|
|
||||||
var peak = 0f
|
|
||||||
repeat(channelCount) { val s = input.getFloat(); val a = if (s < 0f) -s else s; if (a > peak) peak = a }
|
|
||||||
advanceEnvelope(peak)
|
|
||||||
val gain = computeGain(threshLinear) * makeupLinear
|
|
||||||
input.position(frameStart)
|
|
||||||
repeat(channelCount) { out.putFloat(input.getFloat() * gain) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Processes PCM_16BIT frames. Two-pass: peak detection then gain application. */
|
|
||||||
private fun processShort(
|
|
||||||
input: ByteBuffer, out: ByteBuffer,
|
|
||||||
frameCount: Int, threshLinear: Float, makeupLinear: Float
|
|
||||||
) {
|
|
||||||
repeat(frameCount) {
|
|
||||||
val frameStart = input.position()
|
|
||||||
var peak = 0f
|
|
||||||
repeat(channelCount) { val s = input.getShort() / 32768f; val a = if (s < 0f) -s else s; if (a > peak) peak = a }
|
|
||||||
advanceEnvelope(peak)
|
|
||||||
val gain = computeGain(threshLinear) * makeupLinear
|
|
||||||
input.position(frameStart)
|
|
||||||
repeat(channelCount) {
|
|
||||||
val s = input.getShort() / 32768f
|
|
||||||
out.putShort((s * gain).coerceIn(-1f, 1f).let { (it * 32768f).toInt().toShort() })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun advanceEnvelope(peak: Float) {
|
|
||||||
val coeff = if (peak > envelope) attackCoeff else releaseCoeff
|
|
||||||
envelope = peak + coeff * (envelope - peak)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun queueEndOfStream() { inputEnded = true }
|
|
||||||
|
|
||||||
override fun getOutput(): ByteBuffer {
|
|
||||||
val out = outputBuffer
|
|
||||||
outputBuffer = AudioProcessor.EMPTY_BUFFER
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun isEnded(): Boolean =
|
|
||||||
inputEnded && outputBuffer === AudioProcessor.EMPTY_BUFFER
|
|
||||||
|
|
||||||
// AudioProcessor.flush() (no-arg) is deprecated upstream in favor of a
|
|
||||||
// seek-aware overload, but this interface implementation still only exposes
|
|
||||||
// the no-arg version to override, so this suppresses that specific warning
|
|
||||||
// without adding @Deprecated (which would cascade to our own reset() below,
|
|
||||||
// since it calls flush() internally).
|
|
||||||
@Suppress("OVERRIDE_DEPRECATION")
|
|
||||||
override fun flush() {
|
|
||||||
// Called on every seek. Reset envelope so there's no gain burst
|
|
||||||
// from stale state — which is what caused crackling after skipping.
|
|
||||||
envelope = 0f
|
|
||||||
outputBuffer = AudioProcessor.EMPTY_BUFFER
|
|
||||||
inputEnded = false
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun reset() {
|
|
||||||
flush()
|
|
||||||
format = AudioFormat.NOT_SET
|
|
||||||
isFloat = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
private fun computeGain(threshLinear: Float): Float {
|
|
||||||
return if (envelope <= threshLinear) {
|
|
||||||
1f
|
|
||||||
} else {
|
|
||||||
val overDb = linearToDb(envelope) - threshold
|
|
||||||
dbToLinear(-(overDb * (1f - 1f / ratio)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun replaceOutputBuffer(size: Int): ByteBuffer {
|
|
||||||
if (outputBuffer.capacity() < size) {
|
|
||||||
outputBuffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
|
|
||||||
} else {
|
|
||||||
outputBuffer.clear()
|
|
||||||
}
|
|
||||||
return outputBuffer
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun updateCoefficients() {
|
|
||||||
if (attackMs == lastAttackMs &&
|
|
||||||
releaseMs == lastReleaseMs &&
|
|
||||||
sampleRate == lastSampleRate) return
|
|
||||||
lastAttackMs = attackMs
|
|
||||||
lastReleaseMs = releaseMs
|
|
||||||
lastSampleRate = sampleRate
|
|
||||||
attackCoeff = exp(-1.0 / (sampleRate * attackMs / 1000.0)).toFloat()
|
|
||||||
releaseCoeff = exp(-1.0 / (sampleRate * releaseMs / 1000.0)).toFloat()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dbToLinear(db: Float): Float = 10f.pow(db / 20f)
|
|
||||||
private fun linearToDb(linear: Float): Float =
|
|
||||||
if (linear <= 0f) -120f else (20.0 * ln(linear.toDouble()) / ln(10.0)).toFloat()
|
|
||||||
}
|
|
||||||
|
|
@ -2,21 +2,14 @@ package com.lagradost.cloudstream3.ui.player
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import androidx.annotation.OptIn
|
|
||||||
import androidx.media3.common.audio.AudioProcessor
|
|
||||||
import androidx.media3.common.util.UnstableApi
|
import androidx.media3.common.util.UnstableApi
|
||||||
import androidx.media3.exoplayer.Renderer
|
import androidx.media3.exoplayer.Renderer
|
||||||
import androidx.media3.exoplayer.audio.AudioSink
|
|
||||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
|
||||||
import androidx.media3.exoplayer.text.TextOutput
|
import androidx.media3.exoplayer.text.TextOutput
|
||||||
import androidx.media3.exoplayer.text.TextRenderer
|
import androidx.media3.exoplayer.text.TextRenderer
|
||||||
import io.github.anilbeesetti.nextlib.media3ext.ffdecoder.NextRenderersFactory
|
import io.github.anilbeesetti.nextlib.media3ext.ffdecoder.NextRenderersFactory
|
||||||
|
|
||||||
@UnstableApi
|
@UnstableApi
|
||||||
class FixedNextRenderersFactory(
|
class FixedNextRenderersFactory(context: Context) : NextRenderersFactory(context) {
|
||||||
context: Context,
|
|
||||||
private val compressor: DynamicRangeCompressor? = null,
|
|
||||||
) : NextRenderersFactory(context) {
|
|
||||||
/** Somehow the nextlib authors decided that we need a text renderer that causes
|
/** Somehow the nextlib authors decided that we need a text renderer that causes
|
||||||
* "ERROR_CODE_FAILED_RUNTIME_CHECK".
|
* "ERROR_CODE_FAILED_RUNTIME_CHECK".
|
||||||
*
|
*
|
||||||
|
|
@ -32,26 +25,4 @@ class FixedNextRenderersFactory(
|
||||||
) {
|
) {
|
||||||
out.add(TextRenderer(output, outputLooper))
|
out.add(TextRenderer(output, outputLooper))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Only builds a custom [DefaultAudioSink] when a compressor is actually supplied.
|
|
||||||
* When [compressor] is null (the setting is off, or unsupported on this device) we
|
|
||||||
* fall through to the completely unmodified default sink from the parent factory,
|
|
||||||
* so playback behaves exactly as it did before this feature existed.
|
|
||||||
*/
|
|
||||||
@OptIn(UnstableApi::class)
|
|
||||||
override fun buildAudioSink(
|
|
||||||
context: Context,
|
|
||||||
enableFloatOutput: Boolean,
|
|
||||||
enableAudioTrackPlaybackParams: Boolean
|
|
||||||
): AudioSink? {
|
|
||||||
val activeCompressor = compressor
|
|
||||||
?: return super.buildAudioSink(context, enableFloatOutput, enableAudioTrackPlaybackParams)
|
|
||||||
|
|
||||||
return DefaultAudioSink.Builder(context)
|
|
||||||
.setEnableFloatOutput(enableFloatOutput)
|
|
||||||
.setEnableAudioOutputPlaybackParameters(enableAudioTrackPlaybackParams)
|
|
||||||
.setAudioProcessors(arrayOf<AudioProcessor>(activeCompressor))
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -4,7 +4,6 @@ import android.animation.ObjectAnimator
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
import android.app.Dialog
|
import android.app.Dialog
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.DialogInterface
|
import android.content.DialogInterface
|
||||||
import android.content.pm.ActivityInfo
|
import android.content.pm.ActivityInfo
|
||||||
|
|
@ -103,12 +102,12 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
private var hideControlsNames = false
|
private var hideControlsNames = false
|
||||||
protected var subtitleDelay
|
protected var subtitleDelay
|
||||||
set(value) = try {
|
set(value) = try {
|
||||||
player.setSubtitleOffset(value)
|
player.setSubtitleOffset(-value)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
logError(e)
|
logError(e)
|
||||||
}
|
}
|
||||||
get() = try {
|
get() = try {
|
||||||
player.getSubtitleOffset()
|
-player.getSubtitleOffset()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
logError(e)
|
logError(e)
|
||||||
0L
|
0L
|
||||||
|
|
@ -158,15 +157,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
autoHide()
|
autoHide()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
protected var selectCompressorDialog: Dialog? = null
|
|
||||||
set(value) {
|
|
||||||
val prevField = field
|
|
||||||
field = value
|
|
||||||
if (value == null && prevField != null) {
|
|
||||||
autoHide()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
protected var playBackCompressorEnabled = false
|
|
||||||
|
|
||||||
/** Checks if any top level dialog is open and showing */
|
/** Checks if any top level dialog is open and showing */
|
||||||
fun isDialogOpen() =
|
fun isDialogOpen() =
|
||||||
|
|
@ -174,7 +164,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
|| selectTrackDialog?.isShowing == true
|
|| selectTrackDialog?.isShowing == true
|
||||||
|| selectSpeedDialog?.isShowing == true
|
|| selectSpeedDialog?.isShowing == true
|
||||||
|| selectSubtitlesDialog?.isShowing == true
|
|| selectSubtitlesDialog?.isShowing == true
|
||||||
|| selectCompressorDialog?.isShowing == true
|
|
||||||
|| isShowingEpisodeOverlay
|
|| isShowingEpisodeOverlay
|
||||||
|
|
||||||
private fun scheduleMetadataVisibility() {
|
private fun scheduleMetadataVisibility() {
|
||||||
|
|
@ -278,72 +267,84 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
// The lib uses Invisible instead of Gone for no reason
|
// The lib uses Invisible instead of Gone for no reason
|
||||||
binding.previewFrameLayout.height - binding.bottomPlayerBar.height
|
binding.previewFrameLayout.height - binding.bottomPlayerBar.height
|
||||||
) else -sStyle.elevation.toPx
|
) else -sStyle.elevation.toPx
|
||||||
|
ObjectAnimator.ofFloat(sView, "translationY", move.toFloat()).apply {
|
||||||
sView.animateY(move.toFloat())
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun View.animateY(value: Float) {
|
|
||||||
ObjectAnimator.ofFloat(this, "translationY", value).apply {
|
|
||||||
duration = 200
|
|
||||||
start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun View.animateX(value: Float) {
|
|
||||||
ObjectAnimator.ofFloat(this, "translationX", value).apply {
|
|
||||||
duration = 200
|
|
||||||
start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected fun animateLayoutChanges() {
|
protected fun animateLayoutChanges() {
|
||||||
|
if (isLayout(PHONE)) { // isEnabled also disables the onKeyDown
|
||||||
|
playerBinding?.exoProgress?.isEnabled = isShowing // Prevent accidental clicks/drags
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isShowing) {
|
||||||
|
updateUIVisibility()
|
||||||
|
} else {
|
||||||
|
toggleEpisodesOverlay(false)
|
||||||
|
playerBinding?.playerHolder?.postDelayed({ updateUIVisibility() }, 200)
|
||||||
|
}
|
||||||
|
|
||||||
|
val titleMove = if (isShowing) 0f else -50.toPx.toFloat()
|
||||||
|
playerBinding?.playerVideoTitleHolder?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationY", titleMove).apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
playerBinding?.playerVideoTitleRez?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationY", titleMove).apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
playerBinding?.playerVideoInfo?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationY", titleMove).apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
playerBinding?.playerMetadataScrim?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationY", 1f).apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val playerBarMove = if (isShowing) 0f else 50.toPx.toFloat()
|
||||||
|
playerBinding?.bottomPlayerBar?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationY", playerBarMove).apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isLayout(PHONE)) {
|
||||||
|
playerBinding?.playerEpisodesButton?.let {
|
||||||
|
ObjectAnimator.ofFloat(it, "translationX", if (isShowing) 0f else 50.toPx.toFloat())
|
||||||
|
.apply {
|
||||||
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val fadeTo = if (isShowing) 1f else 0f
|
||||||
|
val fadeAnimation = AlphaAnimation(1f - fadeTo, fadeTo)
|
||||||
|
|
||||||
|
fadeAnimation.duration = 100
|
||||||
|
fadeAnimation.fillAfter = true
|
||||||
|
|
||||||
|
animateLayoutChangesForSubtitles()
|
||||||
|
|
||||||
|
val playerSourceMove = if (isShowing) 0f else -50.toPx.toFloat()
|
||||||
|
|
||||||
playerBinding?.apply {
|
playerBinding?.apply {
|
||||||
|
playerOpenSource.let {
|
||||||
if (isLayout(PHONE)) { // isEnabled also disables the onKeyDown
|
ObjectAnimator.ofFloat(it, "translationY", playerSourceMove).apply {
|
||||||
exoProgress.isEnabled = isShowing // Prevent accidental clicks/drags
|
duration = 200
|
||||||
|
start()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isShowing) {
|
|
||||||
updateUIVisibility()
|
|
||||||
} else {
|
|
||||||
toggleEpisodesOverlay(false)
|
|
||||||
playerHolder.postDelayed({ updateUIVisibility() }, 200)
|
|
||||||
}
|
|
||||||
|
|
||||||
val titleMove = if (isShowing) 0f else -50.toPx.toFloat()
|
|
||||||
|
|
||||||
listOfNotNull(
|
|
||||||
playerVideoTitleHolder,
|
|
||||||
playerVideoTitleRez,
|
|
||||||
playerVideoInfo,
|
|
||||||
playerGoBackHolder,
|
|
||||||
playerVideoClock,
|
|
||||||
).forEach {
|
|
||||||
it.animateY(titleMove)
|
|
||||||
}
|
|
||||||
|
|
||||||
playerMetadataScrim.animateY(1f)
|
|
||||||
|
|
||||||
val playerBarMove = if (isShowing) 0f else 50.toPx.toFloat()
|
|
||||||
bottomPlayerBar.animateY(playerBarMove)
|
|
||||||
|
|
||||||
if (isLayout(PHONE)) {
|
|
||||||
playerEpisodesButton.animateX(if (isShowing) 0f else 50.toPx.toFloat())
|
|
||||||
}
|
|
||||||
|
|
||||||
val fadeTo = if (isShowing) 1f else 0f
|
|
||||||
val fadeAnimation = AlphaAnimation(1f - fadeTo, fadeTo)
|
|
||||||
|
|
||||||
fadeAnimation.duration = 100
|
|
||||||
fadeAnimation.fillAfter = true
|
|
||||||
|
|
||||||
animateLayoutChangesForSubtitles()
|
|
||||||
|
|
||||||
val playerSourceMove = if (isShowing) 0f else -50.toPx.toFloat()
|
|
||||||
|
|
||||||
playerOpenSource.animateY(playerSourceMove)
|
|
||||||
|
|
||||||
if (!isLocked) {
|
if (!isLocked) {
|
||||||
playerHostView?.gestureHelper?.animateCenterControls(fadeTo)
|
playerHostView?.gestureHelper?.animateCenterControls(fadeTo)
|
||||||
shadowOverlay.isVisible = true
|
shadowOverlay.isVisible = true
|
||||||
|
|
@ -530,29 +531,16 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
|
|
||||||
var currentOffset = subtitleDelay
|
var currentOffset = subtitleDelay
|
||||||
binding.apply {
|
binding.apply {
|
||||||
var subtitleAdapter: SubtitleOffsetItemAdapter? = null
|
|
||||||
|
|
||||||
subtitleOffsetInput.doOnTextChanged { text, _, _, _ ->
|
subtitleOffsetInput.doOnTextChanged { text, _, _, _ ->
|
||||||
text?.toString()?.toLongOrNull()?.let { time ->
|
text?.toString()?.toLongOrNull()?.let { time ->
|
||||||
currentOffset = time
|
currentOffset = time
|
||||||
|
|
||||||
// Scroll to the first active subtitle
|
|
||||||
val playerPosition = player.getPosition() ?: 0
|
|
||||||
val totalPosition = playerPosition + currentOffset
|
|
||||||
subtitleAdapter?.updateTime(totalPosition)
|
|
||||||
|
|
||||||
subtitleAdapter?.getLatestActiveItem(totalPosition)
|
|
||||||
?.let { subtitlePos ->
|
|
||||||
subtitleOffsetRecyclerview.scrollToPosition(subtitlePos)
|
|
||||||
}
|
|
||||||
|
|
||||||
val str = when {
|
val str = when {
|
||||||
time > 0L -> {
|
time > 0L -> {
|
||||||
txt(R.string.subtitle_offset_extra_hint_before_format, time)
|
txt(R.string.subtitle_offset_extra_hint_later_format, time)
|
||||||
}
|
}
|
||||||
|
|
||||||
time < 0L -> {
|
time < 0L -> {
|
||||||
txt(R.string.subtitle_offset_extra_hint_later_format, -time)
|
txt(R.string.subtitle_offset_extra_hint_before_format, -time)
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
|
|
@ -570,12 +558,12 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
subtitleOffsetRecyclerview.isVisible = subtitles.isNotEmpty()
|
subtitleOffsetRecyclerview.isVisible = subtitles.isNotEmpty()
|
||||||
noSubtitlesLoadedNotice.isVisible = subtitles.isEmpty()
|
noSubtitlesLoadedNotice.isVisible = subtitles.isEmpty()
|
||||||
|
|
||||||
val initialSubtitlePosition = (player.getPosition() ?: 0) + currentOffset
|
val initialSubtitlePosition = (player.getPosition() ?: 0) - currentOffset
|
||||||
subtitleAdapter =
|
val subtitleAdapter =
|
||||||
SubtitleOffsetItemAdapter(initialSubtitlePosition) { subtitleCue ->
|
SubtitleOffsetItemAdapter(initialSubtitlePosition) { subtitleCue ->
|
||||||
val playerPosition = player.getPosition() ?: 0
|
val playerPosition = player.getPosition() ?: 0
|
||||||
subtitleOffsetInput.text = Editable.Factory.getInstance()
|
subtitleOffsetInput.text = Editable.Factory.getInstance()
|
||||||
?.newEditable((subtitleCue.startTimeMs - playerPosition).toString())
|
?.newEditable((playerPosition - subtitleCue.startTimeMs).toString())
|
||||||
}.apply {
|
}.apply {
|
||||||
submitList(subtitles)
|
submitList(subtitles)
|
||||||
}
|
}
|
||||||
|
|
@ -708,268 +696,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
//}
|
//}
|
||||||
}
|
}
|
||||||
|
|
||||||
// getColorStateList(index) on a TypedArray built from a raw intArrayOf(...) can't be
|
|
||||||
// statically verified by lint as a styleable resource index (it isn't tied to an
|
|
||||||
// <declare-styleable>), so it always flags a false-positive ResourceType error here —
|
|
||||||
// this is the standard, expected suppression for this obtainStyledAttributes pattern.
|
|
||||||
@SuppressLint("ResourceType")
|
|
||||||
private fun showCompressorDialog() {
|
|
||||||
val act = activity ?: return
|
|
||||||
val compressor = (player as? CS3IPlayer)?.compressor ?: return
|
|
||||||
|
|
||||||
// Always restore — CS3IPlayer is recreated between videos
|
|
||||||
restoreCompressorSettings()
|
|
||||||
|
|
||||||
// Snapshot for Cancel revert
|
|
||||||
data class Snap(val enabled: Boolean, val threshold: Float, val makeupGain: Float)
|
|
||||||
val snap = Snap(compressor.enabled, compressor.threshold, compressor.makeupGain)
|
|
||||||
|
|
||||||
val binding = com.lagradost.cloudstream3.databinding.CompressorDialogBinding
|
|
||||||
.inflate(android.view.LayoutInflater.from(act))
|
|
||||||
|
|
||||||
// ── Visual update helpers ──────────────────────────────────────────
|
|
||||||
fun updateCurrentLabel() {
|
|
||||||
binding.compressorCurrentLabel.text = if (compressor.enabled) {
|
|
||||||
act.getString(
|
|
||||||
R.string.compressor_on_format,
|
|
||||||
compressor.threshold.toInt(),
|
|
||||||
compressor.makeupGain.toInt()
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
act.getString(R.string.compressor_off)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateThresholdLabel() {
|
|
||||||
binding.compressorThresholdLabel.text =
|
|
||||||
act.getString(R.string.compressor_threshold_label, compressor.threshold.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateMakeupLabel() {
|
|
||||||
binding.compressorMakeupLabel.text =
|
|
||||||
act.getString(R.string.compressor_makeup_label, compressor.makeupGain.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Short, plain-language explanation of what each slider does, updated live —
|
|
||||||
// same idea as the "Use this if the subtitles are shown X ms too late" hint.
|
|
||||||
fun updateThresholdHint() {
|
|
||||||
binding.compressorThresholdHint.text =
|
|
||||||
act.getString(R.string.compressor_threshold_hint, compressor.threshold.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateMakeupHint() {
|
|
||||||
binding.compressorMakeupHint.text =
|
|
||||||
act.getString(R.string.compressor_makeup_hint, compressor.makeupGain.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
// WhiteButton = selected/active, BlackButton = unselected — same as speed presets
|
|
||||||
fun syncEnableButtons() {
|
|
||||||
val ctx = context ?: return
|
|
||||||
listOf(
|
|
||||||
binding.compressorEnableBtt to compressor.enabled,
|
|
||||||
binding.compressorDisableBtt to !compressor.enabled,
|
|
||||||
).forEach { (btn, active) ->
|
|
||||||
// Apply the full WhiteButton or BlackButton style — backgroundTint only.
|
|
||||||
// Also update setTextColor so we don't get white text on white background.
|
|
||||||
val styleAttr = if (active) R.style.WhiteButton else R.style.BlackButton
|
|
||||||
val ta = ctx.obtainStyledAttributes(
|
|
||||||
styleAttr,
|
|
||||||
intArrayOf(
|
|
||||||
com.google.android.material.R.attr.backgroundTint,
|
|
||||||
android.R.attr.textColor,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
btn.backgroundTintList = ta.getColorStateList(0)
|
|
||||||
ta.getColorStateList(1)?.let { btn.setTextColor(it) }
|
|
||||||
ta.recycle()
|
|
||||||
}
|
|
||||||
updateCurrentLabel()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Presets — declared before the sliders so their listeners can call
|
|
||||||
// syncPresetButtons(matchingPresetButton()) to keep the highlight accurate ──
|
|
||||||
val allPresets = listOf(
|
|
||||||
binding.compressorPresetLight,
|
|
||||||
binding.compressorPresetDialog,
|
|
||||||
binding.compressorPresetHeavy,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun syncPresetButtons(active: com.google.android.material.button.MaterialButton?) {
|
|
||||||
val ctx = context ?: return
|
|
||||||
allPresets.forEach { btn ->
|
|
||||||
val isActive = btn == active
|
|
||||||
val ta = ctx.obtainStyledAttributes(
|
|
||||||
if (isActive) R.style.WhiteButton else R.style.BlackButton,
|
|
||||||
intArrayOf(
|
|
||||||
com.google.android.material.R.attr.backgroundTint,
|
|
||||||
android.R.attr.textColor,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
btn.backgroundTintList = ta.getColorStateList(0)
|
|
||||||
ta.getColorStateList(1)?.let { btn.setTextColor(it) }
|
|
||||||
ta.recycle()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Figures out which preset (if any) matches the current values, so the
|
|
||||||
// correct button stays highlighted when the dialog is reopened, instead
|
|
||||||
// of always resetting to "none selected".
|
|
||||||
fun matchingPresetButton(): com.google.android.material.button.MaterialButton? = when {
|
|
||||||
compressor.threshold == -18f && compressor.makeupGain == 4f -> binding.compressorPresetLight
|
|
||||||
compressor.threshold == -24f && compressor.makeupGain == 12f -> binding.compressorPresetDialog
|
|
||||||
compressor.threshold == -30f && compressor.makeupGain == 16f -> binding.compressorPresetHeavy
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
|
|
||||||
fun applyPreset(
|
|
||||||
threshold: Float,
|
|
||||||
makeup: Float,
|
|
||||||
activeBtn: com.google.android.material.button.MaterialButton
|
|
||||||
) {
|
|
||||||
compressor.threshold = threshold
|
|
||||||
compressor.makeupGain = makeup
|
|
||||||
binding.compressorThresholdBar.value = threshold.coerceIn(-30f, 0f)
|
|
||||||
binding.compressorRatioBar.value = makeup.coerceIn(0f, 24f)
|
|
||||||
updateThresholdLabel()
|
|
||||||
updateMakeupLabel()
|
|
||||||
updateThresholdHint()
|
|
||||||
updateMakeupHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(activeBtn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Restore UI to current compressor state ─────────────────────────
|
|
||||||
binding.compressorThresholdBar.value = compressor.threshold.coerceIn(-30f, 0f)
|
|
||||||
binding.compressorRatioBar.value = compressor.makeupGain.coerceIn(0f, 24f)
|
|
||||||
updateThresholdLabel()
|
|
||||||
updateMakeupLabel()
|
|
||||||
updateThresholdHint()
|
|
||||||
updateMakeupHint()
|
|
||||||
syncEnableButtons()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
|
|
||||||
// ── On / Off ───────────────────────────────────────────────────────
|
|
||||||
binding.compressorEnableBtt.setOnClickListener {
|
|
||||||
compressor.enabled = true
|
|
||||||
syncEnableButtons()
|
|
||||||
}
|
|
||||||
binding.compressorDisableBtt.setOnClickListener {
|
|
||||||
compressor.enabled = false
|
|
||||||
syncEnableButtons()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Threshold slider + FABs ────────────────────────────────────────
|
|
||||||
binding.compressorThresholdBar.addOnChangeListener { _, value, fromUser ->
|
|
||||||
if (fromUser) {
|
|
||||||
compressor.threshold = value
|
|
||||||
updateThresholdLabel()
|
|
||||||
updateThresholdHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
binding.thresholdMinus.setOnClickListener {
|
|
||||||
val v = (compressor.threshold - 1f).coerceIn(-30f, 0f)
|
|
||||||
compressor.threshold = v
|
|
||||||
binding.compressorThresholdBar.value = v
|
|
||||||
updateThresholdLabel()
|
|
||||||
updateThresholdHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
binding.thresholdPlus.setOnClickListener {
|
|
||||||
val v = (compressor.threshold + 1f).coerceIn(-30f, 0f)
|
|
||||||
compressor.threshold = v
|
|
||||||
binding.compressorThresholdBar.value = v
|
|
||||||
updateThresholdLabel()
|
|
||||||
updateThresholdHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Makeup gain slider + FABs (reusing ratio_minus/plus ids) ──────
|
|
||||||
binding.compressorRatioBar.addOnChangeListener { _, value, fromUser ->
|
|
||||||
if (fromUser) {
|
|
||||||
compressor.makeupGain = value
|
|
||||||
updateMakeupLabel()
|
|
||||||
updateMakeupHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
binding.ratioMinus.setOnClickListener {
|
|
||||||
val v = (compressor.makeupGain - 1f).coerceIn(0f, 24f)
|
|
||||||
compressor.makeupGain = v
|
|
||||||
binding.compressorRatioBar.value = v
|
|
||||||
updateMakeupLabel()
|
|
||||||
updateMakeupHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
binding.ratioPlus.setOnClickListener {
|
|
||||||
val v = (compressor.makeupGain + 1f).coerceIn(0f, 24f)
|
|
||||||
compressor.makeupGain = v
|
|
||||||
binding.compressorRatioBar.value = v
|
|
||||||
updateMakeupLabel()
|
|
||||||
updateMakeupHint()
|
|
||||||
updateCurrentLabel()
|
|
||||||
syncPresetButtons(matchingPresetButton())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Preset buttons ─────────────────────────────────────────────────
|
|
||||||
binding.compressorPresetLight.setOnClickListener {
|
|
||||||
applyPreset(-18f, 4f, binding.compressorPresetLight)
|
|
||||||
}
|
|
||||||
binding.compressorPresetDialog.setOnClickListener {
|
|
||||||
applyPreset(-24f, 12f, binding.compressorPresetDialog)
|
|
||||||
}
|
|
||||||
binding.compressorPresetHeavy.setOnClickListener {
|
|
||||||
applyPreset(-30f, 16f, binding.compressorPresetHeavy)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Dialog lifecycle ───────────────────────────────────────────────
|
|
||||||
val dialog = AlertDialog.Builder(act, R.style.AlertDialogCustom)
|
|
||||||
.setView(binding.root)
|
|
||||||
.setOnDismissListener {
|
|
||||||
activity?.hideSystemUI()
|
|
||||||
selectCompressorDialog = null
|
|
||||||
}
|
|
||||||
.create()
|
|
||||||
selectCompressorDialog = dialog
|
|
||||||
|
|
||||||
binding.applyBtt.setOnClickListener {
|
|
||||||
saveCompressorSettings(compressor)
|
|
||||||
dialog.dismiss()
|
|
||||||
}
|
|
||||||
binding.resetBtt.setOnClickListener {
|
|
||||||
applyPreset(-24f, 12f, binding.compressorPresetDialog)
|
|
||||||
compressor.enabled = true
|
|
||||||
syncEnableButtons()
|
|
||||||
}
|
|
||||||
binding.cancelBtt.setOnClickListener {
|
|
||||||
compressor.enabled = snap.enabled
|
|
||||||
compressor.threshold = snap.threshold
|
|
||||||
compressor.makeupGain = snap.makeupGain
|
|
||||||
dialog.dismiss()
|
|
||||||
}
|
|
||||||
|
|
||||||
dialog.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun saveCompressorSettings(c: DynamicRangeCompressor) {
|
|
||||||
setKey(COMPRESSOR_ENABLED_KEY, c.enabled)
|
|
||||||
setKey(COMPRESSOR_THRESHOLD_KEY, c.threshold)
|
|
||||||
setKey(COMPRESSOR_RATIO_KEY, c.ratio)
|
|
||||||
setKey(COMPRESSOR_ATTACK_KEY, c.attackMs)
|
|
||||||
setKey(COMPRESSOR_RELEASE_KEY, c.releaseMs)
|
|
||||||
setKey(COMPRESSOR_MAKEUP_KEY, c.makeupGain)
|
|
||||||
}
|
|
||||||
|
|
||||||
protected fun restoreCompressorSettings() {
|
|
||||||
val c = (player as? CS3IPlayer)?.compressor ?: return
|
|
||||||
c.restoreSavedSettings()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun onClickChange() {
|
private fun onClickChange() {
|
||||||
isShowing = !isShowing
|
isShowing = !isShowing
|
||||||
if (isShowing) autoHide()
|
if (isShowing) autoHide()
|
||||||
|
|
@ -1046,8 +772,8 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
val showPlayerEpisodes = !isGone && isThereEpisodes()
|
val showPlayerEpisodes = !isGone && isThereEpisodes()
|
||||||
playerEpisodesButtonRoot.isVisible = showPlayerEpisodes
|
playerEpisodesButtonRoot.isVisible = showPlayerEpisodes
|
||||||
playerEpisodesButton.isVisible = showPlayerEpisodes
|
playerEpisodesButton.isVisible = showPlayerEpisodes
|
||||||
playerVideoTitleHolder.isGone = togglePlayerTitleGone || playerVideoTitle.text.isBlank()
|
playerVideoTitleHolder.isGone = togglePlayerTitleGone
|
||||||
playerVideoTitleRez.isGone = isGone || playerVideoTitleRez.text.isBlank()
|
playerVideoTitleRez.isGone = isGone
|
||||||
playerEpisodeFiller.isGone = isGone
|
playerEpisodeFiller.isGone = isGone
|
||||||
playerCenterMenu.isGone = isGone
|
playerCenterMenu.isGone = isGone
|
||||||
playerLock.isGone = !isShowing
|
playerLock.isGone = !isShowing
|
||||||
|
|
@ -1219,18 +945,12 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
player.handleEvent(CSPlayerEvent.SkipCurrentChapter)
|
player.handleEvent(CSPlayerEvent.SkipCurrentChapter)
|
||||||
}
|
}
|
||||||
|
|
||||||
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_P, KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_NUMPAD_ENTER -> { // space is not captured due to navigation
|
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_P, KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_ENTER -> { // space is not captured due to navigation
|
||||||
player.handleEvent(CSPlayerEvent.PlayPauseToggle)
|
player.handleEvent(CSPlayerEvent.PlayPauseToggle)
|
||||||
}
|
}
|
||||||
|
|
||||||
// KEYCODE_DPAD_CENTER and KEYCODE_ENTER both act as a "select/confirm" button.
|
KeyEvent.KEYCODE_DPAD_CENTER -> {
|
||||||
// Some remotes (e.g. LG Magic Remote) send KEYCODE_ENTER instead of KEYCODE_DPAD_CENTER.
|
if (isShowing) {
|
||||||
// When the player UI or a dialog is visible, we let the event pass through (return null)
|
|
||||||
// so the focused button/item can handle the click normally, rather than always toggling
|
|
||||||
// play/pause. Only when the UI is hidden do we treat it as a play/pause toggle.
|
|
||||||
KeyEvent.KEYCODE_DPAD_CENTER,
|
|
||||||
KeyEvent.KEYCODE_ENTER -> {
|
|
||||||
if (isShowing || isDialogOpen()) {
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
// If UI is not shown make click instantly skip to next chapter even if locked
|
// If UI is not shown make click instantly skip to next chapter even if locked
|
||||||
|
|
@ -1287,7 +1007,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
}
|
}
|
||||||
toggleEpisodesOverlay(true)
|
toggleEpisodesOverlay(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> return null // Avoid capturing all input
|
else -> return null // Avoid capturing all input
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
|
|
@ -1412,10 +1131,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
ctx.getString(R.string.playback_speed_enabled_key),
|
ctx.getString(R.string.playback_speed_enabled_key),
|
||||||
false
|
false
|
||||||
)
|
)
|
||||||
playBackCompressorEnabled = settingsManager.getBoolean(
|
|
||||||
ctx.getString(R.string.compressor_enabled_key),
|
|
||||||
false
|
|
||||||
)
|
|
||||||
playerRotateEnabled = settingsManager.getBoolean(
|
playerRotateEnabled = settingsManager.getBoolean(
|
||||||
ctx.getString(R.string.rotate_video_key),
|
ctx.getString(R.string.rotate_video_key),
|
||||||
false
|
false
|
||||||
|
|
@ -1442,10 +1157,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
}
|
}
|
||||||
playerBinding?.apply {
|
playerBinding?.apply {
|
||||||
playerSpeedBtt.isVisible = playBackSpeedEnabled
|
playerSpeedBtt.isVisible = playBackSpeedEnabled
|
||||||
playerCompressorBtt.isVisible = playBackCompressorEnabled
|
|
||||||
if (playBackCompressorEnabled) {
|
|
||||||
restoreCompressorSettings()
|
|
||||||
}
|
|
||||||
playerResizeBtt.isVisible = playerResizeEnabled
|
playerResizeBtt.isVisible = playerResizeEnabled
|
||||||
playerRotateBtt.isVisible =
|
playerRotateBtt.isVisible =
|
||||||
if (isLayout(TV or EMULATOR)) false else playerRotateEnabled
|
if (isLayout(TV or EMULATOR)) false else playerRotateEnabled
|
||||||
|
|
@ -1484,10 +1195,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
}
|
}
|
||||||
|
|
||||||
skipChapterButton.setOnClickListener {
|
skipChapterButton.setOnClickListener {
|
||||||
// Switch focus for a better UX, as otherwise it is reset to a random button like "back button"
|
|
||||||
if(skipChapterButton.hasFocus()) {
|
|
||||||
playerPausePlay.requestFocus()
|
|
||||||
}
|
|
||||||
player.handleEvent(CSPlayerEvent.SkipCurrentChapter)
|
player.handleEvent(CSPlayerEvent.SkipCurrentChapter)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1507,11 +1214,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|
||||||
showSpeedDialog()
|
showSpeedDialog()
|
||||||
}
|
}
|
||||||
|
|
||||||
playerCompressorBtt.setOnClickListener {
|
|
||||||
autoHide()
|
|
||||||
showCompressorDialog()
|
|
||||||
}
|
|
||||||
|
|
||||||
playerSkipOp.setOnClickListener {
|
playerSkipOp.setOnClickListener {
|
||||||
autoHide()
|
autoHide()
|
||||||
skipOp()
|
skipOp()
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.res.ColorStateList
|
import android.content.res.ColorStateList
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.graphics.Typeface
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.text.Spanned
|
import android.text.Spanned
|
||||||
|
|
@ -80,7 +79,6 @@ import com.lagradost.cloudstream3.ui.player.CS3IPlayer.Companion.preferredAudioT
|
||||||
import com.lagradost.cloudstream3.ui.player.CustomDecoder.Companion.updateForcedEncoding
|
import com.lagradost.cloudstream3.ui.player.CustomDecoder.Companion.updateForcedEncoding
|
||||||
import com.lagradost.cloudstream3.ui.player.PlayerSubtitleHelper.Companion.toSubtitleMimeType
|
import com.lagradost.cloudstream3.ui.player.PlayerSubtitleHelper.Companion.toSubtitleMimeType
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.LinkSource
|
import com.lagradost.cloudstream3.ui.player.source_priority.LinkSource
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.ProfileSettings
|
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
|
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
|
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityProfileDialog
|
import com.lagradost.cloudstream3.ui.player.source_priority.QualityProfileDialog
|
||||||
|
|
@ -101,7 +99,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SUBTITLE_AUTO_SELECT_KEY
|
import com.lagradost.cloudstream3.ui.subtitles.SUBTITLE_AUTO_SELECT_KEY
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment
|
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.getAutoSelectLanguageTagIETF
|
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.getAutoSelectLanguageTagIETF
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragmentDialog2
|
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.getShortSeasonText
|
import com.lagradost.cloudstream3.utils.AppContextUtils.getShortSeasonText
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.html
|
import com.lagradost.cloudstream3.utils.AppContextUtils.html
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
||||||
|
|
@ -120,10 +117,8 @@ import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
|
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.hideProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.hideSystemUI
|
import com.lagradost.cloudstream3.utils.UIHelper.hideSystemUI
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.popCurrentPage
|
import com.lagradost.cloudstream3.utils.UIHelper.popCurrentPage
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadUtils.getImageBitmapFromUrl
|
import com.lagradost.cloudstream3.utils.downloader.DownloadUtils.getImageBitmapFromUrl
|
||||||
import com.lagradost.cloudstream3.utils.setText
|
import com.lagradost.cloudstream3.utils.setText
|
||||||
|
|
@ -135,7 +130,6 @@ import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
import java.lang.ref.WeakReference
|
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
@ -513,8 +507,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
|
|
||||||
showDownloadProgress(DownloadEvent(0, 0, 0, null))
|
showDownloadProgress(DownloadEvent(0, 0, 0, null))
|
||||||
|
|
||||||
// uiReset() // Removed due to UX
|
uiReset()
|
||||||
|
|
||||||
currentSelectedLink = link
|
currentSelectedLink = link
|
||||||
// setEpisodes(viewModel.getAllMeta() ?: emptyList())
|
// setEpisodes(viewModel.getAllMeta() ?: emptyList())
|
||||||
setPlayerDimen(null)
|
setPlayerDimen(null)
|
||||||
|
|
@ -797,58 +790,47 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
binding.applyBtt.setOnClickListener {
|
binding.applyBtt.setOnClickListener {
|
||||||
val currentSubtitle = currentSubtitle
|
currentSubtitle?.let { currentSubtitle ->
|
||||||
if (currentSubtitle == null) {
|
providers.firstOrNull { it.idPrefix == currentSubtitle.idPrefix }?.let { api ->
|
||||||
dialog.dismissSafe()
|
ioSafe {
|
||||||
return@setOnClickListener
|
when (val apiResource =
|
||||||
}
|
Resource.fromResult(api.resource(currentSubtitle))) {
|
||||||
|
is Resource.Success -> {
|
||||||
|
val subtitles = apiResource.value.getSubtitles().map { resource ->
|
||||||
|
SubtitleData(
|
||||||
|
originalName = resource.name ?: getName(
|
||||||
|
currentSubtitle,
|
||||||
|
true
|
||||||
|
),
|
||||||
|
nameSuffix = "",
|
||||||
|
url = resource.url,
|
||||||
|
origin = resource.origin,
|
||||||
|
mimeType = resource.url.toSubtitleMimeType(),
|
||||||
|
headers = currentSubtitle.headers,
|
||||||
|
languageCode = currentSubtitle.lang
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (subtitles.isEmpty()) {
|
||||||
|
showToast(R.string.no_subtitles)
|
||||||
|
return@ioSafe
|
||||||
|
}
|
||||||
|
runOnMainThread {
|
||||||
|
addAndSelectSubtitles(*subtitles.toTypedArray())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val api = providers.firstOrNull { it.idPrefix == currentSubtitle.idPrefix }
|
is Resource.Failure -> {
|
||||||
if (api == null) {
|
showToast(apiResource.errorString)
|
||||||
dialog.dismissSafe()
|
}
|
||||||
return@setOnClickListener
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.applyBtt.showProgress()
|
is Resource.Loading -> {
|
||||||
ioSafe {
|
// not possible
|
||||||
val apiResource =
|
}
|
||||||
Resource.fromResult(api.resource(currentSubtitle))
|
|
||||||
binding.applyBtt.hideProgress()
|
|
||||||
when (apiResource) {
|
|
||||||
is Resource.Success -> {
|
|
||||||
val subtitles = apiResource.value.getSubtitles().map { resource ->
|
|
||||||
SubtitleData(
|
|
||||||
originalName = resource.name ?: getName(
|
|
||||||
currentSubtitle,
|
|
||||||
true
|
|
||||||
),
|
|
||||||
nameSuffix = "",
|
|
||||||
url = resource.url,
|
|
||||||
origin = resource.origin,
|
|
||||||
mimeType = resource.url.toSubtitleMimeType(),
|
|
||||||
headers = currentSubtitle.headers,
|
|
||||||
languageCode = currentSubtitle.lang
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
if (subtitles.isEmpty()) {
|
|
||||||
showToast(R.string.no_subtitles)
|
|
||||||
return@ioSafe
|
|
||||||
}
|
|
||||||
dialog.dismissSafe()
|
|
||||||
runOnMainThread {
|
|
||||||
addAndSelectSubtitles(*subtitles.toTypedArray())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is Resource.Failure -> {
|
|
||||||
showToast(apiResource.errorString)
|
|
||||||
}
|
|
||||||
|
|
||||||
is Resource.Loading -> {
|
|
||||||
// not possible
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
dialog.dismissSafe()
|
||||||
}
|
}
|
||||||
|
|
||||||
dialog.setOnDismissListener {
|
dialog.setOnDismissListener {
|
||||||
|
|
@ -1047,7 +1029,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
|
|
||||||
binding.subtitleSettingsBtt.setOnClickListener {
|
binding.subtitleSettingsBtt.setOnClickListener {
|
||||||
safe {
|
safe {
|
||||||
val subtitlesFragment = SubtitlesFragmentDialog2()
|
val subtitlesFragment = SubtitlesFragment()
|
||||||
subtitlesFragment.systemBarsAddPadding = true
|
subtitlesFragment.systemBarsAddPadding = true
|
||||||
subtitlesFragment.show(this.parentFragmentManager, "SubtitleSettings")
|
subtitlesFragment.show(this.parentFragmentManager, "SubtitleSettings")
|
||||||
}
|
}
|
||||||
|
|
@ -1116,29 +1098,21 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
|
|
||||||
var sourceIndex = 0
|
var sourceIndex = 0
|
||||||
var startSource = 0
|
var startSource = 0
|
||||||
// Filtered and sorted links
|
var sortedUrls = emptyList<Pair<ExtractorLink?, ExtractorUri?>>()
|
||||||
var currentHiddenFooter: View? = null
|
|
||||||
var filteredLinks: List<DisplayLink> = emptyList()
|
|
||||||
|
|
||||||
fun refreshLinks(qualityProfile: Int) {
|
fun refreshLinks(qualityProfile: Int) {
|
||||||
val currentLinkUsed = currentSelectedLink
|
sortedUrls = viewModel.state.sortLinks(qualityProfile)
|
||||||
// Always display current linkFooter
|
if (sortedUrls.isEmpty()) {
|
||||||
val sortedLinks = viewModel.state.sortLinks(qualityProfile)
|
|
||||||
|
|
||||||
filteredLinks = sortedLinks.filter { it.shouldUseLink || it.link == currentLinkUsed }
|
|
||||||
|
|
||||||
if (sortedLinks.isEmpty()) {
|
|
||||||
sourceDialog.findViewById<LinearLayout>(R.id.sort_sources_holder)?.isGone =
|
sourceDialog.findViewById<LinearLayout>(R.id.sort_sources_holder)?.isGone =
|
||||||
true
|
true
|
||||||
} else {
|
} else {
|
||||||
startSource = filteredLinks.indexOfFirst { it.link == currentLinkUsed }
|
startSource = sortedUrls.indexOf(currentSelectedLink)
|
||||||
sourceIndex = startSource
|
sourceIndex = startSource
|
||||||
|
|
||||||
val sourcesArrayAdapter =
|
val sourcesArrayAdapter =
|
||||||
ArrayAdapter<String>(ctx, R.layout.sort_bottom_single_choice)
|
ArrayAdapter<String>(ctx, R.layout.sort_bottom_single_choice)
|
||||||
|
|
||||||
sourcesArrayAdapter.addAll(filteredLinks.map { displayLink ->
|
sourcesArrayAdapter.addAll(sortedUrls.map { (link, uri) ->
|
||||||
val (link, uri) = displayLink.link
|
|
||||||
val name = link?.name ?: uri?.name ?: "NULL"
|
val name = link?.name ?: uri?.name ?: "NULL"
|
||||||
"$name ${Qualities.getStringByInt(link?.quality)}"
|
"$name ${Qualities.getStringByInt(link?.quality)}"
|
||||||
})
|
})
|
||||||
|
|
@ -1154,7 +1128,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
providerList.setOnItemLongClickListener { _, _, position, _ ->
|
providerList.setOnItemLongClickListener { _, _, position, _ ->
|
||||||
sortedLinks.getOrNull(position)?.link?.first?.url?.let {
|
sortedUrls.getOrNull(position)?.first?.url?.let {
|
||||||
clipboardHelper(
|
clipboardHelper(
|
||||||
txt(R.string.video_source),
|
txt(R.string.video_source),
|
||||||
it
|
it
|
||||||
|
|
@ -1162,25 +1136,6 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
val hiddenLinks = sortedLinks.size - filteredLinks.size
|
|
||||||
providerList.removeFooterView(currentHiddenFooter)
|
|
||||||
|
|
||||||
if (hiddenLinks > 0) {
|
|
||||||
val hiddenLinksFooter: TextView = layoutInflater.inflate(
|
|
||||||
R.layout.sort_bottom_footer_add_choice, null
|
|
||||||
) as TextView
|
|
||||||
|
|
||||||
providerList.addFooterView(hiddenLinksFooter, null, false)
|
|
||||||
currentHiddenFooter = hiddenLinksFooter
|
|
||||||
|
|
||||||
val hiddenLinksText =
|
|
||||||
ctx.resources.getQuantityString(R.plurals.links_hidden, hiddenLinks)
|
|
||||||
.format(hiddenLinks)
|
|
||||||
hiddenLinksFooter.text = hiddenLinksText
|
|
||||||
hiddenLinksFooter.setCompoundDrawables(null, null, null, null)
|
|
||||||
hiddenLinksFooter.setTypeface(null, Typeface.ITALIC)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1394,8 +1349,8 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (init) {
|
if (init) {
|
||||||
filteredLinks.getOrNull(sourceIndex)?.let {
|
sortedUrls.getOrNull(sourceIndex)?.let {
|
||||||
loadLink(it.link, true)
|
loadLink(it, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sourceDialog.dismissSafe(activity)
|
sourceDialog.dismissSafe(activity)
|
||||||
|
|
@ -1563,10 +1518,6 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun playerError(exception: Throwable) {
|
override fun playerError(exception: Throwable) {
|
||||||
currentSelectedLink?.let { link ->
|
|
||||||
viewModel.modifyState { this.addError(link) }
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentUrl =
|
val currentUrl =
|
||||||
currentSelectedLink?.let { it.first?.url ?: it.second?.uri?.toString() } ?: "unknown"
|
currentSelectedLink?.let { it.first?.url ?: it.second?.uri?.toString() } ?: "unknown"
|
||||||
val headers = currentSelectedLink?.first?.headers?.toString() ?: "none"
|
val headers = currentSelectedLink?.first?.headers?.toString() ?: "none"
|
||||||
|
|
@ -1574,7 +1525,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
Log.e(
|
Log.e(
|
||||||
TAG,
|
TAG,
|
||||||
"playerError: $currentSelectedLink, " +
|
"playerError: $currentSelectedLink, " +
|
||||||
"type=${exception::class.qualifiedName}, " +
|
"type=${exception::class.java.canonicalName}, " +
|
||||||
"message=${exception.message}, url=$currentUrl, headers=$headers, " +
|
"message=${exception.message}, url=$currentUrl, headers=$headers, " +
|
||||||
"referer=$referer, position=${player.getPosition() ?: "unknown"}, " +
|
"referer=$referer, position=${player.getPosition() ?: "unknown"}, " +
|
||||||
"duration=${player.getDuration() ?: "unknown"}, " +
|
"duration=${player.getDuration() ?: "unknown"}, " +
|
||||||
|
|
@ -1589,22 +1540,8 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
|
|
||||||
private fun noLinksFound() {
|
private fun noLinksFound() {
|
||||||
viewModel.forceClearCache = true
|
viewModel.forceClearCache = true
|
||||||
val hiddenLinks = viewModel.state.sortLinks(currentQualityProfile).count { !it.shouldUseLink }
|
|
||||||
|
|
||||||
context?.let { ctx ->
|
|
||||||
// Display that there are hidden links to the user.
|
|
||||||
if (hiddenLinks > 0) {
|
|
||||||
val noLinksString = ctx.getString(R.string.no_links_found_toast)
|
|
||||||
val hiddenString =
|
|
||||||
ctx.resources.getQuantityString(R.plurals.links_hidden, hiddenLinks)
|
|
||||||
.format(hiddenLinks)
|
|
||||||
val toastText = "$noLinksString\n($hiddenString)"
|
|
||||||
showToast(toastText, Toast.LENGTH_SHORT)
|
|
||||||
} else {
|
|
||||||
showToast(R.string.no_links_found_toast, Toast.LENGTH_SHORT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
showToast(R.string.no_links_found_toast, Toast.LENGTH_SHORT)
|
||||||
activity?.popCurrentPage()
|
activity?.popCurrentPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1615,9 +1552,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
val links = viewModel.state.sortLinks(currentQualityProfile)
|
val links = viewModel.state.sortLinks(currentQualityProfile)
|
||||||
|
if (links.isEmpty()) {
|
||||||
val firstAvailableLink = links.firstOrNull { it.shouldUseLink }?.link
|
|
||||||
if (firstAvailableLink == null) {
|
|
||||||
noLinksFound()
|
noLinksFound()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -1625,7 +1560,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
if (!isPlayerActive.compareAndSet(false, true)) {
|
if (!isPlayerActive.compareAndSet(false, true)) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
loadLink(firstAvailableLink, false)
|
loadLink(links.first(), false)
|
||||||
showPlayerMetadata()
|
showPlayerMetadata()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1649,7 +1584,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
)
|
)
|
||||||
|
|
||||||
val meta = arrayOf(
|
val meta = arrayOf(
|
||||||
load.tags?.takeIf { it.isNotEmpty() }?.take(6)?.joinToString(", "),
|
load.tags?.takeIf { it.isNotEmpty() }?.joinToString(", "),
|
||||||
load.year?.toString(),
|
load.year?.toString(),
|
||||||
if (!load.type.isMovieType())
|
if (!load.type.isMovieType())
|
||||||
context?.getShortSeasonText(
|
context?.getShortSeasonText(
|
||||||
|
|
@ -1669,7 +1604,7 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
|
|
||||||
if (!description.isNullOrBlank()) {
|
if (!description.isNullOrBlank()) {
|
||||||
descView.isVisible = true
|
descView.isVisible = true
|
||||||
descView.text = description.html()
|
descView.text = description
|
||||||
} else {
|
} else {
|
||||||
descView.isVisible = false
|
descView.isVisible = false
|
||||||
|
|
||||||
|
|
@ -1692,26 +1627,25 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getNextLink(): DisplayLink? {
|
|
||||||
val links = viewModel.state.sortLinks(currentQualityProfile)
|
|
||||||
val currentIndex = links.indexOfFirst { it.link == currentSelectedLink }
|
|
||||||
val nextPotentialLink =
|
|
||||||
links.withIndex().firstOrNull { it.index > currentIndex && it.value.shouldUseLink }
|
|
||||||
return nextPotentialLink?.value
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun hasNextMirror(): Boolean {
|
override fun hasNextMirror(): Boolean {
|
||||||
return getNextLink() != null
|
val links = viewModel.state.sortLinks(currentQualityProfile)
|
||||||
|
return links.isNotEmpty() && links.indexOf(currentSelectedLink) + 1 < links.size
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun nextMirror() {
|
override fun nextMirror() {
|
||||||
val nextLink = getNextLink()
|
val links = viewModel.state.sortLinks(currentQualityProfile)
|
||||||
if (nextLink == null) {
|
if (links.isEmpty()) {
|
||||||
noLinksFound()
|
noLinksFound()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
loadLink(nextLink.link, true)
|
val newIndex = links.indexOf(currentSelectedLink) + 1
|
||||||
|
if (newIndex >= links.size) {
|
||||||
|
noLinksFound()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
loadLink(links[newIndex], true)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
|
|
@ -1764,10 +1698,8 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
if (settingsManager.getBoolean(
|
if (settingsManager.getBoolean(
|
||||||
ctx.getString(R.string.episode_sync_enabled_key), true
|
ctx.getString(R.string.episode_sync_enabled_key), true
|
||||||
)
|
)
|
||||||
) {
|
) maxEpisodeSet = meta.episode
|
||||||
maxEpisodeSet = meta.episode
|
sync.modifyMaxEpisode(meta.totalEpisodeIndex ?: meta.episode)
|
||||||
sync.modifyMaxEpisode(meta.totalEpisodeIndex ?: meta.episode)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1800,11 +1732,11 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
): SubtitleData? {
|
): SubtitleData? {
|
||||||
val langCode = preferredAutoSelectSubtitles ?: return null
|
val langCode = preferredAutoSelectSubtitles ?: return null
|
||||||
if (downloads) {
|
if (downloads) {
|
||||||
sortSubs(subtitles).firstOrNull {
|
return sortSubs(subtitles).firstOrNull {
|
||||||
it.origin == SubtitleOrigin.DOWNLOADED_FILE && it.matchesLanguageCode(
|
it.origin == SubtitleOrigin.DOWNLOADED_FILE && it.matchesLanguageCode(
|
||||||
langCode
|
langCode
|
||||||
)
|
)
|
||||||
}?.let { return it }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!settings) return null
|
if (!settings) return null
|
||||||
|
|
@ -2218,7 +2150,6 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
isPlayerActive.set(false)
|
isPlayerActive.set(false)
|
||||||
binding?.overlayLoadingSkipButton?.isVisible = false
|
binding?.overlayLoadingSkipButton?.isVisible = false
|
||||||
binding?.playerLoadingOverlay?.isVisible = true
|
binding?.playerLoadingOverlay?.isVisible = true
|
||||||
viewModel.modifyState { setError(emptyList()) }
|
|
||||||
uiReset()
|
uiReset()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2272,14 +2203,6 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
fromTagToEnglishLanguageName(it)?.lowercase() ?: return@mapNotNull null
|
fromTagToEnglishLanguageName(it)?.lowercase() ?: return@mapNotNull null
|
||||||
} ?: listOf()
|
} ?: listOf()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set up TV clock visibility
|
|
||||||
if (isLayout(TV)) {
|
|
||||||
val showTvClock = settingsManager.getBoolean(ctx.getString(R.string.tv_layout_clock_key), false)
|
|
||||||
playerBinding?.playerVideoClock?.isVisible = showTvClock
|
|
||||||
} else {
|
|
||||||
playerBinding?.playerVideoClock?.isVisible = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
unwrapBundle(savedInstanceState)
|
unwrapBundle(savedInstanceState)
|
||||||
|
|
@ -2358,23 +2281,19 @@ class GeneratorPlayer : FullScreenPlayer() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
observe(viewModel.currentLinks) { (_, instance) ->
|
observe(viewModel.currentLinks) { (links, instance) ->
|
||||||
if (instance != viewModel.state.instance) return@observe // Outdated observe
|
if (instance != viewModel.state.instance) return@observe // Outdated observe
|
||||||
|
|
||||||
val sortedLinks = viewModel.state.sortLinks(currentQualityProfile)
|
val turnVisible = links.isNotEmpty() && viewModel.generator?.canSkipLoading == true
|
||||||
val usableLinks = sortedLinks.count { link -> link.shouldUseLink }
|
|
||||||
|
|
||||||
val turnVisible = usableLinks > 0 && viewModel.generator?.canSkipLoading == true
|
|
||||||
val wasGone = binding.overlayLoadingSkipButton.isGone
|
val wasGone = binding.overlayLoadingSkipButton.isGone
|
||||||
|
|
||||||
binding.overlayLoadingSkipButton.apply {
|
binding.overlayLoadingSkipButton.apply {
|
||||||
isVisible = turnVisible
|
isVisible = turnVisible
|
||||||
|
if (links.isEmpty()) {
|
||||||
if (usableLinks == 0) {
|
|
||||||
setText(R.string.skip_loading)
|
setText(R.string.skip_loading)
|
||||||
} else {
|
} else {
|
||||||
@SuppressLint("SetTextI18n")
|
@SuppressLint("SetTextI18n")
|
||||||
text = "${context.getString(R.string.skip_loading)} (${usableLinks})"
|
text = "${context.getString(R.string.skip_loading)} (${links.size})"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import android.app.Activity
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import androidx.core.content.ContextCompat.getString
|
import androidx.core.content.ContextCompat.getString
|
||||||
import androidx.navigation.NavOptions
|
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
import com.lagradost.cloudstream3.actions.temp.CloudStreamPackage
|
import com.lagradost.cloudstream3.actions.temp.CloudStreamPackage
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
|
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
|
||||||
|
|
@ -13,15 +12,6 @@ import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
||||||
import com.lagradost.safefile.SafeFile
|
import com.lagradost.safefile.SafeFile
|
||||||
|
|
||||||
object OfflinePlaybackHelper {
|
object OfflinePlaybackHelper {
|
||||||
/**
|
|
||||||
* Pop any existing player off the nav back stack before pushing the new one,
|
|
||||||
* keeping the stack flat (at most one player at a time). This prevents an
|
|
||||||
* OOM when many files are opened in sequence via DownloadedPlayerActivity.
|
|
||||||
*/
|
|
||||||
private val replacePlayerNavOptions = NavOptions.Builder()
|
|
||||||
.setPopUpTo(R.id.navigation_player, inclusive = true, saveState = false)
|
|
||||||
.build()
|
|
||||||
|
|
||||||
fun playLink(activity: Activity, url: String) {
|
fun playLink(activity: Activity, url: String) {
|
||||||
activity.navigate(
|
activity.navigate(
|
||||||
R.id.global_to_navigation_player, GeneratorPlayer.newInstance(
|
R.id.global_to_navigation_player, GeneratorPlayer.newInstance(
|
||||||
|
|
@ -30,8 +20,7 @@ object OfflinePlaybackHelper {
|
||||||
BasicLink(url)
|
BasicLink(url)
|
||||||
), id = url.hashCode()
|
), id = url.hashCode()
|
||||||
), 0
|
), 0
|
||||||
),
|
)
|
||||||
replacePlayerNavOptions
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -63,8 +52,7 @@ object OfflinePlaybackHelper {
|
||||||
subs,
|
subs,
|
||||||
if (id != -1) id else null,
|
if (id != -1) id else null,
|
||||||
), 0
|
), 0
|
||||||
),
|
)
|
||||||
replacePlayerNavOptions
|
|
||||||
)
|
)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
@ -88,8 +76,7 @@ object OfflinePlaybackHelper {
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
), 0
|
), 0
|
||||||
),
|
)
|
||||||
replacePlayerNavOptions
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -10,8 +10,6 @@ import com.lagradost.cloudstream3.mvvm.Resource
|
||||||
import com.lagradost.cloudstream3.mvvm.launchSafe
|
import com.lagradost.cloudstream3.mvvm.launchSafe
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.mvvm.safeApiCall
|
import com.lagradost.cloudstream3.mvvm.safeApiCall
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.ProfileSettings
|
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
|
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
|
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
|
||||||
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
import com.lagradost.cloudstream3.ui.result.ResultEpisode
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
|
|
@ -42,20 +40,12 @@ data class GeneratorState(
|
||||||
val id: Int?,
|
val id: Int?,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class DisplayLink(
|
|
||||||
val link: VideoLink,
|
|
||||||
// If the link should be displayed and used by the player
|
|
||||||
val shouldUseLink: Boolean,
|
|
||||||
val priority: Int
|
|
||||||
)
|
|
||||||
|
|
||||||
/** Immutable state of all current links relevant to displaying the video */
|
/** Immutable state of all current links relevant to displaying the video */
|
||||||
// @MustUseReturnValues
|
// @MustUseReturnValues
|
||||||
// @Immutable
|
// @Immutable
|
||||||
data class VideoState(
|
data class VideoState(
|
||||||
val subtitles: PersistentSet<SubtitleData> = persistentSetOf(),
|
val subtitles: PersistentSet<SubtitleData> = persistentSetOf(),
|
||||||
val links: PersistentSet<VideoLink> = persistentSetOf(),
|
val links: PersistentSet<VideoLink> = persistentSetOf(),
|
||||||
val erroredLinks: PersistentSet<VideoLink> = persistentSetOf(),
|
|
||||||
val stamps: PersistentList<VideoSkipStamp> = persistentListOf(),
|
val stamps: PersistentList<VideoSkipStamp> = persistentListOf(),
|
||||||
val loading: Resource<Unit> = Resource.Loading(),
|
val loading: Resource<Unit> = Resource.Loading(),
|
||||||
val generatorState: GeneratorState? = null,
|
val generatorState: GeneratorState? = null,
|
||||||
|
|
@ -66,52 +56,19 @@ data class VideoState(
|
||||||
*
|
*
|
||||||
* sortedBy is not exactly expensive, but each hasNextMirror does it again, so this alleviates unnecessary recomputation
|
* sortedBy is not exactly expensive, but each hasNextMirror does it again, so this alleviates unnecessary recomputation
|
||||||
* */
|
* */
|
||||||
private val sortedLinks: ConcurrentHashMap<Int, List<DisplayLink>> = ConcurrentHashMap()
|
private val sortedLinks: ConcurrentHashMap<Int, List<VideoLink>> = ConcurrentHashMap()
|
||||||
|
|
||||||
/**
|
|
||||||
* The cache is guaranteed to be up to date link-wise due to the immutable links.
|
|
||||||
* However, hideNegativeSources and hideErrorSources could be updated, which requires clearing the cache.
|
|
||||||
*/
|
|
||||||
fun clearSortedLinksCache() = sortedLinks.clear()
|
fun clearSortedLinksCache() = sortedLinks.clear()
|
||||||
|
|
||||||
private fun hasLinkErrored(link: VideoLink): Boolean {
|
|
||||||
return erroredLinks.any { it == link }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun VideoLink.toDisplayLink(
|
|
||||||
qualityProfile: Int,
|
|
||||||
hideNegativeSources: Boolean,
|
|
||||||
hideErrorSources: Boolean
|
|
||||||
): DisplayLink {
|
|
||||||
val priority = getLinkPriority(qualityProfile, this.first)
|
|
||||||
val shouldHideLink =
|
|
||||||
(hideNegativeSources && priority < 0) || (hideErrorSources && hasLinkErrored(this))
|
|
||||||
val displayLink = DisplayLink(this, !shouldHideLink, priority)
|
|
||||||
|
|
||||||
return displayLink
|
|
||||||
}
|
|
||||||
|
|
||||||
// Modifying sortedLinks is not considered a "visible" side effect, and rerunning it does not change the result
|
// Modifying sortedLinks is not considered a "visible" side effect, and rerunning it does not change the result
|
||||||
// It is by all standards, idempotent and by extension also pure as it has no "visible" side effect
|
// It is by all standards, idempotent and by extension also pure as it has no "visible" side effect
|
||||||
/** Returns .links in the sorted order according to the qualityProfile.
|
/** Returns .links in the sorted order according to the qualityProfile.
|
||||||
* Use .links if order is not needed */
|
* Use .links if order is not needed */
|
||||||
@Contract(pure = true)
|
@Contract(pure = true)
|
||||||
fun sortLinks(qualityProfile: Int): List<DisplayLink> {
|
fun sortLinks(qualityProfile: Int): List<VideoLink> {
|
||||||
sortedLinks[qualityProfile]?.let {
|
return sortedLinks[qualityProfile] ?: links.sortedBy { link ->
|
||||||
return it
|
|
||||||
}
|
|
||||||
|
|
||||||
val hideNegativeSources =
|
|
||||||
QualityDataHelper.getProfileSetting(qualityProfile, ProfileSettings.HideNegativeSources)
|
|
||||||
val hideErrorSources =
|
|
||||||
QualityDataHelper.getProfileSetting(qualityProfile, ProfileSettings.HideErrorSources)
|
|
||||||
|
|
||||||
return links.map { link ->
|
|
||||||
// negative because we want to sort highest quality first
|
// negative because we want to sort highest quality first
|
||||||
link.toDisplayLink(qualityProfile, hideNegativeSources, hideErrorSources)
|
-getLinkPriority(qualityProfile, link.first)
|
||||||
}.sortedBy {
|
|
||||||
// negative because we want to sort highest quality first
|
|
||||||
-it.priority
|
|
||||||
}.also { value -> sortedLinks[qualityProfile] = value }
|
}.also { value -> sortedLinks[qualityProfile] = value }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -156,12 +113,6 @@ data class VideoState(
|
||||||
@JvmName("setVideoSkipStamp")
|
@JvmName("setVideoSkipStamp")
|
||||||
@Contract(pure = true)
|
@Contract(pure = true)
|
||||||
fun set(items: Collection<VideoSkipStamp>): VideoState = copy(stamps = items.toPersistentList())
|
fun set(items: Collection<VideoSkipStamp>): VideoState = copy(stamps = items.toPersistentList())
|
||||||
|
|
||||||
@Contract(pure = true)
|
|
||||||
fun addError(item: VideoLink): VideoState = copy(erroredLinks = erroredLinks.add(item))
|
|
||||||
|
|
||||||
@Contract(pure = true)
|
|
||||||
fun setError(items: Collection<VideoLink>): VideoState = copy(erroredLinks = items.toPersistentSet())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
data class VideoLive<T>(
|
data class VideoLive<T>(
|
||||||
|
|
@ -190,8 +141,9 @@ class PlayerGeneratorViewModel : ViewModel() {
|
||||||
var state = VideoState(instance = 0)
|
var state = VideoState(instance = 0)
|
||||||
private set
|
private set
|
||||||
|
|
||||||
private val _currentLinks = MutableLiveData<VideoLive<Set<VideoLink>>>(null)
|
private val _currentLinks =
|
||||||
val currentLinks: LiveData<VideoLive<Set<VideoLink>>> = _currentLinks
|
MutableLiveData<VideoLive<Set<Pair<ExtractorLink?, ExtractorUri?>>>>(null)
|
||||||
|
val currentLinks: LiveData<VideoLive<Set<Pair<ExtractorLink?, ExtractorUri?>>>> = _currentLinks
|
||||||
|
|
||||||
private val _currentSubtitles = MutableLiveData<VideoLive<Set<SubtitleData>>>(null)
|
private val _currentSubtitles = MutableLiveData<VideoLive<Set<SubtitleData>>>(null)
|
||||||
val currentSubtitles: LiveData<VideoLive<Set<SubtitleData>>> = _currentSubtitles
|
val currentSubtitles: LiveData<VideoLive<Set<SubtitleData>>> = _currentSubtitles
|
||||||
|
|
|
||||||
|
|
@ -887,6 +887,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
|
||||||
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
|
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
|
||||||
|
|
||||||
// Only expose the parent chain when controls are currently hidden.
|
// Only expose the parent chain when controls are currently hidden.
|
||||||
|
val prevCenterMenuGone = playerView.playerCenterMenu?.isGone ?: false
|
||||||
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
|
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
|
||||||
if (!wasShowing) {
|
if (!wasShowing) {
|
||||||
playerView.playerCenterMenu?.isGone = false
|
playerView.playerCenterMenu?.isGone = false
|
||||||
|
|
@ -905,7 +906,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
|
||||||
resetRewindText()
|
resetRewindText()
|
||||||
// Restore parent chain only if we changed it and controls are still hidden.
|
// Restore parent chain only if we changed it and controls are still hidden.
|
||||||
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
|
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
|
||||||
playerView.playerCenterMenu?.isGone = true
|
playerView.playerCenterMenu?.isGone = prevCenterMenuGone
|
||||||
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
|
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
|
||||||
rewHolder.alpha = 0f
|
rewHolder.alpha = 0f
|
||||||
}
|
}
|
||||||
|
|
@ -926,6 +927,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
|
||||||
val ffwdText = playerView.exoFfwdText
|
val ffwdText = playerView.exoFfwdText
|
||||||
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
|
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
|
||||||
|
|
||||||
|
val prevCenterMenuGone = playerView.playerCenterMenu?.isGone ?: false
|
||||||
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
|
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
|
||||||
if (!wasShowing) {
|
if (!wasShowing) {
|
||||||
playerView.playerCenterMenu?.isGone = false
|
playerView.playerCenterMenu?.isGone = false
|
||||||
|
|
@ -943,7 +945,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
|
||||||
ffwdText?.post {
|
ffwdText?.post {
|
||||||
resetFastForwardText()
|
resetFastForwardText()
|
||||||
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
|
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
|
||||||
playerView.playerCenterMenu?.isGone = true
|
playerView.playerCenterMenu?.isGone = prevCenterMenuGone
|
||||||
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
|
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
|
||||||
ffwdHolder.alpha = 0f
|
ffwdHolder.alpha = 0f
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,11 @@ import androidx.annotation.OptIn
|
||||||
import androidx.media3.common.MimeTypes
|
import androidx.media3.common.MimeTypes
|
||||||
import androidx.media3.common.util.UnstableApi
|
import androidx.media3.common.util.UnstableApi
|
||||||
import androidx.media3.ui.SubtitleView
|
import androidx.media3.ui.SubtitleView
|
||||||
import com.fasterxml.jackson.annotation.JsonIgnore
|
|
||||||
import com.lagradost.cloudstream3.SubtitleFile
|
import com.lagradost.cloudstream3.SubtitleFile
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SaveCaptionStyle
|
import com.lagradost.cloudstream3.ui.subtitles.SaveCaptionStyle
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.setSubtitleViewStyle
|
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.setSubtitleViewStyle
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
|
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
import com.lagradost.cloudstream3.utils.UIHelper.toPx
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
enum class SubtitleStatus {
|
enum class SubtitleStatus {
|
||||||
IS_ACTIVE,
|
IS_ACTIVE,
|
||||||
|
|
@ -35,19 +32,17 @@ enum class SubtitleOrigin {
|
||||||
* @param url Url for the subtitle, when EMBEDDED_IN_VIDEO this variable is used as the real backend id
|
* @param url Url for the subtitle, when EMBEDDED_IN_VIDEO this variable is used as the real backend id
|
||||||
* @param headers if empty it will use the base onlineDataSource headers else only the specified headers
|
* @param headers if empty it will use the base onlineDataSource headers else only the specified headers
|
||||||
* @param languageCode usually, tags such as "en", "es-mx", or "zh-hant-TW". But it could be something like "English 4"
|
* @param languageCode usually, tags such as "en", "es-mx", or "zh-hant-TW". But it could be something like "English 4"
|
||||||
*/
|
* */
|
||||||
@Serializable
|
|
||||||
data class SubtitleData(
|
data class SubtitleData(
|
||||||
@SerialName("originalName") val originalName: String,
|
val originalName: String,
|
||||||
@SerialName("nameSuffix") val nameSuffix: String,
|
val nameSuffix: String,
|
||||||
@SerialName("url") val url: String,
|
val url: String,
|
||||||
@SerialName("origin") val origin: SubtitleOrigin,
|
val origin: SubtitleOrigin,
|
||||||
@SerialName("mimeType") val mimeType: String,
|
val mimeType: String,
|
||||||
@SerialName("headers") val headers: Map<String, String>,
|
val headers: Map<String, String>,
|
||||||
@SerialName("languageCode") val languageCode: String?,
|
val languageCode: String?,
|
||||||
) {
|
) {
|
||||||
/** Internal ID for media3, unique for each link. */
|
/** Internal ID for exoplayer, unique for each link*/
|
||||||
@JsonIgnore
|
|
||||||
fun getId(): String {
|
fun getId(): String {
|
||||||
return if (origin == SubtitleOrigin.EMBEDDED_IN_VIDEO) url
|
return if (origin == SubtitleOrigin.EMBEDDED_IN_VIDEO) url
|
||||||
else "$url|$name"
|
else "$url|$name"
|
||||||
|
|
@ -59,22 +54,22 @@ data class SubtitleData(
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Tries hard to figure out a valid IETF tag based on language code and name. Will return null if not found. */
|
/** Tries hard to figure out a valid IETF tag based on language code and name. Will return null if not found. */
|
||||||
@JsonIgnore
|
|
||||||
fun getIETF_tag(): String? {
|
fun getIETF_tag(): String? {
|
||||||
return fromLanguageToTagIETF(this.languageCode) ?: fromLanguageToTagIETF(this.originalName, halfMatch = true)
|
return fromLanguageToTagIETF(this.languageCode) ?: fromLanguageToTagIETF(this.originalName, halfMatch = true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@SerialName("name") val name = "$originalName $nameSuffix"
|
val name = "$originalName $nameSuffix"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the URL, but tries to fix it if it is malformed.
|
* Gets the URL, but tries to fix it if it is malformed.
|
||||||
*/
|
*/
|
||||||
@JsonIgnore
|
|
||||||
fun getFixedUrl(): String {
|
fun getFixedUrl(): String {
|
||||||
// Some extensions fail to include the protocol, this helps with that.
|
// Some extensions fail to include the protocol, this helps with that.
|
||||||
val fixedSubUrl = if (this.url.startsWith("//")) {
|
val fixedSubUrl = if (this.url.startsWith("//")) {
|
||||||
"https:${this.url}"
|
"https:${this.url}"
|
||||||
} else this.url
|
} else {
|
||||||
|
this.url
|
||||||
|
}
|
||||||
return fixedSubUrl
|
return fixedSubUrl
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -147,4 +142,4 @@ class PlayerSubtitleHelper {
|
||||||
setSubStyle(it)
|
setSubStyle(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -9,8 +9,6 @@ import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLink
|
import com.lagradost.cloudstream3.utils.ExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
import com.lagradost.cloudstream3.utils.ExtractorLinkType
|
||||||
import com.lagradost.cloudstream3.utils.newExtractorLink
|
import com.lagradost.cloudstream3.utils.newExtractorLink
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import torrServer.TorrServer
|
import torrServer.TorrServer
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.ConnectException
|
import java.net.ConnectException
|
||||||
|
|
@ -34,14 +32,14 @@ object Torrent {
|
||||||
|
|
||||||
/** Returns true if the server is up */
|
/** Returns true if the server is up */
|
||||||
private suspend fun echo(): Boolean {
|
private suspend fun echo(): Boolean {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
app.get(
|
app.get(
|
||||||
"$TORRENT_SERVER_URL/echo",
|
"$TORRENT_SERVER_URL/echo",
|
||||||
).text.isNotEmpty()
|
).text.isNotEmpty()
|
||||||
} catch (_: ConnectException) {
|
} catch (e: ConnectException) {
|
||||||
// `Failed to connect to /127.0.0.1:8090` if the server is down
|
// `Failed to connect to /127.0.0.1:8090` if the server is down
|
||||||
false
|
false
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
|
|
@ -54,7 +52,7 @@ object Torrent {
|
||||||
/** Gracefully shutdown the server.
|
/** Gracefully shutdown the server.
|
||||||
* should not be used because I am unable to start it again, and the stopTorrentServer() crashes the app */
|
* should not be used because I am unable to start it again, and the stopTorrentServer() crashes the app */
|
||||||
suspend fun shutdown(): Boolean {
|
suspend fun shutdown(): Boolean {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
|
|
@ -70,7 +68,7 @@ object Torrent {
|
||||||
/** Lists all torrents by the server */
|
/** Lists all torrents by the server */
|
||||||
@Throws
|
@Throws
|
||||||
private suspend fun list(): Array<TorrentStatus> {
|
private suspend fun list(): Array<TorrentStatus> {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
throw ErrorLoadingException("Not initialized")
|
throw ErrorLoadingException("Not initialized")
|
||||||
}
|
}
|
||||||
return app.post(
|
return app.post(
|
||||||
|
|
@ -85,7 +83,7 @@ object Torrent {
|
||||||
|
|
||||||
/** Drops a single torrent, (I think) this means closing the stream. Returns returns if it is successful */
|
/** Drops a single torrent, (I think) this means closing the stream. Returns returns if it is successful */
|
||||||
private suspend fun drop(hash: String): Boolean {
|
private suspend fun drop(hash: String): Boolean {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
|
|
@ -106,7 +104,7 @@ object Torrent {
|
||||||
|
|
||||||
/** Removes a single torrent from the server registry */
|
/** Removes a single torrent from the server registry */
|
||||||
private suspend fun rem(hash: String): Boolean {
|
private suspend fun rem(hash: String): Boolean {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
|
|
@ -128,7 +126,7 @@ object Torrent {
|
||||||
|
|
||||||
/** Removes all torrents from the server, and returns if it is successful */
|
/** Removes all torrents from the server, and returns if it is successful */
|
||||||
suspend fun clearAll(): Boolean {
|
suspend fun clearAll(): Boolean {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
|
|
@ -166,8 +164,10 @@ object Torrent {
|
||||||
/** Gets all the metadata of a torrent, will throw if that hash does not exists
|
/** Gets all the metadata of a torrent, will throw if that hash does not exists
|
||||||
* https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L126 */
|
* https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L126 */
|
||||||
@Throws
|
@Throws
|
||||||
suspend fun get(hash: String): TorrentStatus {
|
suspend fun get(
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
hash: String,
|
||||||
|
): TorrentStatus {
|
||||||
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
throw ErrorLoadingException("Not initialized")
|
throw ErrorLoadingException("Not initialized")
|
||||||
}
|
}
|
||||||
return app.post(
|
return app.post(
|
||||||
|
|
@ -184,7 +184,7 @@ object Torrent {
|
||||||
/** Adds a torrent to the server, this is needed for us to get the hash for further modification, as well as start streaming it*/
|
/** Adds a torrent to the server, this is needed for us to get the hash for further modification, as well as start streaming it*/
|
||||||
@Throws
|
@Throws
|
||||||
private suspend fun add(url: String): TorrentStatus {
|
private suspend fun add(url: String): TorrentStatus {
|
||||||
if (TORRENT_SERVER_URL.isEmpty()) {
|
if(TORRENT_SERVER_URL.isEmpty()) {
|
||||||
throw ErrorLoadingException("Not initialized")
|
throw ErrorLoadingException("Not initialized")
|
||||||
}
|
}
|
||||||
return app.post(
|
return app.post(
|
||||||
|
|
@ -204,7 +204,7 @@ object Torrent {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
val port = TorrServer.startTorrentServer(dir, 0)
|
val port = TorrServer.startTorrentServer(dir, 0)
|
||||||
if (port < 0) {
|
if(port < 0) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
TORRENT_SERVER_URL = "http://127.0.0.1:$port"
|
TORRENT_SERVER_URL = "http://127.0.0.1:$port"
|
||||||
|
|
@ -278,55 +278,94 @@ object Torrent {
|
||||||
|
|
||||||
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L18
|
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L18
|
||||||
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/main/web/api/route.go#L7
|
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/main/web/api/route.go#L7
|
||||||
@Serializable
|
|
||||||
data class TorrentRequest(
|
data class TorrentRequest(
|
||||||
@JsonProperty("action") @SerialName("action") val action: String,
|
@JsonProperty("action")
|
||||||
@JsonProperty("hash") @SerialName("hash") val hash: String = "",
|
val action: String,
|
||||||
@JsonProperty("link") @SerialName("link") val link: String = "",
|
@JsonProperty("hash")
|
||||||
@JsonProperty("title") @SerialName("title") val title: String = "",
|
val hash: String = "",
|
||||||
@JsonProperty("poster") @SerialName("poster") val poster: String = "",
|
@JsonProperty("link")
|
||||||
@JsonProperty("data") @SerialName("data") val data: String = "",
|
val link: String = "",
|
||||||
@JsonProperty("save_to_db") @SerialName("save_to_db") val saveToDB: Boolean = false,
|
@JsonProperty("title")
|
||||||
|
val title: String = "",
|
||||||
|
@JsonProperty("poster")
|
||||||
|
val poster: String = "",
|
||||||
|
@JsonProperty("data")
|
||||||
|
val data: String = "",
|
||||||
|
@JsonProperty("save_to_db")
|
||||||
|
val saveToDB: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/torr/state/state.go#L33
|
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/torr/state/state.go#L33
|
||||||
// omitempty = nullable
|
// omitempty = nullable
|
||||||
@Serializable
|
|
||||||
data class TorrentStatus(
|
data class TorrentStatus(
|
||||||
@JsonProperty("title") @SerialName("title") var title: String,
|
@JsonProperty("title")
|
||||||
@JsonProperty("poster") @SerialName("poster") var poster: String,
|
var title: String,
|
||||||
@JsonProperty("data") @SerialName("data") var data: String?,
|
@JsonProperty("poster")
|
||||||
@JsonProperty("timestamp") @SerialName("timestamp") var timestamp: Long,
|
var poster: String,
|
||||||
@JsonProperty("name") @SerialName("name") var name: String?,
|
@JsonProperty("data")
|
||||||
@JsonProperty("hash") @SerialName("hash") var hash: String?,
|
var data: String?,
|
||||||
@JsonProperty("stat") @SerialName("stat") var stat: Int,
|
@JsonProperty("timestamp")
|
||||||
@JsonProperty("stat_string") @SerialName("stat_string") var statString: String,
|
var timestamp: Long,
|
||||||
@JsonProperty("loaded_size") @SerialName("loaded_size") var loadedSize: Long?,
|
@JsonProperty("name")
|
||||||
@JsonProperty("torrent_size") @SerialName("torrent_size") var torrentSize: Long?,
|
var name: String?,
|
||||||
@JsonProperty("preloaded_bytes") @SerialName("preloaded_bytes") var preloadedBytes: Long?,
|
@JsonProperty("hash")
|
||||||
@JsonProperty("preload_size") @SerialName("preload_size") var preloadSize: Long?,
|
var hash: String?,
|
||||||
@JsonProperty("download_speed") @SerialName("download_speed") var downloadSpeed: Double?,
|
@JsonProperty("stat")
|
||||||
@JsonProperty("upload_speed") @SerialName("upload_speed") var uploadSpeed: Double?,
|
var stat: Int,
|
||||||
@JsonProperty("total_peers") @SerialName("total_peers") var totalPeers: Int?,
|
@JsonProperty("stat_string")
|
||||||
@JsonProperty("pending_peers") @SerialName("pending_peers") var pendingPeers: Int?,
|
var statString: String,
|
||||||
@JsonProperty("active_peers") @SerialName("active_peers") var activePeers: Int?,
|
@JsonProperty("loaded_size")
|
||||||
@JsonProperty("connected_seeders") @SerialName("connected_seeders") var connectedSeeders: Int?,
|
var loadedSize: Long?,
|
||||||
@JsonProperty("half_open_peers") @SerialName("half_open_peers") var halfOpenPeers: Int?,
|
@JsonProperty("torrent_size")
|
||||||
@JsonProperty("bytes_written") @SerialName("bytes_written") var bytesWritten: Long?,
|
var torrentSize: Long?,
|
||||||
@JsonProperty("bytes_written_data") @SerialName("bytes_written_data") var bytesWrittenData: Long?,
|
@JsonProperty("preloaded_bytes")
|
||||||
@JsonProperty("bytes_read") @SerialName("bytes_read") var bytesRead: Long?,
|
var preloadedBytes: Long?,
|
||||||
@JsonProperty("bytes_read_data") @SerialName("bytes_read_data") var bytesReadData: Long?,
|
@JsonProperty("preload_size")
|
||||||
@JsonProperty("bytes_read_useful_data") @SerialName("bytes_read_useful_data") var bytesReadUsefulData: Long?,
|
var preloadSize: Long?,
|
||||||
@JsonProperty("chunks_written") @SerialName("chunks_written") var chunksWritten: Long?,
|
@JsonProperty("download_speed")
|
||||||
@JsonProperty("chunks_read") @SerialName("chunks_read") var chunksRead: Long?,
|
var downloadSpeed: Double?,
|
||||||
@JsonProperty("chunks_read_useful") @SerialName("chunks_read_useful") var chunksReadUseful: Long?,
|
@JsonProperty("upload_speed")
|
||||||
@JsonProperty("chunks_read_wasted") @SerialName("chunks_read_wasted") var chunksReadWasted: Long?,
|
var uploadSpeed: Double?,
|
||||||
@JsonProperty("pieces_dirtied_good") @SerialName("pieces_dirtied_good") var piecesDirtiedGood: Long?,
|
@JsonProperty("total_peers")
|
||||||
@JsonProperty("pieces_dirtied_bad") @SerialName("pieces_dirtied_bad") var piecesDirtiedBad: Long?,
|
var totalPeers: Int?,
|
||||||
@JsonProperty("duration_seconds") @SerialName("duration_seconds") var durationSeconds: Double?,
|
@JsonProperty("pending_peers")
|
||||||
@JsonProperty("bit_rate") @SerialName("bit_rate") var bitRate: String?,
|
var pendingPeers: Int?,
|
||||||
@JsonProperty("file_stats") @SerialName("file_stats") var fileStats: List<TorrentFileStat>?,
|
@JsonProperty("active_peers")
|
||||||
@JsonProperty("trackers") @SerialName("trackers") var trackers: List<String>?,
|
var activePeers: Int?,
|
||||||
|
@JsonProperty("connected_seeders")
|
||||||
|
var connectedSeeders: Int?,
|
||||||
|
@JsonProperty("half_open_peers")
|
||||||
|
var halfOpenPeers: Int?,
|
||||||
|
@JsonProperty("bytes_written")
|
||||||
|
var bytesWritten: Long?,
|
||||||
|
@JsonProperty("bytes_written_data")
|
||||||
|
var bytesWrittenData: Long?,
|
||||||
|
@JsonProperty("bytes_read")
|
||||||
|
var bytesRead: Long?,
|
||||||
|
@JsonProperty("bytes_read_data")
|
||||||
|
var bytesReadData: Long?,
|
||||||
|
@JsonProperty("bytes_read_useful_data")
|
||||||
|
var bytesReadUsefulData: Long?,
|
||||||
|
@JsonProperty("chunks_written")
|
||||||
|
var chunksWritten: Long?,
|
||||||
|
@JsonProperty("chunks_read")
|
||||||
|
var chunksRead: Long?,
|
||||||
|
@JsonProperty("chunks_read_useful")
|
||||||
|
var chunksReadUseful: Long?,
|
||||||
|
@JsonProperty("chunks_read_wasted")
|
||||||
|
var chunksReadWasted: Long?,
|
||||||
|
@JsonProperty("pieces_dirtied_good")
|
||||||
|
var piecesDirtiedGood: Long?,
|
||||||
|
@JsonProperty("pieces_dirtied_bad")
|
||||||
|
var piecesDirtiedBad: Long?,
|
||||||
|
@JsonProperty("duration_seconds")
|
||||||
|
var durationSeconds: Double?,
|
||||||
|
@JsonProperty("bit_rate")
|
||||||
|
var bitRate: String?,
|
||||||
|
@JsonProperty("file_stats")
|
||||||
|
var fileStats: List<TorrentFileStat>?,
|
||||||
|
@JsonProperty("trackers")
|
||||||
|
var trackers: List<String>?,
|
||||||
) {
|
) {
|
||||||
fun streamUrl(url: String): String {
|
fun streamUrl(url: String): String {
|
||||||
val fileName =
|
val fileName =
|
||||||
|
|
@ -342,10 +381,12 @@ object Torrent {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class TorrentFileStat(
|
data class TorrentFileStat(
|
||||||
@JsonProperty("id") @SerialName("id") val id: Int?,
|
@JsonProperty("id")
|
||||||
@JsonProperty("path") @SerialName("path") val path: String?,
|
val id: Int?,
|
||||||
@JsonProperty("length") @SerialName("length") val length: Long?,
|
@JsonProperty("path")
|
||||||
|
val path: String?,
|
||||||
|
@JsonProperty("length")
|
||||||
|
val length: Long?,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -12,16 +12,12 @@ import com.lagradost.cloudstream3.utils.txt
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
|
import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
|
||||||
import com.lagradost.cloudstream3.utils.ExtractorLink
|
import com.lagradost.cloudstream3.utils.ExtractorLink
|
||||||
import com.lagradost.cloudstream3.utils.Qualities
|
import com.lagradost.cloudstream3.utils.Qualities
|
||||||
import java.util.EnumMap
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import kotlin.also
|
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
object QualityDataHelper {
|
object QualityDataHelper {
|
||||||
private const val VIDEO_SOURCE_PRIORITY = "video_source_priority"
|
private const val VIDEO_SOURCE_PRIORITY = "video_source_priority"
|
||||||
private const val VIDEO_PROFILE_NAME = "video_profile_name"
|
private const val VIDEO_PROFILE_NAME = "video_profile_name"
|
||||||
private const val VIDEO_QUALITY_PRIORITY = "video_quality_priority"
|
private const val VIDEO_QUALITY_PRIORITY = "video_quality_priority"
|
||||||
const val VIDEO_PROFILE_SETTINGS = "video_profile_settings"
|
|
||||||
|
|
||||||
// Old key only supporting one type per profile
|
// Old key only supporting one type per profile
|
||||||
@Deprecated("Changed to support multiple types per profile")
|
@Deprecated("Changed to support multiple types per profile")
|
||||||
|
|
@ -57,21 +53,13 @@ object QualityDataHelper {
|
||||||
val types: Set<QualityProfileType>
|
val types: Set<QualityProfileType>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
// Map profile and name to priority
|
|
||||||
val sourcePriorityCache: ConcurrentHashMap<Int, HashMap<String, Int>> = ConcurrentHashMap()
|
|
||||||
|
|
||||||
fun getSourcePriority(profile: Int, name: String?): Int {
|
fun getSourcePriority(profile: Int, name: String?): Int {
|
||||||
if (name == null) return DEFAULT_SOURCE_PRIORITY
|
if (name == null) return DEFAULT_SOURCE_PRIORITY
|
||||||
|
return getKey(
|
||||||
return sourcePriorityCache[profile]?.get(name) ?: (getKey<Int>(
|
|
||||||
"$currentAccount/$VIDEO_SOURCE_PRIORITY/$profile",
|
"$currentAccount/$VIDEO_SOURCE_PRIORITY/$profile",
|
||||||
name,
|
name,
|
||||||
DEFAULT_SOURCE_PRIORITY
|
DEFAULT_SOURCE_PRIORITY
|
||||||
) ?: DEFAULT_SOURCE_PRIORITY).also {
|
) ?: DEFAULT_SOURCE_PRIORITY
|
||||||
sourcePriorityCache.getOrPut(profile) { hashMapOf() }
|
|
||||||
sourcePriorityCache[profile]?.set(name, it)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getAllSourcePriorityNames(profile: Int): List<String> {
|
fun getAllSourcePriorityNames(profile: Int): List<String> {
|
||||||
|
|
@ -89,8 +77,6 @@ object QualityDataHelper {
|
||||||
} else {
|
} else {
|
||||||
setKey(folder, name, priority)
|
setKey(folder, name, priority)
|
||||||
}
|
}
|
||||||
|
|
||||||
sourcePriorityCache[profile]?.set(name, priority)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setProfileName(profile: Int, name: String?) {
|
fun setProfileName(profile: Int, name: String?) {
|
||||||
|
|
@ -107,17 +93,12 @@ object QualityDataHelper {
|
||||||
?: txt(R.string.profile_number, profile)
|
?: txt(R.string.profile_number, profile)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map profile and quality to priority
|
|
||||||
val qualityPriorityCache: ConcurrentHashMap<Int, EnumMap<Qualities, Int>> = ConcurrentHashMap()
|
|
||||||
fun getQualityPriority(profile: Int, quality: Qualities): Int {
|
fun getQualityPriority(profile: Int, quality: Qualities): Int {
|
||||||
return qualityPriorityCache[profile]?.get(quality) ?: (getKey<Int>(
|
return getKey(
|
||||||
"$currentAccount/$VIDEO_QUALITY_PRIORITY/$profile",
|
"$currentAccount/$VIDEO_QUALITY_PRIORITY/$profile",
|
||||||
quality.value.toString(),
|
quality.value.toString(),
|
||||||
quality.defaultPriority
|
quality.defaultPriority
|
||||||
)?.also {
|
) ?: quality.defaultPriority
|
||||||
qualityPriorityCache.getOrPut(profile) { EnumMap(Qualities::class.java) }
|
|
||||||
qualityPriorityCache[profile]?.set(quality, it)
|
|
||||||
}) ?: quality.defaultPriority
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setQualityPriority(profile: Int, quality: Qualities, priority: Int) {
|
fun setQualityPriority(profile: Int, quality: Qualities, priority: Int) {
|
||||||
|
|
@ -126,24 +107,8 @@ object QualityDataHelper {
|
||||||
quality.value.toString(),
|
quality.value.toString(),
|
||||||
priority
|
priority
|
||||||
)
|
)
|
||||||
qualityPriorityCache[profile]?.set(quality, priority)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <T> setProfileSetting(profile: Int, setting: ProfileSettings<T>, value: T) {
|
|
||||||
val folder = "$currentAccount/$VIDEO_PROFILE_SETTINGS/$profile"
|
|
||||||
// Prevent unnecessary keys
|
|
||||||
if (value == setting.defaultValue) {
|
|
||||||
removeKey(folder, setting.key)
|
|
||||||
} else {
|
|
||||||
setKey(folder, setting.key, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inline fun <reified T : Any> getProfileSetting(profile: Int, setting: ProfileSettings<T>): T {
|
|
||||||
val folder = "$currentAccount/$VIDEO_PROFILE_SETTINGS/$profile"
|
|
||||||
val value = getKey<T>(folder, setting.key)
|
|
||||||
return value ?: setting.defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
fun getQualityProfileTypes(profile: Int): Set<QualityProfileType> {
|
fun getQualityProfileTypes(profile: Int): Set<QualityProfileType> {
|
||||||
|
|
@ -258,9 +223,4 @@ object QualityDataHelper {
|
||||||
if (target == null) return Qualities.Unknown
|
if (target == null) return Qualities.Unknown
|
||||||
return Qualities.entries.minBy { abs(it.value - target) }
|
return Qualities.entries.minBy { abs(it.value - target) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed class ProfileSettings<T>(val key: String, val defaultValue: T) {
|
|
||||||
object HideErrorSources : ProfileSettings<Boolean>("hide_error_sources", false)
|
|
||||||
object HideNegativeSources : ProfileSettings<Boolean>("hide_negative_sources", false)
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
package com.lagradost.cloudstream3.ui.player.source_priority
|
package com.lagradost.cloudstream3.ui.player.source_priority
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.app.Dialog
|
import android.app.Dialog
|
||||||
import androidx.annotation.StyleRes
|
import androidx.annotation.StyleRes
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
|
|
@ -27,7 +26,7 @@ data class LinkSource(
|
||||||
|
|
||||||
|
|
||||||
class QualityProfileDialog private constructor(
|
class QualityProfileDialog private constructor(
|
||||||
val activity: Activity,
|
val activity: FragmentActivity,
|
||||||
@StyleRes val themeRes: Int,
|
@StyleRes val themeRes: Int,
|
||||||
private val links: List<LinkSource>,
|
private val links: List<LinkSource>,
|
||||||
private val usedProfile: Int?,
|
private val usedProfile: Int?,
|
||||||
|
|
@ -35,7 +34,7 @@ class QualityProfileDialog private constructor(
|
||||||
private val useProfileSelection: Boolean
|
private val useProfileSelection: Boolean
|
||||||
) : Dialog(activity, themeRes) {
|
) : Dialog(activity, themeRes) {
|
||||||
constructor(
|
constructor(
|
||||||
activity: Activity,
|
activity: FragmentActivity,
|
||||||
@StyleRes themeRes: Int,
|
@StyleRes themeRes: Int,
|
||||||
links: List<LinkSource>,
|
links: List<LinkSource>,
|
||||||
usedProfile: Int,
|
usedProfile: Int,
|
||||||
|
|
@ -43,7 +42,7 @@ class QualityProfileDialog private constructor(
|
||||||
) : this(activity, themeRes, links, usedProfile, profileSelectionCallback, true)
|
) : this(activity, themeRes, links, usedProfile, profileSelectionCallback, true)
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
activity: Activity,
|
activity: FragmentActivity,
|
||||||
@StyleRes themeRes: Int,
|
@StyleRes themeRes: Int,
|
||||||
links: List<LinkSource>
|
links: List<LinkSource>
|
||||||
) : this(activity, themeRes, links, null, null, false)
|
) : this(activity, themeRes, links, null, null, false)
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
||||||
|
|
||||||
class SourcePriorityDialog(
|
class SourcePriorityDialog(
|
||||||
val ctx: Context,
|
val ctx: Context,
|
||||||
@StyleRes val themeRes: Int,
|
@StyleRes themeRes: Int,
|
||||||
val links: List<LinkSource>,
|
val links: List<LinkSource>,
|
||||||
private val profile: QualityDataHelper.QualityProfile,
|
private val profile: QualityDataHelper.QualityProfile,
|
||||||
/**
|
/**
|
||||||
|
|
@ -28,79 +28,76 @@ class SourcePriorityDialog(
|
||||||
PlayerSelectSourcePriorityBinding.inflate(LayoutInflater.from(ctx), null, false)
|
PlayerSelectSourcePriorityBinding.inflate(LayoutInflater.from(ctx), null, false)
|
||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
fixSystemBarsPadding(binding.root)
|
fixSystemBarsPadding(binding.root)
|
||||||
|
val sourcesRecyclerView = binding.sortSources
|
||||||
|
val qualitiesRecyclerView = binding.sortQualities
|
||||||
|
val profileText = binding.profileTextEditable
|
||||||
|
val saveBtt = binding.saveBtt
|
||||||
|
val exitBtt = binding.closeBtt
|
||||||
|
val helpBtt = binding.helpBtt
|
||||||
|
|
||||||
binding.apply {
|
profileText.setText(QualityDataHelper.getProfileName(profile.id).asString(context))
|
||||||
profileTextEditable.setText(
|
profileText.hint = txt(R.string.profile_number, profile.id).asString(context)
|
||||||
QualityDataHelper.getProfileName(profile.id).asString(context)
|
|
||||||
)
|
|
||||||
profileTextEditable.hint = txt(R.string.profile_number, profile.id).asString(context)
|
|
||||||
|
|
||||||
sortSources.adapter = PriorityAdapter<Nothing?>(
|
sourcesRecyclerView.adapter = PriorityAdapter<Nothing?>(
|
||||||
).apply {
|
).apply {
|
||||||
val sortedLinks = links.map { link ->
|
submitList(links.map { link ->
|
||||||
SourcePriority(
|
SourcePriority(
|
||||||
null,
|
null,
|
||||||
link.source,
|
link.source,
|
||||||
QualityDataHelper.getSourcePriority(profile.id, link.source)
|
QualityDataHelper.getSourcePriority(profile.id, link.source)
|
||||||
)
|
)
|
||||||
}.distinctBy { it.name }.sortedBy { -it.priority }
|
}.distinctBy { it.name }.sortedBy { -it.priority })
|
||||||
|
|
||||||
submitList(sortedLinks)
|
|
||||||
}
|
|
||||||
|
|
||||||
sortQualities.adapter = PriorityAdapter<Qualities>(
|
|
||||||
).apply {
|
|
||||||
submitList(Qualities.entries.mapNotNull {
|
|
||||||
SourcePriority(
|
|
||||||
it,
|
|
||||||
Qualities.getStringByIntFull(it.value).ifBlank { return@mapNotNull null },
|
|
||||||
QualityDataHelper.getQualityPriority(profile.id, it)
|
|
||||||
)
|
|
||||||
}.sortedBy { -it.priority })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST") // We know the types
|
|
||||||
saveBtt.setOnClickListener {
|
|
||||||
val qualityAdapter = sortQualities.adapter as? PriorityAdapter<Qualities>
|
|
||||||
val sourcesAdapter = sortSources.adapter as? PriorityAdapter<Nothing?>
|
|
||||||
|
|
||||||
val qualities = qualityAdapter?.immutableCurrentList ?: emptyList()
|
|
||||||
val sources = sourcesAdapter?.immutableCurrentList ?: emptyList()
|
|
||||||
|
|
||||||
qualities.forEach {
|
|
||||||
QualityDataHelper.setQualityPriority(profile.id, it.data, it.priority)
|
|
||||||
}
|
|
||||||
|
|
||||||
sources.forEach {
|
|
||||||
QualityDataHelper.setSourcePriority(profile.id, it.name, it.priority)
|
|
||||||
}
|
|
||||||
|
|
||||||
qualityAdapter?.submitList(qualities.sortedBy { -it.priority })
|
|
||||||
sourcesAdapter?.submitList(sources.sortedBy { -it.priority })
|
|
||||||
|
|
||||||
val savedProfileName = profileTextEditable.text.toString()
|
|
||||||
if (savedProfileName.isBlank()) {
|
|
||||||
QualityDataHelper.setProfileName(profile.id, null)
|
|
||||||
} else {
|
|
||||||
QualityDataHelper.setProfileName(profile.id, savedProfileName)
|
|
||||||
}
|
|
||||||
updatedCallback.invoke()
|
|
||||||
}
|
|
||||||
|
|
||||||
closeBtt.setOnClickListener {
|
|
||||||
dismissSafe()
|
|
||||||
}
|
|
||||||
|
|
||||||
helpBtt.setOnClickListener {
|
|
||||||
AlertDialog.Builder(context, R.style.AlertDialogCustom).apply {
|
|
||||||
setMessage(R.string.quality_profile_help)
|
|
||||||
}.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
settingsBtt.setOnClickListener {
|
|
||||||
SourceProfileSettingsDialog(ctx, themeRes, profile.id).show()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
qualitiesRecyclerView.adapter = PriorityAdapter<Qualities>(
|
||||||
|
).apply {
|
||||||
|
submitList(Qualities.entries.mapNotNull {
|
||||||
|
SourcePriority(
|
||||||
|
it,
|
||||||
|
Qualities.getStringByIntFull(it.value).ifBlank { return@mapNotNull null },
|
||||||
|
QualityDataHelper.getQualityPriority(profile.id, it)
|
||||||
|
)
|
||||||
|
}.sortedBy { -it.priority })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST") // We know the types
|
||||||
|
saveBtt.setOnClickListener {
|
||||||
|
val qualityAdapter = qualitiesRecyclerView.adapter as? PriorityAdapter<Qualities>
|
||||||
|
val sourcesAdapter = sourcesRecyclerView.adapter as? PriorityAdapter<Nothing?>
|
||||||
|
|
||||||
|
val qualities = qualityAdapter?.immutableCurrentList ?: emptyList()
|
||||||
|
val sources = sourcesAdapter?.immutableCurrentList ?: emptyList()
|
||||||
|
|
||||||
|
qualities.forEach {
|
||||||
|
QualityDataHelper.setQualityPriority(profile.id, it.data, it.priority)
|
||||||
|
}
|
||||||
|
|
||||||
|
sources.forEach {
|
||||||
|
QualityDataHelper.setSourcePriority(profile.id, it.name, it.priority)
|
||||||
|
}
|
||||||
|
|
||||||
|
qualityAdapter?.submitList(qualities.sortedBy { -it.priority })
|
||||||
|
sourcesAdapter?.submitList(sources.sortedBy { -it.priority })
|
||||||
|
|
||||||
|
val savedProfileName = profileText.text.toString()
|
||||||
|
if (savedProfileName.isBlank()) {
|
||||||
|
QualityDataHelper.setProfileName(profile.id, null)
|
||||||
|
} else {
|
||||||
|
QualityDataHelper.setProfileName(profile.id, savedProfileName)
|
||||||
|
}
|
||||||
|
updatedCallback.invoke()
|
||||||
|
}
|
||||||
|
|
||||||
|
exitBtt.setOnClickListener {
|
||||||
|
this.dismissSafe()
|
||||||
|
}
|
||||||
|
|
||||||
|
helpBtt.setOnClickListener {
|
||||||
|
AlertDialog.Builder(context, R.style.AlertDialogCustom).apply {
|
||||||
|
setMessage(R.string.quality_profile_help)
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
super.show()
|
super.show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.player.source_priority
|
|
||||||
|
|
||||||
import android.app.Dialog
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import androidx.annotation.StyleRes
|
|
||||||
import com.lagradost.cloudstream3.databinding.SourceProfileSettingsDialogBinding
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
|
|
||||||
|
|
||||||
class SourceProfileSettingsDialog(
|
|
||||||
val ctx: Context,
|
|
||||||
@StyleRes themeRes: Int,
|
|
||||||
val profile: Int
|
|
||||||
) : Dialog(ctx, themeRes) {
|
|
||||||
override fun show() {
|
|
||||||
val binding =
|
|
||||||
SourceProfileSettingsDialogBinding.inflate(LayoutInflater.from(ctx), null, false)
|
|
||||||
setContentView(binding.root)
|
|
||||||
fixSystemBarsPadding(binding.root)
|
|
||||||
|
|
||||||
binding.apply {
|
|
||||||
var hideErrorSources = QualityDataHelper.getProfileSetting(profile, ProfileSettings.HideErrorSources)
|
|
||||||
var hideNegativeSources = QualityDataHelper.getProfileSetting(profile, ProfileSettings.HideNegativeSources)
|
|
||||||
|
|
||||||
profileHideErrorSources.isChecked = hideErrorSources
|
|
||||||
profileHideErrorSources.setOnCheckedChangeListener { _, bool ->
|
|
||||||
hideErrorSources = bool
|
|
||||||
}
|
|
||||||
|
|
||||||
profileHideNegativeSources.isChecked = hideNegativeSources
|
|
||||||
profileHideNegativeSources.setOnCheckedChangeListener { _, bool ->
|
|
||||||
hideNegativeSources = bool
|
|
||||||
}
|
|
||||||
|
|
||||||
applyBtt.setOnClickListener {
|
|
||||||
QualityDataHelper.setProfileSetting(profile, ProfileSettings.HideErrorSources, hideErrorSources)
|
|
||||||
QualityDataHelper.setProfileSetting(profile, ProfileSettings.HideNegativeSources, hideNegativeSources)
|
|
||||||
dismissSafe()
|
|
||||||
}
|
|
||||||
|
|
||||||
cancelBtt.setOnClickListener {
|
|
||||||
dismissSafe()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
super.show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -5,9 +5,6 @@ import android.content.Intent
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.view.animation.Animation
|
|
||||||
import android.view.animation.OvershootInterpolator
|
|
||||||
import android.view.animation.ScaleAnimation
|
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
import com.lagradost.cloudstream3.ActorData
|
import com.lagradost.cloudstream3.ActorData
|
||||||
import com.lagradost.cloudstream3.ActorRole
|
import com.lagradost.cloudstream3.ActorRole
|
||||||
|
|
@ -49,24 +46,6 @@ class ActorAdaptor(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onUpdateContent(holder: ViewHolderState<Any>, item: ActorData, position: Int) {
|
|
||||||
when (val binding = holder.view) {
|
|
||||||
is CastItemBinding -> {
|
|
||||||
val anim: Animation = ScaleAnimation(
|
|
||||||
0.8f, 1f,
|
|
||||||
0.8f, 1f,
|
|
||||||
Animation.RELATIVE_TO_SELF, 0.5f,
|
|
||||||
Animation.RELATIVE_TO_SELF, 0.5f
|
|
||||||
)
|
|
||||||
anim.fillAfter = true
|
|
||||||
anim.duration = 200
|
|
||||||
anim.interpolator = OvershootInterpolator()
|
|
||||||
binding.voiceActorImageHolder2.startAnimation(anim)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
super.onUpdateContent(holder, item, position)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindContent(holder: ViewHolderState<Any>, item: ActorData, position: Int) {
|
override fun onBindContent(holder: ViewHolderState<Any>, item: ActorData, position: Int) {
|
||||||
when (val binding = holder.view) {
|
when (val binding = holder.view) {
|
||||||
is CastItemBinding -> {
|
is CastItemBinding -> {
|
||||||
|
|
@ -158,4 +137,4 @@ class ActorAdaptor(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -21,8 +21,6 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
|
||||||
import com.lagradost.cloudstream3.utils.Event
|
import com.lagradost.cloudstream3.utils.Event
|
||||||
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
|
||||||
import com.lagradost.cloudstream3.utils.UiImage
|
import com.lagradost.cloudstream3.utils.UiImage
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
const val START_ACTION_RESUME_LATEST = 1
|
const val START_ACTION_RESUME_LATEST = 1
|
||||||
const val START_ACTION_LOAD_EP = 2
|
const val START_ACTION_LOAD_EP = 2
|
||||||
|
|
@ -36,32 +34,33 @@ enum class VideoWatchState {
|
||||||
Watched
|
Watched
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class ResultEpisode(
|
data class ResultEpisode(
|
||||||
@SerialName("headerName") val headerName: String,
|
val headerName: String,
|
||||||
@SerialName("name") val name: String?,
|
val name: String?,
|
||||||
@SerialName("poster") val poster: String?,
|
val poster: String?,
|
||||||
@SerialName("episode") val episode: Int,
|
val episode: Int,
|
||||||
@SerialName("seasonIndex") val seasonIndex: Int?, // this is the "season" index used season names
|
val seasonIndex: Int?, // this is the "season" index used season names
|
||||||
@SerialName("season") val season: Int?, // this is the display
|
val season: Int?, // this is the display
|
||||||
@SerialName("data") val data: String,
|
val data: String,
|
||||||
@SerialName("apiName") val apiName: String,
|
val apiName: String,
|
||||||
@SerialName("id") val id: Int,
|
val id: Int,
|
||||||
@SerialName("index") val index: Int,
|
val index: Int,
|
||||||
@SerialName("position") val position: Long, // time in MS
|
val position: Long, // time in MS
|
||||||
@SerialName("duration") val duration: Long, // duration in MS
|
val duration: Long, // duration in MS
|
||||||
@SerialName("score") val score: Score?,
|
val score: Score?,
|
||||||
@SerialName("description") val description: String?,
|
val description: String?,
|
||||||
@SerialName("isFiller") val isFiller: Boolean?,
|
val isFiller: Boolean?,
|
||||||
@SerialName("tvType") val tvType: TvType,
|
val tvType: TvType,
|
||||||
@SerialName("parentId") val parentId: Int,
|
val parentId: Int,
|
||||||
/** Conveys if the episode itself is marked as watched. */
|
/**
|
||||||
@SerialName("videoWatchState") val videoWatchState: VideoWatchState,
|
* Conveys if the episode itself is marked as watched
|
||||||
/** Sum of all previous season episode counts + episode. */
|
**/
|
||||||
@SerialName("totalEpisodeIndex") val totalEpisodeIndex: Int? = null,
|
val videoWatchState: VideoWatchState,
|
||||||
@SerialName("airDate") val airDate: Long? = null,
|
/** Sum of all previous season episode counts + episode */
|
||||||
@SerialName("runTime") val runTime: Int? = null,
|
val totalEpisodeIndex: Int? = null,
|
||||||
@SerialName("seasonData") val seasonData: SeasonData? = null,
|
val airDate: Long? = null,
|
||||||
|
val runTime: Int? = null,
|
||||||
|
val seasonData: SeasonData? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun ResultEpisode.getRealPosition(): Long {
|
fun ResultEpisode.getRealPosition(): Long {
|
||||||
|
|
|
||||||
|
|
@ -874,9 +874,10 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
|
||||||
resultMetaRating.setText(d.ratingText)
|
resultMetaRating.setText(d.ratingText)
|
||||||
resultMetaStatus.setText(d.onGoingText)
|
resultMetaStatus.setText(d.onGoingText)
|
||||||
resultMetaContentRating.setText(d.contentRatingText)
|
resultMetaContentRating.setText(d.contentRatingText)
|
||||||
|
resultCastText.setText(d.actorsText)
|
||||||
resultNextAiring.setText(d.nextAiringEpisode)
|
resultNextAiring.setText(d.nextAiringEpisode)
|
||||||
resultNextAiringTime.setText(d.nextAiringDate)
|
resultNextAiringTime.setText(d.nextAiringDate)
|
||||||
resultPoster.loadImage(d.posterImage, headers = d.posterHeaders)
|
resultPoster.loadImage(d.posterImage)
|
||||||
|
|
||||||
var isExpanded = false
|
var isExpanded = false
|
||||||
resultDescription.apply {
|
resultDescription.apply {
|
||||||
|
|
@ -909,7 +910,7 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
|
||||||
R.drawable.profile_bg_teal
|
R.drawable.profile_bg_teal
|
||||||
).random()
|
).random()
|
||||||
|
|
||||||
backgroundPoster.loadImage(d.posterBackgroundImage, headers = d.posterHeaders) {
|
backgroundPoster.loadImage(d.posterBackgroundImage) {
|
||||||
error { getImageFromDrawable(context ?: return@error null, error) }
|
error { getImageFromDrawable(context ?: return@error null, error) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -931,7 +932,6 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
|
||||||
true
|
true
|
||||||
)
|
)
|
||||||
|
|
||||||
resultCastText.setText(if (showCast) d.actorsText else null)
|
|
||||||
resultCastItems.isGone = !showCast || d.actors.isNullOrEmpty()
|
resultCastItems.isGone = !showCast || d.actors.isNullOrEmpty()
|
||||||
(resultCastItems.adapter as? ActorAdaptor)?.submitList(if (showCast) d.actors else emptyList())
|
(resultCastItems.adapter as? ActorAdaptor)?.submitList(if (showCast) d.actors else emptyList())
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -83,7 +83,6 @@ import com.lagradost.cloudstream3.utils.AppContextUtils.getNameFull
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.isConnectedToChromecast
|
import com.lagradost.cloudstream3.utils.AppContextUtils.isConnectedToChromecast
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
|
||||||
import com.lagradost.cloudstream3.utils.AppUtils.toJson
|
|
||||||
import com.lagradost.cloudstream3.utils.CastHelper.startCast
|
import com.lagradost.cloudstream3.utils.CastHelper.startCast
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioWork
|
import com.lagradost.cloudstream3.utils.Coroutines.ioWork
|
||||||
|
|
@ -1325,7 +1324,7 @@ class ResultViewModel2 : ViewModel() {
|
||||||
episodeIds: Array<String>,
|
episodeIds: Array<String>,
|
||||||
watchState: VideoWatchState
|
watchState: VideoWatchState
|
||||||
) {
|
) {
|
||||||
val watchStateString = watchState.toJson()
|
val watchStateString = DataStore.mapper.writeValueAsString(watchState)
|
||||||
episodeIds.forEach {
|
episodeIds.forEach {
|
||||||
if (getVideoWatchState(it.toInt()) != watchState) {
|
if (getVideoWatchState(it.toInt()) != watchState) {
|
||||||
editor.setKeyRaw(
|
editor.setKeyRaw(
|
||||||
|
|
@ -1686,13 +1685,14 @@ class ResultViewModel2 : ViewModel() {
|
||||||
}
|
}
|
||||||
|
|
||||||
val realRecommendations = ArrayList<SearchResponse>()
|
val realRecommendations = ArrayList<SearchResponse>()
|
||||||
val apiNames = apis.filter {
|
val apiNames = synchronized(apis) {
|
||||||
it.name.contains("gogoanime", true) ||
|
apis.filter {
|
||||||
it.name.contains("9anime", true)
|
it.name.contains("gogoanime", true) ||
|
||||||
}.map {
|
it.name.contains("9anime", true)
|
||||||
it.name
|
}.map {
|
||||||
|
it.name
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
meta.recommendations?.forEach { rec ->
|
meta.recommendations?.forEach { rec ->
|
||||||
apiNames.forEach { name ->
|
apiNames.forEach { name ->
|
||||||
realRecommendations.add(rec.copy(apiName = name))
|
realRecommendations.add(rec.copy(apiName = name))
|
||||||
|
|
@ -2706,4 +2706,4 @@ class ResultViewModel2 : ViewModel() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -182,7 +182,6 @@ class SyncViewModel : ViewModel() {
|
||||||
fun publishUserData() = ioSafe {
|
fun publishUserData() = ioSafe {
|
||||||
Log.i(TAG, "publishUserData")
|
Log.i(TAG, "publishUserData")
|
||||||
val user = userData.value
|
val user = userData.value
|
||||||
_userDataResponse.postValue(Resource.Loading())
|
|
||||||
if (user is Resource.Success) {
|
if (user is Resource.Success) {
|
||||||
syncs.forEach { (prefix, id) ->
|
syncs.forEach { (prefix, id) ->
|
||||||
repos.firstOrNull { it.idPrefix == prefix }?.updateStatus(id, user.value)
|
repos.firstOrNull { it.idPrefix == prefix }?.updateStatus(id, user.value)
|
||||||
|
|
|
||||||
|
|
@ -149,7 +149,6 @@ class SearchFragment : BaseFragment<FragmentSearchBinding>(
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
searchViewModel.clearSuggestions()
|
|
||||||
afterPluginsLoadedEvent += ::reloadRepos
|
afterPluginsLoadedEvent += ::reloadRepos
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -168,7 +167,6 @@ class SearchFragment : BaseFragment<FragmentSearchBinding>(
|
||||||
**/
|
**/
|
||||||
fun search(query: String?) {
|
fun search(query: String?) {
|
||||||
if (query == null) return
|
if (query == null) return
|
||||||
searchViewModel.clearSuggestions()
|
|
||||||
// don't resume state from prev search
|
// don't resume state from prev search
|
||||||
(binding?.searchMasterRecycler?.adapter as? BaseAdapter<*, *>)?.clearState()
|
(binding?.searchMasterRecycler?.adapter as? BaseAdapter<*, *>)?.clearState()
|
||||||
context?.let { ctx ->
|
context?.let { ctx ->
|
||||||
|
|
|
||||||
|
|
@ -13,15 +13,12 @@ import com.lagradost.cloudstream3.ui.ViewHolderState
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
|
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class SearchHistoryItem(
|
data class SearchHistoryItem(
|
||||||
@JsonProperty("searchedAt") @SerialName("searchedAt") val searchedAt: Long,
|
@JsonProperty("searchedAt") val searchedAt: Long,
|
||||||
@JsonProperty("searchText") @SerialName("searchText") val searchText: String,
|
@JsonProperty("searchText") val searchText: String,
|
||||||
@JsonProperty("type") @SerialName("type") val type: List<TvType>,
|
@JsonProperty("type") val type: List<TvType>,
|
||||||
@JsonProperty("key") @SerialName("key") val key: String,
|
@JsonProperty("key") val key: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class SearchHistoryCallback(
|
data class SearchHistoryCallback(
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,6 @@ import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.app
|
import com.lagradost.cloudstream3.app
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.nicehttp.NiceResponse
|
import com.lagradost.nicehttp.NiceResponse
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* API for fetching search suggestions from external sources.
|
* API for fetching search suggestions from external sources.
|
||||||
|
|
@ -15,18 +13,16 @@ object SearchSuggestionApi {
|
||||||
private const val TMDB_API_URL = "https://api.themoviedb.org/3/search/multi"
|
private const val TMDB_API_URL = "https://api.themoviedb.org/3/search/multi"
|
||||||
private const val TMDB_API_KEY = "e6333b32409e02a4a6eba6fb7ff866bb"
|
private const val TMDB_API_KEY = "e6333b32409e02a4a6eba6fb7ff866bb"
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class TmdbSearchResult(
|
data class TmdbSearchResult(
|
||||||
@JsonProperty("results") @SerialName("results") val results: List<TmdbSearchItem>?,
|
@JsonProperty("results") val results: List<TmdbSearchItem>?
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class TmdbSearchItem(
|
data class TmdbSearchItem(
|
||||||
@JsonProperty("media_type") @SerialName("media_type") val mediaType: String?,
|
@JsonProperty("media_type") val mediaType: String?,
|
||||||
@JsonProperty("title") @SerialName("title") val title: String?,
|
@JsonProperty("title") val title: String?,
|
||||||
@JsonProperty("name") @SerialName("name") val name: String?,
|
@JsonProperty("name") val name: String?,
|
||||||
@JsonProperty("original_title") @SerialName("original_title") val originalTitle: String?,
|
@JsonProperty("original_title") val originalTitle: String?,
|
||||||
@JsonProperty("original_name") @SerialName("original_name") val originalName: String?,
|
@JsonProperty("original_name") val originalName: String?
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -61,7 +57,7 @@ object SearchSuggestionApi {
|
||||||
* Parses the TMDB search response and extracts movie/TV show titles.
|
* Parses the TMDB search response and extracts movie/TV show titles.
|
||||||
* Filters to only include movies, TV shows, and anime.
|
* Filters to only include movies, TV shows, and anime.
|
||||||
*/
|
*/
|
||||||
private suspend fun parseSuggestions(response: NiceResponse): List<String> {
|
private fun parseSuggestions(response: NiceResponse): List<String> {
|
||||||
return try {
|
return try {
|
||||||
val parsed = response.parsed<TmdbSearchResult>()
|
val parsed = response.parsed<TmdbSearchResult>()
|
||||||
parsed.results
|
parsed.results
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@ class SearchViewModel : ViewModel() {
|
||||||
|
|
||||||
private var suggestionJob: Job? = null
|
private var suggestionJob: Job? = null
|
||||||
|
|
||||||
private var repos = apis.withLock { apis.map { APIRepository(it) } }
|
private var repos = synchronized(apis) { apis.map { APIRepository(it) } }
|
||||||
|
|
||||||
fun clearSearch() {
|
fun clearSearch() {
|
||||||
_searchResponse.postValue(Resource.Success(ExpandableSearchList(emptyList(), 0, false)))
|
_searchResponse.postValue(Resource.Success(ExpandableSearchList(emptyList(), 0, false)))
|
||||||
|
|
@ -68,7 +68,7 @@ class SearchViewModel : ViewModel() {
|
||||||
private var onGoingSearch: Job? = null
|
private var onGoingSearch: Job? = null
|
||||||
|
|
||||||
fun reloadRepos() {
|
fun reloadRepos() {
|
||||||
repos = apis.withLock { apis.map { APIRepository(it) } }
|
repos = synchronized(apis) { apis.map { APIRepository(it) } }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun searchAndCancel(
|
fun searchAndCancel(
|
||||||
|
|
|
||||||
|
|
@ -1,274 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.app.Activity
|
|
||||||
import android.app.PendingIntent
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageInstaller
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.core.content.FileProvider
|
|
||||||
import com.lagradost.cloudstream3.BuildConfig
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity
|
|
||||||
import com.lagradost.cloudstream3.ErrorLoadingException
|
|
||||||
import com.lagradost.cloudstream3.MainActivity.Companion.deleteFileOnExit
|
|
||||||
import com.lagradost.cloudstream3.app
|
|
||||||
import com.lagradost.cloudstream3.mvvm.safe
|
|
||||||
import com.lagradost.cloudstream3.receivers.PackageInstallerStatusReceiver
|
|
||||||
import com.lagradost.cloudstream4.AppSettings
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.AppUpdater
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.DigestPair
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.currentCoroutineContext
|
|
||||||
import kotlinx.coroutines.ensureActive
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import java.io.File
|
|
||||||
import java.io.InputStream
|
|
||||||
import java.io.OutputStream
|
|
||||||
import java.security.DigestException
|
|
||||||
import java.security.MessageDigest
|
|
||||||
|
|
||||||
object ApkUpdater : AppUpdater {
|
|
||||||
private const val APP_UPDATE_NAME = "CloudStream"
|
|
||||||
private const val APP_UPDATE_SUFFIX = "apk"
|
|
||||||
|
|
||||||
@Throws
|
|
||||||
override suspend fun update(
|
|
||||||
settings: AppSettings,
|
|
||||||
url: String,
|
|
||||||
digest: DigestPair?,
|
|
||||||
downloadProgress: (Long, Long?) -> Unit
|
|
||||||
) {
|
|
||||||
val activity = CommonActivity.activity ?: throw ErrorLoadingException("No activity found")
|
|
||||||
clearOldFiles(activity)
|
|
||||||
|
|
||||||
val request = app.get(url)
|
|
||||||
val length = request.size
|
|
||||||
val body = request.body
|
|
||||||
body.use { body ->
|
|
||||||
val length = length ?: body.contentLength()
|
|
||||||
val readStream = body.byteStream()
|
|
||||||
|
|
||||||
when (settings.updates.apkInstaller.get()) {
|
|
||||||
0 -> {
|
|
||||||
packageInstallerDownloader(
|
|
||||||
activity,
|
|
||||||
readStream,
|
|
||||||
length,
|
|
||||||
digest,
|
|
||||||
downloadProgress
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
legacyDownloader(activity, readStream, length, digest, downloadProgress)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clearOldFiles(activity: Activity) {
|
|
||||||
// Delete old files
|
|
||||||
activity.cacheDir.listFiles()?.filter {
|
|
||||||
it.name.startsWith(APP_UPDATE_NAME) && it.extension == APP_UPDATE_SUFFIX
|
|
||||||
}?.forEach {
|
|
||||||
deleteFileOnExit(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** https://medium.com/@solrudev/painless-building-of-an-android-package-installer-app-d5a09b5df432 */
|
|
||||||
@SuppressLint("RequestInstallPackagesPolicy")
|
|
||||||
@Throws
|
|
||||||
suspend fun packageInstallerDownloader(
|
|
||||||
activity: Activity,
|
|
||||||
readStream: InputStream,
|
|
||||||
length: Long?,
|
|
||||||
digest: DigestPair?,
|
|
||||||
downloadProgress: (Long, Long?) -> Unit,
|
|
||||||
) = withContext(Dispatchers.IO) {
|
|
||||||
var sessionId: Int? = null
|
|
||||||
val packageInstaller = activity.packageManager.packageInstaller
|
|
||||||
try {
|
|
||||||
val installParams =
|
|
||||||
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
|
|
||||||
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
||||||
installParams.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
|
|
||||||
}
|
|
||||||
if (length != null) {
|
|
||||||
installParams.setSize(length)
|
|
||||||
}
|
|
||||||
|
|
||||||
sessionId = packageInstaller.createSession(installParams)
|
|
||||||
val session = packageInstaller.openSession(sessionId)
|
|
||||||
|
|
||||||
// We do not need to buffer this because transfer has large writes
|
|
||||||
session.openWrite(activity.packageName, 0, length ?: -1L)
|
|
||||||
.use { writeStream ->
|
|
||||||
transfer(writeStream, readStream, length, downloadProgress, digest)
|
|
||||||
session.fsync(writeStream)
|
|
||||||
}
|
|
||||||
|
|
||||||
val receiverIntent = Intent(activity, PackageInstallerStatusReceiver::class.java)
|
|
||||||
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
||||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
|
||||||
} else {
|
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT
|
|
||||||
}
|
|
||||||
val receiverPendingIntent =
|
|
||||||
PendingIntent.getBroadcast(activity, 0, receiverIntent, flags)
|
|
||||||
|
|
||||||
// Avoid delayed updates, and just commit instantly
|
|
||||||
session.commit(receiverPendingIntent.intentSender)
|
|
||||||
session.close()
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
sessionId?.let { sessionId ->
|
|
||||||
packageInstaller.abandonSession(sessionId)
|
|
||||||
}
|
|
||||||
throw t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Write the "readStream" to the "writeStream", while notifying the "downloadProgress" and
|
|
||||||
* calculating the digest
|
|
||||||
*
|
|
||||||
* ------------------------------------------------------------------------------------------
|
|
||||||
*
|
|
||||||
* throws a DigestException if the Digest can be calculated (non-null + correct algorithm),
|
|
||||||
* and is mismatched
|
|
||||||
*
|
|
||||||
* throws a CancellationException if canceled, but may not be "instant" if the read is blocking
|
|
||||||
*
|
|
||||||
* throws IOException and similar for reading
|
|
||||||
*
|
|
||||||
* ------------------------------------------------------------------------------------------
|
|
||||||
*
|
|
||||||
* In case of crashes from the digest, we ignore it as we do not want to "block" someone from
|
|
||||||
* updating if they got a broken OS without the desired algorithm or implementation.
|
|
||||||
*
|
|
||||||
* This is because a malicious CDN should not be able to "crash" the algorithm, but a broken
|
|
||||||
* OS will. And recovering from a broken OS by ignoring it is better than refusing it.
|
|
||||||
* */
|
|
||||||
@Throws
|
|
||||||
suspend fun transfer(
|
|
||||||
writeStream: OutputStream,
|
|
||||||
readStream: InputStream,
|
|
||||||
length: Long?,
|
|
||||||
downloadProgress: (Long, Long?) -> Unit,
|
|
||||||
digest: DigestPair?,
|
|
||||||
) = withContext(Dispatchers.IO) {
|
|
||||||
val md = digest?.algorithm?.let { digestAlgorithm ->
|
|
||||||
safe {
|
|
||||||
MessageDigest.getInstance(digestAlgorithm)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val context = currentCoroutineContext()
|
|
||||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
|
||||||
var read: Int
|
|
||||||
var transferred: Long = 0
|
|
||||||
while ((readStream.read(buffer, 0, DEFAULT_BUFFER_SIZE)
|
|
||||||
.also { read = it }) >= 0
|
|
||||||
) {
|
|
||||||
writeStream.write(buffer, 0, read)
|
|
||||||
|
|
||||||
safe {
|
|
||||||
md?.update(buffer, 0, read)
|
|
||||||
}
|
|
||||||
|
|
||||||
transferred += read.toLong()
|
|
||||||
downloadProgress(transferred, length)
|
|
||||||
context.ensureActive()
|
|
||||||
}
|
|
||||||
writeStream.flush()
|
|
||||||
|
|
||||||
val check = safe { md?.digest() }
|
|
||||||
if (check != null && !check.contentEquals(digest?.digest)) {
|
|
||||||
throw DigestException("Mismatched digest on transfer ${digest?.algorithm} : ${check.toHexString()} / ${digest?.digest?.toHexString()}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if we have a non-null digest that matches a digest on the specified existing file
|
|
||||||
* */
|
|
||||||
suspend fun isFileDigest(file: File, digest: DigestPair?): Boolean {
|
|
||||||
if (digest == null) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
val fileDigest = calculateDigest(
|
|
||||||
digestAlgorithm = digest.algorithm,
|
|
||||||
readStream = file.inputStream()
|
|
||||||
)
|
|
||||||
return fileDigest != null && digest.digest.contentEquals(fileDigest)
|
|
||||||
} catch (_: Throwable) {
|
|
||||||
// File not found/security/read issues, not very useful errors
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculates the digest of a stream with the specified algorithm, use transfer instead if
|
|
||||||
* you already download something.
|
|
||||||
*
|
|
||||||
* Will throw read errors
|
|
||||||
* Will return null if the algorithm is null or does not exist/has some error
|
|
||||||
* */
|
|
||||||
@Throws
|
|
||||||
suspend fun calculateDigest(digestAlgorithm: String?, readStream: InputStream) =
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
if (digestAlgorithm == null) return@withContext null
|
|
||||||
|
|
||||||
val md =
|
|
||||||
safe {
|
|
||||||
MessageDigest.getInstance(digestAlgorithm)
|
|
||||||
} ?: return@withContext null
|
|
||||||
|
|
||||||
val context = currentCoroutineContext()
|
|
||||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
|
||||||
var read: Int
|
|
||||||
while ((readStream.read(buffer, 0, DEFAULT_BUFFER_SIZE)
|
|
||||||
.also { read = it }) >= 0
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
md.update(buffer, 0, read)
|
|
||||||
} catch (_: Throwable) {
|
|
||||||
return@withContext null
|
|
||||||
}
|
|
||||||
context.ensureActive()
|
|
||||||
}
|
|
||||||
return@withContext safe { md.digest() }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Throws
|
|
||||||
suspend fun legacyDownloader(
|
|
||||||
activity: Activity,
|
|
||||||
readStream: InputStream,
|
|
||||||
length: Long?,
|
|
||||||
digest: DigestPair?,
|
|
||||||
downloadProgress: (Long, Long?) -> Unit
|
|
||||||
) = withContext(Dispatchers.IO) {
|
|
||||||
val downloadedFile = File.createTempFile(APP_UPDATE_NAME, ".$APP_UPDATE_SUFFIX")
|
|
||||||
|
|
||||||
// We do not need to buffer this because transfer has large writes
|
|
||||||
downloadedFile.outputStream().use { writeStream ->
|
|
||||||
transfer(writeStream, readStream, length, downloadProgress, digest)
|
|
||||||
}
|
|
||||||
|
|
||||||
openApk(activity, downloadedFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun openApk(context: Context, file: File) {
|
|
||||||
val contentUri = FileProvider.getUriForFile(
|
|
||||||
context, BuildConfig.APPLICATION_ID + ".provider", file
|
|
||||||
)
|
|
||||||
val installIntent = Intent(Intent.ACTION_VIEW).apply {
|
|
||||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
|
||||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
|
||||||
putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
|
|
||||||
data = contentUri
|
|
||||||
}
|
|
||||||
context.startActivity(installIntent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,106 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
|
||||||
import com.lagradost.cloudstream3.app
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubFile
|
|
||||||
import com.lagradost.cloudstream4.viewmodels.GithubRepository
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import java.io.FileNotFoundException
|
|
||||||
|
|
||||||
object GithubReleases : GithubRepository {
|
|
||||||
@Serializable
|
|
||||||
private data class GithubAsset(
|
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
|
||||||
@JsonProperty("size") @SerialName("size") val size: Int, // Size in bytes
|
|
||||||
@JsonProperty("browser_download_url") @SerialName("browser_download_url") val browserDownloadUrl: String,
|
|
||||||
@JsonProperty("content_type") @SerialName("content_type") val contentType: String, // application/vnd.android.package-archive
|
|
||||||
@JsonProperty("digest") @SerialName("digest") val digest: String? = null, // sha256:..., may be null
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
private data class GithubRelease(
|
|
||||||
@JsonProperty("tag_name") @SerialName("tag_name") val tagName: String, // Version code
|
|
||||||
@JsonProperty("body") @SerialName("body") val body: String, // Description
|
|
||||||
@JsonProperty("assets") @SerialName("assets") val assets: List<GithubAsset>,
|
|
||||||
@JsonProperty("target_commitish") @SerialName("target_commitish") val targetCommitish: String, // Branch
|
|
||||||
@JsonProperty("prerelease") @SerialName("prerelease") val prerelease: Boolean,
|
|
||||||
@JsonProperty("node_id") @SerialName("node_id") val nodeId: String,
|
|
||||||
@JsonProperty("created_at") @SerialName("created_at") val createdAt: String, // YYYY-MM-DDTHH:MM:SSZ
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
private data class GithubObject(
|
|
||||||
@JsonProperty("sha") @SerialName("sha") val sha: String, // SHA-256 hash
|
|
||||||
//@JsonProperty("type") @SerialName("type") val type: String,
|
|
||||||
///@JsonProperty("url") @SerialName("url") val url: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
private data class GithubTag(
|
|
||||||
//@JsonProperty("node_id") @SerialName("node_id") val nodeId: String,
|
|
||||||
@JsonProperty("object") @SerialName("object") val githubObject: GithubObject,
|
|
||||||
)
|
|
||||||
|
|
||||||
const val APK_USERNAME = "recloudstream"
|
|
||||||
const val APK_REPOSITORY = "cloudstream"
|
|
||||||
const val APK_PRERELEASE = "pre-release"
|
|
||||||
const val APK_CONTENT_TYPE = "application/vnd.android.package-archive"
|
|
||||||
|
|
||||||
private val defaultHeaders = mapOf("Accept" to "application/vnd.github.v3+json")
|
|
||||||
|
|
||||||
@Throws
|
|
||||||
override suspend fun getSha(
|
|
||||||
userName: String,
|
|
||||||
repository: String,
|
|
||||||
tag: String,
|
|
||||||
): String {
|
|
||||||
return app.get(
|
|
||||||
url = "https://api.github.com/repos/$userName/$repository/git/ref/tags/$tag",
|
|
||||||
headers = defaultHeaders
|
|
||||||
).parsed<GithubTag>().githubObject.sha
|
|
||||||
}
|
|
||||||
|
|
||||||
@Throws
|
|
||||||
override suspend fun getRelease(
|
|
||||||
userName: String,
|
|
||||||
repository: String,
|
|
||||||
prerelease: Boolean,
|
|
||||||
prereleaseTag: String,
|
|
||||||
contentType: String,
|
|
||||||
): GithubFile {
|
|
||||||
val latestReleaseUrl = if (prerelease) {
|
|
||||||
// Find the release object
|
|
||||||
// https://docs.github.com/en/rest/releases/releases?apiVersion=2026-03-10#get-a-release-by-tag-name
|
|
||||||
"https://api.github.com/repos/$userName/$repository/releases/tags/$prereleaseTag"
|
|
||||||
} else {
|
|
||||||
// Just get the latest release
|
|
||||||
// https://docs.github.com/en/rest/releases/releases?apiVersion=2026-03-10#get-the-latest-release
|
|
||||||
// The latest release is the most recent non-prerelease, non-draft release, sorted by the created_at attribute
|
|
||||||
"https://api.github.com/repos/$userName/$repository/releases/latest"
|
|
||||||
}
|
|
||||||
|
|
||||||
val latestRelease = app.get(
|
|
||||||
url = latestReleaseUrl,
|
|
||||||
headers = defaultHeaders
|
|
||||||
).parsed<GithubRelease>()
|
|
||||||
|
|
||||||
// Find the first correct asset, given that we might have other binaries we release in the same version
|
|
||||||
val foundAsset = latestRelease.assets.firstOrNull { asset ->
|
|
||||||
asset.contentType == contentType
|
|
||||||
}
|
|
||||||
|
|
||||||
if (foundAsset == null) {
|
|
||||||
throw FileNotFoundException()
|
|
||||||
}
|
|
||||||
|
|
||||||
return GithubFile(
|
|
||||||
digest = foundAsset.digest,
|
|
||||||
downloadUrl = foundAsset.browserDownloadUrl,
|
|
||||||
displayName = foundAsset.name.substringBeforeLast("."),
|
|
||||||
changeLog = latestRelease.body,
|
|
||||||
tagName = latestRelease.tagName,
|
|
||||||
nodeId = latestRelease.nodeId
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +1,19 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
package com.lagradost.cloudstream3.ui.settings
|
||||||
|
|
||||||
|
import android.app.UiModeManager
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import android.content.res.Resources
|
import android.content.res.Resources
|
||||||
|
import android.os.Build
|
||||||
import androidx.preference.PreferenceManager
|
import androidx.preference.PreferenceManager
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
import com.lagradost.cloudstream4.compose.DeviceLayout.Companion.isAutoTv
|
|
||||||
|
|
||||||
object Globals {
|
object Globals {
|
||||||
var beneneCount = 0
|
var beneneCount = 0
|
||||||
|
|
||||||
const val PHONE: Int = 0b00001
|
const val PHONE : Int = 0b001
|
||||||
const val TV: Int = 0b00010
|
const val TV : Int = 0b010
|
||||||
const val EMULATOR: Int = 0b00100
|
const val EMULATOR : Int = 0b100
|
||||||
private const val INVALID = -1
|
private const val INVALID = -1
|
||||||
private var layoutId = INVALID
|
private var layoutId = INVALID
|
||||||
|
|
||||||
|
|
@ -21,9 +22,18 @@ object Globals {
|
||||||
return settingsManager.getInt(this.getString(R.string.app_layout_key), -1)
|
return settingsManager.getInt(this.getString(R.string.app_layout_key), -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Context.updateTv() {
|
private fun Context.isAutoTv(): Boolean {
|
||||||
layoutId = when (getLayoutInt()) {
|
val uiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager?
|
||||||
-1 -> if (isAutoTv(this)) TV else PHONE
|
// AFT = Fire TV
|
||||||
|
val model = Build.MODEL.lowercase()
|
||||||
|
return uiModeManager?.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION || Build.MODEL.contains(
|
||||||
|
"AFT"
|
||||||
|
) || model.contains("firestick") || model.contains("fire tv") || model.contains("chromecast")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Context.layoutIntCorrected(): Int {
|
||||||
|
return when(getLayoutInt()) {
|
||||||
|
-1 -> if (isAutoTv()) TV else PHONE
|
||||||
0 -> PHONE
|
0 -> PHONE
|
||||||
1 -> TV
|
1 -> TV
|
||||||
2 -> EMULATOR
|
2 -> EMULATOR
|
||||||
|
|
@ -31,10 +41,14 @@ object Globals {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun Context.updateTv() {
|
||||||
|
layoutId = layoutIntCorrected()
|
||||||
|
}
|
||||||
|
|
||||||
/** Returns true if the current orientation is landscape. */
|
/** Returns true if the current orientation is landscape. */
|
||||||
fun isLandscape(): Boolean =
|
fun isLandscape(): Boolean =
|
||||||
isLayout(TV or EMULATOR) ||
|
isLayout(TV or EMULATOR) ||
|
||||||
Resources.getSystem().configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
|
Resources.getSystem().configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||||
|
|
||||||
/** Returns true if the layout is any of the flags,
|
/** Returns true if the layout is any of the flags,
|
||||||
* so isLayout(TV or EMULATOR) is a valid statement for checking if the layout is in the emulator
|
* so isLayout(TV or EMULATOR) is a valid statement for checking if the layout is in the emulator
|
||||||
|
|
@ -42,7 +56,7 @@ object Globals {
|
||||||
*
|
*
|
||||||
* Valid flags are: PHONE, TV, EMULATOR
|
* Valid flags are: PHONE, TV, EMULATOR
|
||||||
* */
|
* */
|
||||||
fun isLayout(flags: Int): Boolean {
|
fun isLayout(flags: Int) : Boolean {
|
||||||
return (layoutId and flags) != 0
|
return (layoutId and flags) != 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
package com.lagradost.cloudstream3.ui.settings
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.app.Activity
|
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.CountDownTimer
|
import android.os.CountDownTimer
|
||||||
|
|
@ -14,6 +13,7 @@ import androidx.appcompat.app.AlertDialog
|
||||||
import androidx.core.content.edit
|
import androidx.core.content.edit
|
||||||
import androidx.core.view.isGone
|
import androidx.core.view.isGone
|
||||||
import androidx.core.view.isVisible
|
import androidx.core.view.isVisible
|
||||||
|
import androidx.fragment.app.FragmentActivity
|
||||||
import androidx.preference.PreferenceManager
|
import androidx.preference.PreferenceManager
|
||||||
import androidx.preference.SwitchPreference
|
import androidx.preference.SwitchPreference
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
|
@ -29,8 +29,8 @@ import com.lagradost.cloudstream3.databinding.DeviceAuthBinding
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
import com.lagradost.cloudstream3.mvvm.logError
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.animeSkipApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.animeSkipApi
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
|
||||||
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.openSubtitlesApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.openSubtitlesApi
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.simklApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.simklApi
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.subDlApi
|
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.subDlApi
|
||||||
|
|
@ -42,8 +42,8 @@ import com.lagradost.cloudstream3.syncproviders.SubtitleRepo
|
||||||
import com.lagradost.cloudstream3.syncproviders.SyncRepo
|
import com.lagradost.cloudstream3.syncproviders.SyncRepo
|
||||||
import com.lagradost.cloudstream3.ui.BasePreferenceFragmentCompat
|
import com.lagradost.cloudstream3.ui.BasePreferenceFragmentCompat
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
|
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
import com.lagradost.cloudstream3.ui.settings.Globals.TV
|
||||||
|
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
|
||||||
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.getPref
|
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.getPref
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.hideOn
|
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.hideOn
|
||||||
|
|
@ -65,8 +65,6 @@ import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialogTe
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
|
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
|
import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.hideProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.showProgress
|
|
||||||
import com.lagradost.cloudstream3.utils.setText
|
import com.lagradost.cloudstream3.utils.setText
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
import com.lagradost.cloudstream3.utils.txt
|
||||||
import qrcode.QRCode
|
import qrcode.QRCode
|
||||||
|
|
@ -76,7 +74,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
/** Used by nginx plugin too */
|
/** Used by nginx plugin too */
|
||||||
@SuppressLint("StringFormatInvalid")
|
@SuppressLint("StringFormatInvalid")
|
||||||
fun showLoginInfo(
|
fun showLoginInfo(
|
||||||
activity: Activity?,
|
activity: FragmentActivity?,
|
||||||
api: AuthRepo,
|
api: AuthRepo,
|
||||||
info: AuthUser?,
|
info: AuthUser?,
|
||||||
index: Int,
|
index: Int,
|
||||||
|
|
@ -121,7 +119,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun showAccountSwitch(activity: Activity, api: AuthRepo) {
|
private fun showAccountSwitch(activity: FragmentActivity, api: AuthRepo) {
|
||||||
val accounts = api.accounts
|
val accounts = api.accounts
|
||||||
val binding: AccountSwitchBinding =
|
val binding: AccountSwitchBinding =
|
||||||
AccountSwitchBinding.inflate(activity.layoutInflater, null, false)
|
AccountSwitchBinding.inflate(activity.layoutInflater, null, false)
|
||||||
|
|
@ -153,7 +151,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
|
|
||||||
|
|
||||||
@UiThread
|
@UiThread
|
||||||
fun showPin(activity: Activity, api: AuthRepo) {
|
fun showPin(activity: FragmentActivity, api: AuthRepo) {
|
||||||
val binding: DeviceAuthBinding =
|
val binding: DeviceAuthBinding =
|
||||||
DeviceAuthBinding.inflate(activity.layoutInflater, null, false)
|
DeviceAuthBinding.inflate(activity.layoutInflater, null, false)
|
||||||
|
|
||||||
|
|
@ -273,7 +271,8 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fun showAppLogin(activity: Activity, api: AuthRepo) {
|
fun showAppLogin(activity: FragmentActivity, api: AuthRepo) {
|
||||||
|
|
||||||
val binding: AddAccountInputBinding =
|
val binding: AddAccountInputBinding =
|
||||||
AddAccountInputBinding.inflate(activity.layoutInflater, null, false)
|
AddAccountInputBinding.inflate(activity.layoutInflater, null, false)
|
||||||
val builder =
|
val builder =
|
||||||
|
|
@ -314,7 +313,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
binding.createAccount.setOnClickListener {
|
binding.createAccount.setOnClickListener {
|
||||||
openBrowser(
|
openBrowser(
|
||||||
api.createAccountUrl ?: return@setOnClickListener,
|
api.createAccountUrl ?: return@setOnClickListener,
|
||||||
activity,
|
activity
|
||||||
)
|
)
|
||||||
dialog.dismissSafe()
|
dialog.dismissSafe()
|
||||||
}
|
}
|
||||||
|
|
@ -349,7 +348,6 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
email = if (req.email) binding.loginEmailInput.text?.toString() else null,
|
email = if (req.email) binding.loginEmailInput.text?.toString() else null,
|
||||||
server = if (req.server) binding.loginServerInput.text?.toString() else null,
|
server = if (req.server) binding.loginServerInput.text?.toString() else null,
|
||||||
)
|
)
|
||||||
binding.applyBtt.showProgress()
|
|
||||||
ioSafe {
|
ioSafe {
|
||||||
try {
|
try {
|
||||||
if (api.login(loginData)) {
|
if (api.login(loginData)) {
|
||||||
|
|
@ -379,8 +377,6 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
api.name
|
api.name
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
} finally {
|
|
||||||
binding.applyBtt.hideProgress()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -390,7 +386,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
|
||||||
}
|
}
|
||||||
|
|
||||||
@UiThread
|
@UiThread
|
||||||
fun addAccount(activity: Activity, api: AuthRepo) {
|
fun addAccount(activity: FragmentActivity, api: AuthRepo) {
|
||||||
try {
|
try {
|
||||||
if (api.hasPin && !isLayout(PHONE)) {
|
if (api.hasPin && !isLayout(PHONE)) {
|
||||||
showPin(activity, api)
|
showPin(activity, api)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import com.lagradost.cloudstream3.utils.BaseComposeFragment
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
|
|
||||||
/** Empty glue code to connect the old navigation graph to Compose */
|
|
||||||
class SettingsAccount2 : BaseComposeFragment(), SearchableSettings by SettingsAccountScreen
|
|
||||||
|
|
@ -1,148 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import androidx.activity.compose.LocalActivity
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.fragment.app.FragmentActivity
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.activity
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.animeSkipApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.openSubtitlesApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.simklApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.subDlApi
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.PlainAuthRepo
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.SubtitleRepo
|
|
||||||
import com.lagradost.cloudstream3.syncproviders.SyncRepo
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsAccount.Companion.addAccount
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsAccount.Companion.showLoginInfo
|
|
||||||
import com.lagradost.cloudstream3.utils.AppContextUtils.html
|
|
||||||
import com.lagradost.cloudstream3.utils.BackupUtils
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.authCallback
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.biometricPrompt
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.deviceHasPasswordPinLock
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.isAuthEnabled
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.promptInfo
|
|
||||||
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.startBiometricAuthentication
|
|
||||||
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialogText
|
|
||||||
import com.lagradost.cloudstream4.AppSettings
|
|
||||||
import com.lagradost.cloudstream4.compose.PHONE
|
|
||||||
import com.lagradost.cloudstream4.compose.isLayout
|
|
||||||
import com.lagradost.cloudstream4.rememberAppSettings
|
|
||||||
import com.mihon.presentation.settings.Preference
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
import kotlinx.collections.immutable.persistentListOf
|
|
||||||
|
|
||||||
object SettingsAccountScreen : SearchableSettings, BiometricAuthenticator.BiometricCallback {
|
|
||||||
val syncApis = persistentListOf(
|
|
||||||
SyncRepo(malApi),
|
|
||||||
SyncRepo(kitsuApi),
|
|
||||||
SyncRepo(aniListApi),
|
|
||||||
SyncRepo(simklApi),
|
|
||||||
SubtitleRepo(openSubtitlesApi),
|
|
||||||
SubtitleRepo(subDlApi),
|
|
||||||
PlainAuthRepo(animeSkipApi),
|
|
||||||
)
|
|
||||||
private fun updateAuthPreference(context: Context, enabled: Boolean) {
|
|
||||||
val settings = AppSettings(context)
|
|
||||||
settings.security.biometrics.set(enabled)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAuthenticationError() {
|
|
||||||
val context = activity ?: return
|
|
||||||
updateAuthPreference(context, !isAuthEnabled(context))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAuthenticationSuccess() {
|
|
||||||
val context = activity ?: return
|
|
||||||
|
|
||||||
if (isAuthEnabled(context)) {
|
|
||||||
updateAuthPreference(context, true)
|
|
||||||
BackupUtils.backup(context)
|
|
||||||
context.showBottomDialogText(
|
|
||||||
context.getString(R.string.biometric_setting),
|
|
||||||
context.getString(R.string.biometric_warning).html()
|
|
||||||
) { onDialogDismissedEvent }
|
|
||||||
} else {
|
|
||||||
updateAuthPreference(context, false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
override fun getTitleRes(): String = stringResource(R.string.category_account)
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
override fun getPreferences(): List<Preference> {
|
|
||||||
val settings = rememberAppSettings()
|
|
||||||
val activity = LocalActivity.current
|
|
||||||
val context = LocalContext.current
|
|
||||||
val hasSecurity = remember(context) {
|
|
||||||
try {
|
|
||||||
deviceHasPasswordPinLock(context)
|
|
||||||
} catch (_ : Throwable) {
|
|
||||||
// e.g preview
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return persistentListOf(
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_accounts),
|
|
||||||
preferenceItems = syncApis.map { api ->
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = api.name,
|
|
||||||
icon = api.icon?.let { painterResource(it) },
|
|
||||||
onClick = {
|
|
||||||
val activity = activity ?: return@TextPreference
|
|
||||||
val info = api.authUser()
|
|
||||||
val index =
|
|
||||||
api.accounts.indexOfFirst { account -> account.user.id == info?.id }
|
|
||||||
if (api.accounts.isNotEmpty()) {
|
|
||||||
showLoginInfo(activity, api, info, index)
|
|
||||||
} else {
|
|
||||||
addAccount(activity, api)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
} + Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.security.skipAccountSelection,
|
|
||||||
title = stringResource(R.string.skip_startup_account_select_pref),
|
|
||||||
icon = painterResource(R.drawable.ic_outline_account_circle_24)
|
|
||||||
),
|
|
||||||
), Preference.PreferenceGroup(
|
|
||||||
enabled = hasSecurity && isLayout(PHONE),
|
|
||||||
title = stringResource(R.string.pref_category_security),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.security.biometrics,
|
|
||||||
title = stringResource(R.string.biometric_setting),
|
|
||||||
subtitle = stringResource(R.string.biometric_setting_summary),
|
|
||||||
icon = painterResource(R.drawable.ic_fingerprint),
|
|
||||||
onValueChanged = { _ ->
|
|
||||||
val activity =
|
|
||||||
activity as? FragmentActivity ?: return@SwitchPreference false
|
|
||||||
|
|
||||||
if (deviceHasPasswordPinLock(activity)) {
|
|
||||||
startBiometricAuthentication(
|
|
||||||
activity, R.string.biometric_authentication_title, false
|
|
||||||
)
|
|
||||||
promptInfo?.let {
|
|
||||||
authCallback = this
|
|
||||||
biometricPrompt?.authenticate(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return@SwitchPreference true
|
|
||||||
})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -249,7 +249,7 @@ class SettingsFragment : BaseFragment<MainSettingsBinding>(
|
||||||
|
|
||||||
val appVersion = BuildConfig.VERSION_NAME
|
val appVersion = BuildConfig.VERSION_NAME
|
||||||
val commitHash = activity?.currentCommitHash() ?: ""
|
val commitHash = activity?.currentCommitHash() ?: ""
|
||||||
val buildTimestamp = SimpleDateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
|
val buildTimestamp = SimpleDateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
|
||||||
Locale.getDefault()
|
Locale.getDefault()
|
||||||
).apply { timeZone = TimeZone.getTimeZone("UTC")
|
).apply { timeZone = TimeZone.getTimeZone("UTC")
|
||||||
}.format(Date(BuildConfig.BUILD_DATE)).replace("UTC", "")
|
}.format(Date(BuildConfig.BUILD_DATE)).replace("UTC", "")
|
||||||
|
|
@ -262,4 +262,4 @@ class SettingsFragment : BaseFragment<MainSettingsBinding>(
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import com.lagradost.cloudstream3.utils.BaseComposeFragment
|
|
||||||
import com.lagradost.cloudstream4.compose.Screen
|
|
||||||
|
|
||||||
|
|
||||||
/** Empty glue code to connect the old navigation graph to Compose */
|
|
||||||
class SettingsFragment2 : BaseComposeFragment(), Screen by SettingsFragmentScreen
|
|
||||||
|
|
@ -1,478 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.compose.animation.Crossfade
|
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.width
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.foundation.text.input.TextFieldLineLimits
|
|
||||||
import androidx.compose.foundation.text.input.TextFieldState
|
|
||||||
import androidx.compose.foundation.text.input.rememberTextFieldState
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
|
||||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.IconButton
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.ProvideTextStyle
|
|
||||||
import androidx.compose.material3.Scaffold
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.material3.TextField
|
|
||||||
import androidx.compose.material3.TextFieldDefaults
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.DisposableEffect
|
|
||||||
import androidx.compose.runtime.Immutable
|
|
||||||
import androidx.compose.runtime.NonRestartableComposable
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.input.key.Key
|
|
||||||
import androidx.compose.ui.input.key.KeyEventType
|
|
||||||
import androidx.compose.ui.input.key.key
|
|
||||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
|
||||||
import androidx.compose.ui.input.key.type
|
|
||||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
|
||||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
|
||||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.platform.LocalFocusManager
|
|
||||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
|
||||||
import androidx.compose.ui.tooling.preview.PreviewLightDark
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import coil3.compose.AsyncImage
|
|
||||||
import com.lagradost.cloudstream3.BuildConfig
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.activity
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper
|
|
||||||
import com.lagradost.cloudstream3.utils.DataStoreHelper.profileImages
|
|
||||||
import com.lagradost.cloudstream3.utils.GitInfo.currentCommitHash
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
|
|
||||||
import com.lagradost.cloudstream3.utils.UIHelper.navigate
|
|
||||||
import com.lagradost.cloudstream3.utils.txt
|
|
||||||
import com.lagradost.cloudstream4.compose.Screen
|
|
||||||
import com.lagradost.cloudstream4.compose.TV
|
|
||||||
import com.lagradost.cloudstream4.compose.circleBorder
|
|
||||||
import com.lagradost.cloudstream4.compose.focusOutline
|
|
||||||
import com.lagradost.cloudstream4.compose.isLayout
|
|
||||||
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
|
|
||||||
import com.mihon.material.padding
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
import com.mihon.presentation.settings.SettingSearchResults
|
|
||||||
import com.mihon.presentation.settings.SettingsData
|
|
||||||
import com.mihon.presentation.settings.widget.TextPreferenceWidget
|
|
||||||
import kotlinx.collections.immutable.PersistentList
|
|
||||||
import kotlinx.collections.immutable.persistentListOf
|
|
||||||
import kotlinx.collections.immutable.toPersistentList
|
|
||||||
import java.text.DateFormat
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
import java.util.TimeZone
|
|
||||||
|
|
||||||
object SettingsFragmentScreen : Screen {
|
|
||||||
val screens = persistentListOf(
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.category_general,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_general,
|
|
||||||
screen = SettingsGeneralScreen,
|
|
||||||
icon = R.drawable.build_24px,
|
|
||||||
subtitle = persistentListOf(
|
|
||||||
R.string.extension_language,
|
|
||||||
R.string.title_downloads,
|
|
||||||
R.string.pref_category_bypass,
|
|
||||||
R.string.pref_category_links
|
|
||||||
)
|
|
||||||
),
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.category_player,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_player,
|
|
||||||
screen = SettingsPlayerScreen,
|
|
||||||
icon = R.drawable.play_arrow_24px,
|
|
||||||
subtitle = persistentListOf(
|
|
||||||
R.string.pref_category_subtitles,
|
|
||||||
R.string.pref_category_player_features,
|
|
||||||
R.string.pref_category_gestures,
|
|
||||||
R.string.pref_category_player_layout,
|
|
||||||
R.string.pref_category_cache
|
|
||||||
)
|
|
||||||
),
|
|
||||||
/*SettingsNavigation(
|
|
||||||
title = R.string.category_providers,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_providers,
|
|
||||||
screen = SettingsProvidersScreen,
|
|
||||||
icon = R.drawable.build_24px,
|
|
||||||
),*/
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.category_ui,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_ui,
|
|
||||||
screen = SettingsUIScreen,
|
|
||||||
icon = R.drawable.format_paint_24px,
|
|
||||||
subtitle = persistentListOf(
|
|
||||||
R.string.pref_category_looks,
|
|
||||||
R.string.pref_category_ui_features,
|
|
||||||
R.string.search_poster_img_des,
|
|
||||||
R.string.poster_ui_settings
|
|
||||||
)
|
|
||||||
),
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.category_updates,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_updates,
|
|
||||||
screen = SettingsUpdatesScreen,
|
|
||||||
icon = R.drawable.mobile_arrow_down_24px,
|
|
||||||
subtitle = persistentListOf(
|
|
||||||
R.string.pref_category_app_updates,
|
|
||||||
R.string.pref_category_backup,
|
|
||||||
R.string.pref_category_extensions,
|
|
||||||
R.string.pref_category_actions
|
|
||||||
)
|
|
||||||
),
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.category_account,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_account,
|
|
||||||
screen = SettingsAccountScreen,
|
|
||||||
icon = R.drawable.encrypted_24px,
|
|
||||||
subtitle = persistentListOf(
|
|
||||||
R.string.pref_category_accounts,
|
|
||||||
R.string.pref_category_security
|
|
||||||
)
|
|
||||||
),
|
|
||||||
SettingsNavigation(
|
|
||||||
title = R.string.pref_category_extensions,
|
|
||||||
navigation = R.id.action_navigation_global_to_navigation_settings_extensions,
|
|
||||||
screen = null,
|
|
||||||
icon = R.drawable.extension_24px,
|
|
||||||
subtitle = persistentListOf(R.string.add_repository)
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
@Immutable
|
|
||||||
data class SettingsNavigation(
|
|
||||||
val title: Int,
|
|
||||||
val navigation: Int,
|
|
||||||
val screen: SearchableSettings?,
|
|
||||||
val icon: Int,
|
|
||||||
val subtitle: PersistentList<Int>,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
|
||||||
@Composable
|
|
||||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
|
||||||
override fun Content() {
|
|
||||||
val textFieldState = rememberTextFieldState()
|
|
||||||
|
|
||||||
val outerListState = rememberScrollState()
|
|
||||||
|
|
||||||
val parentFirstScrollConnection = remember {
|
|
||||||
object : NestedScrollConnection {
|
|
||||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
|
||||||
val delta = available.y
|
|
||||||
return if (delta < 0 && outerListState.canScrollForward) {
|
|
||||||
val consumed = outerListState.dispatchRawDelta(-delta)
|
|
||||||
Offset(0f, -consumed)
|
|
||||||
} else {
|
|
||||||
Offset.Zero
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Scaffold { _ ->
|
|
||||||
Column(modifier = Modifier.verticalScroll(outerListState)) {
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
|
|
||||||
|
|
||||||
val default = DataStoreHelper.getDefaultAccount(
|
|
||||||
LocalContext.current
|
|
||||||
)
|
|
||||||
val flow by DataStoreHelper.selectedAccountNumberFlow.collectAsState()
|
|
||||||
val account = remember(flow) {
|
|
||||||
DataStoreHelper.getCurrentAccount() ?: default
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.focusOutline()
|
|
||||||
.clickable {
|
|
||||||
activity.navigate(
|
|
||||||
R.id.accountSelectActivity,
|
|
||||||
Bundle().apply { putBoolean("isFromMainActivity", true) }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.padding(
|
|
||||||
vertical = MaterialTheme.padding.large,
|
|
||||||
horizontal = MaterialTheme.padding.medium
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
val image =
|
|
||||||
account.customImage ?: profileImages.getOrNull(account.defaultImageIndex)
|
|
||||||
?: profileImages.first()
|
|
||||||
|
|
||||||
AsyncImage(
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
model = image,
|
|
||||||
modifier = Modifier.circleBorder(50.dp),
|
|
||||||
contentDescription = null,
|
|
||||||
)
|
|
||||||
Spacer(modifier = Modifier.width(MaterialTheme.padding.medium))
|
|
||||||
Column {
|
|
||||||
Text(
|
|
||||||
text = account.name,
|
|
||||||
style = MaterialTheme.typography.titleLarge,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.title_settings),
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
|
|
||||||
SettingsSearch(textFieldState = textFieldState)
|
|
||||||
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
|
|
||||||
|
|
||||||
SettingSearchResults(
|
|
||||||
nestedScrollConnection = parentFirstScrollConnection,
|
|
||||||
searchKey = textFieldState.text.toString(),
|
|
||||||
deferredItems = ::generateSearchItems,
|
|
||||||
onItemClick = { item ->
|
|
||||||
SearchableSettings.highlightKey = item.highlightKey
|
|
||||||
activity?.navigate(item.navigation)
|
|
||||||
}, empty = {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.nestedScroll(parentFirstScrollConnection)
|
|
||||||
) {
|
|
||||||
screens.forEach { settingsTab ->
|
|
||||||
SettingsTab(settingsTab)
|
|
||||||
}
|
|
||||||
BuildStamp()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
@NonRestartableComposable
|
|
||||||
fun generateSearchItems() =
|
|
||||||
screens.mapNotNull { item ->
|
|
||||||
val contents = item.screen?.getPreferences() ?: return@mapNotNull null
|
|
||||||
SettingsData(
|
|
||||||
title = stringResource(item.title),
|
|
||||||
navigation = item.navigation,
|
|
||||||
contents = contents
|
|
||||||
)
|
|
||||||
}.toPersistentList()
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
|
||||||
@Composable
|
|
||||||
fun SettingsSearch(textFieldState: TextFieldState) {
|
|
||||||
var hasFocus by remember { mutableStateOf(false) }
|
|
||||||
var isWritable by remember { mutableStateOf(false) }
|
|
||||||
val focusProgress by animateFloatAsState(targetValue = if (hasFocus) 1.0f else 0.0f)
|
|
||||||
val focusManager = LocalFocusManager.current
|
|
||||||
val focusRequester = remember { FocusRequester() }
|
|
||||||
val isTv = isLayout(TV)
|
|
||||||
TextField(
|
|
||||||
state = textFieldState,
|
|
||||||
keyboardOptions = KeyboardOptions.Default.copy(
|
|
||||||
imeAction = ImeAction.Search,
|
|
||||||
/**
|
|
||||||
* We do not want to pull up the keyboard when navigating to the item on TV, therefore
|
|
||||||
* we listen to when the TV user presses some key to "extra" focus it
|
|
||||||
*
|
|
||||||
* showKeyboardOnFocus is somewhat bugged, so need to change this to true when you
|
|
||||||
* press it, as otherwise no keyboard will show even with keyboardController
|
|
||||||
* */
|
|
||||||
showKeyboardOnFocus = if (isTv) isWritable else true
|
|
||||||
),
|
|
||||||
lineLimits = TextFieldLineLimits.SingleLine,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 24.dp - 12.dp * focusProgress)
|
|
||||||
.focusOutline(enabled = isTv, CircleShape)
|
|
||||||
.onFocusChanged { newFocus ->
|
|
||||||
hasFocus = newFocus.hasFocus
|
|
||||||
/** Loss of focus -> readonly */
|
|
||||||
if (!newFocus.hasFocus) {
|
|
||||||
isWritable = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.focusRequester(focusRequester)
|
|
||||||
.onPreviewKeyEvent { keyEvent ->
|
|
||||||
if (isWritable || !isTv || !hasFocus || keyEvent.type != KeyEventType.KeyUp) {
|
|
||||||
return@onPreviewKeyEvent false
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Focus + press once -> writable */
|
|
||||||
return@onPreviewKeyEvent when (keyEvent.key) {
|
|
||||||
Key.Enter, Key.DirectionCenter, Key.NumPadEnter, Key.Spacebar -> {
|
|
||||||
isWritable = true
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
placeholder = {
|
|
||||||
Text(text = stringResource(R.string.search_hint))
|
|
||||||
},
|
|
||||||
shape = CircleShape,
|
|
||||||
colors = TextFieldDefaults.colors(
|
|
||||||
focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
|
|
||||||
unfocusedLeadingIconColor = MaterialTheme.colorScheme.onBackground,
|
|
||||||
unfocusedTrailingIconColor = MaterialTheme.colorScheme.onBackground,
|
|
||||||
focusedTrailingIconColor = MaterialTheme.colorScheme.onBackground,
|
|
||||||
focusedLeadingIconColor = MaterialTheme.colorScheme.onBackground,
|
|
||||||
focusedIndicatorColor = Color.Transparent,
|
|
||||||
unfocusedIndicatorColor = Color.Transparent,
|
|
||||||
focusedPlaceholderColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
unfocusedPlaceholderColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
cursorColor = MaterialTheme.colorScheme.onBackground,
|
|
||||||
),
|
|
||||||
leadingIcon = {
|
|
||||||
Crossfade(
|
|
||||||
targetState = hasFocus,
|
|
||||||
label = "leftsearch",
|
|
||||||
) { value ->
|
|
||||||
if (value) {
|
|
||||||
IconButton(onClick = {
|
|
||||||
textFieldState.edit { replace(0, length, "") }
|
|
||||||
focusManager.clearFocus()
|
|
||||||
}) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.keyboard_arrow_left_24px),
|
|
||||||
contentDescription = null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
IconButton(onClick = {
|
|
||||||
focusRequester.requestFocus()
|
|
||||||
}) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.search_icon),
|
|
||||||
contentDescription = null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
trailingIcon = {
|
|
||||||
Crossfade(
|
|
||||||
targetState = hasFocus,
|
|
||||||
label = "rightsearch",
|
|
||||||
) { value ->
|
|
||||||
if (value) {
|
|
||||||
IconButton(onClick = {
|
|
||||||
textFieldState.edit { replace(0, length, "") }
|
|
||||||
}) {
|
|
||||||
Icon(
|
|
||||||
painter = painterResource(R.drawable.close_24px),
|
|
||||||
contentDescription = null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
val keyboardController = LocalSoftwareKeyboardController.current
|
|
||||||
DisposableEffect(Unit) {
|
|
||||||
onDispose {
|
|
||||||
keyboardController?.hide()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun SettingsTab(settingsTab: SettingsNavigation) {
|
|
||||||
TextPreferenceWidget(
|
|
||||||
title = stringResource(settingsTab.title),
|
|
||||||
icon = painterResource(settingsTab.icon),
|
|
||||||
// This can not be converted to joinToString due to stringResource being composable
|
|
||||||
subtitle =
|
|
||||||
@Suppress("SimplifiableCallChain")
|
|
||||||
settingsTab.subtitle.map { stringResource(it) }.joinToString(),
|
|
||||||
// Clear it if we have already set it but navigated back instantly
|
|
||||||
onPreferenceClick = {
|
|
||||||
SearchableSettings.highlightKey = null
|
|
||||||
activity?.navigate(settingsTab.navigation)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun BuildStamp() {
|
|
||||||
val (commitHash, buildTimestamp) = remember {
|
|
||||||
val commitHash = activity?.currentCommitHash() ?: ""
|
|
||||||
val buildTimestamp = SimpleDateFormat.getDateTimeInstance(
|
|
||||||
DateFormat.LONG, DateFormat.MEDIUM,
|
|
||||||
Locale.getDefault()
|
|
||||||
).apply {
|
|
||||||
timeZone = TimeZone.getTimeZone("UTC")
|
|
||||||
}.format(Date(BuildConfig.BUILD_DATE)).replace("UTC", "")
|
|
||||||
commitHash to buildTimestamp
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(
|
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(50.dp)
|
|
||||||
.focusOutline()
|
|
||||||
.clickable {
|
|
||||||
clipboardHelper(
|
|
||||||
txt(R.string.extension_version),
|
|
||||||
"${BuildConfig.VERSION_NAME} $commitHash $buildTimestamp"
|
|
||||||
)
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
ProvideTextStyle(MaterialTheme.typography.bodyMedium) {
|
|
||||||
Text(text = BuildConfig.VERSION_NAME)
|
|
||||||
if (commitHash != "") {
|
|
||||||
Text("•")
|
|
||||||
Text(text = commitHash)
|
|
||||||
}
|
|
||||||
Text("•")
|
|
||||||
Text(text = buildTimestamp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@PreviewLightDark
|
|
||||||
@Composable
|
|
||||||
fun Preview() {
|
|
||||||
CloudStreamPreviewTheme {
|
|
||||||
SettingsFragmentScreen.Content()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -3,7 +3,6 @@ package com.lagradost.cloudstream3.ui.settings
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.appcompat.app.AlertDialog
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
|
@ -11,14 +10,12 @@ import androidx.core.content.edit
|
||||||
import androidx.core.os.ConfigurationCompat
|
import androidx.core.os.ConfigurationCompat
|
||||||
import androidx.fragment.app.Fragment
|
import androidx.fragment.app.Fragment
|
||||||
import androidx.preference.PreferenceManager
|
import androidx.preference.PreferenceManager
|
||||||
import com.fasterxml.jackson.annotation.JsonAlias
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty
|
import com.fasterxml.jackson.annotation.JsonProperty
|
||||||
import com.lagradost.cloudstream3.APIHolder.allProviders
|
import com.lagradost.cloudstream3.APIHolder.allProviders
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp
|
import com.lagradost.cloudstream3.CloudStreamApp
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
|
||||||
import com.lagradost.cloudstream3.CommonActivity
|
import com.lagradost.cloudstream3.CommonActivity
|
||||||
import com.lagradost.cloudstream3.CommonActivity.activity
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.showToast
|
import com.lagradost.cloudstream3.CommonActivity.showToast
|
||||||
import com.lagradost.cloudstream3.MainActivity
|
import com.lagradost.cloudstream3.MainActivity
|
||||||
import com.lagradost.cloudstream3.R
|
import com.lagradost.cloudstream3.R
|
||||||
|
|
@ -51,10 +48,6 @@ import com.lagradost.cloudstream3.utils.USER_PROVIDER_API
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement
|
import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement.getBasePath
|
import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement.getBasePath
|
||||||
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
|
||||||
import kotlinx.serialization.ExperimentalSerializationApi
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import kotlinx.serialization.json.JsonNames
|
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
// Change local language settings in the app.
|
// Change local language settings in the app.
|
||||||
|
|
@ -79,7 +72,6 @@ val appLanguages = arrayListOf(
|
||||||
Pair("Azərbaycan dili", "az"),
|
Pair("Azərbaycan dili", "az"),
|
||||||
Pair("Bahasa Indonesia", "in"),
|
Pair("Bahasa Indonesia", "in"),
|
||||||
Pair("Bahasa Melayu", "ms"),
|
Pair("Bahasa Melayu", "ms"),
|
||||||
Pair("català", "ca"),
|
|
||||||
Pair("Deutsch", "de"),
|
Pair("Deutsch", "de"),
|
||||||
Pair("English", "en"),
|
Pair("English", "en"),
|
||||||
Pair("Español", "es"),
|
Pair("Español", "es"),
|
||||||
|
|
@ -100,7 +92,6 @@ val appLanguages = arrayListOf(
|
||||||
Pair("Português", "pt"),
|
Pair("Português", "pt"),
|
||||||
Pair("Português (Brasil)", "pt-BR"),
|
Pair("Português (Brasil)", "pt-BR"),
|
||||||
Pair("Română", "ro"),
|
Pair("Română", "ro"),
|
||||||
Pair("Shqip мова", "sq"),
|
|
||||||
Pair("Slovenčina", "sk"),
|
Pair("Slovenčina", "sk"),
|
||||||
Pair("Soomaaliga", "so"),
|
Pair("Soomaaliga", "so"),
|
||||||
Pair("Svenska", "sv"),
|
Pair("Svenska", "sv"),
|
||||||
|
|
@ -110,7 +101,6 @@ val appLanguages = arrayListOf(
|
||||||
Pair("Wikang Filipino", "fil"),
|
Pair("Wikang Filipino", "fil"),
|
||||||
Pair("Čeština", "cs"),
|
Pair("Čeština", "cs"),
|
||||||
Pair("Ελληνικά", "el"),
|
Pair("Ελληνικά", "el"),
|
||||||
Pair("беларуская мова", "be"),
|
|
||||||
Pair("български", "bg"),
|
Pair("български", "bg"),
|
||||||
Pair("македонски", "mk"),
|
Pair("македонски", "mk"),
|
||||||
Pair("русский", "ru"),
|
Pair("русский", "ru"),
|
||||||
|
|
@ -130,7 +120,6 @@ val appLanguages = arrayListOf(
|
||||||
Pair("தமிழ்", "ta"),
|
Pair("தமிழ்", "ta"),
|
||||||
Pair("ಕನ್ನಡ", "kn"),
|
Pair("ಕನ್ನಡ", "kn"),
|
||||||
Pair("മലയാളം", "ml"),
|
Pair("മലയാളം", "ml"),
|
||||||
Pair("ພາສາລາວ", "lo"),
|
|
||||||
Pair("ဗမာစာ", "my"),
|
Pair("ဗမာစာ", "my"),
|
||||||
Pair("ትግርኛ", "ti"),
|
Pair("ትግርኛ", "ti"),
|
||||||
Pair("አማርኛ", "am"),
|
Pair("አማርኛ", "am"),
|
||||||
|
|
@ -145,7 +134,7 @@ fun Pair<String, String>.nameNextToFlagEmoji(): String {
|
||||||
// fallback to [A][A] -> [?] question mak flag
|
// fallback to [A][A] -> [?] question mak flag
|
||||||
val flag = SubtitleHelper.getFlagFromIso(this.second) ?: "\ud83c\udde6\ud83c\udde6"
|
val flag = SubtitleHelper.getFlagFromIso(this.second) ?: "\ud83c\udde6\ud83c\udde6"
|
||||||
|
|
||||||
return "$flag\u00a0${this.first}" // \u00a0 non-breaking space
|
return "$flag\u00a0${this.first}" // \u00a0 non-breaking space
|
||||||
}
|
}
|
||||||
|
|
||||||
class SettingsGeneral : BasePreferenceFragmentCompat() {
|
class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
|
|
@ -156,15 +145,15 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
setToolBarScrollFlags()
|
setToolBarScrollFlags()
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalSerializationApi::class) // JsonNames is an experimental annotation for now
|
|
||||||
@Serializable
|
|
||||||
data class CustomSite(
|
data class CustomSite(
|
||||||
@JsonProperty("parentClassName") @JsonAlias("parentJavaClass")
|
@JsonProperty("parentJavaClass") // javaClass.simpleName
|
||||||
@SerialName("parentClassName") @JsonNames("parentJavaClass")
|
val parentJavaClass: String,
|
||||||
val parentClassName: String, // ::class.simpleName
|
@JsonProperty("name")
|
||||||
@JsonProperty("name") @SerialName("name") val name: String,
|
val name: String,
|
||||||
@JsonProperty("url") @SerialName("url") val url: String,
|
@JsonProperty("url")
|
||||||
@JsonProperty("lang") @SerialName("lang") val lang: String,
|
val url: String,
|
||||||
|
@JsonProperty("lang")
|
||||||
|
val lang: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
@ -178,96 +167,6 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
putString(context.getString(R.string.download_path_key_visual), visual)
|
putString(context.getString(R.string.download_path_key_visual), visual)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getCurrent(): MutableList<CustomSite> {
|
|
||||||
return getKey<Array<CustomSite>>(USER_PROVIDER_API)?.toMutableList()
|
|
||||||
?: mutableListOf()
|
|
||||||
}
|
|
||||||
fun showAdd() {
|
|
||||||
val providers = allProviders.distinctBy { it::class }.sortedBy { it.name }
|
|
||||||
val context = activity
|
|
||||||
context?.showDialog(
|
|
||||||
providers.map { "${it.name} (${it.mainUrl})" },
|
|
||||||
-1,
|
|
||||||
context.getString(R.string.add_site_pref),
|
|
||||||
true,
|
|
||||||
{}) { selection ->
|
|
||||||
val provider = providers.getOrNull(selection) ?: return@showDialog
|
|
||||||
|
|
||||||
val binding : AddSiteInputBinding = AddSiteInputBinding.inflate(LayoutInflater.from(
|
|
||||||
context
|
|
||||||
),null,false)
|
|
||||||
|
|
||||||
val builder =
|
|
||||||
AlertDialog.Builder(context, R.style.AlertDialogCustom)
|
|
||||||
.setView(binding.root)
|
|
||||||
|
|
||||||
val dialog = builder.create()
|
|
||||||
dialog.show()
|
|
||||||
|
|
||||||
binding.text2.text = provider.name
|
|
||||||
binding.applyBtt.setOnClickListener {
|
|
||||||
val name = binding.siteNameInput.text?.toString()
|
|
||||||
val url = binding.siteUrlInput.text?.toString()
|
|
||||||
val lang = binding.siteLangInput.text?.toString()
|
|
||||||
val realLang = if (lang.isNullOrBlank()) provider.lang else lang
|
|
||||||
val simpleName = provider::class.simpleName
|
|
||||||
if (url.isNullOrBlank() || name.isNullOrBlank() || simpleName == null) {
|
|
||||||
showToast(R.string.error_invalid_data, Toast.LENGTH_SHORT)
|
|
||||||
return@setOnClickListener
|
|
||||||
}
|
|
||||||
|
|
||||||
val current = getCurrent()
|
|
||||||
val newSite = CustomSite(simpleName, name, url, realLang)
|
|
||||||
current.add(newSite)
|
|
||||||
setKey(USER_PROVIDER_API, current.toTypedArray())
|
|
||||||
// reload apis
|
|
||||||
MainActivity.afterPluginsLoadedEvent.invoke(false)
|
|
||||||
|
|
||||||
dialog.dismissSafe(activity)
|
|
||||||
}
|
|
||||||
binding.cancelBtt.setOnClickListener {
|
|
||||||
dialog.dismissSafe(activity)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun showDelete() {
|
|
||||||
val current = getCurrent()
|
|
||||||
val context = activity
|
|
||||||
context?.showMultiDialog(
|
|
||||||
current.map { it.name },
|
|
||||||
listOf(),
|
|
||||||
context.getString(R.string.remove_site_pref),
|
|
||||||
{}) { indexes ->
|
|
||||||
current.removeAll(indexes.map { current[it] })
|
|
||||||
setKey(USER_PROVIDER_API, current.toTypedArray())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun showAddOrDelete() {
|
|
||||||
val context = activity
|
|
||||||
|
|
||||||
val binding : AddRemoveSitesBinding = AddRemoveSitesBinding.inflate(
|
|
||||||
LayoutInflater.from(
|
|
||||||
context
|
|
||||||
),null,false)
|
|
||||||
val builder =
|
|
||||||
AlertDialog.Builder(context ?: return, R.style.AlertDialogCustom)
|
|
||||||
.setView(binding.root)
|
|
||||||
|
|
||||||
val dialog = builder.create()
|
|
||||||
dialog.show()
|
|
||||||
|
|
||||||
binding.addSite.setOnClickListener {
|
|
||||||
showAdd()
|
|
||||||
dialog.dismissSafe(activity)
|
|
||||||
}
|
|
||||||
binding.removeSite.setOnClickListener {
|
|
||||||
showDelete()
|
|
||||||
dialog.dismissSafe(activity)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val pathPicker = getChooseFolderLauncher { uri, path ->
|
private val pathPicker = getChooseFolderLauncher { uri, path ->
|
||||||
|
|
@ -279,6 +178,10 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
setPreferencesFromResource(R.xml.settings_general, rootKey)
|
setPreferencesFromResource(R.xml.settings_general, rootKey)
|
||||||
val settingsManager = PreferenceManager.getDefaultSharedPreferences(requireContext())
|
val settingsManager = PreferenceManager.getDefaultSharedPreferences(requireContext())
|
||||||
|
|
||||||
|
fun getCurrent(): MutableList<CustomSite> {
|
||||||
|
return getKey<Array<CustomSite>>(USER_PROVIDER_API)?.toMutableList()
|
||||||
|
?: mutableListOf()
|
||||||
|
}
|
||||||
|
|
||||||
getPref(R.string.locale_key)?.setOnPreferenceClickListener { pref ->
|
getPref(R.string.locale_key)?.setOnPreferenceClickListener { pref ->
|
||||||
val current = getCurrentLocale(pref.context)
|
val current = getCurrentLocale(pref.context)
|
||||||
|
|
@ -315,7 +218,82 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun showAdd() {
|
||||||
|
val providers = synchronized(allProviders) { allProviders.distinctBy { it.javaClass }.sortedBy { it.name } }
|
||||||
|
activity?.showDialog(
|
||||||
|
providers.map { "${it.name} (${it.mainUrl})" },
|
||||||
|
-1,
|
||||||
|
context?.getString(R.string.add_site_pref) ?: return,
|
||||||
|
true,
|
||||||
|
{}) { selection ->
|
||||||
|
val provider = providers.getOrNull(selection) ?: return@showDialog
|
||||||
|
|
||||||
|
val binding : AddSiteInputBinding = AddSiteInputBinding.inflate(layoutInflater,null,false)
|
||||||
|
|
||||||
|
val builder =
|
||||||
|
AlertDialog.Builder(context ?: return@showDialog, R.style.AlertDialogCustom)
|
||||||
|
.setView(binding.root)
|
||||||
|
|
||||||
|
val dialog = builder.create()
|
||||||
|
dialog.show()
|
||||||
|
|
||||||
|
binding.text2.text = provider.name
|
||||||
|
binding.applyBtt.setOnClickListener {
|
||||||
|
val name = binding.siteNameInput.text?.toString()
|
||||||
|
val url = binding.siteUrlInput.text?.toString()
|
||||||
|
val lang = binding.siteLangInput.text?.toString()
|
||||||
|
val realLang = if (lang.isNullOrBlank()) provider.lang else lang
|
||||||
|
if (url.isNullOrBlank() || name.isNullOrBlank()) {
|
||||||
|
showToast(R.string.error_invalid_data, Toast.LENGTH_SHORT)
|
||||||
|
return@setOnClickListener
|
||||||
|
}
|
||||||
|
|
||||||
|
val current = getCurrent()
|
||||||
|
val newSite = CustomSite(provider.javaClass.simpleName, name, url, realLang)
|
||||||
|
current.add(newSite)
|
||||||
|
setKey(USER_PROVIDER_API, current.toTypedArray())
|
||||||
|
// reload apis
|
||||||
|
MainActivity.afterPluginsLoadedEvent.invoke(false)
|
||||||
|
|
||||||
|
dialog.dismissSafe(activity)
|
||||||
|
}
|
||||||
|
binding.cancelBtt.setOnClickListener {
|
||||||
|
dialog.dismissSafe(activity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun showDelete() {
|
||||||
|
val current = getCurrent()
|
||||||
|
|
||||||
|
activity?.showMultiDialog(
|
||||||
|
current.map { it.name },
|
||||||
|
listOf(),
|
||||||
|
context?.getString(R.string.remove_site_pref) ?: return,
|
||||||
|
{}) { indexes ->
|
||||||
|
current.removeAll(indexes.map { current[it] })
|
||||||
|
setKey(USER_PROVIDER_API, current.toTypedArray())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun showAddOrDelete() {
|
||||||
|
val binding : AddRemoveSitesBinding = AddRemoveSitesBinding.inflate(layoutInflater,null,false)
|
||||||
|
val builder =
|
||||||
|
AlertDialog.Builder(context ?: return, R.style.AlertDialogCustom)
|
||||||
|
.setView(binding.root)
|
||||||
|
|
||||||
|
val dialog = builder.create()
|
||||||
|
dialog.show()
|
||||||
|
|
||||||
|
binding.addSite.setOnClickListener {
|
||||||
|
showAdd()
|
||||||
|
dialog.dismissSafe(activity)
|
||||||
|
}
|
||||||
|
binding.removeSite.setOnClickListener {
|
||||||
|
showDelete()
|
||||||
|
dialog.dismissSafe(activity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
getPref(R.string.override_site_key)?.setOnPreferenceClickListener { _ ->
|
getPref(R.string.override_site_key)?.setOnPreferenceClickListener { _ ->
|
||||||
|
|
||||||
|
|
@ -342,7 +320,7 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
val prefValues = resources.getIntArray(R.array.dns_pref_values)
|
val prefValues = resources.getIntArray(R.array.dns_pref_values)
|
||||||
|
|
||||||
val currentDns =
|
val currentDns =
|
||||||
settingsManager.getInt(getString(R.string.dns_key), 0)
|
settingsManager.getInt(getString(R.string.dns_pref), 0)
|
||||||
|
|
||||||
activity?.showBottomDialog(
|
activity?.showBottomDialog(
|
||||||
prefNames.toList(),
|
prefNames.toList(),
|
||||||
|
|
@ -350,7 +328,7 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
getString(R.string.dns_pref),
|
getString(R.string.dns_pref),
|
||||||
true,
|
true,
|
||||||
{}) {
|
{}) {
|
||||||
settingsManager.edit { putInt(getString(R.string.dns_key), prefValues[it]) }
|
settingsManager.edit { putInt(getString(R.string.dns_pref), prefValues[it]) }
|
||||||
(context ?: CloudStreamApp.context)?.let { ctx -> app.initClient(ctx) }
|
(context ?: CloudStreamApp.context)?.let { ctx -> app.initClient(ctx) }
|
||||||
}
|
}
|
||||||
return@setOnPreferenceClickListener true
|
return@setOnPreferenceClickListener true
|
||||||
|
|
@ -368,14 +346,14 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
|
||||||
(first +
|
(first +
|
||||||
ctx.getExternalFilesDirs("").mapNotNull { it.path } +
|
ctx.getExternalFilesDirs("").mapNotNull { it.path } +
|
||||||
currentDir)
|
currentDir)
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
first
|
first
|
||||||
}).filterNotNull().distinct()
|
}).filterNotNull().distinct()
|
||||||
}
|
}
|
||||||
} ?: emptyList()
|
} ?: emptyList()
|
||||||
}
|
}
|
||||||
|
|
||||||
settingsManager.edit { putBoolean(getString(R.string.jsdelivr_proxy_key), getKey<Boolean>(getString(R.string.jsdelivr_proxy_key), false) ?: false) }
|
settingsManager.edit { putBoolean(getString(R.string.jsdelivr_proxy_key), getKey(getString(R.string.jsdelivr_proxy_key), false) ?: false) }
|
||||||
getPref(R.string.jsdelivr_proxy_key)?.setOnPreferenceChangeListener { _, newValue ->
|
getPref(R.string.jsdelivr_proxy_key)?.setOnPreferenceChangeListener { _, newValue ->
|
||||||
setKey(getString(R.string.jsdelivr_proxy_key), newValue)
|
setKey(getString(R.string.jsdelivr_proxy_key), newValue)
|
||||||
return@setOnPreferenceChangeListener true
|
return@setOnPreferenceChangeListener true
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import com.lagradost.cloudstream3.utils.BaseComposeFragment
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
|
|
||||||
/** Empty glue code to connect the old navigation graph to Compose */
|
|
||||||
class SettingsGeneral2 : BaseComposeFragment(), SearchableSettings by SettingsGeneralScreen
|
|
||||||
|
|
@ -1,305 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.net.Uri
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.integerArrayResource
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringArrayResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.tooling.preview.PreviewLightDark
|
|
||||||
import com.lagradost.cloudstream3.APIHolder
|
|
||||||
import com.lagradost.cloudstream3.AllLanguagesName
|
|
||||||
import com.lagradost.cloudstream3.CloudStreamApp
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.activity
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.showToast
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.TvType
|
|
||||||
import com.lagradost.cloudstream3.UnsafeSSL
|
|
||||||
import com.lagradost.cloudstream3.app
|
|
||||||
import com.lagradost.cloudstream3.insecureApp
|
|
||||||
import com.lagradost.cloudstream3.mvvm.logError
|
|
||||||
import com.lagradost.cloudstream3.network.initClient
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsProvidersScreen.toStringRes
|
|
||||||
import com.lagradost.cloudstream3.utils.BatteryOptimizationChecker.isAppRestricted
|
|
||||||
import com.lagradost.cloudstream3.utils.BatteryOptimizationChecker.showRequestIgnoreBatteryOptDialog
|
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
|
|
||||||
import com.lagradost.cloudstream3.utils.SubtitleHelper.getNameNextToFlagEmoji
|
|
||||||
import com.lagradost.cloudstream4.AppSettings
|
|
||||||
import com.lagradost.cloudstream4.compose.ActionDialog
|
|
||||||
import com.lagradost.cloudstream4.compose.PHONE
|
|
||||||
import com.lagradost.cloudstream4.compose.isLayout
|
|
||||||
import com.lagradost.cloudstream4.rememberAppSettings
|
|
||||||
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
|
|
||||||
import com.lagradost.safefile.SafeFile
|
|
||||||
import com.mihon.presentation.settings.Preference
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
import com.mihon.presentation.settings.collectAsState
|
|
||||||
import kotlinx.collections.immutable.persistentListOf
|
|
||||||
import kotlinx.collections.immutable.toPersistentMap
|
|
||||||
|
|
||||||
object SettingsGeneralScreen : SearchableSettings {
|
|
||||||
@Composable
|
|
||||||
override fun getTitleRes(): String = stringResource(R.string.category_general)
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
override fun getPreferences(): List<Preference> {
|
|
||||||
val settings = rememberAppSettings()
|
|
||||||
|
|
||||||
// TODO Refactor entirely to use a different file path selector ect like QuickNovel
|
|
||||||
val selectFileSelector =
|
|
||||||
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
|
|
||||||
// It lies, it can be null if file manager quits.
|
|
||||||
if (uri == null) return@rememberLauncherForActivityResult
|
|
||||||
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
|
|
||||||
|
|
||||||
try {
|
|
||||||
val settings = AppSettings(context)
|
|
||||||
// RW perms for the path
|
|
||||||
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
|
|
||||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
|
||||||
|
|
||||||
context.contentResolver.takePersistableUriPermission(uri, flags)
|
|
||||||
|
|
||||||
val filePath = SafeFile.fromUri(context, uri)?.filePath()
|
|
||||||
println("Selected URI path: $uri - Full path: $filePath")
|
|
||||||
|
|
||||||
// store the actual URI instead of the path due to permissions.
|
|
||||||
// filePath should only be used for cosmetic purposes.
|
|
||||||
val visual = filePath ?: uri.toString()
|
|
||||||
settings.general.downloadPath.set(uri.toString())
|
|
||||||
settings.general.downloadPathVisual.set(visual)
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
logError(t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val bananas by settings.general.bananas.collectAsState()
|
|
||||||
val downloadPathVisual by settings.general.downloadPathVisual.collectAsState()
|
|
||||||
//val downloadPath by settings.general.downloadPath.collectAsState()
|
|
||||||
|
|
||||||
var isBatteryShown by remember { mutableStateOf(false) }
|
|
||||||
val context = LocalContext.current
|
|
||||||
|
|
||||||
if (isBatteryShown) {
|
|
||||||
ActionDialog(
|
|
||||||
icon = painterResource(R.drawable.battery_alert_24px),
|
|
||||||
title = stringResource(R.string.battery_dialog_title),
|
|
||||||
text = stringResource(R.string.battery_dialog_message),
|
|
||||||
confirmText = stringResource(R.string.ok),
|
|
||||||
dismissText = stringResource(R.string.cancel),
|
|
||||||
dismiss = {
|
|
||||||
isBatteryShown = false
|
|
||||||
settings.general.batterOptimization.set(false)
|
|
||||||
},
|
|
||||||
confirm = {
|
|
||||||
isBatteryShown = false
|
|
||||||
// The og impl never modified it to true?
|
|
||||||
// settings.general.batterOptimization.set(true)
|
|
||||||
context.showRequestIgnoreBatteryOptDialog()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val default = AllLanguagesName to stringResource(R.string.all_languages_preference)
|
|
||||||
val languages = APIHolder.apis.withLock {
|
|
||||||
APIHolder.apis.map { api -> api.lang }.distinct()
|
|
||||||
}.sortedBy { fromTagToLanguageName(it) ?: it }
|
|
||||||
|
|
||||||
return persistentListOf(
|
|
||||||
Preference.PreferenceGroup(title = stringResource(R.string.extension_language), preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.general.locale,
|
|
||||||
entries = appLanguages.associate { (name, code) -> (code to (name to code).nameNextToFlagEmoji()) },
|
|
||||||
title = stringResource(R.string.app_language),
|
|
||||||
icon = painterResource(R.drawable.language_korean_latin_24px),
|
|
||||||
onValueChanged = { value ->
|
|
||||||
settings.general.locale.set(value)
|
|
||||||
activity?.recreate()
|
|
||||||
return@ListPreference false
|
|
||||||
},
|
|
||||||
subtitleProvider = { v, e -> e[v] ?: getCurrentLocale(LocalContext.current) }
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.MultiSelectListPreference(
|
|
||||||
title = stringResource(R.string.provider_lang_settings),
|
|
||||||
icon = painterResource(R.drawable.plugin_lang),
|
|
||||||
entries = mapOf(default) + languages.associateWith { lang ->
|
|
||||||
(getNameNextToFlagEmoji(
|
|
||||||
lang
|
|
||||||
) ?: lang)
|
|
||||||
},
|
|
||||||
preference = settings.provider.extensionLanguages
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.MultiSelectListPreference(
|
|
||||||
title = stringResource(R.string.preferred_media_settings),
|
|
||||||
icon = painterResource(R.drawable.movie_edit_24px),
|
|
||||||
preference = settings.provider.preferredMedia,
|
|
||||||
entries = TvType.entries.associate {
|
|
||||||
it.ordinal.toString() to stringResource(it.toStringRes())
|
|
||||||
}
|
|
||||||
// Ok this looks strange af, but we do this to avoid double movie
|
|
||||||
.toPersistentMap().remove(TvType.AnimeMovie.ordinal.toString()), onValueChanged = { diff ->
|
|
||||||
if(diff.contains(TvType.Movie.ordinal.toString())) {
|
|
||||||
settings.provider.preferredMedia.set(diff + TvType.AnimeMovie.ordinal.toString())
|
|
||||||
} else {
|
|
||||||
settings.provider.preferredMedia.set(diff - TvType.AnimeMovie.ordinal.toString())
|
|
||||||
}
|
|
||||||
return@MultiSelectListPreference false
|
|
||||||
}),
|
|
||||||
)),
|
|
||||||
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.title_downloads),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
icon = painterResource(R.drawable.netflix_download),
|
|
||||||
subtitle = downloadPathVisual,
|
|
||||||
title = stringResource(R.string.download_path_pref),
|
|
||||||
onClick = {
|
|
||||||
// This is not a ListPreference because the old selection system is
|
|
||||||
// broken af. This needs to be refactored to QuickNovels download path
|
|
||||||
// system.
|
|
||||||
selectFileSelector.launch(Uri.EMPTY)
|
|
||||||
},
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SliderPreference(
|
|
||||||
icon = painterResource(R.drawable.arrow_or_edge_24px),
|
|
||||||
preference = settings.general.parallelDownloads,
|
|
||||||
valueRange = 1..10,
|
|
||||||
title = stringResource(R.string.parallel_downloads),
|
|
||||||
subtitle = stringResource(R.string.download_parallel_settings_des),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SliderPreference(
|
|
||||||
icon = painterResource(R.drawable.arrow_and_edge_24px),
|
|
||||||
preference = settings.general.concurrentConnections,
|
|
||||||
valueRange = 1..10,
|
|
||||||
title = stringResource(R.string.concurrent_connections),
|
|
||||||
subtitle = stringResource(R.string.concurrent_connections_settings_des),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.battery_dialog_title),
|
|
||||||
icon = painterResource(R.drawable.battery_alert_24px),
|
|
||||||
enabled = isLayout(PHONE),
|
|
||||||
onClick = {
|
|
||||||
if (isAppRestricted(context)) {
|
|
||||||
isBatteryShown = true
|
|
||||||
} else {
|
|
||||||
showToast(R.string.app_unrestricted_toast)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
),
|
|
||||||
)
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_bypass),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.add_site_pref),
|
|
||||||
subtitle = stringResource(R.string.add_site_summary),
|
|
||||||
icon = painterResource(R.drawable.copy_all_24px),
|
|
||||||
onClick = {
|
|
||||||
// TODO refactor into compose
|
|
||||||
if (SettingsGeneral.getCurrent().isEmpty()) {
|
|
||||||
SettingsGeneral.showAdd()
|
|
||||||
} else {
|
|
||||||
SettingsGeneral.showAddOrDelete()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
title = stringResource(R.string.dns_pref),
|
|
||||||
subtitle = stringResource(R.string.dns_pref_summary),
|
|
||||||
icon = painterResource(R.drawable.dns_24px),
|
|
||||||
preference = settings.general.dns,
|
|
||||||
entries = integerArrayResource(R.array.dns_pref_values).zip(
|
|
||||||
stringArrayResource(R.array.dns_pref)
|
|
||||||
).toMap(),
|
|
||||||
onValueChanged = { newValue ->
|
|
||||||
settings.general.dns.set(newValue) // Must set the value before initClient is called
|
|
||||||
(CloudStreamApp.context)?.let { ctx ->
|
|
||||||
app.initClient(ctx, ignoreSSL = false)
|
|
||||||
@OptIn(UnsafeSSL::class)
|
|
||||||
insecureApp.initClient(ctx, ignoreSSL = true)
|
|
||||||
}
|
|
||||||
return@ListPreference true
|
|
||||||
},
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
title = stringResource(R.string.jsdelivr_proxy),
|
|
||||||
subtitle = stringResource(R.string.jsdelivr_proxy_summary),
|
|
||||||
icon = painterResource(R.drawable.wifi_proxy_24px),
|
|
||||||
preference = settings.general.jsdelivrProxy
|
|
||||||
)
|
|
||||||
)
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_links),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.github),
|
|
||||||
subtitle = "https://github.com/recloudstream/cloudstream",
|
|
||||||
icon = painterResource(R.drawable.ic_github_logo),
|
|
||||||
onClick = {
|
|
||||||
CloudStreamApp.openBrowser("https://github.com/recloudstream/cloudstream")
|
|
||||||
}
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.lightnovel),
|
|
||||||
subtitle = "https://github.com/LagradOst/QuickNovel",
|
|
||||||
icon = painterResource(R.drawable.quick_novel_icon),
|
|
||||||
onClick = {
|
|
||||||
CloudStreamApp.openBrowser("https://github.com/LagradOst/QuickNovel")
|
|
||||||
}
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.discord),
|
|
||||||
subtitle = "https://discord.gg/5Hus6fM",
|
|
||||||
icon = painterResource(R.drawable.ic_baseline_discord_24),
|
|
||||||
onClick = {
|
|
||||||
CloudStreamApp.openBrowser("https://discord.gg/5Hus6fM")
|
|
||||||
}
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.cs3wiki),
|
|
||||||
subtitle = "https://cloudstream.miraheze.org/",
|
|
||||||
icon = painterResource(R.drawable.description_24px),
|
|
||||||
onClick = {
|
|
||||||
CloudStreamApp.openBrowser("https://cloudstream.miraheze.org/")
|
|
||||||
}
|
|
||||||
),
|
|
||||||
)
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.benene),
|
|
||||||
subtitle = if (bananas == 0) {
|
|
||||||
stringResource(R.string.benene_count_text_none)
|
|
||||||
} else {
|
|
||||||
stringResource(R.string.benene_count_text, bananas)
|
|
||||||
},
|
|
||||||
onClick = {
|
|
||||||
settings.general.bananas.set(bananas + 1)
|
|
||||||
},
|
|
||||||
icon = painterResource(R.drawable.benene),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.InfoPreference(title = stringResource(R.string.legal_notice_text)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@PreviewLightDark
|
|
||||||
@Composable
|
|
||||||
private fun SettingGeneralPreview() {
|
|
||||||
CloudStreamPreviewTheme {
|
|
||||||
SettingsGeneralScreen.Content()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -205,35 +205,29 @@ class SettingsPlayer : BasePreferenceFragmentCompat() {
|
||||||
}
|
}
|
||||||
|
|
||||||
getPref(R.string.player_default_key)?.setOnPreferenceClickListener {
|
getPref(R.string.player_default_key)?.setOnPreferenceClickListener {
|
||||||
// Pair each player with its display name, dropping any with none,
|
val players = VideoClickActionHolder.getPlayers(activity)
|
||||||
// which would mean something is definitely wrong.
|
|
||||||
val players = VideoClickActionHolder.getPlayers(activity).mapNotNull { player ->
|
|
||||||
(player.name.asStringNull(activity) ?: player::class.simpleName)?.let { player to it }
|
|
||||||
}
|
|
||||||
|
|
||||||
val prefNames = buildList {
|
val prefNames = buildList {
|
||||||
add(getString(R.string.player_settings_play_in_app)) // built-in player display name
|
add(getString(R.string.player_settings_play_in_app))
|
||||||
addAll(players.map { (_, name) -> name })
|
addAll(players.map { it.name.asStringNull(activity) ?: it.javaClass.simpleName })
|
||||||
}
|
}
|
||||||
|
|
||||||
val prefValues = buildList {
|
val prefValues = buildList {
|
||||||
add("") // "" = built-in player, matches default
|
add("")
|
||||||
addAll(players.map { (player, _) -> player.uniqueId() })
|
addAll(players.map { it.uniqueId() })
|
||||||
}
|
}
|
||||||
|
val current =
|
||||||
|
settingsManager.getString(getString(R.string.player_default_key), "") ?: ""
|
||||||
|
|
||||||
val current = settingsManager.getString(getString(R.string.player_default_key), "") ?: ""
|
|
||||||
activity?.showBottomDialog(
|
activity?.showBottomDialog(
|
||||||
prefNames.toList(),
|
prefNames.toList(),
|
||||||
prefValues.indexOf(current), // finds index of currently selected player
|
prefValues.indexOf(current),
|
||||||
getString(R.string.player_pref),
|
getString(R.string.player_pref),
|
||||||
true,
|
true,
|
||||||
{},
|
{}
|
||||||
) {
|
) {
|
||||||
settingsManager.edit {
|
settingsManager.edit {
|
||||||
putString(getString(R.string.player_default_key), prefValues[it])
|
putString(getString(R.string.player_default_key), prefValues[it])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return@setOnPreferenceClickListener true
|
return@setOnPreferenceClickListener true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import com.lagradost.cloudstream3.utils.BaseComposeFragment
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
|
|
||||||
/** Empty glue code to connect the old navigation graph to Compose */
|
|
||||||
class SettingsPlayer2 : BaseComposeFragment(), SearchableSettings by SettingsPlayerScreen
|
|
||||||
|
|
@ -1,358 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
|
|
||||||
import android.text.format.Formatter.formatShortFileSize
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
|
||||||
import androidx.compose.runtime.mutableLongStateOf
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.res.integerArrayResource
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.stringArrayResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import com.lagradost.cloudstream3.CommonActivity.activity
|
|
||||||
import com.lagradost.cloudstream3.R
|
|
||||||
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
|
|
||||||
import com.lagradost.cloudstream3.ui.player.source_priority.QualityProfileDialog
|
|
||||||
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.getFolderSize
|
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment
|
|
||||||
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment
|
|
||||||
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
|
|
||||||
import com.lagradost.cloudstream4.compose.EMULATOR
|
|
||||||
import com.lagradost.cloudstream4.compose.PHONE
|
|
||||||
import com.lagradost.cloudstream4.compose.TV
|
|
||||||
import com.lagradost.cloudstream4.compose.isLayout
|
|
||||||
import com.lagradost.cloudstream4.rememberAppSettings
|
|
||||||
import com.mihon.presentation.settings.Preference
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
import kotlinx.collections.immutable.persistentListOf
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import kotlin.reflect.jvm.jvmName
|
|
||||||
|
|
||||||
object SettingsPlayerScreen : SearchableSettings {
|
|
||||||
@Composable
|
|
||||||
override fun getTitleRes(): String = stringResource(R.string.category_player)
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
override fun getPreferences(): List<Preference> {
|
|
||||||
val settings = rememberAppSettings()
|
|
||||||
|
|
||||||
val context = LocalContext.current
|
|
||||||
val defaultPlayerName = stringResource(R.string.player_settings_play_in_app)
|
|
||||||
val players = remember(context) {
|
|
||||||
mapOf("" to defaultPlayerName) + VideoClickActionHolder.getPlayers()
|
|
||||||
.associate { player ->
|
|
||||||
player.uniqueId() to (player.name.asStringNull(context)
|
|
||||||
?: player::class.simpleName ?: player::class.jvmName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var cacheSize by remember { mutableLongStateOf(0L) }
|
|
||||||
var cacheCleared by remember { mutableIntStateOf(0) }
|
|
||||||
val cacheDir = LocalContext.current.cacheDir
|
|
||||||
LaunchedEffect(cacheCleared) {
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
cacheSize = getFolderSize(cacheDir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return persistentListOf(
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_subtitles),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.player_subtitles_settings),
|
|
||||||
subtitle = stringResource(R.string.player_subtitles_settings_des),
|
|
||||||
icon = painterResource(R.drawable.subtitles_gear_24px),
|
|
||||||
onClick = {
|
|
||||||
SubtitlesFragment.push(activity, false)
|
|
||||||
}),
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.chromecast_subtitles_settings),
|
|
||||||
subtitle = stringResource(R.string.chromecast_subtitles_settings_des),
|
|
||||||
icon = painterResource(R.drawable.cast),
|
|
||||||
onClick = {
|
|
||||||
ChromecastSubtitlesFragment.push(activity, false)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_player_features),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
title = stringResource(R.string.player_pref),
|
|
||||||
icon = painterResource(R.drawable.play_arrow_24px),
|
|
||||||
preference = settings.player.defaultPlayer,
|
|
||||||
entries = players,
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
title = stringResource(R.string.source_priority),
|
|
||||||
subtitle = stringResource(R.string.source_priority_help),
|
|
||||||
icon = painterResource(R.drawable.ic_baseline_people_24),
|
|
||||||
onClick = {
|
|
||||||
ioSafe {
|
|
||||||
val defaultSources = QualityProfileDialog.getAllDefaultSources()
|
|
||||||
val activity = activity ?: return@ioSafe
|
|
||||||
activity.runOnUiThread {
|
|
||||||
QualityProfileDialog(
|
|
||||||
activity,
|
|
||||||
R.style.DialogFullscreenPlayer,
|
|
||||||
defaultSources,
|
|
||||||
).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.pipEnabled,
|
|
||||||
title = stringResource(R.string.picture_in_picture),
|
|
||||||
subtitle = stringResource(R.string.picture_in_picture_des),
|
|
||||||
icon = painterResource(R.drawable.pip_24px),
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.resizeEnabled,
|
|
||||||
title = stringResource(R.string.player_size_settings),
|
|
||||||
subtitle = stringResource(R.string.player_size_settings_des),
|
|
||||||
icon = painterResource(R.drawable.aspect_ratio_24px),
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.speedEnabled,
|
|
||||||
title = stringResource(R.string.eigengraumode_settings),
|
|
||||||
subtitle = stringResource(R.string.speed_setting_summary),
|
|
||||||
icon = painterResource(R.drawable.ic_baseline_speed_24),
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.compressorEnabled,
|
|
||||||
title = stringResource(R.string.compressor_setting),
|
|
||||||
subtitle = stringResource(R.string.compressor_setting_summary),
|
|
||||||
icon = painterResource(R.drawable.ic_compressor_24),
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.tiktokEnabled,
|
|
||||||
title = stringResource(R.string.speedup_title),
|
|
||||||
subtitle = stringResource(R.string.speedup_summary),
|
|
||||||
icon = painterResource(R.drawable.speedup),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.autoPlayEnabled,
|
|
||||||
title = stringResource(R.string.autoplay_next_settings),
|
|
||||||
subtitle = stringResource(R.string.autoplay_next_settings_des),
|
|
||||||
icon = painterResource(R.drawable.skip_next_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.startPaused,
|
|
||||||
title = stringResource(R.string.start_paused_settings),
|
|
||||||
subtitle = stringResource(R.string.start_paused_settings_des),
|
|
||||||
icon = painterResource(R.drawable.pause_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.skipOpEnabled,
|
|
||||||
title = stringResource(R.string.video_skip_op),
|
|
||||||
subtitle = stringResource(R.string.enable_skip_op_from_database_des),
|
|
||||||
icon = painterResource(R.drawable.keyboard_double_arrow_right_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.autoRotateEnabled,
|
|
||||||
title = stringResource(R.string.auto_rotate_video),
|
|
||||||
subtitle = stringResource(R.string.auto_rotate_video_desc),
|
|
||||||
icon = painterResource(R.drawable.screen_rotation_alt_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.rotateButtonEnabled,
|
|
||||||
title = stringResource(R.string.rotate_video),
|
|
||||||
subtitle = stringResource(R.string.rotate_video_desc),
|
|
||||||
icon = painterResource(R.drawable.screen_rotation),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.previewBarEnabled,
|
|
||||||
enabled = isLayout(PHONE or EMULATOR),
|
|
||||||
title = stringResource(R.string.preview_seekbar),
|
|
||||||
subtitle = stringResource(R.string.preview_seekbar_desc),
|
|
||||||
icon = painterResource(R.drawable.picture_in_picture_center_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.player.softwareDecoding,
|
|
||||||
title = stringResource(R.string.software_decoding),
|
|
||||||
subtitle = stringResource(R.string.software_decoding_desc),
|
|
||||||
icon = painterResource(R.drawable.memory_24px),
|
|
||||||
entries = integerArrayResource(R.array.software_decoding_switch_values).zip(
|
|
||||||
stringArrayResource(R.array.software_decoding_switch)
|
|
||||||
).toMap()
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.extraBrightnessEnabled,
|
|
||||||
title = stringResource(R.string.extra_brightness_settings),
|
|
||||||
subtitle = stringResource(R.string.extra_brightness_settings_des),
|
|
||||||
icon = painterResource(R.drawable.light_mode_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.episodeSync,
|
|
||||||
title = stringResource(R.string.episode_sync_settings),
|
|
||||||
subtitle = stringResource(R.string.episode_sync_settings_des),
|
|
||||||
icon = painterResource(R.drawable.autorenew_24px)
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_gestures),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.swipeHorizontalEnabled,
|
|
||||||
title = stringResource(R.string.swipe_to_seek_settings),
|
|
||||||
subtitle = stringResource(R.string.swipe_to_seek_settings_des),
|
|
||||||
icon = painterResource(R.drawable.swipe_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.swipeVerticalEnabled,
|
|
||||||
title = stringResource(R.string.swipe_to_change_settings),
|
|
||||||
subtitle = stringResource(R.string.swipe_to_change_settings_des),
|
|
||||||
icon = painterResource(R.drawable.swipe_vertical_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.doubleTapToSeekEnabled,
|
|
||||||
title = stringResource(R.string.double_tap_to_seek_settings),
|
|
||||||
subtitle = stringResource(R.string.double_tap_to_seek_settings_des),
|
|
||||||
icon = painterResource(R.drawable.touch_double_24px),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.doubleTapToPauseEnabled,
|
|
||||||
title = stringResource(R.string.double_tap_to_pause_settings),
|
|
||||||
subtitle = stringResource(R.string.double_tap_to_pause_settings_des),
|
|
||||||
icon = painterResource(R.drawable.touch_double_24px),
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.SliderPreference(
|
|
||||||
preference = settings.player.doubleTapTime,
|
|
||||||
title = stringResource(R.string.double_tap_to_seek_amount_settings),
|
|
||||||
icon = painterResource(R.drawable.go_forward_30),
|
|
||||||
valueRange = 5..60,
|
|
||||||
//steps = 10,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
),
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_android_tv),
|
|
||||||
enabled = isLayout(TV or EMULATOR),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.SliderPreference(
|
|
||||||
preference = settings.player.tvSeekOnTime,
|
|
||||||
title = stringResource(R.string.android_tv_interface_on_seek_settings),
|
|
||||||
subtitle = stringResource(R.string.android_tv_interface_on_seek_settings_summary),
|
|
||||||
icon = painterResource(R.drawable.go_forward_30),
|
|
||||||
valueRange = 5..60,
|
|
||||||
//steps = 10,
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SliderPreference(
|
|
||||||
preference = settings.player.tvSeekOffTime,
|
|
||||||
title = stringResource(R.string.android_tv_interface_off_seek_settings),
|
|
||||||
subtitle = stringResource(R.string.android_tv_interface_off_seek_settings_summary),
|
|
||||||
icon = painterResource(R.drawable.go_forward_30),
|
|
||||||
valueRange = 5..60,
|
|
||||||
//steps = 10,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
),
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_player_layout),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.player.limitPlayerTitle,
|
|
||||||
title = stringResource(R.string.limit_title),
|
|
||||||
icon = painterResource(R.drawable.match_word_24px),
|
|
||||||
entries = integerArrayResource(R.array.limit_title_pref_values).zip(
|
|
||||||
stringArrayResource(R.array.limit_title_pref_names)
|
|
||||||
).toMap()
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
enabled = isLayout(PHONE or EMULATOR),
|
|
||||||
preference = settings.player.hidePlayerControlNames,
|
|
||||||
icon = painterResource(R.drawable.visibility_off_24px),
|
|
||||||
title = stringResource(R.string.hide_player_control_names),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.showName,
|
|
||||||
icon = painterResource(R.drawable.label_24px),
|
|
||||||
title = stringResource(R.string.source_name),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.showMediaInfo,
|
|
||||||
icon = painterResource(R.drawable.movie_info_24px),
|
|
||||||
title = stringResource(R.string.video_info),
|
|
||||||
),
|
|
||||||
Preference.PreferenceItem.SwitchPreference(
|
|
||||||
preference = settings.player.showResolution,
|
|
||||||
title = stringResource(R.string.resolution),
|
|
||||||
icon = painterResource(R.drawable.high_res_24px),
|
|
||||||
),
|
|
||||||
|
|
||||||
// Unsure if we want to have MultiSelectListPreference or boolean
|
|
||||||
/*Preference.PreferenceItem.MultiSelectListPreference(
|
|
||||||
preference = settings.player.showPlayerInfo,
|
|
||||||
title = stringResource(R.string.limit_title_rez),
|
|
||||||
icon = painterResource(R.drawable.ic_baseline_text_format_24),
|
|
||||||
entries = persistentMapOf(
|
|
||||||
ShowPlayerInfo.Name to stringResource(R.string.source_name),
|
|
||||||
ShowPlayerInfo.Resolution to stringResource(R.string.resolution),
|
|
||||||
ShowPlayerInfo.VideoInfo to stringResource(R.string.video_info),
|
|
||||||
)
|
|
||||||
), */
|
|
||||||
)
|
|
||||||
),
|
|
||||||
Preference.PreferenceGroup(
|
|
||||||
title = stringResource(R.string.pref_category_cache),
|
|
||||||
preferenceItems = persistentListOf(
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.player.bufferDiskMB,
|
|
||||||
title = stringResource(R.string.video_buffer_disk_settings),
|
|
||||||
subtitle = "%s\n" + stringResource(R.string.video_disk_description),
|
|
||||||
icon = painterResource(R.drawable.hard_drive_24px),
|
|
||||||
entries = integerArrayResource(R.array.video_buffer_size_values).zip(
|
|
||||||
stringArrayResource(R.array.video_buffer_size_names)
|
|
||||||
).toMap()
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.player.bufferRamMB,
|
|
||||||
title = stringResource(R.string.video_buffer_size_settings),
|
|
||||||
subtitle = "%s\n" + stringResource(R.string.video_ram_description),
|
|
||||||
icon = painterResource(R.drawable.memory_alt_24px),
|
|
||||||
entries = integerArrayResource(R.array.video_buffer_size_values).zip(
|
|
||||||
stringArrayResource(R.array.video_buffer_size_names)
|
|
||||||
).toMap()
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.ListPreference(
|
|
||||||
preference = settings.player.bufferTimeSec,
|
|
||||||
title = stringResource(R.string.video_buffer_length_settings),
|
|
||||||
subtitle = "%s\n" + stringResource(R.string.video_ram_description),
|
|
||||||
icon = painterResource(R.drawable.history_toggle_off_24px),
|
|
||||||
entries = integerArrayResource(R.array.video_buffer_length_values).zip(
|
|
||||||
stringArrayResource(R.array.video_buffer_length_names)
|
|
||||||
).toMap()
|
|
||||||
),
|
|
||||||
|
|
||||||
Preference.PreferenceItem.TextPreference(
|
|
||||||
icon = painterResource(R.drawable.ic_baseline_delete_outline_24),
|
|
||||||
title = stringResource(R.string.video_buffer_clear_settings),
|
|
||||||
subtitle = formatShortFileSize(LocalContext.current, cacheSize),
|
|
||||||
onClick = {
|
|
||||||
ioSafe {
|
|
||||||
cacheDir.deleteRecursively()
|
|
||||||
cacheCleared += 1
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
),
|
|
||||||
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -109,13 +109,12 @@ class SettingsProviders : BasePreferenceFragmentCompat() {
|
||||||
return@setOnPreferenceClickListener true
|
return@setOnPreferenceClickListener true
|
||||||
}
|
}
|
||||||
|
|
||||||
getPref(R.string.
|
getPref(R.string.provider_lang_key)?.setOnPreferenceClickListener {
|
||||||
provider_lang_key)?.setOnPreferenceClickListener {
|
|
||||||
activity?.getApiProviderLangSettings()?.let { currentLangTags ->
|
activity?.getApiProviderLangSettings()?.let { currentLangTags ->
|
||||||
val languagesTagName = APIHolder.apis.withLock {
|
val languagesTagName = synchronized(APIHolder.apis) {
|
||||||
listOf(Pair(AllLanguagesName, getString(R.string.all_languages_preference))) +
|
listOf( Pair(AllLanguagesName, getString(R.string.all_languages_preference)) ) +
|
||||||
APIHolder.apis.map { Pair(it.lang, getNameNextToFlagEmoji(it.lang) ?: it.lang) }
|
APIHolder.apis.map { Pair(it.lang, getNameNextToFlagEmoji(it.lang) ?: it.lang) }
|
||||||
.toSet().sortedBy { it.second.substringAfter("\u00a0").lowercase() }
|
.toSet().sortedBy { it.second.substringAfter("\u00a0").lowercase() } // name ignoring flag emoji
|
||||||
}
|
}
|
||||||
|
|
||||||
val currentIndexList = currentLangTags.map { langTag ->
|
val currentIndexList = currentLangTags.map { langTag ->
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
package com.lagradost.cloudstream3.ui.settings
|
|
||||||
import com.lagradost.cloudstream3.utils.BaseComposeFragment
|
|
||||||
import com.mihon.presentation.settings.SearchableSettings
|
|
||||||
|
|
||||||
/** Empty glue code to connect the old navigation graph to Compose */
|
|
||||||
@Deprecated("This setting was merged into other places")
|
|
||||||
class SettingsProviders2 : BaseComposeFragment(), SearchableSettings by SettingsProvidersScreen
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue