78 lines
2.6 KiB
Kotlin
78 lines
2.6 KiB
Kotlin
package net.bluemangoo.indpjsk.ui
|
|
|
|
import android.content.Context
|
|
import android.content.Intent
|
|
import androidx.lifecycle.ViewModel
|
|
import androidx.lifecycle.viewModelScope
|
|
import net.bluemangoo.indpjsk.data.CaptureProfile
|
|
import net.bluemangoo.indpjsk.data.MixinProfiles
|
|
import net.bluemangoo.indpjsk.data.PredefinedProfiles
|
|
import net.bluemangoo.indpjsk.data.SettingsStore
|
|
import net.bluemangoo.indpjsk.state.CaptureStateHolder
|
|
import net.bluemangoo.indpjsk.state.CaptureStatus
|
|
import net.bluemangoo.indpjsk.upload.UploadStore
|
|
import net.bluemangoo.indpjsk.vpn.CaptureVpnService
|
|
import net.bluemangoo.indpjsk.vpn.VpnLog
|
|
import kotlinx.coroutines.flow.SharingStarted
|
|
import kotlinx.coroutines.flow.StateFlow
|
|
import kotlinx.coroutines.flow.combine
|
|
import kotlinx.coroutines.flow.stateIn
|
|
import java.io.File
|
|
|
|
data class CaptureUiState(
|
|
val profiles: List<CaptureProfile> = emptyList(),
|
|
val selectedProfile: CaptureProfile? = null,
|
|
val status: CaptureStatus = CaptureStatus.IDLE,
|
|
val lastCapturedFile: File? = null,
|
|
val errorMessage: String? = null
|
|
)
|
|
|
|
class CaptureViewModel : ViewModel() {
|
|
|
|
private fun allProfiles(): List<CaptureProfile> = MixinProfiles.merged()
|
|
|
|
val uiState: StateFlow<CaptureUiState> = combine(
|
|
CaptureStateHolder.state,
|
|
UploadStore.revision,
|
|
) { s, _ ->
|
|
val profiles = allProfiles()
|
|
CaptureUiState(
|
|
profiles = profiles,
|
|
selectedProfile = profiles.firstOrNull { it.id == s.profile.id } ?: s.profile,
|
|
status = s.status,
|
|
lastCapturedFile = s.lastCapturedFile,
|
|
errorMessage = s.errorMessage
|
|
)
|
|
}.stateIn(
|
|
scope = viewModelScope,
|
|
started = SharingStarted.WhileSubscribed(5_000),
|
|
initialValue = CaptureUiState(
|
|
profiles = allProfiles(),
|
|
selectedProfile = PredefinedProfiles.all.firstOrNull()
|
|
)
|
|
)
|
|
|
|
fun selectProfile(profile: CaptureProfile) {
|
|
CaptureStateHolder.selectProfile(profile)
|
|
SettingsStore.selectedProfileId = profile.id
|
|
}
|
|
|
|
fun startCapture(context: Context) {
|
|
val profile = uiState.value.selectedProfile ?: return
|
|
VpnLog.clear()
|
|
CaptureStateHolder.setRunning()
|
|
|
|
val intent = Intent(context, CaptureVpnService::class.java).apply {
|
|
action = CaptureVpnService.ACTION_START
|
|
putExtra(CaptureVpnService.EXTRA_PROFILE_ID, profile.id)
|
|
}
|
|
context.startService(intent)
|
|
}
|
|
|
|
fun stopCapture(context: Context) {
|
|
val intent = Intent(context, CaptureVpnService::class.java).apply {
|
|
action = CaptureVpnService.ACTION_STOP
|
|
}
|
|
context.startService(intent)
|
|
}
|
|
} |