package org.terst.feedreader.ui import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts 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.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable 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.platform.LocalContext import androidx.compose.ui.unit.dp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.Request import org.terst.feedreader.data.AppDatabase import org.terst.feedreader.data.FeedDiscovery import org.terst.feedreader.data.FeedEntity import org.terst.feedreader.data.FeedParser import org.terst.feedreader.data.Net import org.terst.feedreader.opml.Opml import org.terst.feedreader.work.FeedFetchWorker import java.io.ByteArrayInputStream @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddFeedScreen(onDone: () -> Unit) { val context = LocalContext.current val db = remember { AppDatabase.get(context) } val scope = rememberCoroutineScope() var url by remember { mutableStateOf("") } var status by remember { mutableStateOf(null) } var isBusy by remember { mutableStateOf(false) } val importLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> if (uri == null) return@rememberLauncherForActivityResult isBusy = true scope.launch { try { val imported = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { stream -> Opml.parse(stream) } ?: emptyList() } // A feed cross-listed under multiple OPML category folders (common when // exported from a reader with folders/labels) appears once per folder here -- // dedupe by feed URL before reporting a count, or "108 feeds" would be reported // as some larger number even though upsert already collapses them to one row each. val uniqueFeeds = imported.map { it.copy(xmlUrl = preferHttps(it.xmlUrl)) }.distinctBy { it.xmlUrl } withContext(Dispatchers.IO) { // Loaded once, not one getById() per feed: upsert() REPLACEs the whole // row, and for a feed that's already subscribed, building a bare // FeedEntity here would silently wipe readerModeDisabled (and // etag/lastModified/lastError) back to defaults on every re-import -- // preserve the existing row's other fields, only title/siteUrl come // from OPML. val existingById = db.feedDao().getAll().associateBy { it.id } val entities = uniqueFeeds.map { feed -> val existing = existingById[feed.xmlUrl] existing?.copy( title = feed.title, siteUrl = feed.htmlUrl ?: existing.siteUrl, folder = feed.folder ?: existing.folder ) ?: FeedEntity(id = feed.xmlUrl, title = feed.title, siteUrl = feed.htmlUrl, folder = feed.folder) } db.feedDao().upsertAll(entities) } FeedFetchWorker.fetchNow(context) status = "Imported ${uniqueFeeds.size} feed(s)" } catch (e: Exception) { // A non-XML or corrupt/truncated file throws from Opml.parse -- without this, // that crashed the whole app instead of just failing this one import. status = "Couldn't import: ${e.message}" } finally { isBusy = false } } } val exportLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/x-opml")) { uri -> if (uri == null) return@rememberLauncherForActivityResult scope.launch { withContext(Dispatchers.IO) { val feeds = db.feedDao().getAll() context.contentResolver.openOutputStream(uri)?.use { out -> Opml.write(feeds, out) } } status = "Exported subscriptions" } } Scaffold( topBar = { TopAppBar( title = { Text("Add Feed") }, navigationIcon = { IconButton(onClick = onDone) { Icon(Icons.Default.ArrowBack, contentDescription = "Back") } } ) } ) { padding -> LazyColumn(modifier = Modifier.fillMaxWidth().padding(padding)) { item { Column(modifier = Modifier.padding(16.dp)) { OutlinedTextField( value = url, onValueChange = { url = it }, label = { Text("Feed URL") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(4.dp)) Button( enabled = url.isNotBlank() && !isBusy, onClick = { isBusy = true val feedUrl = url.trim() scope.launch { status = addFeedByUrl(context, db, feedUrl) if (status?.startsWith("Added") == true) url = "" isBusy = false } }, modifier = Modifier.fillMaxWidth() ) { Text("Add") } Spacer(modifier = Modifier.height(8.dp)) OutlinedButton(onClick = { importLauncher.launch("*/*") }, modifier = Modifier.fillMaxWidth()) { Text("Import OPML") } Spacer(modifier = Modifier.height(4.dp)) OutlinedButton(onClick = { exportLauncher.launch("subscriptions.opml") }, modifier = Modifier.fillMaxWidth()) { Text("Export OPML") } status?.let { Spacer(modifier = Modifier.height(8.dp)) Text(it) } } } } } } // Feeds get added as https:// even if the user (or an OPML export) gave an http:// URL -- // Android blocks cleartext by default (targetSdk 28+), so an http feed would just fail every // fetch forever. Most sites serve identical content either way; this is a plain scheme swap. // If a site genuinely doesn't support https, the very next fetch attempt fails immediately and // shows up the normal way (the feed list's "Last fetch failed" section) rather than silently // adding a feed that looks fine until you notice it never updates. private fun preferHttps(url: String): String = if (url.startsWith("http://", ignoreCase = true)) "https://" + url.removePrefix("http://") else url /** * Fetches [url] and returns its bytes, or null when the server refused. * * Read into memory rather than parsed from the live stream because the bytes may need looking * at twice: once as a feed, and -- when that is not what the URL turned out to be -- again as a * web page advertising where its feed actually lives. A response body is a one-shot stream, so * the second look is only possible if the first did not consume it. */ private class Fetched(val bytes: ByteArray?, val error: String?) private fun fetchBytes(url: String): Fetched = Net.client.newCall(Request.Builder().url(url).build()).execute().use { response -> when { !response.isSuccessful -> Fetched(null, "Couldn't fetch feed: HTTP ${response.code}") else -> response.body?.let { Fetched(it.bytes(), null) } ?: Fetched(null, "Empty response") } } private suspend fun addFeedByUrl(context: android.content.Context, db: AppDatabase, feedUrl: String): String = withContext(Dispatchers.IO) { val typedUrl = preferHttps(feedUrl) try { val fetched = fetchBytes(typedUrl) val bytes = fetched.bytes ?: return@withContext fetched.error ?: "Empty response" // What the user had to hand is usually the site, not the feed -- a site advertises // its feed in its head, it does not print the URL anywhere a reader can copy. So a // failed parse is not the answer yet: look for what the page says its feed is and // try that, once. See FeedDiscovery. var url = typedUrl var parsed = runCatching { FeedParser.parse(ByteArrayInputStream(bytes)) }.getOrNull() if (parsed == null) { val discovered = FeedDiscovery.findFeedUrl(String(bytes, Charsets.UTF_8), typedUrl) ?: return@withContext "No feed found at that address" val feed = fetchBytes(discovered) val feedBytes = feed.bytes ?: return@withContext feed.error ?: "Empty response" // One hop only: whatever the page pointed at has to be a feed. Following a // second page would be a redirect chain nobody asked for. parsed = FeedParser.parse(ByteArrayInputStream(feedBytes)) url = discovered } // Same REPLACE-wipes-other-fields concern as the OPML import path. val existing = db.feedDao().getById(url) val entity = existing?.copy( title = parsed.title.ifBlank { url }, siteUrl = parsed.siteUrl ?: existing.siteUrl ) ?: FeedEntity(id = url, title = parsed.title.ifBlank { url }, siteUrl = parsed.siteUrl) db.feedDao().upsert(entity) FeedFetchWorker.fetchNow(context) // Says which feed was added when it is not the URL that was typed, so a site URL // quietly becoming a different feed URL is visible rather than surprising later. if (url == typedUrl) "Added" else "Added ${parsed.title.ifBlank { url }}" } catch (e: Exception) { "Couldn't add feed: ${e.message}" } }