mirror of
https://github.com/atsunatsu/Look4Sat.git
synced 2026-10-09 05:47:28 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2e9454ee4 | ||
|
|
ea3e04d5db | ||
|
|
68e1925784 |
No files matched your search
@@ -33,53 +33,38 @@ import java.util.TimeZone
|
||||
|
||||
internal data class LoTWKeyMaterial(val key: PrivateKey, val certificate: X509Certificate, val info: LoTWCertificate) {
|
||||
companion object {
|
||||
fun read(bytes: ByteArray, password: CharArray, now: Long): LoTWKeyMaterial {
|
||||
/**
|
||||
* Reads the private key and certificate out of a TrustedQSL .p12 backup.
|
||||
*
|
||||
* The platform PKCS12 parser is tried first because it resolves the certificate that
|
||||
* belongs to the key entry. When it cannot deliver a usable pair — it may refuse the file
|
||||
* outright (older Android cannot read PBES2 at all) or accept the container yet expose no
|
||||
* key entry (Conscrypt/OpenSSL reads PBES2 but fails to recover the key of, for example,
|
||||
* an empty-password backup) — our own PBES2 reader is consulted before reporting a problem,
|
||||
* so a valid certificate is not rejected as "not a valid LoTW certificate file".
|
||||
*
|
||||
* [platformStore] is a seam that lets tests simulate a platform which accepts the file
|
||||
* without exposing any key entry.
|
||||
*/
|
||||
internal fun read(
|
||||
bytes: ByteArray,
|
||||
password: CharArray,
|
||||
now: Long,
|
||||
platformStore: (ByteArray, CharArray) -> KeyStore? = { data, pass -> loadPlatformStore(data, pass) },
|
||||
): LoTWKeyMaterial {
|
||||
if (bytes.isEmpty() || bytes.size > MAX_CERTIFICATE_BYTES) fail(LoTWProblem.CERTIFICATE_INVALID)
|
||||
val key: PrivateKey
|
||||
val cert: X509Certificate
|
||||
val store = try {
|
||||
KeyStore.getInstance("PKCS12").apply { bytes.inputStream().use { load(it, password) } }
|
||||
} catch (_: Exception) {
|
||||
// Modern TQSL / OpenSSL 3 exports use PBES2+AES-CBC which Android's legacy
|
||||
// Bouncy Castle parser cannot read. Fall back to our own PBES2 reader; if
|
||||
// that fails too, report the real reason (format vs password).
|
||||
if (isPbes2(bytes)) {
|
||||
try {
|
||||
val parsed = Pkcs12Reader.read(bytes, password)
|
||||
parsed.first to parsed.second
|
||||
} catch (e: Exception) {
|
||||
// Classify by exception type so the user sees the right message:
|
||||
// - BadPadding (BAD_DECRYPT) -> wrong password
|
||||
// - IllegalStateException (error()) -> unsupported algorithm,
|
||||
// message is the algorithm name
|
||||
// - IllegalArgumentException (require()) -> structurally invalid file
|
||||
fail(
|
||||
when {
|
||||
e is javax.crypto.BadPaddingException -> LoTWProblem.CERTIFICATE_PASSWORD
|
||||
e is IllegalStateException && password.isNotEmpty() -> LoTWProblem.CERTIFICATE_FORMAT
|
||||
else -> LoTWProblem.CERTIFICATE_INVALID
|
||||
},
|
||||
if (e is IllegalStateException) (e.message ?: "") else ""
|
||||
)
|
||||
}
|
||||
} else {
|
||||
fail(LoTWProblem.CERTIFICATE_PASSWORD)
|
||||
}
|
||||
}
|
||||
if (store is Pair<*, *>) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
key = store.first as PrivateKey
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
cert = store.second as X509Certificate
|
||||
val outcome = platformStore(bytes, password)?.let { platformKeyAndCertificate(it, password) }
|
||||
if (outcome is PlatformOutcome.Ok) {
|
||||
key = outcome.key
|
||||
cert = outcome.certificate
|
||||
} else if (isPbes2(bytes)) {
|
||||
val parsed = readWithPbes2Reader(bytes, password)
|
||||
key = parsed.first
|
||||
cert = parsed.second
|
||||
} else {
|
||||
val ks = store as KeyStore
|
||||
val aliases = Collections.list(ks.aliases()).filter { ks.isKeyEntry(it) }
|
||||
if (aliases.size != 1) fail(LoTWProblem.CERTIFICATE_INVALID)
|
||||
val alias = aliases.single()
|
||||
key = try { ks.getKey(alias, password) as? PrivateKey }
|
||||
catch (_: Exception) { fail(LoTWProblem.CERTIFICATE_PASSWORD) }
|
||||
?: fail(LoTWProblem.CERTIFICATE_INVALID)
|
||||
cert = ks.getCertificate(alias) as? X509Certificate ?: fail(LoTWProblem.CERTIFICATE_INVALID)
|
||||
fail((outcome as? PlatformOutcome.Unusable)?.problem ?: LoTWProblem.CERTIFICATE_PASSWORD)
|
||||
}
|
||||
if (key.algorithm != "RSA" || cert.publicKey.algorithm != "RSA") fail(LoTWProblem.CERTIFICATE_INVALID)
|
||||
try { cert.checkValidity(Date(now)) } catch (_: Exception) { fail(LoTWProblem.CERTIFICATE_EXPIRED) }
|
||||
@@ -92,6 +77,54 @@ internal data class LoTWKeyMaterial(val key: PrivateKey, val certificate: X509Ce
|
||||
return LoTWKeyMaterial(key, cert, info)
|
||||
}
|
||||
|
||||
/** What the platform PKCS12 parser managed to deliver for the key entry. */
|
||||
private sealed interface PlatformOutcome {
|
||||
data class Ok(val key: PrivateKey, val certificate: X509Certificate) : PlatformOutcome
|
||||
|
||||
/** The problem the platform path would have reported on its own. */
|
||||
data class Unusable(val problem: LoTWProblem) : PlatformOutcome
|
||||
}
|
||||
|
||||
/** The platform PKCS12 keystore, or null when it refuses to read the file at all. */
|
||||
private fun loadPlatformStore(bytes: ByteArray, password: CharArray): KeyStore? = try {
|
||||
KeyStore.getInstance("PKCS12").apply { bytes.inputStream().use { load(it, password) } }
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
/** Resolves the single key entry the platform offers, keeping its own failure reasons. */
|
||||
private fun platformKeyAndCertificate(store: KeyStore, password: CharArray): PlatformOutcome {
|
||||
val aliases = Collections.list(store.aliases()).filter { store.isKeyEntry(it) }
|
||||
val alias = aliases.singleOrNull() ?: return PlatformOutcome.Unusable(LoTWProblem.CERTIFICATE_INVALID)
|
||||
val key = try {
|
||||
store.getKey(alias, password) as? PrivateKey
|
||||
} catch (_: Exception) {
|
||||
return PlatformOutcome.Unusable(LoTWProblem.CERTIFICATE_PASSWORD)
|
||||
} ?: return PlatformOutcome.Unusable(LoTWProblem.CERTIFICATE_INVALID)
|
||||
val certificate = store.getCertificate(alias) as? X509Certificate
|
||||
?: return PlatformOutcome.Unusable(LoTWProblem.CERTIFICATE_INVALID)
|
||||
return PlatformOutcome.Ok(key, certificate)
|
||||
}
|
||||
|
||||
/** Our own PBES2 reader, mapping failures onto the message the operator should see. */
|
||||
private fun readWithPbes2Reader(bytes: ByteArray, password: CharArray): Pair<PrivateKey, X509Certificate> = try {
|
||||
Pkcs12Reader.read(bytes, password)
|
||||
} catch (e: Exception) {
|
||||
// Classify by exception type so the user sees the right message:
|
||||
// - BadPadding (BAD_DECRYPT) -> wrong password
|
||||
// - IllegalStateException (error()) -> unsupported algorithm,
|
||||
// message is the algorithm name
|
||||
// - IllegalArgumentException (require()) -> structurally invalid file
|
||||
fail(
|
||||
when {
|
||||
e is javax.crypto.BadPaddingException -> LoTWProblem.CERTIFICATE_PASSWORD
|
||||
e is IllegalStateException && password.isNotEmpty() -> LoTWProblem.CERTIFICATE_FORMAT
|
||||
else -> LoTWProblem.CERTIFICATE_INVALID
|
||||
},
|
||||
if (e is IllegalStateException) (e.message ?: "") else ""
|
||||
)
|
||||
}
|
||||
|
||||
/** True when the PKCS12 uses PBES2 (OID 1.2.840.113549.1.5.13), the default
|
||||
* algorithm of OpenSSL 3 / modern TQSL. Android's legacy BC parser can't read it. */
|
||||
private fun isPbes2(bytes: ByteArray): Boolean {
|
||||
|
||||
+20
-3
@@ -267,16 +267,29 @@ class LoTWUploadRepository internal constructor(
|
||||
var duplicates = 0
|
||||
val unique = hashSetOf<String>()
|
||||
val reasons = mutableMapOf<LoTWProblem, Int>()
|
||||
val certificateCallsign = signing.key.info.callsign
|
||||
val substitutedIds = mutableSetOf<Long>()
|
||||
val callsignConflicts = mutableListOf<Long>()
|
||||
val contacts = records.sortedBy { it.startUtcMillis }.mapNotNull { record ->
|
||||
coroutineContext.ensureActive()
|
||||
if (record.status != QsoStatus.COMPLETE || ((record.lotwReceived || record.lotwUploaded) && !resubmit)) { skipped++; return@mapNotNull null }
|
||||
// A record logged while no certificate was installed carries no own callsign: sign
|
||||
// it with the certificate's callsign (the preview says so, and an accepted upload
|
||||
// writes the callsign into the record). A record naming a DIFFERENT callsign may be
|
||||
// someone else's contact, so it stays refused — the conflict list lets the operator
|
||||
// rewrite those records or import the other certificate.
|
||||
val signable = if (record.myCallsign.isBlank()) {
|
||||
substitutedIds += record.id
|
||||
record.copy(myCallsign = certificateCallsign)
|
||||
} else record
|
||||
val contact = try {
|
||||
signing.signer.contact(record, signing.key, signing.location, now())
|
||||
signing.signer.contact(signable, signing.key, signing.location, now())
|
||||
} catch (e: LoTWOperationException) {
|
||||
// One un-signable record must not abort the whole batch:
|
||||
// skip it, count the real reason, and let the rest upload.
|
||||
unavailable++
|
||||
reasons[e.reason] = (reasons[e.reason] ?: 0) + 1
|
||||
if (e.reason == LoTWProblem.CALLSIGN_MISMATCH) callsignConflicts += record.id
|
||||
return@mapNotNull null
|
||||
}
|
||||
val previous = ledger[contact.fingerprint]
|
||||
@@ -299,6 +312,7 @@ class LoTWUploadRepository internal constructor(
|
||||
signing.location["MY_VUCC_GRIDS"]?.split(',')
|
||||
?.map(String::trim)?.filter(String::isNotBlank)?.let(::addAll)
|
||||
}.distinct()
|
||||
val submittedIds = contacts.map { it.record.id }
|
||||
val preview = LoTWUploadPreview(
|
||||
UUID.randomUUID().toString(), signing.key.info.callsign, signing.key.info.dxcc, signing.location.getValue("GRIDSQUARE"),
|
||||
contacts.size, skipped,
|
||||
@@ -309,9 +323,12 @@ class LoTWUploadRepository internal constructor(
|
||||
unavailable,
|
||||
reasons.toMap(),
|
||||
duplicates,
|
||||
contacts.map { it.record.id },
|
||||
submittedIds,
|
||||
locationGrids,
|
||||
resubmit
|
||||
resubmit,
|
||||
// Only the callsign-filled records that actually made it into this batch are reported.
|
||||
submittedIds.count { it in substitutedIds },
|
||||
callsignConflicts
|
||||
)
|
||||
if (contacts.isNotEmpty()) pending = Pending(
|
||||
preview,
|
||||
|
||||
+26
-5
@@ -82,18 +82,39 @@ class QsoRepository(
|
||||
|
||||
override suspend fun delete(id: Long) = withContext(dispatcher) { importMutex.withLock { dao.delete(id) } }
|
||||
|
||||
override suspend fun markUploaded(ids: List<Long>, grids: List<String>) = withContext(dispatcher) {
|
||||
override suspend fun markUploaded(ids: List<Long>, grids: List<String>, certificateCallsign: String) = withContext(dispatcher) {
|
||||
if (ids.isEmpty()) return@withContext
|
||||
dao.markUploaded(ids)
|
||||
// Stamp the station grid set this batch went out under (a line/corner prefill from
|
||||
// the grid finder carries 2–4 grids). The logbook row shows it after the timestamp.
|
||||
val normalized = grids.map { it.trim().uppercase(Locale.US).take(4) }
|
||||
.filter { it.length >= 4 }.distinct().sorted()
|
||||
if (normalized.isEmpty()) return@withContext
|
||||
val stamped = ids.mapNotNull { id ->
|
||||
dao.find(id)?.toDomain()?.takeIf { it.vuccGrids != normalized }?.copy(vuccGrids = normalized)
|
||||
if (normalized.isNotEmpty()) {
|
||||
val stamped = ids.mapNotNull { id ->
|
||||
dao.find(id)?.toDomain()?.takeIf { it.vuccGrids != normalized }?.copy(vuccGrids = normalized)
|
||||
}
|
||||
if (stamped.isNotEmpty()) dao.saveBatch(stamped.map { it.toEntity() })
|
||||
}
|
||||
if (stamped.isNotEmpty()) dao.saveBatch(stamped.map { it.toEntity() })
|
||||
// Records logged while no certificate was installed carry no own callsign; they were just
|
||||
// signed with the certificate's, so write it into them. Blanks only, and through save() so
|
||||
// the stored dedupe key follows the new value.
|
||||
if (certificateCallsign.isNotBlank()) {
|
||||
ids.mapNotNull { id -> dao.find(id)?.toDomain()?.takeIf { it.myCallsign.isBlank() } }
|
||||
.forEach { save(it.copy(myCallsign = certificateCallsign.trim().uppercase(Locale.US))) }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun rewriteMyCallsign(ids: List<Long>, callsign: String): Int = withContext(dispatcher) {
|
||||
val target = callsign.trim().uppercase(Locale.US)
|
||||
if (ids.isEmpty() || target.isBlank()) return@withContext 0
|
||||
var changed = 0
|
||||
ids.forEach { id ->
|
||||
val record = dao.find(id)?.toDomain() ?: return@forEach
|
||||
if (record.myCallsign.trim().equals(target, true)) return@forEach
|
||||
save(record.copy(myCallsign = target))
|
||||
changed++
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
override suspend fun markWavelogUploaded(ids: List<Long>, stationId: String) = withContext(dispatcher) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Look4Sat. Amateur radio satellite tracker and pass predictor.
|
||||
* Copyright (C) 2019-2026 Arty Bishop and contributors.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.rtbishop.look4sat.core.data.lotw
|
||||
|
||||
import com.rtbishop.look4sat.core.domain.repository.LoTWOperationException
|
||||
import com.rtbishop.look4sat.core.domain.repository.LoTWProblem
|
||||
import java.io.InputStream
|
||||
import java.security.KeyStore
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Certificate import must not depend on the platform PKCS12 parser. Android's parser accepts a
|
||||
* modern TQSL PBES2 export but can expose no key entry for it (observed with an empty-password
|
||||
* backup, which was then rejected as "not a valid LoTW certificate file" although every field of
|
||||
* the certificate is readable). These tests pin the fallback to our own PBES2 reader.
|
||||
*/
|
||||
class LoTWKeyMaterialTest {
|
||||
|
||||
private fun fixture(name: String): ByteArray =
|
||||
javaClass.classLoader!!.getResourceAsStream(name)!!.use { it.readBytes() }
|
||||
|
||||
/** Stands in for a platform that parsed the container but offers no private-key entry. */
|
||||
private fun storeWithoutKeyEntry(): KeyStore = KeyStore.getInstance("PKCS12").apply {
|
||||
load(null as InputStream?, null as CharArray?)
|
||||
}
|
||||
|
||||
private val now = System.currentTimeMillis()
|
||||
|
||||
/** TQSL-style backup (empty password) imported although the platform delivers no key entry. */
|
||||
@Test
|
||||
fun importsCertificateWhenPlatformExposesNoKeyEntry() {
|
||||
val material = LoTWKeyMaterial.read(
|
||||
bytes = fixture("test_tqsl_empty.p12"),
|
||||
password = charArrayOf(),
|
||||
now = now,
|
||||
platformStore = { _, _ -> storeWithoutKeyEntry() },
|
||||
)
|
||||
assertEquals("BA7OPF", material.info.callsign)
|
||||
assertEquals(318, material.info.dxcc)
|
||||
assertEquals("2026-01-01", material.info.firstQsoDate)
|
||||
}
|
||||
|
||||
/** The same backup still imports when the platform is the one that resolves the key entry. */
|
||||
@Test
|
||||
fun importsCertificateThroughPlatformWhenAvailable() {
|
||||
val material = LoTWKeyMaterial.read(fixture("test_tqsl_empty.p12"), charArrayOf(), now)
|
||||
assertEquals("BA7OPF", material.info.callsign)
|
||||
}
|
||||
|
||||
/** A wrong password is still reported as a password problem, not as an invalid file. */
|
||||
@Test
|
||||
fun reportsWrongPasswordForPbes2Backup() {
|
||||
val error = assertThrows(LoTWOperationException::class.java) {
|
||||
LoTWKeyMaterial.read(fixture("test_tqsl_empty.p12"), "wrong-password".toCharArray(), now)
|
||||
}
|
||||
assertEquals(LoTWProblem.CERTIFICATE_PASSWORD, error.reason)
|
||||
}
|
||||
|
||||
/** Something that is not a PKCS12 at all keeps the message the platform path produced. */
|
||||
@Test
|
||||
fun refusesNonPkcs12File() {
|
||||
val error = assertThrows(LoTWOperationException::class.java) {
|
||||
LoTWKeyMaterial.read("not a p12 at all".toByteArray(), "x".toCharArray(), now) { _, _ -> null }
|
||||
}
|
||||
assertEquals(LoTWProblem.CERTIFICATE_PASSWORD, error.reason)
|
||||
}
|
||||
|
||||
/** Oversized input is rejected before any parser runs. */
|
||||
@Test
|
||||
fun refusesOversizedInput() {
|
||||
val bytes = ByteArray(MAX_CERTIFICATE_BYTES + 1)
|
||||
val error = assertThrows(LoTWOperationException::class.java) {
|
||||
LoTWKeyMaterial.read(bytes, charArrayOf(), now) { _, _ -> storeWithoutKeyEntry() }
|
||||
}
|
||||
assertEquals(LoTWProblem.CERTIFICATE_INVALID, error.reason)
|
||||
}
|
||||
}
|
||||
+58
-1
@@ -17,8 +17,12 @@
|
||||
*/
|
||||
package com.rtbishop.look4sat.core.data.lotw
|
||||
|
||||
import com.rtbishop.look4sat.core.domain.logbook.QsoRecord
|
||||
import com.rtbishop.look4sat.core.domain.logbook.QsoStatus
|
||||
import com.rtbishop.look4sat.core.domain.repository.LoTWOperationException
|
||||
import com.rtbishop.look4sat.core.domain.repository.LoTWProblem
|
||||
import com.rtbishop.look4sat.core.domain.repository.LoTWStation
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -39,7 +43,9 @@ class LoTWUploadRepositoryPreviewTest {
|
||||
|
||||
private class MemStorage : LoTWStorage {
|
||||
val files = mutableMapOf<String, ByteArray>()
|
||||
override fun read(name: String): ByteArray? = files[name]
|
||||
// Reads hand out their own copy, like the file-backed storage does: several call sites
|
||||
// wipe what they read, and that must not corrupt the stored bytes.
|
||||
override fun read(name: String): ByteArray? = files[name]?.copyOf()
|
||||
override fun write(name: String, data: ByteArray) { files[name] = data.copyOf() }
|
||||
override fun delete(name: String) { files.remove(name) }
|
||||
}
|
||||
@@ -79,4 +85,55 @@ class LoTWUploadRepositoryPreviewTest {
|
||||
assertTrue("nothing written", storage.files.isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records logged before a certificate was installed (blank own callsign) or under another
|
||||
* certificate are signed with the certificate's callsign instead of being refused, and the
|
||||
* preview reports how many they were.
|
||||
*/
|
||||
@Test
|
||||
fun `records without a matching callsign upload under the certificate and are reported`() {
|
||||
runBlocking {
|
||||
val storage = MemStorage()
|
||||
val repo = LoTWUploadRepository(
|
||||
storage,
|
||||
{ LoTWConfig(File("src/main/assets/lotw/config.tq6").inputStream()) },
|
||||
now = { System.currentTimeMillis() }
|
||||
)
|
||||
repo.importCertificate(fixture("test_tqsl_empty.p12"), charArrayOf())
|
||||
repo.saveStation(LoTWStation(grid = "OL62TI"))
|
||||
val start = 1_787_000_000_000L // 2026-08, inside the fixture certificate's QSO range
|
||||
val preview = repo.prepare(
|
||||
listOf(
|
||||
sampleRecord(start, "BH6RJD", ""),
|
||||
sampleRecord(start + 60_000L, "BG7QBL", "XX0YY"),
|
||||
sampleRecord(start + 120_000L, "BA8BLK", "BA7OPF")
|
||||
),
|
||||
resubmit = false
|
||||
)
|
||||
// The blank record is signed with the certificate's callsign; the one naming another
|
||||
// callsign is refused and offered up for a rewrite instead.
|
||||
assertEquals(2, preview.count)
|
||||
assertEquals(1, preview.missingCallsign)
|
||||
assertEquals(listOf(start + 60_000L), preview.callsignConflicts)
|
||||
assertEquals(1, preview.unavailableReasons[LoTWProblem.CALLSIGN_MISMATCH])
|
||||
}
|
||||
}
|
||||
|
||||
private fun sampleRecord(start: Long, call: String, myCallsign: String) = QsoRecord(
|
||||
id = start,
|
||||
startUtcMillis = start,
|
||||
endUtcMillis = start,
|
||||
theirCallsign = call,
|
||||
myCallsign = myCallsign,
|
||||
myGrid = "OL62TI",
|
||||
txFrequencyHz = 145_850_000L,
|
||||
rxFrequencyHz = 436_795_000L,
|
||||
band = "2M",
|
||||
rxBand = "70CM",
|
||||
mode = "FM",
|
||||
satelliteName = "SO-50",
|
||||
propagationMode = "SAT",
|
||||
status = QsoStatus.COMPLETE
|
||||
)
|
||||
}
|
||||
+30
@@ -295,6 +295,36 @@ class QsoRepositoryTest {
|
||||
assertEquals(1, dao.getAll().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markUploaded_fillsBlankCallsignsAndKeepsTheOthers() = runBlocking {
|
||||
val blank = dao.save(loggedInApp("SO-50", lotwUploaded = false).copy(myCallsign = "").toEntity())
|
||||
val named = dao.save(loggedInApp("SO-50", lotwUploaded = false).copy(myCallsign = "BH3HCF").toEntity())
|
||||
|
||||
repository.markUploaded(listOf(blank, named), emptyList(), "BA7OPF")
|
||||
|
||||
val rows = dao.getAll().associateBy { it.id }
|
||||
// Records logged before a certificate existed get the certificate's callsign; a record that
|
||||
// names another callsign is not touched (they are refused, not rewritten, by the uploader).
|
||||
assertEquals("BA7OPF", rows[blank]!!.myCallsign)
|
||||
assertEquals("BH3HCF", rows[named]!!.myCallsign)
|
||||
assertTrue(rows[blank]!!.lotwUploaded)
|
||||
assertTrue(rows[named]!!.lotwUploaded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rewriteMyCallsign_rewritesTheConflictRecordsOnly() = runBlocking {
|
||||
val conflict = dao.save(loggedInApp("SO-50", lotwUploaded = false).copy(myCallsign = "XX0YY").toEntity())
|
||||
val kept = dao.save(loggedInApp("SO-50", lotwUploaded = false).copy(myCallsign = "BA7OPF").toEntity())
|
||||
|
||||
val changed = repository.rewriteMyCallsign(listOf(conflict, kept), "ba7opf")
|
||||
|
||||
assertEquals(1, changed)
|
||||
val rows = dao.getAll().associateBy { it.id }
|
||||
assertEquals("BA7OPF", rows[conflict]!!.myCallsign)
|
||||
assertEquals("BA7OPF", rows[kept]!!.myCallsign)
|
||||
assertFalse(rows[conflict]!!.lotwUploaded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markWavelogUploaded_setsTheFlagAndTheStationStamp() = runBlocking {
|
||||
val id = dao.save(loggedInApp("SO-50", lotwUploaded = false).toEntity())
|
||||
|
||||
+8
-1
@@ -22,7 +22,14 @@ interface IQsoRepository {
|
||||
* signed with (1–4 gridsquares: inside a grid / on a line / on a corner), so the
|
||||
* logbook row can show which grids the QSO went out under.
|
||||
*/
|
||||
suspend fun markUploaded(ids: List<Long>, grids: List<String> = emptyList())
|
||||
suspend fun markUploaded(ids: List<Long>, grids: List<String> = emptyList(), certificateCallsign: String = "")
|
||||
|
||||
/**
|
||||
* Rewrites the operator's callsign on the given records. This is the answer to "these contacts
|
||||
* were logged under another certificate — upload them under the one installed now". Returns the
|
||||
* number of records that changed.
|
||||
*/
|
||||
suspend fun rewriteMyCallsign(ids: List<Long>, callsign: String): Int
|
||||
|
||||
/**
|
||||
* Marks the batch as uploaded to Wavelog (independent of the LoTW upload state) and
|
||||
|
||||
+7
-1
@@ -107,7 +107,13 @@ data class LoTWUploadPreview(
|
||||
val grids: List<String> = emptyList(),
|
||||
/** True when this batch is a resubmit: already-uploaded/confirmed records were allowed
|
||||
* through so the corrected station location reaches LoTW as an update of the contact. */
|
||||
val resubmit: Boolean = false
|
||||
val resubmit: Boolean = false,
|
||||
/** Records in this batch whose own callsign is blank (logged before a certificate was
|
||||
* installed). They are signed with [callsign]; a successful upload writes it into them. */
|
||||
val missingCallsign: Int = 0,
|
||||
/** Records refused because they name a different own callsign than [callsign]. The upload
|
||||
* flow offers either rewriting them with [callsign] or using the other certificate. */
|
||||
val callsignConflicts: List<Long> = emptyList()
|
||||
)
|
||||
|
||||
/** Pre-upload location check: the freshest known position grid is not covered by the
|
||||
|
||||
@@ -216,6 +216,10 @@
|
||||
<string name="prefs_logbook_selected">已选 %1$d 条</string>
|
||||
<string name="prefs_logbook_select_hint">长按记录行可多选重传</string>
|
||||
<string name="prefs_logbook_resubmit_note">已上传记录将按当前台址就地更新;已被奖项使用的旧网格可能被拒绝。</string>
|
||||
<string name="prefs_logbook_callsign_missing">其中 %1$d 条记录没有呼号,将按证书 %2$s 上传。</string>
|
||||
<string name="prefs_logbook_callsign_different">%1$d 条记录登记的不是证书 %2$s 的呼号。</string>
|
||||
<string name="prefs_logbook_callsign_rewrite">改写为 %1$s</string>
|
||||
<string name="prefs_logbook_callsign_switch">换一张证书</string>
|
||||
<string name="prefs_logbook_station_label">台址</string>
|
||||
<string name="prefs_logbook_station_all">全部</string>
|
||||
<string name="prefs_logbook_upload_wavelog_title">上传到 Wavelog</string>
|
||||
|
||||
@@ -245,6 +245,10 @@
|
||||
<string name="prefs_logbook_selected">%1$d selected</string>
|
||||
<string name="prefs_logbook_select_hint">Long-press a row to re-upload corrected records</string>
|
||||
<string name="prefs_logbook_resubmit_note">Existing contacts will be updated in place — a grid already used for an award may be rejected.</string>
|
||||
<string name="prefs_logbook_callsign_missing">%1$d record(s) have no callsign — signed with %2$s from the certificate.</string>
|
||||
<string name="prefs_logbook_callsign_different">%1$d record(s) name another callsign than the certificate %2$s.</string>
|
||||
<string name="prefs_logbook_callsign_rewrite">Rewrite with %1$s</string>
|
||||
<string name="prefs_logbook_callsign_switch">Use another certificate</string>
|
||||
<string name="prefs_logbook_station_label">Station</string>
|
||||
<string name="prefs_logbook_station_all">All</string>
|
||||
<string name="prefs_logbook_upload_wavelog_title">Upload to Wavelog</string>
|
||||
|
||||
@@ -262,7 +262,9 @@ fun LogPage(
|
||||
preview = preview,
|
||||
busy = logUiState.busy,
|
||||
onConfirm = logViewModel::confirmUpload,
|
||||
onDismiss = logViewModel::dismissPreview
|
||||
onDismiss = logViewModel::dismissPreview,
|
||||
onRewriteCallsign = logViewModel::rewriteCallsignConflicts,
|
||||
onSwitchCertificate = logViewModel::switchCertificateForConflicts
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -417,7 +419,9 @@ private fun UploadPreviewDialog(
|
||||
preview: com.rtbishop.look4sat.core.domain.repository.LoTWUploadPreview,
|
||||
busy: Boolean,
|
||||
onConfirm: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
onDismiss: () -> Unit,
|
||||
onRewriteCallsign: () -> Unit,
|
||||
onSwitchCertificate: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -464,6 +468,32 @@ private fun UploadPreviewDialog(
|
||||
}
|
||||
Text(parts.joinToString(" · "), fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
if (preview.missingCallsign > 0) {
|
||||
// Logged while no certificate was installed; signed with the certificate's
|
||||
// callsign instead of being refused.
|
||||
Text(
|
||||
stringResource(R.string.prefs_logbook_callsign_missing, preview.missingCallsign, preview.callsign),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
if (preview.callsignConflicts.isNotEmpty()) {
|
||||
// These name another callsign than the certificate: rewrite them with this
|
||||
// certificate's callsign, or upload them under the other certificate.
|
||||
Text(
|
||||
stringResource(R.string.prefs_logbook_callsign_different, preview.callsignConflicts.size, preview.callsign),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = onRewriteCallsign, enabled = !busy) {
|
||||
Text(stringResource(R.string.prefs_logbook_callsign_rewrite, preview.callsign), fontSize = 12.sp)
|
||||
}
|
||||
TextButton(onClick = onSwitchCertificate, enabled = !busy) {
|
||||
Text(stringResource(R.string.prefs_logbook_callsign_switch), fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(preview.contacts.joinToString("\n") { it }, fontSize = 12.sp, maxLines = 8)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -343,7 +343,7 @@ class LogViewModel(
|
||||
if (result is LoTWUploadResult.Accepted && lastUploadedIds.isNotEmpty()) {
|
||||
// Mark the submitted QSOs as uploaded (distinct from confirmed) and stamp
|
||||
// the station grids this batch went out under.
|
||||
qsoRepository.markUploaded(lastUploadedIds, preview.grids)
|
||||
qsoRepository.markUploaded(lastUploadedIds, preview.grids, preview.callsign)
|
||||
lastUploadedIds = emptyList()
|
||||
}
|
||||
val msg = when (result) {
|
||||
@@ -368,6 +368,34 @@ class LogViewModel(
|
||||
|
||||
fun dismissPreview() = _uiState.update { it.copy(preview = null) }
|
||||
|
||||
/**
|
||||
* Operator chose "rewrite" on the callsign conflict: the refused records get this certificate's
|
||||
* callsign so the next upload can sign them. The prepared batch is dropped — nothing was sent.
|
||||
*/
|
||||
fun rewriteCallsignConflicts() {
|
||||
val preview = _uiState.value.preview ?: return
|
||||
val ids = preview.callsignConflicts
|
||||
if (ids.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(busy = true) }
|
||||
val changed = qsoRepository.rewriteMyCallsign(ids, preview.callsign)
|
||||
lotwUploadRepository.discardPreview()
|
||||
lastUploadedIds = emptyList()
|
||||
_uiState.update {
|
||||
it.copy(busy = false, preview = null, message = "$changed record(s) rewritten to ${preview.callsign} — upload again")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Operator chose "use another certificate": that certificate is imported on the settings page. */
|
||||
fun switchCertificateForConflicts() {
|
||||
lotwUploadRepository.discardPreview()
|
||||
lastUploadedIds = emptyList()
|
||||
_uiState.update {
|
||||
it.copy(preview = null, message = "Import the other callsign's certificate in Settings → LoTW upload, then upload again")
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissWavelogPreview() = _uiState.update { it.copy(wavelogPreview = null) }
|
||||
|
||||
/**
|
||||
|
||||
+36
-2
@@ -103,6 +103,10 @@ fun LogbookDialog(
|
||||
onDismissMessage: () -> Unit,
|
||||
onIgnorePositionWarning: () -> Unit = {},
|
||||
onFixGrid: (List<String>) -> Unit = {},
|
||||
/** Rewrite the records whose own callsign differs from the certificate's. */
|
||||
onRewriteCallsign: () -> Unit = {},
|
||||
/** Leave the upload to import a different certificate instead. */
|
||||
onSwitchCertificate: () -> Unit = {},
|
||||
selectionMode: Boolean = false,
|
||||
selectedIds: Set<Long> = emptySet(),
|
||||
onStartSelection: (Long) -> Unit = {},
|
||||
@@ -246,7 +250,9 @@ fun LogbookDialog(
|
||||
preview = preview,
|
||||
busy = uploadBusy,
|
||||
onConfirm = onConfirmUpload,
|
||||
onDismiss = onDismissPreview
|
||||
onDismiss = onDismissPreview,
|
||||
onRewriteCallsign = onRewriteCallsign,
|
||||
onSwitchCertificate = onSwitchCertificate
|
||||
)
|
||||
}
|
||||
if (uploadMessage.isNotBlank()) {
|
||||
@@ -280,7 +286,9 @@ private fun LogbookUploadPreviewDialog(
|
||||
preview: com.rtbishop.look4sat.core.domain.repository.LoTWUploadPreview,
|
||||
busy: Boolean,
|
||||
onConfirm: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
onDismiss: () -> Unit,
|
||||
onRewriteCallsign: () -> Unit,
|
||||
onSwitchCertificate: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -319,6 +327,32 @@ private fun LogbookUploadPreviewDialog(
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
if (preview.missingCallsign > 0) {
|
||||
// Logged while no certificate was installed; signed with the certificate's
|
||||
// callsign instead of being refused.
|
||||
Text(
|
||||
stringResource(R.string.prefs_logbook_callsign_missing, preview.missingCallsign, preview.callsign),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
if (preview.callsignConflicts.isNotEmpty()) {
|
||||
// These name another callsign than the certificate: the operator either rewrites
|
||||
// them with the certificate's callsign or uploads them under that other one.
|
||||
Text(
|
||||
stringResource(R.string.prefs_logbook_callsign_different, preview.callsignConflicts.size, preview.callsign),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = onRewriteCallsign, enabled = !busy) {
|
||||
Text(stringResource(R.string.prefs_logbook_callsign_rewrite, preview.callsign), fontSize = 12.sp)
|
||||
}
|
||||
TextButton(onClick = onSwitchCertificate, enabled = !busy) {
|
||||
Text(stringResource(R.string.prefs_logbook_callsign_switch), fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(preview.contacts.joinToString("\n") { it }, fontSize = 12.sp, maxLines = 8)
|
||||
}
|
||||
},
|
||||
|
||||
+9
@@ -308,6 +308,15 @@ private fun SettingsScreen(
|
||||
onConfirmUpload = { onAction(SettingsAction.ConfirmLogbookUpload) },
|
||||
onDismissPreview = { onAction(SettingsAction.DismissLogbookPreview) },
|
||||
onDismissMessage = { onAction(SettingsAction.ClearLogbookMessage) },
|
||||
onRewriteCallsign = { onAction(SettingsAction.RewriteLogbookCallsigns) },
|
||||
onSwitchCertificate = {
|
||||
// The other callsign's certificate lives in the LoTW upload settings: leave the
|
||||
// logbook and open that dialog.
|
||||
onAction(SettingsAction.DismissLogbookPreview)
|
||||
onAction(SettingsAction.ExitLogbookSelection)
|
||||
dialogs.logbook = false
|
||||
dialogs.lotwUpload = true
|
||||
},
|
||||
onIgnorePositionWarning = { onAction(SettingsAction.IgnoreLogbookPositionWarning) },
|
||||
onFixGrid = { grids ->
|
||||
onAction(SettingsAction.AbandonLogbookForGridFix)
|
||||
|
||||
@@ -193,6 +193,7 @@ sealed interface SettingsAction {
|
||||
data object PrepareLogbookUpload : SettingsAction
|
||||
data object ConfirmLogbookUpload : SettingsAction
|
||||
data object DismissLogbookPreview : SettingsAction
|
||||
data object RewriteLogbookCallsigns : SettingsAction
|
||||
/** The operator acknowledged the position mismatch and wants to upload anyway. */
|
||||
data object IgnoreLogbookPositionWarning : SettingsAction
|
||||
/** The operator chose to fix the station location first; the preview is discarded. */
|
||||
|
||||
+25
-1
@@ -257,6 +257,7 @@ class SettingsViewModel(
|
||||
SettingsAction.PrepareLogbookUpload -> prepareLogbookUpload()
|
||||
SettingsAction.ConfirmLogbookUpload -> confirmLogbookUpload()
|
||||
SettingsAction.DismissLogbookPreview -> dismissLogbookPreview()
|
||||
SettingsAction.RewriteLogbookCallsigns -> rewriteLogbookCallsigns()
|
||||
SettingsAction.IgnoreLogbookPositionWarning -> ignoreLogbookPositionWarning()
|
||||
SettingsAction.AbandonLogbookForGridFix -> abandonLogbookForGridFix()
|
||||
is SettingsAction.StartLogbookSelection -> startLogbookSelection(action.id)
|
||||
@@ -648,7 +649,7 @@ class SettingsViewModel(
|
||||
val result = lotwUploadRepository.upload(preview.id)
|
||||
val accepted = result is com.rtbishop.look4sat.core.domain.repository.LoTWUploadResult.Accepted
|
||||
if (accepted && lastLogbookUploadIds.isNotEmpty()) {
|
||||
qsoRepository.markUploaded(lastLogbookUploadIds, preview.grids)
|
||||
qsoRepository.markUploaded(lastLogbookUploadIds, preview.grids, preview.callsign)
|
||||
lastLogbookUploadIds = emptyList()
|
||||
}
|
||||
val msg = when (result) {
|
||||
@@ -673,6 +674,29 @@ class SettingsViewModel(
|
||||
|
||||
private fun dismissLogbookPreview() = _uiState.update { it.copy(logbookPreview = null, logbookWavelogPreview = null) }
|
||||
|
||||
/**
|
||||
* Operator chose "rewrite" on the callsign conflict: the refused records get this certificate's
|
||||
* callsign so the next upload can sign them. The batch is discarded — nothing was uploaded.
|
||||
*/
|
||||
private fun rewriteLogbookCallsigns() {
|
||||
val preview = _uiState.value.logbookPreview ?: return
|
||||
val ids = preview.callsignConflicts
|
||||
if (ids.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_uiState.update { it.copy(logbookUploadBusy = true) }
|
||||
val changed = qsoRepository.rewriteMyCallsign(ids, preview.callsign)
|
||||
lotwUploadRepository.discardPreview()
|
||||
lastLogbookUploadIds = emptyList()
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
logbookUploadBusy = false,
|
||||
logbookPreview = null,
|
||||
logbookUploadMessage = "$changed record(s) rewritten to ${preview.callsign} — upload again"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Operator chose "ignore" on the position check: keep the prepared preview. */
|
||||
private fun ignoreLogbookPositionWarning() = _uiState.update { it.copy(logbookPositionWarning = null) }
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
[versions]
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
appVersionCode = "576"
|
||||
appVersionCode = "578"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
appVersionName = "4.4.8-ba7opf.11.1"
|
||||
appVersionName = "4.4.8-ba7opf.11.3"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
compileSdk = "37"
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
|
||||
Reference in new issue
Block a user