fix: sync completion across clients and restore Windows build
- Guard SystemTray DBus members correctly for MinGW builds\n- Let remote done override local scheduled/in-progress despite clock skew\n- Add Android start/lead reminders and lead-minute setting\n- Use expedited WorkManager for local Android changes\n- Add desktop/Android completion and reminder validation
This commit is contained in:
@@ -6,6 +6,7 @@ import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.OutOfQuotaPolicy
|
||||
import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import com.misaki.schedule.data.Prefs
|
||||
@@ -55,6 +56,7 @@ object BackgroundScheduler {
|
||||
.build()
|
||||
val request = OneTimeWorkRequestBuilder<SyncWorker>()
|
||||
.setConstraints(constraints)
|
||||
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
|
||||
.build()
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
SYNC_NOW_WORK,
|
||||
|
||||
@@ -43,6 +43,35 @@ object NotificationHelper {
|
||||
}
|
||||
|
||||
fun notifyReminder(context: Context, item: ScheduleItem): Boolean {
|
||||
val range = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
|
||||
return notify(
|
||||
context,
|
||||
item,
|
||||
context.getString(R.string.reminder_title),
|
||||
context.getString(R.string.reminder_text, item.task.title, range),
|
||||
)
|
||||
}
|
||||
|
||||
fun notifyLead(context: Context, item: ScheduleItem, minutesBefore: Int): Boolean {
|
||||
val text = context.getString(
|
||||
R.string.reminder_lead_text,
|
||||
item.task.title,
|
||||
minutesBefore,
|
||||
TimeUtils.formatTime(item.block.startAt),
|
||||
)
|
||||
return notify(context, item, context.getString(R.string.reminder_lead_title), text)
|
||||
}
|
||||
|
||||
fun notifyStart(context: Context, item: ScheduleItem): Boolean {
|
||||
val text = context.getString(
|
||||
R.string.reminder_start_text,
|
||||
item.task.title,
|
||||
TimeUtils.formatRange(item.block.startAt, item.block.endAt),
|
||||
)
|
||||
return notify(context, item, context.getString(R.string.reminder_start_title), text)
|
||||
}
|
||||
|
||||
private fun notify(context: Context, item: ScheduleItem, title: String, text: String): Boolean {
|
||||
if (!canNotify(context)) return false
|
||||
ensureChannel(context)
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
@@ -55,11 +84,9 @@ object NotificationHelper {
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val range = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
|
||||
val text = context.getString(R.string.reminder_text, item.task.title, range)
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.reminder_title))
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.misaki.schedule.background
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.misaki.schedule.data.Prefs
|
||||
import com.misaki.schedule.data.ScheduleRepository
|
||||
import com.misaki.schedule.data.TimeUtils
|
||||
|
||||
@@ -14,6 +15,7 @@ class ReminderWorker(appContext: Context, params: WorkerParameters) : CoroutineW
|
||||
return Result.success()
|
||||
}
|
||||
val repository = ScheduleRepository(applicationContext)
|
||||
val prefs = Prefs(applicationContext)
|
||||
val now = TimeUtils.nowIso()
|
||||
val since = TimeUtils.hoursAgo(24)
|
||||
val pending = repository.pendingReminders(now, since)
|
||||
@@ -22,6 +24,33 @@ class ReminderWorker(appContext: Context, params: WorkerParameters) : CoroutineW
|
||||
repository.markReminderSent(key, item.block.id, now)
|
||||
}
|
||||
}
|
||||
|
||||
val leadMinutes = prefs.reminderLeadMinutes
|
||||
val nowInstant = java.time.Instant.now()
|
||||
val horizon = TimeUtils.iso(nowInstant.plusSeconds(maxOf(leadMinutes, 20) * 60L))
|
||||
val active = repository.upcomingReminderCandidates(now, horizon)
|
||||
for (item in active) {
|
||||
val start = TimeUtils.parse(item.block.startAt) ?: continue
|
||||
val end = TimeUtils.parse(item.block.endAt) ?: continue
|
||||
val startKey = "${item.block.id}@${item.block.startAt}@start"
|
||||
val leadKey = "${item.block.id}@${item.block.startAt}@lead@${leadMinutes}"
|
||||
if (leadMinutes > 0 &&
|
||||
!nowInstant.isBefore(start.minusSeconds(leadMinutes * 60L)) &&
|
||||
nowInstant.isBefore(start) &&
|
||||
!repository.isReminderSent(leadKey) &&
|
||||
NotificationHelper.notifyLead(applicationContext, item, leadMinutes)
|
||||
) {
|
||||
repository.markReminderSent(leadKey, item.block.id, now)
|
||||
}
|
||||
if (!nowInstant.isBefore(start) &&
|
||||
nowInstant.isBefore(end) &&
|
||||
nowInstant.isBefore(start.plusSeconds(20 * 60L)) &&
|
||||
!repository.isReminderSent(startKey) &&
|
||||
NotificationHelper.notifyStart(applicationContext, item)
|
||||
) {
|
||||
repository.markReminderSent(startKey, item.block.id, now)
|
||||
}
|
||||
}
|
||||
Result.success()
|
||||
} catch (_: Exception) {
|
||||
Result.retry()
|
||||
|
||||
@@ -27,6 +27,10 @@ class Prefs(context: Context) {
|
||||
get() = prefs.getString("token", "").orEmpty()
|
||||
set(value) = prefs.edit().putString("token", value).apply()
|
||||
|
||||
var reminderLeadMinutes: Int
|
||||
get() = prefs.getInt("reminder_lead_minutes", 10).coerceIn(0, 24 * 60)
|
||||
set(value) = prefs.edit().putInt("reminder_lead_minutes", value.coerceIn(0, 24 * 60)).apply()
|
||||
|
||||
val deviceId: String
|
||||
get() = generatedDeviceId
|
||||
|
||||
|
||||
@@ -53,6 +53,8 @@ object TimeUtils {
|
||||
|
||||
fun nowIso(): String = isoFormatter.format(Instant.now().truncatedTo(ChronoUnit.MILLIS))
|
||||
|
||||
fun iso(value: Instant): String = isoFormatter.format(value.truncatedTo(ChronoUnit.MILLIS))
|
||||
|
||||
fun toIso(local: LocalDateTime): String =
|
||||
isoFormatter.format(local.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.MILLIS))
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import com.misaki.schedule.sync.CompletionMerge
|
||||
import com.misaki.schedule.sync.JsonCodec
|
||||
import com.misaki.schedule.sync.Lww
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -210,6 +211,36 @@ class ScheduleRepository(context: Context) {
|
||||
return result
|
||||
}
|
||||
|
||||
fun upcomingReminderCandidates(nowIso: String, horizonIso: String): List<ScheduleItem> {
|
||||
val result = mutableListOf<ScheduleItem>()
|
||||
db.rawQuery(
|
||||
"""
|
||||
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
|
||||
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
|
||||
t.version, t.device_id,
|
||||
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
|
||||
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id
|
||||
FROM timeblock b JOIN task t ON t.id = b.task_id
|
||||
WHERE b.status IN ('scheduled', 'in_progress')
|
||||
AND b.start_at <= ? AND b.end_at > ?
|
||||
ORDER BY b.start_at ASC
|
||||
LIMIT 50
|
||||
""".trimIndent(),
|
||||
arrayOf(horizonIso, nowIso)
|
||||
).use { cursor ->
|
||||
while (cursor.moveToNext()) {
|
||||
result.add(readItem(cursor))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun isReminderSent(key: String): Boolean {
|
||||
db.rawQuery("SELECT 1 FROM reminder_sent WHERE key = ?", arrayOf(key)).use { cursor ->
|
||||
return cursor.moveToFirst()
|
||||
}
|
||||
}
|
||||
|
||||
fun markReminderSent(key: String, blockId: String, sentAt: String) {
|
||||
val values = ContentValues().apply {
|
||||
put("key", key)
|
||||
@@ -235,9 +266,16 @@ class ScheduleRepository(context: Context) {
|
||||
val entityId = change.optString("entity_id")
|
||||
val op = change.optString("op")
|
||||
val remoteUpdated = change.optString("updated_at")
|
||||
val payload = change.optJSONObject("payload")
|
||||
val localUpdated = localUpdatedAt(database, entityType, entityId)
|
||||
val equalWins = op == "delete"
|
||||
if (!Lww.shouldApply(localUpdated, remoteUpdated, equalWins)) continue
|
||||
val forceCompletion = CompletionMerge.remoteCompletionWins(
|
||||
entityType,
|
||||
op,
|
||||
localBlockStatus(database, entityId),
|
||||
payload?.optString("status"),
|
||||
)
|
||||
if (!forceCompletion && !Lww.shouldApply(localUpdated, remoteUpdated, equalWins)) continue
|
||||
if (op == "delete") {
|
||||
when (entityType) {
|
||||
"task" -> database.delete("task", "id = ?", arrayOf(entityId))
|
||||
@@ -245,7 +283,7 @@ class ScheduleRepository(context: Context) {
|
||||
}
|
||||
applied++
|
||||
} else if (op == "upsert") {
|
||||
val payload = change.optJSONObject("payload") ?: continue
|
||||
if (payload == null) continue
|
||||
when (entityType) {
|
||||
"task" -> {
|
||||
payload.put("updated_at", remoteUpdated)
|
||||
@@ -339,6 +377,12 @@ class ScheduleRepository(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun localBlockStatus(database: SQLiteDatabase, blockId: String): String? {
|
||||
database.rawQuery("SELECT status FROM timeblock WHERE id = ?", arrayOf(blockId)).use { cursor ->
|
||||
return if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||
}
|
||||
}
|
||||
|
||||
private fun taskExists(database: SQLiteDatabase, taskId: String): Boolean {
|
||||
database.rawQuery("SELECT 1 FROM task WHERE id = ?", arrayOf(taskId)).use { cursor ->
|
||||
return cursor.moveToFirst()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.misaki.schedule.sync
|
||||
|
||||
object CompletionMerge {
|
||||
fun remoteCompletionWins(
|
||||
entityType: String,
|
||||
op: String,
|
||||
localStatus: String?,
|
||||
remoteStatus: String?,
|
||||
): Boolean =
|
||||
entityType == "timeblock" &&
|
||||
op == "upsert" &&
|
||||
remoteStatus == "done" &&
|
||||
(localStatus == "scheduled" || localStatus == "in_progress")
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.misaki.schedule.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.widget.ArrayAdapter
|
||||
import android.widget.Spinner
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import com.google.android.material.materialswitch.MaterialSwitch
|
||||
import com.google.android.material.textfield.TextInputEditText
|
||||
@@ -15,6 +17,11 @@ object SettingsDialog {
|
||||
val view = LayoutInflater.from(context).inflate(R.layout.dialog_settings, null)
|
||||
val url = view.findViewById<TextInputEditText>(R.id.serverUrlInput)
|
||||
val enabled = view.findViewById<MaterialSwitch>(R.id.syncSwitch)
|
||||
val lead = view.findViewById<Spinner>(R.id.leadSpinner)
|
||||
val leadValues = intArrayOf(0, 5, 10, 15, 30, 60)
|
||||
val leadLabels = leadValues.map { if (it == 0) "仅开始时" else "提前 $it 分钟" }
|
||||
lead.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, leadLabels)
|
||||
lead.setSelection(leadValues.indexOf(prefs.reminderLeadMinutes).takeIf { it >= 0 } ?: 2)
|
||||
url.setText(prefs.serverUrl)
|
||||
enabled.isChecked = prefs.enabled
|
||||
|
||||
@@ -25,6 +32,7 @@ object SettingsDialog {
|
||||
.setPositiveButton(R.string.save) { _, _ ->
|
||||
prefs.serverUrl = url.text?.toString().orEmpty()
|
||||
prefs.enabled = enabled.isChecked
|
||||
prefs.reminderLeadMinutes = leadValues[lead.selectedItemPosition.coerceIn(0, leadValues.lastIndex)]
|
||||
BackgroundScheduler.update(context, prefs)
|
||||
syncManager.reload()
|
||||
}
|
||||
|
||||
@@ -27,6 +27,18 @@
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/enable_sync" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:text="@string/reminder_lead"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<Spinner
|
||||
android:id="@+id/leadSpinner"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
|
||||
@@ -33,5 +33,10 @@
|
||||
<string name="reminder_channel_description">日程结束时提醒未完成事项</string>
|
||||
<string name="reminder_title">日程已结束</string>
|
||||
<string name="reminder_text">「%1$s」原定 %2 尚未完成,点击处理。</string>
|
||||
<string name="notification_permission_hint">开启通知权限后,日程结束时会收到提醒。</string>
|
||||
<string name="notification_permission_hint">开启通知权限后,日程开始/结束时会收到提醒。</string>
|
||||
<string name="reminder_lead">提前提醒</string>
|
||||
<string name="reminder_lead_title">日程即将开始</string>
|
||||
<string name="reminder_lead_text">「%1$s」将在 %2 分钟后开始(%3)。</string>
|
||||
<string name="reminder_start_title">日程开始</string>
|
||||
<string name="reminder_start_text">「%1$s」现在开始(%2)。</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.misaki.schedule
|
||||
|
||||
import com.misaki.schedule.sync.CompletionMerge
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class CompletionMergeTest {
|
||||
@Test
|
||||
fun doneWinsOverLocalScheduledOrInProgress() {
|
||||
assertTrue(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "scheduled", "done"))
|
||||
assertTrue(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "in_progress", "done"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun doesNotOverrideDroppedOrUnrelatedChanges() {
|
||||
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "dropped", "done"))
|
||||
assertFalse(CompletionMerge.remoteCompletionWins("task", "upsert", "active", "done"))
|
||||
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "delete", "scheduled", "done"))
|
||||
assertFalse(CompletionMerge.remoteCompletionWins("timeblock", "upsert", "scheduled", "scheduled"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user