Compare commits

..

4 commits

Author SHA1 Message Date
firelight
ca17a4c7e1
Merge branch 'master' into poststable480 2026-07-10 16:26:19 +00:00
firelight
5a40b036cb
Update ExtractorApi.kt 2026-07-10 16:25:36 +00:00
firelight
2f69f33f1f
Update ExtractorApi.kt 2026-07-10 16:20:49 +00:00
firelight
b7234cbb2b
remove prerelease annotations 2026-07-10 16:09:42 +00:00
477 changed files with 3425 additions and 37057 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

View file

@ -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

View file

@ -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.

View file

@ -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.**
<p align="left"><a href="https://github.com/recloudstream/cloudstream/releases/download/pre-release/app-prerelease-release.apk"><img src=".github/images/download-cloudstream-pre.png" alt="Download Cloudstream Pre-Release" width=430/></a></p>
[![Discord](https://invidget.switchblade.xyz/5Hus6fM)](https://discord.gg/5Hus6fM)

View file

@ -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<Jar>("androidSourcesJar") {
@ -332,9 +323,11 @@ tasks.withType<KotlinJvmCompile> {
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",
)
}
}

View file

@ -163,7 +163,7 @@ class ExampleInstrumentedTest {
TestingUtils.getDeferredProviderTests(
this,
getAllProviders(),
) { _, _, _ -> }
) { _, _ -> }
}
}
}

View file

@ -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<String> = emptyList(),
val meta: Map<String, String> = emptyMap(),
val name: String = "hello",
) {
object Serializer : NonEmptySerializer<NonEmptyData>(NonEmptyData.generatedSerializer())
}
@OptIn(ExperimentalSerializationApi::class)
@KeepGeneratedSerializer
@Serializable(with = WriteOnlyData.Serializer::class)
data class WriteOnlyData(
val fieldA: String = "",
val fieldB: String = "",
) {
object Serializer : WriteOnlySerializer<WriteOnlyData>(
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>(
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<NonEmptyData>(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<WriteOnlyData>(input)
assertEquals("hello", result.fieldA)
assertEquals("secret", result.fieldB)
}
@Test
fun writeOnlySerializerDeserializesMissingAsDefault() {
val input = """{"fieldA":"hello"}"""
val result = parseJson<WriteOnlyData>(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<UriData>(input)
assertEquals(Uri.parse("https://example.com/path?query=1"), result.uri)
}
@Test
fun uriSerializerRoundtripsCorrectly() {
val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
val encoded = data.toJson()
val decoded = parseJson<UriData>(encoded)
assertEquals(data.uri, decoded.uri)
}
}

View file

@ -1,41 +0,0 @@
package com.lagradost.cloudstream3.utils.serializers
import android.net.Uri
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
@Serializable
data class UriData(
@Serializable(with = UriSerializer::class)
@SerialName("uri") val uri: Uri = Uri.EMPTY,
)
class UriSerializerTest {
@Test
fun uriSerializerSerializesUriToString() {
val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
val result = data.toJson()
assertTrue(result.contains("https://example.com/path?query=1"))
}
@Test
fun uriSerializerDeserializesStringToUri() {
val input = """{"uri":"https://example.com/path?query=1"}"""
val result = parseJson<UriData>(input)
assertEquals(Uri.parse("https://example.com/path?query=1"), result.uri)
}
@Test
fun uriSerializerRoundtripsCorrectly() {
val data = UriData(uri = Uri.parse("https://example.com/path?query=1"))
val encoded = data.toJson()
val decoded = parseJson<UriData>(encoded)
assertEquals(data.uri, decoded.uri)
}
}

View file

@ -161,7 +161,7 @@
android:supportsPictureInPicture="true" />
<activity
android:name=".ui.account.AccountSelectActivity2"
android:name=".ui.account.AccountSelectActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
android:exported="true">
<intent-filter android:exported="true">
@ -253,10 +253,6 @@
</intent-filter>
</receiver>
<receiver
android:name=".receivers.PackageInstallerStatusReceiver"
android:exported="false" />
<service
android:name=".services.VideoDownloadService"
android:enabled="true"

View file

@ -113,7 +113,7 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
get() = _context?.get()
private set(value) {
_context = WeakReference(value)
setContext(value)
setContext(WeakReference(value))
}
fun <T : Any> getKeyClass(path: String, valueType: Class<T>): T? {
@ -170,11 +170,11 @@ class CloudStreamApp : Application(), SingletonImageLoader.Factory {
}
/** Will fall back to WebView if in TV or emulator layout. */
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()
)
}
}

View file

@ -52,7 +52,6 @@ import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
import com.lagradost.cloudstream3.ui.settings.extensions.PluginAdapter
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.isAuthEnabled
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Event
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
@ -267,9 +266,7 @@ object CommonActivity {
}
// Ask for notification permissions on Android 13
// Not while biometric locked, the dialog cancels the biometric prompt
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!isAuthEnabled(componentActivity) &&
ContextCompat.checkSelfPermission(
componentActivity,
Manifest.permission.POST_NOTIFICATIONS

View file

@ -179,8 +179,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.compose.CloudStreamThemeAppSettings
import com.lagradost.cloudstream4.theme.CloudStreamTheme
import com.lagradost.safefile.SafeFile
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
@ -1217,7 +1215,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<String>("VERSION_NAME") ?: ""
val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
if (appVer != lastAppAutoBackup) {
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
if (lastAppAutoBackup.isEmpty()) return@safe
@ -1299,14 +1297,6 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
padRight = false,
padTop = false
)
composeView.apply {
setContent {
CloudStreamThemeAppSettings {
MainActivityScreen.Content()
}
}
}
}
// overscan
@ -1379,7 +1369,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
//Automatically download not existing plugins, using mode specified.
/*val autoDownloadPlugin = AutoDownloadMode.getEnum(
val autoDownloadPlugin = AutoDownloadMode.getEnum(
settingsManager.getInt(
getString(R.string.auto_download_plugins_key),
0
@ -1390,7 +1380,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
this@MainActivity,
autoDownloadPlugin
)
}*/
}
}
ioSafe {
@ -1989,9 +1979,9 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
handleAppIntent(intent)
//ioSafe {
// runAutoUpdate()
//}
ioSafe {
runAutoUpdate()
}
FcastManager().init(this, false)
@ -2028,7 +2018,7 @@ class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCa
}
try {
if (getKey<Boolean>(HAS_DONE_SETUP_KEY, false) != true) {
if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
navController.navigate(R.id.navigation_setup_language)
// If no plugins bring up extensions screen
} else if (PluginManager.getPluginsOnline().isEmpty()

View file

@ -1,266 +0,0 @@
package com.lagradost.cloudstream3
import android.text.format.Formatter.formatFileSize
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lagradost.cloudstream3.mvvm.getStackTracePretty
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.ui.settings.ApkUpdater
import com.lagradost.cloudstream3.ui.settings.GithubReleases
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_CONTENT_TYPE
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_PRERELEASE
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_REPOSITORY
import com.lagradost.cloudstream3.ui.settings.GithubReleases.APK_USERNAME
import com.lagradost.cloudstream3.utils.GitInfo.currentCommitHash
import com.lagradost.cloudstream3.utils.parseMarkdown
import com.lagradost.cloudstream4.compose.BlackButton
import com.lagradost.cloudstream4.compose.Screen
import com.lagradost.cloudstream4.compose.WhiteButton
import com.lagradost.cloudstream4.rememberAppSettings
import com.lagradost.cloudstream4.viewmodels.GithubAction
import com.lagradost.cloudstream4.viewmodels.GithubAction.AutoSearchForUpdate
import com.lagradost.cloudstream4.viewmodels.GithubAction.Dismiss
import com.lagradost.cloudstream4.viewmodels.GithubAction.SearchForUpdate
import com.lagradost.cloudstream4.viewmodels.GithubAction.SkipUpdate
import com.lagradost.cloudstream4.viewmodels.GithubAction.Update
import com.lagradost.cloudstream4.viewmodels.GithubState
import com.lagradost.cloudstream4.viewmodels.GithubUpdateDialogState
import com.lagradost.cloudstream4.viewmodels.GithubViewModel
import com.mihon.material.padding
object MainActivityScreen : Screen {
private var hasSearchedForUpdate: Boolean = false
@Composable
fun githubViewModel(): GithubViewModel? {
// By having the ComponentActivity as the owner we can have a singleton viewmodel
val activity = LocalActivity.current as? ComponentActivity ?: return null
val settings = rememberAppSettings()
return viewModel(viewModelStoreOwner = activity) {
GithubViewModel(
remoteUserName = APK_USERNAME,
remoteRepository = APK_REPOSITORY,
remotePrereleaseTag = APK_PRERELEASE,
remoteContentType = APK_CONTENT_TYPE,
versionName = BuildConfig.VERSION_NAME,
isPrerelease = BuildConfig.FLAVOR == "prerelease",
isDebug = BuildConfig.DEBUG,
buildSha = activity.currentCommitHash(),
settings = settings,
updater = ApkUpdater,
repository = GithubReleases,
).apply {
/** Only search once per session when not in safe mode */
if (!hasSearchedForUpdate && !PluginManager.isSafeMode()) {
hasSearchedForUpdate = true
onAction(AutoSearchForUpdate)
}
}
}
}
@Composable
override fun Content() {
GithubView()
}
@Composable
fun GithubView() {
val updateViewModel = githubViewModel() ?: return
val state by updateViewModel.state.collectAsState()
GithubState(state, updateViewModel::onAction)
}
@Composable
fun GithubState(updaterState: GithubState, onAction: (GithubAction) -> Unit) {
val dialog = updaterState.dialog ?: return
val title: String
val body: @Composable () -> Unit
val confirmButton: @Composable () -> Unit
val dismissButton: @Composable () -> Unit
val cancelable: Boolean
when (val state = dialog.state) {
is GithubUpdateDialogState.Error -> {
// Only show error if it is initialized by the user
if (!dialog.isFromUser) return
cancelable = true
title = stringResource(R.string.download_failed)
body = { Text(text = state.error.getStackTracePretty()) }
confirmButton = {
WhiteButton(text = stringResource(R.string.check_for_update), onClick = {
onAction(SearchForUpdate)
})
}
dismissButton = {
BlackButton(text = stringResource(R.string.ok), onClick = {
onAction(Dismiss)
})
}
}
GithubUpdateDialogState.Loading -> {
// Only show loading if it is initialized by the user
if (!dialog.isFromUser) return
cancelable = true
title = stringResource(R.string.loading)
body = {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.onBackground,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
confirmButton = {}
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = {
onAction(Dismiss)
})
}
}
GithubUpdateDialogState.NoUpdateFound -> {
// Only show error if it is initialized by the user
if (!dialog.isFromUser) return
cancelable = true
title = stringResource(R.string.no_update_found)
body = {}
confirmButton = {
WhiteButton(text = stringResource(R.string.ok), onClick = {
onAction(Dismiss)
})
}
dismissButton = {}
}
is GithubUpdateDialogState.UpdateFound -> {
cancelable = true
title = stringResource(
R.string.new_update_format,
(state.oldSha ?: BuildConfig.VERSION_NAME),
(state.newSha ?: state.file.displayName)
)
body = {
Text(
text = parseMarkdown(state.file.changeLog),
modifier = Modifier.verticalScroll(rememberScrollState())
)
}
confirmButton = {
WhiteButton(text = stringResource(R.string.update), onClick = {
onAction(Update(state.file))
})
}
dismissButton = {
BlackButton(text = stringResource(R.string.skip_update), onClick = {
onAction(SkipUpdate(state.file))
onAction(Dismiss)
})
BlackButton(text = stringResource(R.string.cancel), onClick = {
onAction(Dismiss)
})
}
}
is GithubUpdateDialogState.DownloadProgress -> {
cancelable = false
title = stringResource(R.string.update_notification_downloading)
body = {
val total = state.total
if (total != null) {
val progress =
(state.progress.toFloat() / total.toFloat()).coerceIn(0.0f, 1.0f)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
// Round down the progress to avoid 100%
text = "${(progress * 100.0f).toInt()}% (${
formatFileSize(
LocalContext.current,
state.progress
)
} / ${
formatFileSize(
LocalContext.current,
total
)
})"
)
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.onBackground,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
progress = { progress }
)
}
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
text = formatFileSize(
LocalContext.current,
state.progress
)
)
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.onBackground,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
}
}
confirmButton = {}
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = {
onAction(Dismiss)
})
}
}
}
AlertDialog(
properties = DialogProperties(usePlatformDefaultWidth = false),
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = {
if (cancelable) {
onAction(Dismiss)
}
},
title = { Text(text = title) },
text = body,
confirmButton = confirmButton,
dismissButton = dismissButton
)
}
}

View file

@ -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 {

View file

@ -60,7 +60,7 @@ open class VlcPackage: OpenInAppAction(
intent.putExtra("secure_uri", true)
intent.putExtra("title", video.name)
val subsLang = getKey<String>(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
result.subs.firstOrNull {
subsLang == it.languageCode
}?.let {
@ -74,4 +74,4 @@ open class VlcPackage: OpenInAppAction(
Log.d("VLC", "Position: $position, Duration: $duration")
updateDurationAndPosition(position, duration)
}
}
}

View file

@ -37,7 +37,7 @@ fun buildDefaultClient(context: Context, ignoreSSL: Boolean = false): OkHttpClie
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)

View file

@ -176,11 +176,11 @@ object PluginManager {
fun getPluginsOnline(): Array<PluginData> {
return getKey<Array<PluginData>>(PLUGINS_KEY) ?: emptyArray()
return getKey(PLUGINS_KEY) ?: emptyArray()
}
fun getPluginsLocal(): Array<PluginData> {
return getKey<Array<PluginData>>(PLUGINS_KEY_LOCAL) ?: emptyArray()
return getKey(PLUGINS_KEY_LOCAL) ?: emptyArray()
}
private val CLOUD_STREAM_FOLDER =
@ -590,7 +590,7 @@ object PluginManager {
/**
* @return True if successful, false if not
* */
internal suspend fun loadPlugin(context: Context, file: File, data: PluginData): Boolean {
private suspend fun loadPlugin(context: Context, file: File, data: PluginData): Boolean {
val fileName = file.nameWithoutExtension
val filePath = file.absolutePath
currentlyLoading = fileName

View file

@ -98,7 +98,7 @@ data class PluginWrapper(
object RepositoryManager {
const val ONLINE_PLUGINS_FOLDER = "Extensions"
val PREBUILT_REPOSITORIES: Array<RepositoryData> by lazy {
getKey<Array<RepositoryData>>("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,19 +141,11 @@ 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
}
val response = app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false)
val url = response.headers["Location"] ?: return@safeAsync null
if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
return@safeAsync url
}
} else null
}
@ -161,7 +153,7 @@ object RepositoryManager {
suspend fun parseRepository(url: String): Repository? {
return safeAsync {
// Take manifestVersion and such into account later
app.get(convertRawGitUrl(url), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
app.get(convertRawGitUrl(url), cacheTime = 5, cacheUnit = TimeUnit.MINUTES)
.parsedSafe<Repository>()
}
}
@ -169,7 +161,7 @@ object RepositoryManager {
private suspend fun parsePlugins(pluginUrls: String): List<SitePlugin> {
// Take manifestVersion and such into account later
return try {
app.get(convertRawGitUrl(pluginUrls), cacheTime = 15, cacheUnit = TimeUnit.MINUTES)
app.get(convertRawGitUrl(pluginUrls), cacheTime = 5, cacheUnit = TimeUnit.MINUTES)
.parsed<Array<SitePlugin>>().toList()
} catch (t: Throwable) {
logError(t)
@ -240,23 +232,16 @@ object RepositoryManager {
}
fun getRepositories(): Array<RepositoryData> {
return getKey<Array<RepositoryData>>(REPOSITORIES_KEY) ?: emptyArray()
return getKey(REPOSITORIES_KEY) ?: emptyArray()
}
// Don't want to read before we write in another thread
private val repoLock = Mutex()
suspend fun addRepository(repository: RepositoryData) {
repoLock.withLock {
// No duplicates, but we want the new repository instead of the old one
var currentRepos = getRepositories()
val index = currentRepos.indexOfFirst { it.url == repository.url }
if(index == -1) {
currentRepos += repository
} else {
/** We want to keep the ordering here, as that is the addition order */
currentRepos[index] = repository
}
setKey(REPOSITORIES_KEY, currentRepos)
val currentRepos = getRepositories()
// No duplicates
setKey(REPOSITORIES_KEY, (currentRepos + repository).distinctBy { it.url })
}
}

View file

@ -1,28 +0,0 @@
package com.lagradost.cloudstream3.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import com.lagradost.cloudstream3.utils.getSafeParcelableExtra
/** https://medium.com/@solrudev/painless-building-of-an-android-package-installer-app-d5a09b5df432 */
class PackageInstallerStatusReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
intent.getSafeParcelableExtra<Intent>(Intent.EXTRA_INTENT)?.let { userAction->
userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(userAction)
}
}
PackageInstaller.STATUS_SUCCESS -> {
// do something on success
}
else -> {
val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
println("PackageInstallerStatusReceiver: status=$status, message=$message")
}
}
}
}

View file

@ -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<String, String> {
return splitUrlParameters(
redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
return splitQuery(
URI(
redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
).toURL()
)
}

View file

@ -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<ResultEpisode>,
@JsonProperty("currentLinks") @SerialName("currentLinks") val currentLinks: List<ExtractorLink>,
@JsonProperty("currentSubtitles") @SerialName("currentSubtitles") val currentSubtitles: List<SubtitleData>,
val apiName: String,
val isMovie: Boolean,
val title: String?,
val poster: String?,
val currentEpisodeIndex: Int,
val episodes: List<ResultEpisode>,
val currentLinks: List<ExtractorLink>,
val currentSubtitles: List<SubtitleData>
)
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<ListView>(R.id.sort_providers)!!
val subtitleList = bottomSheetDialog.findViewById<ListView>(R.id.sort_subtitles)!!
// bottomSheetDialog.setContentView(R.layout.sort_bottom_sheet)
val providerList =
bottomSheetDialog.findViewById<ListView>(R.id.sort_providers)!!
val subtitleList =
bottomSheetDialog.findViewById<ListView>(R.id.sort_subtitles)!!
if (subTracks.isEmpty()) {
bottomSheetDialog.findViewById<LinearLayout>(R.id.sort_subtitles_holder)?.visibility = GONE
bottomSheetDialog.findViewById<LinearLayout>(R.id.sort_subtitles_holder)?.visibility =
GONE
} else {
val arrayAdapter = ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
val arrayAdapter =
ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
arrayAdapter.add(view.context.getString(R.string.no_subtitles))
arrayAdapter.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<String>(view.context, R.layout.sort_bottom_single_choice)
val arrayAdapter =
ArrayAdapter<String>(view.context, R.layout.sort_bottom_single_choice)
arrayAdapter.addAll(sortingMethods.toMutableList())
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<MetadataHolder>(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<ExtractorLink>()
val currentSubs = mutableSetOf<SubtitleData>()
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 {

View file

@ -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<Any>) {
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

View file

@ -41,10 +41,6 @@ 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 +56,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 +100,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,12 +166,11 @@ 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)
@ -206,7 +195,7 @@ object AccountHelper {
R.string.edit_profile_image_success,
Toast.LENGTH_SHORT
)
dialog.dismissSafe()
bottomSheetDialog.dismissSafe()
},
onError = { _, _ ->
showToast(
@ -223,7 +212,7 @@ object AccountHelper {
imageLoader.enqueue(request)
}
sheetBinding.cancelBtt.setOnClickListener {
dialog.dismissSafe()
bottomSheetDialog.dismissSafe()
}
}
}
@ -368,11 +357,6 @@ object AccountHelper {
fun Activity?.showAccountSelectLinear() {
val activity = this as? MainActivity ?: return
activity.navigate(
R.id.accountSelectActivity,
Bundle().apply { putBoolean(AccountSelectActivity2.IS_FROM_MAIN_ACTIVITY, true) }
)
/*
val viewModel = ViewModelProvider(activity)[AccountViewModel::class.java]
val binding: AccountSelectLinearBinding = AccountSelectLinearBinding.inflate(
@ -430,6 +414,6 @@ object AccountHelper {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
layoutManager.scrollToPositionWithOffset(selectedKeyIndex, 0)
}
}*/
}
}
}

View file

@ -1,872 +0,0 @@
package com.lagradost.cloudstream3.ui.account
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component2
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import coil3.compose.AsyncImage
import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.Account
import com.lagradost.cloudstream4.compose.ActionDialog
import com.lagradost.cloudstream4.compose.BlackButton
import com.lagradost.cloudstream4.compose.BlackTextField
import com.lagradost.cloudstream4.compose.EMULATOR
import com.lagradost.cloudstream4.compose.PHONE
import com.lagradost.cloudstream4.compose.RoundedShape
import com.lagradost.cloudstream4.compose.TV
import com.lagradost.cloudstream4.compose.WhiteButton
import com.lagradost.cloudstream4.compose.circle
import com.lagradost.cloudstream4.compose.circleBorder
import com.lagradost.cloudstream4.compose.focusOutline
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.compose.rounded
import com.lagradost.cloudstream4.compose.whiteOutline
import com.lagradost.cloudstream4.state.SearchableData
import com.lagradost.cloudstream4.state.sortByInt
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
import com.mihon.material.padding
import com.mihon.presentation.settings.widget.SwitchPreferenceWidget
import com.mihon.presentation.settings.widget.TextPreferenceWidget
import kotlinx.collections.immutable.toPersistentMap
@PreviewLightDark
@Composable
fun Preview() {
CloudStreamPreviewTheme {
AccountScreen.Content(
state = AccountState(
canEditAccount = false,
editAccount = Account(
keyIndex = 1,
name = "Hello world",
defaultImageIndex = 2,
lockPin = "1234"
),
accounts = SearchableData.from(
data =
(0..7).associateWith { index ->
Account(
keyIndex = index,
name = "hello $index",
defaultImageIndex = index,
lockPin = if (index % 2 == 1) {
"1234"
} else {
null
}
)
}.toPersistentMap(),
sortedBy = sortByInt { it.keyIndex },
),
), onAction = {})
}
}
object AccountScreen {
@Composable
fun Content(
state: AccountState,
onAction: (AccountAction) -> Unit
) {
if (state.editAccount != null) {
EditAccountDialog(
exists = state.accounts.data.containsKey(state.editAccount.keyIndex),
account = state.editAccount,
onAction = onAction
)
}
Scaffold { contentPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
horizontalAlignment = Alignment.End
) {
val (edit, accounts) = remember { FocusRequester.createRefs() }
IconButton(
onClick = {
onAction(AccountAction.SetEditMode(!state.canEditAccount))
}, modifier = Modifier
.focusRequester(edit)
.focusProperties {
down = accounts
}
.focusOutline(shape = CircleShape)
) {
Icon(
painter = if (state.canEditAccount) {
painterResource(R.drawable.close_24px)
} else {
painterResource(R.drawable.edit_24px)
},
contentDescription = stringResource(R.string.manage_accounts)
)
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = if (state.canEditAccount) stringResource(R.string.manage_accounts) else stringResource(
R.string.select_an_account
),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
modifier = Modifier.padding(MaterialTheme.padding.large)
)
AccountsRow(
state = state, onAction = onAction,
modifier = Modifier
.focusRequester(accounts)
.focusProperties {
up = edit
})
Spacer(modifier = Modifier.height(100.dp))
}
}
}
}
enum class WaitForDialogType {
RemoveLock,
NewPassword,
DeleteAccount,
NewProfileUrl,
NewProfilePicture,
Login,
}
@Composable
fun WaitForDialog(
type: WaitForDialogType,
onDismissRequest: () -> Unit,
account: Account,
onAction: (AccountAction) -> Unit
) {
when (type) {
WaitForDialogType.RemoveLock -> {
if (account.lockPin != null) {
EnterPinDialog(
expected = account.lockPin,
onDismissRequest = onDismissRequest,
onCorrect = {
onAction(AccountAction.EditAccount(account.copy(lockPin = null)))
}
)
}
}
WaitForDialogType.Login -> {
if (account.lockPin != null) {
EnterPinDialog(
expected = account.lockPin,
onDismissRequest = onDismissRequest,
onCorrect = {
onAction(AccountAction.SaveAccount(account))
onAction(AccountAction.EditAccount(null))
}
)
}
}
WaitForDialogType.NewPassword -> {
SetPinDialog(
onDismissRequest = onDismissRequest,
onSet = { newLockPin ->
onAction(AccountAction.EditAccount(account.copy(lockPin = newLockPin)))
})
}
WaitForDialogType.DeleteAccount -> {
ActionDialog(
title = stringResource(R.string.delete),
text = stringResource(R.string.delete_message, account.name),
confirm = {
onAction(AccountAction.DeleteAccount(account.keyIndex))
onAction(AccountAction.EditAccount(null))
onDismissRequest()
},
dismiss = onDismissRequest,
confirmText = stringResource(R.string.delete),
dismissText = stringResource(R.string.cancel)
)
}
WaitForDialogType.NewProfilePicture -> {
SetPictureDialog(
account = account,
onDismissRequest = onDismissRequest,
onSet = { newImage ->
onAction(
AccountAction.EditAccount(
account.copy(
defaultImageIndex = newImage,
customImage = null
)
)
)
onDismissRequest()
})
}
WaitForDialogType.NewProfileUrl -> {
SetUrlDialog(onDismissRequest = onDismissRequest, onSet = { newImage ->
onAction(AccountAction.EditAccount(account.copy(customImage = newImage)))
onDismissRequest()
})
}
}
}
@Composable
fun EditAccountDialog(
exists: Boolean,
account: Account,
onAction: (AccountAction) -> Unit
) {
val selectFileSelector =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
// It lies, it can be null if file manager quits.
if (uri == null) return@rememberLauncherForActivityResult
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
try {
context.contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
onAction(AccountAction.EditAccount(account = account.copy(customImage = uri.toString())))
} catch (t: Throwable) {
logError(t)
}
}
var pendingDialog by remember { mutableStateOf<WaitForDialogType?>(null) }
pendingDialog?.let { waitType ->
WaitForDialog(
type = waitType,
onDismissRequest = { pendingDialog = null },
account = account,
onAction = onAction
)
}
val focusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
val isTv = isLayout(TV)
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
confirmButton = {
if (exists) {
WhiteButton(text = stringResource(R.string.delete)) {
pendingDialog = WaitForDialogType.DeleteAccount
}
}
WhiteButton(text = stringResource(R.string.sort_apply)) {
if (account.lockPin == null) {
onAction(AccountAction.SaveAccount(account))
onAction(AccountAction.EditAccount(null))
} else {
pendingDialog = WaitForDialogType.Login
}
}
},
dismissButton = {
BlackButton(
text = stringResource(R.string.cancel),
modifier = Modifier.focusRequester(focusRequester)
) {
onAction(AccountAction.EditAccount(null))
}
},
onDismissRequest = {
/**
* For UX reasons we can only dismiss it with the cancel button,
* but does not have those issues
* */
if (isTv) {
onAction(AccountAction.EditAccount(null))
}
},
text = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.verticalScroll(rememberScrollState())
) {
AccountImage(
selected = false,
edit = false,
account = account,
onClick = {
onAction(
AccountAction.EditAccount(
account.copy(
customImage = null,
defaultImageIndex = (account.defaultImageIndex + 1) % DataStoreHelper.profileImages.size
)
)
)
},
onLongClick = {})
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
BlackTextField(
modifier = Modifier.fillMaxWidth(),
value = account.name,
onValueChange = { newText ->
val newName = if (newText.length <= 100) {
newText
} else {
newText.substring(0, 100)
}
onAction(
AccountAction.EditAccount(
account.copy(
name = newName
)
)
)
},
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.PersonName,
),
placeHolder = stringResource(R.string.name)
)
var selectProfileImage by remember { mutableStateOf(false) }
TextPreferenceWidget(
modifier = Modifier
.rounded()
.focusOutline(),
title = stringResource(R.string.edit_profile_image_title),
widget = {
Icon(
painter = painterResource(R.drawable.add_photo_alternate_24px),
contentDescription = null
)
DropdownMenu(expanded = selectProfileImage, onDismissRequest = {
selectProfileImage = false
}, shape = RoundedShape()) {
DropdownMenuItem(
text = { Text(text = stringResource(R.string.edit_profile_image_url)) },
onClick = {
pendingDialog = WaitForDialogType.NewProfileUrl
selectProfileImage = false
}
)
DropdownMenuItem(
text = { Text(text = stringResource(R.string.edit_profile_image_picker)) },
onClick = {
selectFileSelector.launch(arrayOf("image/*"))
selectProfileImage = false
}
)
DropdownMenuItem(
text = { Text(text = stringResource(R.string.edit_profile_image_default)) },
onClick = {
pendingDialog = WaitForDialogType.NewProfilePicture
selectProfileImage = false
}
)
}
},
onPreferenceClick = {
selectProfileImage = true
}
)
if (account.keyIndex != 0) {
SwitchPreferenceWidget(
modifier = Modifier
.rounded()
.focusOutline(),
title = stringResource(R.string.lock_profile),
checked = account.lockPin != null,
onCheckedChanged = {
pendingDialog = if (account.lockPin == null) {
WaitForDialogType.NewPassword
} else {
WaitForDialogType.RemoveLock
}
})
}
}
}
)
}
@Composable
fun AccountsRow(
state: AccountState,
onAction: (AccountAction) -> Unit,
modifier: Modifier = Modifier,
) {
FlowRow(
modifier = modifier.focusGroup(),
horizontalArrangement = Arrangement.spacedBy(
MaterialTheme.padding.medium,
alignment = Alignment.Start
),
verticalArrangement = Arrangement.spacedBy(
MaterialTheme.padding.medium,
alignment = Alignment.CenterVertically
),
) {
state.accounts.sorted.forEach { key ->
val account = state.accounts.data[key]!!
Account(
edit = state.canEditAccount,
account = account,
onAction = onAction,
selected = state.lastLoginKeyIndex == account.keyIndex
)
}
var hasFocus by remember { mutableStateOf(false) }
val size = 100.dp
val innerPadding by animateDpAsState(
targetValue = if (hasFocus || isLayout(PHONE or EMULATOR)) 0.dp else MaterialTheme.padding.extraSmall,
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.width(size)
.onFocusChanged { newFocus ->
hasFocus = newFocus.hasFocus
}
) {
val interactionSource = remember { MutableInteractionSource() }
Box(
modifier = Modifier
.clickable(interactionSource = interactionSource, indication = null) {
onAction(AccountAction.NewAccount)
}
.size(size)
.padding(innerPadding)
.border(
2.dp,
MaterialTheme.colorScheme.onBackground.copy(alpha = 0.2f),
CircleShape
)
.circle()
.background(MaterialTheme.colorScheme.surfaceVariant)
.whiteOutline(hasFocus = hasFocus, shape = CircleShape)
.indication(
interactionSource = interactionSource,
indication = ripple()
),
contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(R.drawable.add_24px),
contentDescription = stringResource(R.string.add_account),
tint = MaterialTheme.colorScheme.onBackground,
modifier = Modifier.size(36.dp)
)
}
Spacer(Modifier.height(MaterialTheme.padding.small))
Text(
text = stringResource(R.string.add_account),
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
)
}
}
}
@Composable
fun PinTextField(value: String, onValueChange: (String) -> Unit) {
BlackTextField(
value = value, keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done,
autoCorrectEnabled = false,
keyboardType = KeyboardType.NumberPassword,
), placeHolder = stringResource(R.string.pin), onValueChange = onValueChange
)
}
@Composable
fun EnterPinDialog(expected: String, onDismissRequest: (() -> Unit), onCorrect: (() -> Unit)) {
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = onDismissRequest,
confirmButton = {},
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
},
text = {
var inputText by remember { mutableStateOf("") }
var hasError by remember { mutableStateOf(false) }
Column {
PinTextField(
value = inputText,
onValueChange = { newText ->
if (newText.length == expected.length) {
if (newText == expected) {
onCorrect()
onDismissRequest()
} else {
inputText = ""
hasError = true
}
} else {
inputText = newText
}
},
)
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
if (hasError) {
Text(text = stringResource(R.string.pin_error_incorrect))
}
}
},
title = {
Text(text = stringResource(R.string.enter_pin))
})
}
@Composable
fun SetPinDialog(onDismissRequest: (() -> Unit), onSet: ((String) -> Unit)) {
var inputText by remember { mutableStateOf("") }
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = onDismissRequest,
confirmButton = {
if (inputText.length == 4) {
WhiteButton(
text = stringResource(R.string.sort_apply),
onClick = {
onSet(inputText)
onDismissRequest()
})
}
},
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
},
text = {
PinTextField(
value = inputText,
onValueChange = { newText ->
/**
* We require isDigit for SetPin,
* but do not for the EnterPin to avoid inaccessable accounts
* */
val newTextFilter = if (newText.all(Char::isDigit)) {
newText
} else {
newText.filter(Char::isDigit)
}
inputText = if (newTextFilter.length <= 4) {
newTextFilter
} else {
newTextFilter.substring(0, 4)
}
},
)
},
title = {
Text(text = stringResource(R.string.enter_pin))
})
}
@Composable
fun SetUrlDialog(onDismissRequest: (() -> Unit), onSet: ((String) -> Unit)) {
var inputText by remember { mutableStateOf("") }
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = onDismissRequest,
confirmButton = {
WhiteButton(
text = stringResource(R.string.sort_apply),
onClick = {
onSet(inputText)
onDismissRequest()
})
},
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
},
text = {
BlackTextField(
value = inputText,
onValueChange = { newText ->
inputText = newText
},
placeHolder = stringResource(R.string.edit_profile_image_hint)
)
},
title = {
Text(text = stringResource(R.string.edit_profile_image_title))
})
}
@Composable
fun SetPictureDialog(
account: Account,
onDismissRequest: (() -> Unit),
onSet: ((Int) -> Unit)
) {
AlertDialog(
properties = DialogProperties(usePlatformDefaultWidth = false),
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = onDismissRequest,
confirmButton = { },
dismissButton = {
BlackButton(text = stringResource(R.string.cancel), onClick = onDismissRequest)
},
text = {
FlowRow(
modifier = Modifier.focusGroup(),
horizontalArrangement = Arrangement.spacedBy(
MaterialTheme.padding.medium,
alignment = Alignment.Start
),
verticalArrangement = Arrangement.spacedBy(
MaterialTheme.padding.medium,
alignment = Alignment.CenterVertically
),
) {
for (i in DataStoreHelper.profileImages.indices) {
AccountImage(
edit = false,
showName = false,
selected = account.defaultImageIndex == i,
account = account.copy(
customImage = null,
defaultImageIndex = i,
lockPin = null
),
onClick = {
onSet(i)
},
onLongClick = {})
}
}
},
title = {
Text(text = stringResource(R.string.edit_profile_image_title))
})
}
@Composable
fun AccountImage(
/** If we should show the edit pen */
edit: Boolean,
/** If this element should have focus */
selected: Boolean,
/** If we should show the name under the picture */
showName: Boolean = true,
account: Account,
onClick: () -> Unit,
onLongClick: () -> Unit
) {
val image = account.customImage
?: DataStoreHelper.profileImages[account.defaultImageIndex % DataStoreHelper.profileImages.size]
val interactionSource = remember { MutableInteractionSource() }
var hasFocus by remember { mutableStateOf(false) }
val size = 100.dp
val innerPadding by animateDpAsState(
targetValue = if (hasFocus || isLayout(PHONE or EMULATOR)) 0.dp else MaterialTheme.padding.extraSmall,
)
val focusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
if (selected) {
focusRequester.requestFocus()
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.width(size)
.focusRequester(focusRequester)
.onFocusChanged { newFocus ->
hasFocus = newFocus.hasFocus
}
) {
Box(
modifier = Modifier
.size(size)
.combinedClickable(
interactionSource = interactionSource,
indication = null,
onClick = onClick,
onLongClick = onLongClick
)
.padding(innerPadding),
contentAlignment = Alignment.Center
) {
AsyncImage(
model = image,
modifier = Modifier
.circleBorder(size)
.whiteOutline(hasFocus = hasFocus, shape = CircleShape)
.indication(interactionSource = interactionSource, indication = ripple()),
contentDescription = account.name,
contentScale = ContentScale.Crop,
alpha = if (edit) {
0.6f
} else {
1.0f
}
)
if (account.lockPin != null) {
Box(
contentAlignment = Alignment.TopEnd, modifier = Modifier
.fillMaxSize()
.padding(
MaterialTheme.padding.extraSmall
)
) {
Icon(
painter = painterResource(R.drawable.video_locked),
contentDescription = null,
tint = MaterialTheme.colorScheme.onBackground,
modifier = Modifier
.size(22.dp + MaterialTheme.padding.extraSmall * 2)
.background(
MaterialTheme.colorScheme.surfaceVariant,
shape = CircleShape
)
.padding(MaterialTheme.padding.extraSmall)
)
}
}
this@Column.AnimatedVisibility(
visible = edit,
enter = fadeIn(),
exit = fadeOut()
) {
Icon(
painter = painterResource(R.drawable.edit_24px),
contentDescription = null,
tint = MaterialTheme.colorScheme.onBackground,
modifier = Modifier.size(36.dp),
)
}
}
if (showName) {
Spacer(Modifier.height(MaterialTheme.padding.small))
Text(
text = account.name,
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
@Composable
fun Account(
edit: Boolean,
selected: Boolean,
account: Account,
onAction: (AccountAction) -> Unit
) {
var waitForLock by remember { mutableStateOf(false) }
if (waitForLock && account.lockPin != null) {
EnterPinDialog(
expected = account.lockPin,
onDismissRequest = {
waitForLock = false
}, onCorrect = {
onAction(AccountAction.LoginWithAccount(account.keyIndex))
})
}
AccountImage(selected = selected, edit = edit, account = account, onClick = {
if (edit) {
onAction(AccountAction.EditAccount(account))
} else if (account.lockPin != null) {
waitForLock = true
} else {
onAction(AccountAction.LoginWithAccount(account.keyIndex))
}
}, onLongClick = {
/** Long click -> edit without having to press the edit button for better UX */
onAction(AccountAction.EditAccount(account))
})
}
}

View file

@ -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 ->

View file

@ -1,180 +0,0 @@
package com.lagradost.cloudstream3.ui.account
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.CommonActivity.loadThemes
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.utils.BiometricAuthenticator
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.BiometricCallback
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.biometricPrompt
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.deviceHasPasswordPinLock
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.promptInfo
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.startBiometricAuthentication
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.Account
import com.lagradost.cloudstream3.utils.UIHelper.enableEdgeToEdgeCompat
import com.lagradost.cloudstream3.utils.UIHelper.openActivity
import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
import com.lagradost.cloudstream4.AppSettings
import com.lagradost.cloudstream4.compose.CloudStreamThemeAppSettings
import com.lagradost.cloudstream4.state.SearchableData
import com.lagradost.cloudstream4.state.sortByInt
import kotlinx.collections.immutable.persistentMapOf
class AccountSelectActivity2 : FragmentActivity(), BiometricCallback {
companion object {
var hasLoggedIn: Boolean = false
const val IS_FROM_MAIN_ACTIVITY = "isFromMainActivity"
const val IS_EDITING_FROM_MAIN_ACTIVITY = "isEditingFromMainActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Are we editing and coming from MainActivity?
val isEditingFromMainActivity = intent.getBooleanExtra(IS_EDITING_FROM_MAIN_ACTIVITY, false)
// Are we invoked from the main activity to edit it?
val isFromMainActivity = intent.getBooleanExtra(IS_FROM_MAIN_ACTIVITY, false)
/**
* Sometimes we start this activity when we have already logged in
* For example when using cloudstreamsearch://
*
* In those cases we want to just go to the main activity instantly
**/
if (hasLoggedIn && !isEditingFromMainActivity && !isFromMainActivity) {
navigateToMainActivity()
return
}
/**
* Here we set the themes, this *can* be deferred for faster instant login,
* but has some consequences that makes it undesirable even if it is slower
*
* CommonActivity.init : loads the correct locale for default_account
* loadThemes : loads the correct color on the toast when logging in
* */
CommonActivity.init(this)
loadThemes(this)
enableEdgeToEdgeCompat()
setNavigationBarColorCompat(R.attr.primaryBlackBackground)
/**
* To avoid touching the UI layer, we use the raw state before the viewmodel is created
* to enable us to skip account selection but still use the ergonomics of AccountState
* */
val defaultName = getString(R.string.default_account)
val defaultAccount = Account(
keyIndex = 0,
name = defaultName,
defaultImageIndex = 0,
)
val initialState = AccountState(
canEditAccount = isEditingFromMainActivity,
lastLoginKeyIndex = DataStoreHelper.selectedKeyIndex,
accounts = SearchableData.from(
/** We must always have a default account
* even if DataStoreHelper.accounts.size = 0 */
data = persistentMapOf(defaultAccount.keyIndex to defaultAccount)
.puttingAll(DataStoreHelper.accounts.associateBy { it.keyIndex }),
sortedBy = sortByInt { it.keyIndex }
)
)
val settings = AppSettings(this)
val skipAccountSelection = settings.security.skipAccountSelection.get()
/** Don't show account selection if there is only one account that exists */
if (
!isFromMainActivity &&
!isEditingFromMainActivity &&
(skipAccountSelection || initialState.accounts.data.size == 1)
) {
/** We must have an account without a pin */
val currentAccount = initialState.accounts.data[initialState.lastLoginKeyIndex]
if (
currentAccount != null &&
currentAccount.lockPin == null
) {
/**
* Show toast if we have many accounts,
* as it is unnecessary for 1 account
* */
DataStoreHelper.setAccount(
currentAccount,
showToast = initialState.accounts.data.size > 1
)
/**
* We avoid using the viewmodel Login as we
* can return *before* we load Compose code!
* */
navigateToMainActivity()
return
}
}
/**
* If this app is locked with biometrics,
* then require that on a startup that is not skipped!
* */
if (
!isFromMainActivity &&
!isEditingFromMainActivity &&
isLayout(PHONE) &&
settings.security.biometrics.get() &&
deviceHasPasswordPinLock(this)
) {
startBiometricAuthentication(
this,
R.string.biometric_authentication_title,
false
)
promptInfo?.let { prompt ->
biometricPrompt?.authenticate(prompt)
}
}
setContent {
val viewModel = viewModel<AccountViewModel2> {
AccountViewModel2(
defaultAccount = defaultAccount,
initialState = initialState
)
}
val state by viewModel.state.collectAsState()
if (state.loggedInWith != null) {
navigateToMainActivity()
}
CloudStreamThemeAppSettings {
AccountScreen.Content(state, viewModel::onAction)
}
}
}
@SuppressLint("UnsafeIntentLaunch")
private fun navigateToMainActivity() {
hasLoggedIn = true
// We want to propagate any intent we get here to MainActivity since this is just an intermediary
openActivity(MainActivity::class.java, baseIntent = intent)
finish() // Finish the account selection activity
}
override fun onAuthenticationSuccess() {
Log.i(BiometricAuthenticator.TAG, "Authentication successful in AccountSelectActivity")
}
override fun onAuthenticationError() {
finish()
}
}

View file

@ -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
}
}

View file

@ -1,141 +0,0 @@
package com.lagradost.cloudstream3.ui.account
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKeys
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream4.state.ActionHandler
import com.lagradost.cloudstream4.state.DefaultStateContainer
import com.lagradost.cloudstream4.state.SearchableData
import com.lagradost.cloudstream4.state.StateContainer
import com.lagradost.cloudstream4.state.sortByInt
import kotlinx.collections.immutable.persistentMapOf
import kotlin.random.Random
import kotlin.random.nextInt
@Immutable
data class AccountState(
/** Mostly used for focus stuff on TV */
val lastLoginKeyIndex : Int = 0,
/** Is currently open to editing */
val canEditAccount: Boolean = false,
/** keyIndex -> DataStoreHelper.Account sorted by keyIndex as keyIndex is unique and in add order */
val accounts: SearchableData<Int, DataStoreHelper.Account> = SearchableData.from(
data = persistentMapOf(),
/** This will cause bugs if changed! */
sortedBy = sortByInt { it.keyIndex }
),
/**
* We are currectly editing this account with this value, it may be an existing/new account
* non-null = editing, null = not editing
* */
val editAccount: DataStoreHelper.Account? = null,
/** We are currently logged in with this account, we use state instead of effect to prevent bugs */
val loggedInWith: Int? = null
)
@Immutable
sealed class AccountAction {
data class SetEditMode(val canEditAccount: Boolean) : AccountAction()
object NewAccount : AccountAction()
data class EditAccount(val account: DataStoreHelper.Account?) : AccountAction()
data class SaveAccount(val account: DataStoreHelper.Account) : AccountAction()
data class LoginWithAccount(val accountKeyIndex: Int) : AccountAction()
data class DeleteAccount(val accountKeyIndex: Int) : AccountAction()
}
class AccountViewModel2(
val defaultAccount: DataStoreHelper.Account,
initialState : AccountState,
) : ViewModel(), StateContainer<AccountState> by DefaultStateContainer(initialState), ActionHandler<AccountAction> {
fun updateAccount(
updater: (SearchableData<Int, DataStoreHelper.Account>) -> SearchableData<Int, DataStoreHelper.Account>
) {
updateState {
/** `adding` has will "Replace" on same key, and "Add" on a new key */
val newAccounts = updater(accounts)
DataStoreHelper.accounts =
Array(newAccounts.sorted.size) { i ->
/** i -> keyIndex -> Account; As keyIndex != index */
newAccounts.data[newAccounts.sorted[i]]!!
}
copy(accounts = newAccounts)
}
MainActivity.reloadAccountEvent(true)
}
override fun onAction(action: AccountAction) {
when (action) {
is AccountAction.SetEditMode -> {
updateState { copy(canEditAccount = action.canEditAccount) }
}
is AccountAction.NewAccount -> {
updateState {
copy(
editAccount = DataStoreHelper.Account(
/** Last => maxOf, this WILL break if we allow other sorting orders */
keyIndex = (accounts.sorted.lastOrNull() ?: 0) + 1,
/** This is not "translated", but that should not really be a problem */
name = "Account ${accounts.data.size + 1}",
customImage = null,
defaultImageIndex = Random.nextInt(DataStoreHelper.profileImages.indices),
lockPin = null,
)
)
}
}
is AccountAction.DeleteAccount -> {
removeKeys(action.accountKeyIndex.toString())
/** If we remove the logged in account,
* then we switch to the default account */
if (action.accountKeyIndex == DataStoreHelper.selectedKeyIndex) {
val nextAccount = state.value.accounts.data[defaultAccount.keyIndex]
/** This should never be non-null, but just in case! */
?: defaultAccount
DataStoreHelper.setAccount(nextAccount)
updateState { copy(lastLoginKeyIndex = nextAccount.keyIndex) }
}
updateAccount { accounts ->
val pendingAccounts = accounts.removing(action.accountKeyIndex)
/** We must always have a default account */
if (pendingAccounts.data.containsKey(defaultAccount.keyIndex)) {
pendingAccounts
} else {
pendingAccounts.adding(defaultAccount.keyIndex, defaultAccount)
}
}
}
is AccountAction.SaveAccount -> {
updateAccount { accounts ->
/** `adding` has will "Replace" on same key, and "Add" on a new key */
accounts.adding(action.account.keyIndex, action.account)
}
}
is AccountAction.LoginWithAccount -> {
val accounts = state.value.accounts
val loginAccount = accounts.data[action.accountKeyIndex] ?: return
// Show toast if we have many accounts, as it is unnecessary for 1 account
DataStoreHelper.setAccount(loginAccount, showToast = accounts.data.size > 1)
MainActivity.reloadAccountEvent(true)
updateState { copy(loggedInWith = loginAccount.keyIndex, lastLoginKeyIndex = loginAccount.keyIndex) }
}
is AccountAction.EditAccount -> {
updateState { copy(editAccount = action.account) }
}
}
}
}

View file

@ -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<Set<Int>?>(null)
val selectedItemIds: LiveData<Set<Int>?> = _selectedItemIds
init {
// Keep the Downloads list in sync when a download is deleted/cancelled from
// anywhere in the app (result page button, queue, notification, etc.). See
// onDownloadDeleted for the rationale (issue #1227).
downloadDeleteEvent += ::onDownloadDeleted
}
override fun onCleared() {
downloadDeleteEvent -= ::onDownloadDeleted
super.onCleared()
}
fun cancelSelection() {
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<VisualDownloadCached.Header>) {
try {
val stat = StatFs(Environment.getExternalStorageDirectory().path)
@ -609,4 +584,4 @@ class DownloadViewModel : ViewModel() {
val names: List<String>,
val parentName: String?
)
}
}

View file

@ -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<Int, VideoDownloadManager.DownloadActionType>) {
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

View file

@ -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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
.inflate(R.layout.sort_bottom_single_provider_choice, parent, false)
val titleText = view.findViewById<TextView>(R.id.text1)
val pinIcon = view.findViewById<ImageView>(R.id.pinicon)
val settingsIcon = view.findViewById<ImageView>(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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
fromUI = true
)
showToast(R.string.action_reload, Toast.LENGTH_SHORT)
true
}
homePreviewSearchButton.setOnClickListener { _ ->
@ -715,38 +673,6 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
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<FragmentHomeBinding>(
}*/
}
private fun updateTvRailFocus() {
if (!isLayout(TV or EMULATOR)) return
// home_api_holder is glued to the header row's top by the mirror logic in
// the scroll listener above. Only target the provider button while the
// holder is actually on screen; once the header scrolls off (y < 0) let
// the rail fall back to default focus search so RIGHT enters content rows
val holder = binding?.homeApiHolder
val target =
if (holder != null && holder.isVisible && holder.y >= 0f) R.id.home_change_api
else View.NO_ID
val rail = activity?.findViewById<View>(R.id.nav_rail_view) ?: return
rail.nextFocusRightId = target
for (focusView in arrayOf(
R.id.navigation_downloads,
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_library,
R.id.navigation_settings,
)) {
rail.findViewById<View>(focusView)?.nextFocusRightId = target
}
}
private fun handleTvBackPress(helper: BackPressedCallbackHelper.CallbackHelper) {
// Only apply custom behavior on TV interface
if (!isLayout(TV)) {

View file

@ -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)
}

