package eu.friedcutlet.yokan.ui.navigation import kotlinx.coroutines.CoroutineDispatcher import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbRepo import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.notifications.InAppNotifications import eu.friedcutlet.yokan.ui.screens.together.TogetherSession import eu.friedcutlet.yokan.util.nowMillis import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.getAndUpdate import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonPrimitive import io.ktor.http.URLDecodeException import io.ktor.http.encodeURLParameter import io.ktor.http.parseQueryString import io.ktor.util.toMap internal data class DeepLinkState( val action: PendingDeepLinkAction? = null, val busy: Boolean = false, val error: String? = null, ) /** Handles app links: action links become a confirmation dialog, backup files open the restore preview, route links navigate. */ internal class DeepLinkViewModel( private val repository: YokanRepository, private val database: YokanDatabase, private val http: HttpService, private val navigator: Navigator, private val injectedScope: CoroutineScope? = null, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val scope: CoroutineScope get() = injectedScope ?: viewModelScope private val _state = MutableStateFlow(DeepLinkState()) val state: StateFlow = _state.asStateFlow() fun open(link: String?) { if (link.isNullOrBlank()) return parseDeepLinkAction(link)?.let { action -> _state.update { it.copy(action = action, error = null) } return } if (isBackupFileLink(link)) { PendingBackupFile.offer(link) navigator.navigate(Route.Settings(SettingsPage.DataAndStorage)) return } val path = link.substringBefore("?").substringBefore("#") val name = path .let { raw -> when { raw.startsWith("yokan://") -> raw.removePrefix("yokan://") raw.startsWith("/") -> raw else -> raw.substringAfterLast("/") } } .trim('/') .substringBefore("/") if (name == "room") { val code = path.removePrefix("yokan://").trim('/').split('/').getOrNull(1) if (!code.isNullOrBlank()) TogetherSession.offerCode(code.uppercase()) } when (name) { "search" -> { val parameters = parseQueryParameters(link) val query = parameters["q"]?.firstOrNull()?.trim().orEmpty() val type = parameters["type"]?.firstOrNull()?.let { raw -> ItemType.entries.firstOrNull { it.name.equals(raw, ignoreCase = true) } } if (query.isNotEmpty()) navigator.navigate(Route.GlobalSearch(type ?: navigator.itemType.value, query)) } "Home", "home" -> navigator.select(NavSection.Home) "MangaLibrary", "manga", "" -> navigator.select(NavSection.MangaLibrary) "AnimeLibrary", "anime" -> navigator.select(NavSection.AnimeLibrary) "NovelLibrary", "novel" -> navigator.select(NavSection.NovelLibrary) "updates" -> navigator.select(NavSection.Updates) "history" -> navigator.select(NavSection.History) "browse" -> navigator.select(NavSection.Browse) "trackerLibrary", "tracking" -> navigator.select(NavSection.TrackerLibrary) "more" -> navigator.select(NavSection.More) else -> legacyRoute(name, navigator.itemType.value)?.let(navigator::navigate) } } fun dismiss() { if (_state.value.busy) return _state.update { it.copy(action = (it.action as? PendingDeepLinkAction.AddCustomButtons)?.remaining(), error = null) } } fun confirm() { val current = _state.value if (current.busy) return when (val action = current.action) { is PendingDeepLinkAction.AddCustomButtons -> { val button = action.buttons.firstOrNull() ?: return database.upsertCustomButton( DbCustomButton( title = button.title, codePress = button.codePress, codeLongPress = button.codeLongPress, codeStartup = button.codeStartup, isFavourite = false, position = database.customButtons().size, updatedAt = nowMillis(), ), ) _state.update { it.copy(action = action.remaining(), error = null) } InAppNotifications.post("Custom button added") } is PendingDeepLinkAction.AddRepositories -> { _state.update { it.copy(busy = true, error = null) } scope.launch { val valid = action.repositories.all { payload -> catchingNonCancellation { val response = http.request(HttpRequest(payload.url)) response.statusCode in 200..299 && withContext(workDispatcher) { repositoryPayloadIsValid(response.body) } }.getOrDefault(false) } when { _state.value.action != action -> _state.update { it.copy(busy = false) } !valid -> _state.update { it.copy(busy = false, error = "Unsupported repository") } else -> { action.repositories.forEach { payload -> repository.upsertRepository( payload.itemType, DbRepo(name = action.name, website = action.website, jsonUrl = payload.url), ) } _state.update { it.copy(action = null, busy = false) } InAppNotifications.post("Repository added") } } } } null -> Unit } } } private fun PendingDeepLinkAction.AddCustomButtons.remaining(): PendingDeepLinkAction.AddCustomButtons? = buttons.drop(1).takeIf(List::isNotEmpty)?.let { PendingDeepLinkAction.AddCustomButtons(it) } /** Maps a legacy `yokan://` route; routes that need arguments (a title, a source) resolve to null. */ internal fun legacyRoute(name: String, itemType: ItemType): Route? = when (name) { "updateErrors" -> Route.UpdateErrors "localLibraryOverview" -> Route.LocalLibraryOverview "globalSearch" -> Route.GlobalSearch(itemType) "ExtensionLang" -> Route.ExtensionLanguages(itemType) "sourceFilter" -> Route.SourceFilters(itemType) "createExtension" -> Route.CreateExtension(itemType) "massMigration" -> Route.MassMigration(itemType) "localLibraryBrowse" -> Route.LocalLibraryBrowse(itemType) "add-repo" -> Route.Settings(SettingsPage.Repositories) "add-button" -> Route.Settings(SettingsPage.CustomButtons) "success" -> Route.Settings(SettingsPage.TrackingDetail) "room" -> Route.Settings(SettingsPage.Together) else -> SettingsPage.entries.firstOrNull { it.legacyRoute == name }?.let { Route.Settings(it) } } internal sealed interface PendingDeepLinkAction { data class AddRepositories( val name: String?, val website: String?, val repositories: List, ) : PendingDeepLinkAction data class AddCustomButtons( val buttons: List, ) : PendingDeepLinkAction } internal data class RepositoryPayload( val itemType: ItemType, val url: String, ) internal data class CustomButtonPayload( val title: String?, val codePress: String?, val codeLongPress: String, val codeStartup: String, ) /** Global-search link built by OS intake (shared text, system search, launch arguments, `?search=`). */ internal fun searchDeepLink(query: String, type: ItemType? = null): String = "yokan://search?q=${query.encodeURLParameter()}" + type?.let { "&type=${it.name.lowercase()}" }.orEmpty() /** Links that reach the app as a document: Android VIEW (`content://`, `file://`), iOS open-in, desktop file arguments. */ internal fun isBackupFileLink(link: String): Boolean = link.startsWith("content://") || link.startsWith("file:") /** Backup file handed in by the OS, consumed once by the Data and storage page. */ internal object PendingBackupFile { private val pending = MutableStateFlow(null) val value: StateFlow = pending.asStateFlow() fun offer(path: String) { pending.value = path } fun take(): String? = pending.getAndUpdate { null } } /** Mihon/Tachiyomi publish manga repositories; Aniyomi/Animetail publish anime repositories. */ private fun foreignRepositoryType(scheme: String): ItemType? = when (scheme) { "tachiyomi", "mihon" -> ItemType.Manga "aniyomi", "animetail" -> ItemType.Anime else -> null } @OptIn(ExperimentalEncodingApi::class) internal fun parseDeepLinkAction(link: String): PendingDeepLinkAction? { val parameters = parseQueryParameters(link) foreignRepositoryType(link.substringBefore("://", "").lowercase())?.let { itemType -> val host = link.substringAfter("://").substringBefore('?').substringBefore('#').trim('/').substringBefore('/') if (host != "add-repo" && host != "extension-store") return null val urls = parameters["url"].orEmpty().filter(String::isNotBlank) if (urls.isEmpty()) return null return PendingDeepLinkAction.AddRepositories(null, null, urls.map { RepositoryPayload(itemType, it) }) } val route = link .substringBefore('?') .substringBefore('#') .removePrefix("yokan://") .trim('/') .substringBefore('/') return when (route) { "add-repo" -> PendingDeepLinkAction.AddRepositories( name = parameters["repo_name"]?.firstOrNull(), website = parameters["repo_url"]?.firstOrNull(), repositories = buildList { parameters["manga_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Manga, it)) } parameters["anime_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Anime, it)) } parameters["novel_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Novel, it)) } }, ) "add-button" -> parameters["button"] .orEmpty() .mapNotNull(::decodeCustomButton) .takeIf(List::isNotEmpty) ?.let { PendingDeepLinkAction.AddCustomButtons(it) } else -> null } } internal fun repositoryPayloadIsValid(body: String): Boolean = runCatching { val first = Json.parseToJsonElement(body) .let { it as? kotlinx.serialization.json.JsonArray } ?.firstOrNull() as? JsonObject val name = first?.get("name")?.jsonPrimitive?.contentOrNull !name.isNullOrBlank() }.getOrDefault(false) /** Query parameters of [link]; a malformed `%` escape rejects the whole query instead of half-decoding it. */ internal fun parseQueryParameters(link: String): Map> { val query = link.substringAfter('?', missingDelimiterValue = "").substringBefore('#') if (query.isBlank()) return emptyMap() return try { parseQueryString(query).toMap() } catch (_: URLDecodeException) { emptyMap() } } @OptIn(ExperimentalEncodingApi::class) private fun decodeCustomButton(encoded: String): CustomButtonPayload? = runCatching { val value = Json.parseToJsonElement(Base64.decode(encoded).decodeToString()) as? JsonObject ?: return@runCatching null CustomButtonPayload( title = value.string("title"), codePress = value.string("codePress"), codeLongPress = value.string("codeLongPress").orEmpty(), codeStartup = value.string("codeStartup").orEmpty(), ) }.getOrNull() private fun JsonObject.string(key: String): String? = get(key)?.jsonPrimitive?.contentOrNull