summaryrefslogtreecommitdiff
path: root/app/src/main/java/org/terst/feedreader/ui/AddFeedScreen.kt
blob: 1e8814cff5ce50ede3429afaf00f54b8e0c43f85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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.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

@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<String?>(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

private suspend fun addFeedByUrl(context: android.content.Context, db: AppDatabase, feedUrl: String): String =
    withContext(Dispatchers.IO) {
        val url = preferHttps(feedUrl)
        try {
            val response = Net.client.newCall(Request.Builder().url(url).build()).execute()
            response.use {
                if (!it.isSuccessful) return@withContext "Couldn't fetch feed: HTTP ${it.code}"
                val body = it.body ?: return@withContext "Empty response"
                val parsed = FeedParser.parse(body.byteStream())
                // 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)
            "Added"
        } catch (e: Exception) {
            "Couldn't add feed: ${e.message}"
        }
    }