View file

@ -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)
}
}
}
}
}

View file

@ -46,9 +46,7 @@ import androidx.media3.exoplayer.DecoderCounters
import androidx.media3.exoplayer.DecoderReuseEvaluation
import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.Renderer.STATE_ENABLED
import androidx.media3.exoplayer.Renderer.STATE_STARTED
@ -110,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
@ -164,14 +161,6 @@ class CS3IPlayer : IPlayer {
private var ignoreSSL: Boolean = true
private var playBackSpeed: Float = 1.0f
/**
* Shared compressor instance — only created when the setting is enabled.
* When disabled, this stays null and the audio pipeline is completely
* unmodified (no custom AudioProcessor, no custom AudioSink at all).
*/
var compressor: DynamicRangeCompressor? = null
private set
private var lastMuteVolume: Float = 1.0f
private var currentLink: ExtractorLink? = null
@ -730,7 +719,7 @@ class CS3IPlayer : IPlayer {
**/
var preferredAudioTrackLanguage: String? = null
get() {
return field ?: getKey<String>(
return field ?: getKey(
"$currentAccount/$PREFERRED_AUDIO_LANGUAGE_KEY",
field
)?.also {
@ -1120,17 +1109,8 @@ class CS3IPlayer : IPlayer {
else -> isLayout(PHONE or EMULATOR) to false
}
// Only create the compressor when the setting is actually enabled.
// When it's off, `compressor` stays null and nothing about the audio
// pipeline is touched — same behaviour as before this feature existed.
val isCompressorEnabled = settingsManager.getBoolean(
context.getString(R.string.compressor_enabled_key),
false
)
compressor = if (isCompressorEnabled) DynamicRangeCompressor().apply { restoreSavedSettings() } else null
val factory = if (isSoftwareDecodingEnabled) {
FixedNextRenderersFactory(context, compressor).apply {
FixedNextRenderersFactory(context).apply {
setEnableDecoderFallback(true)
setExtensionRendererMode(
if (isSoftwareDecodingPreferred)
@ -1140,24 +1120,8 @@ class CS3IPlayer : IPlayer {
)
}
} else {
val activeCompressor = compressor
if (activeCompressor == null) {
// no nextlib = EXTENSION_RENDERER_MODE_OFF, no compressor = fully default sink
DefaultRenderersFactory(context)
} else {
object : DefaultRenderersFactory(context) {
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
override fun buildAudioSink(
ctx: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean
) = DefaultAudioSink.Builder(ctx)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioOutputPlaybackParameters(enableAudioTrackPlaybackParams)
.setAudioProcessors(arrayOf<AudioProcessor>(activeCompressor))
.build()
}
}
// no nextlib = EXTENSION_RENDERER_MODE_OFF
DefaultRenderersFactory(context)
}
val style = CustomDecoder.style
@ -1425,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(
@ -1447,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,

View file

@ -1,266 +0,0 @@
package com.lagradost.cloudstream3.ui.player
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.util.UnstableApi
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.pow
/**
* A dynamic range compressor for the audio player.
*
* ## What it does
* A dynamic range compressor automatically turns down loud sounds and turns up
* quiet ones, narrowing the gap between the loudest and quietest moments.
* This is useful for watching movies or TV shows where action/explosion scenes
* are very loud but dialogue scenes are very quiet — the compressor brings
* everything to a more comfortable, even volume.
*
* ## Algorithm
* Implements a standard single-band feed-forward peak compressor using a
* 1-pole IIR envelope follower. This is the same algorithm used in most
* audio software (Audacity, VLC, etc.) and is well-established DSP. It is
* NOT a port or derivative of any specific implementation — the math is
* standard and covered extensively in audio engineering literature
* (e.g. Zölzer "Digital Audio Signal Processing").
*
* Uses a single shared envelope across all channels so left and right always
* receive identical gain — independent per-channel envelopes would destroy
* the stereo image.
*
* Handles both PCM_16BIT and PCM_FLOAT (both are used by ExoPlayer depending
* on the source and device). Always stays "active" in the pipeline so that
* enable/disable works instantly without reloading the player — when disabled,
* samples are copied unchanged (passthrough).
*/
internal const val COMPRESSOR_ENABLED_KEY = "player_compressor_enabled"
internal const val COMPRESSOR_THRESHOLD_KEY = "player_compressor_threshold"
internal const val COMPRESSOR_RATIO_KEY = "player_compressor_ratio"
internal const val COMPRESSOR_ATTACK_KEY = "player_compressor_attack"
internal const val COMPRESSOR_RELEASE_KEY = "player_compressor_release"
internal const val COMPRESSOR_MAKEUP_KEY = "player_compressor_makeup"
@OptIn(UnstableApi::class)
class DynamicRangeCompressor : AudioProcessor {
@Volatile var enabled: Boolean = false
/**
* The level (in dB) above which compression kicks in. Signals quieter than
* this pass through unchanged; louder signals get compressed.
* Lower = compresses more content (including quieter sounds like dialogue).
* -24 dB is a good starting point for movies: it catches action peaks
* while leaving quiet dialogue mostly untouched before makeup gain.
*/
@Volatile var threshold: Float = -24f // dB, range -30..0
/**
* How aggressively to compress sounds that exceed the threshold.
* A ratio of 8:1 means an 8 dB increase above the threshold becomes only
* 1 dB in the output. Higher = more "squashed" dynamic range.
* Below ~2 is barely noticeable; above ~10 sounds very processed/radio-like.
*/
@Volatile var ratio: Float = 8f // n:1, range 1..20
/**
* How quickly (in ms) the compressor clamps down when a loud sound starts.
* Too low (< 1 ms): no transient punch, sounds dull.
* Too high (> 50 ms): loud transients slip through before gain reduces.
* 5 ms preserves punch while still catching most action scene peaks.
*/
@Volatile var attackMs: Float = 5f // ms, range 1..400
/**
* How quickly (in ms) the compressor lets go after a loud sound ends.
* Too low (< 50 ms): audible "pumping" — volume visibly breathes up/down.
* Too high (> 800 ms): gain stays low too long, quieter sounds after
* an action scene stay suppressed for a noticeable time.
* 400 ms is slow enough to be transparent on most movie content.
*/
@Volatile var releaseMs: Float = 400f // ms, range 2..800
/**
* Output gain (in dB) applied after compression.
* Compression reduces overall loudness so makeup gain brings it back up.
* +12 dB compensates for the typical reduction at a 8:1 ratio with a
* -24 dB threshold, and also lifts quiet dialogue to a more audible level.
* Too high risks clipping on uncompressed peaks below the threshold.
*/
@Volatile var makeupGain: Float = 12f // dB, range 0..24
fun restoreSavedSettings() {
enabled = getKey<Boolean>(COMPRESSOR_ENABLED_KEY) ?: false
threshold = getKey<Float>(COMPRESSOR_THRESHOLD_KEY) ?: -24f
ratio = getKey<Float>(COMPRESSOR_RATIO_KEY) ?: 8f
attackMs = getKey<Float>(COMPRESSOR_ATTACK_KEY) ?: 5f
releaseMs = getKey<Float>(COMPRESSOR_RELEASE_KEY) ?: 400f
makeupGain = getKey<Float>(COMPRESSOR_MAKEUP_KEY) ?: 12f
}
private var format = AudioFormat.NOT_SET
private var isFloat = false
private var sampleRate = 44100
private var channelCount = 2
// Single shared envelope across all channels — keeps L/R gain identical
// so stereo image is preserved and no crackling from gain mismatch.
private var envelope = 0f
private var attackCoeff = 0f
private var releaseCoeff = 0f
private var lastAttackMs = -1f
private var lastReleaseMs = -1f
private var lastSampleRate = -1
private var outputBuffer: ByteBuffer = AudioProcessor.EMPTY_BUFFER
private var inputEnded = false
// ── AudioProcessor ────────────────────────────────────────────────────────
override fun configure(inputAudioFormat: AudioFormat): AudioFormat {
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT &&
inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {
return inputAudioFormat // pass unsupported formats through unchanged
}
format = inputAudioFormat
isFloat = inputAudioFormat.encoding == C.ENCODING_PCM_FLOAT
sampleRate = inputAudioFormat.sampleRate
channelCount = inputAudioFormat.channelCount
envelope = 0f
return inputAudioFormat
}
// Always active when format is set — toggling isActive() mid-stream has no
// effect in media3 (only checked at configure() time). We do passthrough
// in queueInput() instead so enable/disable works immediately.
override fun isActive(): Boolean =
format != AudioFormat.NOT_SET &&
(format.encoding == C.ENCODING_PCM_16BIT || format.encoding == C.ENCODING_PCM_FLOAT)
override fun queueInput(inputBuffer: ByteBuffer) {
if (!inputBuffer.hasRemaining()) return
val remaining = inputBuffer.remaining()
val out = replaceOutputBuffer(remaining)
if (!enabled) { out.put(inputBuffer); out.flip(); return }
updateCoefficients()
val makeupLinear = dbToLinear(makeupGain)
val threshLinear = dbToLinear(threshold)
val bytesPerSample = if (isFloat) 4 else 2
val frameCount = remaining / (channelCount * bytesPerSample)
if (isFloat) processFloat(inputBuffer, out, frameCount, threshLinear, makeupLinear)
else processShort(inputBuffer, out, frameCount, threshLinear, makeupLinear)
out.flip()
}
/** Processes PCM_FLOAT frames. Two-pass: peak detection then gain application. */
private fun processFloat(
input: ByteBuffer, out: ByteBuffer,
frameCount: Int, threshLinear: Float, makeupLinear: Float
) {
repeat(frameCount) {
val frameStart = input.position()
var peak = 0f
repeat(channelCount) { val s = input.getFloat(); val a = if (s < 0f) -s else s; if (a > peak) peak = a }
advanceEnvelope(peak)
val gain = computeGain(threshLinear) * makeupLinear
input.position(frameStart)
repeat(channelCount) { out.putFloat(input.getFloat() * gain) }
}
}
/** Processes PCM_16BIT frames. Two-pass: peak detection then gain application. */
private fun processShort(
input: ByteBuffer, out: ByteBuffer,
frameCount: Int, threshLinear: Float, makeupLinear: Float
) {
repeat(frameCount) {
val frameStart = input.position()
var peak = 0f
repeat(channelCount) { val s = input.getShort() / 32768f; val a = if (s < 0f) -s else s; if (a > peak) peak = a }
advanceEnvelope(peak)
val gain = computeGain(threshLinear) * makeupLinear
input.position(frameStart)
repeat(channelCount) {
val s = input.getShort() / 32768f
out.putShort((s * gain).coerceIn(-1f, 1f).let { (it * 32768f).toInt().toShort() })
}
}
}
private fun advanceEnvelope(peak: Float) {
val coeff = if (peak > envelope) attackCoeff else releaseCoeff
envelope = peak + coeff * (envelope - peak)
}
override fun queueEndOfStream() { inputEnded = true }
override fun getOutput(): ByteBuffer {
val out = outputBuffer
outputBuffer = AudioProcessor.EMPTY_BUFFER
return out
}
override fun isEnded(): Boolean =
inputEnded && outputBuffer === AudioProcessor.EMPTY_BUFFER
// AudioProcessor.flush() (no-arg) is deprecated upstream in favor of a
// seek-aware overload, but this interface implementation still only exposes
// the no-arg version to override, so this suppresses that specific warning
// without adding @Deprecated (which would cascade to our own reset() below,
// since it calls flush() internally).
@Suppress("OVERRIDE_DEPRECATION")
override fun flush() {
// Called on every seek. Reset envelope so there's no gain burst
// from stale state — which is what caused crackling after skipping.
envelope = 0f
outputBuffer = AudioProcessor.EMPTY_BUFFER
inputEnded = false
}
override fun reset() {
flush()
format = AudioFormat.NOT_SET
isFloat = false
}
// ── Helpers ───────────────────────────────────────────────────────────────
private fun computeGain(threshLinear: Float): Float {
return if (envelope <= threshLinear) {
1f
} else {
val overDb = linearToDb(envelope) - threshold
dbToLinear(-(overDb * (1f - 1f / ratio)))
}
}
private fun replaceOutputBuffer(size: Int): ByteBuffer {
if (outputBuffer.capacity() < size) {
outputBuffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
} else {
outputBuffer.clear()
}
return outputBuffer
}
private fun updateCoefficients() {
if (attackMs == lastAttackMs &&
releaseMs == lastReleaseMs &&
sampleRate == lastSampleRate) return
lastAttackMs = attackMs
lastReleaseMs = releaseMs
lastSampleRate = sampleRate
attackCoeff = exp(-1.0 / (sampleRate * attackMs / 1000.0)).toFloat()
releaseCoeff = exp(-1.0 / (sampleRate * releaseMs / 1000.0)).toFloat()
}
private fun dbToLinear(db: Float): Float = 10f.pow(db / 20f)
private fun linearToDb(linear: Float): Float =
if (linear <= 0f) -120f else (20.0 * ln(linear.toDouble()) / ln(10.0)).toFloat()
}

View file

@ -2,21 +2,14 @@ package com.lagradost.cloudstream3.ui.player
import android.content.Context
import android.os.Looper
import androidx.annotation.OptIn
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.exoplayer.text.TextOutput
import androidx.media3.exoplayer.text.TextRenderer
import io.github.anilbeesetti.nextlib.media3ext.ffdecoder.NextRenderersFactory
@UnstableApi
class FixedNextRenderersFactory(
context: Context,
private val compressor: DynamicRangeCompressor? = null,
) : NextRenderersFactory(context) {
class FixedNextRenderersFactory(context: Context) : NextRenderersFactory(context) {
/** Somehow the nextlib authors decided that we need a text renderer that causes
* "ERROR_CODE_FAILED_RUNTIME_CHECK".
*
@ -32,26 +25,4 @@ class FixedNextRenderersFactory(
) {
out.add(TextRenderer(output, outputLooper))
}
/**
* Only builds a custom [DefaultAudioSink] when a compressor is actually supplied.
* When [compressor] is null (the setting is off, or unsupported on this device) we
* fall through to the completely unmodified default sink from the parent factory,
* so playback behaves exactly as it did before this feature existed.
*/
@OptIn(UnstableApi::class)
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean
): AudioSink? {
val activeCompressor = compressor
?: return super.buildAudioSink(context, enableFloatOutput, enableAudioTrackPlaybackParams)
return DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioOutputPlaybackParameters(enableAudioTrackPlaybackParams)
.setAudioProcessors(arrayOf<AudioProcessor>(activeCompressor))
.build()
}
}
}

View file

@ -4,7 +4,6 @@ import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import android.content.Context
import android.content.DialogInterface
import android.content.pm.ActivityInfo
@ -103,12 +102,12 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
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
@ -158,15 +157,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
autoHide()
}
}
protected var selectCompressorDialog: Dialog? = null
set(value) {
val prevField = field
field = value
if (value == null && prevField != null) {
autoHide()
}
}
protected var playBackCompressorEnabled = false
/** Checks if any top level dialog is open and showing */
fun isDialogOpen() =
@ -174,7 +164,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
|| selectTrackDialog?.isShowing == true
|| selectSpeedDialog?.isShowing == true
|| selectSubtitlesDialog?.isShowing == true
|| selectCompressorDialog?.isShowing == true
|| isShowingEpisodeOverlay
private fun scheduleMetadataVisibility() {
@ -318,7 +307,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
playerVideoTitleRez,
playerVideoInfo,
playerGoBackHolder,
playerVideoClock,
).forEach {
it.animateY(titleMove)
}
@ -538,7 +526,7 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
// 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)
@ -548,11 +536,11 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
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 -> {
@ -570,12 +558,12 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
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)
}
@ -708,268 +696,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
//}
}
// getColorStateList(index) on a TypedArray built from a raw intArrayOf(...) can't be
// statically verified by lint as a styleable resource index (it isn't tied to an
// <declare-styleable>), so it always flags a false-positive ResourceType error here —
// this is the standard, expected suppression for this obtainStyledAttributes pattern.
@SuppressLint("ResourceType")
private fun showCompressorDialog() {
val act = activity ?: return
val compressor = (player as? CS3IPlayer)?.compressor ?: return
// Always restore — CS3IPlayer is recreated between videos
restoreCompressorSettings()
// Snapshot for Cancel revert
data class Snap(val enabled: Boolean, val threshold: Float, val makeupGain: Float)
val snap = Snap(compressor.enabled, compressor.threshold, compressor.makeupGain)
val binding = com.lagradost.cloudstream3.databinding.CompressorDialogBinding
.inflate(android.view.LayoutInflater.from(act))
// ── Visual update helpers ──────────────────────────────────────────
fun updateCurrentLabel() {
binding.compressorCurrentLabel.text = if (compressor.enabled) {
act.getString(
R.string.compressor_on_format,
compressor.threshold.toInt(),
compressor.makeupGain.toInt()
)
} else {
act.getString(R.string.compressor_off)
}
}
fun updateThresholdLabel() {
binding.compressorThresholdLabel.text =
act.getString(R.string.compressor_threshold_label, compressor.threshold.toInt())
}
fun updateMakeupLabel() {
binding.compressorMakeupLabel.text =
act.getString(R.string.compressor_makeup_label, compressor.makeupGain.toInt())
}
// Short, plain-language explanation of what each slider does, updated live —
// same idea as the "Use this if the subtitles are shown X ms too late" hint.
fun updateThresholdHint() {
binding.compressorThresholdHint.text =
act.getString(R.string.compressor_threshold_hint, compressor.threshold.toInt())
}
fun updateMakeupHint() {
binding.compressorMakeupHint.text =
act.getString(R.string.compressor_makeup_hint, compressor.makeupGain.toInt())
}
// WhiteButton = selected/active, BlackButton = unselected — same as speed presets
fun syncEnableButtons() {
val ctx = context ?: return
listOf(
binding.compressorEnableBtt to compressor.enabled,
binding.compressorDisableBtt to !compressor.enabled,
).forEach { (btn, active) ->
// Apply the full WhiteButton or BlackButton style — backgroundTint only.
// Also update setTextColor so we don't get white text on white background.
val styleAttr = if (active) R.style.WhiteButton else R.style.BlackButton
val ta = ctx.obtainStyledAttributes(
styleAttr,
intArrayOf(
com.google.android.material.R.attr.backgroundTint,
android.R.attr.textColor,
)
)
btn.backgroundTintList = ta.getColorStateList(0)
ta.getColorStateList(1)?.let { btn.setTextColor(it) }
ta.recycle()
}
updateCurrentLabel()
}
// ── Presets — declared before the sliders so their listeners can call
// syncPresetButtons(matchingPresetButton()) to keep the highlight accurate ──
val allPresets = listOf(
binding.compressorPresetLight,
binding.compressorPresetDialog,
binding.compressorPresetHeavy,
)
fun syncPresetButtons(active: com.google.android.material.button.MaterialButton?) {
val ctx = context ?: return
allPresets.forEach { btn ->
val isActive = btn == active
val ta = ctx.obtainStyledAttributes(
if (isActive) R.style.WhiteButton else R.style.BlackButton,
intArrayOf(
com.google.android.material.R.attr.backgroundTint,
android.R.attr.textColor,
)
)
btn.backgroundTintList = ta.getColorStateList(0)
ta.getColorStateList(1)?.let { btn.setTextColor(it) }
ta.recycle()
}
}
// Figures out which preset (if any) matches the current values, so the
// correct button stays highlighted when the dialog is reopened, instead
// of always resetting to "none selected".
fun matchingPresetButton(): com.google.android.material.button.MaterialButton? = when {
compressor.threshold == -18f && compressor.makeupGain == 4f -> binding.compressorPresetLight
compressor.threshold == -24f && compressor.makeupGain == 12f -> binding.compressorPresetDialog
compressor.threshold == -30f && compressor.makeupGain == 16f -> binding.compressorPresetHeavy
else -> null
}
fun applyPreset(
threshold: Float,
makeup: Float,
activeBtn: com.google.android.material.button.MaterialButton
) {
compressor.threshold = threshold
compressor.makeupGain = makeup
binding.compressorThresholdBar.value = threshold.coerceIn(-30f, 0f)
binding.compressorRatioBar.value = makeup.coerceIn(0f, 24f)
updateThresholdLabel()
updateMakeupLabel()
updateThresholdHint()
updateMakeupHint()
updateCurrentLabel()
syncPresetButtons(activeBtn)
}
// ── Restore UI to current compressor state ─────────────────────────
binding.compressorThresholdBar.value = compressor.threshold.coerceIn(-30f, 0f)
binding.compressorRatioBar.value = compressor.makeupGain.coerceIn(0f, 24f)
updateThresholdLabel()
updateMakeupLabel()
updateThresholdHint()
updateMakeupHint()
syncEnableButtons()
syncPresetButtons(matchingPresetButton())
// ── On / Off ───────────────────────────────────────────────────────
binding.compressorEnableBtt.setOnClickListener {
compressor.enabled = true
syncEnableButtons()
}
binding.compressorDisableBtt.setOnClickListener {
compressor.enabled = false
syncEnableButtons()
}
// ── Threshold slider + FABs ────────────────────────────────────────
binding.compressorThresholdBar.addOnChangeListener { _, value, fromUser ->
if (fromUser) {
compressor.threshold = value
updateThresholdLabel()
updateThresholdHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
}
binding.thresholdMinus.setOnClickListener {
val v = (compressor.threshold - 1f).coerceIn(-30f, 0f)
compressor.threshold = v
binding.compressorThresholdBar.value = v
updateThresholdLabel()
updateThresholdHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
binding.thresholdPlus.setOnClickListener {
val v = (compressor.threshold + 1f).coerceIn(-30f, 0f)
compressor.threshold = v
binding.compressorThresholdBar.value = v
updateThresholdLabel()
updateThresholdHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
// ── Makeup gain slider + FABs (reusing ratio_minus/plus ids) ──────
binding.compressorRatioBar.addOnChangeListener { _, value, fromUser ->
if (fromUser) {
compressor.makeupGain = value
updateMakeupLabel()
updateMakeupHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
}
binding.ratioMinus.setOnClickListener {
val v = (compressor.makeupGain - 1f).coerceIn(0f, 24f)
compressor.makeupGain = v
binding.compressorRatioBar.value = v
updateMakeupLabel()
updateMakeupHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
binding.ratioPlus.setOnClickListener {
val v = (compressor.makeupGain + 1f).coerceIn(0f, 24f)
compressor.makeupGain = v
binding.compressorRatioBar.value = v
updateMakeupLabel()
updateMakeupHint()
updateCurrentLabel()
syncPresetButtons(matchingPresetButton())
}
// ── Preset buttons ─────────────────────────────────────────────────
binding.compressorPresetLight.setOnClickListener {
applyPreset(-18f, 4f, binding.compressorPresetLight)
}
binding.compressorPresetDialog.setOnClickListener {
applyPreset(-24f, 12f, binding.compressorPresetDialog)
}
binding.compressorPresetHeavy.setOnClickListener {
applyPreset(-30f, 16f, binding.compressorPresetHeavy)
}
// ── Dialog lifecycle ───────────────────────────────────────────────
val dialog = AlertDialog.Builder(act, R.style.AlertDialogCustom)
.setView(binding.root)
.setOnDismissListener {
activity?.hideSystemUI()
selectCompressorDialog = null
}
.create()
selectCompressorDialog = dialog
binding.applyBtt.setOnClickListener {
saveCompressorSettings(compressor)
dialog.dismiss()
}
binding.resetBtt.setOnClickListener {
applyPreset(-24f, 12f, binding.compressorPresetDialog)
compressor.enabled = true
syncEnableButtons()
}
binding.cancelBtt.setOnClickListener {
compressor.enabled = snap.enabled
compressor.threshold = snap.threshold
compressor.makeupGain = snap.makeupGain
dialog.dismiss()
}
dialog.show()
}
private fun saveCompressorSettings(c: DynamicRangeCompressor) {
setKey(COMPRESSOR_ENABLED_KEY, c.enabled)
setKey(COMPRESSOR_THRESHOLD_KEY, c.threshold)
setKey(COMPRESSOR_RATIO_KEY, c.ratio)
setKey(COMPRESSOR_ATTACK_KEY, c.attackMs)
setKey(COMPRESSOR_RELEASE_KEY, c.releaseMs)
setKey(COMPRESSOR_MAKEUP_KEY, c.makeupGain)
}
protected fun restoreCompressorSettings() {
val c = (player as? CS3IPlayer)?.compressor ?: return
c.restoreSavedSettings()
}
private fun onClickChange() {
isShowing = !isShowing
if (isShowing) autoHide()
@ -1046,7 +772,7 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
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
@ -1412,10 +1138,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
ctx.getString(R.string.playback_speed_enabled_key),
false
)
playBackCompressorEnabled = settingsManager.getBoolean(
ctx.getString(R.string.compressor_enabled_key),
false
)
playerRotateEnabled = settingsManager.getBoolean(
ctx.getString(R.string.rotate_video_key),
false
@ -1442,10 +1164,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
}
playerBinding?.apply {
playerSpeedBtt.isVisible = playBackSpeedEnabled
playerCompressorBtt.isVisible = playBackCompressorEnabled
if (playBackCompressorEnabled) {
restoreCompressorSettings()
}
playerResizeBtt.isVisible = playerResizeEnabled
playerRotateBtt.isVisible =
if (isLayout(TV or EMULATOR)) false else playerRotateEnabled
@ -1507,11 +1225,6 @@ open class FullScreenPlayer : AbstractPlayerFragment<FragmentPlayerBinding>(
showSpeedDialog()
}
playerCompressorBtt.setOnClickListener {
autoHide()
showCompressorDialog()
}
playerSkipOp.setOnClickListener {
autoHide()
skipOp()

View file

@ -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
@ -135,7 +132,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
@ -514,7 +510,7 @@ class GeneratorPlayer : FullScreenPlayer() {
showDownloadProgress(DownloadEvent(0, 0, 0, null))
// uiReset() // Removed due to UX
currentSelectedLink = link
// setEpisodes(viewModel.getAllMeta() ?: emptyList())
setPlayerDimen(null)
@ -1047,7 +1043,7 @@ class GeneratorPlayer : FullScreenPlayer() {
binding.subtitleSettingsBtt.setOnClickListener {
safe {
val subtitlesFragment = SubtitlesFragmentDialog2()
val subtitlesFragment = SubtitlesFragment()
subtitlesFragment.systemBarsAddPadding = true
subtitlesFragment.show(this.parentFragmentManager, "SubtitleSettings")
}
@ -1116,29 +1112,21 @@ class GeneratorPlayer : FullScreenPlayer() {
var sourceIndex = 0
var startSource = 0
// Filtered and sorted links
var currentHiddenFooter: View? = null
var filteredLinks: List<DisplayLink> = emptyList()
var sortedUrls = emptyList<Pair<ExtractorLink?, ExtractorUri?>>()
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<LinearLayout>(R.id.sort_sources_holder)?.isGone =
true
} else {
startSource = filteredLinks.indexOfFirst { it.link == currentLinkUsed }
startSource = sortedUrls.indexOf(currentSelectedLink)
sourceIndex = startSource
val sourcesArrayAdapter =
ArrayAdapter<String>(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 +1142,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 +1150,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 +1363,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 +1532,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 +1554,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 +1566,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 +1574,7 @@ class GeneratorPlayer : FullScreenPlayer() {
if (!isPlayerActive.compareAndSet(false, true)) {
return
}
loadLink(firstAvailableLink, false)
loadLink(links.first(), false)
showPlayerMetadata()
}
@ -1692,26 +1641,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() {
@ -2218,7 +2166,6 @@ class GeneratorPlayer : FullScreenPlayer() {
isPlayerActive.set(false)
binding?.overlayLoadingSkipButton?.isVisible = false
binding?.playerLoadingOverlay?.isVisible = true
viewModel.modifyState { setError(emptyList()) }
uiReset()
}
@ -2272,14 +2219,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 +2297,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})"
}
}

View file

@ -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<SubtitleData> = persistentSetOf(),
val links: PersistentSet<VideoLink> = persistentSetOf(),
val erroredLinks: PersistentSet<VideoLink> = persistentSetOf(),
val stamps: PersistentList<VideoSkipStamp> = persistentListOf(),
val loading: Resource<Unit> = 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<Int, List<DisplayLink>> = ConcurrentHashMap()
private val sortedLinks: ConcurrentHashMap<Int, List<VideoLink>> = ConcurrentHashMap()
/**
* The cache is guaranteed to be up to date link-wise due to the immutable links.
* However, hideNegativeSources and hideErrorSources could be updated, which requires clearing the cache.
*/
fun clearSortedLinksCache() = sortedLinks.clear()
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<DisplayLink> {
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<VideoLink> {
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<VideoSkipStamp>): VideoState = copy(stamps = items.toPersistentList())
@Contract(pure = true)
fun addError(item: VideoLink): VideoState = copy(erroredLinks = erroredLinks.add(item))
@Contract(pure = true)
fun setError(items: Collection<VideoLink>): VideoState = copy(erroredLinks = items.toPersistentSet())
}
data class VideoLive<T>(
@ -190,8 +141,9 @@ class PlayerGeneratorViewModel : ViewModel() {
var state = VideoState(instance = 0)
private set
private val _currentLinks = MutableLiveData<VideoLive<Set<VideoLink>>>(null)
val currentLinks: LiveData<VideoLive<Set<VideoLink>>> = _currentLinks
private val _currentLinks =
MutableLiveData<VideoLive<Set<Pair<ExtractorLink?, ExtractorUri?>>>>(null)
val currentLinks: LiveData<VideoLive<Set<Pair<ExtractorLink?, ExtractorUri?>>>> = _currentLinks
private val _currentSubtitles = MutableLiveData<VideoLive<Set<SubtitleData>>>(null)
val currentSubtitles: LiveData<VideoLive<Set<SubtitleData>>> = _currentSubtitles

View file

@ -887,6 +887,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
// Only expose the parent chain when controls are currently hidden.
val prevCenterMenuGone = playerView.playerCenterMenu?.isGone ?: false
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
if (!wasShowing) {
playerView.playerCenterMenu?.isGone = false
@ -905,7 +906,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
resetRewindText()
// Restore parent chain only if we changed it and controls are still hidden.
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
playerView.playerCenterMenu?.isGone = true
playerView.playerCenterMenu?.isGone = prevCenterMenuGone
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
rewHolder.alpha = 0f
}
@ -926,6 +927,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
val ffwdText = playerView.exoFfwdText
val wasShowing = playerView.callbacks?.isUIShowing() ?: false
val prevCenterMenuGone = playerView.playerCenterMenu?.isGone ?: false
val prevVideoHolderVisible = playerView.playerVideoHolder?.isVisible ?: true
if (!wasShowing) {
playerView.playerCenterMenu?.isGone = false
@ -943,7 +945,7 @@ class PlayerGestureHelper(private val playerView: PlayerView) {
ffwdText?.post {
resetFastForwardText()
if (!wasShowing && !(playerView.callbacks?.isUIShowing() ?: false)) {
playerView.playerCenterMenu?.isGone = true
playerView.playerCenterMenu?.isGone = prevCenterMenuGone
playerView.playerVideoHolder?.isVisible = prevVideoHolderVisible
ffwdHolder.alpha = 0f
}

View file

@ -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<TorrentStatus> {
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<TorrentFileStat>?,
@JsonProperty("trackers") @SerialName("trackers") var trackers: List<String>?,
@JsonProperty("title")
var title: String,
@JsonProperty("poster")
var poster: String,
@JsonProperty("data")
var data: String?,
@JsonProperty("timestamp")
var timestamp: Long,
@JsonProperty("name")
var name: String?,
@JsonProperty("hash")
var hash: String?,
@JsonProperty("stat")
var stat: Int,
@JsonProperty("stat_string")
var statString: String,
@JsonProperty("loaded_size")
var loadedSize: Long?,
@JsonProperty("torrent_size")
var torrentSize: Long?,
@JsonProperty("preloaded_bytes")
var preloadedBytes: Long?,
@JsonProperty("preload_size")
var preloadSize: Long?,
@JsonProperty("download_speed")
var downloadSpeed: Double?,
@JsonProperty("upload_speed")
var uploadSpeed: Double?,
@JsonProperty("total_peers")
var totalPeers: Int?,
@JsonProperty("pending_peers")
var pendingPeers: Int?,
@JsonProperty("active_peers")
var activePeers: Int?,
@JsonProperty("connected_seeders")
var connectedSeeders: Int?,
@JsonProperty("half_open_peers")
var halfOpenPeers: Int?,
@JsonProperty("bytes_written")
var bytesWritten: Long?,
@JsonProperty("bytes_written_data")
var bytesWrittenData: Long?,
@JsonProperty("bytes_read")
var bytesRead: Long?,
@JsonProperty("bytes_read_data")
var bytesReadData: Long?,
@JsonProperty("bytes_read_useful_data")
var bytesReadUsefulData: Long?,
@JsonProperty("chunks_written")
var chunksWritten: Long?,
@JsonProperty("chunks_read")
var chunksRead: Long?,
@JsonProperty("chunks_read_useful")
var chunksReadUseful: Long?,
@JsonProperty("chunks_read_wasted")
var chunksReadWasted: Long?,
@JsonProperty("pieces_dirtied_good")
var piecesDirtiedGood: Long?,
@JsonProperty("pieces_dirtied_bad")
var piecesDirtiedBad: Long?,
@JsonProperty("duration_seconds")
var durationSeconds: Double?,
@JsonProperty("bit_rate")
var bitRate: String?,
@JsonProperty("file_stats")
var fileStats: List<TorrentFileStat>?,
@JsonProperty("trackers")
var trackers: List<String>?,
) {
fun streamUrl(url: String): String {
val fileName =
@ -342,10 +381,12 @@ object Torrent {
}
}
@Serializable
data class TorrentFileStat(
@JsonProperty("id") @SerialName("id") val id: Int?,
@JsonProperty("path") @SerialName("path") val path: String?,
@JsonProperty("length") @SerialName("length") val length: Long?,
@JsonProperty("id")
val id: Int?,
@JsonProperty("path")
val path: String?,
@JsonProperty("length")
val length: Long?,
)
}
}

View file

@ -12,16 +12,12 @@ import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.DataStoreHelper.currentAccount
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.Qualities
import java.util.EnumMap
import java.util.concurrent.ConcurrentHashMap
import kotlin.also
import kotlin.math.abs
object QualityDataHelper {
private const val VIDEO_SOURCE_PRIORITY = "video_source_priority"
private const val VIDEO_PROFILE_NAME = "video_profile_name"
private const val VIDEO_QUALITY_PRIORITY = "video_quality_priority"
const val VIDEO_PROFILE_SETTINGS = "video_profile_settings"
// Old key only supporting one type per profile
@Deprecated("Changed to support multiple types per profile")
@ -57,21 +53,13 @@ object QualityDataHelper {
val types: Set<QualityProfileType>
)
// Map profile and name to priority
val sourcePriorityCache: ConcurrentHashMap<Int, HashMap<String, Int>> = ConcurrentHashMap()
fun getSourcePriority(profile: Int, name: String?): Int {
if (name == null) return DEFAULT_SOURCE_PRIORITY
return sourcePriorityCache[profile]?.get(name) ?: (getKey<Int>(
return getKey(
"$currentAccount/$VIDEO_SOURCE_PRIORITY/$profile",
name,
DEFAULT_SOURCE_PRIORITY
) ?: DEFAULT_SOURCE_PRIORITY).also {
sourcePriorityCache.getOrPut(profile) { hashMapOf() }
sourcePriorityCache[profile]?.set(name, it)
}
) ?: DEFAULT_SOURCE_PRIORITY
}
fun getAllSourcePriorityNames(profile: Int): List<String> {
@ -89,8 +77,6 @@ object QualityDataHelper {
} else {
setKey(folder, name, priority)
}
sourcePriorityCache[profile]?.set(name, priority)
}
fun setProfileName(profile: Int, name: String?) {
@ -107,17 +93,12 @@ object QualityDataHelper {
?: txt(R.string.profile_number, profile)
}
// Map profile and quality to priority
val qualityPriorityCache: ConcurrentHashMap<Int, EnumMap<Qualities, Int>> = ConcurrentHashMap()
fun getQualityPriority(profile: Int, quality: Qualities): Int {
return qualityPriorityCache[profile]?.get(quality) ?: (getKey<Int>(
return getKey(
"$currentAccount/$VIDEO_QUALITY_PRIORITY/$profile",
quality.value.toString(),
quality.defaultPriority
)?.also {
qualityPriorityCache.getOrPut(profile) { EnumMap(Qualities::class.java) }
qualityPriorityCache[profile]?.set(quality, it)
}) ?: quality.defaultPriority
) ?: quality.defaultPriority
}
fun setQualityPriority(profile: Int, quality: Qualities, priority: Int) {
@ -126,24 +107,8 @@ object QualityDataHelper {
quality.value.toString(),
priority
)
qualityPriorityCache[profile]?.set(quality, priority)
}
fun <T> setProfileSetting(profile: Int, setting: ProfileSettings<T>, value: T) {
val folder = "$currentAccount/$VIDEO_PROFILE_SETTINGS/$profile"
// Prevent unnecessary keys
if (value == setting.defaultValue) {
removeKey(folder, setting.key)
} else {
setKey(folder, setting.key, value)
}
}
inline fun <reified T : Any> getProfileSetting(profile: Int, setting: ProfileSettings<T>): T {
val folder = "$currentAccount/$VIDEO_PROFILE_SETTINGS/$profile"
val value = getKey<T>(folder, setting.key)
return value ?: setting.defaultValue
}
@Suppress("DEPRECATION")
fun getQualityProfileTypes(profile: Int): Set<QualityProfileType> {
@ -258,9 +223,4 @@ object QualityDataHelper {
if (target == null) return Qualities.Unknown
return Qualities.entries.minBy { abs(it.value - target) }
}
}
sealed class ProfileSettings<T>(val key: String, val defaultValue: T) {
object HideErrorSources : ProfileSettings<Boolean>("hide_error_sources", false)
object HideNegativeSources : ProfileSettings<Boolean>("hide_negative_sources", false)
}
}

View file

@ -1,6 +1,5 @@
package com.lagradost.cloudstream3.ui.player.source_priority
import android.app.Activity
import android.app.Dialog
import androidx.annotation.StyleRes
import androidx.core.view.isVisible
@ -27,7 +26,7 @@ data class LinkSource(
class QualityProfileDialog private constructor(
val activity: Activity,
val activity: FragmentActivity,
@StyleRes val themeRes: Int,
private val links: List<LinkSource>,
private val usedProfile: Int?,
@ -35,7 +34,7 @@ class QualityProfileDialog private constructor(
private val useProfileSelection: Boolean
) : Dialog(activity, themeRes) {
constructor(
activity: Activity,
activity: FragmentActivity,
@StyleRes themeRes: Int,
links: List<LinkSource>,
usedProfile: Int,
@ -43,7 +42,7 @@ class QualityProfileDialog private constructor(
) : this(activity, themeRes, links, usedProfile, profileSelectionCallback, true)
constructor(
activity: Activity,
activity: FragmentActivity,
@StyleRes themeRes: Int,
links: List<LinkSource>
) : this(activity, themeRes, links, null, null, false)

View file

@ -14,7 +14,7 @@ import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
class SourcePriorityDialog(
val ctx: Context,
@StyleRes val themeRes: Int,
@StyleRes themeRes: Int,
val links: List<LinkSource>,
private val profile: QualityDataHelper.QualityProfile,
/**
@ -28,79 +28,76 @@ class SourcePriorityDialog(
PlayerSelectSourcePriorityBinding.inflate(LayoutInflater.from(ctx), null, false)
setContentView(binding.root)
fixSystemBarsPadding(binding.root)
val sourcesRecyclerView = binding.sortSources
val qualitiesRecyclerView = binding.sortQualities
val profileText = binding.profileTextEditable
val saveBtt = binding.saveBtt
val exitBtt = binding.closeBtt
val helpBtt = binding.helpBtt
binding.apply {
profileTextEditable.setText(
QualityDataHelper.getProfileName(profile.id).asString(context)
)
profileTextEditable.hint = txt(R.string.profile_number, profile.id).asString(context)
profileText.setText(QualityDataHelper.getProfileName(profile.id).asString(context))
profileText.hint = txt(R.string.profile_number, profile.id).asString(context)
sortSources.adapter = PriorityAdapter<Nothing?>(
).apply {
val sortedLinks = links.map { link ->
SourcePriority(
null,
link.source,
QualityDataHelper.getSourcePriority(profile.id, link.source)
)
}.distinctBy { it.name }.sortedBy { -it.priority }
submitList(sortedLinks)
}
sortQualities.adapter = PriorityAdapter<Qualities>(
).apply {
submitList(Qualities.entries.mapNotNull {
SourcePriority(
it,
Qualities.getStringByIntFull(it.value).ifBlank { return@mapNotNull null },
QualityDataHelper.getQualityPriority(profile.id, it)
)
}.sortedBy { -it.priority })
}
@Suppress("UNCHECKED_CAST") // We know the types
saveBtt.setOnClickListener {
val qualityAdapter = sortQualities.adapter as? PriorityAdapter<Qualities>
val sourcesAdapter = sortSources.adapter as? PriorityAdapter<Nothing?>
val qualities = qualityAdapter?.immutableCurrentList ?: emptyList()
val sources = sourcesAdapter?.immutableCurrentList ?: emptyList()
qualities.forEach {
QualityDataHelper.setQualityPriority(profile.id, it.data, it.priority)
}
sources.forEach {
QualityDataHelper.setSourcePriority(profile.id, it.name, it.priority)
}
qualityAdapter?.submitList(qualities.sortedBy { -it.priority })
sourcesAdapter?.submitList(sources.sortedBy { -it.priority })
val savedProfileName = profileTextEditable.text.toString()
if (savedProfileName.isBlank()) {
QualityDataHelper.setProfileName(profile.id, null)
} else {
QualityDataHelper.setProfileName(profile.id, savedProfileName)
}
updatedCallback.invoke()
}
closeBtt.setOnClickListener {
dismissSafe()
}
helpBtt.setOnClickListener {
AlertDialog.Builder(context, R.style.AlertDialogCustom).apply {
setMessage(R.string.quality_profile_help)
}.show()
}
settingsBtt.setOnClickListener {
SourceProfileSettingsDialog(ctx, themeRes, profile.id).show()
}
sourcesRecyclerView.adapter = PriorityAdapter<Nothing?>(
).apply {
submitList(links.map { link ->
SourcePriority(
null,
link.source,
QualityDataHelper.getSourcePriority(profile.id, link.source)
)
}.distinctBy { it.name }.sortedBy { -it.priority })
}
qualitiesRecyclerView.adapter = PriorityAdapter<Qualities>(
).apply {
submitList(Qualities.entries.mapNotNull {
SourcePriority(
it,
Qualities.getStringByIntFull(it.value).ifBlank { return@mapNotNull null },
QualityDataHelper.getQualityPriority(profile.id, it)
)
}.sortedBy { -it.priority })
}
@Suppress("UNCHECKED_CAST") // We know the types
saveBtt.setOnClickListener {
val qualityAdapter = qualitiesRecyclerView.adapter as? PriorityAdapter<Qualities>
val sourcesAdapter = sourcesRecyclerView.adapter as? PriorityAdapter<Nothing?>
val qualities = qualityAdapter?.immutableCurrentList ?: emptyList()
val sources = sourcesAdapter?.immutableCurrentList ?: emptyList()
qualities.forEach {
QualityDataHelper.setQualityPriority(profile.id, it.data, it.priority)
}
sources.forEach {
QualityDataHelper.setSourcePriority(profile.id, it.name, it.priority)
}
qualityAdapter?.submitList(qualities.sortedBy { -it.priority })
sourcesAdapter?.submitList(sources.sortedBy { -it.priority })
val savedProfileName = profileText.text.toString()
if (savedProfileName.isBlank()) {
QualityDataHelper.setProfileName(profile.id, null)
} else {
QualityDataHelper.setProfileName(profile.id, savedProfileName)
}
updatedCallback.invoke()
}
exitBtt.setOnClickListener {
this.dismissSafe()
}
helpBtt.setOnClickListener {
AlertDialog.Builder(context, R.style.AlertDialogCustom).apply {
setMessage(R.string.quality_profile_help)
}.show()
}
super.show()
}
}

View file

@ -1,48 +0,0 @@
package com.lagradost.cloudstream3.ui.player.source_priority
import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import androidx.annotation.StyleRes
import com.lagradost.cloudstream3.databinding.SourceProfileSettingsDialogBinding
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
class SourceProfileSettingsDialog(
val ctx: Context,
@StyleRes themeRes: Int,
val profile: Int
) : Dialog(ctx, themeRes) {
override fun show() {
val binding =
SourceProfileSettingsDialogBinding.inflate(LayoutInflater.from(ctx), null, false)
setContentView(binding.root)
fixSystemBarsPadding(binding.root)
binding.apply {
var hideErrorSources = QualityDataHelper.getProfileSetting(profile, ProfileSettings.HideErrorSources)
var hideNegativeSources = QualityDataHelper.getProfileSetting(profile, ProfileSettings.HideNegativeSources)
profileHideErrorSources.isChecked = hideErrorSources
profileHideErrorSources.setOnCheckedChangeListener { _, bool ->
hideErrorSources = bool
}
profileHideNegativeSources.isChecked = hideNegativeSources
profileHideNegativeSources.setOnCheckedChangeListener { _, bool ->
hideNegativeSources = bool
}
applyBtt.setOnClickListener {
QualityDataHelper.setProfileSetting(profile, ProfileSettings.HideErrorSources, hideErrorSources)
QualityDataHelper.setProfileSetting(profile, ProfileSettings.HideNegativeSources, hideNegativeSources)
dismissSafe()
}
cancelBtt.setOnClickListener {
dismissSafe()
}
}
super.show()
}
}

View file

@ -874,9 +874,10 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
resultMetaRating.setText(d.ratingText)
resultMetaStatus.setText(d.onGoingText)
resultMetaContentRating.setText(d.contentRatingText)
resultCastText.setText(d.actorsText)
resultNextAiring.setText(d.nextAiringEpisode)
resultNextAiringTime.setText(d.nextAiringDate)
resultPoster.loadImage(d.posterImage, headers = d.posterHeaders)
resultPoster.loadImage(d.posterImage)
var isExpanded = false
resultDescription.apply {
@ -909,7 +910,7 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
R.drawable.profile_bg_teal
).random()
backgroundPoster.loadImage(d.posterBackgroundImage, headers = d.posterHeaders) {
backgroundPoster.loadImage(d.posterBackgroundImage) {
error { getImageFromDrawable(context ?: return@error null, error) }
}
@ -931,7 +932,6 @@ class ResultFragmentTv : BaseFragment<FragmentResultTvBinding>(
true
)
resultCastText.setText(if (showCast) d.actorsText else null)
resultCastItems.isGone = !showCast || d.actors.isNullOrEmpty()
(resultCastItems.adapter as? ActorAdaptor)?.submitList(if (showCast) d.actors else emptyList())

View file

@ -149,7 +149,6 @@ class SearchFragment : BaseFragment<FragmentSearchBinding>(
override fun onResume() {
super.onResume()
searchViewModel.clearSuggestions()
afterPluginsLoadedEvent += ::reloadRepos
}
@ -168,7 +167,6 @@ class SearchFragment : BaseFragment<FragmentSearchBinding>(
**/
fun search(query: String?) {
if (query == null) return
searchViewModel.clearSuggestions()
// don't resume state from prev search
(binding?.searchMasterRecycler?.adapter as? BaseAdapter<*, *>)?.clearState()
context?.let { ctx ->

View file

@ -1,274 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import androidx.core.content.FileProvider
import com.lagradost.cloudstream3.BuildConfig
import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.MainActivity.Companion.deleteFileOnExit
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.receivers.PackageInstallerStatusReceiver
import com.lagradost.cloudstream4.AppSettings
import com.lagradost.cloudstream4.viewmodels.AppUpdater
import com.lagradost.cloudstream4.viewmodels.DigestPair
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.security.DigestException
import java.security.MessageDigest
object ApkUpdater : AppUpdater {
private const val APP_UPDATE_NAME = "CloudStream"
private const val APP_UPDATE_SUFFIX = "apk"
@Throws
override suspend fun update(
settings: AppSettings,
url: String,
digest: DigestPair?,
downloadProgress: (Long, Long?) -> Unit
) {
val activity = CommonActivity.activity ?: throw ErrorLoadingException("No activity found")
clearOldFiles(activity)
val request = app.get(url)
val length = request.size
val body = request.body
body.use { body ->
val length = length ?: body.contentLength()
val readStream = body.byteStream()
when (settings.updates.apkInstaller.get()) {
0 -> {
packageInstallerDownloader(
activity,
readStream,
length,
digest,
downloadProgress
)
}
else -> {
legacyDownloader(activity, readStream, length, digest, downloadProgress)
}
}
}
}
fun clearOldFiles(activity: Activity) {
// Delete old files
activity.cacheDir.listFiles()?.filter {
it.name.startsWith(APP_UPDATE_NAME) && it.extension == APP_UPDATE_SUFFIX
}?.forEach {
deleteFileOnExit(it)
}
}
/** https://medium.com/@solrudev/painless-building-of-an-android-package-installer-app-d5a09b5df432 */
@SuppressLint("RequestInstallPackagesPolicy")
@Throws
suspend fun packageInstallerDownloader(
activity: Activity,
readStream: InputStream,
length: Long?,
digest: DigestPair?,
downloadProgress: (Long, Long?) -> Unit,
) = withContext(Dispatchers.IO) {
var sessionId: Int? = null
val packageInstaller = activity.packageManager.packageInstaller
try {
val installParams =
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
installParams.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
}
if (length != null) {
installParams.setSize(length)
}
sessionId = packageInstaller.createSession(installParams)
val session = packageInstaller.openSession(sessionId)
// We do not need to buffer this because transfer has large writes
session.openWrite(activity.packageName, 0, length ?: -1L)
.use { writeStream ->
transfer(writeStream, readStream, length, downloadProgress, digest)
session.fsync(writeStream)
}
val receiverIntent = Intent(activity, PackageInstallerStatusReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val receiverPendingIntent =
PendingIntent.getBroadcast(activity, 0, receiverIntent, flags)
// Avoid delayed updates, and just commit instantly
session.commit(receiverPendingIntent.intentSender)
session.close()
} catch (t: Throwable) {
sessionId?.let { sessionId ->
packageInstaller.abandonSession(sessionId)
}
throw t
}
}
/**
* Write the "readStream" to the "writeStream", while notifying the "downloadProgress" and
* calculating the digest
*
* ------------------------------------------------------------------------------------------
*
* throws a DigestException if the Digest can be calculated (non-null + correct algorithm),
* and is mismatched
*
* throws a CancellationException if canceled, but may not be "instant" if the read is blocking
*
* throws IOException and similar for reading
*
* ------------------------------------------------------------------------------------------
*
* In case of crashes from the digest, we ignore it as we do not want to "block" someone from
* updating if they got a broken OS without the desired algorithm or implementation.
*
* This is because a malicious CDN should not be able to "crash" the algorithm, but a broken
* OS will. And recovering from a broken OS by ignoring it is better than refusing it.
* */
@Throws
suspend fun transfer(
writeStream: OutputStream,
readStream: InputStream,
length: Long?,
downloadProgress: (Long, Long?) -> Unit,
digest: DigestPair?,
) = withContext(Dispatchers.IO) {
val md = digest?.algorithm?.let { digestAlgorithm ->
safe {
MessageDigest.getInstance(digestAlgorithm)
}
}
val context = currentCoroutineContext()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var read: Int
var transferred: Long = 0
while ((readStream.read(buffer, 0, DEFAULT_BUFFER_SIZE)
.also { read = it }) >= 0
) {
writeStream.write(buffer, 0, read)
safe {
md?.update(buffer, 0, read)
}
transferred += read.toLong()
downloadProgress(transferred, length)
context.ensureActive()
}
writeStream.flush()
val check = safe { md?.digest() }
if (check != null && !check.contentEquals(digest?.digest)) {
throw DigestException("Mismatched digest on transfer ${digest?.algorithm} : ${check.toHexString()} / ${digest?.digest?.toHexString()}")
}
}
/**
* Returns true if we have a non-null digest that matches a digest on the specified existing file
* */
suspend fun isFileDigest(file: File, digest: DigestPair?): Boolean {
if (digest == null) {
return false
}
try {
val fileDigest = calculateDigest(
digestAlgorithm = digest.algorithm,
readStream = file.inputStream()
)
return fileDigest != null && digest.digest.contentEquals(fileDigest)
} catch (_: Throwable) {
// File not found/security/read issues, not very useful errors
}
return false
}
/**
* Calculates the digest of a stream with the specified algorithm, use transfer instead if
* you already download something.
*
* Will throw read errors
* Will return null if the algorithm is null or does not exist/has some error
* */
@Throws
suspend fun calculateDigest(digestAlgorithm: String?, readStream: InputStream) =
withContext(Dispatchers.IO) {
if (digestAlgorithm == null) return@withContext null
val md =
safe {
MessageDigest.getInstance(digestAlgorithm)
} ?: return@withContext null
val context = currentCoroutineContext()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var read: Int
while ((readStream.read(buffer, 0, DEFAULT_BUFFER_SIZE)
.also { read = it }) >= 0
) {
try {
md.update(buffer, 0, read)
} catch (_: Throwable) {
return@withContext null
}
context.ensureActive()
}
return@withContext safe { md.digest() }
}
@Throws
suspend fun legacyDownloader(
activity: Activity,
readStream: InputStream,
length: Long?,
digest: DigestPair?,
downloadProgress: (Long, Long?) -> Unit
) = withContext(Dispatchers.IO) {
val downloadedFile = File.createTempFile(APP_UPDATE_NAME, ".$APP_UPDATE_SUFFIX")
// We do not need to buffer this because transfer has large writes
downloadedFile.outputStream().use { writeStream ->
transfer(writeStream, readStream, length, downloadProgress, digest)
}
openApk(activity, downloadedFile)
}
fun openApk(context: Context, file: File) {
val contentUri = FileProvider.getUriForFile(
context, BuildConfig.APPLICATION_ID + ".provider", file
)
val installIntent = Intent(Intent.ACTION_VIEW).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
data = contentUri
}
context.startActivity(installIntent)
}
}

View file

@ -1,106 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream4.viewmodels.GithubFile
import com.lagradost.cloudstream4.viewmodels.GithubRepository
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.io.FileNotFoundException
object GithubReleases : GithubRepository {
@Serializable
private data class GithubAsset(
@JsonProperty("name") @SerialName("name") val name: String,
@JsonProperty("size") @SerialName("size") val size: Int, // Size in bytes
@JsonProperty("browser_download_url") @SerialName("browser_download_url") val browserDownloadUrl: String,
@JsonProperty("content_type") @SerialName("content_type") val contentType: String, // application/vnd.android.package-archive
@JsonProperty("digest") @SerialName("digest") val digest: String? = null, // sha256:..., may be null
)
@Serializable
private data class GithubRelease(
@JsonProperty("tag_name") @SerialName("tag_name") val tagName: String, // Version code
@JsonProperty("body") @SerialName("body") val body: String, // Description
@JsonProperty("assets") @SerialName("assets") val assets: List<GithubAsset>,
@JsonProperty("target_commitish") @SerialName("target_commitish") val targetCommitish: String, // Branch
@JsonProperty("prerelease") @SerialName("prerelease") val prerelease: Boolean,
@JsonProperty("node_id") @SerialName("node_id") val nodeId: String,
@JsonProperty("created_at") @SerialName("created_at") val createdAt: String, // YYYY-MM-DDTHH:MM:SSZ
)
@Serializable
private data class GithubObject(
@JsonProperty("sha") @SerialName("sha") val sha: String, // SHA-256 hash
//@JsonProperty("type") @SerialName("type") val type: String,
///@JsonProperty("url") @SerialName("url") val url: String,
)
@Serializable
private data class GithubTag(
//@JsonProperty("node_id") @SerialName("node_id") val nodeId: String,
@JsonProperty("object") @SerialName("object") val githubObject: GithubObject,
)
const val APK_USERNAME = "recloudstream"
const val APK_REPOSITORY = "cloudstream"
const val APK_PRERELEASE = "pre-release"
const val APK_CONTENT_TYPE = "application/vnd.android.package-archive"
private val defaultHeaders = mapOf("Accept" to "application/vnd.github.v3+json")
@Throws
override suspend fun getSha(
userName: String,
repository: String,
tag: String,
): String {
return app.get(
url = "https://api.github.com/repos/$userName/$repository/git/ref/tags/$tag",
headers = defaultHeaders
).parsed<GithubTag>().githubObject.sha
}
@Throws
override suspend fun getRelease(
userName: String,
repository: String,
prerelease: Boolean,
prereleaseTag: String,
contentType: String,
): GithubFile {
val latestReleaseUrl = if (prerelease) {
// Find the release object
// https://docs.github.com/en/rest/releases/releases?apiVersion=2026-03-10#get-a-release-by-tag-name
"https://api.github.com/repos/$userName/$repository/releases/tags/$prereleaseTag"
} else {
// Just get the latest release
// https://docs.github.com/en/rest/releases/releases?apiVersion=2026-03-10#get-the-latest-release
// The latest release is the most recent non-prerelease, non-draft release, sorted by the created_at attribute
"https://api.github.com/repos/$userName/$repository/releases/latest"
}
val latestRelease = app.get(
url = latestReleaseUrl,
headers = defaultHeaders
).parsed<GithubRelease>()
// Find the first correct asset, given that we might have other binaries we release in the same version
val foundAsset = latestRelease.assets.firstOrNull { asset ->
asset.contentType == contentType
}
if (foundAsset == null) {
throw FileNotFoundException()
}
return GithubFile(
digest = foundAsset.digest,
downloadUrl = foundAsset.browserDownloadUrl,
displayName = foundAsset.name.substringBeforeLast("."),
changeLog = latestRelease.body,
tagName = latestRelease.tagName,
nodeId = latestRelease.nodeId
)
}
}

View file

@ -1,18 +1,19 @@
package com.lagradost.cloudstream3.ui.settings
import android.app.UiModeManager
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import androidx.preference.PreferenceManager
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream4.compose.DeviceLayout.Companion.isAutoTv
object Globals {
var beneneCount = 0
const val PHONE: Int = 0b00001
const val TV: Int = 0b00010
const val EMULATOR: Int = 0b00100
const val PHONE : Int = 0b001
const val TV : Int = 0b010
const val EMULATOR : Int = 0b100
private const val INVALID = -1
private var layoutId = INVALID
@ -21,9 +22,18 @@ object Globals {
return settingsManager.getInt(this.getString(R.string.app_layout_key), -1)
}
fun Context.updateTv() {
layoutId = when (getLayoutInt()) {
-1 -> if (isAutoTv(this)) TV else PHONE
private fun Context.isAutoTv(): Boolean {
val uiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager?
// AFT = Fire TV
val model = Build.MODEL.lowercase()
return uiModeManager?.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION || Build.MODEL.contains(
"AFT"
) || model.contains("firestick") || model.contains("fire tv") || model.contains("chromecast")
}
private fun Context.layoutIntCorrected(): Int {
return when(getLayoutInt()) {
-1 -> if (isAutoTv()) TV else PHONE
0 -> PHONE
1 -> TV
2 -> EMULATOR
@ -31,10 +41,14 @@ object Globals {
}
}
fun Context.updateTv() {
layoutId = layoutIntCorrected()
}
/** Returns true if the current orientation is landscape. */
fun isLandscape(): Boolean =
isLayout(TV or EMULATOR) ||
Resources.getSystem().configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
Resources.getSystem().configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
/** Returns true if the layout is any of the flags,
* so isLayout(TV or EMULATOR) is a valid statement for checking if the layout is in the emulator
@ -42,7 +56,7 @@ object Globals {
*
* Valid flags are: PHONE, TV, EMULATOR
* */
fun isLayout(flags: Int): Boolean {
fun isLayout(flags: Int) : Boolean {
return (layoutId and flags) != 0
}
}

View file

@ -1,7 +1,6 @@
package com.lagradost.cloudstream3.ui.settings
import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.os.Bundle
import android.os.CountDownTimer
@ -14,6 +13,7 @@ import androidx.appcompat.app.AlertDialog
import androidx.core.content.edit
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.preference.PreferenceManager
import androidx.preference.SwitchPreference
import androidx.recyclerview.widget.RecyclerView
@ -29,8 +29,8 @@ import com.lagradost.cloudstream3.databinding.DeviceAuthBinding
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.animeSkipApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.openSubtitlesApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.simklApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.subDlApi
@ -42,8 +42,8 @@ import com.lagradost.cloudstream3.syncproviders.SubtitleRepo
import com.lagradost.cloudstream3.syncproviders.SyncRepo
import com.lagradost.cloudstream3.ui.BasePreferenceFragmentCompat
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.getPref
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.hideOn
@ -76,7 +76,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
/** Used by nginx plugin too */
@SuppressLint("StringFormatInvalid")
fun showLoginInfo(
activity: Activity?,
activity: FragmentActivity?,
api: AuthRepo,
info: AuthUser?,
index: Int,
@ -121,7 +121,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
}
}
private fun showAccountSwitch(activity: Activity, api: AuthRepo) {
private fun showAccountSwitch(activity: FragmentActivity, api: AuthRepo) {
val accounts = api.accounts
val binding: AccountSwitchBinding =
AccountSwitchBinding.inflate(activity.layoutInflater, null, false)
@ -153,7 +153,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
@UiThread
fun showPin(activity: Activity, api: AuthRepo) {
fun showPin(activity: FragmentActivity, api: AuthRepo) {
val binding: DeviceAuthBinding =
DeviceAuthBinding.inflate(activity.layoutInflater, null, false)
@ -273,7 +273,8 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
}
fun showAppLogin(activity: Activity, api: AuthRepo) {
fun showAppLogin(activity: FragmentActivity, api: AuthRepo) {
val binding: AddAccountInputBinding =
AddAccountInputBinding.inflate(activity.layoutInflater, null, false)
val builder =
@ -314,7 +315,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
binding.createAccount.setOnClickListener {
openBrowser(
api.createAccountUrl ?: return@setOnClickListener,
activity,
activity
)
dialog.dismissSafe()
}
@ -390,7 +391,7 @@ class SettingsAccount : BasePreferenceFragmentCompat(), BiometricCallback {
}
@UiThread
fun addAccount(activity: Activity, api: AuthRepo) {
fun addAccount(activity: FragmentActivity, api: AuthRepo) {
try {
if (api.hasPin && !isLayout(PHONE)) {
showPin(activity, api)

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsAccount2 : BaseComposeFragment(), SearchableSettings by SettingsAccountScreen

View file

@ -1,148 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.content.Context
import androidx.activity.compose.LocalActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.fragment.app.FragmentActivity
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.aniListApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.animeSkipApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.kitsuApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.malApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.openSubtitlesApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.simklApi
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.subDlApi
import com.lagradost.cloudstream3.syncproviders.PlainAuthRepo
import com.lagradost.cloudstream3.syncproviders.SubtitleRepo
import com.lagradost.cloudstream3.syncproviders.SyncRepo
import com.lagradost.cloudstream3.ui.settings.SettingsAccount.Companion.addAccount
import com.lagradost.cloudstream3.ui.settings.SettingsAccount.Companion.showLoginInfo
import com.lagradost.cloudstream3.utils.AppContextUtils.html
import com.lagradost.cloudstream3.utils.BackupUtils
import com.lagradost.cloudstream3.utils.BiometricAuthenticator
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.authCallback
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.biometricPrompt
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.deviceHasPasswordPinLock
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.isAuthEnabled
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.promptInfo
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.startBiometricAuthentication
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialogText
import com.lagradost.cloudstream4.AppSettings
import com.lagradost.cloudstream4.compose.PHONE
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.rememberAppSettings
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.persistentListOf
object SettingsAccountScreen : SearchableSettings, BiometricAuthenticator.BiometricCallback {
val syncApis = persistentListOf(
SyncRepo(malApi),
SyncRepo(kitsuApi),
SyncRepo(aniListApi),
SyncRepo(simklApi),
SubtitleRepo(openSubtitlesApi),
SubtitleRepo(subDlApi),
PlainAuthRepo(animeSkipApi),
)
private fun updateAuthPreference(context: Context, enabled: Boolean) {
val settings = AppSettings(context)
settings.security.biometrics.set(enabled)
}
override fun onAuthenticationError() {
val context = activity ?: return
updateAuthPreference(context, !isAuthEnabled(context))
}
override fun onAuthenticationSuccess() {
val context = activity ?: return
if (isAuthEnabled(context)) {
updateAuthPreference(context, true)
BackupUtils.backup(context)
context.showBottomDialogText(
context.getString(R.string.biometric_setting),
context.getString(R.string.biometric_warning).html()
) { onDialogDismissedEvent }
} else {
updateAuthPreference(context, false)
}
}
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_account)
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
val activity = LocalActivity.current
val context = LocalContext.current
val hasSecurity = remember(context) {
try {
deviceHasPasswordPinLock(context)
} catch (_ : Throwable) {
// e.g preview
false
}
}
return persistentListOf(
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_accounts),
preferenceItems = syncApis.map { api ->
Preference.PreferenceItem.TextPreference(
title = api.name,
icon = api.icon?.let { painterResource(it) },
onClick = {
val activity = activity ?: return@TextPreference
val info = api.authUser()
val index =
api.accounts.indexOfFirst { account -> account.user.id == info?.id }
if (api.accounts.isNotEmpty()) {
showLoginInfo(activity, api, info, index)
} else {
addAccount(activity, api)
}
})
} + Preference.PreferenceItem.SwitchPreference(
preference = settings.security.skipAccountSelection,
title = stringResource(R.string.skip_startup_account_select_pref),
icon = painterResource(R.drawable.ic_outline_account_circle_24)
),
), Preference.PreferenceGroup(
enabled = hasSecurity && isLayout(PHONE),
title = stringResource(R.string.pref_category_security),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
preference = settings.security.biometrics,
title = stringResource(R.string.biometric_setting),
subtitle = stringResource(R.string.biometric_setting_summary),
icon = painterResource(R.drawable.ic_fingerprint),
onValueChanged = { _ ->
val activity =
activity as? FragmentActivity ?: return@SwitchPreference false
if (deviceHasPasswordPinLock(activity)) {
startBiometricAuthentication(
activity, R.string.biometric_authentication_title, false
)
promptInfo?.let {
authCallback = this
biometricPrompt?.authenticate(it)
}
}
return@SwitchPreference true
})
)
)
)
}
}

View file

@ -1,8 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.lagradost.cloudstream4.compose.Screen
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsFragment2 : BaseComposeFragment(), Screen by SettingsFragmentScreen

View file

@ -1,478 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.lagradost.cloudstream3.BuildConfig
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.profileImages
import com.lagradost.cloudstream3.utils.GitInfo.currentCommitHash
import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream4.compose.Screen
import com.lagradost.cloudstream4.compose.TV
import com.lagradost.cloudstream4.compose.circleBorder
import com.lagradost.cloudstream4.compose.focusOutline
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
import com.mihon.material.padding
import com.mihon.presentation.settings.SearchableSettings
import com.mihon.presentation.settings.SettingSearchResults
import com.mihon.presentation.settings.SettingsData
import com.mihon.presentation.settings.widget.TextPreferenceWidget
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
object SettingsFragmentScreen : Screen {
val screens = persistentListOf(
SettingsNavigation(
title = R.string.category_general,
navigation = R.id.action_navigation_global_to_navigation_settings_general,
screen = SettingsGeneralScreen,
icon = R.drawable.build_24px,
subtitle = persistentListOf(
R.string.extension_language,
R.string.title_downloads,
R.string.pref_category_bypass,
R.string.pref_category_links
)
),
SettingsNavigation(
title = R.string.category_player,
navigation = R.id.action_navigation_global_to_navigation_settings_player,
screen = SettingsPlayerScreen,
icon = R.drawable.play_arrow_24px,
subtitle = persistentListOf(
R.string.pref_category_subtitles,
R.string.pref_category_player_features,
R.string.pref_category_gestures,
R.string.pref_category_player_layout,
R.string.pref_category_cache
)
),
/*SettingsNavigation(
title = R.string.category_providers,
navigation = R.id.action_navigation_global_to_navigation_settings_providers,
screen = SettingsProvidersScreen,
icon = R.drawable.build_24px,
),*/
SettingsNavigation(
title = R.string.category_ui,
navigation = R.id.action_navigation_global_to_navigation_settings_ui,
screen = SettingsUIScreen,
icon = R.drawable.format_paint_24px,
subtitle = persistentListOf(
R.string.pref_category_looks,
R.string.pref_category_ui_features,
R.string.search_poster_img_des,
R.string.poster_ui_settings
)
),
SettingsNavigation(
title = R.string.category_updates,
navigation = R.id.action_navigation_global_to_navigation_settings_updates,
screen = SettingsUpdatesScreen,
icon = R.drawable.mobile_arrow_down_24px,
subtitle = persistentListOf(
R.string.pref_category_app_updates,
R.string.pref_category_backup,
R.string.pref_category_extensions,
R.string.pref_category_actions
)
),
SettingsNavigation(
title = R.string.category_account,
navigation = R.id.action_navigation_global_to_navigation_settings_account,
screen = SettingsAccountScreen,
icon = R.drawable.encrypted_24px,
subtitle = persistentListOf(
R.string.pref_category_accounts,
R.string.pref_category_security
)
),
SettingsNavigation(
title = R.string.pref_category_extensions,
navigation = R.id.action_navigation_global_to_navigation_settings_extensions,
screen = null,
icon = R.drawable.extension_24px,
subtitle = persistentListOf(R.string.add_repository)
),
)
@Immutable
data class SettingsNavigation(
val title: Int,
val navigation: Int,
val screen: SearchableSettings?,
val icon: Int,
val subtitle: PersistentList<Int>,
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
override fun Content() {
val textFieldState = rememberTextFieldState()
val outerListState = rememberScrollState()
val parentFirstScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
return if (delta < 0 && outerListState.canScrollForward) {
val consumed = outerListState.dispatchRawDelta(-delta)
Offset(0f, -consumed)
} else {
Offset.Zero
}
}
}
}
Scaffold { _ ->
Column(modifier = Modifier.verticalScroll(outerListState)) {
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
val default = DataStoreHelper.getDefaultAccount(
LocalContext.current
)
val flow by DataStoreHelper.selectedAccountNumberFlow.collectAsState()
val account = remember(flow) {
DataStoreHelper.getCurrentAccount() ?: default
}
Row(
modifier = Modifier
.fillMaxSize()
.focusOutline()
.clickable {
activity.navigate(
R.id.accountSelectActivity,
Bundle().apply { putBoolean("isFromMainActivity", true) }
)
}
.padding(
vertical = MaterialTheme.padding.large,
horizontal = MaterialTheme.padding.medium
)
) {
val image =
account.customImage ?: profileImages.getOrNull(account.defaultImageIndex)
?: profileImages.first()
AsyncImage(
contentScale = ContentScale.Crop,
model = image,
modifier = Modifier.circleBorder(50.dp),
contentDescription = null,
)
Spacer(modifier = Modifier.width(MaterialTheme.padding.medium))
Column {
Text(
text = account.name,
style = MaterialTheme.typography.titleLarge,
)
Text(
text = stringResource(R.string.title_settings),
style = MaterialTheme.typography.bodyMedium,
)
}
}
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
SettingsSearch(textFieldState = textFieldState)
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
SettingSearchResults(
nestedScrollConnection = parentFirstScrollConnection,
searchKey = textFieldState.text.toString(),
deferredItems = ::generateSearchItems,
onItemClick = { item ->
SearchableSettings.highlightKey = item.highlightKey
activity?.navigate(item.navigation)
}, empty = {
Column(
modifier = Modifier
.nestedScroll(parentFirstScrollConnection)
) {
screens.forEach { settingsTab ->
SettingsTab(settingsTab)
}
BuildStamp()
}
})
}
}
}
@Composable
@NonRestartableComposable
fun generateSearchItems() =
screens.mapNotNull { item ->
val contents = item.screen?.getPreferences() ?: return@mapNotNull null
SettingsData(
title = stringResource(item.title),
navigation = item.navigation,
contents = contents
)
}.toPersistentList()
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun SettingsSearch(textFieldState: TextFieldState) {
var hasFocus by remember { mutableStateOf(false) }
var isWritable by remember { mutableStateOf(false) }
val focusProgress by animateFloatAsState(targetValue = if (hasFocus) 1.0f else 0.0f)
val focusManager = LocalFocusManager.current
val focusRequester = remember { FocusRequester() }
val isTv = isLayout(TV)
TextField(
state = textFieldState,
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Search,
/**
* We do not want to pull up the keyboard when navigating to the item on TV, therefore
* we listen to when the TV user presses some key to "extra" focus it
*
* showKeyboardOnFocus is somewhat bugged, so need to change this to true when you
* press it, as otherwise no keyboard will show even with keyboardController
* */
showKeyboardOnFocus = if (isTv) isWritable else true
),
lineLimits = TextFieldLineLimits.SingleLine,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp - 12.dp * focusProgress)
.focusOutline(enabled = isTv, CircleShape)
.onFocusChanged { newFocus ->
hasFocus = newFocus.hasFocus
/** Loss of focus -> readonly */
if (!newFocus.hasFocus) {
isWritable = false
}
}
.focusRequester(focusRequester)
.onPreviewKeyEvent { keyEvent ->
if (isWritable || !isTv || !hasFocus || keyEvent.type != KeyEventType.KeyUp) {
return@onPreviewKeyEvent false
}
/** Focus + press once -> writable */
return@onPreviewKeyEvent when (keyEvent.key) {
Key.Enter, Key.DirectionCenter, Key.NumPadEnter, Key.Spacebar -> {
isWritable = true
true
}
else -> false
}
},
placeholder = {
Text(text = stringResource(R.string.search_hint))
},
shape = CircleShape,
colors = TextFieldDefaults.colors(
focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
unfocusedLeadingIconColor = MaterialTheme.colorScheme.onBackground,
unfocusedTrailingIconColor = MaterialTheme.colorScheme.onBackground,
focusedTrailingIconColor = MaterialTheme.colorScheme.onBackground,
focusedLeadingIconColor = MaterialTheme.colorScheme.onBackground,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedPlaceholderColor = MaterialTheme.colorScheme.onSurfaceVariant,
unfocusedPlaceholderColor = MaterialTheme.colorScheme.onSurfaceVariant,
cursorColor = MaterialTheme.colorScheme.onBackground,
),
leadingIcon = {
Crossfade(
targetState = hasFocus,
label = "leftsearch",
) { value ->
if (value) {
IconButton(onClick = {
textFieldState.edit { replace(0, length, "") }
focusManager.clearFocus()
}) {
Icon(
painter = painterResource(R.drawable.keyboard_arrow_left_24px),
contentDescription = null
)
}
} else {
IconButton(onClick = {
focusRequester.requestFocus()
}) {
Icon(
painter = painterResource(R.drawable.search_icon),
contentDescription = null
)
}
}
}
},
trailingIcon = {
Crossfade(
targetState = hasFocus,
label = "rightsearch",
) { value ->
if (value) {
IconButton(onClick = {
textFieldState.edit { replace(0, length, "") }
}) {
Icon(
painter = painterResource(R.drawable.close_24px),
contentDescription = null
)
}
}
}
},
)
val keyboardController = LocalSoftwareKeyboardController.current
DisposableEffect(Unit) {
onDispose {
keyboardController?.hide()
}
}
}
@Composable
fun SettingsTab(settingsTab: SettingsNavigation) {
TextPreferenceWidget(
title = stringResource(settingsTab.title),
icon = painterResource(settingsTab.icon),
// This can not be converted to joinToString due to stringResource being composable
subtitle =
@Suppress("SimplifiableCallChain")
settingsTab.subtitle.map { stringResource(it) }.joinToString(),
// Clear it if we have already set it but navigated back instantly
onPreferenceClick = {
SearchableSettings.highlightKey = null
activity?.navigate(settingsTab.navigation)
})
}
@Composable
fun BuildStamp() {
val (commitHash, buildTimestamp) = remember {
val commitHash = activity?.currentCommitHash() ?: ""
val buildTimestamp = SimpleDateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.MEDIUM,
Locale.getDefault()
).apply {
timeZone = TimeZone.getTimeZone("UTC")
}.format(Date(BuildConfig.BUILD_DATE)).replace("UTC", "")
commitHash to buildTimestamp
}
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.focusOutline()
.clickable {
clipboardHelper(
txt(R.string.extension_version),
"${BuildConfig.VERSION_NAME} $commitHash $buildTimestamp"
)
},
) {
ProvideTextStyle(MaterialTheme.typography.bodyMedium) {
Text(text = BuildConfig.VERSION_NAME)
if (commitHash != "") {
Text("•")
Text(text = commitHash)
}
Text("•")
Text(text = buildTimestamp)
}
}
}
}
@PreviewLightDark
@Composable
fun Preview() {
CloudStreamPreviewTheme {
SettingsFragmentScreen.Content()
}
}

View file

@ -3,7 +3,6 @@ package com.lagradost.cloudstream3.ui.settings
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
@ -18,7 +17,6 @@ import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.R
@ -79,7 +77,6 @@ val appLanguages = arrayListOf(
Pair("Azərbaycan dili", "az"),
Pair("Bahasa Indonesia", "in"),
Pair("Bahasa Melayu", "ms"),
Pair("català", "ca"),
Pair("Deutsch", "de"),
Pair("English", "en"),
Pair("Español", "es"),
@ -100,7 +97,6 @@ val appLanguages = arrayListOf(
Pair("Português", "pt"),
Pair("Português (Brasil)", "pt-BR"),
Pair("Română", "ro"),
Pair("Shqip мова", "sq"),
Pair("Slovenčina", "sk"),
Pair("Soomaaliga", "so"),
Pair("Svenska", "sv"),
@ -110,7 +106,6 @@ val appLanguages = arrayListOf(
Pair("Wikang Filipino", "fil"),
Pair("Čeština", "cs"),
Pair("Ελληνικά", "el"),
Pair("беларуская мова", "be"),
Pair("български", "bg"),
Pair("македонски", "mk"),
Pair("русский", "ru"),
@ -130,7 +125,6 @@ val appLanguages = arrayListOf(
Pair("தமிழ்", "ta"),
Pair("ಕನ್ನಡ", "kn"),
Pair("മലയാളം", "ml"),
Pair("ພາສາລາວ", "lo"),
Pair("ဗမာစာ", "my"),
Pair("ትግርኛ", "ti"),
Pair("አማርኛ", "am"),
@ -178,96 +172,6 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
putString(context.getString(R.string.download_path_key_visual), visual)
}
}
fun getCurrent(): MutableList<CustomSite> {
return getKey<Array<CustomSite>>(USER_PROVIDER_API)?.toMutableList()
?: mutableListOf()
}
fun showAdd() {
val providers = allProviders.distinctBy { it::class }.sortedBy { it.name }
val context = activity
context?.showDialog(
providers.map { "${it.name} (${it.mainUrl})" },
-1,
context.getString(R.string.add_site_pref),
true,
{}) { selection ->
val provider = providers.getOrNull(selection) ?: return@showDialog
val binding : AddSiteInputBinding = AddSiteInputBinding.inflate(LayoutInflater.from(
context
),null,false)
val builder =
AlertDialog.Builder(context, R.style.AlertDialogCustom)
.setView(binding.root)
val dialog = builder.create()
dialog.show()
binding.text2.text = provider.name
binding.applyBtt.setOnClickListener {
val name = binding.siteNameInput.text?.toString()
val url = binding.siteUrlInput.text?.toString()
val lang = binding.siteLangInput.text?.toString()
val realLang = if (lang.isNullOrBlank()) provider.lang else lang
val simpleName = provider::class.simpleName
if (url.isNullOrBlank() || name.isNullOrBlank() || simpleName == null) {
showToast(R.string.error_invalid_data, Toast.LENGTH_SHORT)
return@setOnClickListener
}
val current = getCurrent()
val newSite = CustomSite(simpleName, name, url, realLang)
current.add(newSite)
setKey(USER_PROVIDER_API, current.toTypedArray())
// reload apis
MainActivity.afterPluginsLoadedEvent.invoke(false)
dialog.dismissSafe(activity)
}
binding.cancelBtt.setOnClickListener {
dialog.dismissSafe(activity)
}
}
}
fun showDelete() {
val current = getCurrent()
val context = activity
context?.showMultiDialog(
current.map { it.name },
listOf(),
context.getString(R.string.remove_site_pref),
{}) { indexes ->
current.removeAll(indexes.map { current[it] })
setKey(USER_PROVIDER_API, current.toTypedArray())
}
}
fun showAddOrDelete() {
val context = activity
val binding : AddRemoveSitesBinding = AddRemoveSitesBinding.inflate(
LayoutInflater.from(
context
),null,false)
val builder =
AlertDialog.Builder(context ?: return, R.style.AlertDialogCustom)
.setView(binding.root)
val dialog = builder.create()
dialog.show()
binding.addSite.setOnClickListener {
showAdd()
dialog.dismissSafe(activity)
}
binding.removeSite.setOnClickListener {
showDelete()
dialog.dismissSafe(activity)
}
}
}
private val pathPicker = getChooseFolderLauncher { uri, path ->
@ -279,6 +183,10 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
setPreferencesFromResource(R.xml.settings_general, rootKey)
val settingsManager = PreferenceManager.getDefaultSharedPreferences(requireContext())
fun getCurrent(): MutableList<CustomSite> {
return getKey<Array<CustomSite>>(USER_PROVIDER_API)?.toMutableList()
?: mutableListOf()
}
getPref(R.string.locale_key)?.setOnPreferenceClickListener { pref ->
val current = getCurrentLocale(pref.context)
@ -315,7 +223,83 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
true
}
fun showAdd() {
val providers = allProviders.distinctBy { it::class }.sortedBy { it.name }
activity?.showDialog(
providers.map { "${it.name} (${it.mainUrl})" },
-1,
context?.getString(R.string.add_site_pref) ?: return,
true,
{}) { selection ->
val provider = providers.getOrNull(selection) ?: return@showDialog
val binding : AddSiteInputBinding = AddSiteInputBinding.inflate(layoutInflater,null,false)
val builder =
AlertDialog.Builder(context ?: return@showDialog, R.style.AlertDialogCustom)
.setView(binding.root)
val dialog = builder.create()
dialog.show()
binding.text2.text = provider.name
binding.applyBtt.setOnClickListener {
val name = binding.siteNameInput.text?.toString()
val url = binding.siteUrlInput.text?.toString()
val lang = binding.siteLangInput.text?.toString()
val realLang = if (lang.isNullOrBlank()) provider.lang else lang
val simpleName = provider::class.simpleName
if (url.isNullOrBlank() || name.isNullOrBlank() || simpleName == null) {
showToast(R.string.error_invalid_data, Toast.LENGTH_SHORT)
return@setOnClickListener
}
val current = getCurrent()
val newSite = CustomSite(simpleName, name, url, realLang)
current.add(newSite)
setKey(USER_PROVIDER_API, current.toTypedArray())
// reload apis
MainActivity.afterPluginsLoadedEvent.invoke(false)
dialog.dismissSafe(activity)
}
binding.cancelBtt.setOnClickListener {
dialog.dismissSafe(activity)
}
}
}
fun showDelete() {
val current = getCurrent()
activity?.showMultiDialog(
current.map { it.name },
listOf(),
context?.getString(R.string.remove_site_pref) ?: return,
{}) { indexes ->
current.removeAll(indexes.map { current[it] })
setKey(USER_PROVIDER_API, current.toTypedArray())
}
}
fun showAddOrDelete() {
val binding : AddRemoveSitesBinding = AddRemoveSitesBinding.inflate(layoutInflater,null,false)
val builder =
AlertDialog.Builder(context ?: return, R.style.AlertDialogCustom)
.setView(binding.root)
val dialog = builder.create()
dialog.show()
binding.addSite.setOnClickListener {
showAdd()
dialog.dismissSafe(activity)
}
binding.removeSite.setOnClickListener {
showDelete()
dialog.dismissSafe(activity)
}
}
getPref(R.string.override_site_key)?.setOnPreferenceClickListener { _ ->
@ -342,7 +326,7 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
val prefValues = resources.getIntArray(R.array.dns_pref_values)
val currentDns =
settingsManager.getInt(getString(R.string.dns_key), 0)
settingsManager.getInt(getString(R.string.dns_pref), 0)
activity?.showBottomDialog(
prefNames.toList(),
@ -350,7 +334,7 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
getString(R.string.dns_pref),
true,
{}) {
settingsManager.edit { putInt(getString(R.string.dns_key), prefValues[it]) }
settingsManager.edit { putInt(getString(R.string.dns_pref), prefValues[it]) }
(context ?: CloudStreamApp.context)?.let { ctx -> app.initClient(ctx) }
}
return@setOnPreferenceClickListener true
@ -368,14 +352,14 @@ class SettingsGeneral : BasePreferenceFragmentCompat() {
(first +
ctx.getExternalFilesDirs("").mapNotNull { it.path } +
currentDir)
} catch (_: Exception) {
} catch (e: Exception) {
first
}).filterNotNull().distinct()
}
} ?: emptyList()
}
settingsManager.edit { putBoolean(getString(R.string.jsdelivr_proxy_key), getKey<Boolean>(getString(R.string.jsdelivr_proxy_key), false) ?: false) }
settingsManager.edit { putBoolean(getString(R.string.jsdelivr_proxy_key), getKey(getString(R.string.jsdelivr_proxy_key), false) ?: false) }
getPref(R.string.jsdelivr_proxy_key)?.setOnPreferenceChangeListener { _, newValue ->
setKey(getString(R.string.jsdelivr_proxy_key), newValue)
return@setOnPreferenceChangeListener true

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsGeneral2 : BaseComposeFragment(), SearchableSettings by SettingsGeneralScreen

View file

@ -1,305 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.integerArrayResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.PreviewLightDark
import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.UnsafeSSL
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.insecureApp
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.network.initClient
import com.lagradost.cloudstream3.ui.settings.SettingsProvidersScreen.toStringRes
import com.lagradost.cloudstream3.utils.BatteryOptimizationChecker.isAppRestricted
import com.lagradost.cloudstream3.utils.BatteryOptimizationChecker.showRequestIgnoreBatteryOptDialog
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
import com.lagradost.cloudstream3.utils.SubtitleHelper.getNameNextToFlagEmoji
import com.lagradost.cloudstream4.AppSettings
import com.lagradost.cloudstream4.compose.ActionDialog
import com.lagradost.cloudstream4.compose.PHONE
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.rememberAppSettings
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
import com.lagradost.safefile.SafeFile
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import com.mihon.presentation.settings.collectAsState
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentMap
object SettingsGeneralScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_general)
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
// TODO Refactor entirely to use a different file path selector ect like QuickNovel
val selectFileSelector =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
// It lies, it can be null if file manager quits.
if (uri == null) return@rememberLauncherForActivityResult
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
try {
val settings = AppSettings(context)
// RW perms for the path
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(uri, flags)
val filePath = SafeFile.fromUri(context, uri)?.filePath()
println("Selected URI path: $uri - Full path: $filePath")
// store the actual URI instead of the path due to permissions.
// filePath should only be used for cosmetic purposes.
val visual = filePath ?: uri.toString()
settings.general.downloadPath.set(uri.toString())
settings.general.downloadPathVisual.set(visual)
} catch (t: Throwable) {
logError(t)
}
}
val bananas by settings.general.bananas.collectAsState()
val downloadPathVisual by settings.general.downloadPathVisual.collectAsState()
//val downloadPath by settings.general.downloadPath.collectAsState()
var isBatteryShown by remember { mutableStateOf(false) }
val context = LocalContext.current
if (isBatteryShown) {
ActionDialog(
icon = painterResource(R.drawable.battery_alert_24px),
title = stringResource(R.string.battery_dialog_title),
text = stringResource(R.string.battery_dialog_message),
confirmText = stringResource(R.string.ok),
dismissText = stringResource(R.string.cancel),
dismiss = {
isBatteryShown = false
settings.general.batterOptimization.set(false)
},
confirm = {
isBatteryShown = false
// The og impl never modified it to true?
// settings.general.batterOptimization.set(true)
context.showRequestIgnoreBatteryOptDialog()
}
)
}
val default = AllLanguagesName to stringResource(R.string.all_languages_preference)
val languages = APIHolder.apis.withLock {
APIHolder.apis.map { api -> api.lang }.distinct()
}.sortedBy { fromTagToLanguageName(it) ?: it }
return persistentListOf(
Preference.PreferenceGroup(title = stringResource(R.string.extension_language), preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = settings.general.locale,
entries = appLanguages.associate { (name, code) -> (code to (name to code).nameNextToFlagEmoji()) },
title = stringResource(R.string.app_language),
icon = painterResource(R.drawable.language_korean_latin_24px),
onValueChanged = { value ->
settings.general.locale.set(value)
activity?.recreate()
return@ListPreference false
},
subtitleProvider = { v, e -> e[v] ?: getCurrentLocale(LocalContext.current) }
),
Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.provider_lang_settings),
icon = painterResource(R.drawable.plugin_lang),
entries = mapOf(default) + languages.associateWith { lang ->
(getNameNextToFlagEmoji(
lang
) ?: lang)
},
preference = settings.provider.extensionLanguages
),
Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.preferred_media_settings),
icon = painterResource(R.drawable.movie_edit_24px),
preference = settings.provider.preferredMedia,
entries = TvType.entries.associate {
it.ordinal.toString() to stringResource(it.toStringRes())
}
// Ok this looks strange af, but we do this to avoid double movie
.toPersistentMap().remove(TvType.AnimeMovie.ordinal.toString()), onValueChanged = { diff ->
if(diff.contains(TvType.Movie.ordinal.toString())) {
settings.provider.preferredMedia.set(diff + TvType.AnimeMovie.ordinal.toString())
} else {
settings.provider.preferredMedia.set(diff - TvType.AnimeMovie.ordinal.toString())
}
return@MultiSelectListPreference false
}),
)),
Preference.PreferenceGroup(
title = stringResource(R.string.title_downloads),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
icon = painterResource(R.drawable.netflix_download),
subtitle = downloadPathVisual,
title = stringResource(R.string.download_path_pref),
onClick = {
// This is not a ListPreference because the old selection system is
// broken af. This needs to be refactored to QuickNovels download path
// system.
selectFileSelector.launch(Uri.EMPTY)
},
),
Preference.PreferenceItem.SliderPreference(
icon = painterResource(R.drawable.arrow_or_edge_24px),
preference = settings.general.parallelDownloads,
valueRange = 1..10,
title = stringResource(R.string.parallel_downloads),
subtitle = stringResource(R.string.download_parallel_settings_des),
),
Preference.PreferenceItem.SliderPreference(
icon = painterResource(R.drawable.arrow_and_edge_24px),
preference = settings.general.concurrentConnections,
valueRange = 1..10,
title = stringResource(R.string.concurrent_connections),
subtitle = stringResource(R.string.concurrent_connections_settings_des),
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.battery_dialog_title),
icon = painterResource(R.drawable.battery_alert_24px),
enabled = isLayout(PHONE),
onClick = {
if (isAppRestricted(context)) {
isBatteryShown = true
} else {
showToast(R.string.app_unrestricted_toast)
}
}
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_bypass),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.add_site_pref),
subtitle = stringResource(R.string.add_site_summary),
icon = painterResource(R.drawable.copy_all_24px),
onClick = {
// TODO refactor into compose
if (SettingsGeneral.getCurrent().isEmpty()) {
SettingsGeneral.showAdd()
} else {
SettingsGeneral.showAddOrDelete()
}
}
),
Preference.PreferenceItem.ListPreference(
title = stringResource(R.string.dns_pref),
subtitle = stringResource(R.string.dns_pref_summary),
icon = painterResource(R.drawable.dns_24px),
preference = settings.general.dns,
entries = integerArrayResource(R.array.dns_pref_values).zip(
stringArrayResource(R.array.dns_pref)
).toMap(),
onValueChanged = { newValue ->
settings.general.dns.set(newValue) // Must set the value before initClient is called
(CloudStreamApp.context)?.let { ctx ->
app.initClient(ctx, ignoreSSL = false)
@OptIn(UnsafeSSL::class)
insecureApp.initClient(ctx, ignoreSSL = true)
}
return@ListPreference true
},
),
Preference.PreferenceItem.SwitchPreference(
title = stringResource(R.string.jsdelivr_proxy),
subtitle = stringResource(R.string.jsdelivr_proxy_summary),
icon = painterResource(R.drawable.wifi_proxy_24px),
preference = settings.general.jsdelivrProxy
)
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_links),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.github),
subtitle = "https://github.com/recloudstream/cloudstream",
icon = painterResource(R.drawable.ic_github_logo),
onClick = {
CloudStreamApp.openBrowser("https://github.com/recloudstream/cloudstream")
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.lightnovel),
subtitle = "https://github.com/LagradOst/QuickNovel",
icon = painterResource(R.drawable.quick_novel_icon),
onClick = {
CloudStreamApp.openBrowser("https://github.com/LagradOst/QuickNovel")
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.discord),
subtitle = "https://discord.gg/5Hus6fM",
icon = painterResource(R.drawable.ic_baseline_discord_24),
onClick = {
CloudStreamApp.openBrowser("https://discord.gg/5Hus6fM")
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.cs3wiki),
subtitle = "https://cloudstream.miraheze.org/",
icon = painterResource(R.drawable.description_24px),
onClick = {
CloudStreamApp.openBrowser("https://cloudstream.miraheze.org/")
}
),
)
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.benene),
subtitle = if (bananas == 0) {
stringResource(R.string.benene_count_text_none)
} else {
stringResource(R.string.benene_count_text, bananas)
},
onClick = {
settings.general.bananas.set(bananas + 1)
},
icon = painterResource(R.drawable.benene),
),
Preference.PreferenceItem.InfoPreference(title = stringResource(R.string.legal_notice_text)),
)
}
}
@PreviewLightDark
@Composable
private fun SettingGeneralPreview() {
CloudStreamPreviewTheme {
SettingsGeneralScreen.Content()
}
}

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsPlayer2 : BaseComposeFragment(), SearchableSettings by SettingsPlayerScreen

View file

@ -1,358 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.text.format.Formatter.formatShortFileSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.integerArrayResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import com.lagradost.cloudstream3.ui.player.source_priority.QualityProfileDialog
import com.lagradost.cloudstream3.ui.settings.SettingsFragment.Companion.getFolderSize
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream4.compose.EMULATOR
import com.lagradost.cloudstream4.compose.PHONE
import com.lagradost.cloudstream4.compose.TV
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.rememberAppSettings
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.reflect.jvm.jvmName
object SettingsPlayerScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_player)
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
val context = LocalContext.current
val defaultPlayerName = stringResource(R.string.player_settings_play_in_app)
val players = remember(context) {
mapOf("" to defaultPlayerName) + VideoClickActionHolder.getPlayers()
.associate { player ->
player.uniqueId() to (player.name.asStringNull(context)
?: player::class.simpleName ?: player::class.jvmName)
}
}
var cacheSize by remember { mutableLongStateOf(0L) }
var cacheCleared by remember { mutableIntStateOf(0) }
val cacheDir = LocalContext.current.cacheDir
LaunchedEffect(cacheCleared) {
withContext(Dispatchers.IO) {
cacheSize = getFolderSize(cacheDir)
}
}
return persistentListOf(
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_subtitles),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.player_subtitles_settings),
subtitle = stringResource(R.string.player_subtitles_settings_des),
icon = painterResource(R.drawable.subtitles_gear_24px),
onClick = {
SubtitlesFragment.push(activity, false)
}),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.chromecast_subtitles_settings),
subtitle = stringResource(R.string.chromecast_subtitles_settings_des),
icon = painterResource(R.drawable.cast),
onClick = {
ChromecastSubtitlesFragment.push(activity, false)
}),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_player_features),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
title = stringResource(R.string.player_pref),
icon = painterResource(R.drawable.play_arrow_24px),
preference = settings.player.defaultPlayer,
entries = players,
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.source_priority),
subtitle = stringResource(R.string.source_priority_help),
icon = painterResource(R.drawable.ic_baseline_people_24),
onClick = {
ioSafe {
val defaultSources = QualityProfileDialog.getAllDefaultSources()
val activity = activity ?: return@ioSafe
activity.runOnUiThread {
QualityProfileDialog(
activity,
R.style.DialogFullscreenPlayer,
defaultSources,
).show()
}
}
}),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.pipEnabled,
title = stringResource(R.string.picture_in_picture),
subtitle = stringResource(R.string.picture_in_picture_des),
icon = painterResource(R.drawable.pip_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.resizeEnabled,
title = stringResource(R.string.player_size_settings),
subtitle = stringResource(R.string.player_size_settings_des),
icon = painterResource(R.drawable.aspect_ratio_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.speedEnabled,
title = stringResource(R.string.eigengraumode_settings),
subtitle = stringResource(R.string.speed_setting_summary),
icon = painterResource(R.drawable.ic_baseline_speed_24),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.compressorEnabled,
title = stringResource(R.string.compressor_setting),
subtitle = stringResource(R.string.compressor_setting_summary),
icon = painterResource(R.drawable.ic_compressor_24),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.tiktokEnabled,
title = stringResource(R.string.speedup_title),
subtitle = stringResource(R.string.speedup_summary),
icon = painterResource(R.drawable.speedup),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.autoPlayEnabled,
title = stringResource(R.string.autoplay_next_settings),
subtitle = stringResource(R.string.autoplay_next_settings_des),
icon = painterResource(R.drawable.skip_next_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.startPaused,
title = stringResource(R.string.start_paused_settings),
subtitle = stringResource(R.string.start_paused_settings_des),
icon = painterResource(R.drawable.pause_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.skipOpEnabled,
title = stringResource(R.string.video_skip_op),
subtitle = stringResource(R.string.enable_skip_op_from_database_des),
icon = painterResource(R.drawable.keyboard_double_arrow_right_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.autoRotateEnabled,
title = stringResource(R.string.auto_rotate_video),
subtitle = stringResource(R.string.auto_rotate_video_desc),
icon = painterResource(R.drawable.screen_rotation_alt_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.rotateButtonEnabled,
title = stringResource(R.string.rotate_video),
subtitle = stringResource(R.string.rotate_video_desc),
icon = painterResource(R.drawable.screen_rotation),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.previewBarEnabled,
enabled = isLayout(PHONE or EMULATOR),
title = stringResource(R.string.preview_seekbar),
subtitle = stringResource(R.string.preview_seekbar_desc),
icon = painterResource(R.drawable.picture_in_picture_center_24px),
),
Preference.PreferenceItem.ListPreference(
preference = settings.player.softwareDecoding,
title = stringResource(R.string.software_decoding),
subtitle = stringResource(R.string.software_decoding_desc),
icon = painterResource(R.drawable.memory_24px),
entries = integerArrayResource(R.array.software_decoding_switch_values).zip(
stringArrayResource(R.array.software_decoding_switch)
).toMap()
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.extraBrightnessEnabled,
title = stringResource(R.string.extra_brightness_settings),
subtitle = stringResource(R.string.extra_brightness_settings_des),
icon = painterResource(R.drawable.light_mode_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.episodeSync,
title = stringResource(R.string.episode_sync_settings),
subtitle = stringResource(R.string.episode_sync_settings_des),
icon = painterResource(R.drawable.autorenew_24px)
),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_gestures),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.swipeHorizontalEnabled,
title = stringResource(R.string.swipe_to_seek_settings),
subtitle = stringResource(R.string.swipe_to_seek_settings_des),
icon = painterResource(R.drawable.swipe_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.swipeVerticalEnabled,
title = stringResource(R.string.swipe_to_change_settings),
subtitle = stringResource(R.string.swipe_to_change_settings_des),
icon = painterResource(R.drawable.swipe_vertical_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.doubleTapToSeekEnabled,
title = stringResource(R.string.double_tap_to_seek_settings),
subtitle = stringResource(R.string.double_tap_to_seek_settings_des),
icon = painterResource(R.drawable.touch_double_24px),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.doubleTapToPauseEnabled,
title = stringResource(R.string.double_tap_to_pause_settings),
subtitle = stringResource(R.string.double_tap_to_pause_settings_des),
icon = painterResource(R.drawable.touch_double_24px),
),
Preference.PreferenceItem.SliderPreference(
preference = settings.player.doubleTapTime,
title = stringResource(R.string.double_tap_to_seek_amount_settings),
icon = painterResource(R.drawable.go_forward_30),
valueRange = 5..60,
//steps = 10,
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_android_tv),
enabled = isLayout(TV or EMULATOR),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SliderPreference(
preference = settings.player.tvSeekOnTime,
title = stringResource(R.string.android_tv_interface_on_seek_settings),
subtitle = stringResource(R.string.android_tv_interface_on_seek_settings_summary),
icon = painterResource(R.drawable.go_forward_30),
valueRange = 5..60,
//steps = 10,
),
Preference.PreferenceItem.SliderPreference(
preference = settings.player.tvSeekOffTime,
title = stringResource(R.string.android_tv_interface_off_seek_settings),
subtitle = stringResource(R.string.android_tv_interface_off_seek_settings_summary),
icon = painterResource(R.drawable.go_forward_30),
valueRange = 5..60,
//steps = 10,
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_player_layout),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = settings.player.limitPlayerTitle,
title = stringResource(R.string.limit_title),
icon = painterResource(R.drawable.match_word_24px),
entries = integerArrayResource(R.array.limit_title_pref_values).zip(
stringArrayResource(R.array.limit_title_pref_names)
).toMap()
),
Preference.PreferenceItem.SwitchPreference(
enabled = isLayout(PHONE or EMULATOR),
preference = settings.player.hidePlayerControlNames,
icon = painterResource(R.drawable.visibility_off_24px),
title = stringResource(R.string.hide_player_control_names),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.showName,
icon = painterResource(R.drawable.label_24px),
title = stringResource(R.string.source_name),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.showMediaInfo,
icon = painterResource(R.drawable.movie_info_24px),
title = stringResource(R.string.video_info),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.player.showResolution,
title = stringResource(R.string.resolution),
icon = painterResource(R.drawable.high_res_24px),
),
// Unsure if we want to have MultiSelectListPreference or boolean
/*Preference.PreferenceItem.MultiSelectListPreference(
preference = settings.player.showPlayerInfo,
title = stringResource(R.string.limit_title_rez),
icon = painterResource(R.drawable.ic_baseline_text_format_24),
entries = persistentMapOf(
ShowPlayerInfo.Name to stringResource(R.string.source_name),
ShowPlayerInfo.Resolution to stringResource(R.string.resolution),
ShowPlayerInfo.VideoInfo to stringResource(R.string.video_info),
)
), */
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_cache),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = settings.player.bufferDiskMB,
title = stringResource(R.string.video_buffer_disk_settings),
subtitle = "%s\n" + stringResource(R.string.video_disk_description),
icon = painterResource(R.drawable.hard_drive_24px),
entries = integerArrayResource(R.array.video_buffer_size_values).zip(
stringArrayResource(R.array.video_buffer_size_names)
).toMap()
),
Preference.PreferenceItem.ListPreference(
preference = settings.player.bufferRamMB,
title = stringResource(R.string.video_buffer_size_settings),
subtitle = "%s\n" + stringResource(R.string.video_ram_description),
icon = painterResource(R.drawable.memory_alt_24px),
entries = integerArrayResource(R.array.video_buffer_size_values).zip(
stringArrayResource(R.array.video_buffer_size_names)
).toMap()
),
Preference.PreferenceItem.ListPreference(
preference = settings.player.bufferTimeSec,
title = stringResource(R.string.video_buffer_length_settings),
subtitle = "%s\n" + stringResource(R.string.video_ram_description),
icon = painterResource(R.drawable.history_toggle_off_24px),
entries = integerArrayResource(R.array.video_buffer_length_values).zip(
stringArrayResource(R.array.video_buffer_length_names)
).toMap()
),
Preference.PreferenceItem.TextPreference(
icon = painterResource(R.drawable.ic_baseline_delete_outline_24),
title = stringResource(R.string.video_buffer_clear_settings),
subtitle = formatShortFileSize(LocalContext.current, cacheSize),
onClick = {
ioSafe {
cacheDir.deleteRecursively()
cacheCleared += 1
}
})
)
),
)
}
}

