Compare commits
22 Commits
50b35a0025
...
v1,0
| Author | SHA1 | Date | |
|---|---|---|---|
| fb2474ba21 | |||
| 3c585c2f6b | |||
| 37d424ef60 | |||
| 66155f6141 | |||
| 4ea8e1c2ff | |||
| 65cb8ee2d5 | |||
| fd28a45cd7 | |||
| df9485bd98 | |||
| b907fdbbc3 | |||
| 0799595b26 | |||
| d606a59a92 | |||
| b44f6866cd | |||
| ba6e0c2364 | |||
| ff5503e30c | |||
| dcf74007e7 | |||
| 2ef56dc78b | |||
| c39ab434b7 | |||
| 2a963d9380 | |||
| 6fb4e65a20 | |||
| 0327bc1d78 | |||
| b1265f2c2d | |||
| f7f9f5f3be |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -16,12 +16,14 @@ android/**/build/
|
|||||||
android/captures/
|
android/captures/
|
||||||
*.apk
|
*.apk
|
||||||
*.aab
|
*.aab
|
||||||
|
*.hprof
|
||||||
|
|
||||||
# ide
|
# ide
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
*.iml
|
*.iml
|
||||||
|
|
||||||
# os
|
# os and emacs
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
/archive
|
||||||
|
|||||||
80
README.md
80
README.md
@@ -2,10 +2,9 @@
|
|||||||
|
|
||||||
open app.
|
open app.
|
||||||
type, optionally mark as todo, optionally add tags, save.
|
type, optionally mark as todo, optionally add tags, save.
|
||||||
if home server accessible, post unsynced captures to lan-only service and appended to `phone.org`.
|
if home server accessible, post unsynced captures to lan-only service and appended to `synq.org`.
|
||||||
|
|
||||||
## non-goals
|
## non-goals
|
||||||
|
|
||||||
- no org parser on android
|
- no org parser on android
|
||||||
- no agenda on android
|
- no agenda on android
|
||||||
- no sync provider dependency
|
- no sync provider dependency
|
||||||
@@ -157,6 +156,83 @@ synq/
|
|||||||
5. add history screen and resend handling.
|
5. add history screen and resend handling.
|
||||||
6. polish launch speed and widget/share-target only after core path works.
|
6. polish launch speed and widget/share-target only after core path works.
|
||||||
|
|
||||||
|
## build & deploy
|
||||||
|
|
||||||
|
### server (docker)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# build
|
||||||
|
docker build -t synq-server ./server
|
||||||
|
|
||||||
|
# run (replace paths and token as needed)
|
||||||
|
docker run -d --name synq --restart=unless-stopped \
|
||||||
|
-p 8765:8765 \
|
||||||
|
-v /mnt/user/synq/data:/data \
|
||||||
|
synq-server
|
||||||
|
```
|
||||||
|
|
||||||
|
the server generates a random token on first start and logs it prominently. copy it into the android app settings. to use a fixed token instead, pass `-e PHONE_CAPTURE_TOKEN=yourtoken`.
|
||||||
|
|
||||||
|
to rebuild after a `git pull`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git pull
|
||||||
|
docker build -t synq-server ./server
|
||||||
|
docker stop synq && docker rm synq
|
||||||
|
# re-run the docker run command above
|
||||||
|
```
|
||||||
|
|
||||||
|
### android
|
||||||
|
|
||||||
|
open `android/` in Android Studio and hit **Sync**. then either:
|
||||||
|
|
||||||
|
- **run on device/emulator directly** from Android Studio (▶), or
|
||||||
|
- **build a release APK** from the terminal:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd android
|
||||||
|
./gradlew assembleRelease
|
||||||
|
# output: app/build/outputs/apk/release/app-release-unsigned.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
sideload to a connected device:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
adb install app/build/outputs/apk/release/app-release-unsigned.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
### releasing on gitea
|
||||||
|
|
||||||
|
tag the commit and push the tag:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag v1.0.0
|
||||||
|
git push gitea v1.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
then go to **Releases → New Release** in the Gitea UI, pick the tag, and drag the APK into the assets box. anyone on the LAN can download it from there.
|
||||||
|
|
||||||
|
## backup
|
||||||
|
|
||||||
|
### what to back up
|
||||||
|
|
||||||
|
the server writes to one directory (the `/data` volume). back up the whole thing:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/data/synq.org ← the canonical org capture file
|
||||||
|
/data/capture.sqlite3 ← idempotency store (dedup ids)
|
||||||
|
/data/token.txt ← auto-generated token (if not using PHONE_CAPTURE_TOKEN env var)
|
||||||
|
```
|
||||||
|
|
||||||
|
on unraid the host path is whatever you mapped in compose, e.g. `/mnt/user/ben/synq/phone-capture`.
|
||||||
|
|
||||||
|
### restore behavior
|
||||||
|
|
||||||
|
- restore the `/data` volume to a new container and start it. the server will pick up where it left off.
|
||||||
|
- `synq.org` is append-only plain text — it is human-readable and recoverable even without the sqlite db.
|
||||||
|
- if `capture.sqlite3` is lost but `synq.org` is intact, the server will accept re-posted captures that were already in the org file (no dedup). the android app marks them synced either way (`already_seen` or `accepted`), so the only side effect is duplicate org entries for anything re-synced. restore the db from backup to avoid this.
|
||||||
|
- if `token.txt` is lost, delete it and let the server generate a new one on next start, then update the app settings.
|
||||||
|
|
||||||
## v2 parking lot
|
## v2 parking lot
|
||||||
|
|
||||||
- android share target
|
- android share target
|
||||||
|
|||||||
@@ -8,7 +8,8 @@
|
|||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:theme="@style/Theme.Synq"
|
android:theme="@style/Theme.Synq"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:supportsRtl="true">
|
android:supportsRtl="true"
|
||||||
|
android:usesCleartextTraffic="true">
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
@@ -18,6 +19,11 @@
|
|||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.SEND" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="text/plain" />
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
</application>
|
</application>
|
||||||
|
|||||||
@@ -1,33 +1,56 @@
|
|||||||
package me.hgsky.synq
|
package me.hgsky.synq
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.navigation.NavType
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
|
import androidx.navigation.navArgument
|
||||||
import me.hgsky.synq.ui.capture.CaptureScreen
|
import me.hgsky.synq.ui.capture.CaptureScreen
|
||||||
import me.hgsky.synq.ui.history.HistoryScreen
|
import me.hgsky.synq.ui.history.HistoryScreen
|
||||||
import me.hgsky.synq.ui.settings.SettingsScreen
|
import me.hgsky.synq.ui.settings.SettingsScreen
|
||||||
import me.hgsky.synq.ui.theme.SynqTheme
|
import me.hgsky.synq.ui.theme.SynqTheme
|
||||||
|
import java.net.URLDecoder
|
||||||
|
import java.net.URLEncoder
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
|
||||||
|
val sharedText = if (intent.action == Intent.ACTION_SEND)
|
||||||
|
intent.getStringExtra(Intent.EXTRA_TEXT) else null
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
SynqTheme { SynqNav() }
|
SynqTheme { SynqNav(sharedText = sharedText) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun SynqNav() {
|
private fun SynqNav(sharedText: String? = null) {
|
||||||
val nav = rememberNavController()
|
val nav = rememberNavController()
|
||||||
NavHost(navController = nav, startDestination = "capture") {
|
val startRoute = if (sharedText != null) {
|
||||||
|
"capture/${URLEncoder.encode(sharedText, "UTF-8")}"
|
||||||
|
} else {
|
||||||
|
"capture"
|
||||||
|
}
|
||||||
|
|
||||||
|
NavHost(navController = nav, startDestination = startRoute) {
|
||||||
composable("capture") { CaptureScreen(nav) }
|
composable("capture") { CaptureScreen(nav) }
|
||||||
|
composable(
|
||||||
|
route = "capture/{prefill}",
|
||||||
|
arguments = listOf(navArgument("prefill") { type = NavType.StringType }),
|
||||||
|
) { back ->
|
||||||
|
val prefill = back.arguments?.getString("prefill")
|
||||||
|
?.let { URLDecoder.decode(it, "UTF-8") }
|
||||||
|
CaptureScreen(nav, prefill = prefill)
|
||||||
|
}
|
||||||
composable("history") { HistoryScreen(nav) }
|
composable("history") { HistoryScreen(nav) }
|
||||||
composable("settings") { SettingsScreen(nav) }
|
composable("settings") { SettingsScreen(nav) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,14 @@ package me.hgsky.synq
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import me.hgsky.synq.data.SettingsRepository
|
import me.hgsky.synq.data.SettingsRepository
|
||||||
import me.hgsky.synq.data.db.CaptureDatabase
|
import me.hgsky.synq.data.db.CaptureDatabase
|
||||||
|
import me.hgsky.synq.data.sync.SyncWorker
|
||||||
|
|
||||||
class SynqApp : Application() {
|
class SynqApp : Application() {
|
||||||
val db by lazy { CaptureDatabase.get(this) }
|
val db by lazy { CaptureDatabase.get(this) }
|
||||||
val settings by lazy { SettingsRepository(this) }
|
val settings by lazy { SettingsRepository(this) }
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
SyncWorker.schedule(this)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package me.hgsky.synq.data
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import androidx.datastore.preferences.core.edit
|
import androidx.datastore.preferences.core.edit
|
||||||
|
import androidx.datastore.preferences.core.intPreferencesKey
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
import androidx.datastore.preferences.preferencesDataStore
|
import androidx.datastore.preferences.preferencesDataStore
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -13,6 +14,7 @@ data class SynqSettings(
|
|||||||
val serverUrl: String = "http://jeeves.mother:8765",
|
val serverUrl: String = "http://jeeves.mother:8765",
|
||||||
val token: String = "",
|
val token: String = "",
|
||||||
val deviceLabel: String = "android",
|
val deviceLabel: String = "android",
|
||||||
|
val syncIntervalMinutes: Int = 15,
|
||||||
)
|
)
|
||||||
|
|
||||||
class SettingsRepository(private val context: Context) {
|
class SettingsRepository(private val context: Context) {
|
||||||
@@ -20,12 +22,14 @@ class SettingsRepository(private val context: Context) {
|
|||||||
private val KEY_URL = stringPreferencesKey("server_url")
|
private val KEY_URL = stringPreferencesKey("server_url")
|
||||||
private val KEY_TOKEN = stringPreferencesKey("token")
|
private val KEY_TOKEN = stringPreferencesKey("token")
|
||||||
private val KEY_DEVICE = stringPreferencesKey("device_label")
|
private val KEY_DEVICE = stringPreferencesKey("device_label")
|
||||||
|
private val KEY_INTERVAL = intPreferencesKey("sync_interval_minutes")
|
||||||
|
|
||||||
val settings: Flow<SynqSettings> = context.dataStore.data.map { prefs ->
|
val settings: Flow<SynqSettings> = context.dataStore.data.map { prefs ->
|
||||||
SynqSettings(
|
SynqSettings(
|
||||||
serverUrl = prefs[KEY_URL] ?: "http://jeeves.mother:8765",
|
serverUrl = prefs[KEY_URL] ?: "http://jeeves.mother:8765",
|
||||||
token = prefs[KEY_TOKEN] ?: "",
|
token = prefs[KEY_TOKEN] ?: "",
|
||||||
deviceLabel = prefs[KEY_DEVICE] ?: "android",
|
deviceLabel = prefs[KEY_DEVICE] ?: "android",
|
||||||
|
syncIntervalMinutes = prefs[KEY_INTERVAL] ?: 15,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +38,7 @@ class SettingsRepository(private val context: Context) {
|
|||||||
prefs[KEY_URL] = settings.serverUrl
|
prefs[KEY_URL] = settings.serverUrl
|
||||||
prefs[KEY_TOKEN] = settings.token
|
prefs[KEY_TOKEN] = settings.token
|
||||||
prefs[KEY_DEVICE] = settings.deviceLabel
|
prefs[KEY_DEVICE] = settings.deviceLabel
|
||||||
|
prefs[KEY_INTERVAL] = settings.syncIntervalMinutes
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package me.hgsky.synq.data.api
|
||||||
|
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import me.hgsky.synq.data.SynqSettings
|
||||||
|
import me.hgsky.synq.data.db.CaptureEntity
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
sealed class PostResult {
|
||||||
|
data class Accepted(val id: String) : PostResult()
|
||||||
|
data class AlreadySeen(val id: String) : PostResult()
|
||||||
|
data class Failed(val id: String, val error: String) : PostResult()
|
||||||
|
}
|
||||||
|
|
||||||
|
class SynqApiClient {
|
||||||
|
|
||||||
|
private val http = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
fun checkHealth(serverUrl: String): Boolean = try {
|
||||||
|
val req = Request.Builder().url("$serverUrl/health").get().build()
|
||||||
|
http.newCall(req).execute().use { it.isSuccessful }
|
||||||
|
} catch (_: IOException) {
|
||||||
|
false
|
||||||
|
} catch (_: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun postCapture(capture: CaptureEntity, settings: SynqSettings): PostResult = try {
|
||||||
|
val tags = try {
|
||||||
|
Json.decodeFromString<List<String>>(capture.tagsJson)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
val bodyJson = JSONObject().apply {
|
||||||
|
put("id", capture.id)
|
||||||
|
put("created_at", capture.createdAt)
|
||||||
|
put("kind", capture.kind)
|
||||||
|
put("body", capture.body)
|
||||||
|
put("tags", JSONArray(tags))
|
||||||
|
put("device", capture.device)
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
val req = Request.Builder()
|
||||||
|
.url("${settings.serverUrl}/capture")
|
||||||
|
.header("Authorization", "Bearer ${settings.token}")
|
||||||
|
.post(bodyJson.toRequestBody("application/json".toMediaType()))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
http.newCall(req).execute().use { response ->
|
||||||
|
when {
|
||||||
|
response.code == 401 -> PostResult.Failed(capture.id, "unauthorized (check token in settings)")
|
||||||
|
!response.isSuccessful -> PostResult.Failed(capture.id, "server error ${response.code}")
|
||||||
|
else -> {
|
||||||
|
val json = JSONObject(response.body?.string() ?: "{}")
|
||||||
|
if (json.optString("status") == "already_seen")
|
||||||
|
PostResult.AlreadySeen(capture.id)
|
||||||
|
else
|
||||||
|
PostResult.Accepted(capture.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
PostResult.Failed(capture.id, e.message ?: "network error")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
PostResult.Failed(capture.id, e.message ?: "unexpected error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,4 +27,13 @@ interface CaptureDao {
|
|||||||
|
|
||||||
@Query("UPDATE captures SET status = 'synced', syncedAt = :syncedAt, lastError = NULL WHERE id = :id")
|
@Query("UPDATE captures SET status = 'synced', syncedAt = :syncedAt, lastError = NULL WHERE id = :id")
|
||||||
suspend fun markSynced(id: String, syncedAt: String)
|
suspend fun markSynced(id: String, syncedAt: String)
|
||||||
|
|
||||||
|
@Query("SELECT MAX(syncedAt) FROM captures WHERE syncedAt IS NOT NULL")
|
||||||
|
fun getLastSyncedAt(): Flow<String?>
|
||||||
|
|
||||||
|
@Query("SELECT tagsJson FROM captures WHERE tagsJson != '[]' AND tagsJson != '' ORDER BY createdAt DESC LIMIT 100")
|
||||||
|
fun getRecentTagsJson(): Flow<List<String>>
|
||||||
|
|
||||||
|
@Query("UPDATE captures SET body = :body WHERE id = :id")
|
||||||
|
suspend fun updateBody(id: String, body: String)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package me.hgsky.synq.data.sync
|
||||||
|
|
||||||
|
import me.hgsky.synq.data.SynqSettings
|
||||||
|
import me.hgsky.synq.data.api.PostResult
|
||||||
|
import me.hgsky.synq.data.api.SynqApiClient
|
||||||
|
import me.hgsky.synq.data.db.CaptureDao
|
||||||
|
import java.time.OffsetDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
|
suspend fun syncPending(dao: CaptureDao, client: SynqApiClient, settings: SynqSettings) {
|
||||||
|
val pending = dao.getPendingAndFailed()
|
||||||
|
for (capture in pending) {
|
||||||
|
dao.updateStatus(capture.id, "syncing", null)
|
||||||
|
val result = client.postCapture(capture, settings)
|
||||||
|
when (result) {
|
||||||
|
is PostResult.Accepted, is PostResult.AlreadySeen -> {
|
||||||
|
val now = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
|
||||||
|
dao.markSynced(capture.id, now)
|
||||||
|
}
|
||||||
|
is PostResult.Failed -> dao.updateStatus(capture.id, "failed", result.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package me.hgsky.synq.data.sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.work.Constraints
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
|
import androidx.work.NetworkType
|
||||||
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import me.hgsky.synq.SynqApp
|
||||||
|
import me.hgsky.synq.data.api.SynqApiClient
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result {
|
||||||
|
val app = applicationContext as SynqApp
|
||||||
|
val settings = app.settings.settings.first()
|
||||||
|
val client = SynqApiClient()
|
||||||
|
|
||||||
|
if (!client.checkHealth(settings.serverUrl)) return Result.success()
|
||||||
|
|
||||||
|
syncPending(app.db.captureDao(), client, settings)
|
||||||
|
return Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val WORK_NAME = "synq_periodic_sync"
|
||||||
|
|
||||||
|
fun schedule(context: Context, intervalMinutes: Int = 15) {
|
||||||
|
val constraints = Constraints.Builder()
|
||||||
|
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val request = PeriodicWorkRequestBuilder<SyncWorker>(
|
||||||
|
intervalMinutes.toLong().coerceAtLeast(15), TimeUnit.MINUTES,
|
||||||
|
)
|
||||||
|
.setConstraints(constraints)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
|
||||||
|
WORK_NAME,
|
||||||
|
ExistingPeriodicWorkPolicy.REPLACE,
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,28 @@
|
|||||||
package me.hgsky.synq.ui.capture
|
package me.hgsky.synq.ui.capture
|
||||||
|
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||||
|
import androidx.compose.foundation.layout.FlowRow
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.History
|
import androidx.compose.material.icons.filled.History
|
||||||
import androidx.compose.material.icons.filled.Settings
|
import androidx.compose.material.icons.filled.Settings
|
||||||
|
import androidx.compose.material.icons.filled.Sync
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
@@ -38,21 +46,59 @@ import androidx.compose.ui.text.input.KeyboardCapitalization
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
|
import java.time.OffsetDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun CaptureScreen(nav: NavController, vm: CaptureViewModel = viewModel()) {
|
fun CaptureScreen(
|
||||||
|
nav: NavController,
|
||||||
|
prefill: String? = null,
|
||||||
|
vm: CaptureViewModel = viewModel(),
|
||||||
|
) {
|
||||||
val state by vm.state.collectAsState()
|
val state by vm.state.collectAsState()
|
||||||
|
val recentTags by vm.recentTags.collectAsState()
|
||||||
|
val lastSyncedAt by vm.lastSyncedAt.collectAsState()
|
||||||
val focusRequester = remember { FocusRequester() }
|
val focusRequester = remember { FocusRequester() }
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
LaunchedEffect(Unit) { focusRequester.requestFocus() }
|
LaunchedEffect(Unit) { focusRequester.requestFocus() }
|
||||||
|
LaunchedEffect(prefill) {
|
||||||
|
if (!prefill.isNullOrEmpty()) vm.setBody(prefill)
|
||||||
|
}
|
||||||
|
|
||||||
|
val activeTags = remember(state.tags) {
|
||||||
|
state.tags.split(Regex("[,\\s]+")).filter { it.isNotEmpty() }.toSet()
|
||||||
|
}
|
||||||
|
|
||||||
|
val lastSyncedText = remember(lastSyncedAt) {
|
||||||
|
lastSyncedAt?.let { iso ->
|
||||||
|
runCatching {
|
||||||
|
val dt = OffsetDateTime.parse(iso)
|
||||||
|
"synced " + dt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = { Text("synq") },
|
title = { Text("synq") },
|
||||||
actions = {
|
actions = {
|
||||||
|
IconButton(
|
||||||
|
onClick = { vm.syncNow() },
|
||||||
|
enabled = !state.isSyncing,
|
||||||
|
) {
|
||||||
|
if (state.isSyncing) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
strokeWidth = 2.dp,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Icon(Icons.Default.Sync, contentDescription = "sync now")
|
||||||
|
}
|
||||||
|
}
|
||||||
IconButton(onClick = { nav.navigate("history") }) {
|
IconButton(onClick = { nav.navigate("history") }) {
|
||||||
Icon(Icons.Default.History, contentDescription = "history")
|
Icon(Icons.Default.History, contentDescription = "history")
|
||||||
}
|
}
|
||||||
@@ -104,10 +150,31 @@ fun CaptureScreen(nav: NavController, vm: CaptureViewModel = viewModel()) {
|
|||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (recentTags.isNotEmpty()) {
|
||||||
|
FlowRow(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
) {
|
||||||
|
recentTags.forEach { tag ->
|
||||||
|
FilterChip(
|
||||||
|
selected = tag in activeTags,
|
||||||
|
onClick = { vm.toggleTag(tag) },
|
||||||
|
label = { Text(tag, style = MaterialTheme.typography.labelSmall) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastSyncedText != null) {
|
||||||
|
Text(
|
||||||
|
lastSyncedText,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxWidth(),
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(bottom = 16.dp),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
) {
|
) {
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
@@ -122,6 +189,8 @@ fun CaptureScreen(nav: NavController, vm: CaptureViewModel = viewModel()) {
|
|||||||
enabled = state.body.isNotBlank(),
|
enabled = state.body.isNotBlank(),
|
||||||
) { Text("save & close") }
|
) { Text("save & close") }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,22 @@ package me.hgsky.synq.ui.capture
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.serialization.encodeToString
|
import kotlinx.serialization.encodeToString
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import me.hgsky.synq.SynqApp
|
import me.hgsky.synq.SynqApp
|
||||||
|
import me.hgsky.synq.data.api.SynqApiClient
|
||||||
import me.hgsky.synq.data.generateCaptureId
|
import me.hgsky.synq.data.generateCaptureId
|
||||||
import me.hgsky.synq.data.db.CaptureEntity
|
import me.hgsky.synq.data.db.CaptureEntity
|
||||||
|
import me.hgsky.synq.data.sync.syncPending
|
||||||
import java.time.OffsetDateTime
|
import java.time.OffsetDateTime
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
@@ -19,19 +26,42 @@ data class CaptureUiState(
|
|||||||
val body: String = "",
|
val body: String = "",
|
||||||
val isTodo: Boolean = false,
|
val isTodo: Boolean = false,
|
||||||
val tags: String = "",
|
val tags: String = "",
|
||||||
|
val isSyncing: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
class CaptureViewModel(app: Application) : AndroidViewModel(app) {
|
class CaptureViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
private val dao = (app as SynqApp).db.captureDao()
|
private val synqApp = app as SynqApp
|
||||||
|
private val dao = synqApp.db.captureDao()
|
||||||
|
|
||||||
private val _state = MutableStateFlow(CaptureUiState())
|
private val _state = MutableStateFlow(CaptureUiState())
|
||||||
val state: StateFlow<CaptureUiState> = _state.asStateFlow()
|
val state: StateFlow<CaptureUiState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
val recentTags: StateFlow<List<String>> = dao.getRecentTagsJson()
|
||||||
|
.map { jsonList ->
|
||||||
|
val seen = LinkedHashSet<String>()
|
||||||
|
for (json in jsonList) {
|
||||||
|
runCatching { Json.decodeFromString<List<String>>(json) }
|
||||||
|
.getOrElse { emptyList() }
|
||||||
|
.forEach { seen.add(it) }
|
||||||
|
}
|
||||||
|
seen.take(20).toList()
|
||||||
|
}
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||||
|
|
||||||
|
val lastSyncedAt: StateFlow<String?> = dao.getLastSyncedAt()
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
|
||||||
|
|
||||||
fun setBody(v: String) { _state.value = _state.value.copy(body = v) }
|
fun setBody(v: String) { _state.value = _state.value.copy(body = v) }
|
||||||
fun setTodo(v: Boolean) { _state.value = _state.value.copy(isTodo = v) }
|
fun setTodo(v: Boolean) { _state.value = _state.value.copy(isTodo = v) }
|
||||||
fun setTags(v: String) { _state.value = _state.value.copy(tags = v) }
|
fun setTags(v: String) { _state.value = _state.value.copy(tags = v) }
|
||||||
|
|
||||||
|
fun toggleTag(tag: String) {
|
||||||
|
val current = parseTags(_state.value.tags).toMutableList()
|
||||||
|
if (current.contains(tag)) current.remove(tag) else current.add(tag)
|
||||||
|
_state.value = _state.value.copy(tags = current.joinToString(" "))
|
||||||
|
}
|
||||||
|
|
||||||
fun save(onDone: () -> Unit = {}) {
|
fun save(onDone: () -> Unit = {}) {
|
||||||
val s = _state.value
|
val s = _state.value
|
||||||
val body = s.body.trim()
|
val body = s.body.trim()
|
||||||
@@ -51,11 +81,27 @@ class CaptureViewModel(app: Application) : AndroidViewModel(app) {
|
|||||||
status = "pending",
|
status = "pending",
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
_state.value = CaptureUiState()
|
_state.value = _state.value.copy(body = "", tags = "")
|
||||||
onDone()
|
onDone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun syncNow() {
|
||||||
|
if (_state.value.isSyncing) return
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
_state.value = _state.value.copy(isSyncing = true)
|
||||||
|
try {
|
||||||
|
val settings = synqApp.settings.settings.first()
|
||||||
|
val client = SynqApiClient()
|
||||||
|
if (client.checkHealth(settings.serverUrl)) {
|
||||||
|
syncPending(dao, client, settings)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
_state.value = _state.value.copy(isSyncing = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun parseTags(raw: String): List<String> =
|
private fun parseTags(raw: String): List<String> =
|
||||||
raw.split(Regex("[,\\s]+"))
|
raw.split(Regex("[,\\s]+"))
|
||||||
.map { it.trim() }
|
.map { it.trim() }
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package me.hgsky.synq.ui.history
|
package me.hgsky.synq.ui.history
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -12,18 +13,26 @@ import androidx.compose.foundation.lazy.LazyColumn
|
|||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.collectAsState
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
@@ -32,16 +41,40 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import me.hgsky.synq.data.db.CaptureEntity
|
import me.hgsky.synq.data.db.CaptureEntity
|
||||||
|
import java.time.OffsetDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun HistoryScreen(nav: NavController, vm: HistoryViewModel = viewModel()) {
|
fun HistoryScreen(nav: NavController, vm: HistoryViewModel = viewModel()) {
|
||||||
val captures by vm.captures.collectAsState(initial = emptyList())
|
val captures by vm.captures.collectAsState(initial = emptyList())
|
||||||
|
val lastSyncedAt by vm.lastSyncedAt.collectAsState()
|
||||||
|
|
||||||
|
val lastSyncedText = remember(lastSyncedAt) {
|
||||||
|
lastSyncedAt?.let { iso ->
|
||||||
|
runCatching {
|
||||||
|
val dt = OffsetDateTime.parse(iso)
|
||||||
|
"last synced " + dt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = { Text("history") },
|
title = {
|
||||||
|
Column {
|
||||||
|
Text("history")
|
||||||
|
if (lastSyncedText != null) {
|
||||||
|
Text(
|
||||||
|
lastSyncedText,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
IconButton(onClick = { nav.navigateUp() }) {
|
IconButton(onClick = { nav.navigateUp() }) {
|
||||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "back")
|
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "back")
|
||||||
@@ -62,7 +95,11 @@ fun HistoryScreen(nav: NavController, vm: HistoryViewModel = viewModel()) {
|
|||||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
) {
|
) {
|
||||||
items(captures, key = { it.id }) { capture ->
|
items(captures, key = { it.id }) { capture ->
|
||||||
CaptureRow(capture, onRetry = { vm.retryCapture(capture) })
|
CaptureRow(
|
||||||
|
capture = capture,
|
||||||
|
onRetry = { vm.retryCapture(capture) },
|
||||||
|
onEditConfirm = { newBody -> vm.updateBody(capture, newBody) },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,14 +107,56 @@ fun HistoryScreen(nav: NavController, vm: HistoryViewModel = viewModel()) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun CaptureRow(capture: CaptureEntity, onRetry: () -> Unit) {
|
private fun CaptureRow(
|
||||||
|
capture: CaptureEntity,
|
||||||
|
onRetry: () -> Unit,
|
||||||
|
onEditConfirm: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
var expanded by rememberSaveable(capture.id) { mutableStateOf(false) }
|
||||||
|
var showEdit by remember { mutableStateOf(false) }
|
||||||
|
var editBody by remember(capture.body) { mutableStateOf(capture.body) }
|
||||||
|
|
||||||
val statusColor = when (capture.status) {
|
val statusColor = when (capture.status) {
|
||||||
"synced" -> Color(0xFF2E7D32)
|
"synced" -> Color(0xFF2E7D32)
|
||||||
"failed" -> MaterialTheme.colorScheme.error
|
"failed" -> MaterialTheme.colorScheme.error
|
||||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
}
|
}
|
||||||
|
|
||||||
Card(modifier = Modifier.fillMaxWidth()) {
|
val editable = capture.status == "pending" || capture.status == "failed"
|
||||||
|
|
||||||
|
if (showEdit) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showEdit = false },
|
||||||
|
title = { Text("edit capture") },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = editBody,
|
||||||
|
onValueChange = { editBody = it },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("body") },
|
||||||
|
minLines = 3,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
onEditConfirm(editBody)
|
||||||
|
showEdit = false
|
||||||
|
},
|
||||||
|
enabled = editBody.isNotBlank(),
|
||||||
|
) { Text("save") }
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showEdit = false }) { Text("cancel") }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { expanded = !expanded },
|
||||||
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier.padding(12.dp),
|
modifier = Modifier.padding(12.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
@@ -96,18 +175,29 @@ private fun CaptureRow(capture: CaptureEntity, onRetry: () -> Unit) {
|
|||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = statusColor,
|
color = statusColor,
|
||||||
)
|
)
|
||||||
if (capture.status == "pending" || capture.status == "failed") {
|
if (editable) {
|
||||||
Button(onClick = onRetry, contentPadding = PaddingValues(horizontal = 8.dp)) {
|
OutlinedButton(
|
||||||
|
onClick = onRetry,
|
||||||
|
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||||
|
) {
|
||||||
Text("retry", style = MaterialTheme.typography.labelSmall)
|
Text("retry", style = MaterialTheme.typography.labelSmall)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (editable && expanded) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = { showEdit = true },
|
||||||
|
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||||
|
) {
|
||||||
|
Text("edit", style = MaterialTheme.typography.labelSmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
capture.body,
|
capture.body,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
maxLines = 2,
|
maxLines = if (expanded) Int.MAX_VALUE else 2,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = if (expanded) TextOverflow.Clip else TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
Text(
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import android.app.Application
|
|||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import me.hgsky.synq.SynqApp
|
import me.hgsky.synq.SynqApp
|
||||||
import me.hgsky.synq.data.db.CaptureEntity
|
import me.hgsky.synq.data.db.CaptureEntity
|
||||||
@@ -14,9 +17,18 @@ class HistoryViewModel(app: Application) : AndroidViewModel(app) {
|
|||||||
|
|
||||||
val captures: Flow<List<CaptureEntity>> = dao.observeAll()
|
val captures: Flow<List<CaptureEntity>> = dao.observeAll()
|
||||||
|
|
||||||
|
val lastSyncedAt: StateFlow<String?> = dao.getLastSyncedAt()
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
|
||||||
|
|
||||||
fun retryCapture(capture: CaptureEntity) {
|
fun retryCapture(capture: CaptureEntity) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
dao.updateStatus(capture.id, "pending", null)
|
dao.updateStatus(capture.id, "pending", null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun updateBody(capture: CaptureEntity, newBody: String) {
|
||||||
|
val trimmed = newBody.trim()
|
||||||
|
if (trimmed.isEmpty()) return
|
||||||
|
viewModelScope.launch { dao.updateBody(capture.id, trimmed) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,21 @@ package me.hgsky.synq.ui.settings
|
|||||||
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -21,7 +27,10 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
@@ -31,13 +40,22 @@ import me.hgsky.synq.data.SynqSettings
|
|||||||
@Composable
|
@Composable
|
||||||
fun SettingsScreen(nav: NavController, vm: SettingsViewModel = viewModel()) {
|
fun SettingsScreen(nav: NavController, vm: SettingsViewModel = viewModel()) {
|
||||||
val saved by vm.settings.collectAsState()
|
val saved by vm.settings.collectAsState()
|
||||||
|
val ping by vm.ping.collectAsState()
|
||||||
|
|
||||||
var url by remember(saved.serverUrl) { mutableStateOf(saved.serverUrl) }
|
var url by remember(saved.serverUrl) { mutableStateOf(saved.serverUrl) }
|
||||||
var token by remember(saved.token) { mutableStateOf(saved.token) }
|
var token by remember(saved.token) { mutableStateOf(saved.token) }
|
||||||
var device by remember(saved.deviceLabel) { mutableStateOf(saved.deviceLabel) }
|
var device by remember(saved.deviceLabel) { mutableStateOf(saved.deviceLabel) }
|
||||||
|
var interval by remember(saved.syncIntervalMinutes) { mutableStateOf(saved.syncIntervalMinutes.toString()) }
|
||||||
|
|
||||||
|
fun buildSettings() = SynqSettings(
|
||||||
|
serverUrl = url.trim(),
|
||||||
|
token = token.trim(),
|
||||||
|
deviceLabel = device.trim().ifEmpty { "android" },
|
||||||
|
syncIntervalMinutes = interval.toIntOrNull()?.coerceAtLeast(15) ?: 15,
|
||||||
|
)
|
||||||
|
|
||||||
fun saveAndBack() {
|
fun saveAndBack() {
|
||||||
vm.save(SynqSettings(url.trim(), token.trim(), device.trim().ifEmpty { "android" }))
|
vm.save(buildSettings())
|
||||||
nav.navigateUp()
|
nav.navigateUp()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,10 +99,55 @@ fun SettingsScreen(nav: NavController, vm: SettingsViewModel = viewModel()) {
|
|||||||
label = { Text("device label") },
|
label = { Text("device label") },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
Button(
|
OutlinedTextField(
|
||||||
onClick = ::saveAndBack,
|
value = interval,
|
||||||
|
onValueChange = { v -> if (v.length <= 4 && v.all { it.isDigit() }) interval = v },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) { Text("save") }
|
label = { Text("sync interval (minutes, min 15)") },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
|
supportingText = { Text("WorkManager minimum is 15 min") },
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
vm.save(buildSettings())
|
||||||
|
vm.checkConnection(url.trim())
|
||||||
|
},
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
enabled = ping !is PingState.Checking,
|
||||||
|
) {
|
||||||
|
if (ping is PingState.Checking) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||||
|
} else {
|
||||||
|
Text("check connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = ::saveAndBack,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
) { Text("save") }
|
||||||
|
}
|
||||||
|
|
||||||
|
when (val p = ping) {
|
||||||
|
is PingState.Ok -> Text(
|
||||||
|
"✓ reachable",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = Color(0xFF2E7D32),
|
||||||
|
)
|
||||||
|
is PingState.Failed -> Text(
|
||||||
|
"✗ unreachable — check URL and that server is running",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,29 @@ package me.hgsky.synq.ui.settings
|
|||||||
import android.app.Application
|
import android.app.Application
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import me.hgsky.synq.SynqApp
|
import me.hgsky.synq.SynqApp
|
||||||
import me.hgsky.synq.data.SynqSettings
|
import me.hgsky.synq.data.SynqSettings
|
||||||
|
import me.hgsky.synq.data.api.SynqApiClient
|
||||||
|
import me.hgsky.synq.data.sync.SyncWorker
|
||||||
|
|
||||||
|
sealed class PingState {
|
||||||
|
object Idle : PingState()
|
||||||
|
object Checking : PingState()
|
||||||
|
data class Ok(val url: String) : PingState()
|
||||||
|
data class Failed(val url: String) : PingState()
|
||||||
|
}
|
||||||
|
|
||||||
class SettingsViewModel(app: Application) : AndroidViewModel(app) {
|
class SettingsViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
private val repo = (app as SynqApp).settings
|
private val synqApp = app as SynqApp
|
||||||
|
private val repo = synqApp.settings
|
||||||
|
|
||||||
val settings = repo.settings.stateIn(
|
val settings = repo.settings.stateIn(
|
||||||
viewModelScope,
|
viewModelScope,
|
||||||
@@ -19,7 +33,22 @@ class SettingsViewModel(app: Application) : AndroidViewModel(app) {
|
|||||||
SynqSettings(),
|
SynqSettings(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private val _ping = MutableStateFlow<PingState>(PingState.Idle)
|
||||||
|
val ping: StateFlow<PingState> = _ping.asStateFlow()
|
||||||
|
|
||||||
fun save(settings: SynqSettings) {
|
fun save(settings: SynqSettings) {
|
||||||
viewModelScope.launch { repo.save(settings) }
|
viewModelScope.launch {
|
||||||
|
repo.save(settings)
|
||||||
|
SyncWorker.schedule(synqApp, settings.syncIntervalMinutes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkConnection(url: String) {
|
||||||
|
if (_ping.value is PingState.Checking) return
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
_ping.value = PingState.Checking
|
||||||
|
val ok = SynqApiClient().checkHealth(url.trim())
|
||||||
|
_ping.value = if (ok) PingState.Ok(url) else PingState.Failed(url)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id("com.android.application") version "8.7.3" apply false
|
id("com.android.application") version "8.13.2" apply false
|
||||||
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
||||||
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
||||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
|
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
BIN
docs/history-m2.png
Normal file
BIN
docs/history-m2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 90 KiB |
BIN
docs/home-m2.png
Normal file
BIN
docs/home-m2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 98 KiB |
BIN
docs/settings-m2.png
Normal file
BIN
docs/settings-m2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 82 KiB |
@@ -1,7 +1,9 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import secrets
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||||
from fastapi.exceptions import RequestValidationError
|
from fastapi.exceptions import RequestValidationError
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
@@ -10,11 +12,51 @@ from .models import CaptureRequest, CaptureResponse, HealthResponse
|
|||||||
from .org_writer import format_capture
|
from .org_writer import format_capture
|
||||||
from .store import IdempotencyStore, get_file_lock
|
from .store import IdempotencyStore, get_file_lock
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger("synq")
|
logger = logging.getLogger("synq")
|
||||||
|
|
||||||
app = FastAPI(title="synq", version="0.1.0")
|
@asynccontextmanager
|
||||||
|
async def lifespan(_: FastAPI):
|
||||||
|
_load_token()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="synq", version="0.1.0", lifespan=lifespan)
|
||||||
|
|
||||||
_store: IdempotencyStore | None = None
|
_store: IdempotencyStore | None = None
|
||||||
|
_token_cache: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _load_token() -> str:
|
||||||
|
global _token_cache
|
||||||
|
if _token_cache:
|
||||||
|
return _token_cache
|
||||||
|
|
||||||
|
env_token = os.environ.get("PHONE_CAPTURE_TOKEN", "").strip()
|
||||||
|
if env_token and env_token != "change-me" and env_token != "change-me-long-random-token":
|
||||||
|
_token_cache = env_token
|
||||||
|
return _token_cache
|
||||||
|
|
||||||
|
token_file = Path(os.environ.get("PHONE_CAPTURE_DB_PATH", "/data/capture.sqlite3")).parent / "token.txt"
|
||||||
|
if token_file.exists():
|
||||||
|
stored = token_file.read_text().strip()
|
||||||
|
if stored:
|
||||||
|
_token_cache = stored
|
||||||
|
logger.info("synq token loaded from %s", token_file)
|
||||||
|
return _token_cache
|
||||||
|
|
||||||
|
generated = secrets.token_hex(32)
|
||||||
|
token_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
token_file.write_text(generated)
|
||||||
|
logger.info("")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
logger.info(" SYNQ TOKEN (paste into app settings):")
|
||||||
|
logger.info(" %s", generated)
|
||||||
|
logger.info("=" * 60)
|
||||||
|
logger.info("")
|
||||||
|
_token_cache = generated
|
||||||
|
return _token_cache
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def get_store() -> IdempotencyStore:
|
def get_store() -> IdempotencyStore:
|
||||||
@@ -30,7 +72,7 @@ def _org_path() -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _token() -> str:
|
def _token() -> str:
|
||||||
return os.environ.get("PHONE_CAPTURE_TOKEN", "")
|
return _load_token()
|
||||||
|
|
||||||
|
|
||||||
async def check_token(request: Request) -> None:
|
async def check_token(request: Request) -> None:
|
||||||
@@ -40,6 +82,7 @@ async def check_token(request: Request) -> None:
|
|||||||
auth = request.headers.get("authorization", "")
|
auth = request.headers.get("authorization", "")
|
||||||
scheme, _, provided = auth.partition(" ")
|
scheme, _, provided = auth.partition(" ")
|
||||||
if scheme.lower() != "bearer" or provided != expected:
|
if scheme.lower() != "bearer" or provided != expected:
|
||||||
|
logger.warning("rejected request: invalid token from %s", request.client.host if request.client else "unknown")
|
||||||
raise HTTPException(status_code=401, detail="unauthorized")
|
raise HTTPException(status_code=401, detail="unauthorized")
|
||||||
|
|
||||||
|
|
||||||
@@ -59,7 +102,10 @@ async def capture(payload: CaptureRequest, store: IdempotencyStore = Depends(get
|
|||||||
|
|
||||||
lock = get_file_lock()
|
lock = get_file_lock()
|
||||||
with lock:
|
with lock:
|
||||||
Path(org_path).parent.mkdir(parents=True, exist_ok=True)
|
org_file = Path(org_path)
|
||||||
|
org_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not org_file.exists():
|
||||||
|
org_file.write_text("#+title: synq captures\n#+startup: overview\n\n", encoding="utf-8")
|
||||||
with open(org_path, "a", encoding="utf-8") as f:
|
with open(org_path, "a", encoding="utf-8") as f:
|
||||||
f.write(entry)
|
f.write(entry)
|
||||||
store.mark_seen(payload.id, payload.created_at)
|
store.mark_seen(payload.id, payload.created_at)
|
||||||
@@ -71,6 +117,8 @@ async def capture(payload: CaptureRequest, store: IdempotencyStore = Depends(get
|
|||||||
@app.exception_handler(RequestValidationError)
|
@app.exception_handler(RequestValidationError)
|
||||||
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||||
errors = exc.errors()
|
errors = exc.errors()
|
||||||
|
fields = [str(e.get("loc", "")) for e in errors]
|
||||||
|
logger.warning("rejected payload: validation failed fields=%s from=%s", fields, request.client.host if request.client else "unknown")
|
||||||
for err in errors:
|
for err in errors:
|
||||||
if "body" in err.get("loc", ()):
|
if "body" in err.get("loc", ()):
|
||||||
return JSONResponse(status_code=400, content={"detail": "body must not be empty"})
|
return JSONResponse(status_code=400, content={"detail": "body must not be empty"})
|
||||||
|
|||||||
165
tasks.org
165
tasks.org
@@ -43,8 +43,10 @@ the app must be instant-feeling, capture-only, and boring. the phone stores note
|
|||||||
*** acceptance
|
*** acceptance
|
||||||
- `android/`, `server/`, and `docs/` directories exist.
|
- `android/`, `server/`, and `docs/` directories exist.
|
||||||
- root `README.md`, `tasks.org`, `.env.example`, and `docker-compose.example.yml` exist.
|
- root `README.md`, `tasks.org`, `.env.example`, and `docker-compose.example.yml` exist.
|
||||||
|
|
||||||
*** notes
|
*** notes
|
||||||
Skeleton committed in initial commit. android/ dir will be created in milestone 2.
|
Skeleton committed in initial commit. android/ dir will be created in milestone 2.
|
||||||
|
|
||||||
*** evidence
|
*** evidence
|
||||||
- commit: c08b3fe
|
- commit: c08b3fe
|
||||||
- tests: n/a (directory structure)
|
- tests: n/a (directory structure)
|
||||||
@@ -203,8 +205,10 @@ server/Dockerfile uses python:3.11-slim, installs deps, copies app/, exposes 876
|
|||||||
- jetpack compose enabled.
|
- jetpack compose enabled.
|
||||||
- min sdk is reasonable for current personal device.
|
- min sdk is reasonable for current personal device.
|
||||||
- app id is stable, e.g. `me.hgsky.phonecapture`.
|
- app id is stable, e.g. `me.hgsky.phonecapture`.
|
||||||
|
|
||||||
*** notes
|
*** notes
|
||||||
Gradle project in android/. AGP 8.7.3, Kotlin 2.0.21, Compose BOM 2024.10.01. minSdk=31, compileSdk=36. App ID is me.hgsky.synq. Open android/ in Android Studio and hit Sync — AS will download the Gradle wrapper (8.9) automatically.
|
Gradle project in android/. AGP 8.7.3, Kotlin 2.0.21, Compose BOM 2024.10.01. minSdk=31, compileSdk=36. App ID is me.hgsky.synq. Open android/ in Android Studio and hit Sync — AS will download the Gradle wrapper (8.9) automatically.
|
||||||
|
|
||||||
*** evidence
|
*** evidence
|
||||||
- commit: 19b05a8
|
- commit: 19b05a8
|
||||||
- tests: Gradle sync in Android Studio (manual step)
|
- tests: Gradle sync in Android Studio (manual step)
|
||||||
@@ -232,12 +236,14 @@ CaptureScreen.kt uses LaunchedEffect(Unit) { focusRequester.requestFocus() } for
|
|||||||
- pending captures survive app restart.
|
- pending captures survive app restart.
|
||||||
*** notes
|
*** notes
|
||||||
CaptureEntity, CaptureDao, CaptureDatabase in data/db/. Tags stored as JSON string (kotlinx-serialization). DB name synq.db, singleton via companion object. Room persists across restarts by default.
|
CaptureEntity, CaptureDao, CaptureDatabase in data/db/. Tags stored as JSON string (kotlinx-serialization). DB name synq.db, singleton via companion object. Room persists across restarts by default.
|
||||||
|
|
||||||
*** evidence
|
*** evidence
|
||||||
- commit: 19b05a8
|
- commit: 19b05a8
|
||||||
- tests: manual — save a capture, force-close app, reopen and check history
|
- tests: manual — save a capture, force-close app, reopen and check history
|
||||||
- datetime: [2026-05-18 Sun 17:00]
|
- datetime: [2026-05-18 Sun 17:00]
|
||||||
|
|
||||||
** DONE implement capture id generation
|
** DONE implement capture id generation
|
||||||
|
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- id format is stable and readable, e.g. `phone-yyyymmdd-hhmmss-rand`.
|
- id format is stable and readable, e.g. `phone-yyyymmdd-hhmmss-rand`.
|
||||||
- ids are generated client-side.
|
- ids are generated client-side.
|
||||||
@@ -262,75 +268,208 @@ HistoryScreen.kt observes captureDao.observeAll() as Flow. Status colored green/
|
|||||||
- tests: manual — save captures, navigate to history, verify status labels and retry button
|
- tests: manual — save captures, navigate to history, verify status labels and retry button
|
||||||
- datetime: [2026-05-18 Sun 17:00]
|
- datetime: [2026-05-18 Sun 17:00]
|
||||||
|
|
||||||
|
** DONE Checkout tests
|
||||||
|
[2026-05-18 Mon 12:40]
|
||||||
|
- updated Android Studio, ran Upgrade Assistant for Android Gradle Plugin to 8.13.2
|
||||||
|
- added Pixel 8 emulator
|
||||||
|
- ran a few fixes:
|
||||||
|
- `779ad6` - upped app memory to 2GB from 500MB - investigate?
|
||||||
|
- `7671416` - app.settings needs the SynqApp cast — same as dao. And it's unused in milestone 2 anyway, so just removed it
|
||||||
|
|
||||||
* milestone 3: android sync
|
* milestone 3: android sync
|
||||||
** TODO implement api client
|
** DONE implement api client
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- base url configurable in app settings or build config.
|
- base url configurable in app settings or build config.
|
||||||
- bearer token configurable in app settings or build config.
|
- bearer token configurable in app settings or build config.
|
||||||
- client can call `/health`.
|
- client can call `/health`.
|
||||||
- client can post capture payload.
|
- client can post capture payload.
|
||||||
** TODO implement manual sync
|
*** notes
|
||||||
|
SynqApiClient in data/api/. OkHttp with 10s timeouts. checkHealth() does GET /health, returns false on any exception so callers never crash. postCapture() maps 401 → failed, non-2xx → failed, already_seen → AlreadySeen, else → Accepted. Uses org.json for request building, kotlinx-serialization for tag decoding.
|
||||||
|
*** evidence
|
||||||
|
- commit: 2a963d9
|
||||||
|
- tests: manual — sync now button, check history screen status
|
||||||
|
- datetime: [2026-05-18 Sun 18:00]
|
||||||
|
|
||||||
|
** DONE implement manual sync
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- sync now posts all pending captures.
|
- sync now posts all pending captures.
|
||||||
- successful posts mark rows synced.
|
- successful posts mark rows synced.
|
||||||
- already-seen response marks row synced.
|
- already-seen response marks row synced.
|
||||||
- failures retain pending/failed status and last error.
|
- failures retain pending/failed status and last error.
|
||||||
** TODO implement opportunistic workmanager sync
|
*** notes
|
||||||
|
syncPending() top-level function in data/sync/SyncService.kt — shared by manual sync and WorkManager. CaptureViewModel.syncNow() calls it on Dispatchers.IO, guards with isSyncing flag. Sync icon in top bar shows CircularProgressIndicator while running.
|
||||||
|
*** evidence
|
||||||
|
- commit: 2a963d9
|
||||||
|
- tests: manual — tap sync, verify captures move to synced in history; test with wrong token, verify failed + error message
|
||||||
|
- datetime: [2026-05-18 Sun 18:00]
|
||||||
|
|
||||||
|
** DONE implement opportunistic workmanager sync
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- periodic sync is registered.
|
- periodic sync is registered.
|
||||||
- sync only runs when network is available.
|
- sync only runs when network is available.
|
||||||
- worker first checks `/health`.
|
- worker first checks `/health`.
|
||||||
- worker does not block capture speed.
|
- worker does not block capture speed.
|
||||||
** TODO add simple server reachability settings
|
*** notes
|
||||||
|
SyncWorker (CoroutineWorker) in data/sync/. Registered in SynqApp.onCreate() as KEEP unique periodic work (15-min interval, NETWORK_CONNECTED constraint). Health check before sync — exits quietly if server unreachable. Does not touch UI thread.
|
||||||
|
*** evidence
|
||||||
|
- commit: 2a963d9
|
||||||
|
- tests: manual — let app sit on WiFi, verify pending captures eventually sync without manual trigger
|
||||||
|
- datetime: [2026-05-18 Sun 18:00]
|
||||||
|
|
||||||
|
** DONE add simple server reachability settings
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- default url can be set to `http://jeeves.mother:8765`.
|
- default url can be set to `http://jeeves.mother:8765`.
|
||||||
- user can change server url.
|
- user can change server url.
|
||||||
- user can change token.
|
- user can change token.
|
||||||
- invalid settings do not crash app.
|
- invalid settings do not crash app.
|
||||||
|
*** notes
|
||||||
|
SettingsScreen + SettingsViewModel from milestone 2. DataStore-backed. Default serverUrl is http://jeeves.mother:8765. All network calls wrap exceptions so invalid URL/token never crashes — they just produce PostResult.Failed with the error message.
|
||||||
|
*** evidence
|
||||||
|
- commit: 19b05a8 (screen), 2a963d9 (wired to sync)
|
||||||
|
- tests: manual — set bad URL, tap sync, verify captures stay pending/failed with error; set correct URL + token, sync succeeds
|
||||||
|
- datetime: [2026-05-18 Sun 18:00]
|
||||||
|
|
||||||
* milestone 4: polish and hardening
|
* milestone 4: polish and hardening
|
||||||
** TODO make launch path fast
|
** DONE make launch path fast
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- app opens directly to capture field.
|
- app opens directly to capture field.
|
||||||
- no network call blocks launch.
|
- no network call blocks launch.
|
||||||
- no history loading blocks text entry.
|
- no history loading blocks text entry.
|
||||||
** TODO normalize tags
|
*** notes
|
||||||
|
LaunchedEffect(Unit) { focusRequester.requestFocus() } fires immediately on composition. No network calls in MainActivity or CaptureScreen init path. History loads via Room Flow on a background coroutine — never blocks text entry.
|
||||||
|
*** evidence
|
||||||
|
- commit: 19b05a8
|
||||||
|
- tests: manual — cold launch, keyboard appears without any loading state
|
||||||
|
- datetime: [2026-05-18 Sun 19:00]
|
||||||
|
|
||||||
|
** DONE normalize tags
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- whitespace-separated and comma-separated tags both work.
|
- whitespace-separated and comma-separated tags both work.
|
||||||
- invalid org tag chars are stripped or replaced.
|
- invalid org tag chars are stripped or replaced.
|
||||||
- duplicate tags collapse.
|
- duplicate tags collapse.
|
||||||
** TODO handle multiline notes well
|
*** notes
|
||||||
|
Two-layer normalization: parseTags() in CaptureViewModel splits on [,\s]+ before storing to Room. normalize_tags() in server/app/org_writer.py lowercases, strips #, replaces spaces with _, removes non-[a-z0-9_] chars, deduplicates. 7 unit tests cover all cases.
|
||||||
|
*** evidence
|
||||||
|
- commit: e873a00 (server), 19b05a8 (android)
|
||||||
|
- tests: pytest tests/test_org_writer.py::TestNormalizeTags — 7 passed
|
||||||
|
- datetime: [2026-05-18 Sun 19:00]
|
||||||
|
|
||||||
|
** DONE fix org formatting
|
||||||
|
*** acceptance
|
||||||
|
- add `#+startup: overview` to synq.org
|
||||||
|
*** notes
|
||||||
|
Append writer in main.py checks if org file exists before first write. If missing, creates it with #+title and #+startup: overview header. Existing files are never modified.
|
||||||
|
*** evidence
|
||||||
|
- commit: fd28a45
|
||||||
|
- tests: manual — delete synq.org, post a capture, verify header present
|
||||||
|
- datetime: [2026-05-18 Sun 19:00]
|
||||||
|
|
||||||
|
** DONE handle multiline notes well
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- first line can become note heading if body is multiline.
|
- first line can become note heading if body is multiline.
|
||||||
- full body is preserved under heading.
|
- full body is preserved under heading.
|
||||||
- todo body remains usable as a single todo heading, with extra lines under it if present.
|
- todo body remains usable as a single todo heading, with extra lines under it if present.
|
||||||
** TODO add basic logs
|
*** notes
|
||||||
|
format_capture() in org_writer.py: multiline note uses first line as heading suffix ("* note: <first line>"), full body preserved below drawer. Single-line note uses "* note" heading, body below. Covered by test_note_multiline.
|
||||||
|
*** evidence
|
||||||
|
- commit: e873a00
|
||||||
|
- tests: pytest tests/test_org_writer.py::TestFormatCapture::test_note_multiline — passed
|
||||||
|
- datetime: [2026-05-17 Sat 17:00]
|
||||||
|
|
||||||
|
** DONE add basic logs
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- server logs accepted capture id.
|
- server logs accepted capture id.
|
||||||
- server logs duplicate capture id.
|
- server logs duplicate capture id.
|
||||||
- server logs rejected payload without dumping secrets.
|
- server logs rejected payload without dumping secrets.
|
||||||
** TODO create backup note
|
*** notes
|
||||||
|
logger.info for accepted and duplicate (id only, no body). logger.warning for invalid token (client IP only, no token value logged). logger.warning for validation errors (field names only, no body content).
|
||||||
|
*** evidence
|
||||||
|
- commit: fd28a45
|
||||||
|
- tests: manual — send bad token, send empty body, check uvicorn stdout
|
||||||
|
- datetime: [2026-05-18 Sun 19:00]
|
||||||
|
|
||||||
|
** DONE create backup note
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- readme documents which paths need backup.
|
- readme documents which paths need backup.
|
||||||
- readme documents restore behavior.
|
- readme documents restore behavior.
|
||||||
|
*** notes
|
||||||
|
Added "backup" section to README.md covering synq.org, capture.sqlite3, token.txt. Restore section documents behavior when each file is lost individually.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: n/a
|
||||||
|
- datetime: [2026-05-18 Sun 19:00]
|
||||||
|
|
||||||
* milestone 5: optional v1.5
|
* milestone 5: optional v1.5 improvements
|
||||||
** TODO add android share target
|
** DONE add android share target
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- sharing text to app opens prefilled capture.
|
- sharing text to app opens prefilled capture.
|
||||||
- user can save as note or todo.
|
- user can save as note or todo.
|
||||||
|
*** notes
|
||||||
|
ACTION_SEND text/plain intent-filter added to MainActivity in manifest. MainActivity.onCreate extracts EXTRA_TEXT and passes it as a URL-encoded nav argument to the capture/{prefill} route. CaptureScreen applies it via LaunchedEffect on first composition.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — share any text from browser/notes to synq, verify it pre-fills capture body
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
** TODO add home screen quick capture widget
|
** TODO add home screen quick capture widget
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- widget opens capture screen quickly.
|
- widget opens capture screen quickly.
|
||||||
- does not require sync to work.
|
- does not require sync to work.
|
||||||
** TODO add recent tag chips
|
|
||||||
|
** DONE add recent tag chips
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- app shows recent tags.
|
- app shows recent tags.
|
||||||
- tapping chip adds/removes tag.
|
- tapping chip adds/removes tag.
|
||||||
** TODO add edit-before-sync
|
*** notes
|
||||||
|
CaptureViewModel.recentTags collects the last 100 capture tagsJson rows, decodes each JSON array, flattens and deduplicates (LinkedHashSet order), limits to 20. CaptureScreen shows a FlowRow of FilterChip below the tags text field. Tapping a chip calls toggleTag() which adds/removes it from the tags string. Active chips are highlighted via FilterChip selected=true.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — save a few captures with tags, open capture screen, verify chips appear and toggle
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
|
** DONE add edit-before-sync
|
||||||
*** acceptance
|
*** acceptance
|
||||||
- pending/failed captures can be edited.
|
- pending/failed captures can be edited.
|
||||||
- synced captures are read-only unless explicitly duplicated.
|
- synced captures are read-only unless explicitly duplicated.
|
||||||
|
*** notes
|
||||||
|
CaptureDao.updateBody() new query. HistoryViewModel.updateBody() calls it. HistoryScreen CaptureRow shows "edit" OutlinedButton only when expanded AND status is pending/failed. Tapping edit opens an AlertDialog with an OutlinedTextField pre-filled with current body. Save calls updateBody; cancel dismisses.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — save a capture, open history, expand row, tap edit, change body, save, verify updated
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
|
** DONE tap to expand history item
|
||||||
|
*** acceptance
|
||||||
|
- tapping a history row expands/collapses it.
|
||||||
|
- expanded row shows full body.
|
||||||
|
- edit button is only visible when expanded.
|
||||||
|
*** notes
|
||||||
|
CaptureRow uses rememberSaveable expanded: Boolean keyed on capture.id. Card has clickable { expanded = !expanded }. maxLines switches between 2 and Int.MAX_VALUE. Edit button only renders when expanded && editable.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — tap history rows to expand/collapse, verify full body visible when expanded
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
|
** DONE add "Last synced" display
|
||||||
|
*** acceptance
|
||||||
|
- "last synced at" visible in history top bar and capture screen.
|
||||||
|
*** notes
|
||||||
|
CaptureDao.getLastSyncedAt() returns Flow<String?> of MAX(syncedAt). HistoryViewModel and CaptureViewModel both stateIn this flow. HistoryScreen shows it as a subtitle under "history" in the TopAppBar. CaptureScreen shows it as a small label above the save buttons. Both parse the ISO string via OffsetDateTime and format with DateTimeFormatter.ofLocalizedDateTime(SHORT).
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — sync a capture, verify timestamp appears in history header and capture screen
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
|
** DONE add settings for sync frequency
|
||||||
|
*** acceptance
|
||||||
|
- user-specified poll rate in minutes (min 15).
|
||||||
|
- changing interval reschedules WorkManager immediately.
|
||||||
|
*** notes
|
||||||
|
SynqSettings gained syncIntervalMinutes: Int = 15 field with DataStore key sync_interval_minutes. SettingsScreen added OutlinedTextField with number keyboard for interval, shows supporting text "WorkManager minimum is 15 min". buildSettings() coerces to max(value, 15). SettingsViewModel.save() now also calls SyncWorker.schedule(app, settings.syncIntervalMinutes). SyncWorker.schedule() uses REPLACE policy so new interval takes effect immediately.
|
||||||
|
*** evidence
|
||||||
|
- commit: 66155f6
|
||||||
|
- tests: manual — change interval to 30, save, verify WorkManager re-queues (check adb shell dumpsys jobscheduler)
|
||||||
|
- datetime: [2026-05-18 Sun 20:00]
|
||||||
|
|
||||||
* implementation notes for coding agents
|
* implementation notes for coding agents
|
||||||
- keep the server small and testable.
|
- keep the server small and testable.
|
||||||
|
|||||||
Reference in New Issue
Block a user