11package app.revanced.manager.ui.viewmodel
22
33import android.app.Application
4+ import android.net.Uri
5+ import android.util.Log
46import androidx.lifecycle.ViewModel
57import androidx.lifecycle.viewModelScope
68import app.revanced.manager.R
9+ import app.revanced.manager.domain.bundles.RemotePatchBundle
710import app.revanced.manager.domain.manager.PreferencesManager
811import app.revanced.manager.domain.repository.PatchBundleRepository
9- import app.revanced.manager.domain.bundles.RemotePatchBundle
12+ import app.revanced.manager.util.tag
13+ import app.revanced.manager.util.toast
1014import app.revanced.manager.util.uiSafe
15+ import com.github.pgreze.process.Redirect
16+ import com.github.pgreze.process.process
17+ import kotlinx.coroutines.CancellationException
1118import kotlinx.coroutines.Dispatchers
19+ import kotlinx.coroutines.flow.collect
20+ import kotlinx.coroutines.flow.flowOn
21+ import kotlinx.coroutines.flow.onEach
1222import kotlinx.coroutines.launch
23+ import kotlinx.coroutines.withContext
24+ import java.time.LocalDateTime
25+ import java.time.format.DateTimeFormatter
1326
1427class AdvancedSettingsViewModel (
1528 val prefs : PreferencesManager ,
1629 private val app : Application ,
1730 private val patchBundleRepository : PatchBundleRepository
1831) : ViewModel() {
32+ val debugLogFileName: String
33+ get() {
34+ val time = DateTimeFormatter .ISO_LOCAL_DATE_TIME .format(LocalDateTime .now())
35+
36+ return " revanced-manager_logcat_$time "
37+ }
38+
1939 fun setApiUrl (value : String ) = viewModelScope.launch(Dispatchers .Default ) {
2040 if (value == prefs.api.get()) return @launch
2141
@@ -32,4 +52,31 @@ class AdvancedSettingsViewModel(
3252 fun resetBundles () = viewModelScope.launch {
3353 patchBundleRepository.reset()
3454 }
55+
56+ fun exportDebugLogs (target : Uri ) = viewModelScope.launch {
57+ val exitCode = try {
58+ withContext(Dispatchers .IO ) {
59+ app.contentResolver.openOutputStream(target)!! .bufferedWriter().use { writer ->
60+ val consumer = Redirect .Consume { flow ->
61+ flow.onEach {
62+ writer.write(it)
63+ }.flowOn(Dispatchers .IO ).collect()
64+ }
65+
66+ process(" logcat" , " -d" , stdout = consumer).resultCode
67+ }
68+ }
69+ } catch (e: CancellationException ) {
70+ throw e
71+ } catch (e: Exception ) {
72+ Log .e(tag, " Got exception while exporting logs" , e)
73+ app.toast(app.getString(R .string.debug_logs_export_failed))
74+ return @launch
75+ }
76+
77+ if (exitCode == 0 )
78+ app.toast(app.getString(R .string.debug_logs_export_success))
79+ else
80+ app.toast(app.getString(R .string.debug_logs_export_read_failed, exitCode))
81+ }
3582}
0 commit comments