View file

@ -109,8 +109,7 @@ class SettingsProviders : BasePreferenceFragmentCompat() {
return@setOnPreferenceClickListener true
}
getPref(R.string.
provider_lang_key)?.setOnPreferenceClickListener {
getPref(R.string.provider_lang_key)?.setOnPreferenceClickListener {
activity?.getApiProviderLangSettings()?.let { currentLangTags ->
val languagesTagName = APIHolder.apis.withLock {
listOf(Pair(AllLanguagesName, getString(R.string.all_languages_preference))) +

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
@Deprecated("This setting was merged into other places")
class SettingsProviders2 : BaseComposeFragment(), SearchableSettings by SettingsProvidersScreen

View file

@ -1,89 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.DubStatus
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToLanguageName
import com.lagradost.cloudstream3.utils.SubtitleHelper.getNameNextToFlagEmoji
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream4.rememberAppSettings
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.persistentListOf
@Deprecated("This setting was merged into other places")
object SettingsProvidersScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_providers)
fun TvType.toStringRes() = when (this) {
TvType.TvSeries -> R.string.tv_series_singular
TvType.Anime -> R.string.anime_singular
TvType.OVA -> R.string.ova_singular
TvType.AnimeMovie -> R.string.movies_singular
TvType.Cartoon -> R.string.cartoons_singular
TvType.Documentary -> R.string.documentaries_singular
TvType.Movie -> R.string.movies_singular
TvType.Torrent -> R.string.torrent_singular
TvType.AsianDrama -> R.string.asian_drama_singular
TvType.Live -> R.string.live_singular
TvType.Others -> R.string.other_singular
TvType.NSFW -> R.string.nsfw_singular
TvType.Music -> R.string.music_singular
TvType.AudioBook -> R.string.audio_book_singular
TvType.CustomMedia -> R.string.custom_media_singular
TvType.Audio -> R.string.audio_singular
TvType.Podcast -> R.string.podcast_singular
TvType.Video -> R.string.video_singular
}
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
val default = AllLanguagesName to stringResource(R.string.all_languages_preference)
val languages = APIHolder.apis.withLock {
APIHolder.apis.map { api -> api.lang }.distinct()
}.sortedBy { fromTagToLanguageName(it) ?: it }
return persistentListOf(
Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.provider_lang_settings),
icon = painterResource(R.drawable.plugin_lang),
entries = mapOf(default) + languages.associateWith { lang ->
(getNameNextToFlagEmoji(
lang
) ?: lang)
},
preference = settings.provider.extensionLanguages
), Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.preferred_media_settings),
icon = painterResource(R.drawable.movie_edit_24px),
preference = settings.provider.preferredMedia,
entries = TvType.entries.associate {
it.ordinal.toString() to stringResource(it.toStringRes())
}),
Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.display_subbed_dubbed_settings),
icon = painterResource(R.drawable.audio_capture_24px),
preference = settings.provider.displayDubSub,
entries = mapOf(
DubStatus.None.name to stringResource(R.string.none),
DubStatus.Dubbed.name to stringResource(R.string.app_dubbed_text),
DubStatus.Subbed.name to stringResource(R.string.app_subbed_text),
)
), Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.test_extensions),
subtitle = stringResource(R.string.test_extensions_summary),
icon = painterResource(R.drawable.baseline_network_ping_24),
onClick = {
activity?.navigate(R.id.navigation_test_providers)
}))
}
}

