diff --git a/.github/images/download-cloudstream-pre.png b/.github/images/download-cloudstream-pre.png
deleted file mode 100644
index db1f90552..000000000
Binary files a/.github/images/download-cloudstream-pre.png and /dev/null differ
diff --git a/.github/workflows/build_to_archive.yml b/.github/workflows/build_to_archive.yml
index 056022d22..b5960d5d9 100644
--- a/.github/workflows/build_to_archive.yml
+++ b/.github/workflows/build_to_archive.yml
@@ -71,10 +71,7 @@ jobs:
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
- TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
- MAL_KEY: ${{ secrets.MAL_KEY }}
- ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
- uses: actions/checkout@v6
with:
diff --git a/.github/workflows/instrumented-tests.yml b/.github/workflows/instrumented-tests.yml
deleted file mode 100644
index 34c6eaf0b..000000000
--- a/.github/workflows/instrumented-tests.yml
+++ /dev/null
@@ -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 }})'
- })
diff --git a/.github/workflows/issue_action.yml b/.github/workflows/issue_action.yml
new file mode 100644
index 000000000..e354d657d
--- /dev/null
+++ b/.github/workflows/issue_action.yml
@@ -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'
diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml
index f089afa8f..d9a20a04b 100644
--- a/.github/workflows/prerelease.yml
+++ b/.github/workflows/prerelease.yml
@@ -62,10 +62,7 @@ jobs:
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
- TRAKT_CLIENT_ID: ${{ secrets.TRAKT_CLIENT_ID }}
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
- MAL_KEY: ${{ secrets.MAL_KEY }}
- ANILIST_KEY: ${{ secrets.ANILIST_KEY }}
- name: Create pre-release
uses: marvinpinto/action-automatic-releases@latest
diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml
index 433816e0f..675ce3b2f 100644
--- a/.github/workflows/pull_request.yml
+++ b/.github/workflows/pull_request.yml
@@ -26,13 +26,8 @@ jobs:
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
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
- run: ./gradlew assemblePrereleaseDebug lint check
+ run: ./gradlew assemblePrereleaseDebug lint
- name: Upload Artifact
uses: actions/upload-artifact@v7
diff --git a/COMPOSE.md b/COMPOSE.md
deleted file mode 100644
index 8d83a50ae..000000000
--- a/COMPOSE.md
+++ /dev/null
@@ -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.
\ No newline at end of file
diff --git a/README.md b/README.md
index 237d7d8fc..c2492c5d8 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,6 @@
# CloudStream
**⚠️ Warning: By default, this app doesn't provide any video sources; you have to install extensions to add functionality to the app.**
-

