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/pull_request.yml b/.github/workflows/pull_request.yml
index 433816e0f..8f5c62866 100644
--- a/.github/workflows/pull_request.yml
+++ b/.github/workflows/pull_request.yml
@@ -26,11 +26,6 @@ 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
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..75a9698c8 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -9,8 +9,6 @@ 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())
@@ -278,8 +276,6 @@ dependencies {
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")
@@ -290,12 +286,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,9 +323,11 @@ 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",
+ "kotlin.uuid.ExperimentalUuidApi",
)
}
}
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
index 84ef1fee0..de6802635 100644
--- a/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
+++ b/app/src/androidTest/java/com/lagradost/cloudstream3/SerializationClassTester.kt
@@ -136,9 +136,9 @@ class SerializationClassTester {
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
+ kClass.java.annotations.any {
+ it is Serializable
+ } && kClass.java.annotations.none { it is SkipSerializationTest }
}
}
diff --git a/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/SerializerTest.kt b/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/SerializerTest.kt
new file mode 100644
index 000000000..15ad532f8
--- /dev/null
+++ b/app/src/androidTest/java/com/lagradost/cloudstream3/utils/serializers/SerializerTest.kt
@@ -0,0 +1,157 @@
+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.ExperimentalSerializationApi
+import kotlinx.serialization.KeepGeneratedSerializer
+import kotlinx.serialization.Serializable
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+@OptIn(ExperimentalSerializationApi::class)
+@KeepGeneratedSerializer
+@Serializable(with = NonEmptyData.Serializer::class)
+data class NonEmptyData(
+ val title: String = "",
+ val tags: List = emptyList(),
+ val meta: Map = emptyMap(),
+ val name: String = "hello",
+) {
+ object Serializer : NonEmptySerializer(NonEmptyData.generatedSerializer())
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+@KeepGeneratedSerializer
+@Serializable(with = WriteOnlyData.Serializer::class)
+data class WriteOnlyData(
+ val fieldA: String = "",
+ val fieldB: String = "",
+) {
+ object Serializer : WriteOnlySerializer(
+ WriteOnlyData.generatedSerializer(),
+ setOf("fieldB"),
+ )
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+@KeepGeneratedSerializer
+@Serializable(with = MultiWriteOnly.Serializer::class)
+data class MultiWriteOnly(
+ val fieldA: String = "",
+ val fieldB: String = "",
+ val fieldC: String = "",
+) {
+ object Serializer : WriteOnlySerializer(
+ MultiWriteOnly.generatedSerializer(),
+ setOf("fieldB", "fieldC"),
+ )
+}
+
+@Serializable
+data class UriData(
+ @Serializable(with = UriSerializer::class)
+ val uri: Uri = Uri.EMPTY,
+)
+
+class SerializerTest {
+
+ @Test
+ fun nonEmptySerializerOmitsEmptyStrings() {
+ val data = NonEmptyData(title = "", name = "hello")
+ val result = data.toJson()
+ assertFalse(result.contains("title"))
+ assertTrue(result.contains("name"))
+ }
+
+ @Test
+ fun nonEmptySerializerOmitsEmptyLists() {
+ val data = NonEmptyData(tags = emptyList(), name = "hello")
+ val result = data.toJson()
+ assertFalse(result.contains("tags"))
+ }
+
+ @Test
+ fun nonEmptySerializerOmitsEmptyMaps() {
+ val data = NonEmptyData(meta = emptyMap(), name = "hello")
+ val result = data.toJson()
+ assertFalse(result.contains("meta"))
+ }
+
+ @Test
+ fun nonEmptySerializerKeepsNonEmptyFields() {
+ val data = NonEmptyData(title = "hello", tags = listOf("a"), meta = mapOf("k" to "v"))
+ val result = data.toJson()
+ assertTrue(result.contains("title"))
+ assertTrue(result.contains("tags"))
+ assertTrue(result.contains("meta"))
+ }
+
+ @Test
+ fun nonEmptySerializerDoesNotAffectDeserialization() {
+ val input = """{"title":"hello","tags":["a"],"meta":{"k":"v"},"name":"world"}"""
+ val result = parseJson(input)
+ assertEquals("hello", result.title)
+ assertEquals(listOf("a"), result.tags)
+ assertEquals(mapOf("k" to "v"), result.meta)
+ assertEquals("world", result.name)
+ }
+
+ @Test
+ fun writeOnlySerializerOmitsFieldOnSerialize() {
+ val data = WriteOnlyData(fieldA = "hello", fieldB = "secret")
+ val result = data.toJson()
+ assertTrue(result.contains("fieldA"))
+ assertFalse(result.contains("fieldB"))
+ }
+
+ @Test
+ fun writeOnlySerializerDeserializesNormally() {
+ val input = """{"fieldA":"hello","fieldB":"secret"}"""
+ val result = parseJson(input)
+ assertEquals("hello", result.fieldA)
+ assertEquals("secret", result.fieldB)
+ }
+
+ @Test
+ fun writeOnlySerializerDeserializesMissingAsDefault() {
+ val input = """{"fieldA":"hello"}"""
+ val result = parseJson(input)
+ assertEquals("hello", result.fieldA)
+ assertEquals("", result.fieldB)
+ }
+
+ @Test
+ fun writeOnlySerializerHandlesMultipleKeys() {
+ val data = MultiWriteOnly(fieldA = "hello", fieldB = "secret1", fieldC = "secret2")
+ val result = data.toJson()
+ assertTrue(result.contains("fieldA"))
+ assertFalse(result.contains("fieldB"))
+ assertFalse(result.contains("fieldC"))
+ }
+
+ @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/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 1012efb56..ee4c978f2 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -253,10 +253,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/MainActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
index 253f10237..0cbed1809 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
@@ -171,7 +171,6 @@ 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
@@ -179,7 +178,6 @@ 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.theme.CloudStreamTheme
import com.lagradost.safefile.SafeFile
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
@@ -1216,7 +1214,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
@@ -1298,14 +1296,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
padRight = false,
padTop = false
)
-
- composeView.apply {
- setContent {
- CloudStreamTheme {
- MainActivityScreen.Content()
- }
- }
- }
}
// overscan
@@ -1438,9 +1428,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)
}
}
}
@@ -1989,7 +1978,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
handleAppIntent(intent)
ioSafe {
- runAutoUpdate() // TODO remove this when we update the updater autosearch
+ runAutoUpdate()
}
FcastManager().init(this, false)
@@ -2027,7 +2016,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
try {
- if (getKey(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 28553b320..000000000
--- a/app/src/main/java/com/lagradost/cloudstream3/MainActivityScreen.kt
+++ /dev/null
@@ -1,250 +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.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.ui.settings.APK_CONTENT_TYPE
-import com.lagradost.cloudstream3.ui.settings.APK_PRERELEASE
-import com.lagradost.cloudstream3.ui.settings.APK_REPOSITORY
-import com.lagradost.cloudstream3.ui.settings.APK_USERNAME
-import com.lagradost.cloudstream3.ui.settings.ApkUpdater
-import com.lagradost.cloudstream3.ui.settings.GithubAction
-import com.lagradost.cloudstream3.ui.settings.GithubAction.AutoSearchForUpdate
-import com.lagradost.cloudstream3.ui.settings.GithubAction.Dismiss
-import com.lagradost.cloudstream3.ui.settings.GithubAction.SearchForUpdate
-import com.lagradost.cloudstream3.ui.settings.GithubAction.SkipUpdate
-import com.lagradost.cloudstream3.ui.settings.GithubAction.Update
-import com.lagradost.cloudstream3.ui.settings.GithubState
-import com.lagradost.cloudstream3.ui.settings.GithubUpdateDialogState
-import com.lagradost.cloudstream3.ui.settings.GithubViewModel
-import com.lagradost.cloudstream3.utils.GitInfo.currentCommitHash
-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.mihon.material.padding
-
-object MainActivityScreen : Screen {
- @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
- )/*.apply {
- onAction(AutoSearchForUpdate) // Remove this for now
- }*/
- }
- }
-
- @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) {
- if (updaterState.dialog == null) {
- return
- }
-
- val title: String
- val body: @Composable () -> Unit
- val confirmButton: @Composable () -> Unit
- val dismissButton: @Composable () -> Unit
- val cancelable: Boolean
-
- when (val state = updaterState.dialog.state) {
- is GithubUpdateDialogState.Error -> {
- // Only show error if it is initialized by the user
- if (!updaterState.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 (!updaterState.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 (!updaterState.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 = state.file.changeLog) }
- 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 = {
- if (state.total != null) {
- val progress =
- (state.progress.toFloat() / state.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,
- state.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..f4e8768d8 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
@@ -98,7 +98,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 {
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/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/PluginManager.kt b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
index 6054bbfaf..de41cbc74 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
@@ -176,11 +176,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 =
@@ -512,9 +512,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
}
}
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 3879ddca4..523798b6e 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
@@ -98,7 +98,7 @@ data class PluginWrapper(
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 +141,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
@@ -240,7 +234,7 @@ 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
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/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..60e41e8b3 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
@@ -6,12 +6,13 @@ 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.syncproviders.AccountManager.Companion.APP_STRING
+import com.lagradost.cloudstream3.utils.AppContextUtils.splitQuery
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonNames
+import java.net.URI
import java.security.SecureRandom
data class AuthLoginPage(
@@ -171,8 +172,10 @@ abstract class AuthAPI {
get() = unixTimeMS
fun splitRedirectUrl(redirectUrl: String): Map {
- return splitUrlParameters(
- redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
+ return splitQuery(
+ URI(
+ redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
+ ).toURL()
)
}
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..0b8c3e5ae 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
@@ -2,6 +2,7 @@ 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
@@ -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(
@@ -66,7 +66,7 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
var found: List? = null
for (item in searchCache) {
// 120 min save
- if (item.idPrefix == idPrefix && item.query == query && (unixTime - item.unixTime) < 60 * 120) {
+ if (item.query == query && (unixTime - item.unixTime) < 60 * 120) {
found = item.response
break
}
@@ -79,7 +79,7 @@ class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
// only cache valid return values
if (returnValue.isNotEmpty()) {
- val add = SavedSearchResponse(unixTime, returnValue, query, idPrefix)
+ val add = SavedSearchResponse(unixTime, returnValue, query)
searchCache.withLock {
if (searchCache.size > CACHE_SIZE) {
searchCache[searchCacheIndex] = add // rolling cache
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..441eb1bf2 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
@@ -27,10 +27,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
@@ -55,7 +54,7 @@ class AniListApi : SyncAPI() {
val token = AuthToken(
accessToken = sanitizer["access_token"]
?: throw ErrorLoadingException("No access token"),
- // refreshToken = sanitizer["refresh_token"],
+ //refreshToken = sanitizer["refresh_token"],
accessTokenLifetime = APIHolder.unixTime + sanitizer["expires_in"]!!.toLong(),
)
return token
@@ -82,6 +81,7 @@ class AniListApi : SyncAPI() {
override fun urlToId(url: String): String? =
url.removePrefix("$mainUrl/anime/").removeSuffix("/")
+
private fun getUrlFromId(id: Int): String {
return "$mainUrl/anime/$id"
}
@@ -103,6 +103,7 @@ class AniListApi : SyncAPI() {
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 {
@@ -156,13 +157,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? {
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 +260,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 +300,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,7 +458,7 @@ class AniListApi : SyncAPI() {
cacheTime = 0,
).text
- return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
+ return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
}
}
@@ -504,6 +506,7 @@ class AniListApi : SyncAPI() {
type = AniListStatusType.None,
)
}
+
}
private suspend fun postApi(token: AuthToken, q: String, cache: Boolean = false): String? {
@@ -519,84 +522,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 +613,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? {
@@ -685,6 +672,7 @@ class AniListApi : SyncAPI() {
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,44 +711,33 @@ class AniListApi : SyncAPI() {
}
}
}
- }
+ }
"""
val text = postApi(auth.token, query)
- return tryParseJson(text)
+ return text?.toKotlinObject()
}
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,
@@ -770,6 +747,7 @@ class AniListApi : SyncAPI() {
progress: Int?
): Boolean {
val userID = auth.user.id
+
val q =
// Delete item if status type is None
if (type == AniListStatusType.None) {
@@ -813,22 +791,22 @@ class AniListApi : SyncAPI() {
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 +839,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/SimklApi.kt b/app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/SimklApi.kt
index a57ec6716..075c08bb8 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,11 @@ 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
@@ -32,12 +32,7 @@ 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 +45,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 +69,63 @@ 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 = APIHolder.unixTime,
+ ) {
+ /** Returns true if cache is newer than cacheDays */
+ fun isFresh(): Boolean {
+ return validUntil > APIHolder.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 = APIHolder.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, APIHolder.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? {
val cache = getKey(SIMKL_CACHE_KEY, path)?.let {
- tryParseJson(it)
+ tryParseJson>(it)
}
- 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 +169,7 @@ class SimklApi : SyncAPI() {
)
)
)
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -222,7 +185,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 +204,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 +300,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 +341,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 +369,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 +383,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 +396,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,12 +407,12 @@ 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))
}
@@ -484,17 +424,19 @@ class SimklApi : SyncAPI() {
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 +446,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 +490,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 +534,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 +548,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(APIHolder.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(APIHolder.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 +607,10 @@ class SimklApi : SyncAPI() {
return
}
}
-
this.add(newItem)
}
+ //
fun merge(
first: List?,
second: List?
@@ -730,17 +644,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 +672,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 +705,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 +743,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 +771,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 +786,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 +799,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 +829,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 +852,7 @@ class SimklApi : SyncAPI() {
episodeConstructor = episodeConstructor,
oldEpisodes = 0,
oldStatus = null,
- oldScore = null,
+ oldScore = null
)
}
}
@@ -935,11 +860,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 = APIHolder.unixTime
val simklStatus = newStatus as? SimklSyncStatus
+
val builder = SimklScoreBuilder.Builder()
.apiUrl(this.mainUrl)
.score(newStatus.score?.toInt(10), simklStatus?.oldScore)
@@ -953,6 +879,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,19 +892,22 @@ 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? {
@@ -988,10 +918,12 @@ class SimklApi : SyncAPI() {
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 +938,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 +957,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 +980,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 +1037,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 +1053,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 +1069,7 @@ class SimklApi : SyncAPI() {
val tokenResponse = app.post(
"$mainUrl/oauth/token", json = TokenRequest(code)
).parsedSafe() ?: return null
+
return AuthToken(
accessToken = tokenResponse.accessToken,
)
@@ -1135,7 +1080,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..fb463ebee 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,11 @@ 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 +20,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 +99,79 @@ 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") @SerialName("success") val success: Boolean,
+ @JsonProperty("found") @SerialName("found") val found: List,
)
@Serializable
- data class Users(
-
- @JsonProperty("id") @SerialName("id") var id: Int? = null,
- @JsonProperty("displayname") @SerialName("displayname") var displayname: String? = null,
- @JsonProperty("avatar") @SerialName("avatar") var avatar: String? = null,
- @JsonProperty("badges") @SerialName("badges") var badges: ArrayList = arrayListOf()
-
+ data class Found(
+ @JsonProperty("id") @SerialName("id") val id: Long,
+ @JsonProperty("title") @SerialName("title") val title: String,
+ @JsonProperty("seasons") @SerialName("seasons") val seasons: Long,
+ @JsonProperty("type") @SerialName("type") val type: String,
+ @JsonProperty("releaseYear") @SerialName("releaseYear") val releaseYear: Long,
+ @JsonProperty("linkName") @SerialName("linkName") val linkName: String,
)
@Serializable
- data class Results(
- @JsonProperty("id") @SerialName("id") var id: Int? = null,
- @JsonProperty("title") @SerialName("title") var title: String? = null,
- @JsonProperty("type") @SerialName("type") var type: String? = null,
- @JsonProperty("link") @SerialName("link") var link: String,
- @JsonProperty("releaseYear") @SerialName("releaseYear") var releaseYear: Int? = null,
- @JsonProperty("poster") @SerialName("poster") var poster: String? = null,
- @JsonProperty("subtitleCount") @SerialName("subtitleCount") var subtitleCount: String? = null,
- @JsonProperty("rating") @SerialName("rating") var rating: Double? = null,
- @JsonProperty("cast") @SerialName("cast") var cast: ArrayList = arrayListOf(),
- @JsonProperty("genres") @SerialName("genres") var genres: ArrayList = arrayListOf(),
- @JsonProperty("score") @SerialName("score") var score: Double? = null
+ data class ApiResponse(
+ @JsonProperty("success") @SerialName("success") val success: Boolean,
+ @JsonProperty("movie") @SerialName("movie") val movie: Movie,
+ @JsonProperty("subs") @SerialName("subs") val subs: List,
)
@Serializable
-
- data class ItemRoot(
-
- // @SerialName("media_type" ) var mediaType : String? = null,
- @JsonProperty("subtitles") @SerialName("subtitles") var subtitles: ArrayList,
- //@SerialName("movie" ) var movie : Movie? = Movie()
-
+ data class Movie(
+ @JsonProperty("id") @SerialName("id") val id: Long? = null,
+ @JsonProperty("type") @SerialName("type") val type: String? = null,
+ @JsonProperty("year") @SerialName("year") val year: Long? = null,
+ @JsonProperty("fullName") @SerialName("fullName") val fullName: String? = null,
)
@Serializable
- data class Subtitles(
-
- @JsonProperty("id") @SerialName("id") var id: Int? = null,
- @JsonProperty("language") @SerialName("language") var language: String,
- @JsonProperty("release_type") @SerialName("release_type") var releaseType: String? = null,
- @JsonProperty("release_info") @SerialName("release_info") var releaseInfo: String,
- @JsonProperty("upload_date") @SerialName("upload_date") var uploadDate: String? = null,
- @JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Int? = null,
- @JsonProperty("caption") @SerialName("caption") var caption: String? = null,
- @JsonProperty("rating") @SerialName("rating") var rating: String? = null,
- @JsonProperty("uploader_id") @SerialName("uploader_id") var uploaderId: Int? = null,
- @JsonProperty("uploader_displayname") @SerialName("uploader_displayname") var uploaderDisplayname: String? = null,
- @JsonProperty("uploader_badges") @SerialName("uploader_badges") var uploaderBadges: ArrayList = arrayListOf(),
- @JsonProperty("link") @SerialName("link") var link: String,
- @JsonProperty("production_type") @SerialName("production_type") var productionType: String? = null,
- @JsonProperty("last_subtitle") @SerialName("last_subtitle") var lastSubtitle: Boolean? = null
-
+ data class Sub(
+ @JsonProperty("hi") @SerialName("hi") val hi: Int? = null,
+ @JsonProperty("fullLink") @SerialName("fullLink") val fullLink: String? = null,
+ @JsonProperty("linkName") @SerialName("linkName") val linkName: String? = null,
+ @JsonProperty("lang") @SerialName("lang") val lang: String? = null,
+ @JsonProperty("releaseName") @SerialName("releaseName") val releaseName: String? = null,
+ @JsonProperty("subId") @SerialName("subId") val subId: Long? = null,
)
@Serializable
- data class DownloadRoot(
- @JsonProperty("subtitle") @SerialName("subtitle") var subtitle: Subtitle,
- //@SerializedName("movie" ) var movie : Movie? = Movie(),
- //@SerializedName("donationLinks" ) var donationLinks : DonationLinks? = DonationLinks(),
- //@SerializedName("isDownloaded" ) var isDownloaded : Boolean? = null,
- //@SerializedName("user_rated" ) var userRated : String? = null
+ data class SubData(
+ @JsonProperty("movie") @SerialName("movie") val movie: String,
+ @JsonProperty("lang") @SerialName("lang") val lang: String,
+ @JsonProperty("id") @SerialName("id") val id: String,
)
@Serializable
- data class Subtitle(
-
- @JsonProperty("id") @SerialName("id") var id: Int? = null,
- @JsonProperty("uploaded_at") @SerialName("uploaded_at") var uploadedAt: String? = null,
- @JsonProperty("language") @SerialName("language") var language: String? = null,
- @JsonProperty("rating") @SerialName("rating") var rating: String? = null,
- //SerialName("rates" ) var rates : Rates? = Rates(),
- @JsonProperty("uploaded_by") @SerialName("uploaded_by") var uploadedBy: Int? = null,
- //@SerialName("contribs" ) var contribs : ArrayList = arrayListOf(),
- @JsonProperty("release_info") @SerialName("release_info") var releaseInfo: ArrayList = arrayListOf(),
- @JsonProperty("commentary") @SerialName("commentary") var commentary: String? = null,
- @JsonProperty("files") @SerialName("files") var files: String? = null,
- @JsonProperty("size") @SerialName("size") var size: String? = null,
- @JsonProperty("downloads") @SerialName("downloads") var downloads: Int? = null,
- @JsonProperty("comments") @SerialName("comments") var comments: Int? = null,
- @JsonProperty("production_type") @SerialName("production_type") var productionType: String? = null,
- @JsonProperty("release_type") @SerialName("release_type") var releaseType: String? = null,
- @JsonProperty("episode") @SerialName("episode") var episode: String? = null,
- @JsonProperty("hearing_impaired") @SerialName("hearing_impaired") var hearingImpaired: Int? = null,
- @JsonProperty("foreign_parts") @SerialName("foreign_parts") var foreignParts: String? = null,
- @JsonProperty("framerate") @SerialName("framerate") var framerate: String? = null,
- @JsonProperty("preview") @SerialName("preview") var preview: String? = null,
- @JsonProperty("user_uploaded") @SerialName("user_uploaded") var userUploaded: Boolean? = null,
- @JsonProperty("download_token") @SerialName("download_token") var downloadToken: String
+ data class SubTitleLink(
+ @JsonProperty("sub") @SerialName("sub") val sub: SubToken,
+ )
+ @Serializable
+ data class SubToken(
+ @JsonProperty("downloadToken") @SerialName("downloadToken") val downloadToken: String,
)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/ControllerActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/ControllerActivity.kt
index f00fd8031..2aadfb13c 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/ControllerActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/ControllerActivity.kt
@@ -12,7 +12,6 @@ import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import androidx.appcompat.app.AlertDialog
-import com.fasterxml.jackson.annotation.JsonProperty
import com.google.android.gms.cast.MediaLoadOptions
import com.google.android.gms.cast.MediaQueueItem
import com.google.android.gms.cast.MediaSeekOptions
@@ -35,24 +34,35 @@ import com.lagradost.cloudstream3.ui.player.SubtitleData
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
-import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.CastHelper.awaitLinks
import com.lagradost.cloudstream3.utils.CastHelper.getMediaInfo
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
+import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.Qualities
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import org.json.JSONObject
+/*class SkipOpController(val view: ImageView) : UIController() {
+ init {
+ view.setImageResource(R.drawable.exo_controls_fastforward)
+ view.setOnClickListener {
+ remoteMediaClient?.let {
+ val options = MediaSeekOptions.Builder()
+ .setPosition(it.approximateStreamPosition + 85000)
+ it.seek(options.build())
+ }
+ }
+ }
+}*/
+
private fun RemoteMediaClient.getItemIndex(): Int? {
return try {
val index = this.mediaQueue.itemIds.indexOf(this.currentItem?.itemId ?: 0)
if (index < 0) null else index
- } catch (_: Exception) {
+ } catch (e: Exception) {
null
}
}
@@ -79,41 +89,48 @@ class SkipNextEpisodeController(val view: ImageView) : UIController() {
}
}
-@Serializable
data class MetadataHolder(
- @JsonProperty("apiName") @SerialName("apiName") val apiName: String,
- @JsonProperty("isMovie") @SerialName("isMovie") val isMovie: Boolean,
- @JsonProperty("title") @SerialName("title") val title: String?,
- @JsonProperty("poster") @SerialName("poster") val poster: String?,
- @JsonProperty("currentEpisodeIndex") @SerialName("currentEpisodeIndex") val currentEpisodeIndex: Int,
- @JsonProperty("episodes") @SerialName("episodes") val episodes: List,
- @JsonProperty("currentLinks") @SerialName("currentLinks") val currentLinks: List,
- @JsonProperty("currentSubtitles") @SerialName("currentSubtitles") val currentSubtitles: List,
+ val apiName: String,
+ val isMovie: Boolean,
+ val title: String?,
+ val poster: String?,
+ val currentEpisodeIndex: Int,
+ val episodes: List,
+ val currentLinks: List,
+ val currentSubtitles: List
)
-class SelectSourceController(val view: ImageView, val activity: ControllerActivity) : UIController() {
+class SelectSourceController(val view: ImageView, val activity: ControllerActivity) :
+ UIController() {
init {
view.setImageResource(R.drawable.ic_baseline_playlist_play_24)
view.setOnClickListener {
+ // lateinit var dialog: AlertDialog
val holder = getCurrentMetaData()
+
if (holder != null) {
val items = holder.currentLinks
if (items.isNotEmpty() && remoteMediaClient?.currentItem != null) {
- val subTracks = remoteMediaClient?.mediaInfo?.mediaTracks?.filter { it.type == MediaTrack.TYPE_TEXT }
- ?: ArrayList()
+ val subTracks =
+ remoteMediaClient?.mediaInfo?.mediaTracks?.filter { it.type == MediaTrack.TYPE_TEXT }
+ ?: ArrayList()
- val bottomSheetDialogBuilder = AlertDialog.Builder(view.context, R.style.AlertDialogCustomBlack)
+ val bottomSheetDialogBuilder =
+ AlertDialog.Builder(view.context, R.style.AlertDialogCustomBlack)
bottomSheetDialogBuilder.setView(R.layout.sort_bottom_sheet)
-
val bottomSheetDialog = bottomSheetDialogBuilder.create()
bottomSheetDialog.show()
-
- val providerList = bottomSheetDialog.findViewById(R.id.sort_providers)!!
- val subtitleList = bottomSheetDialog.findViewById(R.id.sort_subtitles)!!
+ // bottomSheetDialog.setContentView(R.layout.sort_bottom_sheet)
+ val providerList =
+ bottomSheetDialog.findViewById(R.id.sort_providers)!!
+ val subtitleList =
+ bottomSheetDialog.findViewById(R.id.sort_subtitles)!!
if (subTracks.isEmpty()) {
- bottomSheetDialog.findViewById(R.id.sort_subtitles_holder)?.visibility = GONE
+ bottomSheetDialog.findViewById(R.id.sort_subtitles_holder)?.visibility =
+ GONE
} else {
- val arrayAdapter = ArrayAdapter(view.context, R.layout.sort_bottom_single_choice)
+ val arrayAdapter =
+ ArrayAdapter(view.context, R.layout.sort_bottom_single_choice)
arrayAdapter.add(view.context.getString(R.string.no_subtitles))
arrayAdapter.addAll(subTracks.mapNotNull { it.name })
@@ -121,8 +138,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
subtitleList.adapter = arrayAdapter
val currentTracks = remoteMediaClient?.mediaStatus?.activeTrackIds
- val subtitleIndex = if (currentTracks == null) 0 else subTracks.map { it.id }
- .indexOfFirst { currentTracks.contains(it) } + 1
+
+ val subtitleIndex =
+ if (currentTracks == null) 0 else subTracks.map { it.id }
+ .indexOfFirst { currentTracks.contains(it) } + 1
subtitleList.setSelection(subtitleIndex)
subtitleList.setItemChecked(subtitleIndex, true)
@@ -134,7 +153,9 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
ChromecastSubtitlesFragment.getCurrentSavedStyle().apply {
val font = TextTrackStyle()
font.setFontFamily(fontFamily ?: "Google Sans")
- fontGenericFamily?.let { font.fontGenericFamily = it }
+ fontGenericFamily?.let {
+ font.fontGenericFamily = it
+ }
font.windowColor = windowColor
font.backgroundColor = backgroundColor
@@ -151,7 +172,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
if (!it.status.isSuccess) {
Log.e(
"CHROMECAST", "Failed with status code:" +
- it.status.statusCode + " > " + it.status.statusMessage
+ it.status.statusCode + " > " + it.status.statusMessage
)
}
}
@@ -160,15 +181,17 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
}
}
- // https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.MediaInformation
+ //https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.MediaInformation
val contentUrl = (remoteMediaClient?.currentItem?.media?.contentUrl
?: remoteMediaClient?.currentItem?.media?.contentId)
- val sortingMethods = items.map { "${it.name} ${Qualities.getStringByInt(it.quality)}" }
- .toTypedArray()
+ val sortingMethods =
+ items.map { "${it.name} ${Qualities.getStringByInt(it.quality)}" }
+ .toTypedArray()
val sotringIndex = items.indexOfFirst { it.url == contentUrl }
- val arrayAdapter = ArrayAdapter(view.context, R.layout.sort_bottom_single_choice)
+ val arrayAdapter =
+ ArrayAdapter(view.context, R.layout.sort_bottom_single_choice)
arrayAdapter.addAll(sortingMethods.toMutableList())
providerList.choiceMode = AbsListView.CHOICE_MODE_SINGLE
@@ -178,8 +201,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
providerList.setOnItemClickListener { _, _, which, _ ->
val epData = holder.episodes[holder.currentEpisodeIndex]
+
fun loadMirror(index: Int) {
if (holder.currentLinks.size <= index) return
+
val mediaItem = getMediaInfo(
epData,
holder,
@@ -189,21 +214,25 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
)
val startAt = remoteMediaClient?.approximateStreamPosition ?: 0
+
+ //remoteMediaClient.load(mediaItem, true, startAt)
try { // THIS IS VERY IMPORTANT BECAUSE WE NEVER WANT TO AUTOLOAD THE NEXT EPISODE
val currentIdIndex = remoteMediaClient?.getItemIndex()
+
val nextId = remoteMediaClient?.mediaQueue?.itemIds?.get(
currentIdIndex?.plus(1) ?: 0
)
-
if (currentIdIndex == null && nextId != null) {
awaitLinks(
remoteMediaClient?.queueInsertAndPlayItem(
MediaQueueItem.Builder(mediaItem).build(),
nextId,
startAt,
- JSONObject(),
+ JSONObject()
)
- ) { loadMirror(index + 1) }
+ ) {
+ loadMirror(index + 1)
+ }
} else {
val mediaLoadOptions =
MediaLoadOptions.Builder()
@@ -215,9 +244,11 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
mediaItem,
mediaLoadOptions
)
- ) { loadMirror(index + 1) }
+ ) {
+ loadMirror(index + 1)
+ }
}
- } catch (_: Exception) {
+ } catch (e: Exception) {
val mediaLoadOptions =
MediaLoadOptions.Builder()
.setPlayPosition(startAt)
@@ -228,8 +259,8 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
}
}
}
-
loadMirror(which)
+
bottomSheetDialog.dismissSafe(activity)
}
}
@@ -239,19 +270,23 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
private fun getCurrentMetaData(): MetadataHolder? {
return try {
- val data = remoteMediaClient?.mediaInfo?.customData?.toString() ?: return null
- parseJson(data)
- } catch (_: Exception) {
+ val data = remoteMediaClient?.mediaInfo?.customData?.toString()
+ data?.toKotlinObject()
+ } catch (e: Exception) {
null
}
}
var isLoadingMore = false
+
+
override fun onMediaStatusUpdated() {
super.onMediaStatusUpdated()
val meta = getCurrentMetaData()
- view.visibility = if ((meta?.currentLinks?.size ?: 0) > 1) VISIBLE else INVISIBLE
+ view.visibility = if ((meta?.currentLinks?.size
+ ?: 0) > 1
+ ) VISIBLE else INVISIBLE
try {
if (meta != null && meta.episodes.size > meta.currentEpisodeIndex + 1) {
val currentIdIndex = remoteMediaClient?.getItemIndex() ?: return
@@ -268,7 +303,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
currentPosition,
currentDuration,
epData,
- meta.episodes.getOrNull(index + 1),
+ meta.episodes.getOrNull(index + 1)
)
} catch (t: Throwable) {
logError(t)
@@ -279,7 +314,9 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
ioSafe {
val currentLinks = mutableSetOf()
val currentSubs = mutableSetOf()
+
val generator = RepoLinkGenerator(listOf(epData))
+
val isSuccessful = safeApiCall {
generator.generateLinks(
clearCache = false,
@@ -292,7 +329,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
currentSubs.add(it)
},
offset = 0,
- isCasting = true,
+ isCasting = true
)
}
@@ -303,18 +340,32 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
val jsonCopy = meta.copy(
currentLinks = sortedLinks,
currentSubtitles = sortedSubs,
- currentEpisodeIndex = index,
+ currentEpisodeIndex = index
)
- val done = JSONObject(jsonCopy.toJson())
+ val done =
+ JSONObject(jsonCopy.toJson())
+
val mediaInfo = getMediaInfo(
epData,
jsonCopy,
0,
done,
- sortedSubs,
+ sortedSubs
)
+ /*fun loadIndex(index: Int) {
+ println("LOAD INDEX::::: $index")
+ if (meta.currentLinks.size <= index) return
+ val info = getMediaInfo(
+ epData,
+ meta,
+ index,
+ done)
+ awaitLinks(remoteMediaClient?.load(info, true, 0)) {
+ loadIndex(index + 1)
+ }
+ }*/
activity.runOnUiThread {
awaitLinks(
remoteMediaClient?.queueAppendItem(
@@ -323,6 +374,7 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
)
) {
println("FAILED TO LOAD NEXT ITEM")
+ // loadIndex(1)
}
isLoadingMore = false
}
@@ -345,7 +397,10 @@ class SelectSourceController(val view: ImageView, val activity: ControllerActivi
class SkipTimeController(val view: ImageView, forwards: Boolean) : UIController() {
init {
+ //val settingsManager = PreferenceManager.getDefaultSharedPreferences()
+ //val time = settingsManager?.getInt("chromecast_tap_time", 30) ?: 30
val time = 30
+ //view.setImageResource(if (forwards) R.drawable.netflix_skip_forward else R.drawable.netflix_skip_back)
view.setImageResource(if (forwards) R.drawable.go_forward_30 else R.drawable.go_back_30)
view.setOnClickListener {
remoteMediaClient?.let {
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountAdapter.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountAdapter.kt
index f70458285..92d33d0f3 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountAdapter.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountAdapter.kt
@@ -1,8 +1,11 @@
package com.lagradost.cloudstream3.ui.account
+import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
+import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
+import coil3.transform.RoundedCornersTransformation
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.databinding.AccountListItemAddBinding
import com.lagradost.cloudstream3.databinding.AccountListItemBinding
@@ -15,8 +18,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
-import android.util.TypedValue
-import android.view.View
class AccountAdapter(
private val accountSelectCallback: (DataStoreHelper.Account) -> Unit,
@@ -28,12 +29,6 @@ class AccountAdapter(
companion object {
const val VIEW_TYPE_SELECT_ACCOUNT = 0
const val VIEW_TYPE_EDIT_ACCOUNT = 2
-
- fun View.setRippleForeground() {
- val outValue = TypedValue()
- context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true)
- foreground = context.getDrawable(outValue.resourceId)
- }
}
@@ -52,25 +47,45 @@ class AccountAdapter(
when (val binding = holder.view) {
is AccountListItemBinding -> binding.apply {
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
+
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
accountName.text = item.name
accountImage.loadImage(item.image)
lockIcon.isVisible = item.lockPin != null
- root.isSelected = isLastUsedAccount
- cardView.isSelected = isLastUsedAccount
+ outline.isVisible = !isTv && isLastUsedAccount
- if (!isTv) cardView.setRippleForeground()
+ if (isTv) {
+ // For emulator but this is fine on TV also
+ root.isFocusableInTouchMode = true
+ if (isLastUsedAccount) {
+ root.requestFocus()
+ }
- if (!isTv) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ root.foreground = ContextCompat.getDrawable(
+ root.context,
+ R.drawable.outline_drawable
+ )
+ }
+ } else {
root.setOnLongClickListener {
showAccountEditDialog(
context = root.context,
account = item,
isNewAccount = false,
- accountEditCallback = { account -> accountEditCallback.invoke(account) },
- accountDeleteCallback = { account -> accountDeleteCallback.invoke(account) }
+ accountEditCallback = { account ->
+ accountEditCallback.invoke(
+ account
+ )
+ },
+ accountDeleteCallback = { account ->
+ accountDeleteCallback.invoke(
+ account
+ )
+ }
)
+
true
}
}
@@ -82,15 +97,30 @@ class AccountAdapter(
is AccountListItemEditBinding -> binding.apply {
val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
+
val isLastUsedAccount = item.keyIndex == DataStoreHelper.selectedKeyIndex
accountName.text = item.name
- accountImage.loadImage(item.image)
+ accountImage.loadImage(item.image) {
+ RoundedCornersTransformation(10f)
+ }
lockIcon.isVisible = item.lockPin != null
- root.isSelected = isLastUsedAccount
- cardView.isSelected = isLastUsedAccount
+ outline.isVisible = !isTv && isLastUsedAccount
- if (!isTv) cardView.setRippleForeground()
+ if (isTv) {
+ // For emulator but this is fine on TV also
+ root.isFocusableInTouchMode = true
+ if (isLastUsedAccount) {
+ root.requestFocus()
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ root.foreground = ContextCompat.getDrawable(
+ root.context,
+ R.drawable.outline_drawable
+ )
+ }
+ }
root.setOnClickListener {
showAccountEditDialog(
@@ -98,7 +128,11 @@ class AccountAdapter(
account = item,
isNewAccount = false,
accountEditCallback = { account -> accountEditCallback.invoke(account) },
- accountDeleteCallback = { account -> accountDeleteCallback.invoke(account) }
+ accountDeleteCallback = { account ->
+ accountDeleteCallback.invoke(
+ account
+ )
+ }
)
}
}
@@ -108,9 +142,6 @@ class AccountAdapter(
override fun onBindFooter(holder: ViewHolderState) {
val binding = holder.view as? AccountListItemAddBinding ?: return
binding.apply {
- val isTv = isLayout(TV or EMULATOR) || !root.isInTouchMode
- if (!isTv) cardView.setRippleForeground()
-
root.setOnClickListener {
val accounts = this@AccountAdapter.immutableCurrentList
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountHelper.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountHelper.kt
index c88f70a73..1d6b41e5b 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountHelper.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountHelper.kt
@@ -37,14 +37,8 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.getDefaultAccount
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
-import com.lagradost.cloudstream3.utils.UIHelper.hideProgress
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
-import com.lagradost.cloudstream3.utils.UIHelper.showProgress
-import com.lagradost.cloudstream3.ui.account.AccountAdapter.Companion.setRippleForeground
-import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
-import com.lagradost.cloudstream3.ui.settings.Globals.TV
-import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
object AccountHelper {
fun showAccountEditDialog(
@@ -60,12 +54,6 @@ object AccountHelper {
var currentEditAccount = account
val dialog = builder.show()
- binding.accountImageHolder.requestFocus()
-
- if (!isLayout(TV or EMULATOR)) {
- binding.accountImageHolder.setRippleForeground()
- binding.editProfilePhotoButtonHolder.setRippleForeground()
- }
if (!isNewAccount) binding.title.setText(R.string.edit_account)
@@ -110,7 +98,7 @@ object AccountHelper {
// Handle the profile picture and its interactions
binding.accountImage.loadImage(account.image)
- binding.accountImageHolder.setOnClickListener {
+ binding.accountImage.setOnClickListener {
// Roll the image forwards once
currentEditAccount = currentEditAccount.copy(customImage = null)
currentEditAccount =
@@ -176,57 +164,52 @@ object AccountHelper {
canSetPin = true
- binding.editProfilePhotoButtonHolder.setOnClickListener {
- val builder = AlertDialog.Builder(context, R.style.AlertDialogCustom)
+ binding.editProfilePhotoButton.setOnClickListener({
+ val bottomSheetDialog = BottomSheetDialog(context)
val sheetBinding = BottomInputDialogBinding.inflate(LayoutInflater.from(context))
- builder.setView(sheetBinding.root)
- val dialog = builder.create()
- dialog.show()
+ bottomSheetDialog.setContentView(sheetBinding.root)
+ bottomSheetDialog.show()
sheetBinding.apply {
text1.text = context.getString(R.string.edit_profile_image_title)
nginxTextInput.hint = context.getString(R.string.edit_profile_image_hint)
- applyBtt.setOnClickListener {
+ applyBtt.setOnClickListener({
val url = sheetBinding.nginxTextInput.text.toString()
- if (url.isEmpty()) {
+ if (url.isNotEmpty()) {
+ val imageLoader = ImageLoader(context)
+ val request = ImageRequest.Builder(context)
+ .data(url)
+ .allowHardware(false)
+ .listener(
+ onSuccess = { _, _ ->
+ currentEditAccount = currentEditAccount.copy(customImage = url)
+ binding.accountImage.loadImage(url)
+ showToast(
+ R.string.edit_profile_image_success,
+ Toast.LENGTH_SHORT
+ )
+ bottomSheetDialog.dismiss()
+ },
+ onError = { _, _ ->
+ showToast(
+ R.string.edit_profile_image_error_invalid,
+ Toast.LENGTH_SHORT
+ )
+ }
+ )
+ .build()
+ imageLoader.enqueue(request)
+ } else {
showToast(R.string.edit_profile_image_error_empty, Toast.LENGTH_SHORT)
- return@setOnClickListener
}
- applyBtt.showProgress()
- val imageLoader = ImageLoader(context)
- val request = ImageRequest.Builder(context)
- .data(url)
- .allowHardware(false)
- .listener(
- onSuccess = { _, _ ->
- currentEditAccount = currentEditAccount.copy(customImage = url)
- binding.accountImage.loadImage(url)
- showToast(
- R.string.edit_profile_image_success,
- Toast.LENGTH_SHORT
- )
- dialog.dismissSafe()
- },
- onError = { _, _ ->
- showToast(
- R.string.edit_profile_image_error_invalid,
- Toast.LENGTH_SHORT
- )
- applyBtt.hideProgress()
- },
- onCancel = {
- applyBtt.hideProgress()
- }
- )
- .build()
- imageLoader.enqueue(request)
- }
- sheetBinding.cancelBtt.setOnClickListener {
- dialog.dismissSafe()
- }
+ bottomSheetDialog.dismissSafe()
+ })
+ sheetBinding.cancelBtt.setOnClickListener({
+ bottomSheetDialog.dismissSafe()
+ })
}
- }
+ })
}
fun showPinInputDialog(
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectActivity.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectActivity.kt
index 28f5c15d8..ad323c7d1 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectActivity.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectActivity.kt
@@ -54,15 +54,10 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
false
)
- val isFromMainActivity = intent.getBooleanExtra(
- "isFromMainActivity",
- false
- )
-
// Sometimes we start this activity when we have already logged in
// For example when using cloudstreamsearch://
// In those cases we want to just go to the main activity instantly
- if (hasLoggedIn && !isEditingFromMainActivity && !isFromMainActivity) {
+ if (hasLoggedIn && !isEditingFromMainActivity) {
navigateToMainActivity()
return
}
@@ -103,7 +98,7 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
// Don't show account selection if there is only
// one account that exists
- if (!isFromMainActivity && !isEditingFromMainActivity && skipStartup) {
+ if (!isEditingFromMainActivity && skipStartup) {
val currentAccount = accounts.firstOrNull { it.keyIndex == selectedKeyIndex }
if (currentAccount?.lockPin != null) {
CommonActivity.init(this)
@@ -165,11 +160,6 @@ class AccountSelectActivity : FragmentActivity(), BiometricCallback {
// Scroll to current account (which is focused by default)
val layoutManager = recyclerView.layoutManager as GridLayoutManager
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
- if (isLayout(TV or EMULATOR)) {
- recyclerView.post {
- layoutManager.findViewByPosition(selectedKeyIndex)?.requestFocus()
- }
- }
}
observe(accountViewModel.isEditing) { isEditing ->
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectLinearItemDecoration.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectLinearItemDecoration.kt
index 91e0caa2a..eb907b344 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectLinearItemDecoration.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/account/AccountSelectLinearItemDecoration.kt
@@ -8,7 +8,7 @@ class AccountSelectLinearItemDecoration(private val size: Int) : RecyclerView.It
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val layoutParams = view.layoutParams as RecyclerView.LayoutParams
layoutParams.width = size
- layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT
+ layoutParams.height = size
view.layoutParams = layoutParams
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/download/DownloadViewModel.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/download/DownloadViewModel.kt
index 19c006b28..0d35d5670 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/download/DownloadViewModel.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/download/DownloadViewModel.kt
@@ -10,7 +10,6 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lagradost.api.Log
-import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.isEpisodeBased
import com.lagradost.cloudstream3.mvvm.Resource
@@ -37,7 +36,6 @@ import com.lagradost.cloudstream3.utils.ResourceLiveData
import com.lagradost.cloudstream3.utils.downloader.DownloadObjects
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.deleteFilesAndUpdateSettings
-import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.downloadDeleteEvent
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.getDownloadFileInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -69,17 +67,6 @@ class DownloadViewModel : ViewModel() {
private val _selectedItemIds = ConsistentLiveData?>(null)
val selectedItemIds: LiveData?> = _selectedItemIds
- init {
- // Keep the Downloads list in sync when a download is deleted/cancelled from
- // anywhere in the app (result page button, queue, notification, etc.). See
- // onDownloadDeleted for the rationale (issue #1227).
- downloadDeleteEvent += ::onDownloadDeleted
- }
-
- override fun onCleared() {
- downloadDeleteEvent -= ::onDownloadDeleted
- super.onCleared()
- }
fun cancelSelection() {
updateSelectedItems { null }
@@ -402,18 +389,6 @@ class DownloadViewModel : ViewModel() {
postChildren(_childCards.success?.filter { it.data.id !in idsToRemove })
}
- /**
- * Refreshes the Downloads screen in real time when a download is deleted/cancelled.
- */
- private fun onDownloadDeleted(id: Int) {
- // Keep multi-select state consistent: forget the removed id if it was selected.
- updateSelectedItems { it?.minus(id) }
-
- val context = CloudStreamApp.context ?: return
- updateHeaderList(context)
- postChildren(_childCards.success?.filterNot { it.data.id == id })
- }
-
private fun updateStorageStats(visual: List) {
try {
val stat = StatFs(Environment.getExternalStorageDirectory().path)
@@ -609,4 +584,4 @@ class DownloadViewModel : ViewModel() {
val names: List,
val parentName: String?
)
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/download/button/BaseFetchButton.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/download/button/BaseFetchButton.kt
index 450dc9a61..382a770cd 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/download/button/BaseFetchButton.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/download/button/BaseFetchButton.kt
@@ -164,11 +164,9 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
}
}
- fun downloadDeleteEvent(data: Int) {
- if (data == persistentId) {
- resetView()
- }
- }
+ /*fun downloadDeleteEvent(data: Int) {
+
+ }*/
/*fun downloadEvent(data: Pair) {
val (id, action) = data
@@ -187,7 +185,7 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
override fun onAttachedToWindow() {
VideoDownloadManager.downloadStatusEvent += ::downloadStatusEvent
- VideoDownloadManager.downloadDeleteEvent += ::downloadDeleteEvent
+ // VideoDownloadManager.downloadDeleteEvent += ::downloadDeleteEvent
// VideoDownloadManager.downloadEvent += ::downloadEvent
VideoDownloadManager.downloadProgressEvent += ::downloadProgressEvent
@@ -202,7 +200,7 @@ abstract class BaseFetchButton(context: Context, attributeSet: AttributeSet) :
override fun onDetachedFromWindow() {
VideoDownloadManager.downloadStatusEvent -= ::downloadStatusEvent
- VideoDownloadManager.downloadDeleteEvent -= ::downloadDeleteEvent
+ // VideoDownloadManager.downloadDeleteEvent -= ::downloadDeleteEvent
// VideoDownloadManager.downloadEvent -= ::downloadEvent
VideoDownloadManager.downloadProgressEvent -= ::downloadProgressEvent
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeFragment.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeFragment.kt
index 04f8b0b26..b68ef5962 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeFragment.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeFragment.kt
@@ -18,22 +18,17 @@ import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
-import androidx.core.view.doOnLayout
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
-import com.lagradost.cloudstream3.plugins.PluginManager
-import com.lagradost.cloudstream3.CloudStreamApp.Companion.getActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.chip.Chip
import com.lagradost.api.Log
-import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.APIHolder.apis
-import com.lagradost.cloudstream3.APIHolder.getApiFromNameNull
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.MainAPI
@@ -48,7 +43,6 @@ import com.lagradost.cloudstream3.mvvm.Resource
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.observe
import com.lagradost.cloudstream3.mvvm.observeNullable
-import com.lagradost.cloudstream3.plugins.Plugin
import com.lagradost.cloudstream3.ui.APIRepository.Companion.noneApi
import com.lagradost.cloudstream3.ui.APIRepository.Companion.randomApi
import com.lagradost.cloudstream3.ui.BaseFragment
@@ -69,7 +63,6 @@ import com.lagradost.cloudstream3.utils.AppContextUtils.getApiProviderLangSettin
import com.lagradost.cloudstream3.utils.AppContextUtils.isNetworkAvailable
import com.lagradost.cloudstream3.utils.AppContextUtils.isRecyclerScrollable
import com.lagradost.cloudstream3.utils.AppContextUtils.loadSearchResult
-import com.lagradost.cloudstream3.utils.AppContextUtils.openBrowser
import com.lagradost.cloudstream3.utils.AppContextUtils.ownHide
import com.lagradost.cloudstream3.utils.AppContextUtils.ownShow
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
@@ -113,14 +106,6 @@ class HomeFragment : BaseFragment(
val errorProfilePic = errorProfilePics.random()
- fun Context.getDisplayName(apiName: String?): String? {
- return when (apiName) {
- noneApi.name -> getString(R.string.none)
- randomApi.name -> getString(R.string.home_random)
- else -> apiName
- }
- }
-
//fun Activity.loadHomepageList(
// item: HomePageList,
// deleteCallback: (() -> Unit)? = null,
@@ -439,30 +424,11 @@ class HomeFragment : BaseFragment(
.inflate(R.layout.sort_bottom_single_provider_choice, parent, false)
val titleText = view.findViewById(R.id.text1)
val pinIcon = view.findViewById(R.id.pinicon)
- val settingsIcon = view.findViewById(R.id.action_settings)
-
val name = getItem(position)
titleText?.text = name
- val providerApi = currentValidApis[position]
val isPinned =
- pinnedphashset.contains(providerApi.name)
+ pinnedphashset.contains(currentValidApis[position].name)
pinIcon.visibility = if (isPinned) View.VISIBLE else View.GONE
-
- val pluginInstance = providerApi.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
- val isDownloadedPluginWithSettings = pluginInstance?.openSettings != null && !isLayout(TV)
-
- settingsIcon.visibility = if (isDownloadedPluginWithSettings) View.VISIBLE else View.GONE
- if (isDownloadedPluginWithSettings) {
- settingsIcon.setOnClickListener {
- try {
- val activityContext = it.context.getActivity() ?: it.context
- pluginInstance.openSettings?.invoke(activityContext)
- } catch (e: Throwable) {
- logError(e)
- }
- }
- }
-
return view
}
}
@@ -485,14 +451,7 @@ class HomeFragment : BaseFragment(
arrayAdapter.clear()
val sortedApis = validAPIs
.filter {
- val isPinned = pinnedphashset.contains(it.name)
-
- // Hide pinned NSFW when NSFW not selected. NSFW is distracting when not chosen.
- if (isPinned && !preSelectedTypes.contains(TvType.NSFW)) {
- if (it.supportedTypes.all { type -> type == TvType.NSFW }) return@filter false
- }
-
- it.hasMainPage && (isPinned || it.supportedTypes.any(
+ it.hasMainPage && (pinnedphashset.contains(it.name) || it.supportedTypes.any(
preSelectedTypes::contains
))
}
@@ -514,10 +473,8 @@ class HomeFragment : BaseFragment(
addAll(remainingApis)
}
- val names = currentValidApis.map {
- val displayName = getDisplayName(it.name)
- if (isMultiLang) "${getFlagFromIso(it.lang)?.plus(" ") ?: ""}$displayName" else displayName
- }
+ val names =
+ currentValidApis.map { if (isMultiLang) "${getFlagFromIso(it.lang)?.plus(" ") ?: ""}${it.name}" else it.name }
val index = currentValidApis.map { it.name }.indexOf(currentApiName)
listView?.setItemChecked(index, true)
arrayAdapter.addAll(names)
@@ -708,6 +665,7 @@ class HomeFragment : BaseFragment(
fromUI = true
)
showToast(R.string.action_reload, Toast.LENGTH_SHORT)
+ true
}
homePreviewSearchButton.setOnClickListener { _ ->
@@ -715,38 +673,6 @@ class HomeFragment : BaseFragment(
homeViewModel.queryTextSubmit("")
}
- homePreviewSettingsButton.setOnClickListener { view ->
- val apiName = homeViewModel.apiName.value
- val plugin = APIHolder.getApiFromNameNull(apiName)
- ?.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
- val openSettings = plugin?.openSettings
- if (openSettings != null) {
- try {
- val activityContext = view.context.getActivity() ?: view.context
- openSettings.invoke(activityContext)
- } catch (e: Throwable) {
- logError(e)
- }
- }
- }
-
- // Load value for toggling Tv layout real time clock. Hide by default at startup
- // set visibility first, to apply a scroll effect later
- context?.let {
- if (isLayout(TV)) {
- val settingsManager = PreferenceManager.getDefaultSharedPreferences(it)
- val toggleClock =
- settingsManager.getBoolean(
- getString(R.string.tv_layout_clock_key),
- false
- )
- binding.homeClock.isVisible = toggleClock
- } else {
- binding.homeClock.isVisible = false
- }
- }
-
-
homeMasterRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (isLayout(PHONE)) {
@@ -786,26 +712,12 @@ class HomeFragment : BaseFragment(
view.getLocationInWindow(rect)
scrollParent.isVisible = true
scrollParent.translationY = rect[1].toFloat() - 60.toPx
-
- // Move the TV layout real time clock out of the way too
- // We check if we have the correct layout and if the clock is enabled
- if(isLayout(TV) && binding.homeClock.isVisible) {
- val scrollParent = binding.homeClock
-
- val rect = IntArray(2)
- view.getLocationInWindow(rect)
- scrollParent.isVisible = true
- scrollParent.translationY = rect[1].toFloat() - 60.toPx
- }
}
}
super.onScrolled(recyclerView, dx, dy)
- updateTvRailFocus()
}
})
- homeMasterRecycler.doOnLayout { updateTvRailFocus() }
-
}
//Load value for toggling Random button. Hide at startup
@@ -822,10 +734,9 @@ class HomeFragment : BaseFragment(
observe(homeViewModel.apiName) { apiName ->
currentApiName = apiName
- val displayApiName = context?.getDisplayName(apiName) ?: apiName
binding.apply {
- homeApiFab.text = displayApiName
- homeChangeApi.text = displayApiName
+ homeApiFab.text = apiName
+ homeChangeApi.text = apiName
homePreviewReloadProvider.isGone = (apiName == noneApi.name)
homePreviewSearchButton.isGone = (apiName == noneApi.name)
}
@@ -833,12 +744,6 @@ class HomeFragment : BaseFragment(
observe(homeViewModel.page) { data ->
binding.apply {
- if (isLayout(TV or EMULATOR)) {
- val plugin = APIHolder.getApiFromNameNull(homeViewModel.apiName.value)
- ?.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin
- homePreviewSettingsButton.isGone = plugin?.openSettings == null
- }
-
when (data) {
is Resource.Success -> {
val d = data.value
@@ -854,7 +759,6 @@ class HomeFragment : BaseFragment(
homeLoadingError.isVisible = false
homeMasterRecycler.isVisible = true
homeLoadingShimmer.stopShimmer()
-
//home_loaded?.isVisible = true
if (toggleRandomButton) {
val distinct = d.values
@@ -875,16 +779,26 @@ class HomeFragment : BaseFragment(
homeRandomButtonTv.isGone = true
}
}
- //Open browser directly, without a menu.
+
is Resource.Failure -> {
homeLoadingShimmer.stopShimmer()
homeReloadConnectionerror.setOnClickListener(apiChangeClickListener)
- homeReloadConnectionOpenInBrowser.setOnClickListener {
- val currentApi = currentApiName?.let { getApiFromNameNull(it) }
- ?: homeViewModel.apiName.value?.let { getApiFromNameNull(it) }
- val mainUrl = currentApi?.mainUrl
- if (!mainUrl.isNullOrBlank()) {
- context?.openBrowser(mainUrl)
+ homeReloadConnectionOpenInBrowser.setOnClickListener { view ->
+ val validAPIs = apis//.filter { api -> api.hasMainPage }
+
+ view.popupMenuNoIconsAndNoStringRes(validAPIs.mapIndexed { index, api ->
+ Pair(
+ index,
+ api.name
+ )
+ }) {
+ try {
+ val i = Intent(Intent.ACTION_VIEW)
+ i.data = validAPIs[itemId].mainUrl.toUri()
+ startActivity(i)
+ } catch (e: Exception) {
+ logError(e)
+ }
}
}
@@ -979,29 +893,6 @@ class HomeFragment : BaseFragment(
}*/
}
- private fun updateTvRailFocus() {
- if (!isLayout(TV or EMULATOR)) return
- // home_api_holder is glued to the header row's top by the mirror logic in
- // the scroll listener above. Only target the provider button while the
- // holder is actually on screen; once the header scrolls off (y < 0) let
- // the rail fall back to default focus search so RIGHT enters content rows
- val holder = binding?.homeApiHolder
- val target =
- if (holder != null && holder.isVisible && holder.y >= 0f) R.id.home_change_api
- else View.NO_ID
- val rail = activity?.findViewById(R.id.nav_rail_view) ?: return
- rail.nextFocusRightId = target
- for (focusView in arrayOf(
- R.id.navigation_downloads,
- R.id.navigation_home,
- R.id.navigation_search,
- R.id.navigation_library,
- R.id.navigation_settings,
- )) {
- rail.findViewById(focusView)?.nextFocusRightId = target
- }
- }
-
private fun handleTvBackPress(helper: BackPressedCallbackHelper.CallbackHelper) {
// Only apply custom behavior on TV interface
if (!isLayout(TV)) {
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeParentItemAdapter.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeParentItemAdapter.kt
index 1f721ee20..6bdd1bf49 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeParentItemAdapter.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeParentItemAdapter.kt
@@ -159,7 +159,7 @@ open class ParentItemAdapter(
})
//(recyclerView.adapter as HomeChildItemAdapter).notifyDataSetChanged()
- if (isLayout(PHONE or EMULATOR)) {
+ if (isLayout(PHONE)) {
homeChildMoreInfo.setOnClickListener {
moreInfoClickCallback.invoke(item)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeScrollAdapter.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeScrollAdapter.kt
index 1020205ac..e42e774b5 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeScrollAdapter.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/home/HomeScrollAdapter.kt
@@ -58,7 +58,7 @@ class HomeScrollAdapter(
when (binding) {
is HomeScrollViewBinding -> {
- binding.homeScrollPreview.loadImage(posterUrl, item.posterHeaders)
+ binding.homeScrollPreview.loadImage(posterUrl)
binding.homeScrollPreviewTags.apply {
text = item.tags?.joinToString(" • ") ?: ""
isGone = item.tags.isNullOrEmpty()
@@ -79,8 +79,8 @@ class HomeScrollAdapter(
binding.homeScrollPreview.setOnClickListener { view ->
callback.invoke(view ?: return@setOnClickListener, position, item)
}
- binding.homeScrollPreview.loadImage(posterUrl, item.posterHeaders)
+ binding.homeScrollPreview.loadImage(posterUrl)
}
}
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/library/LibraryFragment.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/library/LibraryFragment.kt
index e73a8c75a..c5f8fa3d9 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/library/LibraryFragment.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/library/LibraryFragment.kt
@@ -20,7 +20,6 @@ import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
-import com.fasterxml.jackson.annotation.JsonProperty
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lagradost.cloudstream3.APIHolder
@@ -53,13 +52,12 @@ import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
import com.lagradost.cloudstream3.utils.UIHelper.getSpanCount
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.math.abs
const val LIBRARY_FOLDER = "library_folder"
+
enum class LibraryOpenerType(@StringRes val stringRes: Int) {
Default(R.string.action_default),
Provider(R.string.none),
@@ -69,15 +67,13 @@ enum class LibraryOpenerType(@StringRes val stringRes: Int) {
}
/** Used to store how the user wants to open said poster */
-@Serializable
data class LibraryOpener(
- @JsonProperty("openType") @SerialName("openType") val openType: LibraryOpenerType,
- @JsonProperty("providerData") @SerialName("providerData") val providerData: ProviderLibraryData?,
+ val openType: LibraryOpenerType,
+ val providerData: ProviderLibraryData?,
)
-@Serializable
data class ProviderLibraryData(
- @JsonProperty("apiName") @SerialName("apiName") val apiName: String,
+ val apiName: String
)
class LibraryFragment : BaseFragment(
@@ -572,4 +568,4 @@ class LibraryFragment : BaseFragment(
}
}
-class MenuSearchView(context: Context) : SearchView(context)
+class MenuSearchView(context: Context) : SearchView(context)
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/CS3IPlayer.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/CS3IPlayer.kt
index 9c5685c68..d7e10c814 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/CS3IPlayer.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/CS3IPlayer.kt
@@ -108,7 +108,6 @@ import com.lagradost.cloudstream3.utils.PLAYREADY_DRM_UUID
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
import com.lagradost.cloudstream3.utils.WIDEVINE_DRM_UUID
import com.lagradost.cloudstream3.utils.videoskip.VideoSkipStamp
-import com.lagradost.cloudstream4.AppSettings
import kotlinx.coroutines.delay
import okhttp3.Interceptor
import org.chromium.net.CronetEngine
@@ -720,7 +719,7 @@ class CS3IPlayer : IPlayer {
**/
var preferredAudioTrackLanguage: String? = null
get() {
- return field ?: getKey(
+ return field ?: getKey(
"$currentAccount/$PREFERRED_AUDIO_LANGUAGE_KEY",
field
)?.also {
@@ -1390,17 +1389,10 @@ class CS3IPlayer : IPlayer {
context.getString(if (context.isUsingMobileData()) R.string.quality_pref_mobile_data_key else R.string.quality_pref_key),
Int.MAX_VALUE
)
- val settings = AppSettings(context)
try {
hasUsedFirstRender = false
- val playWhenReady = if (settings.player.startPaused.get()) {
- false
- } else {
- isPlaying // this keep the current state of the player
- }
-
// ye this has to be a val for whatever reason
// this makes no sense
exoPlayer = buildExoPlayer(
@@ -1412,7 +1404,7 @@ class CS3IPlayer : IPlayer {
playBackSpeed,
cacheSize = cacheSize,
videoBufferMs = videoBufferMs,
- playWhenReady = playWhenReady,
+ playWhenReady = isPlaying, // this keep the current state of the player
subtitleOffset = currentSubtitleOffset,
maxVideoHeight = maxVideoHeight,
audioSources = audioSources,
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/FullScreenPlayer.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/FullScreenPlayer.kt
index f38a9ab99..5f5110552 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/FullScreenPlayer.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/FullScreenPlayer.kt
@@ -102,12 +102,12 @@ open class FullScreenPlayer : AbstractPlayerFragment(
private var hideControlsNames = false
protected var subtitleDelay
set(value) = try {
- player.setSubtitleOffset(value)
+ player.setSubtitleOffset(-value)
} catch (e: Exception) {
logError(e)
}
get() = try {
- player.getSubtitleOffset()
+ -player.getSubtitleOffset()
} catch (e: Exception) {
logError(e)
0L
@@ -307,7 +307,6 @@ open class FullScreenPlayer : AbstractPlayerFragment(
playerVideoTitleRez,
playerVideoInfo,
playerGoBackHolder,
- playerVideoClock,
).forEach {
it.animateY(titleMove)
}
@@ -527,7 +526,7 @@ open class FullScreenPlayer : AbstractPlayerFragment(
// Scroll to the first active subtitle
val playerPosition = player.getPosition() ?: 0
- val totalPosition = playerPosition + currentOffset
+ val totalPosition = playerPosition - currentOffset
subtitleAdapter?.updateTime(totalPosition)
subtitleAdapter?.getLatestActiveItem(totalPosition)
@@ -537,11 +536,11 @@ open class FullScreenPlayer : AbstractPlayerFragment(
val str = when {
time > 0L -> {
- txt(R.string.subtitle_offset_extra_hint_before_format, time)
+ txt(R.string.subtitle_offset_extra_hint_later_format, time)
}
time < 0L -> {
- txt(R.string.subtitle_offset_extra_hint_later_format, -time)
+ txt(R.string.subtitle_offset_extra_hint_before_format, -time)
}
else -> {
@@ -559,12 +558,12 @@ open class FullScreenPlayer : AbstractPlayerFragment(
subtitleOffsetRecyclerview.isVisible = subtitles.isNotEmpty()
noSubtitlesLoadedNotice.isVisible = subtitles.isEmpty()
- val initialSubtitlePosition = (player.getPosition() ?: 0) + currentOffset
+ val initialSubtitlePosition = (player.getPosition() ?: 0) - currentOffset
subtitleAdapter =
SubtitleOffsetItemAdapter(initialSubtitlePosition) { subtitleCue ->
val playerPosition = player.getPosition() ?: 0
subtitleOffsetInput.text = Editable.Factory.getInstance()
- ?.newEditable((subtitleCue.startTimeMs - playerPosition).toString())
+ ?.newEditable((playerPosition - subtitleCue.startTimeMs).toString())
}.apply {
submitList(subtitles)
}
@@ -773,7 +772,7 @@ open class FullScreenPlayer : AbstractPlayerFragment(
val showPlayerEpisodes = !isGone && isThereEpisodes()
playerEpisodesButtonRoot.isVisible = showPlayerEpisodes
playerEpisodesButton.isVisible = showPlayerEpisodes
- playerVideoTitleHolder.isGone = togglePlayerTitleGone || playerVideoTitle.text.isBlank()
+ playerVideoTitleHolder.isGone = togglePlayerTitleGone
playerVideoTitleRez.isGone = isGone || playerVideoTitleRez.text.isBlank()
playerEpisodeFiller.isGone = isGone
playerCenterMenu.isGone = isGone
@@ -1203,10 +1202,6 @@ open class FullScreenPlayer : AbstractPlayerFragment(
}
skipChapterButton.setOnClickListener {
- // Switch focus for a better UX, as otherwise it is reset to a random button like "back button"
- if(skipChapterButton.hasFocus()) {
- playerPausePlay.requestFocus()
- }
player.handleEvent(CSPlayerEvent.SkipCurrentChapter)
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/GeneratorPlayer.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/GeneratorPlayer.kt
index e4616c93b..09b6db50f 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/GeneratorPlayer.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/GeneratorPlayer.kt
@@ -8,7 +8,6 @@ import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
-import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Spanned
@@ -80,7 +79,6 @@ import com.lagradost.cloudstream3.ui.player.CS3IPlayer.Companion.preferredAudioT
import com.lagradost.cloudstream3.ui.player.CustomDecoder.Companion.updateForcedEncoding
import com.lagradost.cloudstream3.ui.player.PlayerSubtitleHelper.Companion.toSubtitleMimeType
import com.lagradost.cloudstream3.ui.player.source_priority.LinkSource
-import com.lagradost.cloudstream3.ui.player.source_priority.ProfileSettings
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
import com.lagradost.cloudstream3.ui.player.source_priority.QualityProfileDialog
@@ -101,7 +99,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.ui.subtitles.SUBTITLE_AUTO_SELECT_KEY
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.getAutoSelectLanguageTagIETF
-import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragmentDialog2
import com.lagradost.cloudstream3.utils.AppContextUtils.getShortSeasonText
import com.lagradost.cloudstream3.utils.AppContextUtils.html
import com.lagradost.cloudstream3.utils.AppContextUtils.sortSubs
@@ -120,10 +117,8 @@ import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
-import com.lagradost.cloudstream3.utils.UIHelper.hideProgress
import com.lagradost.cloudstream3.utils.UIHelper.hideSystemUI
import com.lagradost.cloudstream3.utils.UIHelper.popCurrentPage
-import com.lagradost.cloudstream3.utils.UIHelper.showProgress
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream3.utils.downloader.DownloadUtils.getImageBitmapFromUrl
import com.lagradost.cloudstream3.utils.setText
@@ -135,7 +130,6 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.Serializable
-import java.lang.ref.WeakReference
import java.util.Calendar
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
@@ -513,8 +507,7 @@ class GeneratorPlayer : FullScreenPlayer() {
showDownloadProgress(DownloadEvent(0, 0, 0, null))
- // uiReset() // Removed due to UX
-
+ uiReset()
currentSelectedLink = link
// setEpisodes(viewModel.getAllMeta() ?: emptyList())
setPlayerDimen(null)
@@ -797,58 +790,47 @@ class GeneratorPlayer : FullScreenPlayer() {
}
binding.applyBtt.setOnClickListener {
- val currentSubtitle = currentSubtitle
- if (currentSubtitle == null) {
- dialog.dismissSafe()
- return@setOnClickListener
- }
+ currentSubtitle?.let { currentSubtitle ->
+ providers.firstOrNull { it.idPrefix == currentSubtitle.idPrefix }?.let { api ->
+ ioSafe {
+ when (val apiResource =
+ Resource.fromResult(api.resource(currentSubtitle))) {
+ is Resource.Success -> {
+ val subtitles = apiResource.value.getSubtitles().map { resource ->
+ SubtitleData(
+ originalName = resource.name ?: getName(
+ currentSubtitle,
+ true
+ ),
+ nameSuffix = "",
+ url = resource.url,
+ origin = resource.origin,
+ mimeType = resource.url.toSubtitleMimeType(),
+ headers = currentSubtitle.headers,
+ languageCode = currentSubtitle.lang
+ )
+ }
+ if (subtitles.isEmpty()) {
+ showToast(R.string.no_subtitles)
+ return@ioSafe
+ }
+ runOnMainThread {
+ addAndSelectSubtitles(*subtitles.toTypedArray())
+ }
+ }
- val api = providers.firstOrNull { it.idPrefix == currentSubtitle.idPrefix }
- if (api == null) {
- dialog.dismissSafe()
- return@setOnClickListener
- }
+ is Resource.Failure -> {
+ showToast(apiResource.errorString)
+ }
- binding.applyBtt.showProgress()
- ioSafe {
- val apiResource =
- Resource.fromResult(api.resource(currentSubtitle))
- binding.applyBtt.hideProgress()
- when (apiResource) {
- is Resource.Success -> {
- val subtitles = apiResource.value.getSubtitles().map { resource ->
- SubtitleData(
- originalName = resource.name ?: getName(
- currentSubtitle,
- true
- ),
- nameSuffix = "",
- url = resource.url,
- origin = resource.origin,
- mimeType = resource.url.toSubtitleMimeType(),
- headers = currentSubtitle.headers,
- languageCode = currentSubtitle.lang
- )
+ is Resource.Loading -> {
+ // not possible
+ }
}
- if (subtitles.isEmpty()) {
- showToast(R.string.no_subtitles)
- return@ioSafe
- }
- dialog.dismissSafe()
- runOnMainThread {
- addAndSelectSubtitles(*subtitles.toTypedArray())
- }
- }
-
- is Resource.Failure -> {
- showToast(apiResource.errorString)
- }
-
- is Resource.Loading -> {
- // not possible
}
}
}
+ dialog.dismissSafe()
}
dialog.setOnDismissListener {
@@ -1047,7 +1029,7 @@ class GeneratorPlayer : FullScreenPlayer() {
binding.subtitleSettingsBtt.setOnClickListener {
safe {
- val subtitlesFragment = SubtitlesFragmentDialog2()
+ val subtitlesFragment = SubtitlesFragment()
subtitlesFragment.systemBarsAddPadding = true
subtitlesFragment.show(this.parentFragmentManager, "SubtitleSettings")
}
@@ -1116,29 +1098,21 @@ class GeneratorPlayer : FullScreenPlayer() {
var sourceIndex = 0
var startSource = 0
- // Filtered and sorted links
- var currentHiddenFooter: View? = null
- var filteredLinks: List = emptyList()
+ var sortedUrls = emptyList>()
fun refreshLinks(qualityProfile: Int) {
- val currentLinkUsed = currentSelectedLink
- // Always display current linkFooter
- val sortedLinks = viewModel.state.sortLinks(qualityProfile)
-
- filteredLinks = sortedLinks.filter { it.shouldUseLink || it.link == currentLinkUsed }
-
- if (sortedLinks.isEmpty()) {
+ sortedUrls = viewModel.state.sortLinks(qualityProfile)
+ if (sortedUrls.isEmpty()) {
sourceDialog.findViewById(R.id.sort_sources_holder)?.isGone =
true
} else {
- startSource = filteredLinks.indexOfFirst { it.link == currentLinkUsed }
+ startSource = sortedUrls.indexOf(currentSelectedLink)
sourceIndex = startSource
val sourcesArrayAdapter =
ArrayAdapter(ctx, R.layout.sort_bottom_single_choice)
- sourcesArrayAdapter.addAll(filteredLinks.map { displayLink ->
- val (link, uri) = displayLink.link
+ sourcesArrayAdapter.addAll(sortedUrls.map { (link, uri) ->
val name = link?.name ?: uri?.name ?: "NULL"
"$name ${Qualities.getStringByInt(link?.quality)}"
})
@@ -1154,7 +1128,7 @@ class GeneratorPlayer : FullScreenPlayer() {
}
providerList.setOnItemLongClickListener { _, _, position, _ ->
- sortedLinks.getOrNull(position)?.link?.first?.url?.let {
+ sortedUrls.getOrNull(position)?.first?.url?.let {
clipboardHelper(
txt(R.string.video_source),
it
@@ -1162,25 +1136,6 @@ class GeneratorPlayer : FullScreenPlayer() {
}
true
}
-
- val hiddenLinks = sortedLinks.size - filteredLinks.size
- providerList.removeFooterView(currentHiddenFooter)
-
- if (hiddenLinks > 0) {
- val hiddenLinksFooter: TextView = layoutInflater.inflate(
- R.layout.sort_bottom_footer_add_choice, null
- ) as TextView
-
- providerList.addFooterView(hiddenLinksFooter, null, false)
- currentHiddenFooter = hiddenLinksFooter
-
- val hiddenLinksText =
- ctx.resources.getQuantityString(R.plurals.links_hidden, hiddenLinks)
- .format(hiddenLinks)
- hiddenLinksFooter.text = hiddenLinksText
- hiddenLinksFooter.setCompoundDrawables(null, null, null, null)
- hiddenLinksFooter.setTypeface(null, Typeface.ITALIC)
- }
}
}
@@ -1394,8 +1349,8 @@ class GeneratorPlayer : FullScreenPlayer() {
}
}
if (init) {
- filteredLinks.getOrNull(sourceIndex)?.let {
- loadLink(it.link, true)
+ sortedUrls.getOrNull(sourceIndex)?.let {
+ loadLink(it, true)
}
}
sourceDialog.dismissSafe(activity)
@@ -1563,10 +1518,6 @@ class GeneratorPlayer : FullScreenPlayer() {
}
override fun playerError(exception: Throwable) {
- currentSelectedLink?.let { link ->
- viewModel.modifyState { this.addError(link) }
- }
-
val currentUrl =
currentSelectedLink?.let { it.first?.url ?: it.second?.uri?.toString() } ?: "unknown"
val headers = currentSelectedLink?.first?.headers?.toString() ?: "none"
@@ -1589,22 +1540,8 @@ class GeneratorPlayer : FullScreenPlayer() {
private fun noLinksFound() {
viewModel.forceClearCache = true
- val hiddenLinks = viewModel.state.sortLinks(currentQualityProfile).count { !it.shouldUseLink }
-
- context?.let { ctx ->
- // Display that there are hidden links to the user.
- if (hiddenLinks > 0) {
- val noLinksString = ctx.getString(R.string.no_links_found_toast)
- val hiddenString =
- ctx.resources.getQuantityString(R.plurals.links_hidden, hiddenLinks)
- .format(hiddenLinks)
- val toastText = "$noLinksString\n($hiddenString)"
- showToast(toastText, Toast.LENGTH_SHORT)
- } else {
- showToast(R.string.no_links_found_toast, Toast.LENGTH_SHORT)
- }
- }
+ showToast(R.string.no_links_found_toast, Toast.LENGTH_SHORT)
activity?.popCurrentPage()
}
@@ -1615,9 +1552,7 @@ class GeneratorPlayer : FullScreenPlayer() {
}
val links = viewModel.state.sortLinks(currentQualityProfile)
-
- val firstAvailableLink = links.firstOrNull { it.shouldUseLink }?.link
- if (firstAvailableLink == null) {
+ if (links.isEmpty()) {
noLinksFound()
return
}
@@ -1625,7 +1560,7 @@ class GeneratorPlayer : FullScreenPlayer() {
if (!isPlayerActive.compareAndSet(false, true)) {
return
}
- loadLink(firstAvailableLink, false)
+ loadLink(links.first(), false)
showPlayerMetadata()
}
@@ -1692,26 +1627,25 @@ class GeneratorPlayer : FullScreenPlayer() {
}
}
- private fun getNextLink(): DisplayLink? {
- val links = viewModel.state.sortLinks(currentQualityProfile)
- val currentIndex = links.indexOfFirst { it.link == currentSelectedLink }
- val nextPotentialLink =
- links.withIndex().firstOrNull { it.index > currentIndex && it.value.shouldUseLink }
- return nextPotentialLink?.value
- }
-
override fun hasNextMirror(): Boolean {
- return getNextLink() != null
+ val links = viewModel.state.sortLinks(currentQualityProfile)
+ return links.isNotEmpty() && links.indexOf(currentSelectedLink) + 1 < links.size
}
override fun nextMirror() {
- val nextLink = getNextLink()
- if (nextLink == null) {
+ val links = viewModel.state.sortLinks(currentQualityProfile)
+ if (links.isEmpty()) {
noLinksFound()
return
}
- loadLink(nextLink.link, true)
+ val newIndex = links.indexOf(currentSelectedLink) + 1
+ if (newIndex >= links.size) {
+ noLinksFound()
+ return
+ }
+
+ loadLink(links[newIndex], true)
}
override fun onDestroy() {
@@ -1764,10 +1698,8 @@ class GeneratorPlayer : FullScreenPlayer() {
if (settingsManager.getBoolean(
ctx.getString(R.string.episode_sync_enabled_key), true
)
- ) {
- maxEpisodeSet = meta.episode
- sync.modifyMaxEpisode(meta.totalEpisodeIndex ?: meta.episode)
- }
+ ) maxEpisodeSet = meta.episode
+ sync.modifyMaxEpisode(meta.totalEpisodeIndex ?: meta.episode)
}
}
@@ -2218,7 +2150,6 @@ class GeneratorPlayer : FullScreenPlayer() {
isPlayerActive.set(false)
binding?.overlayLoadingSkipButton?.isVisible = false
binding?.playerLoadingOverlay?.isVisible = true
- viewModel.modifyState { setError(emptyList()) }
uiReset()
}
@@ -2272,14 +2203,6 @@ class GeneratorPlayer : FullScreenPlayer() {
fromTagToEnglishLanguageName(it)?.lowercase() ?: return@mapNotNull null
} ?: listOf()
}
-
- // Set up TV clock visibility
- if (isLayout(TV)) {
- val showTvClock = settingsManager.getBoolean(ctx.getString(R.string.tv_layout_clock_key), false)
- playerBinding?.playerVideoClock?.isVisible = showTvClock
- } else {
- playerBinding?.playerVideoClock?.isVisible = false
- }
}
unwrapBundle(savedInstanceState)
@@ -2358,23 +2281,19 @@ class GeneratorPlayer : FullScreenPlayer() {
}
}
- observe(viewModel.currentLinks) { (_, instance) ->
+ observe(viewModel.currentLinks) { (links, instance) ->
if (instance != viewModel.state.instance) return@observe // Outdated observe
- val sortedLinks = viewModel.state.sortLinks(currentQualityProfile)
- val usableLinks = sortedLinks.count { link -> link.shouldUseLink }
-
- val turnVisible = usableLinks > 0 && viewModel.generator?.canSkipLoading == true
+ val turnVisible = links.isNotEmpty() && viewModel.generator?.canSkipLoading == true
val wasGone = binding.overlayLoadingSkipButton.isGone
binding.overlayLoadingSkipButton.apply {
isVisible = turnVisible
-
- if (usableLinks == 0) {
+ if (links.isEmpty()) {
setText(R.string.skip_loading)
} else {
@SuppressLint("SetTextI18n")
- text = "${context.getString(R.string.skip_loading)} (${usableLinks})"
+ text = "${context.getString(R.string.skip_loading)} (${links.size})"
}
}
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerGeneratorViewModel.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerGeneratorViewModel.kt
index cb8cf8bff..e3c390d50 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerGeneratorViewModel.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerGeneratorViewModel.kt
@@ -10,8 +10,6 @@ import com.lagradost.cloudstream3.mvvm.Resource
import com.lagradost.cloudstream3.mvvm.launchSafe
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safeApiCall
-import com.lagradost.cloudstream3.ui.player.source_priority.ProfileSettings
-import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper.getLinkPriority
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
@@ -42,20 +40,12 @@ data class GeneratorState(
val id: Int?,
)
-data class DisplayLink(
- val link: VideoLink,
- // If the link should be displayed and used by the player
- val shouldUseLink: Boolean,
- val priority: Int
-)
-
/** Immutable state of all current links relevant to displaying the video */
// @MustUseReturnValues
// @Immutable
data class VideoState(
val subtitles: PersistentSet = persistentSetOf(),
val links: PersistentSet = persistentSetOf(),
- val erroredLinks: PersistentSet = persistentSetOf(),
val stamps: PersistentList = persistentListOf(),
val loading: Resource = Resource.Loading(),
val generatorState: GeneratorState? = null,
@@ -66,52 +56,19 @@ data class VideoState(
*
* sortedBy is not exactly expensive, but each hasNextMirror does it again, so this alleviates unnecessary recomputation
* */
- private val sortedLinks: ConcurrentHashMap> = ConcurrentHashMap()
+ private val sortedLinks: ConcurrentHashMap> = ConcurrentHashMap()
- /**
- * The cache is guaranteed to be up to date link-wise due to the immutable links.
- * However, hideNegativeSources and hideErrorSources could be updated, which requires clearing the cache.
- */
fun clearSortedLinksCache() = sortedLinks.clear()
- private fun hasLinkErrored(link: VideoLink): Boolean {
- return erroredLinks.any { it == link }
- }
-
- private fun VideoLink.toDisplayLink(
- qualityProfile: Int,
- hideNegativeSources: Boolean,
- hideErrorSources: Boolean
- ): DisplayLink {
- val priority = getLinkPriority(qualityProfile, this.first)
- val shouldHideLink =
- (hideNegativeSources && priority < 0) || (hideErrorSources && hasLinkErrored(this))
- val displayLink = DisplayLink(this, !shouldHideLink, priority)
-
- return displayLink
- }
-
// Modifying sortedLinks is not considered a "visible" side effect, and rerunning it does not change the result
// It is by all standards, idempotent and by extension also pure as it has no "visible" side effect
/** Returns .links in the sorted order according to the qualityProfile.
* Use .links if order is not needed */
@Contract(pure = true)
- fun sortLinks(qualityProfile: Int): List {
- sortedLinks[qualityProfile]?.let {
- return it
- }
-
- val hideNegativeSources =
- QualityDataHelper.getProfileSetting(qualityProfile, ProfileSettings.HideNegativeSources)
- val hideErrorSources =
- QualityDataHelper.getProfileSetting(qualityProfile, ProfileSettings.HideErrorSources)
-
- return links.map { link ->
+ fun sortLinks(qualityProfile: Int): List {
+ return sortedLinks[qualityProfile] ?: links.sortedBy { link ->
// negative because we want to sort highest quality first
- link.toDisplayLink(qualityProfile, hideNegativeSources, hideErrorSources)
- }.sortedBy {
- // negative because we want to sort highest quality first
- -it.priority
+ -getLinkPriority(qualityProfile, link.first)
}.also { value -> sortedLinks[qualityProfile] = value }
}
@@ -156,12 +113,6 @@ data class VideoState(
@JvmName("setVideoSkipStamp")
@Contract(pure = true)
fun set(items: Collection): VideoState = copy(stamps = items.toPersistentList())
-
- @Contract(pure = true)
- fun addError(item: VideoLink): VideoState = copy(erroredLinks = erroredLinks.add(item))
-
- @Contract(pure = true)
- fun setError(items: Collection): VideoState = copy(erroredLinks = items.toPersistentSet())
}
data class VideoLive(
@@ -190,8 +141,9 @@ class PlayerGeneratorViewModel : ViewModel() {
var state = VideoState(instance = 0)
private set
- private val _currentLinks = MutableLiveData>>(null)
- val currentLinks: LiveData>> = _currentLinks
+ private val _currentLinks =
+ MutableLiveData>>>(null)
+ val currentLinks: LiveData>>> = _currentLinks
private val _currentSubtitles = MutableLiveData>>(null)
val currentSubtitles: LiveData>> = _currentSubtitles
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerSubtitleHelper.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerSubtitleHelper.kt
index f62bad58d..ee6170aa5 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerSubtitleHelper.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/PlayerSubtitleHelper.kt
@@ -8,14 +8,11 @@ import androidx.annotation.OptIn
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.ui.SubtitleView
-import com.fasterxml.jackson.annotation.JsonIgnore
import com.lagradost.cloudstream3.SubtitleFile
import com.lagradost.cloudstream3.ui.subtitles.SaveCaptionStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.setSubtitleViewStyle
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
import com.lagradost.cloudstream3.utils.UIHelper.toPx
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
enum class SubtitleStatus {
IS_ACTIVE,
@@ -35,19 +32,17 @@ enum class SubtitleOrigin {
* @param url Url for the subtitle, when EMBEDDED_IN_VIDEO this variable is used as the real backend id
* @param headers if empty it will use the base onlineDataSource headers else only the specified headers
* @param languageCode usually, tags such as "en", "es-mx", or "zh-hant-TW". But it could be something like "English 4"
- */
-@Serializable
+ * */
data class SubtitleData(
- @SerialName("originalName") val originalName: String,
- @SerialName("nameSuffix") val nameSuffix: String,
- @SerialName("url") val url: String,
- @SerialName("origin") val origin: SubtitleOrigin,
- @SerialName("mimeType") val mimeType: String,
- @SerialName("headers") val headers: Map,
- @SerialName("languageCode") val languageCode: String?,
+ val originalName: String,
+ val nameSuffix: String,
+ val url: String,
+ val origin: SubtitleOrigin,
+ val mimeType: String,
+ val headers: Map,
+ val languageCode: String?,
) {
- /** Internal ID for media3, unique for each link. */
- @JsonIgnore
+ /** Internal ID for exoplayer, unique for each link*/
fun getId(): String {
return if (origin == SubtitleOrigin.EMBEDDED_IN_VIDEO) url
else "$url|$name"
@@ -59,22 +54,22 @@ data class SubtitleData(
}
/** Tries hard to figure out a valid IETF tag based on language code and name. Will return null if not found. */
- @JsonIgnore
fun getIETF_tag(): String? {
return fromLanguageToTagIETF(this.languageCode) ?: fromLanguageToTagIETF(this.originalName, halfMatch = true)
}
- @SerialName("name") val name = "$originalName $nameSuffix"
+ val name = "$originalName $nameSuffix"
/**
* Gets the URL, but tries to fix it if it is malformed.
*/
- @JsonIgnore
fun getFixedUrl(): String {
// Some extensions fail to include the protocol, this helps with that.
val fixedSubUrl = if (this.url.startsWith("//")) {
"https:${this.url}"
- } else this.url
+ } else {
+ this.url
+ }
return fixedSubUrl
}
}
@@ -147,4 +142,4 @@ class PlayerSubtitleHelper {
setSubStyle(it)
}
}
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/lagradost/cloudstream3/ui/player/Torrent.kt b/app/src/main/java/com/lagradost/cloudstream3/ui/player/Torrent.kt
index 7e5d04eb0..2e554f75e 100644
--- a/app/src/main/java/com/lagradost/cloudstream3/ui/player/Torrent.kt
+++ b/app/src/main/java/com/lagradost/cloudstream3/ui/player/Torrent.kt
@@ -9,8 +9,6 @@ import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.newExtractorLink
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
import torrServer.TorrServer
import java.io.File
import java.net.ConnectException
@@ -34,14 +32,14 @@ object Torrent {
/** Returns true if the server is up */
private suspend fun echo(): Boolean {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
return false
}
return try {
app.get(
"$TORRENT_SERVER_URL/echo",
).text.isNotEmpty()
- } catch (_: ConnectException) {
+ } catch (e: ConnectException) {
// `Failed to connect to /127.0.0.1:8090` if the server is down
false
} catch (t: Throwable) {
@@ -54,7 +52,7 @@ object Torrent {
/** Gracefully shutdown the server.
* should not be used because I am unable to start it again, and the stopTorrentServer() crashes the app */
suspend fun shutdown(): Boolean {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
return false
}
return try {
@@ -70,7 +68,7 @@ object Torrent {
/** Lists all torrents by the server */
@Throws
private suspend fun list(): Array {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
throw ErrorLoadingException("Not initialized")
}
return app.post(
@@ -85,7 +83,7 @@ object Torrent {
/** Drops a single torrent, (I think) this means closing the stream. Returns returns if it is successful */
private suspend fun drop(hash: String): Boolean {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
return false
}
return try {
@@ -106,7 +104,7 @@ object Torrent {
/** Removes a single torrent from the server registry */
private suspend fun rem(hash: String): Boolean {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
return false
}
return try {
@@ -128,7 +126,7 @@ object Torrent {
/** Removes all torrents from the server, and returns if it is successful */
suspend fun clearAll(): Boolean {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
return true
}
return try {
@@ -166,8 +164,10 @@ object Torrent {
/** Gets all the metadata of a torrent, will throw if that hash does not exists
* https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L126 */
@Throws
- suspend fun get(hash: String): TorrentStatus {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ suspend fun get(
+ hash: String,
+ ): TorrentStatus {
+ if(TORRENT_SERVER_URL.isEmpty()) {
throw ErrorLoadingException("Not initialized")
}
return app.post(
@@ -184,7 +184,7 @@ object Torrent {
/** Adds a torrent to the server, this is needed for us to get the hash for further modification, as well as start streaming it*/
@Throws
private suspend fun add(url: String): TorrentStatus {
- if (TORRENT_SERVER_URL.isEmpty()) {
+ if(TORRENT_SERVER_URL.isEmpty()) {
throw ErrorLoadingException("Not initialized")
}
return app.post(
@@ -204,7 +204,7 @@ object Torrent {
return true
}
val port = TorrServer.startTorrentServer(dir, 0)
- if (port < 0) {
+ if(port < 0) {
return false
}
TORRENT_SERVER_URL = "http://127.0.0.1:$port"
@@ -278,55 +278,94 @@ object Torrent {
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/web/api/torrents.go#L18
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/main/web/api/route.go#L7
- @Serializable
data class TorrentRequest(
- @JsonProperty("action") @SerialName("action") val action: String,
- @JsonProperty("hash") @SerialName("hash") val hash: String = "",
- @JsonProperty("link") @SerialName("link") val link: String = "",
- @JsonProperty("title") @SerialName("title") val title: String = "",
- @JsonProperty("poster") @SerialName("poster") val poster: String = "",
- @JsonProperty("data") @SerialName("data") val data: String = "",
- @JsonProperty("save_to_db") @SerialName("save_to_db") val saveToDB: Boolean = false,
+ @JsonProperty("action")
+ val action: String,
+ @JsonProperty("hash")
+ val hash: String = "",
+ @JsonProperty("link")
+ val link: String = "",
+ @JsonProperty("title")
+ val title: String = "",
+ @JsonProperty("poster")
+ val poster: String = "",
+ @JsonProperty("data")
+ val data: String = "",
+ @JsonProperty("save_to_db")
+ val saveToDB: Boolean = false,
)
// https://github.com/Diegopyl1209/torrentserver-aniyomi/blob/c18f58e51b6738f053261bc863177078aa9c1c98/torr/state/state.go#L33
// omitempty = nullable
- @Serializable
data class TorrentStatus(
- @JsonProperty("title") @SerialName("title") var title: String,
- @JsonProperty("poster") @SerialName("poster") var poster: String,
- @JsonProperty("data") @SerialName("data") var data: String?,
- @JsonProperty("timestamp") @SerialName("timestamp") var timestamp: Long,
- @JsonProperty("name") @SerialName("name") var name: String?,
- @JsonProperty("hash") @SerialName("hash") var hash: String?,
- @JsonProperty("stat") @SerialName("stat") var stat: Int,
- @JsonProperty("stat_string") @SerialName("stat_string") var statString: String,
- @JsonProperty("loaded_size") @SerialName("loaded_size") var loadedSize: Long?,
- @JsonProperty("torrent_size") @SerialName("torrent_size") var torrentSize: Long?,
- @JsonProperty("preloaded_bytes") @SerialName("preloaded_bytes") var preloadedBytes: Long?,
- @JsonProperty("preload_size") @SerialName("preload_size") var preloadSize: Long?,
- @JsonProperty("download_speed") @SerialName("download_speed") var downloadSpeed: Double?,
- @JsonProperty("upload_speed") @SerialName("upload_speed") var uploadSpeed: Double?,
- @JsonProperty("total_peers") @SerialName("total_peers") var totalPeers: Int?,
- @JsonProperty("pending_peers") @SerialName("pending_peers") var pendingPeers: Int?,
- @JsonProperty("active_peers") @SerialName("active_peers") var activePeers: Int?,
- @JsonProperty("connected_seeders") @SerialName("connected_seeders") var connectedSeeders: Int?,
- @JsonProperty("half_open_peers") @SerialName("half_open_peers") var halfOpenPeers: Int?,
- @JsonProperty("bytes_written") @SerialName("bytes_written") var bytesWritten: Long?,
- @JsonProperty("bytes_written_data") @SerialName("bytes_written_data") var bytesWrittenData: Long?,
- @JsonProperty("bytes_read") @SerialName("bytes_read") var bytesRead: Long?,
- @JsonProperty("bytes_read_data") @SerialName("bytes_read_data") var bytesReadData: Long?,
- @JsonProperty("bytes_read_useful_data") @SerialName("bytes_read_useful_data") var bytesReadUsefulData: Long?,
- @JsonProperty("chunks_written") @SerialName("chunks_written") var chunksWritten: Long?,
- @JsonProperty("chunks_read") @SerialName("chunks_read") var chunksRead: Long?,
- @JsonProperty("chunks_read_useful") @SerialName("chunks_read_useful") var chunksReadUseful: Long?,
- @JsonProperty("chunks_read_wasted") @SerialName("chunks_read_wasted") var chunksReadWasted: Long?,
- @JsonProperty("pieces_dirtied_good") @SerialName("pieces_dirtied_good") var piecesDirtiedGood: Long?,
- @JsonProperty("pieces_dirtied_bad") @SerialName("pieces_dirtied_bad") var piecesDirtiedBad: Long?,
- @JsonProperty("duration_seconds") @SerialName("duration_seconds") var durationSeconds: Double?,
- @JsonProperty("bit_rate") @SerialName("bit_rate") var bitRate: String?,
- @JsonProperty("file_stats") @SerialName("file_stats") var fileStats: List?,
- @JsonProperty("trackers") @SerialName("trackers") var trackers: List