View file

@ -228,8 +228,6 @@ class SettingsUI : BasePreferenceFragmentCompat() {
return@setOnPreferenceClickListener true
}
getPref(R.string.tv_layout_clock_key)?.hideOn(PHONE or EMULATOR)
getPref(R.string.confirm_exit_key)?.setOnPreferenceClickListener {
val prefNames = resources.getStringArray(R.array.confirm_exit)
val prefValues = resources.getIntArray(R.array.confirm_exit_values)

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsUI2 : BaseComposeFragment(), SearchableSettings by SettingsUIScreen

View file

@ -1,303 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.integerArrayResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.DubStatus
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.SearchQuality
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.ui.clear
import com.lagradost.cloudstream3.ui.home.HomeChildItemAdapter
import com.lagradost.cloudstream3.ui.home.ParentItemAdapter
import com.lagradost.cloudstream3.ui.search.SearchAdapter
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream4.compose.TV
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.rememberAppSettings
import com.lagradost.cloudstream4.theme.CloudStreamPrimaryColor
import com.lagradost.cloudstream4.theme.modeToTheme
import com.lagradost.cloudstream4.theme.perfToColor
import com.lagradost.cloudstream4.theme.perfToMode
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.mutate
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentMap
object SettingsUIScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_ui)
fun SearchQuality.toStringRes() = when (this) {
SearchQuality.BlueRay -> R.string.quality_blueray
SearchQuality.Cam -> R.string.quality_cam
SearchQuality.CamRip -> R.string.quality_cam_rip
SearchQuality.DVD -> R.string.quality_dvd
SearchQuality.HD -> R.string.quality_hd
SearchQuality.HQ -> R.string.quality_hq
SearchQuality.HdCam -> R.string.quality_cam_hd
SearchQuality.Telecine -> R.string.quality_tc
SearchQuality.Telesync -> R.string.quality_ts
SearchQuality.WorkPrint -> R.string.quality_workprint
SearchQuality.SD -> R.string.quality_sd
SearchQuality.FourK -> R.string.quality_4k
SearchQuality.UHD -> R.string.quality_uhd
SearchQuality.SDR -> R.string.quality_sdr
SearchQuality.HDR -> R.string.quality_hdr
SearchQuality.WebRip -> R.string.quality_webrip
}
@Composable
fun RoundColor(color: Color) {
Box(
modifier = Modifier
.padding(start = 15.dp)
.size(20.dp)
.border(width = 1.5.dp, shape = CircleShape, color = MaterialTheme.colorScheme.onBackground)
.background(color, CircleShape)
)
}
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
return persistentListOf(
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_looks),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = settings.ui.primaryColor,
icon = painterResource(R.drawable.colors_24px),
title = stringResource(R.string.primary_color_settings),
entries = stringArrayResource(R.array.themes_overlay_names_values).zip(
stringArrayResource(R.array.themes_overlay_names)
).toMap().toPersistentMap().mutate { map ->
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { // remove monet on android 11 and less
map.remove("Monet")
map.remove("Monet2")
}
},
iconProvider = { k, _ ->
val color = perfToColor(k)
RoundColor(color.color)
},
onValueChanged = { newValue ->
settings.ui.primaryColor.set(newValue) // We need to set before we recreate
safe {
activity?.recreate()
}
return@ListPreference false
}),
Preference.PreferenceItem.ListPreference(
preference = settings.ui.theme,
icon = painterResource(R.drawable.palette_24px),
title = stringResource(R.string.app_theme_settings),
entries = stringArrayResource(R.array.themes_names_values).zip(
stringArrayResource(R.array.themes_names)
).toMap().toPersistentMap().mutate { map ->
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { // remove monet on android 11 and less
map.remove("Monet")
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { // Remove system on android 9 and less
map.remove("System")
}
},
iconProvider = { k, _ ->
val theme = modeToTheme(perfToMode(k), CloudStreamPrimaryColor.NORMAL)
RoundColor(theme.background)
},
onValueChanged = { newValue ->
settings.ui.theme.set(newValue) // We need to set before we recreate
safe {
activity?.recreate()
}
return@ListPreference false
}),
Preference.PreferenceItem.ListPreference(
preference = settings.ui.layout,
icon = painterResource(R.drawable.responsive_layout_24px),
title = stringResource(R.string.app_layout),
entries = integerArrayResource(R.array.app_layout_values).zip(
stringArrayResource(R.array.app_layout)
).toMap().toPersistentMap(),
onValueChanged = { newValue ->
settings.ui.layout.set(newValue) // We need to set before we recreate
safe {
activity?.updateTv()
activity?.recreate()
}
return@ListPreference false
}),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_ui_features),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SliderPreference(
preference = settings.ui.overscanDp,
title = stringResource(R.string.overscan_settings),
subtitle = stringResource(R.string.overscan_settings_des),
valueRange = 0..100,
icon = painterResource(R.drawable.arrows_input_24px),
enabled = isLayout(TV),
onValueChanged = { newValue ->
settings.ui.overscanDp.set(newValue)
val padding = newValue.toPx
(activity as? MainActivity)?.binding?.homeRoot?.setPadding(
padding, padding, padding, padding
)
return@SliderPreference false
}),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.advancedSearch,
title = stringResource(R.string.advanced_search),
subtitle = stringResource(R.string.advanced_search_des),
icon = painterResource(R.drawable.search_icon)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.searchSuggestions,
title = stringResource(R.string.search_suggestions),
subtitle = stringResource(R.string.search_suggestions_des),
icon = painterResource(R.drawable.tooltip_24px)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.trailersEnabled,
title = stringResource(R.string.show_trailers_settings),
icon = painterResource(R.drawable.baseline_theaters_24)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.kitsuPostersEnabled,
title = stringResource(R.string.kitsu_settings),
icon = painterResource(R.drawable.kitsu_icon)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.castEnabled,
title = stringResource(R.string.show_cast_in_details),
icon = painterResource(R.drawable.face_24px)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.fillersEnabled,
title = stringResource(R.string.show_fillers_settings),
icon = painterResource(R.drawable.skip_next_24px)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.showMetadataOverlay,
title = stringResource(R.string.show_player_metadata_overlay),
icon = painterResource(R.drawable.metadata_overlay_icon)
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.showClock,
title = stringResource(R.string.tv_layout_clock_settings),
subtitle = stringResource(R.string.tv_layout_clock_settings_des),
icon = painterResource(R.drawable.ic_baseline_clock_24),
enabled = isLayout(TV),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.randomButtonEnabled,
title = stringResource(R.string.random_button_settings),
subtitle = stringResource(R.string.random_button_settings_desc),
icon = painterResource(R.drawable.shuffle_24px)
),
Preference.PreferenceItem.ListPreference(
preference = settings.ui.confirmExit,
title = stringResource(R.string.confirm_before_exiting_title),
subtitle = stringResource(R.string.confirm_before_exiting_desc),
icon = painterResource(R.drawable.ic_baseline_exit_24),
entries = integerArrayResource(R.array.confirm_exit_values).zip(
stringArrayResource(R.array.confirm_exit)
).toMap()
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.search_poster_img_des),
preferenceItems = persistentListOf(
Preference.PreferenceItem.MultiSelectListPreference(
preference = settings.ui.filterQuality,
title = stringResource(R.string.pref_filter_search_quality),
icon = painterResource(R.drawable.filter_alt_24px),
entries = SearchQuality.entries.associateWith { stringResource(it.toStringRes()) }),
Preference.PreferenceItem.MultiSelectListPreference(
title = stringResource(R.string.display_subbed_dubbed_settings),
icon = painterResource(R.drawable.audio_capture_24px),
preference = settings.provider.displayDubSub,
entries = mapOf(
DubStatus.None.name to stringResource(R.string.none),
DubStatus.Dubbed.name to stringResource(R.string.app_dubbed_text),
DubStatus.Subbed.name to stringResource(R.string.app_subbed_text),
)),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.bottomTitle,
title = stringResource(R.string.bottom_title_settings),
subtitle = stringResource(R.string.bottom_title_settings_des),
icon = painterResource(R.drawable.title_24px)
),
Preference.PreferenceItem.SliderPreference(
preference = settings.ui.posterSize,
title = stringResource(R.string.poster_size_settings),
subtitle = stringResource(R.string.poster_size_settings_des),
valueRange = 0..15,
icon = painterResource(R.drawable.baseline_grid_view_24),
onValueChanged = { newValue ->
HomeChildItemAdapter.sharedPool.clear()
ParentItemAdapter.sharedPool.clear()
SearchAdapter.sharedPool.clear()
activity?.let { HomeChildItemAdapter.updatePosterSize(it, newValue) }
settings.ui.posterSize.set(newValue)
return@SliderPreference false
}),
),
),
Preference.PreferenceGroup(
title = stringResource(R.string.poster_ui_settings),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowRating,
title = stringResource(R.string.show_rating),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowEpisode,
title = stringResource(R.string.show_episode_text),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowTitle,
title = stringResource(R.string.show_title),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowHd,
title = stringResource(R.string.show_hd),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowDub,
title = stringResource(R.string.show_dub),
),
Preference.PreferenceItem.SwitchPreference(
preference = settings.ui.posterShowSub,
title = stringResource(R.string.show_sub),
),
)
)
)
}
}

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.mihon.presentation.settings.SearchableSettings
/** Empty glue code to connect the old navigation graph to Compose */
class SettingsUpdates2 : BaseComposeFragment(), SearchableSettings by SettingsUpdatesScreen