[](https://discord.gg/5Hus6fM)
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index c714368ee..ae5301929 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -8,9 +8,6 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
plugins {
alias(libs.plugins.android.application)
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())
@@ -106,8 +103,8 @@ android {
applicationId = "com.lagradost.cloudstream3"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
- versionCode = libs.versions.versionCode.get().toInt()
- versionName = libs.versions.versionName.get()
+ versionCode = 68
+ versionName = "4.7.0"
manifestPlaceholders["target_sdk_version"] = libs.versions.targetSdk.get()
@@ -129,16 +126,6 @@ android {
"SIMKL_CLIENT_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"
}
@@ -219,11 +206,9 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.json)
androidTestImplementation(libs.core)
- androidTestImplementation(libs.espresso.core)
+ implementation(libs.junit.ktx)
androidTestImplementation(libs.ext.junit)
- androidTestImplementation(libs.instancio.core)
- androidTestImplementation(libs.junit.ktx)
- androidTestImplementation(libs.kotlin.test)
+ androidTestImplementation(libs.espresso.core)
// Android Core & Lifecycle
implementation(libs.core.ktx)
@@ -234,7 +219,6 @@ dependencies {
implementation(libs.bundles.lifecycle)
implementation(libs.bundles.navigation)
implementation(libs.kotlinx.collections.immutable)
- implementation(libs.kotlinx.serialization.json) // JSON Parser
// Design & UI
implementation(libs.preference.ktx)
@@ -270,19 +254,14 @@ dependencies {
// Extensions & Other Libs
implementation(libs.jsoup) // HTML Parser
- implementation(libs.ksoup) // HTML Parser
implementation(libs.rhino) // Run JavaScript
+ implementation(libs.fuzzywuzzy) // Library/Ext Searching with Levenshtein Distance
implementation(libs.safefile) // To Prevent the URI File Fu*kery
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.jackson.module.kotlin) // JSON Parser
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
implementation(libs.torrentserver)
@@ -290,12 +269,7 @@ dependencies {
implementation(libs.work.runtime.ktx)
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(":shared"))
}
tasks.register("androidSourcesJar") {
@@ -332,6 +306,7 @@ tasks.withType {
compilerOptions {
jvmTarget.set(javaTarget)
jvmDefault.set(JvmDefaultMode.ENABLE)
+ freeCompilerArgs.add("-Xannotation-default-target=param-property")
optIn.addAll(
"com.lagradost.cloudstream3.InternalAPI",
"com.lagradost.cloudstream3.Prerelease",
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
index 1d596ccee..4c5cdea5b 100644
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
@@ -55,6 +55,12 @@ class ExampleInstrumentedTest {
return APIHolder.allProviders.toTypedArray() //.filter { !it.usesWebView }
}
+ @Test
+ fun providersExist() {
+ Assert.assertTrue(getAllProviders().isNotEmpty())
+ println("Done providersExist")
+ }
+
@Throws
private inline fun testAllLayouts(
activity: Activity,
@@ -163,7 +169,7 @@ class ExampleInstrumentedTest {
TestingUtils.getDeferredProviderTests(
this,
getAllProviders(),
- ) { _, _, _ -> }
+ ) { _, _ -> }
}
}
}
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
deleted file mode 100644
index 84ef1fee0..000000000
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
+++ /dev/null
@@ -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()
-
- 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()
-
- 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> {
- 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
- return kotlinxMapper.encodeToString(serializer, value)
- }
-}
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt
deleted file mode 100644
index 3ffd37124..000000000
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/UriSerializerTest.kt
+++ /dev/null
@@ -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(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(encoded)
- assertEquals(data.uri, decoded.uri)
- }
-}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3ff59515e..b2c7091b0 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -22,47 +22,6 @@
android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -253,10 +212,6 @@
-
-
setKey(path: String, value: T) =
CloudStreamApp.setKey(path, value)
@@ -38,7 +38,7 @@ class AcraApplication {
@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(folder, path, value)"),
- level = DeprecationLevel.ERROR
+ level = DeprecationLevel.WARNING
)
fun setKey(folder: String, path: String, value: T) =
CloudStreamApp.setKey(folder, path, value)
@@ -46,7 +46,7 @@ class AcraApplication {
@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path, defVal)"),
- level = DeprecationLevel.ERROR
+ level = DeprecationLevel.WARNING
)
inline fun getKey(path: String, defVal: T?): T? =
CloudStreamApp.getKey(path, defVal)
@@ -54,7 +54,7 @@ class AcraApplication {
@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path)"),
- level = DeprecationLevel.ERROR
+ level = DeprecationLevel.WARNING
)
inline fun getKey(path: String): T? =
CloudStreamApp.getKey(path)
@@ -62,7 +62,7 @@ class AcraApplication {
@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path)"),
- level = DeprecationLevel.ERROR
+ level = DeprecationLevel.WARNING
)
inline fun getKey(folder: String, path: String): T? =
CloudStreamApp.getKey(folder, path)
@@ -70,7 +70,7 @@ class AcraApplication {
@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path, defVal)"),
- level = DeprecationLevel.ERROR
+ level = DeprecationLevel.WARNING
)
inline fun getKey(folder: String, path: String, defVal: T?): T? =
CloudStreamApp.getKey(folder, path, defVal)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt b/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
index 6ff3ab54d..a9cd9c01e 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
@@ -113,7 +113,7 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
get() = _context?.get()
private set(value) {
_context = WeakReference(value)
- setContext(value)
+ setContext(WeakReference(value))
}
fun getKeyClass(path: String, valueType: Class): T? {
@@ -170,11 +170,11 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
}
/** Will fall back to WebView if in TV or emulator layout. */
- fun openBrowser(url: String, activity: Activity?) {
+ fun openBrowser(url: String, activity: FragmentActivity?) {
openBrowser(
url,
isLayout(TV or EMULATOR),
- (activity as? FragmentActivity)?.supportFragmentManager?.fragments?.lastOrNull()
+ activity?.supportFragmentManager?.fragments?.lastOrNull()
)
}
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
index 8daf168c1..ed0aaf9b7 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
@@ -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.extensions.PluginAdapter
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.Event
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
@@ -267,9 +266,7 @@ object CommonActivity {
}
// 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 &&
- !isAuthEnabled(componentActivity) &&
ContextCompat.checkSelfPermission(
componentActivity,
Manifest.permission.POST_NOTIFICATIONS
@@ -582,10 +579,8 @@ object CommonActivity {
// TODO: Figure out why removing the check for SearchAutoComplete seems
// 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")
- 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)
) {
showInputMethod(act.currentFocus?.findFocus())
@@ -606,4 +601,4 @@ object CommonActivity {
}
return null
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
index c13b2600c..8a98bd297 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
@@ -171,19 +171,13 @@ import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.UIHelper.requestRW
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.USER_PROVIDER_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.setTextHtml
import com.lagradost.cloudstream3.utils.txt
-import com.lagradost.cloudstream4.compose.CloudStreamThemeAppSettings
-import com.lagradost.cloudstream4.theme.CloudStreamTheme
import com.lagradost.safefile.SafeFile
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.cancel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
@@ -193,8 +187,10 @@ import java.net.URLDecoder
import java.nio.charset.Charset
import kotlin.math.abs
import kotlin.math.absoluteValue
-import kotlin.reflect.full.createInstance
import kotlin.system.exitProcess
+import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.cancel
class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCallback {
companion object {
@@ -412,10 +408,13 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
return true
}
- val matchedApi = apis.filter { str.startsWith(it.mainUrl) }.firstOrNull()
- if (matchedApi != null) {
- loadResult(str, matchedApi.name, "")
- return true
+ synchronized(apis) {
+ for (api in apis) {
+ if (str.startsWith(api.mainUrl)) {
+ loadResult(str, api.name, "")
+ return true
+ }
+ }
}
}
}
@@ -788,6 +787,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
}
+
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
.setEnterAnim(R.anim.enter_anim)
.setExitAnim(R.anim.exit_anim)
@@ -809,33 +809,32 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
}
+
private val pluginsLock = Mutex()
private fun onAllPluginsLoaded(success: Boolean = false) {
ioSafe {
pluginsLock.withLock {
- allProviders.withLock {
+ synchronized(allProviders) {
// Load cloned sites after plugins have been loaded since clones depend on plugins.
try {
getKey>(USER_PROVIDER_API)?.let { list ->
list.forEach { custom ->
- allProviders.firstOrNull {
- it::class.simpleName == custom.parentClassName
- }?.let {
- allProviders.add(
- it::class.createInstance().apply {
- name = custom.name
- lang = custom.lang
- mainUrl = custom.url.trimEnd('/')
- canBeOverridden = false
- }
- )
- }
+ allProviders.firstOrNull { it.javaClass.simpleName == custom.parentJavaClass }
+ ?.let {
+ allProviders.add(
+ it.javaClass.getDeclaredConstructor().newInstance()
+ .apply {
+ name = custom.name
+ lang = custom.lang
+ mainUrl = custom.url.trimEnd('/')
+ canBeOverridden = false
+ })
+ }
}
}
// it.hashCode() is not enough to make sure they are distinct
- apis = allProviders.distinctBy {
- it.lang + it.name + it.mainUrl + it::class.qualifiedName
- }
+ apis =
+ allProviders.distinctBy { it.lang + it.name + it.mainUrl + it.javaClass.name }
APIHolder.apiMap = null
} catch (e: Exception) {
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?
safe {
val appVer = BuildConfig.VERSION_NAME
- val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
+ val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
if (appVer != lastAppAutoBackup) {
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
if (lastAppAutoBackup.isEmpty()) return@safe
@@ -1299,14 +1298,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
padRight = false,
padTop = false
)
-
- composeView.apply {
- setContent {
- CloudStreamThemeAppSettings {
- MainActivityScreen.Content()
- }
- }
- }
}
// overscan
@@ -1379,7 +1370,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
//Automatically download not existing plugins, using mode specified.
- /*val autoDownloadPlugin = AutoDownloadMode.getEnum(
+ val autoDownloadPlugin = AutoDownloadMode.getEnum(
settingsManager.getInt(
getString(R.string.auto_download_plugins_key),
0
@@ -1390,7 +1381,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
this@MainActivity,
autoDownloadPlugin
)
- }*/
+ }
}
ioSafe {
@@ -1439,9 +1430,8 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
else -> {
resultviewPreviewBookmark.isEnabled = false
- resultviewPreviewBookmark.showProgress()
- //resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
- //resultviewPreviewBookmark.setText(R.string.loading)
+ resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
+ resultviewPreviewBookmark.setText(R.string.loading)
}
}
}
@@ -1667,7 +1657,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
ioSafe {
initAll()
// 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)
@@ -1975,7 +1967,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
if (BuildConfig.DEBUG) {
var providersAndroidManifestString = "Current androidmanifest should be:\n"
- allProviders.withLock {
+ synchronized(allProviders) {
for (api in allProviders) {
providersAndroidManifestString += "(HAS_DONE_SETUP_KEY, false) != true) {
+ if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
navController.navigate(R.id.navigation_setup_language)
// If no plugins bring up extensions screen
} else if (PluginManager.getPluginsOnline().isEmpty()
diff --git a/app/src/main/java/com/lagradost/cloudstream3/MainActivityScreen.kt b/app/src/main/java/com/lagradost/cloudstream3/MainActivityScreen.kt
deleted file mode 100644
index 9bab11562..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/MainActivityScreen.kt
+++ /dev/null
@@ -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
- )
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
index 0fdccb476..4843b7617 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
@@ -20,10 +20,8 @@ import com.lagradost.cloudstream3.actions.temp.MpvExPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPreviewPackage
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.NextPlayerPackage
-import com.lagradost.cloudstream3.actions.temp.OnlyPlayer
import com.lagradost.cloudstream3.actions.temp.PlayInBrowserAction
import com.lagradost.cloudstream3.actions.temp.PlayMirrorAction
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.ui.result.LinkLoadingResult
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.threadSafeListOf
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.UiText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.Callable
import java.util.concurrent.FutureTask
+import kotlin.reflect.jvm.jvmName
object VideoClickActionHolder {
- val allVideoClickActions = atomicListOf(
+ val allVideoClickActions = threadSafeListOf(
// Default
PlayInBrowserAction(),
CopyClipboardAction(),
@@ -65,8 +64,6 @@ object VideoClickActionHolder {
MpvYTDLPackage(),
MpvKtPackage(),
MpvKtPreviewPackage(),
- OnlyPlayer(),
- MpvRxPackage(),
// Always Ask option
AlwaysAskAction(),
// added by plugins
@@ -98,7 +95,7 @@ object VideoClickActionHolder {
?.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 {
@@ -160,7 +157,7 @@ abstract class VideoClickAction {
}
}
- fun uniqueId() = "$sourcePlugin:${this::class.qualifiedName}"
+ fun uniqueId() = "$sourcePlugin:${this::class.jvmName}"
@Throws
abstract fun shouldShow(context: Context?, video: ResultEpisode?): Boolean
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
index a2bb53a16..d414b6117 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
@@ -7,7 +7,6 @@ import android.net.Uri
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.BuildConfig
-import com.lagradost.cloudstream3.SkipSerializationTest
import com.lagradost.cloudstream3.ui.player.ExtractorUri
import com.lagradost.cloudstream3.ui.player.SubtitleData
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.SubtitleHelper.fromCodeToLangTagIETF
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
-import com.lagradost.cloudstream3.utils.serializers.UriSerializer
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
@@ -53,17 +49,19 @@ class CloudStreamPackage : OpenInAppAction(
const val DURATION_EXTRA: String = "dur" // Duration time in MS (Long)
}
- @Serializable
- @SkipSerializationTest //.Uri has issues with Jackson
data class MinimalVideoLink(
- @JsonProperty("uri") @SerialName("uri")
- @Serializable(with = UriSerializer::class)
+ @JsonProperty("uri")
val uri: Uri?,
- @JsonProperty("url") @SerialName("url") val url: String?,
- @JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "video/mp4",
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("headers") @SerialName("headers") var headers: Map = mapOf(),
- @JsonProperty("quality") @SerialName("quality") val quality: Int?,
+ @JsonProperty("url")
+ val url: String?,
+ @JsonProperty("mimeType")
+ val mimeType: String = "video/mp4",
+ @JsonProperty("name")
+ val name: String?,
+ @JsonProperty("headers")
+ var headers: Map = mapOf(),
+ @JsonProperty("quality")
+ val quality: Int?,
) {
companion object {
fun fromExtractor(link: ExtractorLink): MinimalVideoLink = MinimalVideoLink(
@@ -99,12 +97,16 @@ class CloudStreamPackage : OpenInAppAction(
}
}
- @Serializable
+
data class MinimalSubtitleLink(
- @JsonProperty("url") @SerialName("url") val url: String,
- @JsonProperty("mimeType") @SerialName("mimeType") val mimeType: String = "text/vtt",
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("headers") @SerialName("headers") var headers: Map = mapOf(),
+ @JsonProperty("url")
+ val url: String,
+ @JsonProperty("mimeType")
+ val mimeType: String = "text/vtt",
+ @JsonProperty("name")
+ val name: String?,
+ @JsonProperty("headers")
+ var headers: Map = mapOf(),
) {
companion object {
fun fromSubtitle(sub: SubtitleData): MinimalSubtitleLink = MinimalSubtitleLink(
@@ -157,4 +159,4 @@ class CloudStreamPackage : OpenInAppAction(
override fun onResult(activity: Activity, intent: Intent?) {
// No results yet
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt
deleted file mode 100644
index e8bb93a99..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvRxPackage.kt
+++ /dev/null
@@ -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() )*/
-
- 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())
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt
deleted file mode 100644
index 348be440a..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/OnlyPlayer.kt
+++ /dev/null
@@ -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 */
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
index b6478b1d9..46b46a2c2 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
@@ -60,7 +60,7 @@ open class VlcPackage: OpenInAppAction(
intent.putExtra("secure_uri", true)
intent.putExtra("title", video.name)
- val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
+ val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
result.subs.firstOrNull {
subsLang == it.languageCode
}?.let {
@@ -74,4 +74,4 @@ open class VlcPackage: OpenInAppAction(
Log.d("VLC", "Position: $position, Duration: $duration")
updateDurationAndPosition(position, duration)
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
index d54791e89..26f5cec53 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
@@ -1,9 +1,5 @@
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
enum class Opcode(val value: Byte) {
None(0),
@@ -22,18 +18,18 @@ enum class Opcode(val value: Byte) {
Pong(13);
}
-@Serializable
+
data class PlayMessage(
- @JsonProperty("container") @SerialName("container") val container: String,
- @JsonProperty("url") @SerialName("url") val url: String? = null,
- @JsonProperty("content") @SerialName("content") val content: String? = null,
- @JsonProperty("time") @SerialName("time") val time: Double? = null,
- @JsonProperty("speed") @SerialName("speed") val speed: Double? = null,
- @JsonProperty("headers") @SerialName("headers") val headers: Map? = null,
+ val container: String,
+ val url: String? = null,
+ val content: String? = null,
+ val time: Double? = null,
+ val speed: Double? = null,
+ val headers: Map? = null
)
data class SeekMessage(
- val time: Double,
+ val time: Double
)
data class PlaybackUpdateMessage(
@@ -41,26 +37,26 @@ data class PlaybackUpdateMessage(
val time: Double,
val duration: Double,
val state: Int,
- val speed: Double,
+ val speed: Double
)
data class VolumeUpdateMessage(
val generationTime: Long,
- val volume: Double,
+ val volume: Double
)
data class PlaybackErrorMessage(
- val message: String,
+ val message: String
)
data class SetSpeedMessage(
- val speed: Double,
+ val speed: Double
)
data class SetVolumeMessage(
- val volume: Double,
+ val volume: Double
)
data class VersionMessage(
- val version: Long,
+ val version: Long
)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt b/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
index e49245904..6234297d0 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
@@ -22,6 +22,7 @@ fun Requests.initClient(context: Context) {
}
/** Only use ignoreSSL if you know what you are doing*/
+@Prerelease
fun Requests.initClient(context: Context, ignoreSSL: Boolean = false) {
this.baseClient = buildDefaultClient(context, ignoreSSL)
}
@@ -33,11 +34,12 @@ fun buildDefaultClient(context: Context): OkHttpClient {
}
/** Only use ignoreSSL if you know what you are doing*/
+@Prerelease
fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClient {
safe { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
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()
.followRedirects(true)
.followSslRedirects(true)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
index e1496db06..efa028d14 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
@@ -7,6 +7,7 @@ import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import kotlin.Throws
+
abstract class Plugin : BasePlugin() {
/**
* Called when your Plugin is loaded
@@ -25,7 +26,9 @@ abstract class Plugin : BasePlugin() {
fun registerVideoClickAction(element: VideoClickAction) {
Log.i(PLUGIN_TAG, "Adding ${element.name} VideoClickAction")
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
*/
var openSettings: ((context: Context) -> Unit)? = null
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
index 7ea736416..eae14a6c0 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
@@ -61,8 +61,6 @@ import com.lagradost.cloudstream3.utils.txt
import dalvik.system.PathClassLoader
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.io.File
import java.io.InputStreamReader
@@ -75,13 +73,12 @@ const val EXTENSIONS_CHANNEL_NAME = "Extensions"
const val EXTENSIONS_CHANNEL_DESCRIPT = "Extension notification channel"
// Data class for internal storage
-@Serializable
data class PluginData(
- @JsonProperty("internalName") @SerialName("internalName") val internalName: String,
- @JsonProperty("url") @SerialName("url") val url: String?,
- @JsonProperty("isOnline") @SerialName("isOnline") val isOnline: Boolean,
- @JsonProperty("filePath") @SerialName("filePath") val filePath: String,
- @JsonProperty("version") @SerialName("version") val version: Int,
+ @JsonProperty("internalName") val internalName: String,
+ @JsonProperty("url") val url: String?,
+ @JsonProperty("isOnline") val isOnline: Boolean,
+ @JsonProperty("filePath") val filePath: String,
+ @JsonProperty("version") val version: Int,
) {
@WorkerThread
fun toSitePlugin(): SitePlugin {
@@ -176,11 +173,11 @@ object PluginManager {
fun getPluginsOnline(): Array {
- return getKey>(PLUGINS_KEY) ?: emptyArray()
+ return getKey(PLUGINS_KEY) ?: emptyArray()
}
fun getPluginsLocal(): Array {
- return getKey>(PLUGINS_KEY_LOCAL) ?: emptyArray()
+ return getKey(PLUGINS_KEY_LOCAL) ?: emptyArray()
}
private val CLOUD_STREAM_FOLDER =
@@ -224,17 +221,17 @@ object PluginManager {
// Helper class for updateAllOnlinePluginsAndLoadThem
data class OnlinePluginData(
val savedData: PluginData,
- val onlineData: PluginWrapper,
+ val onlineData: Pair,
) {
val isOutdated =
- onlineData.plugin.version > savedData.version || onlineData.plugin.version == PLUGIN_VERSION_ALWAYS_UPDATE
- val isDisabled = onlineData.plugin.status == PROVIDER_STATUS_DOWN
+ onlineData.second.version > savedData.version || onlineData.second.version == PLUGIN_VERSION_ALWAYS_UPDATE
+ val isDisabled = onlineData.second.status == PROVIDER_STATUS_DOWN
fun validOnlineData(context: Context): Boolean {
return getPluginPath(
context,
savedData.internalName,
- onlineData.repositoryData.url
+ onlineData.first
).absolutePath == savedData.filePath
}
}
@@ -282,19 +279,19 @@ object PluginManager {
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it) ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
+ getRepoPlugins(it.url)?.toList() ?: emptyList()
+ }.flatten().distinctBy { it.second.url }
// Iterates over all offline plugins, compares to remote repo and returns the plugins which are outdated
val outdatedPlugins = getPluginsOnline().map { savedData ->
onlinePlugins
- .filter { onlineData -> savedData.internalName == onlineData.plugin.internalName }
+ .filter { onlineData -> savedData.internalName == onlineData.second.internalName }
.map { onlineData ->
OnlinePluginData(savedData, onlineData)
}.filter {
it.validOnlineData(activity)
}
- }.flatten().distinctBy { it.onlineData.plugin.url }
+ }.flatten().distinctBy { it.onlineData.second.url }
debugPrint {
"Outdated plugins: ${outdatedPlugins.filter { it.isOutdated }}"
@@ -309,14 +306,14 @@ object PluginManager {
} else if (pluginData.isOutdated) {
downloadPlugin(
activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
+ pluginData.onlineData.second.url,
+ pluginData.onlineData.second.fileHash,
pluginData.savedData.internalName,
File(pluginData.savedData.filePath),
true
).let { success ->
if (success)
- updatedPlugins.add(pluginData.onlineData.plugin.name)
+ updatedPlugins.add(pluginData.onlineData.second.name)
}
}
}
@@ -359,15 +356,15 @@ object PluginManager {
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it)?.toList() ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
+ getRepoPlugins(it.url)?.toList() ?: emptyList()
+ }.flatten().distinctBy { it.second.url }
val providerLang = activity.getApiProviderLangSettings()
//Log.i(TAG, "providerLang => ${providerLang.toJson()}")
// Iterate online repos and returns not downloaded plugins
val notDownloadedPlugins = onlinePlugins.mapNotNull { onlineData ->
- val sitePlugin = onlineData.plugin
+ val sitePlugin = onlineData.second
val tvtypes = sitePlugin.tvTypes ?: listOf()
//Don't include empty urls
@@ -379,7 +376,7 @@ object PluginManager {
}
//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}")
return@mapNotNull null
}
@@ -421,14 +418,14 @@ object PluginManager {
notDownloadedPlugins.amap { pluginData ->
downloadPlugin(
activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
+ pluginData.onlineData.second.url,
+ pluginData.onlineData.second.fileHash,
pluginData.savedData.internalName,
- pluginData.onlineData.repositoryData.url,
+ pluginData.onlineData.first,
!pluginData.isDisabled
).let { 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()
if (!res) {
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
}
}
@@ -590,7 +584,7 @@ object PluginManager {
/**
* @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 filePath = file.absolutePath
currentlyLoading = fileName
@@ -616,7 +610,7 @@ object PluginManager {
return false
}
InputStreamReader(stream).use { reader ->
- manifest = parseJson(reader.readText())
+ manifest = parseJson(reader, BasePlugin.Manifest::class.java)
}
}
@@ -657,15 +651,9 @@ object PluginManager {
context.resources.configuration
)
}
- synchronized(plugins) {
- plugins[filePath] = pluginInstance
- }
- synchronized(classLoaders) {
- classLoaders[loader] = pluginInstance
- }
- synchronized(urlPlugins) {
- urlPlugins[data.url ?: filePath] = pluginInstance
- }
+ plugins[filePath] = pluginInstance
+ classLoaders[loader] = pluginInstance
+ urlPlugins[data.url ?: filePath] = pluginInstance
if (pluginInstance is Plugin) {
pluginInstance.load(context)
} else {
@@ -701,20 +689,21 @@ object PluginManager {
}
// remove all registered apis
- APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
- removePluginMapping(it)
+ synchronized(APIHolder.apis) {
+ 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 {
- APIHolder.allProviders.removeAll { provider -> provider.sourcePlugin == plugin.filename }
+ synchronized(extractorApis) {
+ extractorApis.removeIf { provider: ExtractorApi -> provider.sourcePlugin == plugin.filename }
}
- extractorApis.withLock {
- extractorApis.removeAll { provider -> provider.sourcePlugin == plugin.filename }
- }
-
- VideoClickActionHolder.allVideoClickActions.withLock {
- VideoClickActionHolder.allVideoClickActions.removeAll { action -> action.sourcePlugin == plugin.filename }
+ synchronized(VideoClickActionHolder.allVideoClickActions) {
+ VideoClickActionHolder.allVideoClickActions.removeIf { action: VideoClickAction -> action.sourcePlugin == plugin.filename }
}
synchronized(classLoaders) {
@@ -838,16 +827,16 @@ object PluginManager {
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
- getRepoPlugins(it) ?: emptyList()
- }.flatten().distinctBy { it.plugin.url }
+ getRepoPlugins(it.url)?.toList() ?: emptyList()
+ }.flatten().distinctBy { it.second.url }
val allPlugins = getPluginsOnline().flatMap { savedData ->
onlinePlugins
- .filter { it.plugin.internalName == savedData.internalName }
+ .filter { it.second.internalName == savedData.internalName }
.mapNotNull { onlineData ->
OnlinePluginData(savedData, onlineData).takeIf { it.validOnlineData(activity) }
}
- }.distinctBy { it.onlineData.plugin.url }
+ }.distinctBy { it.onlineData.second.url }
val updatedPlugins = mutableListOf()
@@ -855,7 +844,7 @@ object PluginManager {
if (pluginData.isDisabled) {
Log.e(
"PluginManager",
- "Unloading disabled plugin: ${pluginData.onlineData.plugin.name}"
+ "Unloading disabled plugin: ${pluginData.onlineData.second.name}"
)
unloadPlugin(pluginData.savedData.filePath)
} else {
@@ -864,14 +853,14 @@ object PluginManager {
if (downloadPlugin(
activity,
- pluginData.onlineData.plugin.url,
- pluginData.onlineData.plugin.fileHash,
+ pluginData.onlineData.second.url,
+ pluginData.onlineData.second.fileHash,
pluginData.savedData.internalName,
existingFile,
true
)
) {
- updatedPlugins.add(pluginData.onlineData.plugin.name)
+ updatedPlugins.add(pluginData.onlineData.second.name)
}
}
}.also {
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
index 910d84735..07d6aaa37 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
@@ -16,27 +16,26 @@ import com.lagradost.cloudstream3.plugins.PluginManager.getPluginSanitizedFileNa
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
+import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.io.File
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
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.
- */
-@Serializable
+ * */
+
data class Repository(
- @JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("manifestVersion") @SerialName("manifestVersion") val manifestVersion: Int,
- @JsonProperty("pluginLists") @SerialName("pluginLists") val pluginLists: List,
+ @JsonProperty("iconUrl") val iconUrl: String?,
+ @JsonProperty("name") val name: String,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("manifestVersion") val manifestVersion: Int,
+ @JsonProperty("pluginLists") val pluginLists: List
)
/**
@@ -45,60 +44,40 @@ data class Repository(
* 1: Ok
* 2: Slow
* 3: Beta only
- */
-@Serializable
+ * */
data class SitePlugin(
// Url to the .cs3 file
- @JsonProperty("url") @SerialName("url") val url: String,
+ @JsonProperty("url") val url: String,
// 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
- @JsonProperty("version") @SerialName("version") val version: Int,
+ @JsonProperty("version") val version: Int,
// Unused currently, used to make the api backwards compatible?
// Set to 1
- @JsonProperty("apiVersion") @SerialName("apiVersion") val apiVersion: Int,
+ @JsonProperty("apiVersion") val apiVersion: Int,
// 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
- @JsonProperty("internalName") @SerialName("internalName") val internalName: String,
- @JsonProperty("authors") @SerialName("authors") val authors: List,
- @JsonProperty("description") @SerialName("description") val description: String?,
+ @JsonProperty("internalName") val internalName: String,
+ @JsonProperty("authors") val authors: List,
+ @JsonProperty("description") val description: String?,
// 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
- @JsonProperty("tvTypes") @SerialName("tvTypes") val tvTypes: List?,
+ @JsonProperty("tvTypes") val tvTypes: List?,
// Most often a language tag like "en" or "zh-TW"
- @JsonProperty("language") @SerialName("language") val language: String?,
- @JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
+ @JsonProperty("language") val language: String?,
+ @JsonProperty("iconUrl") val iconUrl: String?,
// Automatically generated by the gradle plugin
- @JsonProperty("fileSize") @SerialName("fileSize") val fileSize: Long?,
- @JsonProperty("fileHash") @SerialName("fileHash") val fileHash: String?,
+ @JsonProperty("fileSize") val fileSize: Long?,
+ @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 {
const val ONLINE_PLUGINS_FOLDER = "Extensions"
val PREBUILT_REPOSITORIES: Array by lazy {
- getKey>("PREBUILT_REPOSITORIES") ?: emptyArray()
+ getKey("PREBUILT_REPOSITORIES") ?: emptyArray()
}
private val GH_REGEX =
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())) {
safeAsync {
- if (fixedUrl.startsWith("!")) {
- val response = app.get("https://py.md/${fixedUrl.removePrefix("!")}", allowRedirects = false)
- val url = response.headers["Location"] ?: return@safeAsync null
- if (url.startsWith("https://py.md/404")) return@safeAsync null
- if (url.removeSuffix("/") == "https://py.md") return@safeAsync null
- 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
+ app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false).let { it2 ->
+ it2.headers["Location"]?.let { url ->
+ if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
+ if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
+ return@safeAsync url
+ }
}
}
} else null
@@ -161,16 +134,17 @@ object RepositoryManager {
suspend fun parseRepository(url: String): Repository? {
return safeAsync {
// Take manifestVersion and such into account later
- app.get(convertRawGitUrl(url), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
- .parsedSafe()
+ app.get(convertRawGitUrl(url)).parsedSafe()
}
}
private suspend fun parsePlugins(pluginUrls: String): List {
// Take manifestVersion and such into account later
return try {
- app.get(convertRawGitUrl(pluginUrls), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
- .parsed>().toList()
+ val response = app.get(convertRawGitUrl(pluginUrls))
+ // Normal parsed function not working?
+ // return response.parsedSafe()
+ tryParseJson>(response.text)?.toList() ?: emptyList()
} catch (t: Throwable) {
logError(t)
emptyList()
@@ -179,17 +153,17 @@ object RepositoryManager {
/**
* Gets all plugins from repositories and pairs them with the repository url
- */
- suspend fun getRepoPlugins(repositoryData: RepositoryData): List? {
- val repo = parseRepository(repositoryData.url) ?: return null
- val list = repo.pluginLists.amap { url ->
+ * */
+ suspend fun getRepoPlugins(repositoryUrl: String): List>? {
+ val repo = parseRepository(repositoryUrl) ?: return null
+ return repo.pluginLists.amap { url ->
parsePlugins(url).map {
- PluginWrapper(repo, repositoryData, it)
+ repositoryUrl to it
}
}.flatten()
- return list
}
+
suspend fun downloadPluginToFile(
context: Context,
pluginUrl: String,
@@ -240,29 +214,22 @@ object RepositoryManager {
}
fun getRepositories(): Array {
- return getKey>(REPOSITORIES_KEY) ?: emptyArray()
+ return getKey(REPOSITORIES_KEY) ?: emptyArray()
}
// Don't want to read before we write in another thread
private val repoLock = Mutex()
suspend fun addRepository(repository: RepositoryData) {
repoLock.withLock {
- // No duplicates, but we want the new repository instead of the old one
- var currentRepos = getRepositories()
- val index = currentRepos.indexOfFirst { it.url == repository.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)
+ val currentRepos = getRepositories()
+ // No duplicates
+ setKey(REPOSITORIES_KEY, (currentRepos + repository).distinctBy { it.url })
}
}
/**
* Also deletes downloaded repository plugins
- */
+ * */
suspend fun removeRepository(context: Context, repository: RepositoryData) {
val extensionsDir = File(context.filesDir, ONLINE_PLUGINS_FOLDER)
diff --git a/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
index 57f6f4750..85a806f0b 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
@@ -2,7 +2,6 @@ package com.lagradost.cloudstream3.plugins
import android.util.Log
import android.widget.Toast
-import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
@@ -12,10 +11,9 @@ import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.utils.Coroutines.main
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
object VotingApi {
+
private const val LOGKEY = "VotingApi"
private const val API_DOMAIN = "https://api.countify.xyz"
@@ -52,8 +50,8 @@ object VotingApi {
votesCache[pluginUrl] = it
}
- fun hasVoted(pluginUrl: String): Boolean =
- getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
+ fun hasVoted(pluginUrl: String) =
+ getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
fun canVote(pluginUrl: String): Boolean =
PluginManager.urlPlugins.contains(pluginUrl)
@@ -93,9 +91,8 @@ object VotingApi {
}
}
- @Serializable
private data class CountifyResult(
- @JsonProperty("id") @SerialName("id") val id: String? = null,
- @JsonProperty("count") @SerialName("count") val count: Int? = null,
+ val id: String? = null,
+ val count: Int? = null
)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/receivers/PackageInstallerStatusReceiver.kt b/app/src/main/java/com/lagradost/cloudstream3/receivers/PackageInstallerStatusReceiver.kt
deleted file mode 100644
index 1739b8147..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/receivers/PackageInstallerStatusReceiver.kt
+++ /dev/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.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")
- }
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt b/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
index e07747a86..028356e76 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
@@ -36,7 +36,6 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
@@ -187,16 +186,6 @@ class DownloadQueueService : Service() {
debugAssert({ timeTaken == null }, { "Downloader startup should not time out" })
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) ->
// Stop if destroyed
isRunning
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
index 68fba9777..3bc5f2733 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
@@ -70,8 +70,7 @@ abstract class AccountManager {
SubtitleRepo(openSubtitlesApi),
SubtitleRepo(addic7ed),
SubtitleRepo(subDlApi),
- PlainAuthRepo(animeSkipApi),
- SubtitleRepo(subSourceApi)
+ PlainAuthRepo(animeSkipApi)
)
fun updateAccountIds() {
@@ -121,8 +120,7 @@ abstract class AccountManager {
val subtitleProviders = arrayOf(
SubtitleRepo(openSubtitlesApi),
SubtitleRepo(addic7ed),
- SubtitleRepo(subDlApi),
- SubtitleRepo(subSourceApi)
+ SubtitleRepo(subDlApi)
)
val syncApis = arrayOf(
SyncRepo(malApi),
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
index c0f0e4a03..83a7a0984 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
@@ -1,18 +1,50 @@
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.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.APIHolder.unixTime
-import com.lagradost.cloudstream3.APIHolder.unixTimeMS
-import com.lagradost.cloudstream3.base64Encode
-import com.lagradost.cloudstream3.splitUrlParameters
+import com.lagradost.cloudstream3.ActorData
+import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
+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 kotlinx.serialization.ExperimentalSerializationApi
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-import kotlinx.serialization.json.JsonNames
+import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.NONE_ID
+import com.lagradost.cloudstream3.syncproviders.providers.Addic7ed
+import com.lagradost.cloudstream3.syncproviders.providers.AniListApi
+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.util.Date
+import java.util.concurrent.TimeUnit
data class AuthLoginPage(
/** 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.
* This parameter will be saved, and then used in AuthAPI::login.
- */
+ * */
val payload: String? = null,
)
-@Serializable
data class AuthToken(
/**
* 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.
- */
- @JsonProperty("accessToken") @SerialName("accessToken")
+ *
+ * `Access tokens are the thing that applications use to make API requests on behalf of a user.`
+ * */
+ @JsonProperty("accessToken")
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,
/** In UnixTime (sec) when it expires */
- @JsonProperty("accessTokenLifetime") @SerialName("accessTokenLifetime")
+ @JsonProperty("accessTokenLifetime")
val accessTokenLifetime: Long? = null,
/** In UnixTime (sec) when it expires */
- @JsonProperty("refreshTokenLifetime") @SerialName("refreshTokenLifetime")
+ @JsonProperty("refreshTokenLifetime")
val refreshTokenLifetime: Long? = null,
- /**
- * Sometimes AuthToken needs to be customized to store e.g. username/password,
- * this acts as a catch all to store text or JSON data.
- */
- @JsonProperty("payload") @SerialName("payload")
+ /** Sometimes AuthToken needs to be customized to store e.g. username/password,
+ * this acts as a catch all to store text or JSON data. */
+ @JsonProperty("payload")
val payload: String? = null,
) {
fun isAccessTokenExpired(marginSec: Long = 10L) =
- accessTokenLifetime != null && unixTime + marginSec >= accessTokenLifetime
+ accessTokenLifetime != null && (System.currentTimeMillis() / 1000) + marginSec >= accessTokenLifetime
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(
/** Account display-name, can also be email if name does not exist */
- @JsonProperty("name") @SerialName("name")
+ @JsonProperty("name")
val name: String?,
- /**
- * Unique account identifier. If a subsequent login is done then it
- * will be refused if another account with the same id exists.
- */
- @JsonProperty("id") @SerialName("id")
+ /** Unique account identifier,
+ * if a subsequent login is done then it will be refused if another account with the same id exists*/
+ @JsonProperty("id")
val id: Int,
/** Profile picture URL */
- @JsonProperty("profilePicture") @SerialName("profilePicture")
+ @JsonProperty("profilePicture")
val profilePicture: String? = null,
/** Profile picture Headers of the URL */
- @JsonProperty("profilePictureHeaders") @JsonAlias("profilePictureHeader")
- @SerialName("profilePictureHeaders") @JsonNames("profilePictureHeader")
- val profilePictureHeaders: Map? = null,
+ @JsonProperty("profilePictureHeader")
+ val profilePictureHeaders: Map? = null
)
/**
@@ -83,11 +110,12 @@ data class AuthUser(
*
* Any local set/get key should use user.id.toString(),
* as token.accessToken (even hashed) is unsecure, and will rotate.
- */
-@Serializable
+ * */
data class AuthData(
- @JsonProperty("user") @SerialName("user") val user: AuthUser,
- @JsonProperty("token") @SerialName("token") val token: AuthToken,
+ @JsonProperty("user")
+ val user: AuthUser,
+ @JsonProperty("token")
+ val token: AuthToken,
)
data class AuthPinData(
@@ -110,12 +138,15 @@ data class AuthLoginRequirement(
)
/** What the user responds to the AuthLoginRequirement */
-@Serializable
data class AuthLoginResponse(
- @JsonProperty("password") @SerialName("password") val password: String?,
- @JsonProperty("username") @SerialName("username") val username: String?,
- @JsonProperty("email") @SerialName("email") val email: String?,
- @JsonProperty("server") @SerialName("server") val server: String?,
+ @JsonProperty("password")
+ val password: String?,
+ @JsonProperty("username")
+ val username: String?,
+ @JsonProperty("email")
+ val email: String?,
+ @JsonProperty("server")
+ val server: String?,
)
/** Stateless Authentication class used for all personalized content */
@@ -148,31 +179,16 @@ abstract class AuthAPI {
open val inAppLoginRequirement: AuthLoginRequirement? = null
companion object {
- @Deprecated(
- message = "Use APIHolder.unixTime instead",
- replaceWith = ReplaceWith(
- expression = "APIHolder.unixTime",
- imports = ["com.lagradost.cloudstream3.APIHolder"]
- ),
- level = DeprecationLevel.WARNING,
- )
val unixTime: Long
- get() = APIHolder.unixTime
-
- @Deprecated(
- message = "Use APIHolder.unixTimeMS instead",
- replaceWith = ReplaceWith(
- expression = "unixTimeMS",
- imports = ["com.lagradost.cloudstream3.APIHolder.unixTimeMS"]
- ),
- level = DeprecationLevel.WARNING,
- )
+ get() = System.currentTimeMillis() / 1000L
val unixTimeMs: Long
- get() = unixTimeMS
+ get() = System.currentTimeMillis()
fun splitRedirectUrl(redirectUrl: String): Map {
- return splitUrlParameters(
- redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
+ return splitQuery(
+ URL(
+ redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
+ )
)
}
@@ -182,8 +198,9 @@ abstract class AuthAPI {
val secureRandom = SecureRandom()
val codeVerifierBytes = ByteArray(96) // base64 has 6bit per char; (8/6)*96 = 128
secureRandom.nextBytes(codeVerifierBytes)
- return base64Encode(codeVerifierBytes).trimEnd('=')
- .replace("+", "-").replace("/", "_").replace("\n", "")
+ return Base64.encodeToString(codeVerifierBytes, Base64.DEFAULT).trimEnd('=')
+ .replace("+", "-")
+ .replace("/", "_").replace("\n", "")
}
}
@@ -226,7 +243,7 @@ abstract class AuthAPI {
*
* 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.
- */
+ **/
@Throws
open suspend fun invalidateToken(token: AuthToken): Nothing = throw NotImplementedError()
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
index 161001611..7a93f96f6 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
@@ -2,10 +2,11 @@ package com.lagradost.cloudstream3.syncproviders
import androidx.annotation.WorkerThread
import com.lagradost.cloudstream3.APIHolder.unixTime
+import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
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 */
class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
@@ -13,8 +14,7 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
data class SavedSearchResponse(
val unixTime: Long,
val response: List,
- val query: SubtitleSearch,
- val idPrefix: String,
+ val query: SubtitleSearch
)
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
- private val searchCache = atomicListOf()
+ private val searchCache = threadSafeListOf()
private var searchCacheIndex: Int = 0
- private val resourceCache = atomicListOf()
+ private val resourceCache = threadSafeListOf()
private var resourceCacheIndex: Int = 0
const val CACHE_SIZE = 20
}
@WorkerThread
suspend fun resource(data: SubtitleEntity): Result = runCatching {
- val cached = resourceCache.withLock {
- var found: SubtitleResource? = null
+ synchronized(resourceCache) {
for (item in resourceCache) {
// 20 min save
if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
- found = item.response
- break
+ return@runCatching item.response
}
}
- found
}
- if (cached != null) return@runCatching cached
val returnValue = api.resource(freshAuth(), data)
- resourceCache.withLock {
+ synchronized(resourceCache) {
val add = SavedResourceResponse(unixTime, returnValue, data)
if (resourceCache.size > CACHE_SIZE) {
resourceCache[resourceCacheIndex] = add // rolling cache
@@ -62,25 +58,22 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
@WorkerThread
suspend fun search(query: SubtitleSearch): Result> {
return runCatching {
- val cached = searchCache.withLock {
- var found: List? = null
+ synchronized(searchCache) {
for (item in searchCache) {
// 120 min save
- if (item.idPrefix == idPrefix && item.query == query && (unixTime - item.unixTime) < 60 * 120) {
- found = item.response
- break
+ if (item.query == query && (unixTime - item.unixTime) < 60 * 120) {
+ return@runCatching item.response
}
}
- found
}
- if (cached != null) return@runCatching cached
- val returnValue = api.search(freshAuth(), query) ?: emptyList()
+ val returnValue =
+ api.search(freshAuth(), query) ?: emptyList()
// only cache valid return values
if (returnValue.isNotEmpty()) {
- val add = SavedSearchResponse(unixTime, returnValue, query, idPrefix)
- searchCache.withLock {
+ val add = SavedSearchResponse(unixTime, returnValue, query)
+ synchronized(searchCache) {
if (searchCache.size > CACHE_SIZE) {
searchCache[searchCacheIndex] = add // rolling cache
searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
@@ -93,3 +86,4 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
}
}
}
+
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
index f30a64748..e5f9aca84 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
@@ -10,8 +10,8 @@ import com.lagradost.cloudstream3.ShowStatus
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
-import com.lagradost.cloudstream3.utils.Levenshtein
import com.lagradost.cloudstream3.utils.UiText
+import me.xdrop.fuzzywuzzy.FuzzySearch
import java.util.Date
/**
@@ -138,7 +138,7 @@ abstract class SyncAPI : AuthAPI() {
ListSorting.Query ->
if (query != null) {
items.sortedBy {
- -Levenshtein.partialRatio(
+ -FuzzySearch.partialRatio(
query.lowercase(), it.name.lowercase()
)
}
@@ -191,4 +191,4 @@ abstract class SyncAPI : AuthAPI() {
override var score: Score? = null,
val tags: List? = null
) : SearchResponse
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
index d3e7f22c7..7a46b4113 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
@@ -5,8 +5,6 @@ import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.Actor
import com.lagradost.cloudstream3.ActorData
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.setKey
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.toJson
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.txt
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.net.URLEncoder
import java.util.Locale
@@ -38,7 +35,7 @@ class AniListApi : SyncAPI() {
override var name = "AniList"
override val idPrefix = "anilist"
- private val key = BuildConfig.ANILIST_KEY
+ val key = "6871"
override val redirectUrlIdentifier = "anilistlogin"
override var requireLibraryRefresh = true
override val hasOAuth2 = true
@@ -53,10 +50,9 @@ class AniListApi : SyncAPI() {
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
val sanitizer = splitRedirectUrl(redirectUrl)
val token = AuthToken(
- accessToken = sanitizer["access_token"]
- ?: throw ErrorLoadingException("No access token"),
- // refreshToken = sanitizer["refresh_token"],
- accessTokenLifetime = APIHolder.unixTime + sanitizer["expires_in"]!!.toLong(),
+ accessToken = sanitizer["access_token"] ?: throw ErrorLoadingException("No access token"),
+ //refreshToken = sanitizer["refresh_token"],
+ accessTokenLifetime = unixTime + sanitizer["expires_in"]!!.toLong(),
)
return token
}
@@ -82,12 +78,13 @@ class AniListApi : SyncAPI() {
override fun urlToId(url: String): String? =
url.removePrefix("$mainUrl/anime/").removeSuffix("/")
+
private fun getUrlFromId(id: Int): String {
return "$mainUrl/anime/$id"
}
- override suspend fun search(auth: AuthData?, query: String): List? {
- val data = searchShows(query) ?: return null
+ override suspend fun search(auth : AuthData?, query: String): List? {
+ val data = searchShows(name) ?: return null
return data.data?.page?.media?.map {
SyncAPI.SyncSearchResult(
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)
?: id).toIntOrNull() ?: throw ErrorLoadingException("Invalid internalId")
val season = getSeason(internalId).data.media
+
return SyncAPI.SyncResult(
season.id.toString(),
nextAiring = season.nextAiringEpisode?.let {
NextAiring(
it.episode ?: return@let null,
- (it.timeUntilAiring ?: return@let null) + APIHolder.unixTime
+ (it.timeUntilAiring ?: return@let null) + unixTime
)
},
title = season.title?.userPreferred,
@@ -156,13 +154,14 @@ class AniListApi : SyncAPI() {
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
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 data = getDataAboutId(auth ?: return null, internalId) ?: return null
+
return SyncAPI.SyncStatus(
score = Score.from100(data.score),
watchedEpisodes = data.progress,
@@ -258,24 +257,24 @@ class AniListApi : SyncAPI() {
val data =
mapOf(
"query" to query,
- "variables" to Variables(
- search = name,
- page = 1,
- type = "ANIME",
- ).toJson()
+ "variables" to
+ mapOf(
+ "search" to name,
+ "page" to 1,
+ "type" to "ANIME"
+ ).toJson()
)
val res = app.post(
"https://graphql.anilist.co/",
- // headers = mapOf(),
- data = data, // (if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
+ //headers = mapOf(),
+ data = data,//(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
timeout = 5000 // REASONABLE TIMEOUT
).text.replace("\\", "")
- return parseJson(res)
+ return res.toKotlinObject()
} catch (e: Exception) {
logError(e)
}
-
return null
}
@@ -298,7 +297,7 @@ class AniListApi : SyncAPI() {
.replace(")", "\\)")
})"""
)
- // println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
+ //println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
val shows = searchShows(name.replace(blackListRegex, ""))
shows?.data?.page?.media?.find {
@@ -456,11 +455,11 @@ class AniListApi : SyncAPI() {
cacheTime = 0,
).text
- return tryParseJson(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 =
"""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)
@@ -504,9 +503,10 @@ class AniListApi : SyncAPI() {
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(
"https://graphql.anilist.co/",
headers = mapOf(
@@ -519,84 +519,71 @@ class AniListApi : SyncAPI() {
q,
"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
).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(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("title") @SerialName("title") val title: Title?,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage?,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("title") val title: Title?,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("coverImage") val coverImage: CoverImage?,
+ @JsonProperty("averageScore") val averageScore: Int?
)
- @Serializable
data class FullAnilistList(
- @JsonProperty("data") @SerialName("data") val data: Data?,
+ @JsonProperty("data") val data: Data?
)
- @Serializable
data class CompletedAt(
- @JsonProperty("year") @SerialName("year") val year: Int,
- @JsonProperty("month") @SerialName("month") val month: Int,
- @JsonProperty("day") @SerialName("day") val day: Int,
+ @JsonProperty("year") val year: Int,
+ @JsonProperty("month") val month: Int,
+ @JsonProperty("day") val day: Int
)
- @Serializable
data class StartedAt(
- @JsonProperty("year") @SerialName("year") val year: String?,
- @JsonProperty("month") @SerialName("month") val month: String?,
- @JsonProperty("day") @SerialName("day") val day: String?,
+ @JsonProperty("year") val year: String?,
+ @JsonProperty("month") val month: String?,
+ @JsonProperty("day") val day: String?
)
- @Serializable
data class Title(
- @JsonProperty("english") @SerialName("english") val english: String?,
- @JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
+ @JsonProperty("english") val english: String?,
+ @JsonProperty("romaji") val romaji: String?
)
- @Serializable
data class CoverImage(
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("extraLarge") @SerialName("extraLarge") val extraLarge: String?,
+ @JsonProperty("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("extraLarge") val extraLarge: String?
)
- @Serializable
data class Media(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("season") @SerialName("season") val season: String?,
- @JsonProperty("seasonYear") @SerialName("seasonYear") val seasonYear: Int,
- @JsonProperty("format") @SerialName("format") val format: String?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int,
- @JsonProperty("title") @SerialName("title") val title: Title,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage,
- @JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List,
- @JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("season") val season: String?,
+ @JsonProperty("seasonYear") val seasonYear: Int,
+ @JsonProperty("format") val format: String?,
+ //@JsonProperty("source") val source: String,
+ @JsonProperty("episodes") val episodes: Int,
+ @JsonProperty("title") val title: Title,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("coverImage") val coverImage: CoverImage,
+ @JsonProperty("synonyms") val synonyms: List,
+ @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
)
- @Serializable
data class Entries(
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("completedAt") @SerialName("completedAt") val completedAt: CompletedAt,
- @JsonProperty("startedAt") @SerialName("startedAt") val startedAt: StartedAt,
- @JsonProperty("updatedAt") @SerialName("updatedAt") val updatedAt: Int,
- @JsonProperty("progress") @SerialName("progress") val progress: Int,
- @JsonProperty("score") @SerialName("score") val score: Int,
- @JsonProperty("private") @SerialName("private") val private: Boolean,
- @JsonProperty("media") @SerialName("media") val media: Media,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("completedAt") val completedAt: CompletedAt,
+ @JsonProperty("startedAt") val startedAt: StartedAt,
+ @JsonProperty("updatedAt") val updatedAt: Int,
+ @JsonProperty("progress") val progress: Int,
+ @JsonProperty("score") val score: Int,
+ @JsonProperty("private") val private: Boolean,
+ @JsonProperty("media") val media: Media
) {
fun toLibraryItem(): SyncAPI.LibraryItem {
return SyncAPI.LibraryItem(
@@ -623,20 +610,17 @@ class AniListApi : SyncAPI() {
}
}
- @Serializable
data class Lists(
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("entries") @SerialName("entries") val entries: List,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("entries") val entries: List
)
- @Serializable
data class MediaListCollection(
- @JsonProperty("lists") @SerialName("lists") val lists: List,
+ @JsonProperty("lists") val lists: List
)
- @Serializable
data class Data(
- @JsonProperty("MediaListCollection") @SerialName("MediaListCollection") val mediaListCollection: MediaListCollection,
+ @JsonProperty("MediaListCollection") val mediaListCollection: MediaListCollection
)
private suspend fun getAniListAnimeListSmart(auth: AuthData): Array? {
@@ -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 {
convertAniListStringToStatus(it.status ?: "").stringRes
}?.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 mediaType = "ANIME"
+
val query = """
query (${'$'}userID: Int = $userID, ${'$'}MEDIA: MediaType = $mediaType) {
MediaListCollection (userId: ${'$'}userID, type: ${'$'}MEDIA) {
@@ -723,53 +708,43 @@ class AniListApi : SyncAPI() {
}
}
}
- }
+ }
"""
val text = postApi(auth.token, query)
- return tryParseJson(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) {
- ToggleFavourite (animeId: ${'$'}animeId) {
- anime {
- nodes {
- id
- title {
- romaji
- }
- }
- }
- }
- }"""
+ ToggleFavourite (animeId: ${'$'}animeId) {
+ anime {
+ nodes {
+ id
+ title {
+ romaji
+ }
+ }
+ }
+ }
+ }"""
val data = postApi(auth.token, q)
return data != ""
}
/** Used to query a saved MediaItem on the list to get the id for removal */
- @Serializable
- data class MediaListItemRoot(
- @JsonProperty("data") @SerialName("data") val data: MediaListItem? = 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,
- )
+ data class MediaListItemRoot(@JsonProperty("data") val data: MediaListItem? = null)
+ data class MediaListItem(@JsonProperty("MediaList") val mediaList: MediaListId? = null)
+ data class MediaListId(@JsonProperty("id") val id: Long? = null)
private suspend fun postDataAboutId(
- auth: AuthData,
+ auth : AuthData,
id: Int,
type: AniListStatusType,
score: Score?,
progress: Int?
): Boolean {
val userID = auth.user.id
+
val q =
// Delete item if status type is None
if (type == AniListStatusType.None) {
@@ -811,24 +786,24 @@ class AniListApi : SyncAPI() {
return data != ""
}
- private suspend fun getUser(token: AuthToken): AniListUser? {
+ private suspend fun getUser(token : AuthToken): AniListUser? {
val q = """
- {
- Viewer {
- id
- name
- avatar {
- large
- }
- favourites {
- anime {
- nodes {
- id
+ {
+ Viewer {
+ id
+ name
+ avatar {
+ large
+ }
+ favourites {
+ anime {
+ nodes {
+ id
+ }
}
}
- }
- }
- }"""
+ }
+ }"""
val data = postApi(token, q)
if (data.isNullOrBlank()) return null
val userData = parseJson(data)
@@ -861,356 +836,305 @@ class AniListApi : SyncAPI() {
return seasons.toList()
}
- @Serializable
data class SeasonResponse(
- @JsonProperty("data") @SerialName("data") val data: SeasonData,
+ @JsonProperty("data") val data: SeasonData,
)
- @Serializable
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(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("title") @SerialName("title") val title: MediaTitle?,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("format") @SerialName("format") val format: String?,
- @JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
- @JsonProperty("relations") @SerialName("relations") val relations: SeasonEdges?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: MediaCoverImage?,
- @JsonProperty("duration") @SerialName("duration") val duration: Int?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
- @JsonProperty("genres") @SerialName("genres") val genres: List?,
- @JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List?,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
- @JsonProperty("isAdult") @SerialName("isAdult") val isAdult: Boolean?,
- @JsonProperty("trailer") @SerialName("trailer") val trailer: MediaTrailer?,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("characters") @SerialName("characters") val characters: CharacterConnection?,
- @JsonProperty("recommendations") @SerialName("recommendations") val recommendations: RecommendationConnection?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("title") val title: MediaTitle?,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("format") val format: String?,
+ @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
+ @JsonProperty("relations") val relations: SeasonEdges?,
+ @JsonProperty("coverImage") val coverImage: MediaCoverImage?,
+ @JsonProperty("duration") val duration: Int?,
+ @JsonProperty("episodes") val episodes: Int?,
+ @JsonProperty("genres") val genres: List?,
+ @JsonProperty("synonyms") val synonyms: List?,
+ @JsonProperty("averageScore") val averageScore: Int?,
+ @JsonProperty("isAdult") val isAdult: Boolean?,
+ @JsonProperty("trailer") val trailer: MediaTrailer?,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("characters") val characters: CharacterConnection?,
+ @JsonProperty("recommendations") val recommendations: RecommendationConnection?,
)
- @Serializable
data class RecommendationConnection(
- @JsonProperty("edges") @SerialName("edges") val edges: List = emptyList(),
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List = emptyList(),
+ @JsonProperty("edges") val edges: List = emptyList(),
+ @JsonProperty("nodes") val nodes: List = emptyList(),
+ //@JsonProperty("pageInfo") val pageInfo: PageInfo,
)
- @Serializable
data class RecommendationEdge(
- @JsonProperty("node") @SerialName("node") val node: Recommendation,
+ //@JsonProperty("rating") val rating: Int,
+ @JsonProperty("node") val node: Recommendation,
)
- @Serializable
data class Recommendation(
- @JsonProperty("mediaRecommendation") @SerialName("mediaRecommendation") val mediaRecommendation: RecommendedMedia?,
+ val id: Long,
+ @JsonProperty("mediaRecommendation") val mediaRecommendation: SeasonMedia?,
)
- @Serializable
data class CharacterName(
- @JsonProperty("name") @SerialName("name") val first: String?,
- @JsonProperty("middle") @SerialName("middle") val middle: String?,
- @JsonProperty("last") @SerialName("last") val last: String?,
- @JsonProperty("full") @SerialName("full") val full: String?,
- @JsonProperty("native") @SerialName("native") val native: String?,
- @JsonProperty("alternative") @SerialName("alternative") val alternative: List?,
- @JsonProperty("alternativeSpoiler") @SerialName("alternativeSpoiler") val alternativeSpoiler: List?,
- @JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
+ @JsonProperty("name") val first: String?,
+ @JsonProperty("middle") val middle: String?,
+ @JsonProperty("last") val last: String?,
+ @JsonProperty("full") val full: String?,
+ @JsonProperty("native") val native: String?,
+ @JsonProperty("alternative") val alternative: List?,
+ @JsonProperty("alternativeSpoiler") val alternativeSpoiler: List?,
+ @JsonProperty("userPreferred") val userPreferred: String?,
)
- @Serializable
data class CharacterImage(
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
)
- @Serializable
data class Character(
- @JsonProperty("name") @SerialName("name") val name: CharacterName?,
- @JsonProperty("age") @SerialName("age") val age: String?,
- @JsonProperty("image") @SerialName("image") val image: CharacterImage?,
+ @JsonProperty("name") val name: CharacterName?,
+ @JsonProperty("age") val age: String?,
+ @JsonProperty("image") val image: CharacterImage?,
)
- @Serializable
data class CharacterEdge(
- @JsonProperty("id") @SerialName("id") val id: Int?,
+ @JsonProperty("id") val id: Int?,
/**
- * MAIN - A primary character role in the media
- * SUPPORTING - A supporting character role in the media
- * BACKGROUND - A background character in the media
+ MAIN
+ A primary character role 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("name") @SerialName("name") val name: String?,
- @JsonProperty("voiceActors") @SerialName("voiceActors") val voiceActors: List?,
- @JsonProperty("favouriteOrder") @SerialName("favouriteOrder") val favouriteOrder: Int?,
- @JsonProperty("media") @SerialName("media") val media: List?,
- @JsonProperty("node") @SerialName("node") val node: Character?,
+ @JsonProperty("role") val role: String?,
+ @JsonProperty("name") val name: String?,
+ @JsonProperty("voiceActors") val voiceActors: List?,
+ @JsonProperty("favouriteOrder") val favouriteOrder: Int?,
+ @JsonProperty("media") val media: List?,
+ @JsonProperty("node") val node: Character?,
)
- @Serializable
data class StaffImage(
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
)
- @Serializable
data class StaffName(
- @JsonProperty("name") @SerialName("name") val first: String?,
- @JsonProperty("middle") @SerialName("middle") val middle: String?,
- @JsonProperty("last") @SerialName("last") val last: String?,
- @JsonProperty("full") @SerialName("full") val full: String?,
- @JsonProperty("native") @SerialName("native") val native: String?,
- @JsonProperty("alternative") @SerialName("alternative") val alternative: List?,
- @JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
+ @JsonProperty("name") val first: String?,
+ @JsonProperty("middle") val middle: String?,
+ @JsonProperty("last") val last: String?,
+ @JsonProperty("full") val full: String?,
+ @JsonProperty("native") val native: String?,
+ @JsonProperty("alternative") val alternative: List?,
+ @JsonProperty("userPreferred") val userPreferred: String?,
)
- @Serializable
data class Staff(
- @JsonProperty("image") @SerialName("image") val image: StaffImage?,
- @JsonProperty("name") @SerialName("name") val name: StaffName?,
- @JsonProperty("age") @SerialName("age") val age: Int?,
+ @JsonProperty("image") val image: StaffImage?,
+ @JsonProperty("name") val name: StaffName?,
+ @JsonProperty("age") val age: Int?,
)
- @Serializable
data class CharacterConnection(
- @JsonProperty("edges") @SerialName("edges") val edges: List?,
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List?,
+ @JsonProperty("edges") val edges: List?,
+ @JsonProperty("nodes") val nodes: List?,
+ //@JsonProperty("pageInfo") pageInfo: PageInfo
)
- @Serializable
data class MediaTrailer(
- @JsonProperty("id") @SerialName("id") val id: String?,
- @JsonProperty("site") @SerialName("site") val site: String?,
- @JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: String?,
+ @JsonProperty("id") val id: String?,
+ @JsonProperty("site") val site: String?,
+ @JsonProperty("thumbnail") val thumbnail: String?,
)
- @Serializable
data class MediaCoverImage(
- @JsonProperty("extraLarge") @SerialName("extraLarge") val extraLarge: String?,
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
- @JsonProperty("color") @SerialName("color") val color: String?,
+ @JsonProperty("extraLarge") val extraLarge: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
+ @JsonProperty("color") val color: String?,
)
- @Serializable
data class SeasonNextAiringEpisode(
- @JsonProperty("episode") @SerialName("episode") val episode: Int?,
- @JsonProperty("timeUntilAiring") @SerialName("timeUntilAiring") val timeUntilAiring: Int?,
+ @JsonProperty("episode") val episode: Int?,
+ @JsonProperty("timeUntilAiring") val timeUntilAiring: Int?,
)
- @Serializable
data class SeasonEdges(
- @JsonProperty("edges") @SerialName("edges") val edges: List?,
+ @JsonProperty("edges") val edges: List?,
)
- @Serializable
data class SeasonEdge(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("relationType") @SerialName("relationType") val relationType: String?,
- @JsonProperty("node") @SerialName("node") val node: SeasonNode?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("relationType") val relationType: String?,
+ @JsonProperty("node") val node: SeasonNode?,
)
- @Serializable
data class AniListFavoritesMediaConnection(
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List,
+ @JsonProperty("nodes") val nodes: List,
)
- @Serializable
data class AniListFavourites(
- @JsonProperty("anime") @SerialName("anime") val anime: AniListFavoritesMediaConnection,
+ @JsonProperty("anime") val anime: AniListFavoritesMediaConnection,
)
- @Serializable
data class MediaTitle(
- @JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
- @JsonProperty("english") @SerialName("english") val english: String?,
- @JsonProperty("native") @SerialName("native") val native: String?,
- @JsonProperty("userPreferred") @SerialName("userPreferred") val userPreferred: String?,
+ @JsonProperty("romaji") val romaji: String?,
+ @JsonProperty("english") val english: String?,
+ @JsonProperty("native") val native: String?,
+ @JsonProperty("userPreferred") val userPreferred: String?,
)
- @Serializable
data class SeasonNode(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("format") @SerialName("format") val format: String?,
- @JsonProperty("title") @SerialName("title") val title: Title?,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("coverImage") @SerialName("coverImage") val coverImage: CoverImage?,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("format") val format: String?,
+ @JsonProperty("title") val title: Title?,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("coverImage") val coverImage: CoverImage?,
+ @JsonProperty("averageScore") val averageScore: Int?
+// @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
)
- @Serializable
data class AniListAvatar(
- @JsonProperty("large") @SerialName("large") val large: String?,
+ @JsonProperty("large") val large: String?,
)
- @Serializable
data class AniListViewer(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("avatar") @SerialName("avatar") val avatar: AniListAvatar?,
- @JsonProperty("favourites") @SerialName("favourites") val favourites: AniListFavourites?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("name") val name: String,
+ @JsonProperty("avatar") val avatar: AniListAvatar?,
+ @JsonProperty("favourites") val favourites: AniListFavourites?,
)
- @Serializable
data class AniListData(
- @JsonProperty("Viewer") @SerialName("Viewer") val viewer: AniListViewer?,
+ @JsonProperty("Viewer") val viewer: AniListViewer?,
)
- @Serializable
data class AniListRoot(
- @JsonProperty("data") @SerialName("data") val data: AniListData?,
+ @JsonProperty("data") val data: AniListData?,
)
- @Serializable
data class AniListUser(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("picture") @SerialName("picture") val picture: String?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("name") val name: String,
+ @JsonProperty("picture") val picture: String?,
)
- @Serializable
data class LikeNode(
- @JsonProperty("id") @SerialName("id") val id: Int?,
+ @JsonProperty("id") val id: Int?,
+ //@JsonProperty("idMal") public int idMal;
)
- @Serializable
data class LikePageInfo(
- @JsonProperty("total") @SerialName("total") val total: Int?,
- @JsonProperty("currentPage") @SerialName("currentPage") val currentPage: Int?,
- @JsonProperty("lastPage") @SerialName("lastPage") val lastPage: Int?,
- @JsonProperty("perPage") @SerialName("perPage") val perPage: Int?,
- @JsonProperty("hasNextPage") @SerialName("hasNextPage") val hasNextPage: Boolean?,
+ @JsonProperty("total") val total: Int?,
+ @JsonProperty("currentPage") val currentPage: Int?,
+ @JsonProperty("lastPage") val lastPage: Int?,
+ @JsonProperty("perPage") val perPage: Int?,
+ @JsonProperty("hasNextPage") val hasNextPage: Boolean?,
)
- @Serializable
data class LikeAnime(
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List?,
- @JsonProperty("pageInfo") @SerialName("pageInfo") val pageInfo: LikePageInfo?,
+ @JsonProperty("nodes") val nodes: List?,
+ @JsonProperty("pageInfo") val pageInfo: LikePageInfo?,
)
- @Serializable
data class LikeFavourites(
- @JsonProperty("anime") @SerialName("anime") val anime: LikeAnime?,
+ @JsonProperty("anime") val anime: LikeAnime?,
)
- @Serializable
data class LikeViewer(
- @JsonProperty("favourites") @SerialName("favourites") val favourites: LikeFavourites?,
+ @JsonProperty("favourites") val favourites: LikeFavourites?,
)
- @Serializable
data class LikeData(
- @JsonProperty("Viewer") @SerialName("Viewer") val viewer: LikeViewer?,
+ @JsonProperty("Viewer") val viewer: LikeViewer?,
)
- @Serializable
data class LikeRoot(
- @JsonProperty("data") @SerialName("data") val data: LikeData?,
+ @JsonProperty("data") val data: LikeData?,
)
- @Serializable
data class AniListTitleHolder(
- @JsonProperty("title") @SerialName("title") val title: Title?,
- @JsonProperty("isFavourite") @SerialName("isFavourite") val isFavourite: Boolean?,
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("progress") @SerialName("progress") val progress: Int?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
- @JsonProperty("score") @SerialName("score") val score: Int?,
- @JsonProperty("type") @SerialName("type") val type: AniListStatusType?,
+ @JsonProperty("title") val title: Title?,
+ @JsonProperty("isFavourite") val isFavourite: Boolean?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("progress") val progress: Int?,
+ @JsonProperty("episodes") val episodes: Int?,
+ @JsonProperty("score") val score: Int?,
+ @JsonProperty("type") val type: AniListStatusType?,
)
- @Serializable
data class GetDataMediaListEntry(
- @JsonProperty("progress") @SerialName("progress") val progress: Int?,
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("score") @SerialName("score") val score: Int?,
+ @JsonProperty("progress") val progress: Int?,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("score") val score: Int?,
)
- @Serializable
data class Nodes(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("mediaRecommendation") @SerialName("mediaRecommendation") val mediaRecommendation: MediaRecommendation?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("mediaRecommendation") val mediaRecommendation: MediaRecommendation?
)
- @Serializable
data class GetDataMedia(
- @JsonProperty("isFavourite") @SerialName("isFavourite") val isFavourite: Boolean?,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Int?,
- @JsonProperty("title") @SerialName("title") val title: Title?,
- @JsonProperty("mediaListEntry") @SerialName("mediaListEntry") val mediaListEntry: GetDataMediaListEntry?,
+ @JsonProperty("isFavourite") val isFavourite: Boolean?,
+ @JsonProperty("episodes") val episodes: Int?,
+ @JsonProperty("title") val title: Title?,
+ @JsonProperty("mediaListEntry") val mediaListEntry: GetDataMediaListEntry?
)
- @Serializable
data class Recommendations(
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List?,
+ @JsonProperty("nodes") val nodes: List?
)
- @Serializable
data class GetDataData(
- @JsonProperty("Media") @SerialName("Media") val media: GetDataMedia?,
+ @JsonProperty("Media") val media: GetDataMedia?,
)
- @Serializable
data class GetDataRoot(
- @JsonProperty("data") @SerialName("data") val data: GetDataData?,
+ @JsonProperty("data") val data: GetDataData?,
)
- @Serializable
data class GetSearchTitle(
- @JsonProperty("romaji") @SerialName("romaji") val romaji: String?,
+ @JsonProperty("romaji") val romaji: String?,
)
- @Serializable
data class TrailerObject(
- @JsonProperty("id") @SerialName("id") val id: String?,
- @JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: String?,
- @JsonProperty("site") @SerialName("site") val site: String?,
+ @JsonProperty("id") val id: String?,
+ @JsonProperty("thumbnail") val thumbnail: String?,
+ @JsonProperty("site") val site: String?,
)
- @Serializable
data class GetSearchMedia(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("idMal") @SerialName("idMal") val idMal: Int?,
- @JsonProperty("seasonYear") @SerialName("seasonYear") val seasonYear: Int,
- @JsonProperty("title") @SerialName("title") val title: GetSearchTitle,
- @JsonProperty("startDate") @SerialName("startDate") val startDate: StartedAt,
- @JsonProperty("averageScore") @SerialName("averageScore") val averageScore: Int?,
- @JsonProperty("meanScore") @SerialName("meanScore") val meanScore: Int?,
- @JsonProperty("bannerImage") @SerialName("bannerImage") val bannerImage: String?,
- @JsonProperty("trailer") @SerialName("trailer") val trailer: TrailerObject?,
- @JsonProperty("nextAiringEpisode") @SerialName("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
- @JsonProperty("recommendations") @SerialName("recommendations") val recommendations: Recommendations?,
- @JsonProperty("relations") @SerialName("relations") val relations: SeasonEdges?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("idMal") val idMal: Int?,
+ @JsonProperty("seasonYear") val seasonYear: Int,
+ @JsonProperty("title") val title: GetSearchTitle,
+ @JsonProperty("startDate") val startDate: StartedAt,
+ @JsonProperty("averageScore") val averageScore: Int?,
+ @JsonProperty("meanScore") val meanScore: Int?,
+ @JsonProperty("bannerImage") val bannerImage: String?,
+ @JsonProperty("trailer") val trailer: TrailerObject?,
+ @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
+ @JsonProperty("recommendations") val recommendations: Recommendations?,
+ @JsonProperty("relations") val relations: SeasonEdges?
)
- @Serializable
data class GetSearchPage(
- @JsonProperty("Page") @SerialName("Page") val page: GetSearchData?,
+ @JsonProperty("Page") val page: GetSearchData?,
)
- @Serializable
data class GetSearchData(
- @JsonProperty("media") @SerialName("media") val media: List?,
+ @JsonProperty("media") val media: List?,
)
- @Serializable
data class GetSearchRoot(
- @JsonProperty("data") @SerialName("data") val data: GetSearchPage?,
+ @JsonProperty("data") val data: GetSearchPage?,
)
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/KitsuApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/KitsuApi.kt
index c613aa6ea..29c3c0c17 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/KitsuApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/KitsuApi.kt
@@ -1,8 +1,8 @@
package com.lagradost.cloudstream3.syncproviders.providers
+
import androidx.annotation.StringRes
import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
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.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.txt
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.text.SimpleDateFormat
+import java.time.Instant
import java.time.LocalDate
-import java.time.ZoneId
+import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
@@ -69,9 +68,13 @@ class KitsuApi: SyncAPI() {
val request: Request = chain.request()
try {
+
val response = chain.proceed(request);
+
if (response.isSuccessful) return response
+
response.close()
+
} catch (_: Exception) {
}
@@ -80,6 +83,7 @@ class KitsuApi: SyncAPI() {
.build()
return chain.proceed(fallbackRequest)
+
}
}
@@ -103,7 +107,7 @@ class KitsuApi: SyncAPI() {
).parsed()
return AuthToken(
- accessTokenLifetime = APIHolder.unixTime + token.expiresIn.toLong(),
+ accessTokenLifetime = unixTime + token.expiresIn.toLong(),
refreshToken = token.refreshToken,
accessToken = token.accessToken,
)
@@ -122,7 +126,7 @@ class KitsuApi: SyncAPI() {
return AuthToken(
accessToken = res.accessToken,
refreshToken = res.refreshToken,
- accessTokenLifetime = APIHolder.unixTime + res.expiresIn.toLong()
+ accessTokenLifetime = unixTime + res.expiresIn.toLong()
)
}
@@ -179,9 +183,9 @@ class KitsuApi: SyncAPI() {
return null
}
- @Serializable
data class KitsuResponse(
- @JsonProperty("data") @SerialName("data") val data: KitsuNode,
+ @field:JsonProperty(value = "data")
+ val data: KitsuNode,
)
val url =
@@ -198,10 +202,10 @@ class KitsuApi: SyncAPI() {
id = id,
totalEpisodes = anime.episodeCount,
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,
synopsis = anime.synopsis,
- airStatus = when (anime.status) {
+ airStatus = when(anime.status) {
"finished" -> ShowStatus.Completed
"current" -> ShowStatus.Ongoing
else -> null
@@ -217,6 +221,7 @@ class KitsuApi: SyncAPI() {
prevSeason = null,
actors = null,
)
+
}
override suspend fun status(auth : AuthData?, id: String): AbstractSyncStatus? {
@@ -245,19 +250,21 @@ class KitsuApi: SyncAPI() {
}
return SyncStatus(
- score = Score.from(anime.ratingTwenty, 20),
+ score = Score.from(anime.ratingTwenty.toString(), 20),
status = SyncWatchType.fromInternalId(kitsuStatusAsString.indexOf(anime.status)),
isFavorite = null,
watchedEpisodes = anime.progress,
)
}
-
suspend fun getAnimeIdByTitle(title: String): String? {
+
val animeSelectedFields = arrayOf("titles","canonicalTitle")
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()
+
return res.data.firstOrNull()?.id
+
}
override fun urlToId(url: String): String? =
@@ -268,6 +275,7 @@ class KitsuApi: SyncAPI() {
id: String,
newStatus: AbstractSyncStatus
): Boolean {
+
return setScoreRequest(
auth ?: return false,
id.toIntOrNull() ?: return false,
@@ -278,18 +286,21 @@ class KitsuApi: SyncAPI() {
}
private suspend fun setScoreRequest(
- auth: AuthData,
+ auth : AuthData,
id: Int,
status: KitsuStatusType? = null,
score: Int? = null,
numWatchedEpisodes: Int? = null,
): Boolean {
+
val libraryEntryId = getAnimeLibraryEntryId(auth, id)
// Exists entry for anime in library
if (libraryEntryId != null) {
+
// Delete anime from library
if (status == null || status == KitsuStatusType.None) {
+
val res = app.delete(
"$apiUrl/library-entries/$libraryEntryId",
headers = mapOf(
@@ -298,7 +309,9 @@ class KitsuApi: SyncAPI() {
interceptor = apiFallbackInterceptor
)
+
return res.isSuccessful
+
}
return setScoreRequest(
@@ -308,6 +321,7 @@ class KitsuApi: SyncAPI() {
score,
numWatchedEpisodes
)
+
}
val data = mapOf(
@@ -346,6 +360,7 @@ class KitsuApi: SyncAPI() {
)
return res.isSuccessful
+
}
@Suppress("UNCHECKED_CAST")
@@ -378,11 +393,15 @@ class KitsuApi: SyncAPI() {
interceptor = apiFallbackInterceptor
)
+
return res.isSuccessful
+
}
private suspend fun getAnimeLibraryEntryId(auth: AuthData, id: Int): Int? {
+
val userId = auth.user.id
+
val res = app.get(
"$apiUrl/library-entries?filter[userId]=$userId&filter[animeId]=$id",
headers = mapOf(
@@ -392,6 +411,7 @@ class KitsuApi: SyncAPI() {
).parsed().data.firstOrNull() ?: return null
return res.id.toInt()
+
}
override suspend fun library(auth : AuthData?): LibraryMetadata? {
@@ -433,52 +453,58 @@ class KitsuApi: SyncAPI() {
}
private suspend fun getKitsuAnimeList(token: AuthToken, userId: Int): Array {
- 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
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()
while (true) {
+
val data: KitsuResponse = getKitsuAnimeListSlice(token, url)
+
data.data.forEachIndexed { index, value ->
value.anime = data.included?.get(index)
}
fullList.addAll(data.data)
+
url = data.links?.next ?: break
}
+
return fullList.toTypedArray()
}
private suspend fun getKitsuAnimeListSlice(token: AuthToken, url: String): KitsuResponse {
- return app.get(
+ val res = app.get(
url, headers = mapOf(
"Authorization" to "Bearer ${token.accessToken}",
),
interceptor = apiFallbackInterceptor
).parsed()
+ return res
}
- @Serializable
+
data class ResponseToken(
- @JsonProperty("token_type") @SerialName("token_type") val tokenType: String,
- @JsonProperty("expires_in") @SerialName("expires_in") val expiresIn: Int,
- @JsonProperty("access_token") @SerialName("access_token") val accessToken: String,
- @JsonProperty("refresh_token") @SerialName("refresh_token") val refreshToken: String,
+ @JsonProperty("token_type") val tokenType: String,
+ @JsonProperty("expires_in") val expiresIn: Int,
+ @JsonProperty("access_token") val accessToken: String,
+ @JsonProperty("refresh_token") val refreshToken: String,
)
- @Serializable
data class KitsuNode(
- @JsonProperty("id") @SerialName("id") val id: String,
- @JsonProperty("attributes") @SerialName("attributes") val attributes: KitsuNodeAttributes,
+ @JsonProperty("id") val id: String,
+ @JsonProperty("attributes") val attributes: KitsuNodeAttributes,
/* User list anime node */
- @JsonProperty("relationships") @SerialName("relationships") val relationships: KitsuRelationships?,
- @JsonProperty("anime") @SerialName("anime") var anime: KitsuAnimeData?,
+ @JsonProperty("relationships") val relationships: KitsuRelationships?,
+ var anime: KitsuAnimeData?
) {
fun toLibraryItem(): LibraryItem {
+
val animeItem = this.anime
val numEpisodes = animeItem?.attributes?.episodeCount
@@ -500,7 +526,7 @@ class KitsuApi: SyncAPI() {
this.id,
this.attributes.progress,
numEpisodes,
- Score.from(this.attributes.ratingTwenty, 20),
+ Score.from(this.attributes.ratingTwenty.toString(), 20),
parseDateLong(this.attributes.updatedAt),
"Kitsu",
TvType.Anime,
@@ -509,9 +535,12 @@ class KitsuApi: SyncAPI() {
null,
plot = synopsis,
releaseDate = if (startDate == null) null else try {
- Date.from(LocalDate.parse(startDate).atStartOfDay()
- .atZone(ZoneId.systemDefault())
- .toInstant())
+ Date.from(
+ Instant.from(
+ DateTimeFormatter.ofPattern(if (startDate.length == 4) "yyyy" else if (startDate.length == 7) "yyyy-MM" else "yyyy-MM-dd")
+ .parse(startDate)
+ )
+ )
} catch (_: RuntimeException) {
null
}
@@ -520,100 +549,93 @@ class KitsuApi: SyncAPI() {
}
- @Serializable
data class KitsuAnimeAttributes(
- @JsonProperty("titles") @SerialName("titles") val titles: KitsuTitles?,
- @JsonProperty("canonicalTitle") @SerialName("canonicalTitle") val canonicalTitle: String?,
- @JsonProperty("posterImage") @SerialName("posterImage") val posterImage: KitsuPosterImage?,
- @JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
- @JsonProperty("startDate") @SerialName("startDate") val startDate: String?,
- @JsonProperty("endDate") @SerialName("endDate") val endDate: String?,
- @JsonProperty("episodeCount") @SerialName("episodeCount") val episodeCount: Int?,
- @JsonProperty("episodeLength") @SerialName("episodeLength") val episodeLength: Int?,
+ @JsonProperty("titles") val titles: KitsuTitles?,
+ @JsonProperty("canonicalTitle") val canonicalTitle: String?,
+ @JsonProperty("posterImage") val posterImage: KitsuPosterImage?,
+ @JsonProperty("synopsis") val synopsis: String?,
+ @JsonProperty("startDate") val startDate: String?,
+ @JsonProperty("endDate") val endDate: String?,
+ @JsonProperty("episodeCount") val episodeCount: Int?,
+ @JsonProperty("episodeLength") val episodeLength: Int?,
)
- @Serializable
data class KitsuAnimeData(
- @JsonProperty("id") @SerialName("id") val id: String,
- @JsonProperty("attributes") @SerialName("attributes") val attributes: KitsuAnimeAttributes,
+ @JsonProperty("id") val id: String,
+ @JsonProperty("attributes") val attributes: KitsuAnimeAttributes,
)
- @Serializable
+
data class KitsuNodeAttributes(
/* General attributes */
- @JsonProperty("titles") @SerialName("titles") val titles: KitsuTitles?,
- @JsonProperty("canonicalTitle") @SerialName("canonicalTitle") val canonicalTitle: String?,
- @JsonProperty("posterImage") @SerialName("posterImage") val posterImage: KitsuPosterImage?,
- @JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
- @JsonProperty("startDate") @SerialName("startDate") val startDate: String?,
- @JsonProperty("endDate") @SerialName("endDate") val endDate: String?,
- @JsonProperty("episodeCount") @SerialName("episodeCount") val episodeCount: Int?,
- @JsonProperty("episodeLength") @SerialName("episodeLength") val episodeLength: Int?,
+ @JsonProperty("titles") val titles: KitsuTitles?,
+ @JsonProperty("canonicalTitle") val canonicalTitle: String?,
+ @JsonProperty("posterImage") val posterImage: KitsuPosterImage?,
+ @JsonProperty("synopsis") val synopsis: String?,
+ @JsonProperty("startDate") val startDate: String?,
+ @JsonProperty("endDate") val endDate: String?,
+ @JsonProperty("episodeCount") val episodeCount: Int?,
+ @JsonProperty("episodeLength") val episodeLength: Int?,
/* User attributes */
- @JsonProperty("name") @SerialName("name") val name: String?,
- @JsonProperty("location") @SerialName("location") val location: String?,
- @JsonProperty("createdAt") @SerialName("createdAt") val createdAt: String?,
- @JsonProperty("avatar") @SerialName("avatar") val avatar: KitsuUserAvatar?,
+ @JsonProperty("name") val name: String?,
+ @JsonProperty("location") val location: String?,
+ @JsonProperty("createdAt") val createdAt: String?,
+ @JsonProperty("avatar") val avatar: KitsuUserAvatar?,
/* User list anime attributes */
- @JsonProperty("progress") @SerialName("progress") val progress: Int?,
- @JsonProperty("ratingTwenty") @SerialName("ratingTwenty") val ratingTwenty: Int?,
- @JsonProperty("updatedAt") @SerialName("updatedAt") val updatedAt: String?,
- @JsonProperty("status") @SerialName("status") val status: String?,
+ @JsonProperty("progress") val progress: Int?,
+ @JsonProperty("ratingTwenty") val ratingTwenty: Float?,
+ @JsonProperty("updatedAt") val updatedAt: String?,
+ @JsonProperty("status") val status: String?,
)
- @Serializable
data class KitsuRelationships(
- @JsonProperty("anime") @SerialName("anime") val anime: KitsuRelationshipsAnime?,
+ @JsonProperty("anime") val anime: KitsuRelationshipsAnime?
)
- @Serializable
data class KitsuRelationshipsAnime(
- @JsonProperty("links") @SerialName("links") val links: KitsuLinks?,
+ @JsonProperty("links") val links: KitsuLinks?
)
- @Serializable
data class KitsuPosterImage(
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
)
- @Serializable
data class KitsuTitles(
- @JsonProperty("en_jp") @SerialName("en_jp") val enJp: String?,
- @JsonProperty("ja_jp") @SerialName("ja_jp") val jaJp: String?,
+ @JsonProperty("en_jp") val enJp: String?,
+ @JsonProperty("ja_jp") val jaJp: String?
)
- @Serializable
data class KitsuUserAvatar(
- @JsonProperty("original") @SerialName("original") val original: String?,
+ @JsonProperty("original") val original: String?
)
- @Serializable
data class KitsuLinks(
/* Pagination */
- @JsonProperty("first") @SerialName("first") val first: String?,
- @JsonProperty("next") @SerialName("next") val next: String?,
- @JsonProperty("last") @SerialName("last") val last: String?,
+ @JsonProperty("first") val first: String?,
+ @JsonProperty("next") val next: String?,
+ @JsonProperty("last") val last: String?,
/* Relationships */
- @JsonProperty("related") @SerialName("related") val related: String?,
+ @JsonProperty("related") val related: String?
)
- @Serializable
data class KitsuResponse(
- @JsonProperty("links") @SerialName("links") val links: KitsuLinks?,
- @JsonProperty("data") @SerialName("data") val data: List,
+ @JsonProperty("links") val links: KitsuLinks?,
+ @JsonProperty("data") val data: List,
/* When requesting related info (User library entry -> anime) */
- @JsonProperty("included") @SerialName("included") val included: List?,
+ @JsonProperty("included") val included: List?,
)
+
companion object {
+
const val KITSU_CACHED_LIST: String = "kitsu_cached_list"
private fun parseDateLong(string: String?): Long? {
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
)?.time?.div(1000)
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -622,13 +644,13 @@ class KitsuApi: SyncAPI() {
arrayOf("current", "completed", "on_hold", "dropped", "planned")
private fun fromIntToAnimeStatus(inp: SyncWatchType): KitsuStatusType {
return when (inp) {
- SyncWatchType.NONE -> KitsuStatusType.None
- SyncWatchType.WATCHING -> KitsuStatusType.Watching
- SyncWatchType.COMPLETED -> KitsuStatusType.Completed
- SyncWatchType.ONHOLD -> KitsuStatusType.OnHold
- SyncWatchType.DROPPED -> KitsuStatusType.Dropped
- SyncWatchType.PLANTOWATCH -> KitsuStatusType.PlanToWatch
- SyncWatchType.REWATCHING -> KitsuStatusType.Watching
+ SyncWatchType.NONE -> KitsuStatusType.None
+ SyncWatchType.WATCHING -> KitsuStatusType.Watching
+ SyncWatchType.COMPLETED -> KitsuStatusType.Completed
+ SyncWatchType.ONHOLD -> KitsuStatusType.OnHold
+ SyncWatchType.DROPPED -> KitsuStatusType.Dropped
+ SyncWatchType.PLANTOWATCH -> KitsuStatusType.PlanToWatch
+ SyncWatchType.REWATCHING -> KitsuStatusType.Watching
}
}
@@ -643,12 +665,12 @@ class KitsuApi: SyncAPI() {
private fun convertToStatus(string: String): KitsuStatusType {
return when (string) {
- "current" -> KitsuStatusType.Watching
- "completed" -> KitsuStatusType.Completed
- "on_hold" -> KitsuStatusType.OnHold
- "dropped" -> KitsuStatusType.Dropped
- "planned" -> KitsuStatusType.PlanToWatch
- else -> KitsuStatusType.None
+ "current" -> KitsuStatusType.Watching
+ "completed" -> KitsuStatusType.Completed
+ "on_hold" -> KitsuStatusType.OnHold
+ "dropped" -> KitsuStatusType.Dropped
+ "planned" -> KitsuStatusType.PlanToWatch
+ else -> KitsuStatusType.None
}
}
}
@@ -670,7 +692,7 @@ object Kitsu {
"https://kitsu.io/api/graphql",
headers = headers,
data = mapOf("query" to query)
- ).parsed()
+ ).parsed()
}
private val cache: MutableMap, Map> =
@@ -752,52 +774,44 @@ query {
return map
}
- @Serializable
data class KitsuResponse(
- @JsonProperty("data") @SerialName("data") val data: Data? = null,
+ val data: Data? = null
) {
- @Serializable
data class Data(
- @JsonProperty("lookupMapping") @SerialName("lookupMapping") val lookupMapping: LookupMapping? = null,
+ val lookupMapping: LookupMapping? = null
)
- @Serializable
data class LookupMapping(
- @JsonProperty("id") @SerialName("id") val id: String? = null,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: Episodes? = null,
+ val id: String? = null,
+ val episodes: Episodes? = null
)
- @Serializable
data class Episodes(
- @JsonProperty("nodes") @SerialName("nodes") val nodes: List? = null,
+ val nodes: List? = null
)
- @Serializable
data class Node(
- @JsonProperty("number") @SerialName("number") val num: Int? = null,
- @JsonProperty("titles") @SerialName("titles") val titles: Titles? = null,
- @JsonProperty("description") @SerialName("description") val description: Description? = null,
- @JsonProperty("thumbnail") @SerialName("thumbnail") val thumbnail: Thumbnail? = null,
+ @JsonProperty("number")
+ val num: Int? = null,
+ val titles: Titles? = null,
+ val description: Description? = null,
+ val thumbnail: Thumbnail? = null
)
- @Serializable
data class Description(
- @JsonProperty("en") @SerialName("en") val en: String? = null,
+ val en: String? = null
)
- @Serializable
data class Thumbnail(
- @JsonProperty("original") @SerialName("original") val original: Original? = null,
+ val original: Original? = null
)
- @Serializable
data class Original(
- @JsonProperty("url") @SerialName("url") val url: String? = null,
+ val url: String? = null
)
- @Serializable
data class Titles(
- @JsonProperty("canonical") @SerialName("canonical") val canonical: String? = null,
+ val canonical: String? = null
)
}
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/MALApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/MALApi.kt
index f74102b13..ba0195be6 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/MALApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/MALApi.kt
@@ -2,8 +2,6 @@ package com.lagradost.cloudstream3.syncproviders.providers
import androidx.annotation.StringRes
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.setKey
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.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJson
+import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
import com.lagradost.cloudstream3.utils.txt
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.format.DateTimeFormatter
@@ -37,7 +34,7 @@ class MALApi : SyncAPI() {
override var name = "MAL"
override val idPrefix = "mal"
- private val key = BuildConfig.MAL_KEY
+ val key = "1714d6f2f4f7cc19644384f8c4629910"
private val apiUrl = "https://api.myanimelist.net"
override val hasOAuth2 = true
override val redirectUrlIdentifier: String? = "mallogin"
@@ -52,17 +49,16 @@ class MALApi : SyncAPI() {
SyncWatchType.PLANTOWATCH,
SyncWatchType.DROPPED,
SyncWatchType.ONHOLD,
- SyncWatchType.NONE,
+ SyncWatchType.NONE
)
- @Serializable
- data class Payload(
- @JsonProperty("requestId") @SerialName("requestId") val requestId: Int,
- @JsonProperty("codeVerifier") @SerialName("codeVerifier") val codeVerifier: String,
+ data class PayLoad(
+ val requestId: Int,
+ val codeVerifier: String
)
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
- val payloadData = parseJson(payload!!)
+ val payloadData = parseJson(payload!!)
val sanitizer = splitRedirectUrl(redirectUrl)
val state = sanitizer["state"]!!
@@ -78,13 +74,13 @@ class MALApi : SyncAPI() {
"client_id" to key,
"code" to currentCode,
"code_verifier" to payloadData.codeVerifier,
- "grant_type" to "authorization_code",
+ "grant_type" to "authorization_code"
)
).parsed()
return AuthToken(
- accessTokenLifetime = APIHolder.unixTime + token.expiresIn.toLong(),
+ accessTokenLifetime = unixTime + token.expiresIn.toLong(),
refreshToken = token.refreshToken,
- accessToken = token.accessToken,
+ accessToken = token.accessToken
)
}
@@ -98,13 +94,13 @@ class MALApi : SyncAPI() {
return AuthUser(
id = user.id,
name = user.name,
- profilePicture = user.picture,
+ profilePicture = user.picture
)
}
- override suspend fun search(auth: AuthData?, query: String): List? {
+ override suspend fun search(auth : AuthData?, query: String): List? {
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(
url, headers = mapOf(
"Authorization" to "Bearer $auth",
@@ -117,7 +113,7 @@ class MALApi : SyncAPI() {
this.name,
node.id.toString(),
"$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()
override suspend fun updateStatus(
- auth: AuthData?,
+ auth : AuthData?,
id: String,
newStatus: SyncAPI.AbstractSyncStatus
): Boolean {
@@ -139,89 +135,82 @@ class MALApi : SyncAPI() {
)
}
- @Serializable
data class MalAnime(
- @JsonProperty("id") @SerialName("id") val id: Int?,
- @JsonProperty("title") @SerialName("title") val title: String?,
- @JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MainPicture?,
- @JsonProperty("alternative_titles") @SerialName("alternative_titles") val alternativeTitles: AlternativeTitles?,
- @JsonProperty("start_date") @SerialName("start_date") val startDate: String?,
- @JsonProperty("end_date") @SerialName("end_date") val endDate: String?,
- @JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
- @JsonProperty("mean") @SerialName("mean") val mean: Double?,
- @JsonProperty("rank") @SerialName("rank") val rank: Int?,
- @JsonProperty("popularity") @SerialName("popularity") val popularity: Int?,
- @JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int?,
- @JsonProperty("num_scoring_users") @SerialName("num_scoring_users") val numScoringUsers: Int?,
- @JsonProperty("nsfw") @SerialName("nsfw") val nsfw: String?,
- @JsonProperty("created_at") @SerialName("created_at") val createdAt: String?,
- @JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String?,
- @JsonProperty("media_type") @SerialName("media_type") val mediaType: String?,
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("genres") @SerialName("genres") val genres: ArrayList?,
- @JsonProperty("my_list_status") @SerialName("my_list_status") val myListStatus: MyListStatus?,
- @JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int?,
- @JsonProperty("start_season") @SerialName("start_season") val startSeason: StartSeason?,
- @JsonProperty("broadcast") @SerialName("broadcast") val broadcast: Broadcast?,
- @JsonProperty("source") @SerialName("source") val source: String?,
- @JsonProperty("average_episode_duration") @SerialName("average_episode_duration") val averageEpisodeDuration: Int?,
- @JsonProperty("rating") @SerialName("rating") val rating: String?,
- @JsonProperty("pictures") @SerialName("pictures") val pictures: ArrayList?,
- @JsonProperty("background") @SerialName("background") val background: String?,
- @JsonProperty("related_anime") @SerialName("related_anime") val relatedAnime: ArrayList?,
- @JsonProperty("related_manga") @SerialName("related_manga") val relatedManga: ArrayList?,
- @JsonProperty("recommendations") @SerialName("recommendations") val recommendations: ArrayList?,
- @JsonProperty("studios") @SerialName("studios") val studios: ArrayList?,
- @JsonProperty("statistics") @SerialName("statistics") val statistics: Statistics?,
+ @JsonProperty("id") val id: Int?,
+ @JsonProperty("title") val title: String?,
+ @JsonProperty("main_picture") val mainPicture: MainPicture?,
+ @JsonProperty("alternative_titles") val alternativeTitles: AlternativeTitles?,
+ @JsonProperty("start_date") val startDate: String?,
+ @JsonProperty("end_date") val endDate: String?,
+ @JsonProperty("synopsis") val synopsis: String?,
+ @JsonProperty("mean") val mean: Double?,
+ @JsonProperty("rank") val rank: Int?,
+ @JsonProperty("popularity") val popularity: Int?,
+ @JsonProperty("num_list_users") val numListUsers: Int?,
+ @JsonProperty("num_scoring_users") val numScoringUsers: Int?,
+ @JsonProperty("nsfw") val nsfw: String?,
+ @JsonProperty("created_at") val createdAt: String?,
+ @JsonProperty("updated_at") val updatedAt: String?,
+ @JsonProperty("media_type") val mediaType: String?,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("genres") val genres: ArrayList?,
+ @JsonProperty("my_list_status") val myListStatus: MyListStatus?,
+ @JsonProperty("num_episodes") val numEpisodes: Int?,
+ @JsonProperty("start_season") val startSeason: StartSeason?,
+ @JsonProperty("broadcast") val broadcast: Broadcast?,
+ @JsonProperty("source") val source: String?,
+ @JsonProperty("average_episode_duration") val averageEpisodeDuration: Int?,
+ @JsonProperty("rating") val rating: String?,
+ @JsonProperty("pictures") val pictures: ArrayList?,
+ @JsonProperty("background") val background: String?,
+ @JsonProperty("related_anime") val relatedAnime: ArrayList?,
+ @JsonProperty("related_manga") val relatedManga: ArrayList?,
+ @JsonProperty("recommendations") val recommendations: ArrayList?,
+ @JsonProperty("studios") val studios: ArrayList?,
+ @JsonProperty("statistics") val statistics: Statistics?,
)
- @Serializable
data class Recommendations(
- @JsonProperty("node") @SerialName("node") val node: Node? = null,
- @JsonProperty("num_recommendations") @SerialName("num_recommendations") val numRecommendations: Int? = null,
+ @JsonProperty("node") val node: Node? = null,
+ @JsonProperty("num_recommendations") val numRecommendations: Int? = null
)
- @Serializable
data class Studios(
- @JsonProperty("id") @SerialName("id") val id: Int? = null,
- @JsonProperty("name") @SerialName("name") val name: String? = null,
+ @JsonProperty("id") val id: Int? = null,
+ @JsonProperty("name") val name: String? = null
)
- @Serializable
data class MyListStatus(
- @JsonProperty("status") @SerialName("status") val status: String? = null,
- @JsonProperty("score") @SerialName("score") val score: Int? = null,
- @JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int? = null,
- @JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean? = null,
- @JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String? = null,
+ @JsonProperty("status") val status: String? = null,
+ @JsonProperty("score") val score: Int? = null,
+ @JsonProperty("num_episodes_watched") val numEpisodesWatched: Int? = null,
+ @JsonProperty("is_rewatching") val isRewatching: Boolean? = null,
+ @JsonProperty("updated_at") val updatedAt: String? = null
)
- @Serializable
data class RelatedAnime(
- @JsonProperty("node") @SerialName("node") val node: Node? = null,
- @JsonProperty("relation_type") @SerialName("relation_type") val relationType: String? = null,
- @JsonProperty("relation_type_formatted") @SerialName("relation_type_formatted") val relationTypeFormatted: String? = null,
+ @JsonProperty("node") val node: Node? = null,
+ @JsonProperty("relation_type") val relationType: String? = null,
+ @JsonProperty("relation_type_formatted") val relationTypeFormatted: String? = null
)
- @Serializable
data class Status(
- @JsonProperty("watching") @SerialName("watching") val watching: String? = null,
- @JsonProperty("completed") @SerialName("completed") val completed: String? = null,
- @JsonProperty("on_hold") @SerialName("on_hold") val onHold: String? = null,
- @JsonProperty("dropped") @SerialName("dropped") val dropped: String? = null,
- @JsonProperty("plan_to_watch") @SerialName("plan_to_watch") val planToWatch: String? = null,
+ @JsonProperty("watching") val watching: String? = null,
+ @JsonProperty("completed") val completed: String? = null,
+ @JsonProperty("on_hold") val onHold: String? = null,
+ @JsonProperty("dropped") val dropped: String? = null,
+ @JsonProperty("plan_to_watch") val planToWatch: String? = null
)
- @Serializable
data class Statistics(
- @JsonProperty("status") @SerialName("status") val status: Status? = null,
- @JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int? = null,
+ @JsonProperty("status") val status: Status? = null,
+ @JsonProperty("num_list_users") val numListUsers: Int? = null
)
private fun parseDate(string: String?): Long? {
return try {
SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(string ?: return null)?.time
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -232,11 +221,11 @@ class MALApi : SyncAPI() {
apiName = this.name,
syncId = node.id.toString(),
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 internalId = id.toIntOrNull() ?: return null
val url =
@@ -258,7 +247,7 @@ class MALApi : SyncAPI() {
airStatus = when (malAnime.status) {
"finished_airing" -> ShowStatus.Completed
"currently_airing" -> ShowStatus.Ongoing
- // "not_yet_aired"
+ //"not_yet_aired"
else -> 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
// 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(
string ?: return null
)?.time?.div(1000)
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -355,10 +344,12 @@ class MALApi : SyncAPI() {
val codeVerifier = generateCodeVerifier()
val requestId = ++requestIdCounter
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(
url = request,
- payload = Payload(requestId, codeVerifier).toJson(),
+ payload = PayLoad(requestId, codeVerifier).toJson()
)
}
@@ -368,71 +359,69 @@ class MALApi : SyncAPI() {
data = mapOf(
"client_id" to key,
"grant_type" to "refresh_token",
- "refresh_token" to token.refreshToken!!,
+ "refresh_token" to token.refreshToken!!
)
).parsed()
+
return AuthToken(
accessToken = res.accessToken,
refreshToken = res.refreshToken,
- accessTokenLifetime = APIHolder.unixTime + res.expiresIn.toLong(),
+ accessTokenLifetime = unixTime + res.expiresIn.toLong()
)
}
private var requestIdCounter = 0
+
+
private val allTitles = hashMapOf()
- @Serializable
data class MalList(
- @JsonProperty("data") @SerialName("data") val data: List,
- @JsonProperty("paging") @SerialName("paging") val paging: Paging,
+ @JsonProperty("data") val data: List,
+ @JsonProperty("paging") val paging: Paging
)
- @Serializable
data class MainPicture(
- @JsonProperty("medium") @SerialName("medium") val medium: String,
- @JsonProperty("large") @SerialName("large") val large: String,
+ @JsonProperty("medium") val medium: String,
+ @JsonProperty("large") val large: String
)
- @Serializable
data class Node(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("title") @SerialName("title") val title: String,
- @JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MainPicture?,
- @JsonProperty("alternative_titles") @SerialName("alternative_titles") val alternativeTitles: AlternativeTitles?,
- @JsonProperty("media_type") @SerialName("media_type") val mediaType: String?,
- @JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int?,
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("start_date") @SerialName("start_date") val startDate: String?,
- @JsonProperty("end_date") @SerialName("end_date") val endDate: String?,
- @JsonProperty("average_episode_duration") @SerialName("average_episode_duration") val averageEpisodeDuration: Int?,
- @JsonProperty("synopsis") @SerialName("synopsis") val synopsis: String?,
- @JsonProperty("mean") @SerialName("mean") val mean: Double?,
- @JsonProperty("genres") @SerialName("genres") val genres: List?,
- @JsonProperty("rank") @SerialName("rank") val rank: Int?,
- @JsonProperty("popularity") @SerialName("popularity") val popularity: Int?,
- @JsonProperty("num_list_users") @SerialName("num_list_users") val numListUsers: Int?,
- @JsonProperty("num_favorites") @SerialName("num_favorites") val numFavorites: Int?,
- @JsonProperty("num_scoring_users") @SerialName("num_scoring_users") val numScoringUsers: Int?,
- @JsonProperty("start_season") @SerialName("start_season") val startSeason: StartSeason?,
- @JsonProperty("broadcast") @SerialName("broadcast") val broadcast: Broadcast?,
- @JsonProperty("nsfw") @SerialName("nsfw") val nsfw: String?,
- @JsonProperty("created_at") @SerialName("created_at") val createdAt: String?,
- @JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("title") val title: String,
+ @JsonProperty("main_picture") val mainPicture: MainPicture?,
+ @JsonProperty("alternative_titles") val alternativeTitles: AlternativeTitles?,
+ @JsonProperty("media_type") val mediaType: String?,
+ @JsonProperty("num_episodes") val numEpisodes: Int?,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("start_date") val startDate: String?,
+ @JsonProperty("end_date") val endDate: String?,
+ @JsonProperty("average_episode_duration") val averageEpisodeDuration: Int?,
+ @JsonProperty("synopsis") val synopsis: String?,
+ @JsonProperty("mean") val mean: Double?,
+ @JsonProperty("genres") val genres: List?,
+ @JsonProperty("rank") val rank: Int?,
+ @JsonProperty("popularity") val popularity: Int?,
+ @JsonProperty("num_list_users") val numListUsers: Int?,
+ @JsonProperty("num_favorites") val numFavorites: Int?,
+ @JsonProperty("num_scoring_users") val numScoringUsers: Int?,
+ @JsonProperty("start_season") val startSeason: StartSeason?,
+ @JsonProperty("broadcast") val broadcast: Broadcast?,
+ @JsonProperty("nsfw") val nsfw: String?,
+ @JsonProperty("created_at") val createdAt: String?,
+ @JsonProperty("updated_at") val updatedAt: String?
)
- @Serializable
data class ListStatus(
- @JsonProperty("status") @SerialName("status") val status: String?,
- @JsonProperty("score") @SerialName("score") val score: Int,
- @JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int,
- @JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean,
- @JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String,
+ @JsonProperty("status") val status: String?,
+ @JsonProperty("score") val score: Int,
+ @JsonProperty("num_episodes_watched") val numEpisodesWatched: Int,
+ @JsonProperty("is_rewatching") val isRewatching: Boolean,
+ @JsonProperty("updated_at") val updatedAt: String,
)
- @Serializable
data class Data(
- @JsonProperty("node") @SerialName("node") val node: Node,
- @JsonProperty("list_status") @SerialName("list_status") val listStatus: ListStatus?,
+ @JsonProperty("node") val node: Node,
+ @JsonProperty("list_status") val listStatus: ListStatus?,
) {
fun toLibraryItem(): SyncAPI.LibraryItem {
return SyncAPI.LibraryItem(
@@ -463,37 +452,32 @@ class MALApi : SyncAPI() {
}
}
- @Serializable
data class Paging(
- @JsonProperty("next") @SerialName("next") val next: String?,
+ @JsonProperty("next") val next: String?
)
- @Serializable
data class AlternativeTitles(
- @JsonProperty("synonyms") @SerialName("synonyms") val synonyms: List,
- @JsonProperty("en") @SerialName("en") val en: String,
- @JsonProperty("ja") @SerialName("ja") val ja: String,
+ @JsonProperty("synonyms") val synonyms: List,
+ @JsonProperty("en") val en: String,
+ @JsonProperty("ja") val ja: String
)
- @Serializable
data class Genres(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("name") @SerialName("name") val name: String,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("name") val name: String
)
- @Serializable
data class StartSeason(
- @JsonProperty("year") @SerialName("year") val year: Int,
- @JsonProperty("season") @SerialName("season") val season: String,
+ @JsonProperty("year") val year: Int,
+ @JsonProperty("season") val season: String
)
- @Serializable
data class Broadcast(
- @JsonProperty("day_of_the_week") @SerialName("day_of_the_week") val dayOfTheWeek: String?,
- @JsonProperty("start_time") @SerialName("start_time") val startTime: String?,
+ @JsonProperty("day_of_the_week") val dayOfTheWeek: 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 {
convertToStatus(it.listStatus?.status ?: "").stringRes
}?.mapValues { group ->
@@ -521,7 +505,7 @@ class MALApi : SyncAPI() {
)
}
- private suspend fun getMalAnimeListSmart(auth: AuthData): Array? {
+ private suspend fun getMalAnimeListSmart(auth : AuthData): Array? {
return if (requireLibraryRefresh) {
val list = getMalAnimeList(auth.token)
setKey(MAL_CACHED_LIST, auth.user.id.toString(), list)
@@ -536,7 +520,7 @@ class MALApi : SyncAPI() {
val fullList = mutableListOf()
val offsetRegex = Regex("""offset=(\d+)""")
while (true) {
- val data: MalList = getMalAnimeListSlice(token, offset)
+ val data: MalList = getMalAnimeListSlice(token, offset) ?: break
fullList.addAll(data.data)
offset =
data.paging.next?.let { offsetRegex.find(it)?.groupValues?.get(1)?.toInt() }
@@ -545,17 +529,18 @@ class MALApi : SyncAPI() {
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"
// Very lackluster docs
// 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(
url, headers = mapOf(
"Authorization" to "Bearer ${token.accessToken}",
), cacheTime = 0
).text
- return parseJson(res)
+ return res.toKotlinObject()
}
private suspend fun setScoreRequest(
@@ -598,7 +583,7 @@ class MALApi : SyncAPI() {
val data = mapOf(
"status" to status,
"score" to score?.toString(),
- "num_watched_episodes" to numWatchedEpisodes?.toString(),
+ "num_watched_episodes" to numWatchedEpisodes?.toString()
).filterValues { it != null } as Map
return app.put(
@@ -610,74 +595,71 @@ class MALApi : SyncAPI() {
).text
}
- @Serializable
+
data class ResponseToken(
- @JsonProperty("token_type") @SerialName("token_type") val tokenType: String,
- @JsonProperty("expires_in") @SerialName("expires_in") val expiresIn: Int,
- @JsonProperty("access_token") @SerialName("access_token") val accessToken: String,
- @JsonProperty("refresh_token") @SerialName("refresh_token") val refreshToken: String,
+ @JsonProperty("token_type") val tokenType: String,
+ @JsonProperty("expires_in") val expiresIn: Int,
+ @JsonProperty("access_token") val accessToken: String,
+ @JsonProperty("refresh_token") val refreshToken: String,
)
- @Serializable
data class MalRoot(
- @JsonProperty("data") @SerialName("data") val data: List,
+ @JsonProperty("data") val data: List,
)
- @Serializable
data class MalDatum(
- @JsonProperty("node") @SerialName("node") val node: MalNode,
- @JsonProperty("list_status") @SerialName("list_status") val listStatus: MalStatus,
+ @JsonProperty("node") val node: MalNode,
+ @JsonProperty("list_status") val listStatus: MalStatus,
)
- @Serializable
data class MalNode(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("title") @SerialName("title") val title: String,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("title") val title: String,
+ /*
+ also, but not used
+ main_picture ->
+ public string medium;
+ public string large;
+ */
)
- @Serializable
data class MalStatus(
- @JsonProperty("status") @SerialName("status") val status: String,
- @JsonProperty("score") @SerialName("score") val score: Int,
- @JsonProperty("num_episodes_watched") @SerialName("num_episodes_watched") val numEpisodesWatched: Int,
- @JsonProperty("is_rewatching") @SerialName("is_rewatching") val isRewatching: Boolean,
- @JsonProperty("updated_at") @SerialName("updated_at") val updatedAt: String,
+ @JsonProperty("status") val status: String,
+ @JsonProperty("score") val score: Int,
+ @JsonProperty("num_episodes_watched") val numEpisodesWatched: Int,
+ @JsonProperty("is_rewatching") val isRewatching: Boolean,
+ @JsonProperty("updated_at") val updatedAt: String,
)
- @Serializable
data class MalUser(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("location") @SerialName("location") val location: String,
- @JsonProperty("joined_at") @SerialName("joined_at") val joinedAt: String,
- @JsonProperty("picture") @SerialName("picture") val picture: String?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("name") val name: String,
+ @JsonProperty("location") val location: String,
+ @JsonProperty("joined_at") val joinedAt: String,
+ @JsonProperty("picture") val picture: String?,
)
- @Serializable
data class MalMainPicture(
- @JsonProperty("large") @SerialName("large") val large: String?,
- @JsonProperty("medium") @SerialName("medium") val medium: String?,
+ @JsonProperty("large") val large: String?,
+ @JsonProperty("medium") val medium: String?,
)
// Used for getDataAboutId()
- @Serializable
data class SmallMalAnime(
- @JsonProperty("id") @SerialName("id") val id: Int,
- @JsonProperty("title") @SerialName("title") val title: String?,
- @JsonProperty("num_episodes") @SerialName("num_episodes") val numEpisodes: Int,
- @JsonProperty("my_list_status") @SerialName("my_list_status") val myListStatus: MalStatus?,
- @JsonProperty("main_picture") @SerialName("main_picture") val mainPicture: MalMainPicture?,
+ @JsonProperty("id") val id: Int,
+ @JsonProperty("title") val title: String?,
+ @JsonProperty("num_episodes") val numEpisodes: Int,
+ @JsonProperty("my_list_status") val myListStatus: MalStatus?,
+ @JsonProperty("main_picture") val mainPicture: MalMainPicture?,
)
- @Serializable
data class MalSearchNode(
- @JsonProperty("node") @SerialName("node") val node: Node,
+ @JsonProperty("node") val node: Node,
)
- @Serializable
data class MalSearch(
- @JsonProperty("data") @SerialName("data") val data: List,
- // paging
+ @JsonProperty("data") val data: List,
+ //paging
)
data class MalTitleHolder(
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/OpenSubtitlesApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/OpenSubtitlesApi.kt
index fca3e5df8..4b17fdb29 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/OpenSubtitlesApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/OpenSubtitlesApi.kt
@@ -2,11 +2,9 @@ package com.lagradost.cloudstream3.syncproviders.providers
import android.util.Log
import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.APIHolder
-import com.lagradost.cloudstream3.APIHolder.unixTimeMS
+import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.R
-import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
import com.lagradost.cloudstream3.syncproviders.AuthData
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.SubtitleHelper.fromCodeToLangTagIETF
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToOpenSubtitlesTag
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
class OpenSubtitlesApi : SubtitleAPI() {
override val name = "OpenSubtitles"
@@ -47,17 +43,17 @@ class OpenSubtitlesApi : SubtitleAPI() {
}
private fun canDoRequest(): Boolean {
- return unixTimeMS > currentCoolDown
+ return unixTimeMs > currentCoolDown
}
private fun throwIfCantDoRequest() {
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() {
- currentCoolDown = unixTimeMS + COOLDOWN_DURATION
+ currentCoolDown = unixTimeMs + COOLDOWN_DURATION
throw ErrorLoadingException("Too many requests")
}
@@ -93,7 +89,7 @@ class OpenSubtitlesApi : SubtitleAPI() {
accessToken = response.token
?: throw ErrorLoadingException("Invalid password or username"),
/// 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()
)
}
@@ -101,7 +97,7 @@ class OpenSubtitlesApi : SubtitleAPI() {
/**
* Fetch subtitles using token authenticated on previous method (see authorize).
* Returns list of Subtitles which user can select to download (see load).
- */
+ * */
override suspend fun search(
auth : AuthData?,
query: AbstractSubtitleEntities.SubtitleSearch
@@ -181,15 +177,16 @@ class OpenSubtitlesApi : SubtitleAPI() {
return results
}
- /**
- * Process data returned from search.
- * Returns string url for the subtitle file.
- */
+ /*
+ Process data returned from search.
+ Returns string url for the subtitle file.
+ */
+
override suspend fun load(
auth : AuthData?,
subtitle: AbstractSubtitleEntities.SubtitleEntity
): String? {
- if (auth == null) return null
+ if(auth == null) return null
throwIfCantDoRequest()
val req = app.post(
@@ -221,64 +218,57 @@ class OpenSubtitlesApi : SubtitleAPI() {
return null
}
- @Serializable
data class OAuthToken(
- @JsonProperty("token") @SerialName("token") var token: String? = null,
- @JsonProperty("status") @SerialName("status") var status: Int? = null,
+ @JsonProperty("token") var token: String? = null,
+ @JsonProperty("status") var status: Int? = null
)
- @Serializable
data class Results(
- @JsonProperty("data") @SerialName("data") var data: List? = listOf(),
+ @JsonProperty("data") var data: List? = listOf()
)
- @Serializable
data class ResultData(
- @JsonProperty("id") @SerialName("id") var id: String? = null,
- @JsonProperty("type") @SerialName("type") var type: String? = null,
- @JsonProperty("attributes") @SerialName("attributes") var attributes: ResultAttributes? = ResultAttributes(),
+ @JsonProperty("id") var id: String? = null,
+ @JsonProperty("type") var type: String? = null,
+ @JsonProperty("attributes") var attributes: ResultAttributes? = ResultAttributes()
)
- @Serializable
data class ResultAttributes(
- @JsonProperty("subtitle_id") @SerialName("subtitle_id") var subtitleId: String? = null,
- @JsonProperty("language") @SerialName("language") var language: String? = null,
- @JsonProperty("release") @SerialName("release") var release: String? = null,
- @JsonProperty("url") @SerialName("url") var url: String? = null,
- @JsonProperty("files") @SerialName("files") var files: List? = listOf(),
- @JsonProperty("feature_details") @SerialName("feature_details") var featDetails: ResultFeatureDetails? = ResultFeatureDetails(),
- @JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Boolean? = null,
+ @JsonProperty("subtitle_id") var subtitleId: String? = null,
+ @JsonProperty("language") var language: String? = null,
+ @JsonProperty("release") var release: String? = null,
+ @JsonProperty("url") var url: String? = null,
+ @JsonProperty("files") var files: List? = listOf(),
+ @JsonProperty("feature_details") var featDetails: ResultFeatureDetails? = ResultFeatureDetails(),
+ @JsonProperty("hearing_impaired") var hearingImpaired: Boolean? = null,
)
- @Serializable
data class ResultFiles(
- @JsonProperty("file_id") @SerialName("file_id") var fileId: Int? = null,
- @JsonProperty("file_name") @SerialName("file_name") var fileName: String? = null,
+ @JsonProperty("file_id") var fileId: Int? = null,
+ @JsonProperty("file_name") var fileName: String? = null
)
- @Serializable
data class ResultDownloadLink(
- @JsonProperty("link") @SerialName("link") var link: String? = null,
- @JsonProperty("file_name") @SerialName("file_name") var fileName: String? = null,
- @JsonProperty("requests") @SerialName("requests") var requests: Int? = null,
- @JsonProperty("remaining") @SerialName("remaining") var remaining: Int? = null,
- @JsonProperty("message") @SerialName("message") var message: String? = null,
- @JsonProperty("reset_time") @SerialName("reset_time") var resetTime: String? = null,
- @JsonProperty("reset_time_utc") @SerialName("reset_time_utc") var resetTimeUtc: String? = null,
+ @JsonProperty("link") var link: String? = null,
+ @JsonProperty("file_name") var fileName: String? = null,
+ @JsonProperty("requests") var requests: Int? = null,
+ @JsonProperty("remaining") var remaining: Int? = null,
+ @JsonProperty("message") var message: String? = null,
+ @JsonProperty("reset_time") var resetTime: String? = null,
+ @JsonProperty("reset_time_utc") var resetTimeUtc: String? = null
)
- @Serializable
data class ResultFeatureDetails(
- @JsonProperty("year") @SerialName("year") var year: Int? = null,
- @JsonProperty("title") @SerialName("title") var title: String? = null,
- @JsonProperty("movie_name") @SerialName("movie_name") var movieName: String? = null,
- @JsonProperty("imdb_id") @SerialName("imdb_id") var imdbId: Int? = null,
- @JsonProperty("tmdb_id") @SerialName("tmdb_id") var tmdbId: Int? = null,
- @JsonProperty("season_number") @SerialName("season_number") var seasonNumber: Int? = null,
- @JsonProperty("episode_number") @SerialName("episode_number") var episodeNumber: Int? = null,
- @JsonProperty("parent_imdb_id") @SerialName("parent_imdb_id") var parentImdbId: Int? = null,
- @JsonProperty("parent_title") @SerialName("parent_title") var parentTitle: String? = null,
- @JsonProperty("parent_tmdb_id") @SerialName("parent_tmdb_id") var parentTmdbId: Int? = null,
- @JsonProperty("parent_feature_id") @SerialName("parent_feature_id") var parentFeatureId: Int? = null,
+ @JsonProperty("year") var year: Int? = null,
+ @JsonProperty("title") var title: String? = null,
+ @JsonProperty("movie_name") var movieName: String? = null,
+ @JsonProperty("imdb_id") var imdbId: Int? = null,
+ @JsonProperty("tmdb_id") var tmdbId: Int? = null,
+ @JsonProperty("season_number") var seasonNumber: Int? = null,
+ @JsonProperty("episode_number") var episodeNumber: Int? = null,
+ @JsonProperty("parent_imdb_id") var parentImdbId: Int? = null,
+ @JsonProperty("parent_title") var parentTitle: String? = null,
+ @JsonProperty("parent_tmdb_id") var parentTmdbId: Int? = null,
+ @JsonProperty("parent_feature_id") var parentFeatureId: Int? = null
)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SimklApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SimklApi.kt
index a57ec6716..c4095e2d8 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SimklApi.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SimklApi.kt
@@ -2,11 +2,10 @@ package com.lagradost.cloudstream3.syncproviders.providers
import androidx.annotation.StringRes
import androidx.core.net.toUri
-import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
-import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.BuildConfig
+import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKeys
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
@@ -17,6 +16,7 @@ import com.lagradost.cloudstream3.Score
import com.lagradost.cloudstream3.SimklSyncServices
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.app
+import com.lagradost.cloudstream3.mapper
import com.lagradost.cloudstream3.mvvm.debugPrint
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
@@ -30,14 +30,8 @@ import com.lagradost.cloudstream3.syncproviders.SyncIdName
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
import com.lagradost.cloudstream3.utils.AppUtils.toJson
-import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import com.lagradost.cloudstream3.utils.DataStoreHelper.toYear
-import com.lagradost.cloudstream3.utils.serializers.NonEmptySerializer
import com.lagradost.cloudstream3.utils.txt
-import kotlinx.serialization.ExperimentalSerializationApi
-import kotlinx.serialization.KeepGeneratedSerializer
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.math.BigInteger
import java.security.SecureRandom
import java.text.SimpleDateFormat
@@ -50,18 +44,22 @@ import kotlin.time.DurationUnit
import kotlin.time.toDuration
class SimklApi : SyncAPI() {
- override val name = "Simkl"
+ override var name = "Simkl"
override val idPrefix = "simkl"
+ val key = "simkl-key"
override val redirectUrlIdentifier = "simkl"
override val hasOAuth2 = true
override val hasPin = true
override var requireLibraryRefresh = true
- override val mainUrl = "https://api.simkl.com"
+ override var mainUrl = "https://api.simkl.com"
override val icon = R.drawable.simkl_logo
override val createAccountUrl = "$mainUrl/signup"
override val syncIdName = SyncIdName.Simkl
+ /** Automatically adds simkl auth headers */
+ // private val interceptor = HeaderInterceptor()
+
/**
* This is required to override the reported last activity as simkl activites
* may not always update based on testing.
@@ -70,99 +68,68 @@ class SimklApi : SyncAPI() {
private object SimklCache {
private const val SIMKL_CACHE_KEY = "SIMKL_API_CACHE"
+
enum class CacheTimes(val value: String) {
OneMonth("30d"),
ThirtyMinutes("30m")
}
- @Serializable
- private data class MediaObjectCacheEntry(
- @JsonProperty("obj") @SerialName("obj") val obj: MediaObject?,
- @JsonProperty("validUntil") @SerialName("validUntil") val validUntil: Long,
- @JsonProperty("cacheTime") @SerialName("cacheTime") val cacheTime: Long = APIHolder.unixTime,
- )
+ private class SimklCacheWrapper(
+ @JsonProperty("obj") val obj: T?,
+ @JsonProperty("validUntil") val validUntil: Long,
+ @JsonProperty("cacheTime") val cacheTime: Long = unixTime,
+ ) {
+ /** Returns true if cache is newer than cacheDays */
+ fun isFresh(): Boolean {
+ return validUntil > unixTime
+ }
- @Serializable
- private data class EpisodesCacheEntry(
- @JsonProperty("obj") @SerialName("obj") val obj: Array?,
- @JsonProperty("validUntil") @SerialName("validUntil") val validUntil: Long,
- @JsonProperty("cacheTime") @SerialName("cacheTime") val cacheTime: Long = APIHolder.unixTime,
- )
-
- /**
- * Minimal class used only to peek at an entry's expiry, without caring which of the
- * concrete entry types above actually produced it.
- */
- @Serializable
- private data class CacheFreshness(
- @JsonProperty("validUntil") @SerialName("validUntil") val validUntil: Long,
- )
-
- private fun Long.isFresh(): Boolean = this > APIHolder.unixTime
-
- private fun Long.remaining(): Duration {
- val unixTime = APIHolder.unixTime
- return if (this > unixTime) {
- (this - unixTime).toDuration(DurationUnit.SECONDS)
- } else {
- Duration.ZERO
+ fun remainingTime(): Duration {
+ val unixTime = unixTime
+ return if (validUntil > unixTime) {
+ (validUntil - unixTime).toDuration(DurationUnit.SECONDS)
+ } else {
+ Duration.ZERO
+ }
}
}
fun cleanOldCache() {
getKeys(SIMKL_CACHE_KEY)?.forEach {
- val isOld = getKey(it)?.validUntil?.isFresh() == false
- if (isOld) removeKey(it)
- }
- }
-
- fun setMediaObject(path: String, value: MediaObject, cacheTime: Duration) {
- debugPrint { "Set cache: $SIMKL_CACHE_KEY/$path for ${cacheTime.inWholeDays} days or ${cacheTime.inWholeSeconds} seconds." }
- setKey(
- SIMKL_CACHE_KEY,
- path,
- MediaObjectCacheEntry(value, APIHolder.unixTime + cacheTime.inWholeSeconds).toJson(),
- )
- }
-
- /** Gets the cached [MediaObject], if it's not fresh returns null and removes it from cache */
- fun getMediaObject(path: String): MediaObject? {
- val cache = getKey(SIMKL_CACHE_KEY, path)?.let {
- tryParseJson(it)
- }
-
- return if (cache?.validUntil?.isFresh() == true) {
- debugPrint {
- "Cache hit at: $SIMKL_CACHE_KEY/$path. " +
- "Remains fresh for ${cache.validUntil.remaining().inWholeDays} days or ${cache.validUntil.remaining().inWholeSeconds} seconds."
+ val isOld = CloudStreamApp.getKey>(it)?.isFresh() == false
+ if (isOld) {
+ removeKey(it)
}
- cache.obj
- } else {
- debugPrint { "Cache miss at: $SIMKL_CACHE_KEY/$path" }
- removeKey(SIMKL_CACHE_KEY, path)
- null
}
}
- fun setEpisodes(path: String, value: Array, cacheTime: Duration) {
+ fun setKey(path: String, value: T, cacheTime: Duration) {
debugPrint { "Set cache: $SIMKL_CACHE_KEY/$path for ${cacheTime.inWholeDays} days or ${cacheTime.inWholeSeconds} seconds." }
setKey(
SIMKL_CACHE_KEY,
path,
- EpisodesCacheEntry(value, APIHolder.unixTime + cacheTime.inWholeSeconds).toJson(),
+ // Storing as plain sting is required to make generics work.
+ SimklCacheWrapper(value, unixTime + cacheTime.inWholeSeconds).toJson()
)
}
- /** Gets the cached episode list, if it's not fresh returns null and removes it from cache */
- fun getEpisodes(path: String): Array? {
+ /**
+ * Gets cached object, if object is not fresh returns null and removes it from cache
+ */
+ inline fun getKey(path: String): T? {
+ // Required for generic otherwise "LinkedHashMap cannot be cast to MediaObject"
+ val type = mapper.typeFactory.constructParametricType(
+ SimklCacheWrapper::class.java,
+ T::class.java
+ )
val cache = getKey(SIMKL_CACHE_KEY, path)?.let {
- tryParseJson(it)
+ mapper.readValue>(it, type)
}
- return if (cache?.validUntil?.isFresh() == true) {
+ return if (cache?.isFresh() == true) {
debugPrint {
"Cache hit at: $SIMKL_CACHE_KEY/$path. " +
- "Remains fresh for ${cache.validUntil.remaining().inWholeDays} days or ${cache.validUntil.remaining().inWholeSeconds} seconds."
+ "Remains fresh for ${cache.remainingTime().inWholeDays} days or ${cache.remainingTime().inWholeSeconds} seconds."
}
cache.obj
} else {
@@ -206,7 +173,7 @@ class SimklApi : SyncAPI() {
)
)
)
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -222,7 +189,7 @@ class SimklApi : SyncAPI() {
enum class SimklListStatusType(
var value: Int,
@StringRes val stringRes: Int,
- val originalName: String?,
+ val originalName: String?
) {
Watching(0, R.string.type_watching, "watching"),
Completed(1, R.string.type_completed, "completed"),
@@ -241,92 +208,83 @@ class SimklApi : SyncAPI() {
}
}
+ // -------------------
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = TokenRequest.Serializer::class)
data class TokenRequest(
- @JsonProperty("code") @SerialName("code") val code: String,
- @JsonProperty("client_id") @SerialName("client_id") val clientId: String = CLIENT_ID,
- @JsonProperty("client_secret") @SerialName("client_secret") val clientSecret: String = CLIENT_SECRET,
- @JsonProperty("redirect_uri") @SerialName("redirect_uri") val redirectUri: String = "$APP_STRING://simkl",
- @JsonProperty("grant_type") @SerialName("grant_type") val grantType: String = "authorization_code",
- ) {
- object Serializer : NonEmptySerializer(TokenRequest.generatedSerializer())
- }
+ @JsonProperty("code") val code: String,
+ @JsonProperty("client_id") val clientId: String = CLIENT_ID,
+ @JsonProperty("client_secret") val clientSecret: String = CLIENT_SECRET,
+ @JsonProperty("redirect_uri") val redirectUri: String = "$APP_STRING://simkl",
+ @JsonProperty("grant_type") val grantType: String = "authorization_code"
+ )
- @Serializable
data class TokenResponse(
/** No expiration date */
- @JsonProperty("access_token") @SerialName("access_token") val accessToken: String,
- @JsonProperty("token_type") @SerialName("token_type") val tokenType: String,
- @JsonProperty("scope") @SerialName("scope") val scope: String,
+ @JsonProperty("access_token") val accessToken: String,
+ @JsonProperty("token_type") val tokenType: String,
+ @JsonProperty("scope") val scope: String
)
+ // -------------------
/** https://simkl.docs.apiary.io/#reference/users/settings/receive-settings */
- @Serializable
data class SettingsResponse(
- @JsonProperty("user") @SerialName("user") val user: User,
- @JsonProperty("account") @SerialName("account") val account: Account,
+ @JsonProperty("user")
+ val user: User,
+ @JsonProperty("account")
+ val account: Account,
) {
- @Serializable
data class User(
- @JsonProperty("name") @SerialName("name") val name: String,
- @JsonProperty("avatar") @SerialName("avatar") val avatar: String, // Url
+ @JsonProperty("name")
+ val name: String,
+ /** Url */
+ @JsonProperty("avatar")
+ val avatar: String
)
- @Serializable
data class Account(
- @JsonProperty("id") @SerialName("id") val id: Int,
+ @JsonProperty("id")
+ val id: Int,
)
}
- @Serializable
data class PinAuthResponse(
- @JsonProperty("result") @SerialName("result") val result: String,
- @JsonProperty("device_code") @SerialName("device_code") val deviceCode: String,
- @JsonProperty("user_code") @SerialName("user_code") val userCode: String,
- @JsonProperty("verification_url") @SerialName("verification_url") val verificationUrl: String,
- @JsonProperty("expires_in") @SerialName("expires_in") val expiresIn: Int,
- @JsonProperty("interval") @SerialName("interval") val interval: Int,
+ @JsonProperty("result") val result: String,
+ @JsonProperty("device_code") val deviceCode: String,
+ @JsonProperty("user_code") val userCode: String,
+ @JsonProperty("verification_url") val verificationUrl: String,
+ @JsonProperty("expires_in") val expiresIn: Int,
+ @JsonProperty("interval") val interval: Int,
)
- @Serializable
data class PinExchangeResponse(
- @JsonProperty("result") @SerialName("result") val result: String,
- @JsonProperty("message") @SerialName("message") val message: String? = null,
- @JsonProperty("access_token") @SerialName("access_token") val accessToken: String? = null,
+ @JsonProperty("result") val result: String,
+ @JsonProperty("message") val message: String? = null,
+ @JsonProperty("access_token") val accessToken: String? = null,
)
- @Serializable
+ // -------------------
data class ActivitiesResponse(
- @JsonProperty("all") @SerialName("all") val all: String?,
- @JsonProperty("tv_shows") @SerialName("tv_shows") val tvShows: UpdatedAt,
- @JsonProperty("anime") @SerialName("anime") val anime: UpdatedAt,
- @JsonProperty("movies") @SerialName("movies") val movies: UpdatedAt,
+ @JsonProperty("all") val all: String?,
+ @JsonProperty("tv_shows") val tvShows: UpdatedAt,
+ @JsonProperty("anime") val anime: UpdatedAt,
+ @JsonProperty("movies") val movies: UpdatedAt,
) {
- @Serializable
data class UpdatedAt(
- @JsonProperty("all") @SerialName("all") val all: String?,
- @JsonProperty("removed_from_list") @SerialName("removed_from_list") val removedFromList: String?,
- @JsonProperty("rated_at") @SerialName("rated_at") val ratedAt: String?,
+ @JsonProperty("all") val all: String?,
+ @JsonProperty("removed_from_list") val removedFromList: String?,
+ @JsonProperty("rated_at") val ratedAt: String?,
)
}
/** https://simkl.docs.apiary.io/#reference/tv/episodes/get-tv-show-episodes */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = EpisodeMetadata.Serializer::class)
data class EpisodeMetadata(
- @JsonProperty("title") @SerialName("title") val title: String?,
- @JsonProperty("description") @SerialName("description") val description: String?,
- @JsonProperty("season") @SerialName("season") val season: Int?,
- @JsonProperty("episode") @SerialName("episode") val episode: Int,
- @JsonProperty("img") @SerialName("img") val img: String?,
+ @JsonProperty("title") val title: String?,
+ @JsonProperty("description") val description: String?,
+ @JsonProperty("season") val season: Int?,
+ @JsonProperty("episode") val episode: Int,
+ @JsonProperty("img") val img: String?
) {
- object Serializer : NonEmptySerializer(EpisodeMetadata.generatedSerializer())
-
companion object {
fun convertToEpisodes(list: List?): List? {
return list?.map {
@@ -346,58 +304,40 @@ class SimklApi : SyncAPI() {
/**
* https://simkl.docs.apiary.io/#introduction/about-simkl-api/standard-media-objects
- * Useful for finding shows from metadata.
+ * Useful for finding shows from metadata
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = MediaObject.Serializer::class)
- data class MediaObject(
- @JsonProperty("title") @SerialName("title") val title: String?,
- @JsonProperty("year") @SerialName("year") val year: Int?,
- @JsonProperty("ids") @SerialName("ids") val ids: Ids?,
- @JsonProperty("total_episodes") @SerialName("total_episodes") val totalEpisodes: Int? = null,
- @JsonProperty("status") @SerialName("status") val status: String? = null,
- @JsonProperty("poster") @SerialName("poster") val poster: String? = null,
- @JsonProperty("type") @SerialName("type") val type: String? = null,
- @JsonProperty("seasons") @SerialName("seasons") val seasons: List? = null,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: List? = null,
+ open class MediaObject(
+ @JsonProperty("title") val title: String?,
+ @JsonProperty("year") val year: Int?,
+ @JsonProperty("ids") val ids: Ids?,
+ @JsonProperty("total_episodes") val totalEpisodes: Int? = null,
+ @JsonProperty("status") val status: String? = null,
+ @JsonProperty("poster") val poster: String? = null,
+ @JsonProperty("type") val type: String? = null,
+ @JsonProperty("seasons") val seasons: List? = null,
+ @JsonProperty("episodes") val episodes: List? = null
) {
- object Serializer : NonEmptySerializer(MediaObject.generatedSerializer())
-
fun hasEnded(): Boolean {
return status == "released" || status == "ended"
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = Season.Serializer::class)
data class Season(
- @JsonProperty("number") @SerialName("number") val number: Int,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: List,
+ @JsonProperty("number") val number: Int,
+ @JsonProperty("episodes") val episodes: List
) {
- object Serializer : NonEmptySerializer(Season.generatedSerializer())
-
- @Serializable
- data class Episode(
- @JsonProperty("number") @SerialName("number") val number: Int,
- )
+ data class Episode(@JsonProperty("number") val number: Int)
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = Ids.Serializer::class)
data class Ids(
- @JsonProperty("simkl") @SerialName("simkl") val simkl: Int?,
- @JsonProperty("imdb") @SerialName("imdb") val imdb: String? = null,
- @JsonProperty("tmdb") @SerialName("tmdb") val tmdb: String? = null,
- @JsonProperty("mal") @SerialName("mal") val mal: String? = null,
- @JsonProperty("anilist") @SerialName("anilist") val anilist: String? = null,
+ @JsonProperty("simkl") val simkl: Int?,
+ @JsonProperty("imdb") val imdb: String? = null,
+ @JsonProperty("tmdb") val tmdb: String? = null,
+ @JsonProperty("mal") val mal: String? = null,
+ @JsonProperty("anilist") val anilist: String? = null,
) {
- object Serializer : NonEmptySerializer(Ids.generatedSerializer())
-
companion object {
fun fromMap(map: Map): Ids {
return Ids(
@@ -405,21 +345,20 @@ class SimklApi : SyncAPI() {
imdb = map[SimklSyncServices.Imdb],
tmdb = map[SimklSyncServices.Tmdb],
mal = map[SimklSyncServices.Mal],
- anilist = map[SimklSyncServices.AniList],
+ anilist = map[SimklSyncServices.AniList]
)
}
}
}
fun toSyncSearchResult(): SyncAPI.SyncSearchResult? {
- val currentIds = this.ids
return SyncAPI.SyncSearchResult(
this.title ?: return null,
"Simkl",
- currentIds?.simkl?.toString() ?: return null,
- getUrlFromId(currentIds.simkl),
+ this.ids?.simkl?.toString() ?: return null,
+ getUrlFromId(this.ids.simkl),
this.poster?.let { getPosterUrl(it) },
- if (this.type == "movie") TvType.Movie else TvType.TvSeries,
+ if (this.type == "movie") TvType.Movie else TvType.TvSeries
)
}
}
@@ -434,7 +373,7 @@ class SimklApi : SyncAPI() {
private var addEpisodes: Pair?, List?>? = null,
private var removeEpisodes: Pair?, List?>? = null,
// Required for knowing if the status should be overwritten
- private var onList: Boolean = false,
+ private var onList: Boolean = false
) {
fun token(token: AuthToken) = apply { this.headers = getHeaders(token) }
fun apiUrl(url: String) = apply { this.url = url }
@@ -448,7 +387,11 @@ class SimklApi : SyncAPI() {
fun status(newStatus: Int?, oldStatus: Int?) = apply {
onList = oldStatus != null
// Only set status if its new
- this.status = if (newStatus != oldStatus) newStatus else null
+ if (newStatus != oldStatus) {
+ this.status = newStatus
+ } else {
+ this.status = null
+ }
}
fun episodes(
@@ -457,6 +400,7 @@ class SimklApi : SyncAPI() {
oldEpisodes: Int?,
) = apply {
if (allEpisodes == null || newEpisodes == null) return@apply
+
fun getEpisodes(rawEpisodes: List) =
if (rawEpisodes.any { it.season != null }) {
EpisodeMetadata.convertToSeasons(rawEpisodes) to null
@@ -467,34 +411,36 @@ class SimklApi : SyncAPI() {
// Do not add episodes if there is no change
if (newEpisodes > (oldEpisodes ?: 0)) {
this.addEpisodes = getEpisodes(allEpisodes.take(newEpisodes))
+
// Set to watching if episodes are added and there is no current status
if (!onList) {
status = SimklListStatusType.Watching.value
}
}
-
if ((oldEpisodes ?: 0) > newEpisodes) {
this.removeEpisodes = getEpisodes(allEpisodes.drop(newEpisodes))
}
}
suspend fun execute(): Boolean {
- val time = getDateTime(APIHolder.unixTime)
+ val time = getDateTime(unixTime)
val headers = this.headers ?: emptyMap()
return if (this.status == SimklListStatusType.None.value) {
app.post(
"$url/sync/history/remove",
- json = HistoryRequest(
+ json = StatusRequest(
shows = listOf(HistoryMediaObject(ids = ids)),
- movies = emptyList(),
+ movies = emptyList()
),
- headers = headers,
+ headers = headers
).isSuccessful
} else {
val statusResponse = this.status?.let { setStatus ->
- val newStatus = SimklListStatusType.entries.firstOrNull {
- it.value == setStatus
- }?.originalName ?: SimklListStatusType.Watching.originalName!!
+ val newStatus =
+ SimklListStatusType.entries
+ .firstOrNull { it.value == setStatus }?.originalName
+ ?: SimklListStatusType.Watching.originalName!!
+
app.post(
"${this.url}/sync/add-to-list",
json = StatusRequest(
@@ -504,40 +450,41 @@ class SimklApi : SyncAPI() {
null,
ids,
newStatus,
- ),
- ),
- movies = emptyList(),
+ )
+ ), movies = emptyList()
),
- headers = headers,
+ headers = headers
).isSuccessful
} ?: true
val episodeRemovalResponse = removeEpisodes?.let { (seasons, episodes) ->
app.post(
"${this.url}/sync/history/remove",
- json = HistoryRequest(
+ json = StatusRequest(
shows = listOf(
HistoryMediaObject(
ids = ids,
seasons = seasons,
- episodes = episodes,
- ),
+ episodes = episodes
+ )
),
- movies = emptyList(),
+ movies = emptyList()
),
- headers = headers,
+ headers = headers
).isSuccessful
} ?: true
// You cannot rate if you are planning to watch it.
- val shouldRate = score != null && status != SimklListStatusType.Planning.value
+ val shouldRate =
+ score != null && status != SimklListStatusType.Planning.value
val realScore = if (shouldRate) score else null
+
val historyResponse =
// Only post if there are episodes or score to upload
if (addEpisodes != null || shouldRate) {
app.post(
"${this.url}/sync/history",
- json = HistoryRequest(
+ json = StatusRequest(
shows = listOf(
HistoryMediaObject(
null,
@@ -547,33 +494,34 @@ class SimklApi : SyncAPI() {
addEpisodes?.second,
realScore,
realScore?.let { time },
- ),
- ),
- movies = emptyList(),
+ )
+ ), movies = emptyList()
),
- headers = headers,
+ headers = headers
).isSuccessful
- } else true
+ } else {
+ true
+ }
+
statusResponse && episodeRemovalResponse && historyResponse
}
}
}
}
- fun getHeaders(token: AuthToken): Map = mapOf(
- "Authorization" to "Bearer ${token.accessToken}",
- "simkl-api-key" to CLIENT_ID,
- )
+ fun getHeaders(token: AuthToken): Map =
+ mapOf("Authorization" to "Bearer ${token.accessToken}", "simkl-api-key" to CLIENT_ID)
suspend fun getEpisodes(
simklId: Int?,
type: String?,
episodes: Int?,
- hasEnded: Boolean?,
+ hasEnded: Boolean?
): Array? {
if (simklId == null) return null
+
val cacheKey = "Episodes/$simklId"
- val cache = SimklCache.getEpisodes(cacheKey)
+ val cache = SimklCache.getKey>(cacheKey)
// Return cached result if its higher or equal the amount of episodes.
if (cache != null && cache.size >= (episodes ?: 0)) {
@@ -590,7 +538,6 @@ class SimklApi : SyncAPI() {
}.toTypedArray()
}
}
-
val url = when (type) {
"anime" -> "https://api.simkl.com/anime/episodes/$simklId"
"tv" -> "https://api.simkl.com/tv/episodes/$simklId"
@@ -605,86 +552,57 @@ class SimklApi : SyncAPI() {
if (hasEnded == true) SimklCache.CacheTimes.OneMonth.value else SimklCache.CacheTimes.ThirtyMinutes.value
// 1 Month cache
- SimklCache.setEpisodes(cacheKey, it, Duration.parse(cacheTime))
+ SimklCache.setKey(cacheKey, it, Duration.parse(cacheTime))
}
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = HistoryMediaObject.Serializer::class)
- data class HistoryMediaObject(
- @JsonProperty("title") @SerialName("title") val title: String? = null,
- @JsonProperty("year") @SerialName("year") val year: Int? = null,
- @JsonProperty("ids") @SerialName("ids") val ids: MediaObject.Ids? = null,
- @JsonProperty("seasons") @SerialName("seasons") val seasons: List? = null,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: List? = null,
- @JsonProperty("rating") @SerialName("rating") val rating: Int? = null,
- @JsonProperty("rated_at") @SerialName("rated_at") val ratedAt: String? = null,
- ) {
- object Serializer : NonEmptySerializer(HistoryMediaObject.generatedSerializer())
- }
+ class HistoryMediaObject(
+ @JsonProperty("title") title: String? = null,
+ @JsonProperty("year") year: Int? = null,
+ @JsonProperty("ids") ids: Ids? = null,
+ @JsonProperty("seasons") seasons: List? = null,
+ @JsonProperty("episodes") episodes: List? = null,
+ @JsonProperty("rating") val rating: Int? = null,
+ @JsonProperty("rated_at") val ratedAt: String? = null,
+ ) : MediaObject(title, year, ids, seasons = seasons, episodes = episodes)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = RatingMediaObject.Serializer::class)
- data class RatingMediaObject(
- @JsonProperty("title") @SerialName("title") val title: String? = null,
- @JsonProperty("year") @SerialName("year") val year: Int? = null,
- @JsonProperty("ids") @SerialName("ids") val ids: MediaObject.Ids? = null,
- @JsonProperty("rating") @SerialName("rating") val rating: Int,
- @JsonProperty("rated_at") @SerialName("rated_at") val ratedAt: String? = getDateTime(APIHolder.unixTime),
- ) {
- object Serializer : NonEmptySerializer(RatingMediaObject.generatedSerializer())
- }
+ class RatingMediaObject(
+ @JsonProperty("title") title: String?,
+ @JsonProperty("year") year: Int?,
+ @JsonProperty("ids") ids: Ids?,
+ @JsonProperty("rating") val rating: Int,
+ @JsonProperty("rated_at") val ratedAt: String? = getDateTime(unixTime)
+ ) : MediaObject(title, year, ids)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = StatusMediaObject.Serializer::class)
- data class StatusMediaObject(
- @JsonProperty("title") @SerialName("title") val title: String? = null,
- @JsonProperty("year") @SerialName("year") val year: Int? = null,
- @JsonProperty("ids") @SerialName("ids") val ids: MediaObject.Ids? = null,
- @JsonProperty("to") @SerialName("to") val to: String,
- @JsonProperty("watched_at") @SerialName("watched_at") val watchedAt: String? = getDateTime(APIHolder.unixTime),
- ) {
- object Serializer : NonEmptySerializer(StatusMediaObject.generatedSerializer())
- }
+ class StatusMediaObject(
+ @JsonProperty("title") title: String?,
+ @JsonProperty("year") year: Int?,
+ @JsonProperty("ids") ids: Ids?,
+ @JsonProperty("to") val to: String,
+ @JsonProperty("watched_at") val watchedAt: String? = getDateTime(unixTime)
+ ) : MediaObject(title, year, ids)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = StatusRequest.Serializer::class)
data class StatusRequest(
- @JsonProperty("movies") @SerialName("movies") val movies: List,
- @JsonProperty("shows") @SerialName("shows") val shows: List,
- ) {
- object Serializer : NonEmptySerializer(StatusRequest.generatedSerializer())
- }
-
- /** Same shape as [StatusRequest], for the endpoints that post [HistoryMediaObject]s instead. */
- @JsonInclude(JsonInclude.Include.NON_EMPTY)
- @OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
- @KeepGeneratedSerializer
- @Serializable(with = HistoryRequest.Serializer::class)
- data class HistoryRequest(
- @JsonProperty("movies") @SerialName("movies") val movies: List,
- @JsonProperty("shows") @SerialName("shows") val shows: List,
- ) {
- object Serializer : NonEmptySerializer(HistoryRequest.generatedSerializer())
- }
+ @JsonProperty("movies") val movies: List,
+ @JsonProperty("shows") val shows: List
+ )
/** https://simkl.docs.apiary.io/#reference/sync/get-all-items/get-all-items-in-the-user's-watchlist */
- @Serializable
data class AllItemsResponse(
- @JsonProperty("shows") @SerialName("shows") val shows: List = emptyList(),
- @JsonProperty("anime") @SerialName("anime") val anime: List = emptyList(),
- @JsonProperty("movies") @SerialName("movies") val movies: List = emptyList(),
+ @JsonProperty("shows")
+ val shows: List = emptyList(),
+ @JsonProperty("anime")
+ val anime: List = emptyList(),
+ @JsonProperty("movies")
+ val movies: List = emptyList(),
) {
companion object {
fun merge(first: AllItemsResponse?, second: AllItemsResponse?): AllItemsResponse {
+
// Replace the first item with the same id, or add the new item
fun MutableList.replaceOrAddItem(newItem: T, predicate: (T) -> Boolean) {
for (i in this.indices) {
@@ -693,10 +611,10 @@ class SimklApi : SyncAPI() {
return
}
}
-
this.add(newItem)
}
+ //
fun merge(
first: List?,
second: List?
@@ -730,17 +648,15 @@ class SimklApi : SyncAPI() {
fun toLibraryItem(): SyncAPI.LibraryItem
}
- @Serializable
data class MovieMetadata(
- @JsonProperty("last_watched_at") @SerialName("last_watched_at") override val lastWatchedAt: String?,
- @JsonProperty("status") @SerialName("status") override val status: String,
- @JsonProperty("user_rating") @SerialName("user_rating") override val userRating: Int?,
- @JsonProperty("last_watched") @SerialName("last_watched") override val lastWatched: String?,
- @JsonProperty("watched_episodes_count") @SerialName("watched_episodes_count") override val watchedEpisodesCount: Int?,
- @JsonProperty("total_episodes_count") @SerialName("total_episodes_count") override val totalEpisodesCount: Int?,
- @JsonProperty("movie") @SerialName("movie") val movie: ShowMetadata.Show,
+ @JsonProperty("last_watched_at") override val lastWatchedAt: String?,
+ @JsonProperty("status") override val status: String,
+ @JsonProperty("user_rating") override val userRating: Int?,
+ @JsonProperty("last_watched") override val lastWatched: String?,
+ @JsonProperty("watched_episodes_count") override val watchedEpisodesCount: Int?,
+ @JsonProperty("total_episodes_count") override val totalEpisodesCount: Int?,
+ val movie: ShowMetadata.Show
) : Metadata {
- @JsonIgnore
override fun getIds(): ShowMetadata.Show.Ids {
return this.movie.ids
}
@@ -760,22 +676,20 @@ class SimklApi : SyncAPI() {
null,
null,
this.movie.year?.toYear(),
- movie.ids.simkl,
+ movie.ids.simkl
)
}
}
- @Serializable
data class ShowMetadata(
- @JsonProperty("last_watched_at") @SerialName("last_watched_at") override val lastWatchedAt: String?,
- @JsonProperty("status") @SerialName("status") override val status: String,
- @JsonProperty("user_rating") @SerialName("user_rating") override val userRating: Int?,
- @JsonProperty("last_watched") @SerialName("last_watched") override val lastWatched: String?,
- @JsonProperty("watched_episodes_count") @SerialName("watched_episodes_count") override val watchedEpisodesCount: Int?,
- @JsonProperty("total_episodes_count") @SerialName("total_episodes_count") override val totalEpisodesCount: Int?,
- @JsonProperty("show") @SerialName("show") val show: Show,
+ @JsonProperty("last_watched_at") override val lastWatchedAt: String?,
+ @JsonProperty("status") override val status: String,
+ @JsonProperty("user_rating") override val userRating: Int?,
+ @JsonProperty("last_watched") override val lastWatched: String?,
+ @JsonProperty("watched_episodes_count") override val watchedEpisodesCount: Int?,
+ @JsonProperty("total_episodes_count") override val totalEpisodesCount: Int?,
+ @JsonProperty("show") val show: Show
) : Metadata {
- @JsonIgnore
override fun getIds(): Show.Ids {
return this.show.ids
}
@@ -795,30 +709,28 @@ class SimklApi : SyncAPI() {
null,
null,
this.show.year?.toYear(),
- show.ids.simkl,
+ show.ids.simkl
)
}
- @Serializable
data class Show(
- @JsonProperty("title") @SerialName("title") val title: String,
- @JsonProperty("poster") @SerialName("poster") val poster: String?,
- @JsonProperty("year") @SerialName("year") val year: Int?,
- @JsonProperty("ids") @SerialName("ids") val ids: Ids,
+ @JsonProperty("title") val title: String,
+ @JsonProperty("poster") val poster: String?,
+ @JsonProperty("year") val year: Int?,
+ @JsonProperty("ids") val ids: Ids,
) {
- @Serializable
data class Ids(
- @JsonProperty("simkl") @SerialName("simkl") val simkl: Int,
- @JsonProperty("slug") @SerialName("slug") val slug: String?,
- @JsonProperty("imdb") @SerialName("imdb") val imdb: String?,
- @JsonProperty("zap2it") @SerialName("zap2it") val zap2it: String?,
- @JsonProperty("tmdb") @SerialName("tmdb") val tmdb: String?,
- @JsonProperty("offen") @SerialName("offen") val offen: String?,
- @JsonProperty("tvdb") @SerialName("tvdb") val tvdb: String?,
- @JsonProperty("mal") @SerialName("mal") val mal: String?,
- @JsonProperty("anidb") @SerialName("anidb") val anidb: String?,
- @JsonProperty("anilist") @SerialName("anilist") val anilist: String?,
- @JsonProperty("traktslug") @SerialName("traktslug") val traktslug: String?,
+ @JsonProperty("simkl") val simkl: Int,
+ @JsonProperty("slug") val slug: String?,
+ @JsonProperty("imdb") val imdb: String?,
+ @JsonProperty("zap2it") val zap2it: String?,
+ @JsonProperty("tmdb") val tmdb: String?,
+ @JsonProperty("offen") val offen: String?,
+ @JsonProperty("tvdb") val tvdb: String?,
+ @JsonProperty("mal") val mal: String?,
+ @JsonProperty("anidb") val anidb: String?,
+ @JsonProperty("anilist") val anilist: String?,
+ @JsonProperty("traktslug") val traktslug: String?
) {
fun matchesId(database: SimklSyncServices, id: String): Boolean {
return when (database) {
@@ -835,10 +747,27 @@ class SimklApi : SyncAPI() {
}
}
+ /**
+ * Appends api keys to the requests
+ **/
+ /*private inner class HeaderInterceptor : Interceptor {
+ override fun intercept(chain: Interceptor.Chain): Response {
+ debugPrint { "${this@SimklApi.name} made request to ${chain.request().url}" }
+ return chain.proceed(
+ chain.request()
+ .newBuilder()
+ .addHeader("Authorization", "Bearer $token")
+ .addHeader("simkl-api-key", CLIENT_ID)
+ .build()
+ )
+ }
+ }*/
+
private suspend fun getUser(token: AuthToken): SettingsResponse =
app.post("$mainUrl/users/settings", headers = getHeaders(token))
.parsed()
+
/**
* Useful to get episodes on demand to prevent unnecessary requests.
*/
@@ -846,7 +775,7 @@ class SimklApi : SyncAPI() {
private val simklId: Int?,
private val type: String?,
private val totalEpisodeCount: Int?,
- private val hasEnded: Boolean?,
+ private val hasEnded: Boolean?
) {
suspend fun getEpisodes(): Array? {
return getEpisodes(simklId, type, totalEpisodeCount, hasEnded)
@@ -861,12 +790,10 @@ class SimklApi : SyncAPI() {
val episodeConstructor: SimklEpisodeConstructor,
override var isFavorite: Boolean? = null,
override var maxEpisodes: Int? = null,
- /**
- * Save seen episodes separately to know the change from old to new.
- * Required to remove seen episodes if count decreases.
- */
+ /** Save seen episodes separately to know the change from old to new.
+ * Required to remove seen episodes if count decreases */
val oldEpisodes: Int,
- val oldStatus: String?,
+ val oldStatus: String?
) : SyncAPI.AbstractSyncStatus()
override suspend fun status(auth: AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
@@ -876,23 +803,22 @@ class SimklApi : SyncAPI() {
// Key which assumes all ids are the same each time :/
// This could be some sort of reference system to make multiple IDs
// point to the same key.
- val idKey = realIds.toList().map {
- "${it.first.originalName}=${it.second}"
- }.sorted().joinToString()
+ val idKey =
+ realIds.toList().map { "${it.first.originalName}=${it.second}" }.sorted().joinToString()
- val cachedObject = SimklCache.getMediaObject(idKey)
+ val cachedObject = SimklCache.getKey(idKey)
val searchResult: MediaObject = cachedObject
?: (searchByIds(realIds)?.firstOrNull()?.also { result ->
val cacheTime =
if (result.hasEnded()) SimklCache.CacheTimes.OneMonth.value else SimklCache.CacheTimes.ThirtyMinutes.value
- SimklCache.setMediaObject(idKey, result, Duration.parse(cacheTime))
+ SimklCache.setKey(idKey, result, Duration.parse(cacheTime))
}) ?: return null
val episodeConstructor = SimklEpisodeConstructor(
searchResult.ids?.simkl,
searchResult.type,
searchResult.totalEpisodes,
- searchResult.hasEnded(),
+ searchResult.hasEnded()
)
val foundItem = getSyncListSmart(auth)?.let { list ->
@@ -907,16 +833,19 @@ class SimklApi : SyncAPI() {
return SimklSyncStatus(
status = foundItem.status?.let {
SyncWatchType.fromInternalId(
- SimklListStatusType.fromString(it)?.value
+ SimklListStatusType.fromString(
+ it
+ )?.value
)
- } ?: return null,
+ }
+ ?: return null,
score = Score.from10(foundItem.userRating),
watchedEpisodes = foundItem.watchedEpisodesCount,
maxEpisodes = searchResult.totalEpisodes,
episodeConstructor = episodeConstructor,
oldEpisodes = foundItem.watchedEpisodesCount ?: 0,
oldScore = foundItem.userRating,
- oldStatus = foundItem.status,
+ oldStatus = foundItem.status
)
} else {
return SimklSyncStatus(
@@ -927,7 +856,7 @@ class SimklApi : SyncAPI() {
episodeConstructor = episodeConstructor,
oldEpisodes = 0,
oldStatus = null,
- oldScore = null,
+ oldScore = null
)
}
}
@@ -935,11 +864,12 @@ class SimklApi : SyncAPI() {
override suspend fun updateStatus(
auth: AuthData?,
id: String,
- newStatus: AbstractSyncStatus,
+ newStatus: AbstractSyncStatus
): Boolean {
- lastScoreTime = APIHolder.unixTime
val parsedId = readIdFromString(id)
+ lastScoreTime = unixTime
val simklStatus = newStatus as? SimklSyncStatus
+
val builder = SimklScoreBuilder.Builder()
.apiUrl(this.mainUrl)
.score(newStatus.score?.toInt(10), simklStatus?.oldScore)
@@ -953,6 +883,7 @@ class SimklApi : SyncAPI() {
.token(auth?.token ?: return false)
.ids(MediaObject.Ids.fromMap(parsedId))
+
// Get episodes only when required
val episodes = simklStatus?.episodeConstructor?.getEpisodes()
@@ -965,33 +896,38 @@ class SimklApi : SyncAPI() {
}
builder.episodes(episodes?.toList(), watchedEpisodes, simklStatus?.oldEpisodes)
+
requireLibraryRefresh = true
return builder.execute()
}
+
/** See https://simkl.docs.apiary.io/#reference/search/id-lookup/get-items-by-id */
private suspend fun searchByIds(serviceMap: Map): Array? {
if (serviceMap.isEmpty()) return emptyArray()
+
return app.get(
"$mainUrl/search/id",
params = mapOf("client_id" to CLIENT_ID) + serviceMap.map { (service, id) ->
service.originalName to id
}
- ).parsedSafe>()
+ ).parsedSafe()
}
override suspend fun search(auth: AuthData?, query: String): List? {
return app.get(
- "$mainUrl/search/", params = mapOf("client_id" to CLIENT_ID, "q" to query)
+ "$mainUrl/search/", params = mapOf("client_id" to CLIENT_ID, "q" to name)
).parsedSafe>()?.mapNotNull { it.toSyncSearchResult() }
}
override fun loginRequest(): AuthLoginPage? {
val lastLoginState = BigInteger(130, SecureRandom()).toString(32)
- val url = "https://simkl.com/oauth/authorize?response_type=code&client_id=$CLIENT_ID&redirect_uri=$APP_STRING://$redirectUrlIdentifier&state=$lastLoginState"
+ val url =
+ "https://simkl.com/oauth/authorize?response_type=code&client_id=$CLIENT_ID&redirect_uri=$APP_STRING://${redirectUrlIdentifier}&state=$lastLoginState"
+
return AuthLoginPage(
url = url,
- payload = lastLoginState,
+ payload = lastLoginState
)
}
@@ -1006,12 +942,12 @@ class SimklApi : SyncAPI() {
return app.get(
"$mainUrl/sync/all-items/",
params = params,
- headers = getHeaders(auth.token),
- ).parsedSafe()
+ headers = getHeaders(auth.token)
+ ).parsedSafe()
}
private suspend fun getActivities(token: AuthToken): ActivitiesResponse? {
- return app.post("$mainUrl/sync/activities", headers = getHeaders(token)).parsedSafe()
+ return app.post("$mainUrl/sync/activities", headers = getHeaders(token)).parsedSafe()
}
private fun getSyncListCached(auth: AuthData): AllItemsResponse? {
@@ -1025,13 +961,18 @@ class SimklApi : SyncAPI() {
val lastRemoval = listOf(
activities?.tvShows?.removedFromList,
activities?.anime?.removedFromList,
- activities?.movies?.removedFromList,
- ).maxOf { getUnixTime(it) ?: -1 }
- val lastRealUpdate = listOf(
- activities?.tvShows?.all,
- activities?.anime?.all,
- activities?.movies?.all,
- ).maxOf { getUnixTime(it) ?: -1 }
+ activities?.movies?.removedFromList
+ ).maxOf {
+ getUnixTime(it) ?: -1
+ }
+ val lastRealUpdate =
+ listOf(
+ activities?.tvShows?.all,
+ activities?.anime?.all,
+ activities?.movies?.all,
+ ).maxOf {
+ getUnixTime(it) ?: -1
+ }
debugPrint { "Cache times: lastCacheUpdate=$lastCacheUpdate, lastRemoval=$lastRemoval, lastRealUpdate=$lastRealUpdate" }
val list = if (lastCacheUpdate == null || lastCacheUpdate < lastRemoval) {
@@ -1043,33 +984,38 @@ class SimklApi : SyncAPI() {
setKey(SIMKL_CACHED_LIST_TIME, userId, lastCacheUpdate)
AllItemsResponse.merge(
getSyncListCached(auth),
- getSyncListSince(auth, lastCacheUpdate),
+ getSyncListSince(auth, lastCacheUpdate)
)
} else {
debugPrint { "Cached list update in ${this.name}." }
getSyncListCached(auth)
}
-
debugPrint { "List sizes: movies=${list?.movies?.size}, shows=${list?.shows?.size}, anime=${list?.anime?.size}" }
+
setKey(SIMKL_CACHED_LIST, userId, list)
+
return list
}
override suspend fun library(auth: AuthData?): SyncAPI.LibraryMetadata? {
val list = getSyncListSmart(auth ?: return null) ?: return null
- val baseMap = SimklListStatusType.entries
- .filter { it.value >= 0 && it.value != SimklListStatusType.ReWatching.value }
- .associate {
- it.stringRes to emptyList()
- }
+
+ val baseMap =
+ SimklListStatusType.entries
+ .filter { it.value >= 0 && it.value != SimklListStatusType.ReWatching.value }
+ .associate {
+ it.stringRes to emptyList()
+ }
val syncMap = listOf(list.anime, list.movies, list.shows)
.flatten()
- .groupBy { it.status }
+ .groupBy {
+ it.status
+ }
.mapNotNull { (status, list) ->
- val stringRes = status?.let {
- SimklListStatusType.fromString(it)?.stringRes
- } ?: return@mapNotNull null
+ val stringRes =
+ status?.let { SimklListStatusType.fromString(it)?.stringRes }
+ ?: return@mapNotNull null
val libraryList = list.map { it.toLibraryItem() }
stringRes to libraryList
}.toMap()
@@ -1095,14 +1041,15 @@ class SimklApi : SyncAPI() {
override suspend fun pinRequest(): AuthPinData? {
val pinAuthResp = app.get(
- "$mainUrl/oauth/pin?client_id=$CLIENT_ID&redirect_uri=$APP_STRING://$redirectUrlIdentifier"
+ "$mainUrl/oauth/pin?client_id=$CLIENT_ID&redirect_uri=$APP_STRING://${redirectUrlIdentifier}"
).parsedSafe() ?: return null
+
return AuthPinData(
deviceCode = pinAuthResp.deviceCode,
userCode = pinAuthResp.userCode,
verificationUrl = pinAuthResp.verificationUrl,
expiresIn = pinAuthResp.expiresIn,
- interval = pinAuthResp.interval,
+ interval = pinAuthResp.interval
)
}
@@ -1110,6 +1057,7 @@ class SimklApi : SyncAPI() {
val pinAuthResp = app.get(
"$mainUrl/oauth/pin/${payload.userCode}?client_id=$CLIENT_ID"
).parsedSafe() ?: return null
+
return AuthToken(
accessToken = pinAuthResp.accessToken ?: return null,
)
@@ -1125,6 +1073,7 @@ class SimklApi : SyncAPI() {
val tokenResponse = app.post(
"$mainUrl/oauth/token", json = TokenRequest(code)
).parsedSafe() ?: return null
+
return AuthToken(
accessToken = tokenResponse.accessToken,
)
@@ -1135,7 +1084,7 @@ class SimklApi : SyncAPI() {
return AuthUser(
id = user.account.id,
name = user.user.name,
- profilePicture = user.user.avatar,
+ profilePicture = user.user.avatar
)
}
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SubSource.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SubSource.kt
index 317c3dc90..19122768e 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SubSource.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SubSource.kt
@@ -7,10 +7,9 @@ import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities
import com.lagradost.cloudstream3.subtitles.SubtitleResource
import com.lagradost.cloudstream3.syncproviders.AuthData
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 kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-import java.util.concurrent.TimeUnit
class SubSourceApi : SubtitleAPI() {
override val name = "SubSource"
@@ -19,70 +18,77 @@ class SubSourceApi : SubtitleAPI() {
override val requiresLogin = false
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(
auth: AuthData?,
query: AbstractSubtitleEntities.SubtitleSearch
): List? {
+
//Only supports Imdb Id search for now
if (query.imdbId == null) return null
val queryLang = SubtitleHelper.fromTagToEnglishLanguageName(query.lang)
val type = if ((query.seasonNumber ?: 0) > 0) TvType.TvSeries else TvType.Movie
- val searchResponse = app.post(
- url = "$APIURL/movie/search",
- json = mapOf(
- "includeSeasons" to false,
- "limit" to 15,
- "query" to query.imdbId!!,
- "signal" to "{}"
- ),
- cacheTime = 120,
- cacheUnit = TimeUnit.MINUTES,
- ).parsedSafe() ?: return null
-
- val firstResult = searchResponse.results.firstOrNull() ?: return null
-
- val apiResponse = app.get(
- url = "$APIURL${firstResult.link.replace("series", "subtitles")}",
- cacheTime = 120,
- cacheUnit = TimeUnit.MINUTES,
- ).parsedSafe() ?: 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
+ val searchRes = app.post(
+ url = "$APIURL/searchMovie",
+ data = mapOf(
+ "query" to query.imdbId!!
+ )
+ ).parsedSafe() ?: return null
+
+ val postData = if (type == TvType.TvSeries) {
+ mapOf(
+ "langs" to "[]",
+ "movieName" to searchRes.found.first().linkName,
+ "season" to "season-${query.seasonNumber}"
+ )
+ } else {
+ mapOf(
+ "langs" to "[]",
+ "movieName" to searchRes.found.first().linkName,
)
- filteredSubtitles.filter { sub ->
- sub.releaseInfo.contains(
- shouldContain
- )
- }
}
- return subtitles.map { subtitle ->
+ val getMovieRes = app.post(
+ url = "$APIURL/getMovie",
+ data = postData
+ ).parsedSafe().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(
idPrefix = this.idPrefix,
- name = subtitle.releaseInfo,
- lang = subtitle.language,
- data = subtitle.link,
+ name = subtitle.releaseName!!,
+ lang = subtitle.lang!!,
+ data = SubData(
+ movie = subtitle.linkName!!,
+ lang = subtitle.lang,
+ id = subtitle.subId.toString(),
+ ).toJson(),
type = type,
source = this.name,
epNumber = query.epNumber,
seasonNumber = query.seasonNumber,
- isHearingImpaired = subtitle.hearingImpaired == 1,
+ isHearingImpaired = subtitle.hi == 1,
)
}
}
@@ -91,114 +97,71 @@ class SubSourceApi : SubtitleAPI() {
auth: AuthData?,
subtitle: AbstractSubtitleEntities.SubtitleEntity
) {
- val data = app.get("$APIURL/subtitle/${subtitle.data}")
- .parsedSafe()
- ?: return
+ val parsedSub = parseJson(subtitle.data)
+
+ val subRes = app.post(
+ url = "$APIURL/getSub",
+ data = mapOf(
+ "movie" to parsedSub.movie,
+ "lang" to subtitle.lang,
+ "id" to parsedSub.id
+ )
+ ).parsedSafe() ?: return
this.addZipUrl(
- "$APIURL/subtitle/download/${data.subtitle.downloadToken}"
+ "$DOWNLOADENDPOINT/${subRes.sub.downloadToken}"
) { name, _ ->
name
}
}
-
- @Serializable
- data class SearchRoot(
- @JsonProperty("success") @SerialName("success") var success: Boolean? = null,
- @JsonProperty("results") @SerialName("results") var results: ArrayList = arrayListOf(),
- @JsonProperty("users") @SerialName("users") var users: ArrayList = arrayListOf()
+ data class ApiSearch(
+ @JsonProperty("success") val success: Boolean,
+ @JsonProperty("found") val found: List