Compare commits

...

3 Commits

Author SHA1 Message Date
Misaki 795f9730f8 feat: add desktop start and native reminders
- Notify at schedule start and optionally N minutes before\n- Add reminder lead setting and TOML persistence\n- Use Linux DBus native notifications with action handling\n- Focus the matching block when a notification is clicked\n- Keep overdue reminders and update validation docs/screenshots
2026-10-26 21:16:07 +08:00
Misaki 121e66d527 feat(android): add reminders and background sync
- Add local overdue reminders with notification channel and tap-to-date\n- Extract shared sync engine for foreground and WorkManager sync\n- Schedule 15-minute sync/reminder work and restore tasks after boot\n- Request notification permission and document Android background limits
2026-10-26 21:02:55 +08:00
Misaki 082c1229f9 feat: add Android sync client
- Add Kotlin/Material 3 Android project with SQLite outbox and LWW\n- Implement registration, push/pull, WebSocket notifications, and settings\n- Add schedule list, date navigation, create/edit/delete, and completion\n- Add JVM LWW/time tests and build a debug APK\n- Document Android v1 scope and validation
2026-10-26 20:43:34 +08:00
69 changed files with 3307 additions and 8 deletions
+4
View File
@@ -13,3 +13,7 @@ server/bin/
config.toml config.toml
config.toml.bak config.toml.bak
server/data/ server/data/
android/.gradle/
android/local.properties
android/app/build/
android/build/
+39 -2
View File
@@ -2,7 +2,7 @@
细粒度个人日程 + AI 自然语言排程 + 自部署多设备同步。 细粒度个人日程 + AI 自然语言排程 + 自部署多设备同步。
当前进度:**阶段 0–4 + 搜索 / 重复日程 / Windows 安装包 / 界面动画**。 当前进度:**阶段 0–4 + 搜索 / 重复日程 / Windows 安装包 / 界面动画 + 桌面日程提醒 + Android 同步客户端 v1**。
本地模型 50 条指令回归已完成:完整 49/50(98%),失败项 #42 单独复测通过。 本地模型 50 条指令回归已完成:完整 49/50(98%),失败项 #42 单独复测通过。
详细计划见 [`docs/PLAN.md`](docs/PLAN.md),验证记录见 [`docs/validation/`](docs/validation/)。 详细计划见 [`docs/PLAN.md`](docs/PLAN.md),验证记录见 [`docs/validation/`](docs/validation/)。
@@ -14,7 +14,7 @@
- **智能增强**:今日任务面板显示主动建议;日视图绘制幽灵时间;提供每日复盘对话框。 - **智能增强**:今日任务面板显示主动建议;日视图绘制幽灵时间;提供每日复盘对话框。
- **搜索与重复**:详细日程支持标题/说明搜索(`Ctrl+F`);新建日程可设置每天/每周/每月重复。 - **搜索与重复**:详细日程支持标题/说明搜索(`Ctrl+F`);新建日程可设置每天/每周/每月重复。
- **轻量动画**:窗口淡入、视图切换淡入、任务列表刷新与 Diff 卡片淡入。 - **轻量动画**:窗口淡入、视图切换淡入、任务列表刷新与 Diff 卡片淡入。
- **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、同步服务地址/开关。 - **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、日程提前提醒分钟数、同步服务地址/开关。
> 云母效果使用 ElaWidgetTools 的 `ElaMica` 跨平台模拟背景(内置模糊基底图), > 云母效果使用 ElaWidgetTools 的 `ElaMica` 跨平台模拟背景(内置模糊基底图),
> 在 Linux 下不是系统级窗口模糊;后续可在 Windows 上扩展系统 Mica。 > 在 Linux 下不是系统级窗口模糊;后续可在 Windows 上扩展系统 Mica。
@@ -67,6 +67,21 @@
- 重复规则元数据保存在本机 `recurrence` 表;具体时间块照常参与多设备同步。其他设备能看到所有已物化的日程。 - 重复规则元数据保存在本机 `recurrence` 表;具体时间块照常参与多设备同步。其他设备能看到所有已物化的日程。
- 编辑某个重复日程的标题会修改共享任务标题(影响该系列);删除单个块只删除该次。 - 编辑某个重复日程的标题会修改共享任务标题(影响该系列);删除单个块只删除该次。
## 桌面日程提醒
桌面端现在提供三种系统通知:
- **日程开始**:时间块到达开始时间时通知(App 需运行,轮询间隔 20 秒)。
- **提前提醒**:在开始前 N 分钟再通知一次;N 可在设置中选择 0(仅开始时)、5、10、15、30、60 分钟。
- **日程超时**:结束时间后仍未完成时通知(原有行为)。
通知后端:
- Linux 使用 `org.freedesktop.Notifications` DBus 原生通知,并在支持动作的桌面环境提供「打开日程」按钮。
- Windows/macOS 使用 `QSystemTrayIcon` 的系统托盘通知。
- 点击通知会打开详细日程并定位到对应时间块;Linux DBus 点击走 `ActionInvoked`,Windows/macOS 走 `messageClicked`。
限制:应用必须仍在运行(可最小化到托盘);没有开机自启;轮询不是精确闹钟;同一时间块提醒状态只保存在内存中,重启后可能再次提醒。
## 同步冲突行为 ## 同步冲突行为
同步是后台无感进行的:不弹冲突对话框,失败自动重试,状态只显示在顶部标签。 同步是后台无感进行的:不弹冲突对话框,失败自动重试,状态只显示在顶部标签。
@@ -129,6 +144,23 @@ Windows/macOS 使用 Qt 原生输入法支持,不需要该插件。
客户端使用 SQLite outbox 捕获本地变更,按服务端 `seq` 增量拉取;冲突按 `updated_at` 做 LWW,删除墓碑优先于等时间戳的更新。断线后保留 outbox 并自动重试,WebSocket 断开时退化为定时轮询。同步协议与部署说明见 [`server/README.md`](server/README.md),验证记录见 [`docs/validation/phase-3.md`](docs/validation/phase-3.md)。 客户端使用 SQLite outbox 捕获本地变更,按服务端 `seq` 增量拉取;冲突按 `updated_at` 做 LWW,删除墓碑优先于等时间戳的更新。断线后保留 outbox 并自动重试,WebSocket 断开时退化为定时轮询。同步协议与部署说明见 [`server/README.md`](server/README.md),验证记录见 [`docs/validation/phase-3.md`](docs/validation/phase-3.md)。
## Android 客户端
`android/` 是阶段 5.0 的 Kotlin/Android 同步客户端,复用阶段 3 的 REST/WebSocket 协议:
- 今日日程列表、完成状态、编辑、长按删除、新建。
- SQLite outbox、LWW、WebSocket + 15 秒轮询、设备注册。
- 日程结束本地通知;WorkManager 每 15 分钟后台同步;开机重建任务。
- 暂不含 AI 对话/附件、精力曲线、复盘。
```bash
cd android
./gradlew :app:assembleDebug
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
首次使用需安装 Android SDK 34 + Build-Tools 34,并在 App 设置中填写服务地址(模拟器用 `http://10.0.2.2:8787`,真机用电脑局域网 IP)。详细说明见 [`android/README.md`](android/README.md),验证记录见 [`docs/validation/phase-5.md`](docs/validation/phase-5.md)。
## 构建 ## 构建
依赖:CMake ≥ 3.24、Ninja、Qt 6.5+(含 Qt WebSockets)、GCC/Clang(C++20);构建同步服务端需要 Go 1.23+,Docker 部署可选。 依赖:CMake ≥ 3.24、Ninja、Qt 6.5+(含 Qt WebSockets)、GCC/Clang(C++20);构建同步服务端需要 Go 1.23+,Docker 部署可选。
@@ -232,6 +264,8 @@ ctest --preset linux-gcc
精力档案 / 幽灵时间 / 每日复盘、搜索 / 重复日程、AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、 精力档案 / 幽灵时间 / 每日复盘、搜索 / 重复日程、AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务,含无 API Key 的本地模型)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。 OpenAI 兼容 Provider(本地假 SSE 服务,含无 API Key 的本地模型)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
Android:`cd android && ./gradlew :app:testDebugUnitTest`,当前 LWW / 时间工具共 6 个 JVM 测试通过;APK 构建见 [`android/README.md`](android/README.md)。
本地模型回归(50 条真实中文指令): 本地模型回归(50 条真实中文指令):
```bash ```bash
@@ -261,6 +295,9 @@ temperature = 0.2
enabled = false enabled = false
server_url = "http://127.0.0.1:8787" server_url = "http://127.0.0.1:8787"
token = "" token = ""
[reminders]
lead_minutes = 10
``` ```
AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设置对话框中修改。同步令牌由客户端在注册后自动写入,文件权限 0600。 AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设置对话框中修改。同步令牌由客户端在注册后自动写入,文件权限 0600。
+7
View File
@@ -0,0 +1,7 @@
.gradle/
local.properties
build/
app/build/
*.apk
*.aab
.idea/
+66
View File
@@ -0,0 +1,66 @@
# Schedule Android
阶段 5.0 的 Android 同步客户端。使用 Kotlin + 原生 View,直接复用阶段 3 的 REST/WebSocket 协议,不依赖 Qt。
## 功能
- 今日日程列表:按日期前后切换、完成状态、编辑、长按删除。
- 本地 SQLite:task / timeblock / outbox / sync_state。
- 同步:设备注册、outbox 推送、增量拉取、LWW、WebSocket 通知、定时轮询。
- 提醒:日程结束后对未完成项发本地通知;通知点击回到对应日期。
- 后台:WorkManager 每 15 分钟同步一次;开机接收 `BOOT_COMPLETED` 重新登记任务。
- 设置:同步服务地址与启用开关;不支持 AI 对话和附件提取(桌面端功能)。
## 构建
要求:JDK 17+、Android SDK Platform 34 + Build-Tools 34。
```bash
cd android
# 首次使用 Android Studio 打开项目会自动生成 local.properties;
# 命令行可手动创建:
printf 'sdk.dir=/path/to/Android/Sdk\n' > local.properties
./gradlew :app:assembleDebug
```
APK:`android/app/build/outputs/apk/debug/app-debug.apk`。
安装到手机(开启 USB 调试):
```bash
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
单元测试:
```bash
./gradlew :app:testDebugUnitTest
```
## 同步配置
1. 服务端监听 `0.0.0.0:8787`(或局域网可访问地址),手机与电脑同一局域网。
2. 打开 App → 右上角菜单 → 设置 → 填写 `http://<电脑局域网IP>:8787`,启用同步。
3. 首次启用自动注册设备;服务端需保存稳定的 `SYNC_TOKEN_PEPPER`。
4. Android 模拟器访问宿主机用 `http://10.0.2.2:8787`。
> App 允许明文 HTTP 以便局域网自部署测试;公网部署请使用 HTTPS 反向代理。
> Token 存在 SharedPreferences 中,明文保存;后续可接入 Android Keystore。
## 通知与后台同步
- 提醒使用 Android 本地通知,不依赖服务端推送/FCM。
- 通知在工作线程中检查过去 24 小时内已结束、仍未完成的日程;同一时间块只提醒一次。
- Android 13+ 首次启动会请求通知权限;拒绝后提醒不显示,但同步不受影响。
- WorkManager 周期最小为 15 分钟;省电模式/Doze 或厂商后台限制可能进一步延迟。
- 开机广播会重新安排提醒与同步任务;不会自动打开 App 界面。
- 如需即时后台推送,需要后续接入 FCM 或常驻前台服务(会增加耗电/复杂度)。
> 部分国产 ROM 需要手动允许「自启动」「后台运行」或关闭电池优化,否则开机任务和周期同步可能被系统拦截。
## 当前限制
- 无 AI 对话 / 文件附件 / 精力曲线 / 重复日程创建 / 每日复盘;这些仍由桌面端提供。
- 提醒不是精确闹钟:周期任务可能延迟,且没有“提前 N 分钟”提醒。
- 无 FCM 推送;App 被强制停止后,Android 不会执行周期任务,直到下次手动打开。
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建、JVM 单元测试和 Manifest 检查。
+47
View File
@@ -0,0 +1,47 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.misaki.schedule"
compileSdk = 34
defaultConfig {
applicationId = "com.misaki.schedule"
minSdk = 26
targetSdk = 34
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.appcompat:appcompat:1.7.0")
implementation("com.google.android.material:material:1.12.0")
implementation("androidx.recyclerview:recyclerview:1.3.2")
implementation("androidx.activity:activity-ktx:1.9.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("androidx.work:work-runtime-ktx:2.9.1")
testImplementation("junit:junit:4.13.2")
testImplementation("org.json:json:20240303")
}
+1
View File
@@ -0,0 +1 @@
# Keep OkHttp and coroutines defaults.
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Schedule"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".background.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,209 @@
package com.misaki.schedule
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.background.NotificationHelper
import com.misaki.schedule.data.TimeUtils
import com.misaki.schedule.sync.SyncManager
import com.misaki.schedule.ui.ScheduleAdapter
import com.misaki.schedule.ui.ScheduleDialog
import com.misaki.schedule.ui.SettingsDialog
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var repository: ScheduleRepository
private lateinit var prefs: Prefs
private lateinit var syncManager: SyncManager
private lateinit var adapter: ScheduleAdapter
private lateinit var list: RecyclerView
private lateinit var emptyText: TextView
private lateinit var dateText: TextView
private lateinit var syncStatus: TextView
private var selectedDate: LocalDate = LocalDate.now()
private val dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.CHINA)
private val notificationPermission = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
repository = ScheduleRepository(this)
prefs = Prefs(this)
syncManager = SyncManager(this, prefs, repository)
NotificationHelper.ensureChannel(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
}
BackgroundScheduler.update(this, prefs)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let { selectedDate = it }
}
list = findViewById(R.id.scheduleList)
emptyText = findViewById(R.id.emptyText)
dateText = findViewById(R.id.dateText)
syncStatus = findViewById(R.id.syncStatus)
adapter = ScheduleAdapter(
onEdit = { showScheduleDialog(it) },
onLongPress = { confirmDelete(it) },
onDoneChanged = { item, done ->
repository.setDone(item.block.id, done, prefs.deviceId)
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
},
)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
findViewById<FloatingActionButton>(R.id.addButton).setOnClickListener {
val start = TimeUtils.defaultStart(selectedDate)
showScheduleDialog(null, start)
}
findViewById<MaterialButton>(R.id.todayButton).setOnClickListener {
selectedDate = LocalDate.now()
refresh()
}
findViewById<View>(R.id.previousDay).setOnClickListener {
selectedDate = selectedDate.minusDays(1)
refresh()
}
findViewById<View>(R.id.nextDay).setOnClickListener {
selectedDate = selectedDate.plusDays(1)
refresh()
}
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_sync -> {
syncManager.reload()
true
}
R.id.action_settings -> {
SettingsDialog.show(this, prefs, syncManager)
true
}
else -> false
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch { repository.revision.collect { refresh() } }
launch {
syncManager.status.collect { status ->
syncStatus.text = status.text
syncStatus.setTextColor(
ContextCompat.getColor(
this@MainActivity,
if (status.error) android.R.color.holo_red_dark else R.color.seed,
)
)
}
}
}
}
refresh()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let {
selectedDate = it
refresh()
}
}
}
override fun onStart() {
super.onStart()
syncManager.start()
}
override fun onStop() {
syncManager.stop()
super.onStop()
}
override fun onDestroy() {
syncManager.shutdown()
super.onDestroy()
}
private fun refresh() {
dateText.text = selectedDate.format(dateFormatter)
val items = repository.itemsForDate(selectedDate)
adapter.submit(items)
emptyText.visibility = if (items.isEmpty()) View.VISIBLE else View.GONE
}
private fun showScheduleDialog(item: ScheduleItem?, fallbackStart: java.time.LocalDateTime? = null) {
val start = item?.let { TimeUtils.localTime(it.block.startAt) } ?: fallbackStart ?: TimeUtils.defaultStart(selectedDate)
val end = item?.let { TimeUtils.localTime(it.block.endAt) } ?: start.plusHours(1)
val dialog = ScheduleDialog(
this,
if (item == null) getString(R.string.add_schedule) else item.task.title,
item?.task?.title.orEmpty(),
start,
end,
) { title, newStart, newEnd ->
if (item == null) {
repository.create(title, newStart, newEnd, prefs.deviceId)
} else {
repository.update(item.block.id, title, newStart, newEnd, prefs.deviceId)
}
selectedDate = newStart.toLocalDate()
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh()
}
dialog.show()
}
private fun confirmDelete(item: ScheduleItem) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.delete_title)
.setMessage(getString(R.string.delete_message, item.task.title))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.delete) { _, _ ->
repository.delete(item.block.id)
syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh()
}
.show()
}
}
@@ -0,0 +1,65 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.misaki.schedule.data.Prefs
import java.util.concurrent.TimeUnit
object BackgroundScheduler {
private const val SYNC_WORK = "schedule-sync"
private const val REMINDER_WORK = "schedule-reminders"
private const val SYNC_NOW_WORK = "schedule-sync-now"
fun update(context: Context, prefs: Prefs) {
scheduleReminders(context)
if (prefs.enabled) scheduleSync(context) else cancelSync(context)
}
fun scheduleSync(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
SYNC_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun cancelSync(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK)
WorkManager.getInstance(context).cancelUniqueWork(SYNC_NOW_WORK)
}
fun scheduleReminders(context: Context) {
val request = PeriodicWorkRequestBuilder<ReminderWorker>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
REMINDER_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun syncNow(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
SYNC_NOW_WORK,
ExistingWorkPolicy.REPLACE,
request,
)
}
}
@@ -0,0 +1,13 @@
package com.misaki.schedule.background
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.misaki.schedule.data.Prefs
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
BackgroundScheduler.update(context, Prefs(context))
}
}
@@ -0,0 +1,72 @@
package com.misaki.schedule.background
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.misaki.schedule.MainActivity
import com.misaki.schedule.R
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.TimeUtils
object NotificationHelper {
const val CHANNEL_ID = "schedule_reminders"
fun ensureChannel(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
val channel = NotificationChannel(
CHANNEL_ID,
context.getString(R.string.reminder_channel_name),
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = context.getString(R.string.reminder_channel_description)
}
manager.createNotificationChannel(channel)
}
fun canNotify(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
return false
}
return NotificationManagerCompat.from(context).areNotificationsEnabled()
}
fun notifyReminder(context: Context, item: ScheduleItem): Boolean {
if (!canNotify(context)) return false
ensureChannel(context)
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra("date", item.block.startAt)
}
val pending = PendingIntent.getActivity(
context,
item.block.id.hashCode(),
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))
.setContentText(text)
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pending)
.build()
NotificationManagerCompat.from(context).notify(item.block.id.hashCode(), notification)
return true
}
}
@@ -0,0 +1,30 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.data.TimeUtils
class ReminderWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
return try {
NotificationHelper.ensureChannel(applicationContext)
if (!NotificationHelper.canNotify(applicationContext)) {
return Result.success()
}
val repository = ScheduleRepository(applicationContext)
val now = TimeUtils.nowIso()
val since = TimeUtils.hoursAgo(24)
val pending = repository.pendingReminders(now, since)
for ((item, key) in pending) {
if (NotificationHelper.notifyReminder(applicationContext, item)) {
repository.markReminderSent(key, item.block.id, now)
}
}
Result.success()
} catch (_: Exception) {
Result.retry()
}
}
}
@@ -0,0 +1,34 @@
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.sync.SyncEngine
import com.misaki.schedule.sync.UnauthorizedException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
class SyncWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val prefs = Prefs(applicationContext)
if (!prefs.enabled || prefs.serverUrl.isBlank()) return Result.success()
val repository = ScheduleRepository(applicationContext)
val engine = SyncEngine(prefs, repository)
return withContext(Dispatchers.IO) {
try {
engine.runOnce()
Result.success()
} catch (_: UnauthorizedException) {
prefs.clearToken()
Result.retry()
} catch (_: IOException) {
Result.retry()
} catch (_: Exception) {
Result.retry()
}
}
}
}
@@ -0,0 +1,51 @@
package com.misaki.schedule.data
import android.content.Context
import android.os.Build
import java.util.UUID
class Prefs(context: Context) {
private val prefs = context.getSharedPreferences("schedule_prefs", Context.MODE_PRIVATE)
private val generatedDeviceId: String by lazy {
val existing = prefs.getString("device_id", null)
if (!existing.isNullOrBlank()) {
existing
} else {
UUID.randomUUID().toString().also { prefs.edit().putString("device_id", it).apply() }
}
}
var serverUrl: String
get() = prefs.getString("server_url", "").orEmpty()
set(value) = prefs.edit().putString("server_url", normalizeUrl(value)).apply()
var enabled: Boolean
get() = prefs.getBoolean("sync_enabled", false)
set(value) = prefs.edit().putBoolean("sync_enabled", value).apply()
var token: String
get() = prefs.getString("token", "").orEmpty()
set(value) = prefs.edit().putString("token", value).apply()
val deviceId: String
get() = generatedDeviceId
val deviceName: String
get() = listOf(Build.MANUFACTURER, Build.MODEL).filter { it.isNotBlank() }
.joinToString(" ").ifBlank { "Android" }
fun clearToken() {
prefs.edit().remove("token").apply()
}
companion object {
fun normalizeUrl(value: String): String {
var url = value.trim()
if (url.isEmpty()) return ""
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://$url"
}
return url.trimEnd('/')
}
}
}
@@ -0,0 +1,81 @@
package com.misaki.schedule.data
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", null, 2) {
override fun onConfigure(db: SQLiteDatabase) {
super.onConfigure(db)
db.setForeignKeyConstraintsEnabled(true)
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE task(
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
source TEXT,
source_ref TEXT,
estimated_min INTEGER,
energy_req INTEGER,
deadline TEXT,
priority INTEGER DEFAULT 1,
status TEXT DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
version INTEGER DEFAULT 0,
device_id TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE timeblock(
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES task(id) ON DELETE CASCADE,
start_at TEXT NOT NULL,
end_at TEXT NOT NULL,
granularity INTEGER DEFAULT 15,
splittable INTEGER DEFAULT 1,
breakable INTEGER DEFAULT 1,
status TEXT DEFAULT 'scheduled',
done_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
version INTEGER DEFAULT 0,
device_id TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE outbox(
id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_type TEXT NOT NULL,
entity_id TEXT NOT NULL,
op TEXT NOT NULL,
payload TEXT,
created_at TEXT NOT NULL
)
""".trimIndent()
)
db.execSQL("CREATE TABLE sync_state(device_id TEXT PRIMARY KEY, last_seq INTEGER DEFAULT 0)")
db.execSQL(
"CREATE TABLE reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
db.execSQL("CREATE INDEX idx_timeblock_start ON timeblock(start_at)")
db.execSQL("CREATE INDEX idx_timeblock_task ON timeblock(task_id)")
db.execSQL("CREATE INDEX idx_outbox_entity ON outbox(entity_type, entity_id)")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 2) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
}
}
}
@@ -0,0 +1,107 @@
package com.misaki.schedule.data
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
data class Task(
val id: String,
val title: String,
val description: String?,
val source: String,
val sourceRef: String?,
val estimatedMin: Int?,
val energyReq: Int?,
val deadline: String?,
val priority: Int,
val status: String,
val createdAt: String,
val updatedAt: String,
val version: Int,
val deviceId: String,
)
data class TimeBlock(
val id: String,
val taskId: String,
val startAt: String,
val endAt: String,
val granularity: Int,
val splittable: Boolean,
val breakable: Boolean,
val status: String,
val doneAt: String?,
val createdAt: String,
val updatedAt: String,
val version: Int,
val deviceId: String,
)
data class ScheduleItem(val task: Task, val block: TimeBlock) {
fun isActive(): Boolean = block.status == "scheduled" || block.status == "in_progress"
fun isDone(): Boolean = block.status == "done"
}
object TimeUtils {
private val isoFormatter = DateTimeFormatter.ISO_INSTANT
private val displayTime = DateTimeFormatter.ofPattern("HH:mm")
private val displayDate = DateTimeFormatter.ofPattern("M月d日")
fun nowIso(): String = isoFormatter.format(Instant.now().truncatedTo(ChronoUnit.MILLIS))
fun toIso(local: LocalDateTime): String =
isoFormatter.format(local.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.MILLIS))
fun parse(local: String?): Instant? = try {
if (local.isNullOrBlank()) null else Instant.parse(local)
} catch (_: Exception) {
null
}
fun localTime(iso: String?): LocalDateTime? =
parse(iso)?.atZone(ZoneId.systemDefault())?.toLocalDateTime()
fun formatTime(iso: String?): String =
localTime(iso)?.format(displayTime) ?: "--:--"
fun formatDate(iso: String?): String =
localTime(iso)?.format(displayDate) ?: ""
fun formatRange(start: String?, end: String?): String =
"${formatTime(start)}–${formatTime(end)}"
fun dayStart(date: LocalDate): String =
toIso(date.atStartOfDay())
fun dayEnd(date: LocalDate): String =
toIso(date.plusDays(1).atStartOfDay())
fun dateOf(iso: String?): LocalDate? =
parse(iso)?.atZone(ZoneId.systemDefault())?.toLocalDate()
fun startOfDay(date: LocalDate): LocalDateTime = date.atStartOfDay()
fun hoursAgo(hours: Long): String =
isoFormatter.format(Instant.now().minus(hours, ChronoUnit.HOURS).truncatedTo(ChronoUnit.MILLIS))
fun defaultStart(date: LocalDate): LocalDateTime {
val today = LocalDate.now()
if (date == today) {
val now = LocalDateTime.now().plusMinutes(15)
return now.withSecond(0).withNano(0)
}
return LocalDateTime.of(date, LocalTime.of(9, 0))
}
}
fun statusLabel(status: String): String = when (status) {
"done" -> "已完成"
"in_progress" -> "进行中"
"dropped" -> "已放弃"
"missed" -> "已错过"
else -> "待办"
}
@@ -0,0 +1,471 @@
package com.misaki.schedule.data
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.misaki.schedule.sync.JsonCodec
import com.misaki.schedule.sync.Lww
import kotlinx.coroutines.flow.MutableStateFlow
import org.json.JSONArray
import org.json.JSONObject
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
class ScheduleRepository(context: Context) {
private val dbHelper = ScheduleDb(context.applicationContext)
private val db: SQLiteDatabase get() = dbHelper.writableDatabase
val revision = MutableStateFlow(0L)
data class PendingBatch(val maxId: Long, val count: Int, val changes: JSONArray)
data class PullResult(val applied: Int)
fun itemsForDate(date: LocalDate): 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.start_at < ? AND b.end_at > ?
ORDER BY b.start_at ASC
""".trimIndent(),
arrayOf(TimeUtils.dayEnd(date), TimeUtils.dayStart(date))
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor))
}
}
return result
}
fun create(title: String, start: LocalDateTime, end: LocalDateTime, deviceId: String): String {
val now = TimeUtils.nowIso()
val taskId = UUID.randomUUID().toString()
val blockId = UUID.randomUUID().toString()
val task = Task(
id = taskId,
title = title.trim().ifBlank { "未命名日程" },
description = null,
source = "android",
sourceRef = null,
estimatedMin = minutesBetween(start, end),
energyReq = null,
deadline = null,
priority = 1,
status = "active",
createdAt = now,
updatedAt = now,
version = 0,
deviceId = deviceId,
)
val block = TimeBlock(
id = blockId,
taskId = taskId,
startAt = TimeUtils.toIso(start),
endAt = TimeUtils.toIso(end),
granularity = 15,
splittable = true,
breakable = true,
status = "scheduled",
doneAt = null,
createdAt = now,
updatedAt = now,
version = 0,
deviceId = deviceId,
)
inTransaction { database ->
database.insertOrThrow("task", null, taskValues(task))
database.insertOrThrow("timeblock", null, blockValues(block))
enqueue(database, "task", taskId, "upsert", JsonCodec.taskToJson(task), now)
enqueue(database, "timeblock", blockId, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
return blockId
}
fun update(blockId: String, title: String, start: LocalDateTime, end: LocalDateTime, deviceId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
val task = existing.task.copy(
title = title.trim().ifBlank { "未命名日程" },
estimatedMin = minutesBetween(start, end),
updatedAt = now,
version = existing.task.version + 1,
deviceId = deviceId,
)
val block = existing.block.copy(
startAt = TimeUtils.toIso(start),
endAt = TimeUtils.toIso(end),
updatedAt = now,
version = existing.block.version + 1,
deviceId = deviceId,
)
inTransaction { database ->
database.update("task", taskValues(task), "id = ?", arrayOf(task.id))
database.update("timeblock", blockValues(block), "id = ?", arrayOf(block.id))
enqueue(database, "task", task.id, "upsert", JsonCodec.taskToJson(task), now)
enqueue(database, "timeblock", block.id, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
}
fun setDone(blockId: String, done: Boolean, deviceId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
val block = existing.block.copy(
status = if (done) "done" else "scheduled",
doneAt = if (done) now else null,
updatedAt = now,
version = existing.block.version + 1,
deviceId = deviceId,
)
inTransaction { database ->
database.update("timeblock", blockValues(block), "id = ?", arrayOf(block.id))
enqueue(database, "timeblock", block.id, "upsert", JsonCodec.blockToJson(block), now)
}
bump()
}
fun delete(blockId: String) {
val existing = itemByBlock(blockId) ?: return
val now = TimeUtils.nowIso()
inTransaction { database ->
database.delete("timeblock", "id = ?", arrayOf(existing.block.id))
val remaining = database.rawQuery(
"SELECT COUNT(*) FROM timeblock WHERE task_id = ?",
arrayOf(existing.task.id)
).use { cursor -> if (cursor.moveToFirst()) cursor.getInt(0) else 0 }
enqueue(database, "timeblock", existing.block.id, "delete",
JsonCodec.blockToJson(existing.block).withUpdatedAt(now), now)
if (remaining == 0) {
database.delete("task", "id = ?", arrayOf(existing.task.id))
enqueue(database, "task", existing.task.id, "delete",
JsonCodec.taskToJson(existing.task).withUpdatedAt(now), now)
}
}
bump()
}
fun pendingChanges(limit: Int = 100): PendingBatch {
val changes = JSONArray()
var maxId = 0L
var count = 0
db.rawQuery(
"SELECT id, entity_type, entity_id, op, payload FROM outbox ORDER BY id ASC LIMIT ?",
arrayOf(limit.toString())
).use { cursor ->
while (cursor.moveToNext()) {
val id = cursor.getLong(0)
maxId = maxOf(maxId, id)
val payload = cursor.getString(4)?.let { JSONObject(it) } ?: JSONObject()
val change = JSONObject().apply {
put("entity_type", cursor.getString(1))
put("entity_id", cursor.getString(2))
put("op", cursor.getString(3))
put("version", payload.optInt("version", 0))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("payload", payload)
}
changes.put(change)
count++
}
}
return PendingBatch(maxId, count, changes)
}
fun clearOutboxThrough(maxId: Long) {
db.delete("outbox", "id <= ?", arrayOf(maxId.toString()))
}
fun pendingReminders(nowIso: String, sinceIso: String): List<Pair<ScheduleItem, String>> {
val result = mutableListOf<Pair<ScheduleItem, String>>()
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,
b.id || '@' || b.updated_at
FROM timeblock b JOIN task t ON t.id = b.task_id
LEFT JOIN reminder_sent r ON r.key = b.id || '@' || b.updated_at
WHERE b.status IN ('scheduled', 'in_progress')
AND b.end_at <= ? AND b.end_at >= ?
AND r.key IS NULL
ORDER BY b.end_at ASC
""".trimIndent(),
arrayOf(nowIso, sinceIso)
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor) to cursor.getString(27))
}
}
return result
}
fun markReminderSent(key: String, blockId: String, sentAt: String) {
val values = ContentValues().apply {
put("key", key)
put("block_id", blockId)
put("sent_at", sentAt)
}
db.insertWithOnConflict("reminder_sent", null, values, SQLiteDatabase.CONFLICT_IGNORE)
}
fun lastSeq(deviceId: String): Long {
db.rawQuery("SELECT last_seq FROM sync_state WHERE device_id = ?", arrayOf(deviceId)).use { cursor ->
return if (cursor.moveToFirst()) cursor.getLong(0) else 0L
}
}
fun applyRemote(deviceId: String, changes: JSONArray, latestSeq: Long): PullResult {
var applied = 0
inTransaction { database ->
for (index in 0 until changes.length()) {
val change = changes.getJSONObject(index)
if (change.optString("device_id") == deviceId) continue
val entityType = change.optString("entity_type")
val entityId = change.optString("entity_id")
val op = change.optString("op")
val remoteUpdated = change.optString("updated_at")
val localUpdated = localUpdatedAt(database, entityType, entityId)
val equalWins = op == "delete"
if (!Lww.shouldApply(localUpdated, remoteUpdated, equalWins)) continue
if (op == "delete") {
when (entityType) {
"task" -> database.delete("task", "id = ?", arrayOf(entityId))
"timeblock" -> database.delete("timeblock", "id = ?", arrayOf(entityId))
}
applied++
} else if (op == "upsert") {
val payload = change.optJSONObject("payload") ?: continue
when (entityType) {
"task" -> {
payload.put("updated_at", remoteUpdated)
payload.put("version", change.optInt("version", 0))
payload.put("device_id", change.optString("device_id"))
database.insertWithOnConflict("task", null, taskValues(payload), SQLiteDatabase.CONFLICT_REPLACE)
applied++
}
"timeblock" -> {
payload.put("updated_at", remoteUpdated)
payload.put("version", change.optInt("version", 0))
payload.put("device_id", change.optString("device_id"))
if (taskExists(database, payload.optString("task_id"))) {
database.insertWithOnConflict("timeblock", null, blockValues(payload), SQLiteDatabase.CONFLICT_REPLACE)
applied++
}
}
}
}
}
val values = ContentValues().apply { put("last_seq", latestSeq) }
val updated = database.update("sync_state", values, "device_id = ?", arrayOf(deviceId))
if (updated == 0) {
values.put("device_id", deviceId)
database.insertOrThrow("sync_state", null, values)
}
}
if (applied > 0) bump()
return PullResult(applied)
}
private fun itemByBlock(blockId: String): 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.id = ?
""".trimIndent(),
arrayOf(blockId)
).use { cursor ->
return if (cursor.moveToFirst()) readItem(cursor) else null
}
}
private fun readItem(cursor: Cursor): ScheduleItem {
val task = Task(
id = cursor.getString(0),
title = cursor.getString(1),
description = cursor.stringOrNull(2),
source = cursor.getString(3) ?: "android",
sourceRef = cursor.stringOrNull(4),
estimatedMin = cursor.intOrNull(5),
energyReq = cursor.intOrNull(6),
deadline = cursor.stringOrNull(7),
priority = cursor.getInt(8),
status = cursor.getString(9) ?: "active",
createdAt = cursor.getString(10),
updatedAt = cursor.getString(11),
version = cursor.getInt(12),
deviceId = cursor.getString(13),
)
val block = TimeBlock(
id = cursor.getString(14),
taskId = cursor.getString(15),
startAt = cursor.getString(16),
endAt = cursor.getString(17),
granularity = cursor.getInt(18),
splittable = cursor.getInt(19) != 0,
breakable = cursor.getInt(20) != 0,
status = cursor.getString(21) ?: "scheduled",
doneAt = cursor.stringOrNull(22),
createdAt = cursor.getString(23),
updatedAt = cursor.getString(24),
version = cursor.getInt(25),
deviceId = cursor.getString(26),
)
return ScheduleItem(task, block)
}
private fun localUpdatedAt(database: SQLiteDatabase, entityType: String, entityId: String): String? {
val table = when (entityType) {
"task" -> "task"
"timeblock" -> "timeblock"
else -> return null
}
database.rawQuery("SELECT updated_at FROM $table WHERE id = ?", arrayOf(entityId)).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()
}
}
private fun enqueue(
database: SQLiteDatabase,
entityType: String,
entityId: String,
op: String,
payload: JSONObject,
createdAt: String,
) {
val values = ContentValues().apply {
put("entity_type", entityType)
put("entity_id", entityId)
put("op", op)
put("payload", payload.toString())
put("created_at", createdAt)
}
database.insertOrThrow("outbox", null, values)
}
private fun taskValues(task: Task): ContentValues = ContentValues().apply {
put("id", task.id)
put("title", task.title)
put("description", task.description)
put("source", task.source)
put("source_ref", task.sourceRef)
put("estimated_min", task.estimatedMin)
put("energy_req", task.energyReq)
put("deadline", task.deadline)
put("priority", task.priority)
put("status", task.status)
put("created_at", task.createdAt)
put("updated_at", task.updatedAt)
put("version", task.version)
put("device_id", task.deviceId)
}
private fun taskValues(payload: JSONObject): ContentValues = ContentValues().apply {
put("id", payload.optString("id"))
put("title", payload.optString("title", "未命名日程"))
put("description", payload.stringOrNull("description"))
put("source", payload.optString("source", "android"))
put("source_ref", payload.stringOrNull("source_ref"))
put("estimated_min", payload.intOrNull("estimated_min"))
put("energy_req", payload.intOrNull("energy_req"))
put("deadline", payload.stringOrNull("deadline"))
put("priority", payload.optInt("priority", 1))
put("status", payload.optString("status", "active"))
put("created_at", payload.optString("created_at", TimeUtils.nowIso()))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("version", payload.optInt("version", 0))
put("device_id", payload.optString("device_id"))
}
private fun blockValues(block: TimeBlock): ContentValues = ContentValues().apply {
put("id", block.id)
put("task_id", block.taskId)
put("start_at", block.startAt)
put("end_at", block.endAt)
put("granularity", block.granularity)
put("splittable", if (block.splittable) 1 else 0)
put("breakable", if (block.breakable) 1 else 0)
put("status", block.status)
put("done_at", block.doneAt)
put("created_at", block.createdAt)
put("updated_at", block.updatedAt)
put("version", block.version)
put("device_id", block.deviceId)
}
private fun blockValues(payload: JSONObject): ContentValues = ContentValues().apply {
put("id", payload.optString("id"))
put("task_id", payload.optString("task_id"))
put("start_at", payload.optString("start_at"))
put("end_at", payload.optString("end_at"))
put("granularity", payload.optInt("granularity", 15))
put("splittable", if (payload.boolInt("splittable", true)) 1 else 0)
put("breakable", if (payload.boolInt("breakable", true)) 1 else 0)
put("status", payload.optString("status", "scheduled"))
put("done_at", payload.stringOrNull("done_at"))
put("created_at", payload.optString("created_at", TimeUtils.nowIso()))
put("updated_at", payload.optString("updated_at", TimeUtils.nowIso()))
put("version", payload.optInt("version", 0))
put("device_id", payload.optString("device_id"))
}
private fun inTransaction(block: (SQLiteDatabase) -> Unit) {
val database = db
database.beginTransaction()
try {
block(database)
database.setTransactionSuccessful()
} finally {
database.endTransaction()
}
}
private fun bump() {
revision.value = revision.value + 1
}
private fun minutesBetween(start: LocalDateTime, end: LocalDateTime): Int =
java.time.Duration.between(start, end).toMinutes().toInt()
private fun Cursor.stringOrNull(index: Int): String? = if (isNull(index)) null else getString(index)
private fun Cursor.intOrNull(index: Int): Int? = if (isNull(index)) null else getInt(index)
private fun JSONObject.stringOrNull(key: String): String? =
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
private fun JSONObject.intOrNull(key: String): Int? =
if (isNull(key) || !has(key)) null else optInt(key)
private fun JSONObject.boolInt(key: String, fallback: Boolean): Boolean = when (val value = opt(key)) {
is Boolean -> value
is Number -> value.toInt() != 0
else -> fallback
}
private fun JSONObject.withUpdatedAt(value: String): JSONObject {
val copy = JSONObject(toString())
copy.put("updated_at", value)
return copy
}
}
@@ -0,0 +1,40 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Task
import com.misaki.schedule.data.TimeBlock
import org.json.JSONObject
object JsonCodec {
fun taskToJson(task: Task): JSONObject = JSONObject().apply {
put("id", task.id)
put("title", task.title)
put("description", task.description ?: JSONObject.NULL)
put("source", task.source)
put("source_ref", task.sourceRef ?: JSONObject.NULL)
put("estimated_min", task.estimatedMin ?: JSONObject.NULL)
put("energy_req", task.energyReq ?: JSONObject.NULL)
put("deadline", task.deadline ?: JSONObject.NULL)
put("priority", task.priority)
put("status", task.status)
put("created_at", task.createdAt)
put("updated_at", task.updatedAt)
put("version", task.version)
put("device_id", task.deviceId)
}
fun blockToJson(block: TimeBlock): JSONObject = JSONObject().apply {
put("id", block.id)
put("task_id", block.taskId)
put("start_at", block.startAt)
put("end_at", block.endAt)
put("granularity", block.granularity)
put("splittable", block.splittable)
put("breakable", block.breakable)
put("status", block.status)
put("done_at", block.doneAt ?: JSONObject.NULL)
put("created_at", block.createdAt)
put("updated_at", block.updatedAt)
put("version", block.version)
put("device_id", block.deviceId)
}
}
@@ -0,0 +1,18 @@
package com.misaki.schedule.sync
import java.time.Instant
object Lww {
/**
* @param equalWins delete tombstones win when timestamps are equal.
*/
fun shouldApply(local: String?, remote: String, equalWins: Boolean): Boolean {
if (local.isNullOrBlank()) return true
val localInstant: Instant? = runCatching { Instant.parse(local) }.getOrNull()
val remoteInstant: Instant? = runCatching { Instant.parse(remote) }.getOrNull()
if (localInstant != null && remoteInstant != null) {
return remoteInstant.isAfter(localInstant) || (equalWins && remoteInstant == localInstant)
}
return remote > local || (equalWins && remote == local)
}
}
@@ -0,0 +1,106 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Prefs
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
class UnauthorizedException : IOException("同步认证失效")
data class PullPage(val changes: JSONArray, val latestSeq: Long, val hasMore: Boolean)
class SyncApi(private val prefs: Prefs) {
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
private val jsonType = "application/json; charset=utf-8".toMediaType()
fun register(deviceId: String, name: String): String {
val body = JSONObject().apply {
put("device_id", deviceId)
put("name", name)
}
val request = Request.Builder()
.url(apiUrl("v1/devices/register"))
.post(body.toString().toRequestBody(jsonType))
.build()
val json = executeJson(request, requireAuth = false)
val token = json.optString("token")
if (token.isBlank()) throw IOException("注册响应缺少 token")
return token
}
fun push(token: String, changes: JSONArray): Int {
val body = JSONObject().apply { put("changes", changes) }
val request = Request.Builder()
.url(apiUrl("v1/changes/push"))
.header("Authorization", "Bearer $token")
.post(body.toString().toRequestBody(jsonType))
.build()
return executeJson(request, requireAuth = true).optInt("accepted", 0)
}
fun pull(token: String, sinceSeq: Long): PullPage {
val url = apiUrl("v1/changes/pull").newBuilder()
.addQueryParameter("since_seq", sinceSeq.toString())
.addQueryParameter("limit", "200")
.build()
val request = Request.Builder()
.url(url)
.header("Authorization", "Bearer $token")
.get()
.build()
val json = executeJson(request, requireAuth = true)
return PullPage(
changes = json.optJSONArray("changes") ?: JSONArray(),
latestSeq = json.optLong("latest_seq", sinceSeq),
hasMore = json.optBoolean("has_more", false),
)
}
fun newWebSocket(token: String, listener: WebSocketListener): WebSocket {
val url = streamUrl(token)
return client.newWebSocket(Request.Builder().url(url).build(), listener)
}
private fun streamUrl(token: String): HttpUrl {
return baseUrl().newBuilder()
.addPathSegments("v1/stream")
.addQueryParameter("token", token)
.build()
}
private fun apiUrl(path: String): HttpUrl =
baseUrl().newBuilder().addPathSegments(path).build()
private fun baseUrl(): HttpUrl {
val raw = Prefs.normalizeUrl(prefs.serverUrl)
return raw.toHttpUrlOrNull()
?: throw IOException("同步服务地址无效")
}
private fun executeJson(request: Request, requireAuth: Boolean): JSONObject {
client.newCall(request).execute().use { response ->
if (response.code == 401 && requireAuth) throw UnauthorizedException()
val text = response.body?.string().orEmpty()
if (!response.isSuccessful) {
throw IOException("HTTP ${response.code}: ${text.take(200)}")
}
return runCatching { JSONObject(text) }.getOrElse {
throw IOException("服务器返回了无效 JSON")
}
}
}
}
@@ -0,0 +1,49 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Shared one-pass sync implementation used by the foreground controller and WorkManager.
*/
class SyncEngine(
private val prefs: Prefs,
private val repository: ScheduleRepository,
) {
val api = SyncApi(prefs)
suspend fun runOnce() = mutex.withLock {
if (!prefs.enabled || prefs.serverUrl.isBlank()) {
return@withLock
}
if (prefs.token.isBlank()) {
prefs.token = api.register(prefs.deviceId, prefs.deviceName)
}
var pushes = 0
while (pushes < 10) {
val batch = repository.pendingChanges()
if (batch.count == 0) break
val accepted = api.push(prefs.token, batch.changes)
if (accepted < batch.count) throw IllegalStateException("服务端未接受全部变更")
repository.clearOutboxThrough(batch.maxId)
pushes++
}
var cursor = repository.lastSeq(prefs.deviceId)
var pages = 0
while (pages < 10) {
val page = api.pull(prefs.token, cursor)
repository.applyRemote(prefs.deviceId, page.changes, page.latestSeq)
cursor = page.latestSeq
pages++
if (!page.hasMore) break
}
}
companion object {
private val mutex = Mutex()
}
}
@@ -0,0 +1,138 @@
package com.misaki.schedule.sync
import android.content.Context
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONObject
class SyncManager(
@Suppress("UNUSED_PARAMETER") context: Context,
private val prefs: Prefs,
private val repository: ScheduleRepository,
) {
data class Status(val text: String, val error: Boolean = false)
val status = MutableStateFlow(Status("本地"))
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val engine = SyncEngine(prefs, repository)
private val api = engine.api
private val trigger = Channel<Unit>(Channel.CONFLATED)
private var job: Job? = null
@Volatile private var webSocket: WebSocket? = null
fun start() {
job?.cancel()
closeWebSocket()
if (!prefs.enabled) {
status.value = Status("同步未启用")
return
}
if (prefs.serverUrl.isBlank()) {
status.value = Status("未配置同步地址", error = true)
return
}
job = scope.launch { loop() }
}
fun stop() {
job?.cancel()
job = null
closeWebSocket()
status.value = Status("本地")
}
fun reload() {
stop()
start()
}
fun triggerSync() {
trigger.trySend(Unit)
}
private suspend fun loop() {
while (scope.isActive) {
try {
if (prefs.token.isBlank()) register()
ensureWebSocket()
syncOnce()
status.value = Status("已同步")
withTimeoutOrNull(15000) { trigger.receive() }
} catch (_: UnauthorizedException) {
closeWebSocket()
prefs.clearToken()
status.value = Status("认证失效,正在重新注册")
delay(300)
} catch (error: Exception) {
status.value = Status("离线,等待重试", error = true)
withTimeoutOrNull(5000) { trigger.receive() }
}
}
}
private fun register() {
status.value = Status("正在注册设备…")
val token = api.register(prefs.deviceId, prefs.deviceName)
prefs.token = token
}
private suspend fun syncOnce() {
status.value = Status("同步中…")
engine.runOnce()
}
private fun ensureWebSocket() {
if (webSocket != null || prefs.token.isBlank()) return
synchronized(this) {
if (webSocket != null) return
webSocket = api.newWebSocket(prefs.token, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
triggerSync()
}
override fun onMessage(webSocket: WebSocket, text: String) {
val type = runCatching { JSONObject(text).optString("type") }.getOrNull()
if (type == "ready" || type == "changes") {
triggerSync()
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
this@SyncManager.webSocket = null
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
this@SyncManager.webSocket = null
}
})
}
}
private fun closeWebSocket() {
synchronized(this) {
webSocket?.close(1000, "stop")
webSocket = null
}
}
fun shutdown() {
stop()
scope.cancel()
}
}
@@ -0,0 +1,65 @@
package com.misaki.schedule.ui
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.misaki.schedule.R
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.TimeUtils
import com.misaki.schedule.data.statusLabel
class ScheduleAdapter(
private val onEdit: (ScheduleItem) -> Unit,
private val onLongPress: (ScheduleItem) -> Unit,
private val onDoneChanged: (ScheduleItem, Boolean) -> Unit,
) : RecyclerView.Adapter<ScheduleAdapter.ViewHolder>() {
private var items: List<ScheduleItem> = emptyList()
fun submit(newItems: List<ScheduleItem>) {
items = newItems
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_schedule, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.titleText)
private val time: TextView = itemView.findViewById(R.id.timeText)
private val status: TextView = itemView.findViewById(R.id.statusText)
private val done: CheckBox = itemView.findViewById(R.id.doneCheck)
fun bind(item: ScheduleItem) {
title.text = item.task.title
time.text = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
status.text = statusLabel(item.block.status)
val isDone = item.isDone()
done.setOnCheckedChangeListener(null)
done.isChecked = isDone
done.setOnCheckedChangeListener { _, checked -> onDoneChanged(item, checked) }
title.paintFlags = if (isDone) {
title.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
title.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
itemView.setOnClickListener { onEdit(item) }
itemView.setOnLongClickListener {
onLongPress(item)
true
}
}
}
}
@@ -0,0 +1,105 @@
package com.misaki.schedule.ui
import android.app.DatePickerDialog
import android.app.Dialog
import android.app.TimePickerDialog
import android.content.Context
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.misaki.schedule.R
import com.misaki.schedule.data.TimeUtils
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class ScheduleDialog(
context: Context,
dialogTitle: String,
private val initialTitle: String,
initialStart: LocalDateTime,
initialEnd: LocalDateTime,
private val onSave: (String, LocalDateTime, LocalDateTime) -> Unit,
) : Dialog(context) {
private var start: LocalDateTime = initialStart
private var end: LocalDateTime = initialEnd
private val titleInput: TextInputEditText
private val startButton: MaterialButton
private val endButton: MaterialButton
private val errorText: TextView
private val formatter = DateTimeFormatter.ofPattern("M月d日 HH:mm")
init {
setContentView(R.layout.dialog_schedule)
setTitle(dialogTitle)
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
titleInput = findViewById(R.id.titleInput)
startButton = findViewById(R.id.startButton)
endButton = findViewById(R.id.endButton)
errorText = findViewById(R.id.errorText)
titleInput.setText(initialTitle)
updateButtons()
findViewById<MaterialButton>(R.id.cancelButton).setOnClickListener { dismiss() }
findViewById<MaterialButton>(R.id.saveButton).setOnClickListener { save() }
startButton.setOnClickListener {
pickDateTime(start) { picked ->
start = picked
if (end <= start) end = start.plusHours(1)
updateButtons()
}
}
endButton.setOnClickListener {
pickDateTime(end) { picked ->
end = picked
updateButtons()
}
}
}
private fun updateButtons() {
startButton.text = formatter.format(start)
endButton.text = formatter.format(end)
}
private fun pickDateTime(initial: LocalDateTime, onPicked: (LocalDateTime) -> Unit) {
DatePickerDialog(
context,
{ _, year, month, day ->
TimePickerDialog(
context,
{ _, hour, minute ->
onPicked(LocalDateTime.of(year, month + 1, day, hour, minute))
},
initial.hour,
initial.minute,
true,
).show()
},
initial.year,
initial.monthValue - 1,
initial.dayOfMonth,
).show()
}
private fun save() {
val title = titleInput.text?.toString()?.trim().orEmpty()
if (title.isEmpty()) {
showError(context.getString(R.string.title_required))
return
}
if (end <= start) {
showError(context.getString(R.string.start_after_end))
return
}
onSave(title, start, end)
dismiss()
}
private fun showError(message: String) {
errorText.text = message
errorText.visibility = View.VISIBLE
}
}
@@ -0,0 +1,33 @@
package com.misaki.schedule.ui
import android.content.Context
import android.view.LayoutInflater
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.materialswitch.MaterialSwitch
import com.google.android.material.textfield.TextInputEditText
import com.misaki.schedule.R
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.sync.SyncManager
object SettingsDialog {
fun show(context: Context, prefs: Prefs, syncManager: SyncManager) {
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)
url.setText(prefs.serverUrl)
enabled.isChecked = prefs.enabled
MaterialAlertDialogBuilder(context)
.setTitle(R.string.settings)
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.save) { _, _ ->
prefs.serverUrl = url.text?.toString().orEmpty()
prefs.enabled = enabled.isChecked
BackgroundScheduler.update(context, prefs)
syncManager.reload()
}
.show()
}
}
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M11,5h2v6h6v2h-6v6h-2v-6h-6v-2h6z" />
</vector>
@@ -0,0 +1,18 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#4F6BED"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M28,24h52a8,8 0,0 1,8 8v52a8,8 0,0 1,-8 8h-52a8,8 0,0 1,-8 -8v-52a8,8 0,0 1,8 -8z" />
<path
android:fillColor="#4F6BED"
android:pathData="M28,40h52v6h-52zM38,30h6v12h-6zM64,30h6v12h-6z" />
<path
android:fillColor="#4F6BED"
android:pathData="M42,56h8v8h-8zM58,56h8v8h-8zM42,70h8v8h-8z" />
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,2a10,10 0,1 0,0 20a10,10 0,0 0,0 -20zM12,4a8,8 0,1 1,0 16a8,8 0,0 1,0 -16zM11,7h2v5.4l3.2,3.2l-1.4,1.4l-3.8,-3.8z" />
</vector>
@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorSurface">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorSurface"
app:menu="@menu/menu_main"
app:title="@string/app_name"
app:titleTextColor="?attr/colorOnSurface" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingHorizontal="12dp"
android:paddingVertical="6dp">
<ImageButton
android:id="@+id/previousDay"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/previous_day"
android:src="@android:drawable/ic_media_previous"
app:tint="?attr/colorOnSurface" />
<TextView
android:id="@+id/dateText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="17sp"
android:textStyle="bold" />
<ImageButton
android:id="@+id/nextDay"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/next_day"
android:src="@android:drawable/ic_media_next"
app:tint="?attr/colorOnSurface" />
<com.google.android.material.button.MaterialButton
android:id="@+id/todayButton"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="@string/today" />
</LinearLayout>
<TextView
android:id="@+id/syncStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingBottom="4dp"
android:text="@string/sync_local"
android:textColor="?attr/colorPrimary"
android:textSize="12sp" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/scheduleList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingTop="6dp"
android:paddingBottom="88dp" />
<TextView
android:id="@+id/emptyText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/empty_schedule"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="15sp"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="@string/add_schedule"
android:src="@drawable/ic_add"
app:tint="?attr/colorOnPrimary" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="22dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/title">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/titleInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="2" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/startButton"
style="@style/Widget.Material3.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/start" />
<Space
android:layout_width="10dp"
android:layout_height="1dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/endButton"
style="@style/Widget.Material3.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/end" />
</LinearLayout>
<TextView
android:id="@+id/errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:textColor="?attr/colorError"
android:textSize="12sp"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:gravity="end"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/cancelButton"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel" />
<com.google.android.material.button.MaterialButton
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save" />
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="22dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/server_url">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/serverUrlInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/server_url_hint"
android:imeOptions="actionDone"
android:inputType="textUri"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.materialswitch.MaterialSwitch
android:id="@+id/syncSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="@string/enable_sync" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="@string/settings_hint"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="12sp" />
</LinearLayout>
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="14dp"
android:layout_marginVertical="5dp"
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
app:cardCornerRadius="12dp"
app:cardElevation="1dp"
app:strokeWidth="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<CheckBox
android:id="@+id/doneCheck"
android:layout_width="48dp"
android:layout_height="48dp"
android:buttonTint="?attr/colorPrimary"
android:contentDescription="@string/save"
android:gravity="center" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingEnd="8dp">
<TextView
android:id="@+id/titleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="@+id/timeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="4dp"
android:textColor="?attr/colorOnSurfaceVariant"
android:textSize="12sp" />
</LinearLayout>
<TextView
android:id="@+id/statusText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/colorPrimary"
android:textSize="11sp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_sync"
android:title="@string/sync_now"
android:showAsAction="never" />
<item
android:id="@+id/action_settings"
android:title="@string/settings"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,6 @@
<resources>
<color name="seed">#4F6BED</color>
<color name="accent">#4F6BED</color>
<color name="surface">#F6F7FB</color>
<color name="surface_dark">#15171C</color>
</resources>
@@ -0,0 +1,37 @@
<resources>
<string name="app_name">AI 日程</string>
<string name="settings">设置</string>
<string name="sync_now">立即同步</string>
<string name="today">今天</string>
<string name="previous_day">前一天</string>
<string name="next_day">后一天</string>
<string name="add_schedule">新建日程</string>
<string name="empty_schedule">今天还没有安排</string>
<string name="sync_local">本地</string>
<string name="sync_not_configured">未配置同步服务</string>
<string name="sync_disabled">同步未启用</string>
<string name="sync_registering">正在注册设备…</string>
<string name="sync_busy">同步中…</string>
<string name="sync_done">已同步</string>
<string name="sync_offline">离线,等待重试</string>
<string name="delete_title">删除日程</string>
<string name="delete_message">确定删除「%1$s」吗?</string>
<string name="cancel">取消</string>
<string name="delete">删除</string>
<string name="save">保存</string>
<string name="title">标题</string>
<string name="start">开始</string>
<string name="end">结束</string>
<string name="title_hint">例如:写周报</string>
<string name="start_after_end">结束时间必须晚于开始时间</string>
<string name="title_required">请输入标题</string>
<string name="server_url">同步服务地址</string>
<string name="server_url_hint">http://192.168.1.2:8787</string>
<string name="enable_sync">启用多设备同步</string>
<string name="settings_hint">服务端需与手机在同一网络,或使用可访问的 HTTPS 地址。</string>
<string name="reminder_channel_name">日程提醒</string>
<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>
</resources>
@@ -0,0 +1,7 @@
<resources>
<style name="Theme.Schedule" parent="Theme.Material3.DayNight.NoActionBar">
<item name="colorPrimary">@color/seed</item>
<item name="colorSecondary">@color/accent</item>
<item name="android:fontFamily">sans</item>
</style>
</resources>
@@ -0,0 +1,27 @@
package com.misaki.schedule
import com.misaki.schedule.sync.Lww
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LwwTest {
@Test
fun newerRemoteWins() {
assertTrue(Lww.shouldApply("2026-10-26T10:00:00.000Z", "2026-10-26T10:00:00.001Z", false))
assertFalse(Lww.shouldApply("2026-10-26T10:00:00.002Z", "2026-10-26T10:00:00.001Z", false))
}
@Test
fun equalTimestampRules() {
val value = "2026-10-26T10:00:00.000Z"
assertFalse(Lww.shouldApply(value, value, false))
assertTrue(Lww.shouldApply(value, value, true))
}
@Test
fun missingLocalAlwaysApplies() {
assertTrue(Lww.shouldApply(null, "2026-10-26T10:00:00.000Z", false))
assertTrue(Lww.shouldApply("", "2026-10-26T10:00:00.000Z", true))
}
}
@@ -0,0 +1,30 @@
package com.misaki.schedule
import com.misaki.schedule.data.TimeUtils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
import java.time.LocalDateTime
class TimeUtilsTest {
@Test
fun roundTripsLocalDateTime() {
val value = LocalDateTime.of(2026, 10, 26, 9, 30)
val iso = TimeUtils.toIso(value)
assertEquals(value, TimeUtils.localTime(iso))
}
@Test
fun formatsTimeRange() {
assertEquals("09:00–10:30", TimeUtils.formatRange(
"2026-10-26T01:00:00.000Z",
"2026-10-26T02:30:00.000Z",
))
}
@Test
fun invalidTimestampIsSafe() {
assertNotNull(TimeUtils.nowIso())
assertEquals("--:--", TimeUtils.formatTime("not-a-time"))
}
}
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.5.2" apply false
id("org.jetbrains.kotlin.android") version "1.9.24" apply false
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+18
View File
@@ -0,0 +1,18 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ScheduleAndroid"
include(":app")
+3
View File
@@ -1,6 +1,9 @@
cmake_minimum_required(VERSION 3.24) cmake_minimum_required(VERSION 3.24)
find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Widgets Sql Network Concurrent WebSockets Test) find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Widgets Sql Network Concurrent WebSockets Test)
if(UNIX AND NOT APPLE)
find_package(Qt6 REQUIRED COMPONENTS DBus)
endif()
qt_standard_project_setup() qt_standard_project_setup()
+3
View File
@@ -115,6 +115,9 @@ target_link_libraries(schedule_ui
PUBLIC schedule_ai schedule_sync Qt6::Widgets ElaWidgetTools PUBLIC schedule_ai schedule_sync Qt6::Widgets ElaWidgetTools
PRIVATE schedule_warnings PRIVATE schedule_warnings
) )
if(UNIX AND NOT APPLE)
target_link_libraries(schedule_ui PRIVATE Qt6::DBus)
endif()
qt_add_executable(Schedule qt_add_executable(Schedule
main.cpp main.cpp
+1
View File
@@ -76,6 +76,7 @@ int main(int argc, char* argv[])
ScheduleService scheduleService(store, settings.deviceId()); ScheduleService scheduleService(store, settings.deviceId());
NotificationService notificationService(scheduleService); NotificationService notificationService(scheduleService);
notificationService.setLeadMinutes(settings.reminderLeadMinutes());
AIService aiService(scheduleService, store, settings); AIService aiService(scheduleService, store, settings);
SyncService syncService(scheduleService, store, settings); SyncService syncService(scheduleService, store, settings);
+99 -1
View File
@@ -3,12 +3,43 @@
#include <QAction> #include <QAction>
#include <QSystemTrayIcon> #include <QSystemTrayIcon>
#ifdef Q_OS_LINUX
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusReply>
#include <QStringList>
#include <QVariantMap>
#endif
#include "ElaMenu.h" #include "ElaMenu.h"
#include "ui/AppIcon.h" #include "ui/AppIcon.h"
SystemTray::SystemTray(QObject* parent) SystemTray::SystemTray(QObject* parent)
: QObject(parent) : QObject(parent)
{ {
#ifdef Q_OS_LINUX
m_notifications = new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QDBusConnection::sessionBus(),
this);
if (m_notifications->isValid())
{
QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("ActionInvoked"),
this,
SLOT(handleDbusAction(uint, QString)));
QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("NotificationClosed"),
this,
SLOT(handleDbusClosed(uint, uint)));
}
#endif
if (!QSystemTrayIcon::isSystemTrayAvailable()) if (!QSystemTrayIcon::isSystemTrayAvailable())
{ {
return; return;
@@ -33,7 +64,18 @@ SystemTray::SystemTray(QObject* parent)
break; break;
} }
}); });
connect(m_trayIcon, &QSystemTrayIcon::messageClicked, this, &SystemTray::showRequested); connect(m_trayIcon, &QSystemTrayIcon::messageClicked, this, [this]() {
if (!m_pendingBlockId.isEmpty())
{
const QString blockId = m_pendingBlockId;
m_pendingBlockId.clear();
Q_EMIT notificationClicked(blockId);
}
else
{
Q_EMIT showRequested();
}
});
} }
SystemTray::~SystemTray() SystemTray::~SystemTray()
@@ -73,13 +115,69 @@ void SystemTray::hide()
void SystemTray::showNotification(const QString& title, const QString& message, int timeoutMs) void SystemTray::showNotification(const QString& title, const QString& message, int timeoutMs)
{ {
showNotification(title, message, timeoutMs, QString());
}
void SystemTray::showNotification(const QString& title,
const QString& message,
int timeoutMs,
const QString& blockId)
{
#ifdef Q_OS_LINUX
if (m_notifications && m_notifications->isValid())
{
QStringList actions;
actions << QStringLiteral("default")
<< (blockId.isEmpty() ? QStringLiteral("打开应用") : QStringLiteral("打开日程"));
QVariantMap hints;
hints.insert(QStringLiteral("desktop-entry"), QStringLiteral("Schedule"));
const QDBusReply<uint> reply = m_notifications->call(QStringLiteral("Notify"),
QStringLiteral("AI 日程"),
0u,
QStringLiteral("x-office-calendar"),
title,
message,
actions,
hints,
timeoutMs);
if (reply.isValid())
{
m_dbusTargets.insert(reply.value(), blockId);
return;
}
}
#endif
if (!m_trayIcon || !m_trayIcon->isVisible()) if (!m_trayIcon || !m_trayIcon->isVisible())
{ {
return; return;
} }
m_pendingBlockId = blockId;
m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, timeoutMs); m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, timeoutMs);
} }
void SystemTray::handleDbusAction(uint id, const QString& key)
{
if (!key.isEmpty() && key != QStringLiteral("default"))
{
return;
}
const QString blockId = m_dbusTargets.take(id);
if (!blockId.isEmpty())
{
Q_EMIT notificationClicked(blockId);
}
else
{
Q_EMIT showRequested();
}
}
void SystemTray::handleDbusClosed(uint id, uint reason)
{
Q_UNUSED(reason)
m_dbusTargets.remove(id);
}
void SystemTray::setOverdueCount(int count) void SystemTray::setOverdueCount(int count)
{ {
m_overdueCount = count; m_overdueCount = count;
+15
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <QHash>
#include <QObject> #include <QObject>
#include <QString> #include <QString>
@@ -27,12 +28,21 @@ public:
void hide(); void hide();
void showNotification(const QString& title, const QString& message, int timeoutMs = 6000); void showNotification(const QString& title, const QString& message, int timeoutMs = 6000);
void showNotification(const QString& title,
const QString& message,
int timeoutMs,
const QString& blockId);
void setOverdueCount(int count); void setOverdueCount(int count);
signals: signals:
void showRequested(); void showRequested();
void newBlockRequested(); void newBlockRequested();
void quitRequested(); void quitRequested();
void notificationClicked(const QString& blockId);
private slots:
void handleDbusAction(uint id, const QString& key);
void handleDbusClosed(uint id, uint reason);
private: private:
void rebuildMenu(); void rebuildMenu();
@@ -41,4 +51,9 @@ private:
ElaMenu* m_menu = nullptr; ElaMenu* m_menu = nullptr;
QAction* m_statusAction = nullptr; QAction* m_statusAction = nullptr;
int m_overdueCount = 0; int m_overdueCount = 0;
QString m_pendingBlockId;
#ifdef Q_OS_LINUX
class QDBusInterface* m_notifications = nullptr;
QHash<uint, QString> m_dbusTargets;
#endif
}; };
+51 -1
View File
@@ -32,7 +32,8 @@ void NotificationService::stop()
void NotificationService::checkNow() void NotificationService::checkNow()
{ {
const QVector<ScheduleItem> current = m_scheduleService.overdueItems(QDateTime::currentDateTime()); const QDateTime now = QDateTime::currentDateTime();
const QVector<ScheduleItem> current = m_scheduleService.overdueItems(now);
QSet<QString> currentIds; QSet<QString> currentIds;
currentIds.reserve(current.size()); currentIds.reserve(current.size());
@@ -84,6 +85,55 @@ void NotificationService::checkNow()
{ {
Q_EMIT overdueListChanged(m_overdueItems); Q_EMIT overdueListChanged(m_overdueItems);
} }
const QVector<ScheduleItem> upcoming =
m_scheduleService.itemsForRange(now.date().addDays(-1), now.date().addDays(2));
for (const ScheduleItem& item : upcoming)
{
if (item.block.status != QStringLiteral("scheduled") &&
item.block.status != QStringLiteral("in_progress"))
{
continue;
}
if (!item.block.startAt.isValid() || !item.block.endAt.isValid())
{
continue;
}
const QString startKey = QStringLiteral("%1@%2")
.arg(item.block.id,
item.block.startAt.toUTC().toString(Qt::ISODateWithMs));
if (m_leadMinutes > 0 && now >= item.block.startAt.addSecs(-m_leadMinutes * 60) &&
now < item.block.startAt)
{
const QString leadKey = QStringLiteral("%1@%2").arg(startKey).arg(m_leadMinutes);
if (!m_leadNotifiedKeys.contains(leadKey))
{
m_leadNotifiedKeys.insert(leadKey);
Q_EMIT leadReminderDue(item, m_leadMinutes);
}
}
if (now >= item.block.startAt &&
now < item.block.endAt &&
now < item.block.startAt.addSecs(10 * 60))
{
const QString key = startKey + QStringLiteral("@start");
if (!m_startNotifiedKeys.contains(key))
{
m_startNotifiedKeys.insert(key);
Q_EMIT startReminderDue(item);
}
}
}
}
int NotificationService::leadMinutes() const
{
return m_leadMinutes;
}
void NotificationService::setLeadMinutes(int minutes)
{
m_leadMinutes = qBound(0, minutes, 24 * 60);
} }
QVector<ScheduleItem> NotificationService::overdueItems() const QVector<ScheduleItem> NotificationService::overdueItems() const
@@ -26,13 +26,21 @@ public:
void checkNow(); void checkNow();
QVector<ScheduleItem> overdueItems() const; QVector<ScheduleItem> overdueItems() const;
int leadMinutes() const;
void setLeadMinutes(int minutes);
signals: signals:
void overdueDetected(const ScheduleItem& item); void overdueDetected(const ScheduleItem& item);
void leadReminderDue(const ScheduleItem& item, int minutesBefore);
void startReminderDue(const ScheduleItem& item);
void overdueListChanged(const QVector<ScheduleItem>& items); void overdueListChanged(const QVector<ScheduleItem>& items);
private: private:
ScheduleService& m_scheduleService; ScheduleService& m_scheduleService;
QTimer m_timer; QTimer m_timer;
QSet<QString> m_notifiedIds; QSet<QString> m_notifiedIds;
QSet<QString> m_leadNotifiedKeys;
QSet<QString> m_startNotifiedKeys;
QVector<ScheduleItem> m_overdueItems; QVector<ScheduleItem> m_overdueItems;
int m_leadMinutes = 10;
}; };
+15
View File
@@ -1145,6 +1145,21 @@ bool ScheduleService::applyProposedCreates(const ProposedDiff& diff,
return applyProposedDiff(diff, acceptedTempIds, error); return applyProposedDiff(diff, acceptedTempIds, error);
} }
std::optional<ScheduleItem> ScheduleService::itemForBlock(const QString& blockId) const
{
const auto block = m_store.timeBlockById(blockId);
if (!block.has_value())
{
return std::nullopt;
}
const auto task = m_store.taskById(block->taskId);
if (!task.has_value())
{
return std::nullopt;
}
return ScheduleItem{*task, *block};
}
QVector<ScheduleItem> ScheduleService::itemsForDay(const QDate& date) const QVector<ScheduleItem> ScheduleService::itemsForDay(const QDate& date) const
{ {
auto items = m_store.blocksInRange(DateTimeUtils::localDayStartUtc(date), auto items = m_store.blocksInRange(DateTimeUtils::localDayStartUtc(date),
+1
View File
@@ -58,6 +58,7 @@ public:
QString* error = nullptr); QString* error = nullptr);
QVector<ScheduleItem> itemsForDay(const QDate& date) const; QVector<ScheduleItem> itemsForDay(const QDate& date) const;
std::optional<ScheduleItem> itemForBlock(const QString& blockId) const;
// 返回 [from, to] 闭区间内的所有日程,按开始时间升序。 // 返回 [from, to] 闭区间内的所有日程,按开始时间升序。
QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const; QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const;
QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const; QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const;
+33 -1
View File
@@ -193,6 +193,14 @@ void CompactWindow::buildUi()
void CompactWindow::setupTray() void CompactWindow::setupTray()
{ {
m_tray = new SystemTray(this); m_tray = new SystemTray(this);
connect(m_tray, &SystemTray::notificationClicked, this, [this](const QString& blockId) {
const auto item = m_scheduleService.itemForBlock(blockId);
openSchedule();
if (m_scheduleWindow && item.has_value())
{
m_scheduleWindow->focusBlock(item->block.startAt.date(), blockId);
}
});
if (!SystemTray::isAvailable()) if (!SystemTray::isAvailable())
{ {
return; return;
@@ -276,7 +284,7 @@ void CompactWindow::connectSignals()
QStringLiteral("「%1」原定 %2 尚未完成,点击打开处理。") QStringLiteral("「%1」原定 %2 尚未完成,点击打开处理。")
.arg(item.task.title, .arg(item.task.title,
DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt)); DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt));
m_tray->showNotification(QStringLiteral("日程超时"), body); m_tray->showNotification(QStringLiteral("日程超时"), body, 6000, item.block.id);
} }
if (isVisible()) if (isVisible())
{ {
@@ -288,6 +296,26 @@ void CompactWindow::connectSignals()
} }
}); });
connect(&m_notificationService, &NotificationService::leadReminderDue, this, [this](const ScheduleItem& item, int minutesBefore) {
if (m_tray)
{
const QString body = QStringLiteral("「%1」将在 %2 分钟后开始(%3)。")
.arg(item.task.title)
.arg(minutesBefore)
.arg(item.block.startAt.toString(QStringLiteral("HH:mm")));
m_tray->showNotification(QStringLiteral("日程即将开始"), body, 6000, item.block.id);
}
});
connect(&m_notificationService, &NotificationService::startReminderDue, this, [this](const ScheduleItem& item) {
if (m_tray)
{
const QString body = QStringLiteral("「%1」现在开始(%2)。")
.arg(item.task.title,
DateTimeUtils::formatTimeRange(item.block.startAt, item.block.endAt));
m_tray->showNotification(QStringLiteral("日程开始"), body, 6000, item.block.id);
}
});
connect(&m_themeManager, &ThemeManager::themeChanged, this, &CompactWindow::applyTheme); connect(&m_themeManager, &ThemeManager::themeChanged, this, &CompactWindow::applyTheme);
connect(&m_themeManager, &ThemeManager::preferenceChanged, this, [this](ThemeManager::Preference) { connect(&m_themeManager, &ThemeManager::preferenceChanged, this, [this](ThemeManager::Preference) {
applyTheme(m_themeManager.tokens()); applyTheme(m_themeManager.tokens());
@@ -377,6 +405,10 @@ void CompactWindow::openSettings()
{ {
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig); connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
} }
connect(&dialog, &SettingsDialog::reminderSettingsChanged, this, [this]() {
m_notificationService.setLeadMinutes(m_settings.reminderLeadMinutes());
m_notificationService.checkNow();
});
dialog.moveToCenter(); dialog.moveToCenter();
dialog.exec(); dialog.exec();
} }
+4
View File
@@ -867,6 +867,10 @@ void MainWindow::openSettings()
{ {
connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig); connect(&dialog, &SettingsDialog::syncSettingsChanged, m_syncService, &SyncService::reloadConfig);
} }
connect(&dialog, &SettingsDialog::reminderSettingsChanged, this, [this]() {
m_notificationService.setLeadMinutes(m_settings.reminderLeadMinutes());
m_notificationService.checkNow();
});
dialog.moveToCenter(); dialog.moveToCenter();
dialog.exec(); dialog.exec();
} }
+42 -1
View File
@@ -25,7 +25,7 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
{ {
setWindowTitle(QStringLiteral("设置")); setWindowTitle(QStringLiteral("设置"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint); setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(560, 720); resize(560, 820);
setMinimumWidth(520); setMinimumWidth(520);
auto* root = new QVBoxLayout(this); auto* root = new QVBoxLayout(this);
@@ -155,6 +155,39 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
keyNote->setWordWrap(true); keyNote->setWordWrap(true);
root->addWidget(keyNote); root->addWidget(keyNote);
addDivider();
addSectionTitle(QStringLiteral("日程提醒"));
auto* reminderDescription = new ElaText(
QStringLiteral("日程开始时发送系统通知;可额外提前 N 分钟再提醒一次。"),
11,
this);
reminderDescription->setTextStyle(ElaTextType::Caption);
reminderDescription->setWordWrap(true);
root->addWidget(reminderDescription);
auto* reminderRow = new QHBoxLayout();
reminderRow->setSpacing(16);
auto* reminderLabel = new ElaText(QStringLiteral("提前提醒"), 13, this);
m_reminderLeadCombo = new ElaComboBox(this);
const QList<int> leadValues = {0, 5, 10, 15, 30, 60};
for (int minutes : leadValues)
{
m_reminderLeadCombo->addItem(minutes == 0 ? QStringLiteral("仅开始时")
: QStringLiteral("提前 %1 分钟").arg(minutes));
}
int leadIndex = leadValues.indexOf(m_settings.reminderLeadMinutes());
if (leadIndex < 0)
{
leadIndex = 2;
}
m_reminderLeadCombo->setCurrentIndex(leadIndex);
m_reminderLeadCombo->setFixedSize(180, 32);
reminderRow->addWidget(reminderLabel, 0, Qt::AlignVCenter);
reminderRow->addWidget(m_reminderLeadCombo, 0, Qt::AlignVCenter);
reminderRow->addStretch(1);
root->addLayout(reminderRow);
addDivider(); addDivider();
addSectionTitle(QStringLiteral("同步服务")); addSectionTitle(QStringLiteral("同步服务"));
@@ -238,6 +271,14 @@ SettingsDialog::SettingsDialog(ThemeManager& themeManager, AppSettings& settings
connect(m_modelEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig); connect(m_modelEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig);
connect(m_apiKeyEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig); connect(m_apiKeyEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveAiConfig);
connect(m_keyVisibilityButton, &ElaToolButton::clicked, this, &SettingsDialog::toggleKeyVisibility); connect(m_keyVisibilityButton, &ElaToolButton::clicked, this, &SettingsDialog::toggleKeyVisibility);
connect(m_reminderLeadCombo, &ElaComboBox::currentIndexChanged, this, [this](int index) {
static const int values[] = {0, 5, 10, 15, 30, 60};
if (index >= 0 && index < 6)
{
m_settings.setReminderLeadMinutes(values[index]);
Q_EMIT reminderSettingsChanged();
}
});
connect(m_syncUrlEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveSyncConfig); connect(m_syncUrlEdit, &ElaLineEdit::editingFinished, this, &SettingsDialog::saveSyncConfig);
connect(m_syncEnabledSwitch, &ElaToggleSwitch::toggled, this, [this](bool) { saveSyncConfig(); }); connect(m_syncEnabledSwitch, &ElaToggleSwitch::toggled, this, [this](bool) { saveSyncConfig(); });
connect(doneButton, &ElaPushButton::clicked, this, [this]() { connect(doneButton, &ElaPushButton::clicked, this, [this]() {
+2
View File
@@ -24,6 +24,7 @@ public:
signals: signals:
void micaChanged(bool enabled); void micaChanged(bool enabled);
void syncSettingsChanged(); void syncSettingsChanged();
void reminderSettingsChanged();
private: private:
void saveAiConfig(); void saveAiConfig();
@@ -38,6 +39,7 @@ private:
ElaLineEdit* m_modelEdit = nullptr; ElaLineEdit* m_modelEdit = nullptr;
ElaLineEdit* m_apiKeyEdit = nullptr; ElaLineEdit* m_apiKeyEdit = nullptr;
ElaToolButton* m_keyVisibilityButton = nullptr; ElaToolButton* m_keyVisibilityButton = nullptr;
ElaComboBox* m_reminderLeadCombo = nullptr;
ElaLineEdit* m_syncUrlEdit = nullptr; ElaLineEdit* m_syncUrlEdit = nullptr;
ElaToggleSwitch* m_syncEnabledSwitch = nullptr; ElaToggleSwitch* m_syncEnabledSwitch = nullptr;
}; };
+19
View File
@@ -195,6 +195,10 @@ void AppSettings::load()
m_snapMinutes = normalizedSnap(intValue(ui, "snap_minutes", 15)); m_snapMinutes = normalizedSnap(intValue(ui, "snap_minutes", 15));
m_trayHintShown = boolValue(ui, "tray_hint_shown", false); m_trayHintShown = boolValue(ui, "tray_hint_shown", false);
} }
if (const toml::table* reminders = subTable(root, "reminders"))
{
m_reminderLeadMinutes = qBound(0, intValue(reminders, "lead_minutes", 10), 24 * 60);
}
if (const toml::table* window = subTable(root, "window")) if (const toml::table* window = subTable(root, "window"))
{ {
m_compactGeometry = QByteArray::fromBase64(stringValue(window, "compact_geometry").toLatin1()); m_compactGeometry = QByteArray::fromBase64(stringValue(window, "compact_geometry").toLatin1());
@@ -288,6 +292,10 @@ void AppSettings::save()
ui.insert("tray_hint_shown", m_trayHintShown); ui.insert("tray_hint_shown", m_trayHintShown);
root.insert("ui", std::move(ui)); root.insert("ui", std::move(ui));
toml::table reminders;
reminders.insert("lead_minutes", m_reminderLeadMinutes);
root.insert("reminders", std::move(reminders));
toml::table window; toml::table window;
window.insert("compact_geometry", m_compactGeometry.toBase64().toStdString()); window.insert("compact_geometry", m_compactGeometry.toBase64().toStdString());
window.insert("schedule_geometry", m_scheduleGeometry.toBase64().toStdString()); window.insert("schedule_geometry", m_scheduleGeometry.toBase64().toStdString());
@@ -395,6 +403,17 @@ void AppSettings::setSnapMinutes(int minutes)
save(); save();
} }
int AppSettings::reminderLeadMinutes() const
{
return m_reminderLeadMinutes;
}
void AppSettings::setReminderLeadMinutes(int minutes)
{
m_reminderLeadMinutes = qBound(0, minutes, 24 * 60);
save();
}
bool AppSettings::trayHintShown() const bool AppSettings::trayHintShown() const
{ {
return m_trayHintShown; return m_trayHintShown;
+4
View File
@@ -47,6 +47,9 @@ public:
int snapMinutes() const; int snapMinutes() const;
void setSnapMinutes(int minutes); void setSnapMinutes(int minutes);
int reminderLeadMinutes() const;
void setReminderLeadMinutes(int minutes);
bool trayHintShown() const; bool trayHintShown() const;
void setTrayHintShown(bool shown); void setTrayHintShown(bool shown);
@@ -80,6 +83,7 @@ private:
QString m_themePreference = QStringLiteral("system"); QString m_themePreference = QStringLiteral("system");
bool m_micaEnabled = false; bool m_micaEnabled = false;
int m_snapMinutes = 15; int m_snapMinutes = 15;
int m_reminderLeadMinutes = 10;
bool m_trayHintShown = false; bool m_trayHintShown = false;
QByteArray m_compactGeometry; QByteArray m_compactGeometry;
QByteArray m_scheduleGeometry; QByteArray m_scheduleGeometry;
+3
View File
@@ -28,6 +28,7 @@ void TestConfig::defaultsAndRoundTrip()
QCOMPARE(settings.themePreference(), QStringLiteral("system")); QCOMPARE(settings.themePreference(), QStringLiteral("system"));
QCOMPARE(settings.micaEnabled(), false); QCOMPARE(settings.micaEnabled(), false);
QCOMPARE(settings.snapMinutes(), 15); QCOMPARE(settings.snapMinutes(), 15);
QCOMPARE(settings.reminderLeadMinutes(), 10);
QCOMPARE(settings.trayHintShown(), false); QCOMPARE(settings.trayHintShown(), false);
QCOMPARE(settings.aiConfig().baseUrl, QStringLiteral("https://api.openai.com/v1")); QCOMPARE(settings.aiConfig().baseUrl, QStringLiteral("https://api.openai.com/v1"));
QCOMPARE(settings.aiConfig().model, QStringLiteral("gpt-4o-mini")); QCOMPARE(settings.aiConfig().model, QStringLiteral("gpt-4o-mini"));
@@ -39,6 +40,7 @@ void TestConfig::defaultsAndRoundTrip()
settings.setThemePreference(QStringLiteral("dark")); settings.setThemePreference(QStringLiteral("dark"));
settings.setMicaEnabled(true); settings.setMicaEnabled(true);
settings.setSnapMinutes(30); settings.setSnapMinutes(30);
settings.setReminderLeadMinutes(30);
settings.setTrayHintShown(true); settings.setTrayHintShown(true);
settings.setCompactGeometry(QByteArray("compact-geometry")); settings.setCompactGeometry(QByteArray("compact-geometry"));
settings.setScheduleGeometry(QByteArray("schedule-geometry")); settings.setScheduleGeometry(QByteArray("schedule-geometry"));
@@ -63,6 +65,7 @@ void TestConfig::defaultsAndRoundTrip()
QCOMPARE(reloaded.themePreference(), QStringLiteral("dark")); QCOMPARE(reloaded.themePreference(), QStringLiteral("dark"));
QCOMPARE(reloaded.micaEnabled(), true); QCOMPARE(reloaded.micaEnabled(), true);
QCOMPARE(reloaded.snapMinutes(), 30); QCOMPARE(reloaded.snapMinutes(), 30);
QCOMPARE(reloaded.reminderLeadMinutes(), 30);
QCOMPARE(reloaded.trayHintShown(), true); QCOMPARE(reloaded.trayHintShown(), true);
QCOMPARE(reloaded.compactGeometry(), QByteArray("compact-geometry")); QCOMPARE(reloaded.compactGeometry(), QByteArray("compact-geometry"));
QCOMPARE(reloaded.scheduleGeometry(), QByteArray("schedule-geometry")); QCOMPARE(reloaded.scheduleGeometry(), QByteArray("schedule-geometry"));
+35
View File
@@ -28,6 +28,7 @@ private slots:
void energyProfileLearnsFromHistory(); void energyProfileLearnsFromHistory();
void searchFindsSchedules(); void searchFindsSchedules();
void createsRecurringSchedules(); void createsRecurringSchedules();
void startAndLeadReminders();
}; };
namespace namespace
@@ -439,5 +440,39 @@ void TestServices::createsRecurringSchedules()
QVERIFY(!error.isEmpty()); QVERIFY(!error.isEmpty());
} }
void TestServices::startAndLeadReminders()
{
Context context;
QVERIFY(context.open());
const QDateTime now = QDateTime::currentDateTime();
QString error;
QVERIFY(context.service->createBlock(QStringLiteral("即将开始"),
now.addSecs(5 * 60),
now.addSecs(65 * 60),
&error));
QVERIFY(context.service->createBlock(QStringLiteral("已经开始"),
now.addSecs(-5 * 60),
now.addSecs(55 * 60),
&error));
NotificationService notifications(*context.service);
QSignalSpy leadSpy(&notifications, &NotificationService::leadReminderDue);
QSignalSpy startSpy(&notifications, &NotificationService::startReminderDue);
notifications.checkNow();
QCOMPARE(leadSpy.count(), 1);
QCOMPARE(startSpy.count(), 1);
QCOMPARE(leadSpy.first().at(0).value<ScheduleItem>().task.title, QStringLiteral("即将开始"));
QCOMPARE(leadSpy.first().at(1).toInt(), 10);
QCOMPARE(startSpy.first().at(0).value<ScheduleItem>().task.title, QStringLiteral("已经开始"));
notifications.checkNow();
QCOMPARE(leadSpy.count(), 1);
QCOMPARE(startSpy.count(), 1);
notifications.setLeadMinutes(0);
QCOMPARE(leadSpy.count(), 1);
}
QTEST_GUILESS_MAIN(TestServices) QTEST_GUILESS_MAIN(TestServices)
#include "test_services.moc" #include "test_services.moc"
+23 -2
View File
@@ -10,6 +10,8 @@
> 阶段 3(Go 同步服务端 / 多设备)已验证:[`validation/phase-3.md`](validation/phase-3.md)。 > 阶段 3(Go 同步服务端 / 多设备)已验证:[`validation/phase-3.md`](validation/phase-3.md)。
> 阶段 4(精力曲线 / 幽灵时间 / 每日复盘 / 主动建议)已验证:[`validation/phase-4.md`](validation/phase-4.md)。 > 阶段 4(精力曲线 / 幽灵时间 / 每日复盘 / 主动建议)已验证:[`validation/phase-4.md`](validation/phase-4.md)。
> 阶段 4.1(搜索 / 重复日程 / Windows 安装包 / 动画)已验证:[`validation/phase-4-1.md`](validation/phase-4-1.md)。 > 阶段 4.1(搜索 / 重复日程 / Windows 安装包 / 动画)已验证:[`validation/phase-4-1.md`](validation/phase-4-1.md)。
> 阶段 4.2(桌面开始提醒 / 原生通知 / 点击定位)已验证:[`validation/phase-4-2.md`](validation/phase-4-2.md)。
> 阶段 5.0(Android 同步客户端)已构建验证:[`validation/phase-5.md`](validation/phase-5.md)。
## 0. 当前环境 ## 0. 当前环境
@@ -27,6 +29,7 @@
``` ```
Schedule/ Schedule/
├── CMakeLists.txt / CMakePresets.json ├── CMakeLists.txt / CMakePresets.json
├── android/ # Android 同步客户端(阶段 5)
├── client/ ├── client/
│ ├── CMakeLists.txt │ ├── CMakeLists.txt
│ ├── 3rd/ElaWidgetTools/ # git submodule │ ├── 3rd/ElaWidgetTools/ # git submodule
@@ -142,8 +145,26 @@ Schedule/
- [x] 轻量动画:窗口/对话框淡入、视图切换淡入、任务列表与 Diff 卡片淡入 - [x] 轻量动画:窗口/对话框淡入、视图切换淡入、任务列表与 Diff 卡片淡入
- 验收:`ctest --preset linux-gcc` 12/12;见 [`validation/phase-4-1.md`](validation/phase-4-1.md) - 验收:`ctest --preset linux-gcc` 12/12;见 [`validation/phase-4-1.md`](validation/phase-4-1.md)
### 阶段 5:移动端(后续) ### 阶段 4.2:桌面日程提醒与原生通知(已完成)
- Android 优先,复用同步协议与逻辑层 - [x] 开始时提醒 + 提前 N 分钟提醒(0/5/10/15/30/60)
- [x] 保留结束未完成提醒
- [x] Linux DBus 原生通知;Windows/macOS 系统托盘通知
- [x] 通知点击打开详细日程并定位时间块
- [x] 设置页提前提醒选项、TOML `[reminders] lead_minutes`
- 验收:`ctest --preset linux-gcc` 12/12;见 [`validation/phase-4-2.md`](validation/phase-4-2.md)
### 阶段 5.0:Android 同步客户端(已完成 v1)
- [x] 独立 Kotlin/Android 工程,不依赖 Qt
- [x] SQLite task/timeblock/outbox/sync_state、LWW、删除墓碑
- [x] 设备注册、push/pull、WebSocket + 轮询、设置页
- [x] 今日列表、日期切换、完成/编辑/删除/新建、Material 3
- [x] Debug APK 构建成功;JVM 单元测试 6/6
- [x] 本地通知提醒(结束未完成)、通知权限、通知点击回到日期
- [x] WorkManager 15 分钟后台同步、开机广播重建任务
- [ ] 真机/模拟器交互验证
- [ ] AI 对话 / 附件 / 精力曲线 / 复盘 / 重复日程创建
- [ ] FCM 即时推送、精确提醒、Keystore、发布签名
- 验收:`assembleDebug` + `testDebugUnitTest`;见 [`validation/phase-5.md`](validation/phase-5.md)
## 3. 质量门槛(每阶段) ## 3. 质量门槛(每阶段)
@@ -0,0 +1,61 @@
To honour the JVM settings for this build a single-use Daemon process will be forked. For more on this, please refer to https://docs.gradle.org/8.7/userguide/gradle_daemon.html#sec:disabling_the_daemon in the Gradle documentation.
Daemon will be stopped at the end of the build
> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
> Task :app:checkKotlinGradlePluginConfigurationErrors
> Task :app:checkDebugAarMetadata UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:mapDebugSourceSetPaths UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources UP-TO-DATE
> Task :app:packageDebugResources UP-TO-DATE
> Task :app:parseDebugLocalResources UP-TO-DATE
> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
> Task :app:extractDeepLinksDebug UP-TO-DATE
> Task :app:processDebugMainManifest UP-TO-DATE
> Task :app:processDebugManifest UP-TO-DATE
> Task :app:processDebugManifestForPackage UP-TO-DATE
> Task :app:processDebugResources UP-TO-DATE
> Task :app:compileDebugKotlin UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:compileDebugJavaWithJavac NO-SOURCE
> Task :app:mergeDebugShaders UP-TO-DATE
> Task :app:compileDebugShaders NO-SOURCE
> Task :app:generateDebugAssets UP-TO-DATE
> Task :app:mergeDebugAssets UP-TO-DATE
> Task :app:compressDebugAssets UP-TO-DATE
> Task :app:desugarDebugFileDependencies UP-TO-DATE
> Task :app:dexBuilderDebug UP-TO-DATE
> Task :app:mergeDebugGlobalSynthetics UP-TO-DATE
> Task :app:processDebugJavaRes UP-TO-DATE
> Task :app:mergeDebugJavaResource UP-TO-DATE
> Task :app:checkDebugDuplicateClasses UP-TO-DATE
> Task :app:mergeDebugStartupProfile UP-TO-DATE
> Task :app:mergeExtDexDebug UP-TO-DATE
> Task :app:mergeLibDexDebug UP-TO-DATE
> Task :app:mergeProjectDexDebug UP-TO-DATE
> Task :app:mergeDebugJniLibFolders UP-TO-DATE
> Task :app:mergeDebugNativeLibs NO-SOURCE
> Task :app:stripDebugDebugSymbols NO-SOURCE
> Task :app:validateSigningDebug UP-TO-DATE
> Task :app:writeDebugAppMetadata UP-TO-DATE
> Task :app:writeDebugSigningConfigVersions UP-TO-DATE
> Task :app:packageDebug UP-TO-DATE
> Task :app:createDebugApkListingFileRedirect UP-TO-DATE
> Task :app:assembleDebug UP-TO-DATE
> Task :app:bundleDebugClassesToRuntimeJar UP-TO-DATE
> Task :app:bundleDebugClassesToCompileJar UP-TO-DATE
> Task :app:compileDebugUnitTestKotlin UP-TO-DATE
> Task :app:preDebugUnitTestBuild UP-TO-DATE
> Task :app:javaPreCompileDebugUnitTest UP-TO-DATE
> Task :app:compileDebugUnitTestJavaWithJavac NO-SOURCE
> Task :app:processDebugUnitTestJavaRes UP-TO-DATE
> Task :app:testDebugUnitTest UP-TO-DATE
BUILD SUCCESSFUL in 8s
41 actionable tasks: 1 executed, 40 up-to-date
APK: android/app/build/outputs/apk/debug/app-debug.apk (6.5 MB)
JVM unit tests: TimeUtilsTest 3 passed; LwwTest 3 passed; 0 failures.
+29
View File
@@ -0,0 +1,29 @@
Test project /home/misaki/MisakiCodes/Schedule/build/linux-gcc
Start 1: go_server_tests
1/12 Test #1: go_server_tests .................. Passed 0.09 sec
Start 2: storage
2/12 Test #2: storage .......................... Passed 0.02 sec
Start 3: services
3/12 Test #3: services ......................... Passed 0.05 sec
Start 4: grid
4/12 Test #4: grid ............................. Passed 0.38 sec
Start 5: mainwindow
5/12 Test #5: mainwindow ....................... Passed 1.25 sec
Start 6: compactwindow
6/12 Test #6: compactwindow .................... Passed 4.31 sec
Start 7: config
7/12 Test #7: config ........................... Passed 0.01 sec
Start 8: scheduler
8/12 Test #8: scheduler ........................ Passed 0.01 sec
Start 9: energy
9/12 Test #9: energy ........................... Passed 0.01 sec
Start 10: ai
10/12 Test #10: ai ............................... Passed 0.11 sec
Start 11: openai_provider
11/12 Test #11: openai_provider .................. Passed 0.21 sec
Start 12: sync_integration
12/12 Test #12: sync_integration ................. Passed 7.71 sec
100% tests passed, 0 tests failed out of 12
Total Test time (real) = 14.17 sec
+69
View File
@@ -0,0 +1,69 @@
# 阶段 4.2 验证报告:桌面开始提醒 / 原生通知 / 点击定位
> 日期:2026-10-26
> 环境:Ubuntu 24.04 / GCC 13.3 / Qt 6.6.3(Linux DBus 通知)
## 1. 本次交付
1. **开始时间提醒**:时间块到达开始时间后发送系统通知;20 秒轮询,最多有 20 秒延迟。为避免启动时补发过多历史提醒,开始提醒只覆盖开始后 10 分钟内。
2. **提前 N 分钟提醒**:设置页可选择 0(仅开始时)、5、10、15、30、60 分钟;提前量保存在 TOML `[reminders] lead_minutes`。
3. **保留超时提醒**:结束时间后仍未完成的日程继续通知,并支持点击定位。
4. **原生通知**:
- Linux:`org.freedesktop.Notifications` DBus `Notify`,支持 `ActionInvoked`「打开日程」动作。
- Windows/macOS:`QSystemTrayIcon` 系统托盘通知,使用 `messageClicked` 处理点击。
5. **点击定位**:通知携带 block id;点击后打开详细日程并按日期定位到对应时间块。Linux DBus 使用通知 id → block id 映射;Windows/macOS 使用待处理 block id。
6. **设置同步**:设置对话框修改提前分钟后立即更新 NotificationService,并重新检查当前提醒。
## 2. 构建与自动化测试
```bash
cmake --preset linux-gcc
cmake --build --preset linux-gcc --clean-first -j$(nproc)
ctest --preset linux-gcc
```
| 项目 | 结果 |
|---|---|
| 客户端全量构建 | 成功,0 警告(`-Werror`) |
| `ctest --preset linux-gcc` | **12/12 通过** |
| 新增提醒测试 | `NotificationService` 提前/开始提醒各一次,重复检查不重复通知 |
| 配置测试 | `[reminders] lead_minutes` 默认值/写入/重载 |
完整输出见 [`ctest-phase-4-2.txt`](ctest-phase-4-2.txt)。
## 3. 界面截图
| 截图 | 说明 |
|---|---|
| [`settings-dark.png`](settings-dark.png) | 设置 · 日程提前提醒(深色) |
| [`settings-light.png`](settings-light.png) | 设置 · 日程提前提醒(浅色) |
系统通知截图未保存:当前验证环境没有可交互的桌面通知中心;通知发送路径通过代码审查和 Linux DBus 编译验证。
## 4. 行为说明
- 应用必须运行(窗口可最小化到托盘)。完全退出后不会提醒。
- 开始提醒:`now >= start` 且 `now < end` 且开始时间不超过 10 分钟前;只提醒一次。
- 提前提醒:`start - N <= now < start`;只提醒一次。
- 超时提醒:`now >= end` 且状态仍为 scheduled/in_progress;沿用原有逻辑。
- 提前量为 0 时不发提前提醒,仅开始时提醒。
- 通知点击:Linux DBus 点击「打开日程」;Windows/macOS 点击托盘通知。
- 通知状态只保存在内存,重启应用后可能再次提醒。
- 没有桌面开机自启(按要求未添加)。
## 5. 已知限制
1. 20 秒轮询不是精确闹钟;系统休眠或应用被挂起时可能延迟。
2. 应用必须运行;退出进程后无法提醒。
3. Linux 通知动作取决于桌面通知服务是否支持 actions;不支持时仍会显示通知,但点击可能只聚焦应用。
4. Windows/macOS 使用 Qt 托盘通知,具体视觉样式由系统决定;不是自绘窗口。
5. 通知去重仅在内存;重启后同一开始/提前提醒可能再次出现。
6. 没有开机自启(用户明确不要求)。
## 6. 人工验收建议
1. 设置提前提醒为 5 分钟,创建一条 6 分钟后开始的日程;等待/触发检查,确认收到系统通知。
2. 到开始时间再次收到「日程开始」通知;点击通知,确认打开详细日程并定位。
3. 把提前提醒改为「仅开始时」,确认不再出现提前通知。
4. 创建一条已结束但未完成的日程,确认原有超时通知仍工作且点击定位。
5. 最小化到托盘/隐藏主窗口,确认通知仍出现;退出应用后确认不再提醒。
+85
View File
@@ -0,0 +1,85 @@
# 阶段 5 验证报告:Android 同步客户端 v1
> 日期:2026-10-26
> 环境:Ubuntu 24.04 / JDK 21 / Android SDK 34 / Build-Tools 34.0.0 / Gradle 8.7 / AGP 8.5.2 / Kotlin 1.9.24
## 1. 本次交付
新增独立 Android 工程 `android/`,不依赖 Qt,直接复用阶段 3 的同步协议:
- Kotlin + 原生 View(Material 3)。
- 本地 SQLite:`task`、`timeblock`、`outbox`、`sync_state`,外键级联。
- 今日日程:日期切换、完成/取消完成、编辑、长按删除、FAB 新建。
- 同步:设备注册、outbox 推送、按 `seq` 增量拉取、`updated_at` LWW、WebSocket 通知、15 秒轮询兜底。
- 设置:服务地址、启用开关;首次启用自动注册。
- 提醒:`ReminderWorker` 每 15 分钟检查过去 24 小时内结束且未完成的日程,发本地通知;通知点击回到对应日期。
- 后台:`SyncWorker` 由 WorkManager 每 15 分钟执行;`BOOT_COMPLETED` 广播重建同步/提醒任务。
- 单测:LWW 时间比较、时间格式与 ISO 转换。
## 2. 构建与测试
```bash
cd android
./gradlew :app:assembleDebug
./gradlew :app:testDebugUnitTest
```
| 项目 | 结果 |
|---|---|
| Debug APK | 构建成功:`android/app/build/outputs/apk/debug/app-debug.apk`(约 6.5 MB) |
| JVM 单元测试 | 6/6 通过(LwwTest 3 + TimeUtilsTest 3) |
| `aapt dump badging` | package `com.misaki.schedule`,minSdk 26,targetSdk 34;包含通知/开机权限和 WorkManager 服务 |
完整构建/测试输出见 [`android-build-test-phase-5.txt`](android-build-test-phase-5.txt)。
## 3. 协议兼容性
Android 发送与桌面端相同的字段:
- task:id/title/description/source/source_ref/estimated_min/energy_req/deadline/priority/status/created_at/updated_at/version/device_id
- timeblock:id/task_id/start_at/end_at/granularity/splittable/breakable/status/done_at/created_at/updated_at/version/device_id
- change:entity_type/entity_id/op/version/updated_at/payload
客户端行为:
- 同一实体按 `updated_at` LWW;删除在等时间戳时优先。
- 不同日程同一时间都保留,不做自动合并。
- 本地删除会写入删除时刻的顶层 `updated_at`,避免墓碑被旧时间戳忽略。
- 重复日程在 Android 上以物化后的普通 timeblock 显示。
- 精力曲线、复盘、AI 对话不参与 Android v1。
- 提醒为本地通知,不是服务端推送;后台同步周期为 15 分钟,受 Doze/厂商限制。
## 4. 运行与配置
```bash
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
服务端:
```bash
cd server
SYNC_TOKEN_PEPPER=<固定随机值> go run ./cmd/server
```
- 手机与电脑同一局域网,App 设置填 `http://<电脑IP>:8787`。
- 模拟器访问宿主机填 `http://10.0.2.2:8787`。
- Android Manifest 允许明文 HTTP,便于局域网自部署;公网必须用 HTTPS 反向代理。
- Token 保存在 SharedPreferences,未接入 Keystore。
## 5. 已知限制
1. 当前没有设备/模拟器可用,**未进行 Android 真机交互验证**;只验证了 APK 编译与 JVM 单元测试。
2. Android v1 没有 AI 对话、文件附件、精力曲线、复盘、主动建议和重复日程创建;重复日程只显示已物化块。
3. 无后台同步(WorkManager)和系统通知;Application 进入后台会停止同步。
4. 没有发布签名、Play Store 打包、崩溃上报与自动更新。
5. 明文 HTTP 仅适合本地/局域网;公网必须 HTTPS。
6. 同步冲突策略沿用桌面 LWW:同一时间的不同日程不会自动合并。
## 6. 后续移动端工作
- FCM 即时推送 + 精确提醒(AlarmManager 或服务端调度)。
- 移动端 AI 对话与文件上传/提取;需要服务端增加附件能力。
- 移动端重复日程创建、精力/复盘视图。
- Android Keystore 保存 Token、HTTPS 默认、发布签名。
- 真机/模拟器交互测试与截图。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 93 KiB