View file

@ -1,236 +0,0 @@
package com.lagradost.cloudstream3.ui.settings
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.integerArrayResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import com.lagradost.cloudstream3.BuildConfig
import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.CommonActivity.activity
import com.lagradost.cloudstream3.MainActivityScreen
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.services.BackupWorkManager
import com.lagradost.cloudstream3.utils.BackupUtils
import com.lagradost.cloudstream3.utils.BackupUtils.restorePrompt
import com.lagradost.cloudstream3.utils.InAppUpdater.installPreReleaseIfNeeded
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream4.AppSettings
import com.lagradost.cloudstream4.rememberAppSettings
import com.lagradost.cloudstream4.viewmodels.GithubAction
import com.lagradost.safefile.SafeFile
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import com.mihon.presentation.settings.collectAsState
import kotlinx.collections.immutable.persistentListOf
object SettingsUpdatesScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.category_updates)
@Composable
override fun getPreferences(): List<Preference> {
val settings = rememberAppSettings()
// TODO Refactor entirely to use a different file path selector ect like QuickNovel
val selectFileSelector =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
// It lies, it can be null if file manager quits.
if (uri == null) return@rememberLauncherForActivityResult
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
try {
val settings = AppSettings(context)
// RW perms for the path
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(uri, flags)
val filePath = SafeFile.fromUri(context, uri)?.filePath()
println("Selected URI path: $uri - Full path: $filePath")
// store the actual URI instead of the path due to permissions.
// filePath should only be used for cosmetic purposes.
val visual = filePath ?: uri.toString()
settings.backup.path.set(uri.toString())
settings.backup.visualPath.set(visual)
} catch (t: Throwable) {
logError(t)
}
}
val visualBackupPath by settings.backup.visualPath.collectAsState()
var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
com.lagradost.cloudstream3.ui.settings.logcat.LogcatDialog {
showDialog = false
}
}
val githubViewModel = MainActivityScreen.githubViewModel()
return persistentListOf(
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_app_updates),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.check_for_update),
subtitle = BuildConfig.VERSION_NAME,
icon = painterResource(R.drawable.mobile_arrow_down_24px),
onClick = {
githubViewModel?.onAction(GithubAction.SearchForUpdate)
/*ioSafe {
if (activity?.runAutoUpdate(false) == false) {
activity?.runOnUiThread {
showToast(
R.string.no_update_found,
Toast.LENGTH_SHORT
)
}
}
}*/
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.install_prerelease),
icon = painterResource(R.drawable.mobile_code_24px),
enabled = BuildConfig.FLAVOR == "stable",
onClick = {
activity?.installPreReleaseIfNeeded()
}
),
Preference.PreferenceItem.ListPreference(
title = stringResource(R.string.apk_installer_settings),
subtitle = stringResource(R.string.apk_installer_settings_des),
icon = painterResource(R.drawable.mobile_wrench_24px),
entries = integerArrayResource(R.array.apk_installer_values).zip(
stringArrayResource(R.array.apk_installer_pref)
).toMap(),
preference = settings.updates.apkInstaller
),
Preference.PreferenceItem.SwitchPreference(
title = stringResource(R.string.updates_settings),
subtitle = stringResource(R.string.updates_settings_des),
icon = painterResource(R.drawable.notifications_active_24px),
preference = settings.updates.showAppUpdates
)
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_backup),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.backup_settings),
icon = painterResource(R.drawable.save_as_24px),
onClick = {
BackupUtils.backup(activity)
}
),
Preference.PreferenceItem.ListPreference(
title = stringResource(R.string.backup_frequency),
icon = painterResource(R.drawable.save_clock_24px),
entries = integerArrayResource(R.array.periodic_work_values).zip(
stringArrayResource(R.array.periodic_work_names)
).toMap(),
preference = settings.backup.frequency,
onValueChanged = { value ->
BackupWorkManager.enqueuePeriodicWork(
CloudStreamApp.context,
value.toLong()
)
return@ListPreference true
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.backup_path_title),
icon = painterResource(R.drawable.folder_24px),
subtitle = visualBackupPath,
onClick = {
// This is not a ListPreference because the old selection system is
// broken af. This needs to be refactored to QuickNovels download path
// system.
selectFileSelector.launch(Uri.EMPTY)
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.restore_settings),
icon = painterResource(R.drawable.restore_page_24px),
onClick = {
activity?.restorePrompt()
}
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_extensions),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
title = stringResource(R.string.automatic_plugin_updates),
icon = painterResource(R.drawable.extension_24px),
preference = settings.plugins.autoUpdate,
),
/*Preference.PreferenceItem.ListPreference(
title = stringResource(R.string.automatic_plugin_download),
subtitle = "%s\n" + stringResource(R.string.automatic_plugin_download_summary),
icon = painterResource(R.drawable.extention_renew2),
entries = AutoDownloadMode.entries.map { it.value }.sorted()
.zip(stringArrayResource((R.array.auto_download_plugin))).toMap(),
preference = settings.plugins.autoDownload
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.update_plugins),
subtitle = stringResource(R.string.update_plugins_manually),
icon = painterResource(R.drawable.extention_download),
onClick = {
ioSafe {
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_manuallyReloadAndUpdatePlugins(
activity ?: return@ioSafe
)
}
}
),*/
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.test_extensions),
subtitle = stringResource(R.string.test_extensions_summary),
icon = painterResource(R.drawable.baseline_network_ping_24),
onClick = {
activity?.navigate(R.id.navigation_test_providers)
})
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_actions),
preferenceItems = persistentListOf(
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.show_log_cat),
icon = painterResource(R.drawable.article_24px),
onClick = {
showDialog = true
}
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.redo_setup_process),
icon = painterResource(R.drawable.construction_24px),
onClick = {
activity?.navigate(R.id.navigation_setup_language)
}
),
)
)
)
}
}

View file

@ -1,282 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.extensions
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.InternalAPI
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.cmap
import com.lagradost.cloudstream3.plugins.PLUGIN_VERSION_NOT_SET
import com.lagradost.cloudstream3.plugins.PluginData
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.plugins.PluginManager.deletePlugin
import com.lagradost.cloudstream3.plugins.PluginManager.getPluginPath
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
import com.lagradost.cloudstream3.plugins.RepositoryManager.PREBUILT_REPOSITORIES
import com.lagradost.cloudstream3.plugins.RepositoryManager.addRepository
import com.lagradost.cloudstream3.plugins.RepositoryManager.convertRawGitUrl
import com.lagradost.cloudstream3.plugins.RepositoryManager.parseRepoUrl
import com.lagradost.cloudstream3.plugins.RepositoryManager.removeRepository
import com.lagradost.cloudstream3.plugins.SitePlugin
import com.lagradost.cloudstream3.ui.settings.ApkUpdater
import com.lagradost.cloudstream3.ui.settings.ApkUpdater.isFileDigest
import com.lagradost.cloudstream4.viewmodels.DigestPair
import com.lagradost.cloudstream4.viewmodels.Plugin
import com.lagradost.cloudstream4.viewmodels.PluginDownloadSource
import com.lagradost.cloudstream4.viewmodels.PluginInfo
import com.lagradost.cloudstream4.viewmodels.PluginStatus
import com.lagradost.cloudstream4.viewmodels.RepositoryInfo
import com.lagradost.cloudstream4.viewmodels.RepositoryManager
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.TimeUnit
import kotlin.uuid.Uuid
@InternalAPI
object AndroidRepositoryManager : RepositoryManager {
fun RepositoryInfo.toData() =
RepositoryData(
name = name,
url = url,
iconUrl = iconUrl,
description = description
)
fun RepositoryData.toInfo() =
RepositoryInfo(
name = name,
url = url,
iconUrl = iconUrl,
description = description
)
override fun getRepositories(): List<RepositoryInfo> {
return ((getKey<Array<RepositoryData>>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES).map { info ->
info.toInfo()
}
}
override suspend fun getPlugins(
repository: RepositoryInfo,
repositoryUuid: Uuid
): Pair<RepositoryInfo, List<Plugin>> =
withContext(Dispatchers.IO) {
val activity =
CommonActivity.activity ?: throw ErrorLoadingException("No activity found")
val url = parseRepoUrl(repository.url)
if (url.isNullOrBlank()) {
throw ErrorLoadingException(activity.getString(R.string.error_invalid_url))
}
val parsedRepository = app.get(
url = convertRawGitUrl(url),
cacheTime = 15,
cacheUnit = TimeUnit.MINUTES
).parsed<com.lagradost.cloudstream3.plugins.Repository>()
/**
* No sane repository should be able to DDoS the app when navigating to settings, so
* we limit this to a maximum of 10
*
* Note that this list is on all verified repos = 1, as pluginLists is a list of lists
* */
require(parsedRepository.pluginLists.size <= 10)
/** Add this as a new repository -> replaces the old data with new icon,name and description */
addRepository(
RepositoryData(
iconUrl = parsedRepository.iconUrl,
url = url,
name = parsedRepository.name,
description = parsedRepository.description
)
)
val plugins = parsedRepository.pluginLists.cmap { url ->
/** This should really be a list of size ~ 1 */
app.get(
url = convertRawGitUrl(url),
cacheTime = 15,
cacheUnit = TimeUnit.MINUTES
).parsed<Array<SitePlugin>>()
}.flatMap { plugins ->
plugins.map { plugin ->
val file = getPluginPath(
context = activity,
internalName = plugin.internalName,
repositoryUrl = url
)
val language = plugin.language?.trim()
Plugin(
info = PluginInfo(
name = plugin.name,
status = plugin.status,
internalName = plugin.internalName,
version = plugin.version,
tvTypes = plugin.tvTypes?.mapNotNull { runCatching { TvType.valueOf(it) }.getOrNull() }
?.toPersistentList()
?: persistentListOf(),
authors = plugin.authors.toPersistentList(),
iconUrl = plugin.iconUrl,
language = if (language.isNullOrBlank()) {
null
} else {
language
},
description = plugin.description,
repositoryUrl = plugin.repositoryUrl
),
source = PluginDownloadSource(
size = plugin.fileSize,
repositoryUrl = url,
pluginUrl = plugin.url,
internalName = plugin.internalName,
digest = DigestPair.parse(plugin.fileHash)
),
status = PluginStatus.Idle,
downloadLocation = if (file.exists()) {
file.absolutePath
} else {
null
},
repository = repositoryUuid,
)
}
}
val info = RepositoryInfo(
iconUrl = parsedRepository.iconUrl,
url = url,
name = parsedRepository.name,
description = parsedRepository.description,
)
info to plugins
}
override suspend fun downloadPlugin(
source: PluginDownloadSource,
downloadProgress: (Long, Long?) -> Unit
): String = withContext(Dispatchers.IO) {
val context = CommonActivity.activity ?: throw ErrorLoadingException("No activity found")
val file = getPluginPath(
context = context,
internalName = source.internalName,
repositoryUrl = source.repositoryUrl
)
/**
* Before we do anything that needs a network connection,
* we actually check if we need to update it
*
* Because if the file digest is correct, then why do we need to do a network connection?
* */
if (isFileDigest(file, source.digest)) {
return@withContext file.absolutePath
}
val tempFile = File.createTempFile(file.name, ".tmp", context.cacheDir)
tempFile.outputStream().use { writeStream ->
app.get(convertRawGitUrl(source.pluginUrl)).body.use { body ->
val readStream = body.byteStream()
ApkUpdater.transfer(
writeStream = writeStream,
readStream = readStream,
length = source.size,
downloadProgress = downloadProgress,
digest = source.digest
)
}
}
// Always load the plugin
unloadPlugin(file.absolutePath)
file.delete() // delete if we somehow already have this downloaded?
file.parentFile?.mkdirs() // make the directories as Files.move needs this to work
try {
Files.move(
tempFile.toPath(),
file.toPath(),
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE
)
} catch (_: AtomicMoveNotSupportedException) {
Files.move(
tempFile.toPath(),
file.toPath(),
StandardCopyOption.REPLACE_EXISTING
)
}
val result = PluginManager.loadPlugin(
context = context,
file = file,
data = PluginData(
internalName = source.internalName,
url = source.pluginUrl,
isOnline = true,
filePath = file.absolutePath,
version = PLUGIN_VERSION_NOT_SET
)
)
if (!result) {
throw ErrorLoadingException("Unable to load plugin ${source.internalName}")
}
return@withContext file.absolutePath
}
override fun getLocalPlugins(localUuid: Uuid): List<Plugin> {
val plugins = PluginManager.getPluginsLocal()
return plugins.map { plugin ->
Plugin(
info = PluginInfo(
name = plugin.internalName,
internalName = plugin.internalName,
version = plugin.version,
tvTypes = persistentListOf(),
authors = persistentListOf(),
status = 1,
iconUrl = null,
language = null,
description = null,
repositoryUrl = null
),
source = null,
status = PluginStatus.Idle,
downloadLocation = plugin.filePath,
repository = localUuid,
)
}
}
override suspend fun deletePlugin(location: String) {
deletePlugin(File(location))
}
override suspend fun deleteRepository(repository: RepositoryInfo) {
val context = CommonActivity.activity ?: throw ErrorLoadingException("No activity found")
removeRepository(
context,
repository.toData()
)
}
override suspend fun updateRepositoryInfo(repository: RepositoryInfo) {
addRepository(
repository.toData()
)
}
}

View file

@ -302,7 +302,7 @@ class ExtensionsFragment : BaseFragment<FragmentExtensionsBinding>(
val fixedName = if (!name.isNullOrBlank()) name
else repository.name
val newRepo = RepositoryData(repository.iconUrl, fixedName, url, repository.description)
val newRepo = RepositoryData(repository.iconUrl, fixedName, url)
RepositoryManager.addRepository(newRepo)
extensionViewModel.loadStats()
extensionViewModel.loadRepositories()

View file

@ -1,6 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.extensions
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.lagradost.cloudstream4.compose.Screen
class ExtensionsFragment2 : BaseComposeFragment(), Screen by ExtensionsScreen

View file

@ -23,21 +23,8 @@ data class RepositoryData(
@JsonProperty("iconUrl") @SerialName("iconUrl") val iconUrl: String?,
@JsonProperty("name") @SerialName("name") val name: String,
@JsonProperty("url") @SerialName("url") val url: String,
@JsonProperty("description") @SerialName("description") val description: String? = null,
) {
constructor(name: String, url: String) : this(
iconUrl = null,
name = name,
url = url,
description = null
)
constructor(iconUrl: String?, name: String, url: String) : this(
iconUrl = iconUrl,
name = name,
url = url,
description = null
)
constructor(name: String, url: String): this(null, name, url)
}
const val REPOSITORIES_KEY = "REPOSITORIES_KEY"

View file

@ -1,181 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.logcat
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component1
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component2
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.window.DialogProperties
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream4.compose.BlackButton
import com.lagradost.cloudstream4.compose.LogBoxBlack
import com.lagradost.cloudstream4.compose.LogBoxWhite
import com.lagradost.cloudstream4.compose.LogText
import com.lagradost.cloudstream4.compose.WhiteButton
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.OutputStream
import java.lang.System.currentTimeMillis
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
fun LogcatDialog(dismiss: () -> Unit) {
val list = remember { mutableStateOf(persistentListOf<LogcatItem>()) }
var isLoading by remember { mutableStateOf(true) }
LaunchedEffect(dismiss) {
try {
isLoading = true
// https://developer.android.com/studio/command-line/logcat
val process = Runtime.getRuntime().exec("logcat --binary -d")
val items = arrayListOf<LogcatItem>()
LogcatBinaryParser(process.inputStream).use { parser ->
while (true) {
val item = parser.parseItem() ?: break
items.add(item)
}
}
list.value = items.toPersistentList()
} catch (e: Exception) {
logError(e) // kinda ironic
} finally {
isLoading = false
}
}
val (dismissFocus, confirmFocus) = remember { FocusRequester.createRefs() }
val context = LocalContext.current
val scope = rememberCoroutineScope()
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = dismiss,
title = {
Text(text = stringResource(R.string.log_cat))
},
text = {
if (isLoading) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.onBackground,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
LazyColumn(
modifier = Modifier.focusProperties {
start = dismissFocus
end = confirmFocus
}
) {
items(items = list.value, key = { item -> item.uuid }) { item ->
LogcatItem(item, modifier = Modifier.focusProperties {
start = dismissFocus
end = confirmFocus
})
}
}
},
confirmButton = {
WhiteButton(
text = stringResource(R.string.sort_save),
modifier = Modifier.focusRequester(confirmFocus)
) {
scope.launch {
withContext(Dispatchers.IO) {
val date = SimpleDateFormat("yyyy_MM_dd_HH_mm", Locale.getDefault()).format(
Date(currentTimeMillis())
)
var fileStream: OutputStream?
try {
fileStream = VideoDownloadManager.setupStream(
context,
"logcat_${date}",
null,
"txt",
false
).openNew()
fileStream.bufferedWriter()
.use { writer ->
list.value.forEach {
writer.write(it.toString())
writer.write("\n\n")
}
}
dismiss()
} catch (t: Throwable) {
logError(t)
showToast(t.message)
}
}
}
}
WhiteButton(text = stringResource(R.string.sort_copy)) {
clipboardHelper(
txt("Logcat"),
list.value.joinToString(separator = "\n\n") { it.toString() }
)
}
WhiteButton(text = stringResource(R.string.sort_clear)) {
try {
Runtime.getRuntime().exec("logcat -c")
} catch (t: Throwable) {
logError(t)
}
dismiss()
}
},
dismissButton = {
BlackButton(
text = stringResource(R.string.sort_close),
onClick = dismiss,
modifier = Modifier.focusRequester(dismissFocus)
)
},
properties = DialogProperties(usePlatformDefaultWidth = false)
)
}
@Composable
fun LogcatItem(item: LogcatItem, modifier: Modifier = Modifier) {
Row(modifier = Modifier.fillMaxWidth()) {
item.level?.identifier?.let { value ->
LogBoxWhite(value)
}
LogBoxBlack(item.date.toHumanReadable())
LogBoxBlack(item.tag)
}
LogText(level = item.level, message = item.message, modifier = modifier, onClick = {
clipboardHelper(txt("Logcat"), item.toString())
})
}

View file

@ -1,136 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.logcat
import androidx.compose.runtime.Immutable
import com.lagradost.cloudstream4.state.LogLevel
import com.lagradost.cloudstream4.state.UniqueItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.io.Buffer
import kotlinx.io.asSource
import kotlinx.io.readByteArray
import kotlinx.io.readIntLe
import kotlinx.io.readString
import kotlinx.io.readUShortLe
import java.io.Closeable
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlin.time.Instant
import kotlin.uuid.Uuid
fun Instant.toHumanReadable(): String {
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).apply {
timeZone = TimeZone.getDefault()
}
return formatter.format(Date(this.toEpochMilliseconds()))
}
@Immutable
data class LogcatItem(
val date: Instant,
val pid: Int,
val tid: Int,
val level: LogLevel?,
val tag: String,
val message: String,
override val uuid : Uuid = Uuid.random(),
) : UniqueItem {
override fun toString(): String {
return "${date.toHumanReadable()} $pid-$tid $tag ${level?.identifier ?: "?"} $message"
}
}
/**https://github.com/brudaswen/android-logcat/blob/main/library/logcat-core/src/main/kotlin/de/brudaswen/android/logcat/core/parser/LogcatBinaryParser.kt */
class LogcatBinaryParser(
private val input: InputStream,
) : Closeable by input {
val source = input.asSource()
private val buffer = Buffer()
/**
* Parse one [LogcatItem] from the current [input] stream.
*
* @return The parsed [LogcatItem] or `null` if stream reached EOF.
*/
suspend fun parseItem(): LogcatItem? = withContext(Dispatchers.IO) {
val firstByte = input.read()
if (firstByte == -1) return@withContext null
// Read v1 header
buffer.writeByte(firstByte.toByte())
buffer.write(source = source, byteCount = 19)
val len = buffer.readUShortLe().toInt()
val headerSize = buffer.readUShortLe().toInt()
val pid = buffer.readIntLe()
val tid = buffer.readIntLe()
val sec = buffer.readIntLe()
val nsec = buffer.readIntLe()
// Read additional header fields
buffer.write(source = source, byteCount = headerSize - 20L)
val additionalHeaderBytes = (headerSize - 20).coerceAtLeast(0)
buffer.readByteArray(byteCount = additionalHeaderBytes)
// Read payload
buffer.write(source = source, byteCount = len.toLong())
val priority = buffer.readByte()
val payload = buffer.readString()
val texts = payload.split('\u0000', limit = 2)
val tag = texts.getOrNull(0).orEmpty()
val message = texts.getOrNull(1).orEmpty().removeSuffix("\u0000").trim()
// Clear buffer
buffer.clear()
// Convert raw values to item
LogcatItem(
sec = sec,
nsec = nsec,
priority = priority,
pid = pid,
tid = tid,
tag = tag,
message = message,
)
}
private fun LogcatItem(
sec: Int,
nsec: Int,
priority: Byte,
pid: Int,
tid: Int,
tag: String,
message: String,
): LogcatItem {
val date = Instant.fromEpochSeconds(
epochSeconds = sec.toLong(),
nanosecondAdjustment = nsec,
)
val level = when (priority) {
2.toByte() -> LogLevel.Verbose
3.toByte() -> LogLevel.Debug
4.toByte() -> LogLevel.Info
5.toByte() -> LogLevel.Warning
6.toByte() -> LogLevel.Error
7.toByte() -> LogLevel.Fatal
else -> null
}
return LogcatItem(
date = date,
pid = pid,
tid = tid,
level = level,
tag = tag,
message = message,
)
}
}

View file

@ -1,7 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.testing
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.lagradost.cloudstream4.compose.Screen
/** Empty glue code to connect the old navigation graph to Compose */
class TestFragment2 : BaseComposeFragment(), Screen by TestScreen

View file

@ -21,12 +21,10 @@ import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
import com.lagradost.cloudstream3.utils.SubtitleHelper.getFlagFromIso
import com.lagradost.cloudstream3.utils.TestingUtils
import com.lagradost.cloudstream3.utils.TestingUtils.Logger
import com.lagradost.cloudstream4.state.LogLevel
import java.io.File
class TestResultAdapter() :
NoStateAdapter<Triple<MainAPI, TestingUtils.TestResultProvider, Logger>>(
NoStateAdapter<Pair<MainAPI, TestingUtils.TestResultProvider>>(
diffCallback = BaseDiffCallback(
itemSame = { a, b ->
a.first.name == b.first.name && a.first.mainUrl == b.first.mainUrl
@ -58,11 +56,11 @@ class TestResultAdapter() :
override fun onBindContent(
holder: ViewHolderState<Any>,
item: Triple<MainAPI, TestingUtils.TestResultProvider, Logger>,
item: Pair<MainAPI, TestingUtils.TestResultProvider>,
position: Int
) {
val binding = holder.view as? ProviderTestItemBinding ?: return
val (api, result, log) = item
val (api, result) = item
val itemView = holder.itemView
@ -76,7 +74,7 @@ class TestResultAdapter() :
providerTitle.text = api.name
val (resultText, resultColor) = if (result.success) {
if (log.messageLog.any { it.level == LogLevel.Warning }) {
if (result.log.any { it.level == TestingUtils.Logger.LogLevel.Warning }) {
R.string.test_warning to R.color.colorTestWarning
} else {
R.string.test_passed to R.color.colorTestPass
@ -90,7 +88,7 @@ class TestResultAdapter() :
val stackTrace = result.exception?.getStackTracePretty(false)?.ifBlank { null }
val messages = result.exception?.getAllMessages()?.ifBlank { null }
val resultLog = log.messageLog.joinToString("\n")
val resultLog = result.log.joinToString("\n")
val fullLog =
resultLog +
(messages?.let { "\n\nError: $it" } ?: "") +

View file

@ -1,470 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.testing
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component1
import androidx.compose.ui.focus.FocusRequester.Companion.FocusRequesterFactory.component2
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lagradost.cloudstream3.APIHolder.allProviders
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.ui.settings.SettingsFragmentScreen.SettingsSearch
import com.lagradost.cloudstream3.ui.settings.logcat.toHumanReadable
import com.lagradost.cloudstream3.utils.TestingUtils
import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream4.compose.BlackButton
import com.lagradost.cloudstream4.compose.LogBoxBlack
import com.lagradost.cloudstream4.compose.LogBoxWhite
import com.lagradost.cloudstream4.compose.LogText
import com.lagradost.cloudstream4.compose.PHONE
import com.lagradost.cloudstream4.compose.Screen
import com.lagradost.cloudstream4.compose.WhiteButton
import com.lagradost.cloudstream4.compose.WhiteFilterChip
import com.lagradost.cloudstream4.compose.isLayout
import com.lagradost.cloudstream4.state.LogItem
import com.lagradost.cloudstream4.state.LogLevel
import com.lagradost.cloudstream4.state.SearchableDataState
import com.lagradost.cloudstream4.state.SortByName
import com.lagradost.cloudstream4.theme.CloudStreamPreviewTheme
import com.mihon.material.AppBar
import com.mihon.material.Scaffold
import com.mihon.material.padding
import com.mihon.presentation.LocalBackPress
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toPersistentList
import kotlin.uuid.Uuid
@PreviewLightDark
@Composable
fun Preview() {
val uuid1 = Uuid.random()
val uuid2 = Uuid.random()
CloudStreamPreviewTheme {
TestScreen.Content(
state = TestState(
items = SearchableDataState.from(
state = DerivedTestState(),
data = persistentMapOf(
uuid1 to ImmutableTestResult(
name = "test",
language = "en",
uuid = uuid1,
plugin = "test plugin"
),
uuid2 to ImmutableTestResult(
name = "aaa",
language = "se",
uuid = uuid2,
plugin = "test plugin",
highestLogLevel = LogLevel.Error,
result = TestingUtils.TestResultProvider(false, Throwable())
)
),
sortedBy = SortByName { it.name },
filteredBy = null,
)
), onAction = {})
}
}
object TestScreen : Screen {
@Composable
override fun Content() {
val viewModel = viewModel { TestViewModel2() }
LaunchedEffect(Unit) {
viewModel.onAction(TestAction.Init(allProviders.withLock { allProviders.toPersistentList() }))
}
val state by viewModel.state.collectAsState()
Content(state, viewModel::onAction)
}
@Composable
fun Content(
state: TestState,
onAction: (TestAction) -> Unit,
) {
val (top, bottom) = remember { FocusRequester.createRefs() }
val handleBack = LocalBackPress.current
Scaffold(
// TODO @WindowInsets remove this when we have converted everything to compose
contentWindowInsets = WindowInsets(0, 0, 0, 0),
topBar = {
AppBar(
modifier = Modifier
.focusRequester(top)
.focusProperties {
down = bottom
},
title = stringResource(R.string.category_provider_test),
navigateUp = handleBack,
actions = { },
scrollBehavior = it,
)
},
floatingActionButton = {
if (isLayout(PHONE)) {
val loading = state.activeQueries > 0
FloatingActionButton(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onBackground,
onClick = {
if (loading) {
onAction(TestAction.Cancel)
} else {
onAction(TestAction.Start)
}
}) {
if (loading) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
color = MaterialTheme.colorScheme.onBackground,
)
} else {
Icon(
painter = painterResource(R.drawable.play_arrow_24px),
contentDescription = stringResource(R.string.test_extensions)
)
}
}
}
},
content = { contentPadding ->
TestContent(
state = state,
onAction = onAction,
contentPadding = contentPadding,
modifier = Modifier
.focusRequester(bottom)
.focusProperties {
up = top
})
},
)
}
@Composable
fun SelectSingleButton(
name: Int,
filtering: PersistentSet<LogLevel>,
level: LogLevel,
highestLogLevelCount: PersistentMap<LogLevel, Int>,
onAction: (TestAction) -> Unit,
) {
val selected = filtering.contains(level)
WhiteFilterChip(
selected = selected,
label = "${stringResource(name)} ${highestLogLevelCount[level] ?: 0}"
) {
if (selected) {
onAction(TestAction.SetLevel(filtering.removing(level)))
} else {
onAction(TestAction.SetLevel(filtering.adding(level)))
}
}
}
@Composable
fun TestContent(
state: TestState,
onAction: (TestAction) -> Unit,
contentPadding: PaddingValues,
modifier: Modifier = Modifier,
) {
LazyColumn(
modifier = modifier,
contentPadding = contentPadding,
) {
item(key = "header") {
ProviderHeader(onAction = onAction)
}
item(key = "filter") {
FilterRow(state = state, onAction = onAction)
}
items(
items = state.items.sorted,
key = { api -> api }
) { uuid ->
val result = state.items.data[uuid]!!
TestResult(
result = result,
onAction = onAction,
modifier = Modifier.animateItem(),
)
}
}
}
/** This is not a .toString() because toHumanReadable is jvm */
fun LogItem.format() = "${date.toHumanReadable()} $tag ${level.identifier} $message"
@Composable
fun LogItem(item: LogItem, modifier: Modifier = Modifier) {
Row(modifier = Modifier.fillMaxWidth()) {
LogBoxWhite(item.level.identifier)
LogBoxBlack(item.date.toHumanReadable())
LogBoxBlack(item.tag)
}
LogText(level = item.level, message = item.message, modifier = modifier, onClick = {
clipboardHelper(txt("Log"), item.format())
})
}
@Composable
fun FilterRow(state: TestState, onAction: (TestAction) -> Unit) {
Row(
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.padding.small),
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(state = rememberScrollState())
) {
Spacer(modifier = Modifier.width(MaterialTheme.padding.small))
val highestLogLevelCount = state.items.state.highestLogLevelCount
SelectSingleButton(
name = R.string.no_data,
filtering = state.filtering.levelFilter,
level = LogLevel.Verbose,
highestLogLevelCount = highestLogLevelCount,
onAction = onAction,
)
SelectSingleButton(
name = R.string.test_passed,
filtering = state.filtering.levelFilter,
level = LogLevel.Info,
highestLogLevelCount = highestLogLevelCount,
onAction = onAction,
)
SelectSingleButton(
name = R.string.test_warning,
filtering = state.filtering.levelFilter,
level = LogLevel.Warning,
highestLogLevelCount = highestLogLevelCount,
onAction = onAction,
)
SelectSingleButton(
name = R.string.test_failed,
filtering = state.filtering.levelFilter,
level = LogLevel.Error,
highestLogLevelCount = highestLogLevelCount,
onAction = onAction,
)
Spacer(modifier = Modifier.width(MaterialTheme.padding.small))
}
}
@Composable
fun TestResultDialog(
result: ImmutableTestResult,
onAction: (TestAction) -> Unit,
dismiss: () -> Unit,
) {
val (dismissFocus, confirmFocus) = remember { FocusRequester.createRefs() }
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = dismiss,
title = {
Text(text = result.name)
},
text = {
LazyColumn(
modifier = Modifier.focusProperties {
start = dismissFocus
end = confirmFocus
}
) {
item(key = "loading header") {
if (result.isLoading) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.onBackground,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
Spacer(Modifier.height(height = MaterialTheme.padding.small))
} else if (result.log.isEmpty()) {
Text(
text = stringResource(R.string.no_data),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
}
}
items(items = result.log, key = { item -> item.uuid }) { item ->
LogItem(item, modifier = Modifier.focusProperties {
start = dismissFocus
end = confirmFocus
})
}
}
},
confirmButton = {
WhiteButton(
text = if (result.isLoading) stringResource(R.string.stop) else stringResource(R.string.start),
modifier = Modifier.focusRequester(confirmFocus)
) {
if (result.isLoading) {
onAction(TestAction.CancelSingle(result.uuid))
} else {
onAction(TestAction.StartSingle(result.uuid))
}
}
WhiteButton(text = stringResource(R.string.sort_copy)) {
clipboardHelper(
txt("Log"),
result.log.joinToString(separator = "\n\n") { it.format() }
)
}
WhiteButton(text = stringResource(R.string.sort_clear)) {
onAction(TestAction.ClearSingle(result.uuid))
}
},
dismissButton = {
BlackButton(
text = stringResource(R.string.sort_close),
onClick = dismiss,
modifier = Modifier.focusRequester(dismissFocus)
)
},
properties = DialogProperties(usePlatformDefaultWidth = false)
)
}
@Composable
fun TestResult(
result: ImmutableTestResult,
onAction: (TestAction) -> Unit,
modifier: Modifier = Modifier,
) {
var dialogShown by remember { mutableStateOf(false) }
if (dialogShown) {
TestResultDialog(result = result, onAction = onAction, dismiss = {
dialogShown = false
})
}
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.clickable(onClick = {
dialogShown = !dialogShown
})
.padding(horizontal = MaterialTheme.padding.medium)
) {
Column(modifier = Modifier.weight(1.0f)) {
Text(text = result.name)
Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.padding.small)) {
if (result.result != null) {
val (text, color) = when (result.highestLogLevel) {
LogLevel.Fatal, LogLevel.Error -> R.string.test_failed to R.color.colorTestFail
LogLevel.Warning -> R.string.test_warning to R.color.colorTestWarning
LogLevel.Verbose, LogLevel.Debug, LogLevel.Info -> R.string.test_passed to R.color.colorTestPass
}
Text(text = stringResource(text), color = colorResource(color))
}
if (result.plugin != null) {
Text(
text = result.plugin,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
Spacer(modifier = Modifier.width(MaterialTheme.padding.small))
IconButton(
onClick = {
if (result.isLoading) {
onAction(TestAction.CancelSingle(result.uuid))
} else {
onAction(TestAction.StartSingle(result.uuid))
}
},
colors = IconButtonDefaults.iconButtonColors(contentColor = MaterialTheme.colorScheme.onBackground)
) {
if (result.isLoading) {
CircularProgressIndicator(
modifier = Modifier.padding(MaterialTheme.padding.small),
color = MaterialTheme.colorScheme.onBackground,
)
} else {
Icon(
painter = painterResource(R.drawable.play_arrow_24px),
contentDescription = null,
)
}
}
}
}
@Composable
fun ProviderHeader(
onAction: (TestAction) -> Unit,
) {
val textFieldState = rememberTextFieldState()
Box(modifier = Modifier.padding(vertical = MaterialTheme.padding.small)) {
SettingsSearch(textFieldState)
}
LaunchedEffect(textFieldState.text) {
onAction(TestAction.Search(textFieldState.text.toString()))
}
}
}

View file

@ -28,11 +28,11 @@ class TestViewModel : ViewModel() {
val providerProgress: LiveData<TestProgress> = _providerProgress
private val _providerResults =
MutableLiveData<List<Triple<MainAPI, TestingUtils.TestResultProvider, TestingUtils.Logger>>>(
MutableLiveData<List<Pair<MainAPI, TestingUtils.TestResultProvider>>>(
emptyList()
)
val providerResults: LiveData<List<Triple<MainAPI, TestingUtils.TestResultProvider, TestingUtils.Logger>>> =
val providerResults: LiveData<List<Pair<MainAPI, TestingUtils.TestResultProvider>>> =
_providerResults
private var scope: CoroutineScope? = null
@ -40,8 +40,7 @@ class TestViewModel : ViewModel() {
get() = scope != null
private var filter = ProviderFilter.All
private val providers =
atomicListOf<Triple<MainAPI, TestingUtils.TestResultProvider, TestingUtils.Logger>>()
private val providers = atomicListOf<Pair<MainAPI, TestingUtils.TestResultProvider>>()
private var passed = 0
private var failed = 0
private var total = 0
@ -68,19 +67,14 @@ class TestViewModel : ViewModel() {
postProviders()
}
private fun addProvider(
api: MainAPI,
results: TestingUtils.TestResultProvider,
logger: TestingUtils.Logger
) {
private fun addProvider(api: MainAPI, results: TestingUtils.TestResultProvider) {
providers.withLock {
val index = providers.indexOfFirst { it.first == api }
val triple = Triple(api, results, logger)
if (index == -1) {
providers.add(triple)
providers.add(api to results)
if (results.success) passed++ else failed++
} else {
providers[index] = triple
providers[index] = api to results
}
updateProgress()
}
@ -101,8 +95,8 @@ class TestViewModel : ViewModel() {
providers.clear()
updateProgress()
TestingUtils.getDeferredProviderTests(scope ?: return, apis) { api, result, log ->
addProvider(api, result, log)
TestingUtils.getDeferredProviderTests(scope ?: return, apis) { api, result ->
addProvider(api, result)
}
}

View file

@ -1,291 +0,0 @@
package com.lagradost.cloudstream3.ui.settings.testing
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lagradost.cloudstream3.MainAPI
import com.lagradost.cloudstream3.utils.TestingUtils.TestResultProvider
import com.lagradost.cloudstream3.utils.TestingUtils.runSingleProviderTest
import com.lagradost.cloudstream4.state.ActionHandler
import com.lagradost.cloudstream4.state.DefaultStateContainer
import com.lagradost.cloudstream4.state.DerivedState
import com.lagradost.cloudstream4.state.FilterByQuery
import com.lagradost.cloudstream4.state.Log
import com.lagradost.cloudstream4.state.LogItem
import com.lagradost.cloudstream4.state.LogLevel
import com.lagradost.cloudstream4.state.MultiActiveQuery
import com.lagradost.cloudstream4.state.SearchableDataState
import com.lagradost.cloudstream4.state.SortByName
import com.lagradost.cloudstream4.state.StateContainer
import com.lagradost.cloudstream4.state.UniqueItem
import com.lagradost.cloudstream4.state.edit
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toPersistentMap
import kotlinx.collections.immutable.toPersistentSet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.milliseconds
import kotlin.uuid.Uuid
@Immutable
data class ImmutableTestResult(
val name: String,
val language: String,
val plugin: String?,
override val uuid: Uuid,
val log: PersistentList<LogItem> = persistentListOf(),
val highestLogLevel: LogLevel = LogLevel.Verbose,
val isLoading: Boolean = false,
val result: TestResultProvider? = null,
) : UniqueItem {
fun addMessage(message: LogItem): ImmutableTestResult {
val lastMessage = log.lastOrNull()
/** If we have a very similar message at almost the same time,
* then append it instead of adding a new message*/
if (lastMessage != null
&& lastMessage.level == message.level
&& lastMessage.tag == message.tag
&& (message.date - lastMessage.date) < 100.milliseconds
) {
return copy(
log = log.replacingAt(log.lastIndex, lastMessage.copy(
message = lastMessage.message + "\n" + message.message,
date = message.date
))
)
}
return copy(log = log.adding(message))
}
}
@Immutable
data class FilterTestResults(
val searchFilter: FilterByQuery<ImmutableTestResult> = FilterByQuery(query = "") { it.name },
val levelFilter: PersistentSet<LogLevel> = LogLevel.entries.toPersistentSet(),
) : Function1<ImmutableTestResult, Boolean> {
override fun invoke(result: ImmutableTestResult): Boolean =
levelFilter.contains(result.highestLogLevel) && searchFilter(result)
fun setQuery(newQuery: String): FilterTestResults {
return copy(searchFilter = searchFilter.update(newQuery))
}
fun setLevel(newLevel: PersistentSet<LogLevel>): FilterTestResults {
return copy(levelFilter = newLevel)
}
}
@Immutable
data class DerivedTestState(
val highestLogLevelCount: PersistentMap<LogLevel, Int> = zero
) : DerivedState<DerivedTestState, ImmutableTestResult> {
companion object {
val zero = LogLevel.entries.associateWith { 0 }.toPersistentMap()
}
override fun clearing(): DerivedTestState = DerivedTestState()
override fun adding(value: ImmutableTestResult): DerivedTestState =
copy(highestLogLevelCount = highestLogLevelCount.edit(value.highestLogLevel) { plus(1) })
override fun removing(value: ImmutableTestResult): DerivedTestState =
copy(highestLogLevelCount = highestLogLevelCount.edit(value.highestLogLevel) { minus(1) })
}
/**
* To avoid issues with the uniqueness of a MainAPI, we use an Uuid to refer to each MainAPI
* */
@Immutable
data class TestState(
val sorting: SortByName<ImmutableTestResult> = SortByName { it.name },
val filtering: FilterTestResults = FilterTestResults(),
val items: SearchableDataState<Uuid, ImmutableTestResult, DerivedTestState> = SearchableDataState.from(
state = DerivedTestState(),
data = persistentMapOf(),
sortedBy = sorting,
filteredBy = filtering
),
val activeQueries: Int = 0,
val internalApis: PersistentMap<Uuid, MainAPI> = persistentMapOf(),
) {
val total: Int = internalApis.size
}
@Immutable
sealed class TestAction {
object Start : TestAction()
object Cancel : TestAction()
data class Init(val apis: List<MainAPI>) : TestAction()
data class StartSingle(val uuid: Uuid) : TestAction()
data class ClearSingle(val uuid: Uuid) : TestAction()
data class CancelSingle(val uuid: Uuid) : TestAction()
data class Search(val query: String) : TestAction()
data class SetLevel(val level: PersistentSet<LogLevel>) : TestAction()
}
class TestViewModel2 : ViewModel(), StateContainer<TestState> by DefaultStateContainer(TestState()),
ActionHandler<TestAction> {
private val dispatcher = MultiActiveQuery<Uuid>(Dispatchers.IO)
override fun onAction(action: TestAction) {
when (action) {
TestAction.Cancel -> {
viewModelScope.launch {
dispatcher.cancelAll()
}
}
TestAction.Start -> {
viewModelScope.launch {
runAll()
}
}
is TestAction.StartSingle -> {
viewModelScope.launch {
runSingleTest(action.uuid)
}
}
is TestAction.CancelSingle -> {
viewModelScope.launch {
dispatcher.cancelOne(action.uuid)
}
}
is TestAction.ClearSingle -> {
viewModelScope.launch {
/** Replace the existing work by cancelling and then clearing */
dispatcher.launch(action.uuid) {
updateState {
copy(items = items.updating(action.uuid) {
copy(
log = log.cleared(),
highestLogLevel = LogLevel.Verbose,
result = null
)
})
}
}
}
}
is TestAction.Init -> {
updateState {
/** We do a reverse map lookup here to keep the old data and insert new elements */
val inverseMap = internalApis.map { entry -> entry.value to entry.key }.toMap()
val newInternalApis =
/** Make sure it is distinct to avoid possible runtime crashes */
action.apis.distinct()
/** Keep the old uuid if it exists */
.associateBy { api -> inverseMap[api] ?: Uuid.random() }
.toPersistentMap()
/** By default, they are idle, but we also keep the old data */
val newData = (newInternalApis.mapValues { entry ->
// val pluginInstance = (entry.value.sourcePlugin?.let { PluginManager.plugins[it] } as? Plugin)?.filename
// There is no way to get the icon without a get request...
ImmutableTestResult(
language = entry.value.lang,
name = entry.value.name,
plugin = null, // The readable plugin name is wonky af to get
uuid = entry.key,
)
} + items.data).toPersistentMap()
val map = LogLevel.entries.associateWith { 0 }.toMutableMap()
for (entry in newData) {
map[entry.value.highestLogLevel] = map[entry.value.highestLogLevel]!! + 1
}
copy(
internalApis = newInternalApis,
items = items.setTo(newData),
)
}
}
is TestAction.Search -> {
updateState {
val newFiltering = filtering.setQuery(action.query)
copy(filtering = newFiltering, items = items.filteringBy(newFiltering))
}
}
is TestAction.SetLevel -> {
updateState {
val newFiltering = filtering.setLevel(action.level)
copy(filtering = newFiltering, items = items.filteringBy(newFiltering))
}
}
}
}
private suspend fun runAll() {
val apis = state.value.items.sorted
for (api in apis) {
runSingleTest(api)
}
}
private suspend fun runSingleTest(uuid: Uuid) {
val internalApi = state.value.internalApis[uuid] ?: return
dispatcher.launch(uuid) {
updateState {
val newItems = items.updating(uuid) {
copy(
isLoading = true,
log = persistentListOf(),
highestLogLevel = LogLevel.Verbose,
result = null,
)
}
copy(
/**
* We assume that runSingleProviderTest will not crash, so the final updateState
* will always be called and decrement this
* */
activeQueries = activeQueries + 1,
items = newItems
)
}
val logger = object : Log {
override fun log(item: LogItem) {
updateState {
copy(items = items.updating(uuid) {
addMessage(item)
})
}
}
}
val result = runSingleProviderTest(internalApi, logger)
updateState {
copy(
activeQueries = activeQueries - 1,
items = items.updating(uuid) {
copy(
isLoading = false,
result = result,
/** Only set the log level when done to prevent items from sorting directly */
highestLogLevel = log.fold(
highestLogLevel
) { acc, item -> acc.highestLogLevel(item.level) }
)
})
}
}
}
}

View file

@ -5,13 +5,12 @@ import android.net.Uri
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.safefile.SafeFile
fun Fragment.getChooseFolderLauncher(dirSelected: (uri: Uri?, path: String?) -> Unit) =
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
// It lies, it can be null if file manager quits.
if (uri == null) {
if(uri == null) {
dirSelected(null, null)
return@registerForActivityResult
}
@ -20,14 +19,7 @@ fun Fragment.getChooseFolderLauncher(dirSelected: (uri: Uri?, path: String?) ->
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
try {
context.contentResolver.takePersistableUriPermission(uri, flags)
} catch (e: SecurityException) {
// Some non-system SAF providers grant temporary access but do not expose a
// persistable grant. Keep the returned URI usable for this session instead
// of crashing while delivering the picker result.
logError(e)
}
context.contentResolver.takePersistableUriPermission(uri, flags)
val filePath = SafeFile.fromUri(context, uri)?.filePath()
println("Selected URI path: $uri - Full path: $filePath")
@ -35,4 +27,4 @@ fun Fragment.getChooseFolderLauncher(dirSelected: (uri: Uri?, path: String?) ->
// store the actual URI instead of the path due to permissions.
// filePath should only be used for cosmetic purposes.
dirSelected(uri, filePath)
}
}

View file

@ -50,18 +50,18 @@ class SetupFragmentLanguage : BaseFragment<FragmentSetupLanguageBinding>(
appIconImage.setImageDrawable(ContextCompat.getDrawable(ctx, drawable))
}
val tags = appLanguages.map { it.second }
val current = getCurrentLocale(ctx).replace('_', '-')
val currentIndex = tags.indexOf(current).takeIf { it >= 0 }
?: tags.indexOf(current.substringBefore('-'))
val current = getCurrentLocale(ctx)
val languageTagsIETF = appLanguages.map { it.second }
val languageNames = appLanguages.map { it.nameNextToFlagEmoji() }
val currentIndex = languageTagsIETF.indexOf(current)
arrayAdapter.addAll(appLanguages.map { it.nameNextToFlagEmoji() })
arrayAdapter.addAll(languageNames)
listview1.adapter = arrayAdapter
listview1.choiceMode = AbsListView.CHOICE_MODE_SINGLE
if (currentIndex >= 0) listview1.setItemChecked(currentIndex, true)
listview1.setItemChecked(currentIndex, true)
listview1.setOnItemClickListener { _, _, selectedLangIndex, _ ->
val langTagIETF = tags[selectedLangIndex]
val langTagIETF = languageTagsIETF[selectedLangIndex]
CommonActivity.setLocale(activity, langTagIETF)
settingsManager.edit {
putString(getString(R.string.locale_key), langTagIETF)

View file

@ -4,6 +4,7 @@ import android.view.View
import android.widget.AbsListView
import android.widget.ArrayAdapter
import androidx.core.content.edit
import androidx.core.util.forEach
import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceManager
import com.lagradost.cloudstream3.R
@ -26,41 +27,40 @@ class SetupFragmentMedia : BaseFragment<FragmentSetupMediaBinding>(
safe {
val ctx = context ?: return@safe
val settingsManager = PreferenceManager.getDefaultSharedPreferences(ctx)
val prefKey = getString(R.string.prefer_media_type_key)
val arrayAdapter =
ArrayAdapter<String>(ctx, R.layout.sort_bottom_single_choice)
val sortedTypes = enumValues<TvType>().sorted()
val names = enumValues<TvType>().sorted().map { it.name }
val selected = mutableListOf<Int>()
arrayAdapter.addAll(sortedTypes.map { it.name })
arrayAdapter.addAll(names)
binding.apply {
listview1.let {
it.adapter = arrayAdapter
it.choiceMode = AbsListView.CHOICE_MODE_MULTIPLE
val stored = settingsManager.getStringSet(prefKey, null)
sortedTypes.forEachIndexed { index, type ->
// All media types except NSFW are checked by default
val isChecked = stored?.contains(type.ordinal.toString())
?: (type != TvType.NSFW)
it.setItemChecked(index, isChecked)
}
val saveSelection = {
val values = sortedTypes
.filterIndexed { index, _ -> it.isItemChecked(index) }
.map { type -> type.ordinal.toString() }
.toSet()
settingsManager.edit { putStringSet(prefKey, values) }
it.setOnItemClickListener { _, _, _, _ ->
it.checkedItemPositions?.forEach { key, value ->
if (value) {
selected.add(key)
} else {
selected.remove(key)
}
}
val prefValues = selected.mapNotNull { pos ->
val item =
it.getItemAtPosition(pos)?.toString() ?: return@mapNotNull null
val itemVal = TvType.valueOf(item)
itemVal.ordinal.toString()
}.toSet()
settingsManager.edit {
putStringSet(getString(R.string.prefer_media_type_key), prefValues)
}
// Regenerate set homepage
DataStoreHelper.currentHomePage = null
}
if (stored == null) saveSelection()
it.setOnItemClickListener { _, _, _, _ -> saveSelection() }
}
nextBtt.setOnClickListener {

View file

@ -11,8 +11,6 @@ import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.mutableStateOf
import androidx.media3.common.text.Cue
import androidx.media3.common.util.UnstableApi
import com.fasterxml.jackson.annotation.JsonProperty
@ -46,16 +44,15 @@ import kotlinx.serialization.Serializable
const val CHROME_SUBTITLE_KEY = "chome_subtitle_settings"
@Serializable
@Immutable
data class SaveChromeCaptionStyle(
@JsonProperty("fontFamily") @SerialName("fontFamily") val fontFamily: String? = null,
@JsonProperty("fontGenericFamily") @SerialName("fontGenericFamily") val fontGenericFamily: Int? = null,
@JsonProperty("backgroundColor") @SerialName("backgroundColor") val backgroundColor: Int = 0x00FFFFFF, // transparent
@JsonProperty("edgeColor") @SerialName("edgeColor") val edgeColor: Int = Color.BLACK, // BLACK
@JsonProperty("edgeType") @SerialName("edgeType") val edgeType: Int = EDGE_TYPE_OUTLINE,
@JsonProperty("foregroundColor") @SerialName("foregroundColor") val foregroundColor: Int = Color.WHITE,
@JsonProperty("fontScale") @SerialName("fontScale") val fontScale: Float = 1.05f,
@JsonProperty("windowColor") @SerialName("windowColor") val windowColor: Int = Color.TRANSPARENT,
@JsonProperty("fontFamily") @SerialName("fontFamily") var fontFamily: String? = null,
@JsonProperty("fontGenericFamily") @SerialName("fontGenericFamily") var fontGenericFamily: Int? = null,
@JsonProperty("backgroundColor") @SerialName("backgroundColor") var backgroundColor: Int = 0x00FFFFFF, // transparent
@JsonProperty("edgeColor") @SerialName("edgeColor") var edgeColor: Int = Color.BLACK, // BLACK
@JsonProperty("edgeType") @SerialName("edgeType") var edgeType: Int = EDGE_TYPE_OUTLINE,
@JsonProperty("foregroundColor") @SerialName("foregroundColor") var foregroundColor: Int = Color.WHITE,
@JsonProperty("fontScale") @SerialName("fontScale") var fontScale: Float = 1.05f,
@JsonProperty("windowColor") @SerialName("windowColor") var windowColor: Int = Color.TRANSPARENT,
)
class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBinding>(
@ -95,9 +92,6 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
}
fun Context.saveStyle(style: SaveChromeCaptionStyle) {
if (chromeCastSubtitleState.value !== style) {
chromeCastSubtitleState.value = style
}
this.setKey(CHROME_SUBTITLE_KEY, style)
}
@ -107,13 +101,10 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
}
fun getCurrentSavedStyle(): SaveChromeCaptionStyle {
return chromeCastSubtitleState.value
return getKey(CHROME_SUBTITLE_KEY) ?: defaultState
}
val defaultChromeCastSubtitleState = SaveChromeCaptionStyle()
val chromeCastSubtitleState = mutableStateOf(
getKey<SaveChromeCaptionStyle>(CHROME_SUBTITLE_KEY) ?: defaultChromeCastSubtitleState
)
private val defaultState = SaveChromeCaptionStyle()
}
private fun onColorSelected(stuff: Pair<Int, Int>) {
@ -143,10 +134,10 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
private fun setColor(id: Int, color: Int?) {
val realColor = color ?: getDefColor(id)
when (id) {
0 -> state = state.copy(foregroundColor = realColor)
1 -> state = state.copy(edgeColor = realColor)
2 -> state = state.copy(backgroundColor = realColor)
3 -> state = state.copy(windowColor = realColor)
0 -> state.foregroundColor = realColor
1 -> state.edgeColor = realColor
2 -> state.backgroundColor = realColor
3 -> state.windowColor = realColor
else -> Unit
}
@ -249,13 +240,13 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
false,
dismissCallback
) { index ->
state = state.copy(edgeType = edgeTypes.map { it.first }[index])
state.edgeType = edgeTypes.map { it.first }[index]
updateState()
}
}
binding.subsEdgeType.setOnLongClickListener {
state = state.copy(edgeType = defaultChromeCastSubtitleState.edgeType)
state.edgeType = defaultState.edgeType
updateState()
showToast(R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -290,13 +281,13 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
false,
dismissCallback
) { index ->
state = state.copy(fontScale = fontSizes.map { it.first }[index])
state.fontScale = fontSizes.map { it.first }[index]
//textView.context.updateState() // font size not changed
}
}
binding.subsFontSize.setOnLongClickListener { _ ->
state = state.copy(fontScale = defaultChromeCastSubtitleState.fontScale)
state.fontScale = defaultState.fontScale
//textView.context.updateState() // font size not changed
showToast(R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -323,12 +314,12 @@ class ChromecastSubtitlesFragment : BaseFragment<ChromecastSubtitleSettingsBindi
false,
dismissCallback
) { index ->
state = state.copy(fontFamily = fontTypes.map { it.first }[index])
state.fontFamily = fontTypes.map { it.first }[index]
updateState()
}
}
binding.subsFont.setOnLongClickListener { _ ->
state = state.copy(fontFamily = defaultChromeCastSubtitleState.fontFamily)
state.fontFamily = defaultState.fontFamily
updateState()
showToast(activity, R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true

View file

@ -1,6 +0,0 @@
package com.lagradost.cloudstream3.ui.subtitles
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.lagradost.cloudstream4.compose.Screen
class ChromecastSubtitlesFragment2 : BaseComposeFragment(), Screen by ChromecastSubtitlesScreen

View file

@ -1,159 +0,0 @@
package com.lagradost.cloudstream3.ui.subtitles
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import com.google.android.gms.cast.TextTrackStyle.EDGE_TYPE_DEPRESSED
import com.google.android.gms.cast.TextTrackStyle.EDGE_TYPE_DROP_SHADOW
import com.google.android.gms.cast.TextTrackStyle.EDGE_TYPE_NONE
import com.google.android.gms.cast.TextTrackStyle.EDGE_TYPE_OUTLINE
import com.google.android.gms.cast.TextTrackStyle.EDGE_TYPE_RAISED
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment.Companion.applyStyleEvent
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment.Companion.chromeCastSubtitleState
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment.Companion.defaultChromeCastSubtitleState
import com.lagradost.cloudstream3.ui.subtitles.ChromecastSubtitlesFragment.Companion.saveStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesScreen.SetUpUndoBar
import com.mihon.common.preference.StatePreferenceStore
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlin.math.roundToInt
object ChromecastSubtitlesScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.chromecast_subtitles_settings)
// For ux purposes we also want to show a diff of what will be reset
private val diff = arrayOf<Pair<Int, (SaveChromeCaptionStyle) -> Any?>>(
R.string.subs_font to { style -> style.fontFamily },
R.string.subs_text_color to { state -> state.foregroundColor },
R.string.subs_font_size to { state -> state.fontScale },
R.string.subs_edge_type to { state -> state.edgeType },
R.string.subs_outline_color to { state -> state.edgeColor },
R.string.subs_window_color to { state -> state.windowColor },
R.string.subs_background_color to { state -> state.backgroundColor },
)
@Composable
override fun RowScope.AppBarAction() {
val initialState = remember { chromeCastSubtitleState.value }
var state by chromeCastSubtitleState
val context = LocalContext.current
SideEffect(state) {
// When we modify the state, we modify the stored data
context.saveStyle(state)
}
DisposableEffect(Unit) {
onDispose {
if (initialState != state) {
applyStyleEvent.invoke(state)
}
}
}
SetUpUndoBar(
diff = diff,
initialState = initialState,
currentState = chromeCastSubtitleState,
default = defaultChromeCastSubtitleState
)
}
@Composable
override fun getPreferences(): List<Preference> {
val store = StatePreferenceStore(chromeCastSubtitleState)
return persistentListOf(
Preference.PreferenceGroup(
title = stringResource(R.string.subs_font),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = store.field(SaveChromeCaptionStyle::fontFamily) { newValue ->
copy(fontFamily = newValue)
},
icon = painterResource(R.drawable.font_download_24px),
title = stringResource(R.string.subs_font),
entries = persistentMapOf(
null to stringResource(R.string.normal),
"Droid Sans" to "Droid Sans",
"Droid Sans Mono" to "Droid Sans Mono",
"Droid Serif Regular" to "Droid Serif Regular",
"Cutive Mono" to "Cutive Mono",
"Short Stack" to "Short Stack",
"Quintessential" to "Quintessential",
"Alegreya Sans SC" to "Alegreya Sans SC",
)
),
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveChromeCaptionStyle::foregroundColor) { newValue ->
copy(foregroundColor = newValue)
},
title = stringResource(R.string.subs_text_color),
icon = painterResource(R.drawable.format_color_text_24px),
),
Preference.PreferenceItem.SliderPreference(
preference = store.field(
get = { fontScale.times(100.0f).roundToInt() },
set = { newValue -> copy(fontScale = newValue.toFloat() * 0.01f) }),
icon = painterResource(R.drawable.text_fields_24px),
title = stringResource(R.string.subs_font_size),
valueRange = 75..150,
steps = 75 / 5 - 1,
)
)
), Preference.PreferenceGroup(
title = stringResource(R.string.subs_edge), preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = store.field(SaveChromeCaptionStyle::edgeType) { newValue ->
copy(edgeType = newValue)
},
icon = painterResource(R.drawable.shadow_24px),
title = stringResource(R.string.subs_edge_type),
entries = persistentMapOf(
EDGE_TYPE_NONE to stringResource(R.string.subtitles_none),
EDGE_TYPE_OUTLINE to stringResource(R.string.subtitles_outline),
EDGE_TYPE_DEPRESSED to stringResource(R.string.subtitles_depressed),
EDGE_TYPE_DROP_SHADOW to stringResource(R.string.subtitles_shadow),
EDGE_TYPE_RAISED to stringResource(R.string.subtitles_raised),
)
),
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveChromeCaptionStyle::edgeColor) { newValue ->
copy(edgeColor = newValue)
},
//enabled = state.edgeType != EDGE_TYPE_NONE,
title = stringResource(R.string.subs_outline_color),
icon = painterResource(R.drawable.border_color_24px),
),
)
), Preference.PreferenceGroup(
title = stringResource(R.string.background), preferenceItems = persistentListOf(
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveChromeCaptionStyle::windowColor) { newValue ->
copy(windowColor = newValue)
},
title = stringResource(R.string.subs_window_color),
icon = painterResource(R.drawable.imagesearch_roller_24px),
),
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveChromeCaptionStyle::backgroundColor) { newValue ->
copy(backgroundColor = newValue)
},
title = stringResource(R.string.subs_background_color),
icon = painterResource(R.drawable.format_color_fill_24px),
),
)
)
)
}
}

View file

@ -9,7 +9,6 @@ import android.os.Bundle
import android.text.Layout
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.util.DisplayMetrics
import android.util.TypedValue
@ -19,8 +18,6 @@ import android.widget.Toast
import androidx.annotation.FontRes
import androidx.annotation.OptIn
import androidx.annotation.Px
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.edit
import androidx.core.content.res.ResourcesCompat
import androidx.media3.common.text.Cue
@ -66,83 +63,30 @@ const val SUBTITLE_AUTO_SELECT_KEY = "subs_auto_select"
const val SUBTITLE_DOWNLOAD_KEY = "subs_auto_download"
@Serializable
enum class SubtitleFont(
@FontRes val resource: Int,
val label: String
) {
@JsonProperty("Trebuchet")
@SerialName("Trebuchet")
Trebuchet(R.font.trebuchet_ms, "Trebuchet MS"),
@JsonProperty("Netflix")
@SerialName("Netflix")
Netflix(R.font.netflix_sans, "Netflix Sans"),
@JsonProperty("Google")
@SerialName("Google")
Google(R.font.google_sans, "Google Sans"),
@JsonProperty("Open")
@SerialName("Open")
Open(R.font.open_sans, "Open Sans"),
@JsonProperty("Futura")
@SerialName("Futura")
Futura(R.font.futura, "Futura"),
@JsonProperty("Consola")
@SerialName("Consola")
Consola(R.font.consola, "Consola"),
@JsonProperty("Gotham")
@SerialName("Gotham")
Gotham(R.font.gotham, "Gotham"),
@JsonProperty("Lucida")
@SerialName("Lucida")
Lucida(R.font.lucida_grande, "Lucida Grande"),
@JsonProperty("STIX")
@SerialName("STIX")
STIX(R.font.stix_general, "STIX General"),
@JsonProperty("TimesNewRoman")
@SerialName("TimesNewRoman")
TimesNewRoman(R.font.times_new_roman, "Times New Roman"),
@JsonProperty("Verdana")
@SerialName("Verdana")
Verdana(R.font.verdana, "Verdana"),
@JsonProperty("Ubuntu")
@SerialName("Ubuntu")
Ubuntu(R.font.ubuntu_regular, "Ubuntu"),
@JsonProperty("Comic")
@SerialName("Comic")
Comic(R.font.comic_sans, "Comic Sans"),
@JsonProperty("Poppins")
@SerialName("Poppins")
Poppins(R.font.poppins_regular, "Poppins"),
@JsonProperty("Custom")
@SerialName("Custom")
Custom(0, "Custom"),
}
@Serializable
@Immutable
data class SaveCaptionStyle(
@JsonProperty("foregroundColor") @SerialName("foregroundColor") val foregroundColor: Int,
@JsonProperty("backgroundColor") @SerialName("backgroundColor") val backgroundColor: Int,
@JsonProperty("windowColor") @SerialName("windowColor") val windowColor: Int,
@JsonProperty("foregroundColor") @SerialName("foregroundColor") var foregroundColor: Int,
@JsonProperty("backgroundColor") @SerialName("backgroundColor") var backgroundColor: Int,
@JsonProperty("windowColor") @SerialName("windowColor") var windowColor: Int,
@OptIn(UnstableApi::class)
@JsonProperty("edgeType") @SerialName("edgeType") val edgeType: @CaptionStyleCompat.EdgeType Int,
@JsonProperty("edgeColor") @SerialName("edgeColor") val edgeColor: Int,
@JsonProperty("font") @SerialName("font") val font: SubtitleFont? = null,
@JsonProperty("typefaceFilePath") @SerialName("typefaceFilePath") val typefaceFilePath: String?,
@JsonProperty("elevation") @SerialName("elevation") val elevation: Int, // in dp
@JsonProperty("fixedTextSize") @SerialName("fixedTextSize") val fixedTextSize: Float?, // in sp
@Px @JsonProperty("edgeSize") @SerialName("edgeSize") val edgeSize: Float? = null,
@JsonProperty("removeCaptions") @SerialName("removeCaptions") val removeCaptions: Boolean = false,
@JsonProperty("removeBloat") @SerialName("removeBloat") val removeBloat: Boolean = true,
@JsonProperty("edgeType") @SerialName("edgeType") var edgeType: @CaptionStyleCompat.EdgeType Int,
@JsonProperty("edgeColor") @SerialName("edgeColor") var edgeColor: Int,
@FontRes @JsonProperty("typeface") @SerialName("typeface") var typeface: Int?,
@JsonProperty("typefaceFilePath") @SerialName("typefaceFilePath") var typefaceFilePath: String?,
@JsonProperty("elevation") @SerialName("elevation") var elevation: Int, // in dp
@JsonProperty("fixedTextSize") @SerialName("fixedTextSize") var fixedTextSize: Float?, // in sp
@Px @JsonProperty("edgeSize") @SerialName("edgeSize") var edgeSize: Float? = null,
@JsonProperty("removeCaptions") @SerialName("removeCaptions") var removeCaptions: Boolean = false,
@JsonProperty("removeBloat") @SerialName("removeBloat") var removeBloat: Boolean = true,
/** Apply caps lock to the text */
@JsonProperty("upperCase") @SerialName("upperCase") val upperCase: Boolean = false,
@JsonProperty("upperCase") @SerialName("upperCase") var upperCase: Boolean = false,
/** Apply bold to the text */
@JsonProperty("bold") @SerialName("bold") val bold: Boolean = false,
@JsonProperty("bold") @SerialName("bold") var bold: Boolean = false,
/** Apply italic to the text */
@JsonProperty("italic") @SerialName("italic") val italic: Boolean = false,
@JsonProperty("italic") @SerialName("italic") var italic: Boolean = false,
/** in px, background radius, aka how round the background (backgroundColor) on each row is */
@JsonProperty("backgroundRadius") @SerialName("backgroundRadius") val backgroundRadius: Float? = null,
@JsonProperty("backgroundRadius") @SerialName("backgroundRadius") var backgroundRadius: Float? = null,
/** The SSA_ALIGNMENT */
@JsonProperty("alignment") @SerialName("alignment") val alignment: Int? = null,
@JsonProperty("alignment") @SerialName("alignment") var alignment: Int? = null,
)
const val DEF_SUBS_ELEVATION = 20
@ -171,9 +115,6 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
)
}
view.clipToPadding = false
view.clipChildren = false
// we default to 25sp, this is needed as RoundedBackgroundColorSpan breaks on override sizes
val size = data.fixedTextSize ?: 25.0f
view.setFixedTextSize(TypedValue.COMPLEX_UNIT_SP, size)
@ -186,7 +127,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
}
fun Cue.Builder.applyStyle(style: SaveCaptionStyle): Cue.Builder {
val edgeSize = style.edgeSize ?: 0.0f
val edgeSize = style.edgeSize
/*
This is old code for only applying on non null
@ -204,18 +145,22 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
// instead we use the inherit size of the subtitle view
setTextSize(Cue.DIMEN_UNSET, Cue.TYPE_UNSET)
// 2. apply edge
text?.let { text ->
val textSpanBuilder = SpannableStringBuilder(text)
// 2. apply edge
if (edgeSize > 0.0f) {
textSpanBuilder.setSpan(
OutlineSpan(edgeSize), 0, textSpanBuilder.length,
val customSpan = SpannableString.valueOf(text)
if (edgeSize != null) {
customSpan.setSpan(
OutlineSpan(edgeSize), 0, customSpan.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
setText(customSpan)
}
// 3. apply bold + italic
text?.let { text ->
val customSpan = SpannableString.valueOf(text)
// 3. apply bold + italic
val typeface = when (style.bold to style.italic) {
(true to true) -> Typeface.BOLD_ITALIC
(true to false) -> Typeface.BOLD
@ -227,36 +172,39 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
}
if (typeface != Typeface.NORMAL) {
val styleSpan = StyleSpan(typeface)
textSpanBuilder.setSpan(
styleSpan, 0, textSpanBuilder.length,
customSpan.setSpan(
styleSpan, 0, customSpan.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
setText(customSpan)
}
// 4. apply radius
val radius = style.backgroundRadius ?: 0.0f
if (radius > 0.0f && style.backgroundColor != Color.TRANSPARENT) {
// 4. apply radius
text?.let { text ->
val customSpan = SpannableString.valueOf(text)
val radius = style.backgroundRadius
if (radius != null && style.backgroundColor != Color.TRANSPARENT) {
val styleSpan = RoundedBackgroundColorSpan(
style.backgroundColor,
this.textAlignment ?: Layout.Alignment.ALIGN_CENTER,
2.0F + radius * 0.5f,
radius
)
textSpanBuilder.setSpan(
styleSpan, 0, textSpanBuilder.length,
customSpan.setSpan(
styleSpan, 0, customSpan.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
setText(customSpan)
}
// 5. remove captions but ensure that styling is kept
// Just doing .replace removes all styling!
// 5. remove captions
text?.let { text ->
if (style.removeCaptions) {
for (match in captionRegex.findAll(text).toList().asReversed()) {
textSpanBuilder.delete(match.range.first, match.range.last + 1)
}
setText(text.replace(captionRegex, ""))
}
this.setText(textSpanBuilder)
}
// 6. set alignment
@ -266,31 +214,23 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
private fun Context.fromSaveToStyle(data: SaveCaptionStyle): CaptionStyleCompat {
return CaptionStyleCompat(
data.foregroundColor,
data.backgroundColor,
// we actually override with a custom span when backgroundRadius != null
if (data.backgroundRadius == null) data.backgroundColor else Color.TRANSPARENT,
data.windowColor,
data.edgeType,
data.edgeColor,
data.typefaceFilePath?.let {
try {
// RuntimeException: Font asset not found
// Fuck android, they have no good way to load a font from a uri without a copy
Typeface.createFromFile(File(it))
} catch (_: Exception) {
} catch (e: Exception) {
null
}
} ?: data.font?.let { font ->
if(font.resource != 0) {
try {
ResourcesCompat.getFont(
this,
font.resource
)
} catch (_ : Throwable) {
Typeface.SANS_SERIF
}
} else {
Typeface.SANS_SERIF
}
} ?: data.typeface?.let {
ResourcesCompat.getFont(
this,
it
)
}
?: Typeface.SANS_SERIF
)
@ -313,29 +253,25 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
}
}
private var cachedSubtitleStyle: SaveCaptionStyle? = null
fun Context.saveStyle(style: SaveCaptionStyle) {
if (subtitleStyleState.value !== style) {
subtitleStyleState.value = style
}
cachedSubtitleStyle = style
this.setKey(SUBTITLE_KEY, style)
}
val defaultSubtitleStyle = SaveCaptionStyle(
foregroundColor = getDefColor(0),
backgroundColor = getDefColor(2),
windowColor = getDefColor(3),
edgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE,
edgeColor = getDefColor(1),
font = null,
typefaceFilePath = null,
elevation = DEF_SUBS_ELEVATION,
fixedTextSize = null,
)
val subtitleStyleState =
mutableStateOf((getKey<SaveCaptionStyle>(SUBTITLE_KEY) ?: defaultSubtitleStyle))
fun getCurrentSavedStyle(): SaveCaptionStyle {
return subtitleStyleState.value
return cachedSubtitleStyle ?: (getKey(SUBTITLE_KEY) ?: SaveCaptionStyle(
foregroundColor = getDefColor(0),
backgroundColor = getDefColor(2),
windowColor = getDefColor(3),
edgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE,
edgeColor = getDefColor(1),
typeface = null,
typefaceFilePath = null,
elevation = DEF_SUBS_ELEVATION,
fixedTextSize = null,
)).also { cachedSubtitleStyle = it }
}
private fun Context.getSavedFonts(): List<File> {
@ -357,11 +293,11 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
}
fun getDownloadSubsLanguageTagIETF(): List<String> {
return getKey<List<String>>(SUBTITLE_DOWNLOAD_KEY) ?: listOf("en")
return getKey(SUBTITLE_DOWNLOAD_KEY) ?: listOf("en")
}
fun getAutoSelectLanguageTagIETF(): String {
return getKey<String>(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
return getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
}
}
@ -379,10 +315,10 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
private fun Context.setColor(id: Int, color: Int?) {
val realColor = color ?: getDefColor(id)
when (id) {
0 -> state = state.copy(foregroundColor = realColor)
1 -> state = state.copy(edgeColor = realColor)
2 -> state = state.copy(backgroundColor = realColor)
3 -> state = state.copy(windowColor = realColor)
0 -> state.foregroundColor = realColor
1 -> state.edgeColor = realColor
2 -> state.backgroundColor = realColor
3 -> state.windowColor = realColor
else -> Unit
}
@ -508,7 +444,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = state.copy(elevation = elevationTypes.map { it.first }[index])
state.elevation = elevationTypes.map { it.first }[index]
textView.context.updateState()
if (hide)
activity?.hideSystemUI()
@ -516,7 +452,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
}
subsSubtitleElevation.setOnLongClickListener {
state = state.copy(elevation = DEF_SUBS_ELEVATION)
state.elevation = DEF_SUBS_ELEVATION
it.context.updateState()
showToast(R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -539,14 +475,13 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state =
state.copy(backgroundRadius = radiusTypes.map { it.first }[index]?.toFloat())
state.backgroundRadius = radiusTypes.map { it.first }[index]?.toFloat()
textView.context.updateState()
}
}
subsBackgroundRadius.setOnLongClickListener {
state = state.copy(backgroundRadius = null)
state.backgroundRadius = null
it.context.updateState()
showToast(R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -574,7 +509,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = state.copy(alignment = alignmentTypes.map { it.first }[index])
state.alignment = alignmentTypes.map { it.first }[index]
textView.context.updateState()
}
}
@ -602,13 +537,13 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = state.copy(edgeType = edgeTypes.map { it.first }[index])
state.edgeType = edgeTypes.map { it.first }[index]
textView.context.updateState()
}
}
subsEdgeType.setOnLongClickListener {
state = state.copy(edgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE)
state.edgeType = CaptionStyleCompat.EDGE_TYPE_OUTLINE
it.context.updateState()
showToast(R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -628,7 +563,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = state.copy(fixedTextSize = fontSizes.map { it.first }[index])
state.fixedTextSize = fontSizes.map { it.first }[index]
textView.context.updateState()
}
}
@ -647,47 +582,47 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = state.copy(edgeSize = fontSizes.map { it.first }[index])
state.edgeSize = fontSizes.map { it.first }[index]
textView.context.updateState()
}
}
subtitlesRemoveBloat.isChecked = state.removeBloat
subtitlesRemoveBloat.setOnCheckedChangeListener { _, b ->
state = state.copy(removeBloat = b)
state.removeBloat = b
}
subtitlesUppercase.isChecked = state.upperCase
subtitlesUppercase.setOnCheckedChangeListener { _, b ->
state = state.copy(upperCase = b)
state.upperCase = b
context?.updateState()
}
subtitlesRemoveCaptions.isChecked = state.removeCaptions
subtitlesRemoveCaptions.setOnCheckedChangeListener { _, b ->
state = state.copy(removeCaptions = b)
state.removeCaptions = b
}
subtitlesBold.isChecked = state.bold
subtitlesBold.setOnCheckedChangeListener { _, b ->
state = state.copy(bold = b)
state.bold = b
context?.updateState()
}
subtitlesItalic.isChecked = state.italic
subtitlesItalic.setOnCheckedChangeListener { _, b ->
state = state.copy(italic = b)
state.italic = b
context?.updateState()
}
subsFontSize.setOnLongClickListener { _ ->
state = state.copy(fixedTextSize = null)
state.fixedTextSize = null
context?.updateState()
showToast(activity, R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
}
subsEdgeSize.setOnLongClickListener { _ ->
state = state.copy(edgeSize = null)
state.edgeSize = null
context?.updateState()
showToast(activity, R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true
@ -733,7 +668,7 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
savedFontTypes.indexOfFirst { it.absolutePath == state.typefaceFilePath }
.let { index ->
if (index == -1)
fontTypes.indexOfFirst { it.first == state.font?.resource }
fontTypes.indexOfFirst { it.first == state.typeface }
else index + fontTypes.size
}
@ -745,23 +680,20 @@ class SubtitlesFragment : BaseDialogFragment<SubtitleSettingsBinding>(
false,
dismissCallback
) { index ->
state = if (index < fontTypes.size) {
state.copy(
font = SubtitleFont.entries.firstOrNull { it.resource == fontTypes[index].first },
typefaceFilePath = null
)
if (index < fontTypes.size) {
state.typeface = fontTypes[index].first
state.typefaceFilePath = null
} else {
state.copy(
typefaceFilePath = savedFontTypes[index - fontTypes.size].absolutePath,
font = null
)
state.typefaceFilePath = savedFontTypes[index - fontTypes.size].absolutePath
state.typeface = null
}
textView.context.updateState()
}
}
subsFont.setOnLongClickListener { textView ->
state = state.copy(font = null, typefaceFilePath = null)
state.typeface = null
state.typefaceFilePath = null
textView.context.updateState()
showToast(activity, R.string.subs_default_reset_toast, Toast.LENGTH_SHORT)
return@setOnLongClickListener true

View file

@ -1,8 +0,0 @@
package com.lagradost.cloudstream3.ui.subtitles
import com.lagradost.cloudstream3.utils.BaseComposeFragment
import com.lagradost.cloudstream3.utils.BaseDialogComposeFragment
import com.lagradost.cloudstream4.compose.Screen
class SubtitlesFragment2 : BaseComposeFragment(), Screen by SubtitlesScreen
class SubtitlesFragmentDialog2 : BaseDialogComposeFragment(), Screen by SubtitlesScreen

View file

@ -1,453 +0,0 @@
package com.lagradost.cloudstream3.ui.subtitles
import android.text.SpannableString
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.OptIn
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.text.Cue
import androidx.media3.common.util.UnstableApi
import androidx.media3.ui.CaptionStyleCompat
import androidx.media3.ui.SubtitleView
import coil3.compose.AsyncImage
import com.lagradost.cloudstream3.CloudStreamApp
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.ui.player.CustomDecoder
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.applyStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.applyStyleEvent
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.defaultSubtitleStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.saveStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.setSubtitleViewStyle
import com.lagradost.cloudstream3.ui.subtitles.SubtitlesFragment.Companion.subtitleStyleState
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJsonLiteral
import com.lagradost.cloudstream3.utils.SubtitleHelper.languages
import com.lagradost.cloudstream4.compose.ActionDialog
import com.mihon.common.preference.AndroidPreferenceStore
import com.mihon.common.preference.DataPreferenceStore
import com.mihon.common.preference.StatePreferenceStore
import com.mihon.presentation.settings.Preference
import com.mihon.presentation.settings.SearchableSettings
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import java.io.File
object SubtitlesScreen : SearchableSettings {
@Composable
override fun getTitleRes(): String = stringResource(R.string.subtitles_settings)
// For ux purposes we also want to show a diff of what will be reset
private val diff = arrayOf<Pair<Int, (SaveCaptionStyle) -> Any?>>(
R.string.subs_font to { style -> style.font },
R.string.subs_text_color to { state -> state.foregroundColor },
R.string.subs_font_size to { state -> state.fixedTextSize },
R.string.uppercase_all_subtitles to { state -> state.upperCase },
R.string.all_subtitles_bold to { state -> state.bold },
R.string.all_subtitles_italic to { state -> state.italic },
R.string.subs_edge_type to { state -> state.edgeType },
R.string.subs_outline_color to { state -> state.edgeColor },
R.string.subs_edge_size to { state -> state.edgeSize },
R.string.subs_window_color to { state -> state.windowColor },
R.string.subs_background_color to { state -> state.backgroundColor },
R.string.background_radius to { state -> state.backgroundRadius },
R.string.subs_subtitle_alignment to { state -> state.alignment },
R.string.subs_subtitle_elevation to { state -> state.elevation },
R.string.subtitles_remove_captions to { state -> state.removeCaptions },
R.string.subtitles_remove_bloat to { state -> state.removeBloat },
)
@Composable
fun <T> SetUpUndoBar(
diff: Array<Pair<Int, (T) -> Any?>>,
initialState: T,
currentState: MutableState<T>,
default: T
) {
var currentState by currentState
var dialogShown by remember { mutableStateOf(false) }
if (dialogShown) {
ActionDialog(
title = stringResource(R.string.subs_default_reset_toast),
// This can not be converted to joinToString due to stringResource being composable
text =
@Suppress("SimplifiableCallChain")
diff.filter { (_, f) -> f(default) != f(currentState) }
.map { (name, _) -> stringResource(name) }.joinToString(separator = "\n"),
confirmText = stringResource(R.string.reset_btn),
dismissText = stringResource(R.string.dismiss),
confirm = {
currentState = default
dialogShown = false
},
dismiss = {
dialogShown = false
})
}
// Undo, current -> initial last saved value
AnimatedVisibility(currentState != initialState) {
IconButton(onClick = {
currentState = initialState
}) {
Icon(
painter = painterResource(R.drawable.undo_24px),
contentDescription = stringResource(R.string.reset_btn),
tint = MaterialTheme.colorScheme.onBackground
)
}
}
// Reset, current -> default
AnimatedVisibility(currentState != default) {
IconButton(onClick = {
dialogShown = true
}) {
Icon(
painter = painterResource(R.drawable.reset_colors_24px),
contentDescription = stringResource(R.string.subs_default_reset_toast),
tint = MaterialTheme.colorScheme.onBackground
)
}
}
}
@Composable
override fun RowScope.AppBarAction() {
val initialState = remember { subtitleStyleState.value }
var state by subtitleStyleState
val context = LocalContext.current
SideEffect(state) {
// When we modify the state, we modify the stored data
context.saveStyle(state)
}
DisposableEffect(Unit) {
onDispose {
if (initialState != state) {
applyStyleEvent.invoke(state)
}
}
}
SetUpUndoBar(
diff = diff,
initialState = initialState,
currentState = subtitleStyleState,
default = defaultSubtitleStyle
)
}
private val sortedLanguages by lazy {
languages.map { it.IETF_tag to it.nameNextToFlagEmoji() }.sortedBy {
it.second.substringAfter("\u00a0").lowercase()
}.toMap()
}
@OptIn(UnstableApi::class)
@Composable
override fun getPreferences(): List<Preference> {
val store = StatePreferenceStore(subtitleStyleState)
val dataStore = DataPreferenceStore(LocalContext.current)
val androidStore = AndroidPreferenceStore(LocalContext.current)
val subtitlesFilterSubLang = androidStore.getBoolean("filter_sub_lang_key", false)
val autoSelectSubtitles = dataStore.getString(SUBTITLE_AUTO_SELECT_KEY, "en")
val downloadSubsLanguage =
dataStore.getObjectFromString(SUBTITLE_DOWNLOAD_KEY, setOf("en"), serializer = { obj ->
obj.toList().toJsonLiteral()
}, deserializer = { json ->
parseJson<List<String>>(json).toSet()
})
val subtitleFileSelector =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
// It lies, it can be null if file manager quits.
if (uri == null) return@rememberLauncherForActivityResult
val context = CloudStreamApp.context ?: return@rememberLauncherForActivityResult
try {
val localFile = File(context.filesDir, "customfont.ttf")
localFile.delete()
localFile.createNewFile()
context.contentResolver?.openInputStream(uri)?.use { stream ->
stream.copyTo(localFile.outputStream())
}
store.state.value = store.state.value.copy(
font = SubtitleFont.Custom,
typefaceFilePath = localFile.absolutePath
)
} catch (t: Throwable) {
logError(t)
}
}
return persistentListOf(
Preference.PreferenceItem.CustomPreference(
title = stringResource(R.string.skip_type_preview), content = {
val state by store.state
val text = stringResource(R.string.subtitles_example_text)
val fixedText =
SpannableString.valueOf(if (state.upperCase) text.uppercase() else text)
Box(
modifier = Modifier
.fillMaxWidth()
.height(75.dp)
) {
AsyncImage(
contentDescription = stringResource(R.string.preview_background_img_des),
model = R.drawable.subtitles_preview_background,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
AndroidView(modifier = Modifier.fillMaxSize(), factory = { context ->
SubtitleView(context).apply {
setSubtitleViewStyle(this, state, false)
this.setCues(
listOf(
Cue.Builder().setText(fixedText).applyStyle(state).build()
)
)
}
}, update = { view ->
setSubtitleViewStyle(view, state, false)
view.setCues(
listOf(
Cue.Builder().setText(fixedText).applyStyle(state).build()
)
)
})
}
}),
Preference.PreferenceGroup(
title = stringResource(R.string.subs_font),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = store.field(SaveCaptionStyle::font) { newValue -> copy(font = newValue, typefaceFilePath = null) },
icon = painterResource(R.drawable.font_download_24px),
title = stringResource(R.string.subs_font),
entries = mapOf(null to stringResource(R.string.normal)) + SubtitleFont.entries.associateWith { it.label },
onValueChanged = { value ->
if (value?.resource == 0) {
subtitleFileSelector.launch(
arrayOf(
"font/*",
)
)
false
} else {
true
}
}
),
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveCaptionStyle::foregroundColor) { newValue ->
copy(foregroundColor = newValue)
},
title = stringResource(R.string.subs_text_color),
icon = painterResource(R.drawable.format_color_text_24px),
),
Preference.PreferenceItem.SliderPreference(
preference = store.field(
get = { fixedTextSize?.toInt() ?: 25 },
set = { newValue -> copy(fixedTextSize = newValue.toFloat()) }
),
icon = painterResource(R.drawable.text_fields_24px),
title = stringResource(R.string.subs_font_size),
valueRange = 5..60
),
Preference.PreferenceItem.SwitchPreference(
preference = store.field(SaveCaptionStyle::upperCase) { newValue ->
copy(upperCase = newValue)
},
icon = painterResource(R.drawable.uppercase_24px),
title = stringResource(R.string.uppercase_all_subtitles),
),
Preference.PreferenceItem.SwitchPreference(
preference = store.field(SaveCaptionStyle::bold) { newValue -> copy(bold = newValue) },
icon = painterResource(R.drawable.format_bold_24px),
title = stringResource(R.string.all_subtitles_bold),
),
Preference.PreferenceItem.SwitchPreference(
preference = store.field(SaveCaptionStyle::italic) { newValue -> copy(italic = newValue) },
icon = painterResource(R.drawable.format_italic_24px),
title = stringResource(R.string.all_subtitles_italic),
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.subs_edge),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
icon = painterResource(R.drawable.shadow_24px),
title = stringResource(R.string.subs_edge_type),
preference = store.field(SaveCaptionStyle::edgeType) { newValue ->
copy(edgeType = newValue)
},
entries = persistentMapOf(
CaptionStyleCompat.EDGE_TYPE_NONE to stringResource(R.string.subtitles_none),
CaptionStyleCompat.EDGE_TYPE_OUTLINE to stringResource(R.string.subtitles_outline),
CaptionStyleCompat.EDGE_TYPE_DEPRESSED to stringResource(R.string.subtitles_depressed),
CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW to stringResource(R.string.subtitles_shadow),
CaptionStyleCompat.EDGE_TYPE_RAISED to stringResource(R.string.subtitles_raised),
)
),
Preference.PreferenceItem.ColorPreference(
//enabled = state.edgeType != CaptionStyleCompat.EDGE_TYPE_NONE,
preference = store.field(SaveCaptionStyle::edgeColor) { newValue ->
copy(edgeColor = newValue)
},
title = stringResource(R.string.subs_outline_color),
icon = painterResource(R.drawable.border_color_24px),
),
Preference.PreferenceItem.SliderPreference(
preference = store.field(
get = { edgeSize?.toInt() ?: 0 },
set = { newValue -> copy(edgeSize = newValue.toFloat()) }
),
//enabled = state.edgeType == CaptionStyleCompat.EDGE_TYPE_OUTLINE,
icon = painterResource(R.drawable.shadow_add_24px),
title = stringResource(R.string.subs_edge_size),
valueRange = 0..60,
)
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.background),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveCaptionStyle::windowColor) { newValue ->
copy(windowColor = newValue)
},
title = stringResource(R.string.subs_window_color),
icon = painterResource(R.drawable.imagesearch_roller_24px),
),
Preference.PreferenceItem.ColorPreference(
preference = store.field(SaveCaptionStyle::backgroundColor) { newValue ->
copy(backgroundColor = newValue)
},
title = stringResource(R.string.subs_background_color),
icon = painterResource(R.drawable.format_color_fill_24px),
),
Preference.PreferenceItem.SliderPreference(
preference = store.field(
get = { backgroundRadius?.toInt() ?: 0 },
set = { newValue -> copy(backgroundRadius = newValue.toFloat()) }
),
icon = painterResource(R.drawable.rounded_corner_24px),
title = stringResource(R.string.background_radius),
valueRange = 0..50,
steps = 9,
)
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_player_layout),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
preference = store.field(SaveCaptionStyle::alignment) { newValue ->
copy(alignment = newValue)
},
icon = painterResource(R.drawable.format_align_center_24px),
title = stringResource(R.string.subs_subtitle_alignment),
entries = persistentMapOf(
null to stringResource(R.string.automatic),
CustomDecoder.SSA_ALIGNMENT_BOTTOM_LEFT to stringResource(R.string.bottom_left),
CustomDecoder.SSA_ALIGNMENT_BOTTOM_CENTER to stringResource(R.string.bottom_center),
CustomDecoder.SSA_ALIGNMENT_BOTTOM_RIGHT to stringResource(R.string.bottom_right),
CustomDecoder.SSA_ALIGNMENT_MIDDLE_LEFT to stringResource(R.string.middle_left),
CustomDecoder.SSA_ALIGNMENT_MIDDLE_CENTER to stringResource(R.string.middle_center),
CustomDecoder.SSA_ALIGNMENT_MIDDLE_RIGHT to stringResource(R.string.middle_right),
CustomDecoder.SSA_ALIGNMENT_TOP_LEFT to stringResource(R.string.top_left),
CustomDecoder.SSA_ALIGNMENT_TOP_CENTER to stringResource(R.string.top_center),
CustomDecoder.SSA_ALIGNMENT_TOP_RIGHT to stringResource(R.string.top_right),
)
),
Preference.PreferenceItem.SliderPreference(
preference = store.field(SaveCaptionStyle::elevation) { newValue ->
copy(elevation = newValue)
},
title = stringResource(R.string.subs_subtitle_elevation),
icon = painterResource(R.drawable.text_select_move_up_24px),
valueRange = 0..400,
steps = 39
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.extension_language),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
icon = painterResource(R.drawable.language_korean_latin_24px),
title = stringResource(R.string.subs_auto_select_language),
preference = autoSelectSubtitles,
entries = mapOf(
"None" to stringResource(R.string.none)
) + sortedLanguages,
),
Preference.PreferenceItem.MultiSelectListPreference(
icon = painterResource(R.drawable.language_download2),
title = stringResource(R.string.subs_download_languages),
preference = downloadSubsLanguage,
entries = mapOf(
"None" to stringResource(R.string.none)
) + sortedLanguages,
),
Preference.PreferenceItem.SwitchPreference(
preference = subtitlesFilterSubLang,
icon = painterResource(R.drawable.filter_alt_24px),
title = stringResource(R.string.subtitles_filter_lang),
),
)
),
Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_ui_features),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
preference = store.field(SaveCaptionStyle::removeCaptions) { newValue ->
copy(removeCaptions = newValue)
},
icon = painterResource(R.drawable.closed_caption_24px),
title = stringResource(R.string.subtitles_remove_captions),
subtitle = "[Knocking on door] Hello → Hello",
),
Preference.PreferenceItem.SwitchPreference(
preference = store.field(SaveCaptionStyle::removeBloat) { newValue ->
copy(removeBloat = newValue)
},
icon = painterResource(R.drawable.text_ad_off_24px),
title = stringResource(R.string.subtitles_remove_bloat),
),
)
),
)
}
}

View file

@ -86,14 +86,16 @@ import com.lagradost.cloudstream3.utils.FillerEpisodeCheck.toClassDir
import com.lagradost.cloudstream3.utils.JsUnpacker.Companion.load
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.downloader.DownloadObjects
import com.lagradost.cloudstream4.AppSettings
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.Cache
import java.io.File
import java.net.URL
import java.net.URLDecoder
import java.util.concurrent.Executor
import java.util.concurrent.Executors
object AppContextUtils {
fun RecyclerView.isRecyclerScrollable(): Boolean {
val layoutManager =
@ -482,14 +484,14 @@ object AppContextUtils {
fun Context.filterSearchResultByFilmQuality(data: List<SearchResponse>): List<SearchResponse> {
// Filter results omitting entries with certain quality
if (data.isNotEmpty()) {
val filteredSearchQuality = AppSettings(this).ui.filterQuality.get() /*PreferenceManager.getDefaultSharedPreferences(this)
val filteredSearchQuality = PreferenceManager.getDefaultSharedPreferences(this)
?.getStringSet(getString(R.string.pref_filter_search_quality_key), setOf())
?.mapNotNull { entry ->
entry.toIntOrNull() ?: return@mapNotNull null
} ?: listOf()*/
} ?: listOf()
if (filteredSearchQuality.isNotEmpty()) {
return data.filter { item ->
val searchQualVal = item.quality //?.ordinal ?: -1
val searchQualVal = item.quality?.ordinal ?: -1
//Log.i("filterSearch", "QuickSearch item => ${item.toJson()}")
!filteredSearchQuality.contains(searchQualVal)
}
@ -501,17 +503,17 @@ object AppContextUtils {
fun Context.filterHomePageListByFilmQuality(data: HomePageList): HomePageList {
// Filter results omitting entries with certain quality
if (data.list.isNotEmpty()) {
val filteredSearchQuality = AppSettings(this).ui.filterQuality.get() /*PreferenceManager.getDefaultSharedPreferences(this)
val filteredSearchQuality = PreferenceManager.getDefaultSharedPreferences(this)
?.getStringSet(getString(R.string.pref_filter_search_quality_key), setOf())
?.mapNotNull { entry ->
entry.toIntOrNull() ?: return@mapNotNull null
} ?: listOf()*/
} ?: listOf()
if (filteredSearchQuality.isNotEmpty()) {
return HomePageList(
name = data.name,
isHorizontalImages = data.isHorizontalImages,
list = data.list.filter { item ->
val searchQualVal = item.quality //?.ordinal ?: -1
val searchQualVal = item.quality?.ordinal ?: -1
//Log.i("filterSearch", "QuickSearch item => ${item.toJson()}")
!filteredSearchQuality.contains(searchQualVal)
}
@ -527,8 +529,7 @@ object AppContextUtils {
val data = RepositoryData(
repo.iconUrl ?: "",
repo.name,
url,
repo.description
url
)
RepositoryManager.addRepository(data)
main {
@ -634,17 +635,16 @@ object AppContextUtils {
}
}
// Deprecate after next stable
/* @Deprecated(
message = "Use splitUrlParameters instead.",
replaceWith = ReplaceWith(
expression = "splitUrlParameters(url.toString())",
imports = ["com.lagradost.cloudstream3.splitUrlParameters"],
),
level = DeprecationLevel.WARNING,
) */
fun splitQuery(url: java.net.URL): Map<String, String> {
return com.lagradost.cloudstream3.splitUrlParameters(url.toString())
fun splitQuery(url: URL): Map<String, String> {
val queryPairs: MutableMap<String, String> = LinkedHashMap()
val query: String = url.query
val pairs = query.split("&").toTypedArray()
for (pair in pairs) {
val idx = pair.indexOf("=")
queryPairs[URLDecoder.decode(pair.substring(0, idx), "UTF-8")] =
URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
}
return queryPairs
}
/**| S1:E2 Hello World
@ -902,4 +902,4 @@ object AppContextUtils {
} else null
return currentAudioFocusRequest
}
}
}

View file

@ -1,6 +1,5 @@
package com.lagradost.cloudstream3.utils
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.widget.Toast
@ -283,7 +282,7 @@ object BackupUtils {
}
}
fun Activity.restorePrompt() {
fun FragmentActivity.restorePrompt() {
runOnUiThread {
try {
restoreFileSelector?.launch(

View file

@ -1,86 +0,0 @@
package com.lagradost.cloudstream3.utils
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.isLandscape
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
import com.lagradost.cloudstream4.compose.Screen
import com.lagradost.cloudstream4.compose.createComposeView
abstract class BaseComposeFragment : Fragment(), Screen {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = createComposeView(inflater, container, savedInstanceState)
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
this.view?.let { view ->
fixSystemBarsPadding(
view,
padLeft = isLayout(TV or EMULATOR),
padBottom = isLandscape()
)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fixSystemBarsPadding(
view,
padLeft = isLayout(TV or EMULATOR),
padBottom = isLandscape()
)
}
}
abstract class BaseDialogComposeFragment : DialogFragment(), Screen {
var systemBarsAddPadding = isLayout(TV or EMULATOR)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = createComposeView(inflater, container, savedInstanceState)
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
dialog?.window?.decorView?.let { view ->
fixSystemBarsPadding(
view,
padLeft = systemBarsAddPadding,
padBottom = systemBarsAddPadding || isLandscape()
)
}
}
override fun onStart() {
super.onStart()
dialog?.window?.setWindowAnimations(R.style.DialogFullscreenPlayer)
}
override fun getTheme(): Int {
return R.style.DialogFullscreenPlayer
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.window?.decorView?.let { view ->
fixSystemBarsPadding(
view,
padLeft = systemBarsAddPadding,
padBottom = systemBarsAddPadding || isLandscape()
)
}
}
}

View file

@ -181,11 +181,11 @@ object DataStore {
}
fun <T : Any> Context.getKey(path: String, valueType: Class<T>): T? {
return try {
try {
val json: String = getSharedPrefs().getString(path, null) ?: return null
parseJson(json, valueType.kotlin)
} catch (_: Exception) {
null
return parseJson(json, valueType.kotlin)
} catch (e: Exception) {
return null
}
}
@ -193,37 +193,21 @@ object DataStore {
setKey(getFolderName(folder, path), value)
}
@Deprecated(
message = "Use parseJson<T>(this) directly instead.",
level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith(
expression = "parseJson<T>(this)",
imports = ["com.lagradost.cloudstream3.utils.AppUtils.parseJson"],
),
)
inline fun <reified T : Any> String.toKotlinObject(): T {
return parseJson(this)
}
@Deprecated(
message = "Use parseJson<T>(this) directly instead.",
level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith(
expression = "parseJson<T>(this)",
imports = ["com.lagradost.cloudstream3.utils.AppUtils.parseJson"],
),
)
fun <T : Any> String.toKotlinObject(valueType: Class<T>): T {
return parseJson(this, valueType.kotlin)
}
// GET KEY GIVEN PATH AND DEFAULT VALUE, NULL IF ERROR
inline fun <reified T : Any> Context.getKey(path: String, defVal: T?): T? {
return try {
try {
val json: String = getSharedPrefs().getString(path, null) ?: return defVal
parseJson<T>(json)
} catch (_: Exception) {
null
return json.toKotlinObject()
} catch (e: Exception) {
return null
}
}

View file

@ -1,8 +1,6 @@
package com.lagradost.cloudstream3.utils
import android.content.Context
import androidx.compose.runtime.Immutable
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.APIHolder.unixTimeMS
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
@ -33,14 +31,6 @@ import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.ui.result.VideoWatchState
import com.lagradost.cloudstream3.utils.AppContextUtils.filterProviderByPreferredMedia
import com.lagradost.cloudstream3.utils.downloader.DownloadObjects
import com.lagradost.cloudstream3.utils.serializers.WriteOnlySerializer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KeepGeneratedSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
@ -53,18 +43,17 @@ const val RESULT_WATCH_STATE = "result_watch_state"
const val RESULT_WATCH_STATE_DATA = "result_watch_state_data"
const val RESULT_SUBSCRIBED_STATE_DATA = "result_subscribed_state_data"
const val RESULT_FAVORITES_STATE_DATA = "result_favorites_state_data"
const val RESULT_RESUME_WATCHING = "result_resume_watching_2" // Changed due to id changes
const val RESULT_RESUME_WATCHING = "result_resume_watching_2" // changed due to id changes
const val RESULT_RESUME_WATCHING_OLD = "result_resume_watching"
const val RESULT_RESUME_WATCHING_HAS_MIGRATED = "result_resume_watching_migrated"
const val RESULT_EPISODE = "result_episode"
const val RESULT_SEASON = "result_season"
const val RESULT_DUB = "result_dub"
const val KEY_RESULT_SORT = "result_sort"
const val USER_PINNED_PROVIDERS = "user_pinned_providers" // Key for pinned user set
const val USER_PINNED_PROVIDERS = "user_pinned_providers" //key for pinned user set
class UserPreferenceDelegate<T : Any>(
private val key: String,
private val default: T,
private val key: String, private val default: T //, private val klass: KClass<T>
) {
private val klass: KClass<out T> = default::class
private val realKey get() = "${DataStoreHelper.currentAccount}/$key"
@ -74,7 +63,7 @@ class UserPreferenceDelegate<T : Any>(
operator fun setValue(
self: Any?,
property: KProperty<*>,
t: T?,
t: T?
) {
if (t == null) {
removeKey(realKey)
@ -93,7 +82,7 @@ object DataStoreHelper {
R.drawable.profile_bg_pink,
R.drawable.profile_bg_purple,
R.drawable.profile_bg_red,
R.drawable.profile_bg_teal,
R.drawable.profile_bg_teal
)
private var searchPreferenceProvidersStrings: List<String> by UserPreferenceDelegate(
@ -123,17 +112,16 @@ object DataStoreHelper {
private var searchPreferenceTagsStrings: List<String> by UserPreferenceDelegate(
"search_pref_tags",
listOf(TvType.Movie, TvType.TvSeries).map { it.name })
var searchPreferenceTags: List<TvType>
get() = deserializeTv(searchPreferenceTagsStrings)
set(value) {
searchPreferenceTagsStrings = serializeTv(value)
}
private var homePreferenceStrings: List<String> by UserPreferenceDelegate(
"home_pref_homepage",
listOf(TvType.Movie, TvType.TvSeries).map { it.name })
var homePreference: List<TvType>
get() = deserializeTv(homePreferenceStrings)
set(value) {
@ -144,39 +132,38 @@ object DataStoreHelper {
"home_bookmarked_last_list",
IntArray(0)
)
var playBackSpeed: Float by UserPreferenceDelegate("playback_speed", 1.0f)
var resizeMode: Int by UserPreferenceDelegate("resize_mode", 0)
var librarySortingMode: Int by UserPreferenceDelegate(
"library_sorting_mode",
ListSorting.AlphabeticalA.ordinal
)
private var _resultsSortingMode: Int by UserPreferenceDelegate(
"results_sorting_mode",
EpisodeSortType.NUMBER_ASC.ordinal
)
var resultsSortingMode: EpisodeSortType
get() = EpisodeSortType.entries.getOrNull(_resultsSortingMode) ?: EpisodeSortType.NUMBER_ASC
set(value) {
_resultsSortingMode = value.ordinal
}
@Serializable
@Immutable
data class Account(
@JsonProperty("keyIndex") @SerialName("keyIndex") val keyIndex: Int,
@JsonProperty("name") @SerialName("name") val name: String,
@JsonProperty("customImage") @SerialName("customImage") val customImage: String? = null,
@JsonProperty("defaultImageIndex") @SerialName("defaultImageIndex") val defaultImageIndex: Int,
@JsonProperty("lockPin") @SerialName("lockPin") val lockPin: String? = null,
@JsonProperty("keyIndex")
val keyIndex: Int,
@JsonProperty("name")
val name: String,
@JsonProperty("customImage")
val customImage: String? = null,
@JsonProperty("defaultImageIndex")
val defaultImageIndex: Int,
@JsonProperty("lockPin")
val lockPin: String? = null,
) {
@get:JsonIgnore
val image get() = customImage?.let { UiImage.Image(it) } ?:
profileImages.getOrNull(defaultImageIndex)?.let {
UiImage.Drawable(it)
} ?: UiImage.Drawable(profileImages.first())
val image
get() = customImage?.let { UiImage.Image(it) } ?: profileImages.getOrNull(
defaultImageIndex
)?.let { UiImage.Drawable(it) } ?: UiImage.Drawable(profileImages.first())
}
const val TAG = "data_store_helper"
@ -184,16 +171,12 @@ object DataStoreHelper {
var selectedKeyIndex by PreferenceDelegate("$TAG/account_key_index", 0)
val currentAccount: String get() = selectedKeyIndex.toString()
private val _selectedAccountNumberFlow = MutableStateFlow(0)
/** What account instance we are on, this number changes whenever anything about local accounts changes */
val selectedAccountNumberFlow : StateFlow<Int> = _selectedAccountNumberFlow
/**
* Get or set the current account homepage.
* Setting this does not automatically reload the homepage.
*/
var currentHomePage: String?
get() = getKey<String>("$currentAccount/$USER_SELECTED_HOMEPAGE_API")
get() = getKey("$currentAccount/$USER_SELECTED_HOMEPAGE_API")
set(value) {
val key = "$currentAccount/$USER_SELECTED_HOMEPAGE_API"
if (value == null) {
@ -203,13 +186,12 @@ object DataStoreHelper {
}
}
fun setAccount(account: Account, showToast : Boolean = true) {
fun setAccount(account: Account) {
val homepage = currentHomePage
selectedKeyIndex = account.keyIndex
AccountManager.updateAccountIds()
if(showToast) {
showToast(context?.getString(R.string.logged_account, account.name) ?: account.name)
}
showToast(context?.getString(R.string.logged_account, account.name) ?: account.name)
MainActivity.bookmarksUpdatedEvent(true)
MainActivity.reloadLibraryEvent(true)
val oldAccount = accounts.find { it.keyIndex == account.keyIndex }
@ -217,7 +199,6 @@ object DataStoreHelper {
// This is not a new account, and the homepage has changed, reload it
MainActivity.reloadHomeEvent(true)
}
_selectedAccountNumberFlow.value += 1
}
fun getDefaultAccount(context: Context): Account {
@ -225,7 +206,7 @@ object DataStoreHelper {
currentAccounts.getOrNull(currentAccounts.indexOfFirst { it.keyIndex == 0 }) ?: Account(
keyIndex = 0,
name = context.getString(R.string.default_account),
defaultImageIndex = 0,
defaultImageIndex = 0
)
}
}
@ -251,21 +232,18 @@ object DataStoreHelper {
}
}
@Serializable
data class PosDur(
@JsonProperty("position") @SerialName("position") val position: Long,
@JsonProperty("duration") @SerialName("duration") val duration: Long,
@JsonProperty("position") val position: Long,
@JsonProperty("duration") val duration: Long
)
fun PosDur.fixVisual(): PosDur {
if (duration <= 0) return PosDur(0, duration)
val percentage = position * 100 / duration
return when {
percentage <= 1 -> PosDur(0, duration)
percentage <= 5 -> PosDur(5 * duration / 100, duration)
percentage >= 95 -> PosDur(duration, duration)
else -> this
}
if (percentage <= 1) return PosDur(0, duration)
if (percentage <= 5) return PosDur(5 * duration / 100, duration)
if (percentage >= 95) return PosDur(duration, duration)
return this
}
fun Int.toYear(): Date =
@ -273,38 +251,28 @@ object DataStoreHelper {
/**
* Used to display notifications on new episodes and posters in library.
*/
@Serializable
**/
abstract class LibrarySearchResponse(
/**
* These fields are marked @Transient because this class is only ever serialized through
* through its subclasses, which redeclare each property with their own @SerialName
* annotations. Without @Transient here, kotlinx.serialization would try to
* generate a serializer for the abstract base class itself (or double-serialize
* these fields), which fails/conflicts since these are meant to be overridden,
* not serialized directly from the parent.
*/
@Transient override var id: Int? = null,
@Transient open val latestUpdatedTime: Long = 0L,
@Transient override val name: String = "",
@Transient override val url: String = "",
@Transient override val apiName: String = "",
@Transient override var type: TvType? = null,
@Transient override var posterUrl: String? = null,
@Transient open val year: Int? = null,
@Transient open val syncData: Map<String, String>? = null,
@Transient override var quality: SearchQuality? = null,
@Transient override var posterHeaders: Map<String, String>? = null,
@Transient open val plot: String? = null,
@Transient override var score: Score? = null,
@Transient open val tags: List<String>? = null,
@JsonProperty("id") override var id: Int?,
@JsonProperty("latestUpdatedTime") open val latestUpdatedTime: Long,
@JsonProperty("name") override val name: String,
@JsonProperty("url") override val url: String,
@JsonProperty("apiName") override val apiName: String,
@JsonProperty("type") override var type: TvType?,
@JsonProperty("posterUrl") override var posterUrl: String?,
@JsonProperty("year") open val year: Int?,
@JsonProperty("syncData") open val syncData: Map<String, String>?,
@JsonProperty("quality") override var quality: SearchQuality?,
@JsonProperty("posterHeaders") override var posterHeaders: Map<String, String>?,
@JsonProperty("plot") open val plot: String? = null,
@JsonProperty("score") override var score: Score? = null,
@JsonProperty("tags") open val tags: List<String>? = null,
) : SearchResponse {
@JsonProperty("rating", access = JsonProperty.Access.WRITE_ONLY)
@SerialName("rating")
@Deprecated(
"`rating` is the old scoring system, use score instead",
replaceWith = ReplaceWith("score"),
level = DeprecationLevel.ERROR,
level = DeprecationLevel.ERROR
)
var rating: Int? = null
set(value) {
@ -315,26 +283,23 @@ object DataStoreHelper {
}
}
@OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
@KeepGeneratedSerializer
@Serializable(with = SubscribedData.Serializer::class)
data class SubscribedData(
@JsonProperty("subscribedTime") @SerialName("subscribedTime") val subscribedTime: Long,
@JsonProperty("lastSeenEpisodeCount") @SerialName("lastSeenEpisodeCount") val lastSeenEpisodeCount: Map<DubStatus, Int?>,
@JsonProperty("id") @SerialName("id") override var id: Int?,
@JsonProperty("latestUpdatedTime") @SerialName("latestUpdatedTime") override val latestUpdatedTime: Long,
@JsonProperty("name") @SerialName("name") override val name: String,
@JsonProperty("url") @SerialName("url") override val url: String,
@JsonProperty("apiName") @SerialName("apiName") override val apiName: String,
@JsonProperty("type") @SerialName("type") override var type: TvType?,
@JsonProperty("posterUrl") @SerialName("posterUrl") override var posterUrl: String?,
@JsonProperty("year") @SerialName("year") override val year: Int?,
@JsonProperty("syncData") @SerialName("syncData") override val syncData: Map<String, String>? = null,
@JsonProperty("quality") @SerialName("quality") override var quality: SearchQuality? = null,
@JsonProperty("posterHeaders") @SerialName("posterHeaders") override var posterHeaders: Map<String, String>? = null,
@JsonProperty("plot") @SerialName("plot") override val plot: String? = null,
@JsonProperty("score") @SerialName("score") override var score: Score? = null,
@JsonProperty("tags") @SerialName("tags") override val tags: List<String>? = null,
@JsonProperty("subscribedTime") val subscribedTime: Long,
@JsonProperty("lastSeenEpisodeCount") val lastSeenEpisodeCount: Map<DubStatus, Int?>,
override var id: Int?,
override val latestUpdatedTime: Long,
override val name: String,
override val url: String,
override val apiName: String,
override var type: TvType?,
override var posterUrl: String?,
override val year: Int?,
override val syncData: Map<String, String>? = null,
override var quality: SearchQuality? = null,
override var posterHeaders: Map<String, String>? = null,
override val plot: String? = null,
override var score: Score? = null,
override val tags: List<String>? = null,
) : LibrarySearchResponse(
id,
latestUpdatedTime,
@ -349,13 +314,8 @@ object DataStoreHelper {
posterHeaders,
plot,
score,
tags,
tags
) {
object Serializer : WriteOnlySerializer<SubscribedData>(
SubscribedData.generatedSerializer(),
setOf("rating"),
)
fun toLibraryItem(): SyncAPI.LibraryItem? {
return SyncAPI.LibraryItem(
name,
@ -374,30 +334,27 @@ object DataStoreHelper {
this.id,
plot = this.plot,
score = this.score,
tags = this.tags,
tags = this.tags
)
}
}
@OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
@KeepGeneratedSerializer
@Serializable(with = BookmarkedData.Serializer::class)
data class BookmarkedData(
@JsonProperty("bookmarkedTime") @SerialName("bookmarkedTime") val bookmarkedTime: Long,
@JsonProperty("id") @SerialName("id") override var id: Int?,
@JsonProperty("latestUpdatedTime") @SerialName("latestUpdatedTime") override val latestUpdatedTime: Long,
@JsonProperty("name") @SerialName("name") override val name: String,
@JsonProperty("url") @SerialName("url") override val url: String,
@JsonProperty("apiName") @SerialName("apiName") override val apiName: String,
@JsonProperty("type") @SerialName("type") override var type: TvType?,
@JsonProperty("posterUrl") @SerialName("posterUrl") override var posterUrl: String?,
@JsonProperty("year") @SerialName("year") override val year: Int?,
@JsonProperty("syncData") @SerialName("syncData") override val syncData: Map<String, String>? = null,
@JsonProperty("quality") @SerialName("quality") override var quality: SearchQuality? = null,
@JsonProperty("posterHeaders") @SerialName("posterHeaders") override var posterHeaders: Map<String, String>? = null,
@JsonProperty("plot") @SerialName("plot") override val plot: String? = null,
@JsonProperty("score") @SerialName("score") override var score: Score? = null,
@JsonProperty("tags") @SerialName("tags") override val tags: List<String>? = null,
@JsonProperty("bookmarkedTime") val bookmarkedTime: Long,
override var id: Int?,
override val latestUpdatedTime: Long,
override val name: String,
override val url: String,
override val apiName: String,
override var type: TvType?,
override var posterUrl: String?,
override val year: Int?,
override val syncData: Map<String, String>? = null,
override var quality: SearchQuality? = null,
override var posterHeaders: Map<String, String>? = null,
override val plot: String? = null,
override var score: Score? = null,
override val tags: List<String>? = null,
) : LibrarySearchResponse(
id,
latestUpdatedTime,
@ -410,13 +367,8 @@ object DataStoreHelper {
syncData,
quality,
posterHeaders,
plot,
plot
) {
object Serializer : WriteOnlySerializer<BookmarkedData>(
BookmarkedData.generatedSerializer(),
setOf("rating"),
)
fun toLibraryItem(id: String): SyncAPI.LibraryItem {
return SyncAPI.LibraryItem(
name,
@ -435,30 +387,27 @@ object DataStoreHelper {
this.id,
plot = this.plot,
score = this.score,
tags = this.tags,
tags = this.tags
)
}
}
@OptIn(ExperimentalSerializationApi::class) // KeepGeneratedSerializer is an experimental annotation for now
@KeepGeneratedSerializer
@Serializable(with = FavoritesData.Serializer::class)
data class FavoritesData(
@JsonProperty("favoritesTime") @SerialName("favoritesTime") val favoritesTime: Long,
@JsonProperty("id") @SerialName("id") override var id: Int?,
@JsonProperty("latestUpdatedTime") @SerialName("latestUpdatedTime") override val latestUpdatedTime: Long,
@JsonProperty("name") @SerialName("name") override val name: String,
@JsonProperty("url") @SerialName("url") override val url: String,
@JsonProperty("apiName") @SerialName("apiName") override val apiName: String,
@JsonProperty("type") @SerialName("type") override var type: TvType?,
@JsonProperty("posterUrl") @SerialName("posterUrl") override var posterUrl: String?,
@JsonProperty("year") @SerialName("year") override val year: Int?,
@JsonProperty("syncData") @SerialName("syncData") override val syncData: Map<String, String>? = null,
@JsonProperty("quality") @SerialName("quality") override var quality: SearchQuality? = null,
@JsonProperty("posterHeaders") @SerialName("posterHeaders") override var posterHeaders: Map<String, String>? = null,
@JsonProperty("plot") @SerialName("plot") override val plot: String? = null,
@JsonProperty("score") @SerialName("score") override var score: Score? = null,
@JsonProperty("tags") @SerialName("tags") override val tags: List<String>? = null,
@JsonProperty("favoritesTime") val favoritesTime: Long,
override var id: Int?,
override val latestUpdatedTime: Long,
override val name: String,
override val url: String,
override val apiName: String,
override var type: TvType?,
override var posterUrl: String?,
override val year: Int?,
override val syncData: Map<String, String>? = null,
override var quality: SearchQuality? = null,
override var posterHeaders: Map<String, String>? = null,
override val plot: String? = null,
override var score: Score? = null,
override val tags: List<String>? = null,
) : LibrarySearchResponse(
id,
latestUpdatedTime,
@ -471,13 +420,8 @@ object DataStoreHelper {
syncData,
quality,
posterHeaders,
plot,
plot
) {
object Serializer : WriteOnlySerializer<FavoritesData>(
FavoritesData.generatedSerializer(),
setOf("rating"),
)
fun toLibraryItem(): SyncAPI.LibraryItem? {
return SyncAPI.LibraryItem(
name,
@ -496,32 +440,31 @@ object DataStoreHelper {
this.id,
plot = this.plot,
score = this.score,
tags = this.tags,
tags = this.tags
)
}
}
@Serializable
data class ResumeWatchingResult(
@JsonProperty("name") @SerialName("name") override val name: String,
@JsonProperty("url") @SerialName("url") override val url: String,
@JsonProperty("apiName") @SerialName("apiName") override val apiName: String,
@JsonProperty("type") @SerialName("type") override var type: TvType? = null,
@JsonProperty("posterUrl") @SerialName("posterUrl") override var posterUrl: String?,
@JsonProperty("watchPos") @SerialName("watchPos") val watchPos: PosDur?,
@JsonProperty("id") @SerialName("id") override var id: Int?,
@JsonProperty("parentId") @SerialName("parentId") val parentId: Int?,
@JsonProperty("episode") @SerialName("episode") val episode: Int?,
@JsonProperty("season") @SerialName("season") val season: Int?,
@JsonProperty("isFromDownload") @SerialName("isFromDownload") val isFromDownload: Boolean,
@JsonProperty("quality") @SerialName("quality") override var quality: SearchQuality? = null,
@JsonProperty("posterHeaders") @SerialName("posterHeaders") override var posterHeaders: Map<String, String>? = null,
@JsonProperty("score") @SerialName("score") override var score: Score? = null,
@JsonProperty("name") override val name: String,
@JsonProperty("url") override val url: String,
@JsonProperty("apiName") override val apiName: String,
@JsonProperty("type") override var type: TvType? = null,
@JsonProperty("posterUrl") override var posterUrl: String?,
@JsonProperty("watchPos") val watchPos: PosDur?,
@JsonProperty("id") override var id: Int?,
@JsonProperty("parentId") val parentId: Int?,
@JsonProperty("episode") val episode: Int?,
@JsonProperty("season") val season: Int?,
@JsonProperty("isFromDownload") val isFromDownload: Boolean,
@JsonProperty("quality") override var quality: SearchQuality? = null,
@JsonProperty("posterHeaders") override var posterHeaders: Map<String, String>? = null,
@JsonProperty("score") override var score: Score? = null,
) : SearchResponse
/**
* A datastore wide account for future implementations of a multiple account system
*/
**/
fun getAllWatchStateIds(): List<Int>? {
val folder = "$currentAccount/$RESULT_WATCH_STATE"
@ -557,7 +500,7 @@ object DataStoreHelper {
}
fun migrateResumeWatching() {
// if (getKey<Boolean>(RESULT_RESUME_WATCHING_HAS_MIGRATED, false) != true) {
// if (getKey(RESULT_RESUME_WATCHING_HAS_MIGRATED, false) != true) {
setKey(RESULT_RESUME_WATCHING_HAS_MIGRATED, true)
getAllResumeStateIdsOld()?.forEach { id ->
getLastWatchedOld(id)?.let {
@ -567,12 +510,12 @@ object DataStoreHelper {
it.episode,
it.season,
it.isFromDownload,
it.updateTime,
it.updateTime
)
removeLastWatchedOld(it.parentId)
}
}
// }
//}
}
fun setLastWatched(
@ -593,7 +536,7 @@ object DataStoreHelper {
episode,
season,
updateTime ?: System.currentTimeMillis(),
isFromDownload,
isFromDownload
)
)
}
@ -610,7 +553,7 @@ object DataStoreHelper {
fun getLastWatched(id: Int?): DownloadObjects.ResumeWatching? {
if (id == null) return null
return getKey<DownloadObjects.ResumeWatching>(
return getKey(
"$currentAccount/$RESULT_RESUME_WATCHING",
id.toString(),
)
@ -618,7 +561,7 @@ object DataStoreHelper {
private fun getLastWatchedOld(id: Int?): DownloadObjects.ResumeWatching? {
if (id == null) return null
return getKey<DownloadObjects.ResumeWatching>(
return getKey(
"$currentAccount/$RESULT_RESUME_WATCHING_OLD",
id.toString(),
)
@ -632,18 +575,18 @@ object DataStoreHelper {
fun getBookmarkedData(id: Int?): BookmarkedData? {
if (id == null) return null
return getKey<BookmarkedData>("$currentAccount/$RESULT_WATCH_STATE_DATA", id.toString())
return getKey("$currentAccount/$RESULT_WATCH_STATE_DATA", id.toString())
}
fun getAllBookmarkedData(): List<BookmarkedData> {
return getKeys("$currentAccount/$RESULT_WATCH_STATE_DATA")?.mapNotNull {
getKey<BookmarkedData>(it)
getKey(it)
} ?: emptyList()
}
fun getAllSubscriptions(): List<SubscribedData> {
return getKeys("$currentAccount/$RESULT_SUBSCRIBED_STATE_DATA")?.mapNotNull {
getKey<SubscribedData>(it)
getKey(it)
} ?: emptyList()
}
@ -655,12 +598,12 @@ object DataStoreHelper {
/**
* Set new seen episodes and update time
*/
**/
fun updateSubscribedData(id: Int?, data: SubscribedData?, episodeResponse: EpisodeResponse?) {
if (id == null || data == null || episodeResponse == null) return
val newData = data.copy(
latestUpdatedTime = unixTimeMS,
lastSeenEpisodeCount = episodeResponse.getLatestEpisodes(),
lastSeenEpisodeCount = episodeResponse.getLatestEpisodes()
)
setKey("$currentAccount/$RESULT_SUBSCRIBED_STATE_DATA", id.toString(), newData)
}
@ -673,12 +616,12 @@ object DataStoreHelper {
fun getSubscribedData(id: Int?): SubscribedData? {
if (id == null) return null
return getKey<SubscribedData>("$currentAccount/$RESULT_SUBSCRIBED_STATE_DATA", id.toString())
return getKey("$currentAccount/$RESULT_SUBSCRIBED_STATE_DATA", id.toString())
}
fun getAllFavorites(): List<FavoritesData> {
return getKeys("$currentAccount/$RESULT_FAVORITES_STATE_DATA")?.mapNotNull {
getKey<FavoritesData>(it)
getKey(it)
} ?: emptyList()
}
@ -696,7 +639,7 @@ object DataStoreHelper {
fun getFavoritesData(id: Int?): FavoritesData? {
if (id == null) return null
return getKey<FavoritesData>("$currentAccount/$RESULT_FAVORITES_STATE_DATA", id.toString())
return getKey("$currentAccount/$RESULT_FAVORITES_STATE_DATA", id.toString())
}
fun setViewPos(id: Int?, pos: Long, dur: Long) {
@ -705,10 +648,10 @@ object DataStoreHelper {
setKey("$currentAccount/$VIDEO_POS_DUR", id.toString(), PosDur(pos, dur))
}
/**
* Sets the position, duration, and resume data of an episode/movie,
* If nextEpisode is not specified it will not be able to set the next episode as resumable if progress > NEXT_WATCH_EPISODE_PERCENTAGE
*/
/** Sets the position, duration, and resume data of an episode/movie,
*
* if nextEpisode is not specified it will not be able to set the next episode as resumable if progress > NEXT_WATCH_EPISODE_PERCENTAGE
* */
fun setViewPosAndResume(id: Int?, position: Long, duration: Long, currentEpisode: Any?, nextEpisode: Any?) {
setViewPos(id, position, duration)
if (id != null) {
@ -744,7 +687,7 @@ object DataStoreHelper {
resumeMeta.id,
resumeMeta.episode,
resumeMeta.season,
isFromDownload = false,
isFromDownload = false
)
}
@ -754,7 +697,7 @@ object DataStoreHelper {
resumeMeta.id,
resumeMeta.episode,
resumeMeta.season,
isFromDownload = true,
isFromDownload = true
)
}
}
@ -763,16 +706,17 @@ object DataStoreHelper {
fun getViewPos(id: Int?): PosDur? {
if (id == null) return null
return getKey<PosDur>("$currentAccount/$VIDEO_POS_DUR", id.toString(), null)
return getKey("$currentAccount/$VIDEO_POS_DUR", id.toString(), null)
}
fun getVideoWatchState(id: Int?): VideoWatchState? {
if (id == null) return null
return getKey<VideoWatchState>("$currentAccount/$VIDEO_WATCH_STATE", id.toString(), null)
return getKey("$currentAccount/$VIDEO_WATCH_STATE", id.toString(), null)
}
fun setVideoWatchState(id: Int?, watchState: VideoWatchState) {
if (id == null) return
// None == No key
if (watchState == VideoWatchState.None) {
removeKey("$currentAccount/$VIDEO_WATCH_STATE", id.toString())
@ -783,7 +727,7 @@ object DataStoreHelper {
fun getDub(id: Int): DubStatus? {
return DubStatus.entries
.getOrNull(getKey<Int>("$currentAccount/$RESULT_DUB", id.toString(), -1) ?: -1)
.getOrNull(getKey("$currentAccount/$RESULT_DUB", id.toString(), -1) ?: -1)
}
fun setDub(id: Int, status: DubStatus) {
@ -804,13 +748,13 @@ object DataStoreHelper {
getKey<Int>(
"$currentAccount/$RESULT_WATCH_STATE",
id.toString(),
null,
null
)
)
}
fun getResultSeason(id: Int): Int? {
return getKey<Int>("$currentAccount/$RESULT_SEASON", id.toString(), null)
return getKey("$currentAccount/$RESULT_SEASON", id.toString(), null)
}
fun setResultSeason(id: Int, value: Int?) {
@ -818,7 +762,7 @@ object DataStoreHelper {
}
fun getResultEpisode(id: Int): Int? {
return getKey<Int>("$currentAccount/$RESULT_EPISODE", id.toString(), null)
return getKey("$currentAccount/$RESULT_EPISODE", id.toString(), null)
}
fun setResultEpisode(id: Int, value: Int?) {
@ -831,11 +775,12 @@ object DataStoreHelper {
fun getSync(id: Int, idPrefixes: List<String>): List<String?> {
return idPrefixes.map { idPrefix ->
getKey<String>("${idPrefix}_sync", id.toString())
getKey("${idPrefix}_sync", id.toString())
}
}
var pinnedProviders: Array<String>
get() = getKey<Array<String>>(USER_PINNED_PROVIDERS) ?: emptyArray<String>()
get() = getKey(USER_PINNED_PROVIDERS) ?: emptyArray<String>()
set(value) = setKey(USER_PINNED_PROVIDERS, value)
}

View file

@ -1,233 +0,0 @@
/**
* Modified ver of a basic Markdown parser:
* https://github.com/DAKSHSEMWAL/mdparserkit
* **/
package com.lagradost.cloudstream3.utils
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withLink
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
//private val lineNumberRegex: Regex = Regex("^\\d+\\.\\s.*$")
private val boldItalicPattern = Regex("\\*\\*[*_](.*?)[*_]\\*\\*")
private val boldPattern = Regex("\\*\\*(.*?)\\*\\*")
private val italicPattern = Regex("[*_](.*?)[*_]")
private val strikethroughPattern = Regex("~~(.+?)~~")
private val linkPattern = Regex("\\[(.*?)]\\((.*?)\\)")
/**
* Parses a given Markdown text and converts it into an [AnnotatedString] with appropriate styles.
*
* @param markdownText The input Markdown text to parse.
* @return An [AnnotatedString] with styles applied according to the Markdown syntax.
*/
fun parseMarkdown(markdownText: String): AnnotatedString {
try {
val lines = markdownText.split("\n")
val resultBuilder = AnnotatedString.Builder()
lines.forEach { line ->
when {
// Heading 1: Extracting content, applying bold style, and appending to resultBuilder
line.startsWith("# ") -> {
textMarkDown(
line.removePrefix("# ").trim(),
resultBuilder,
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
// Similar processing for Heading 2 to Heading 6
// Heading 2
line.startsWith("## ") -> {
textMarkDown(
line.removePrefix("## ").trim(),
resultBuilder,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
// Heading 3
line.startsWith("### ") -> {
textMarkDown(
line.removePrefix("### ").trim(),
resultBuilder,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
// Heading 4
line.startsWith("#### ") -> {
textMarkDown(
line.removePrefix("#### ").trim(),
resultBuilder,
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
}
// Heading 5
line.startsWith("##### ") -> {
textMarkDown(
line.removePrefix("##### ").trim(),
resultBuilder,
fontSize = 14.sp,
fontWeight = FontWeight.Bold
)
}
// Heading 6
line.startsWith("###### ") -> {
textMarkDown(
line.removePrefix("###### ").trim(),
resultBuilder,
fontSize = 12.sp,
fontWeight = FontWeight.Bold
)
}
// Unordered list item: Extracting content, applying bold style, appending bullet point symbol, and appending to resultBuilder
line.startsWith("* ") || line.startsWith("- ") -> {
val content = line.removePrefix("* ").removePrefix("- ").trim()
val currentStyle = SpanStyle(
fontWeight = FontWeight.Bold,
fontSize = 14.sp
)
resultBuilder.append(
AnnotatedString("• ", currentStyle)
)
textMarkDown(content, resultBuilder, fontSize = 14.sp)
}
// Ordered list item: Extracting content, applying bold style, appending number and period, and appending to resultBuilder
/*line.matches(lineNumberRegex) -> {
val startIndex = lineNumberRegex.find(line)?.range?.first ?: 0
val currentStyle = SpanStyle(
fontWeight = FontWeight.Bold,
fontSize = 14.sp
)
val annotatedString = buildAnnotatedString {
if (startIndex > 0) {
append(line.substring(0, startIndex))
}
withStyle(currentStyle) {
append(line.substring(startIndex, startIndex + 2))
}
}
resultBuilder.append(annotatedString)
textMarkDown(
inputText = line.substring(startIndex + 2, line.length),
resultBuilder = resultBuilder,
fontSize = 14.sp
)
}*/
// Remaining Text
else -> {
textMarkDown(line, resultBuilder, fontSize = 14.sp)
}
} // Appending new line
resultBuilder.append("\n")
}
return resultBuilder.toAnnotatedString().trim() as AnnotatedString
} catch (_: Throwable) {
// Just in case! We never want the UI to crash!
return AnnotatedString(text = markdownText)
}
}
/**
* Converts markdown-style text formatting to [AnnotatedString] with appropriate [SpanStyle]s.
*
* @param inputText The input text to be converted.
* @param resultBuilder The [AnnotatedString.Builder] to append the converted text to.
* @param fontSize The desired font size for the text.
* @return The converted text with Markdown formatting replaced by appropriate [SpanStyle]s.
*/
private fun textMarkDown(
inputText: String,
resultBuilder: AnnotatedString.Builder,
fontSize: TextUnit,
fontWeight: FontWeight = FontWeight.Normal
) {
var currentIndex = 0
while (currentIndex < inputText.length) {
val nextBoldItalic = boldItalicPattern.find(inputText, startIndex = currentIndex)
val nextBold = boldPattern.find(inputText, startIndex = currentIndex)
val nextItalic = italicPattern.find(inputText, startIndex = currentIndex)
val nextStrikethrough = strikethroughPattern.find(inputText, startIndex = currentIndex)
val nextLink = linkPattern.find(inputText, startIndex = currentIndex)
val nextMarkDown = listOfNotNull(
nextBoldItalic,
nextBold,
nextItalic,
nextStrikethrough,
nextLink
).minByOrNull { it.range.first }
if (nextMarkDown == null) {
// Append any remaining text if no more markdown found
val normalText = inputText.substring(currentIndex)
val style = SpanStyle(fontWeight = fontWeight, fontSize = fontSize)
resultBuilder.append(AnnotatedString(normalText, style))
break
}
if (nextMarkDown.range.first > currentIndex) {
// Append any normal text before the markdown
val normalText = inputText.substring(currentIndex, nextMarkDown.range.first)
val style = SpanStyle(fontWeight = fontWeight, fontSize = fontSize)
resultBuilder.append(AnnotatedString(normalText, style))
}
val matchText = nextMarkDown.groupValues.getOrNull(1) ?: ""
val style = when (nextMarkDown) {
nextBoldItalic -> SpanStyle(
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
fontSize = fontSize
)
nextBold -> SpanStyle(
fontWeight = FontWeight.Bold,
fontSize = fontSize
)
nextItalic -> SpanStyle(
fontStyle = FontStyle.Italic,
fontSize = fontSize
)
nextStrikethrough -> SpanStyle(
textDecoration = TextDecoration.LineThrough,
fontSize = fontSize
)
nextLink -> {
resultBuilder.append(buildAnnotatedString {
withLink(
LinkAnnotation.Url(
nextMarkDown.groupValues.getOrNull(2) ?: "",
)
) {
append(matchText)
}
})
currentIndex = nextMarkDown.range.last + 1
continue
}
else -> throw IllegalStateException("Unhandled markdown type")
}
resultBuilder.append(AnnotatedString(matchText, style))
currentIndex = nextMarkDown.range.last + 1
}
}

View file

@ -63,7 +63,7 @@ object BatteryOptimizationChecker {
return isRestricted && isOptimizedNotShown && isLayout(PHONE)
}
fun Context.showRequestIgnoreBatteryOptDialog() {
private fun Context.showRequestIgnoreBatteryOptDialog() {
try {
val intent = Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS

View file

@ -1,25 +1,12 @@
package com.lagradost.cloudstream3.utils
import com.lagradost.cloudstream3.AnimeLoadResponse
import com.lagradost.cloudstream3.LiveStreamLoadResponse
import com.lagradost.cloudstream3.MainAPI
import com.lagradost.cloudstream3.MainPageRequest
import com.lagradost.cloudstream3.MovieLoadResponse
import com.lagradost.cloudstream3.SearchResponse
import com.lagradost.cloudstream3.TvSeriesLoadResponse
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.mvvm.getStackTracePretty
import com.lagradost.cloudstream3.*
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream4.state.Log
import com.lagradost.cloudstream4.state.LogItem
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.*
import kotlin.random.Random
object TestingUtils {
open class TestResult(val success: Boolean) {
companion object {
val Pass = TestResult(true)
@ -27,37 +14,60 @@ object TestingUtils {
}
}
data class Logger(
var messageLog: PersistentList<LogItem> = persistentListOf<LogItem>()
) : Log {
override fun log(item: LogItem) {
messageLog = messageLog.adding(item)
class Logger {
enum class LogLevel {
Normal,
Warning,
Error;
}
data class Message(val level: LogLevel, val message: String) {
override fun toString(): String {
val level = when (this.level) {
LogLevel.Normal -> ""
LogLevel.Warning -> "Warning: "
LogLevel.Error -> "Error: "
}
return "$level$message"
}
}
private val messageLog = mutableListOf<Message>()
fun getRawLog(): List<Message> = messageLog
fun log(message: String) {
messageLog.add(Message(LogLevel.Normal, message))
}
fun warn(message: String) {
messageLog.add(Message(LogLevel.Warning, message))
}
fun error(message: String) {
messageLog.add(Message(LogLevel.Error, message))
}
}
private fun fail(message: String): Nothing = throw AssertionError(message)
private fun assertTrue(message: String, condition: Boolean) {
if (!condition) fail(message)
}
private fun assertNotNull(message: String, value: Any?) {
if (value == null) fail(message)
}
private fun assertTrue(message: String, condition: Boolean) { if (!condition) fail(message) }
private fun assertNotNull(message: String, value: Any?) { if (value == null) fail(message) }
class TestResultList(val results: List<SearchResponse>) : TestResult(true)
class TestResultLoad(val extractorData: String, val shouldLoadLinks: Boolean) : TestResult(true)
class TestResultProvider(
success: Boolean,
val log: List<Logger.Message>,
val exception: Throwable?
) :
TestResult(success)
@Throws(AssertionError::class, CancellationException::class)
suspend fun testHomepage(
api: MainAPI, logger: Log
api: MainAPI,
logger: Logger
): TestResult {
val tag = "Homepage"
if (api.hasMainPage) {
try {
val f = api.mainPage.first()
@ -65,18 +75,15 @@ object TestingUtils {
api.getMainPage(1, MainPageRequest(f.name, f.data, f.horizontalImages))
when {
homepage == null -> {
logger.e(tag, "Provider ${api.name} did not correctly load homepage!")
logger.error("Provider ${api.name} did not correctly load homepage!")
}
homepage.items.isEmpty() -> {
logger.w(tag, "Provider ${api.name} does not contain any homepage rows!")
logger.warn("Provider ${api.name} does not contain any homepage rows!")
}
homepage.items.any { it.list.isEmpty() } -> {
logger.w(
tag,
"Provider ${api.name} does not have any items in a homepage row!"
)
logger.warn("Provider ${api.name} does not have any items in a homepage row!")
}
}
val homePageList = homepage?.items?.flatMap { it.list } ?: emptyList()
@ -92,12 +99,7 @@ object TestingUtils {
}
else -> {
e.message?.let {
logger.w(
tag,
"Exception thrown when loading homepage: \"$it\""
)
}
e.message?.let { logger.warn("Exception thrown when loading homepage: \"$it\"") }
}
}
}
@ -109,11 +111,11 @@ object TestingUtils {
private suspend fun testSearch(
api: MainAPI,
testQueries: List<String>,
logger: Log,
logger: Logger,
): TestResult {
val searchResults = testQueries.firstNotNullOfOrNull { query ->
try {
logger.i("Search", "Searching for: $query")
logger.log("Searching for: $query")
api.search(query, 1)?.items?.takeIf { it.isNotEmpty() }
} catch (e: Throwable) {
if (e is NotImplementedError) {
@ -139,33 +141,26 @@ object TestingUtils {
private suspend fun testLoad(
api: MainAPI,
result: SearchResponse,
logger: Log
logger: Logger
): TestResult {
val tag = "load"
try {
if (result.apiName != api.name) {
logger.w(tag, "Wrong apiName on SearchResponse: ${api.name} != ${result.apiName}")
logger.warn("Wrong apiName on SearchResponse: ${api.name} != ${result.apiName}")
}
val loadResponse = api.load(result.url)
if (loadResponse == null) {
logger.e(tag, "Returned null loadResponse on ${result.url} on ${api.name}")
logger.error("Returned null loadResponse on ${result.url} on ${api.name}")
return TestResult.Fail
}
if (loadResponse.apiName != api.name) {
logger.w(
tag,
"Wrong apiName on LoadResponse: ${api.name} != ${loadResponse.apiName}"
)
logger.warn("Wrong apiName on LoadResponse: ${api.name} != ${loadResponse.apiName}")
}
if (!api.supportedTypes.contains(loadResponse.type)) {
logger.w(
tag,
"Api ${api.name} on load does not contain any of the supportedTypes: ${loadResponse.type}"
)
logger.warn("Api ${api.name} on load does not contain any of the supportedTypes: ${loadResponse.type}")
}
val url = when (loadResponse) {
@ -174,7 +169,7 @@ object TestingUtils {
loadResponse.episodes.keys.isEmpty() || loadResponse.episodes.keys.any { loadResponse.episodes[it].isNullOrEmpty() }
if (gotNoEpisodes) {
logger.e(tag, "Api ${api.name} got no episodes on ${loadResponse.url}")
logger.error("Api ${api.name} got no episodes on ${loadResponse.url}")
return TestResult.Fail
}
@ -184,7 +179,7 @@ object TestingUtils {
is MovieLoadResponse -> {
val gotNoEpisodes = loadResponse.dataUrl.isBlank()
if (gotNoEpisodes) {
logger.e(tag, "Api ${api.name} got no movie on ${loadResponse.url}")
logger.error("Api ${api.name} got no movie on ${loadResponse.url}")
return TestResult.Fail
}
@ -194,7 +189,7 @@ object TestingUtils {
is TvSeriesLoadResponse -> {
val gotNoEpisodes = loadResponse.episodes.isEmpty()
if (gotNoEpisodes) {
logger.e(tag, "Api ${api.name} got no episodes on ${loadResponse.url}")
logger.error("Api ${api.name} got no episodes on ${loadResponse.url}")
return TestResult.Fail
}
loadResponse.episodes.firstOrNull()?.data
@ -205,7 +200,7 @@ object TestingUtils {
}
else -> {
logger.e(tag, "Unknown load response: ${loadResponse::class.qualifiedName}")
logger.error("Unknown load response: ${loadResponse::class.qualifiedName}")
return TestResult.Fail
}
} ?: return TestResult.Fail
@ -235,16 +230,15 @@ object TestingUtils {
private suspend fun testLinkLoading(
api: MainAPI,
url: String?,
logger: Log
logger: Logger
): TestResult {
val tag = "Link"
assertNotNull("Api ${api.name} has invalid url on episode", url)
if (url == null) return TestResult.Fail // Should never trigger
var linksLoaded = 0
try {
val success = api.loadLinks(url, false, {}) { link ->
logger.i(tag, "Video loaded: ${link.name}")
logger.log("Video loaded: ${link.name}")
assertTrue(
"Api ${api.name} returns link with invalid url ${link.url}",
link.url.length > 4
@ -252,7 +246,7 @@ object TestingUtils {
linksLoaded++
}
if (success) {
logger.i(tag, "Links loaded: $linksLoaded")
logger.log("Links loaded: $linksLoaded")
return TestResult(linksLoaded > 0)
} else {
fail("Api ${api.name} returns false on loadLinks() with $linksLoaded links loaded")
@ -264,7 +258,7 @@ object TestingUtils {
}
else -> {
logger.e(tag, "Failed link loading on ${api.name} using data: $url")
logger.error("Failed link loading on ${api.name} using data: $url")
throw e
}
}
@ -275,68 +269,60 @@ object TestingUtils {
fun getDeferredProviderTests(
scope: CoroutineScope,
providers: Array<MainAPI>,
callback: (MainAPI, TestResultProvider, Logger) -> Unit,
callback: (MainAPI, TestResultProvider) -> Unit
) {
providers.forEach { api ->
scope.launch {
val logger = Logger()
val result = runSingleProviderTest(api, logger)
callback.invoke(api, result, logger)
}
}
}
suspend fun runSingleProviderTest(api: MainAPI, logger: Log): TestResultProvider {
val tag = "Test"
return try {
logger.i(tag, "Trying ${api.name}")
val result = try {
logger.log("Trying ${api.name}")
// Test Homepage
val homepage = testHomepage(api, logger)
assertTrue("Homepage failed to load", homepage.success)
val homePageList = (homepage as? TestResultList)?.results ?: emptyList()
// Test Homepage
val homepage = testHomepage(api, logger)
assertTrue("Homepage failed to load", homepage.success)
val homePageList = (homepage as? TestResultList)?.results ?: emptyList()
// Test Search Results
val searchQueries =
// Use the random 3 home page results as queries since they are guaranteed to exist
(homePageList.shuffled(Random).take(3).map { it.name.split(" ").first() } +
// If home page is sparse then use generic search queries
listOf("over", "iron", "guy")).take(3)
// Test Search Results
val searchQueries =
// Use the random 3 home page results as queries since they are guaranteed to exist
(homePageList.shuffled(Random).take(3).map { it.name.split(" ").first() } +
// If home page is sparse then use generic search queries
listOf("over", "iron", "guy")).take(3)
val searchResults = testSearch(api, searchQueries, logger)
assertTrue("Failed to get search results", searchResults.success)
searchResults as TestResultList
val searchResults = testSearch(api, searchQueries, logger)
assertTrue("Failed to get search results", searchResults.success)
searchResults as TestResultList
// Test Load and LoadLinks
// Only try the first 3 search results to prevent spamming
val success = searchResults.results.take(3).any { searchResponse ->
logger.i("Search", "Testing search result: ${searchResponse.url}")
val loadResponse = testLoad(api, searchResponse, logger)
if (loadResponse !is TestResultLoad) {
false
} else {
if (loadResponse.shouldLoadLinks) {
testLinkLoading(api, loadResponse.extractorData, logger).success
} else {
logger.i(tag, "Skipping link loading test")
true
// Test Load and LoadLinks
// Only try the first 3 search results to prevent spamming
val success = searchResults.results.take(3).any { searchResponse ->
logger.log("Testing search result: ${searchResponse.url}")
val loadResponse = testLoad(api, searchResponse, logger)
if (loadResponse !is TestResultLoad) {
false
} else {
if (loadResponse.shouldLoadLinks) {
testLinkLoading(api, loadResponse.extractorData, logger).success
} else {
logger.log("Skipping link loading test")
true
}
}
}
}
}
if (success) {
logger.i(tag, "Success ${api.name}")
TestResultProvider(true, null)
} else {
logger.e(tag, "Link loading failed")
TestResultProvider(false, null)
if (success) {
logger.log("Success ${api.name}")
TestResultProvider(true, logger.getRawLog(), null)
} else {
logger.error("Link loading failed")
TestResultProvider(false, logger.getRawLog(), null)
}
} catch (e: Throwable) {
TestResultProvider(false, logger.getRawLog(), e)
}
callback.invoke(api, result)
}
} catch (e : CancellationException) {
logger.e(tag, "Testing of ${api.name} was cancelled")
TestResultProvider(false, e)
} catch (e: Throwable) {
logger.e(tag, e.getStackTracePretty().trim())
TestResultProvider(false, e)
}
}
}

View file

@ -23,15 +23,15 @@ const val PROGRAM_ID_LIST_KEY = "persistent_program_ids"
object TvChannelUtils {
fun Context.saveProgramId(programId: Long) {
val existing: List<Long> = getKey<List<Long>>(PROGRAM_ID_LIST_KEY) ?: emptyList()
val existing: List<Long> = getKey(PROGRAM_ID_LIST_KEY) ?: emptyList()
val updated = (existing + programId).distinct()
setKey(PROGRAM_ID_LIST_KEY, updated)
}
fun Context.getStoredProgramIds(): List<Long> {
return getKey<List<Long>>(PROGRAM_ID_LIST_KEY) ?: emptyList()
return getKey(PROGRAM_ID_LIST_KEY) ?: emptyList()
}
fun Context.removeProgramId(programId: Long) {
val existing: List<Long> = getKey<List<Long>>(PROGRAM_ID_LIST_KEY) ?: emptyList()
val existing: List<Long> = getKey(PROGRAM_ID_LIST_KEY) ?: emptyList()
val updated = existing.filter { it != programId }
setKey(PROGRAM_ID_LIST_KEY, updated)
}
@ -149,12 +149,10 @@ object TvChannelUtils {
.setInputId(inputId)
.build()
val channelUri = runCatching {
context.contentResolver.insert(
TvContractCompat.Channels.CONTENT_URI,
channel.toContentValues()
)
}.getOrNull()
val channelUri = context.contentResolver.insert(
TvContractCompat.Channels.CONTENT_URI,
channel.toContentValues()
)
channelUri?.let {
val channelId = ContentUris.parseId(it)
@ -163,4 +161,4 @@ object TvChannelUtils {
}
}
}
}

View file

@ -1640,11 +1640,11 @@ object VideoDownloadManager {
}
fun getDownloadResumePackage(context: Context, id: Int): DownloadResumePackage? {
return context.getKey<DownloadResumePackage>(KEY_RESUME_PACKAGES, id.toString())
return context.getKey(KEY_RESUME_PACKAGES, id.toString())
}
fun getDownloadQueuePackage(context: Context, id: Int): DownloadQueueWrapper? {
return context.getKey<DownloadQueueWrapper>(KEY_RESUME_IN_QUEUE, id.toString())
return context.getKey(KEY_RESUME_IN_QUEUE, id.toString())
}
fun getDownloadEpisodeMetadata(

Some files were not shown because too many files have changed in this diff Show more