diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..cdef0c6d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# CMake embeds a digest of these exact source bytes into the prebuilt reader. +# Keep checkouts identical on Windows and Linux so the artifact check is stable. +ohos/entry/src/main/cpp/** text eol=lf diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index 6a6765d3..d08eba53 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -61,3 +61,11 @@ jobs: - name: Test run: flutter test + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Test watch protocol, signing configuration and feedback recovery + run: node --test harmonyos_watch/scripts/*.test.cjs harmonyos_watch/scripts/*.test.mjs web/feedback/test/*.test.mjs diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml index 0fe63891..c11c35b2 100644 --- a/.github/workflows/android-release.yml +++ b/.github/workflows/android-release.yml @@ -267,6 +267,116 @@ jobs: exit 1 fi + # Prebuilt plugin JNI can remain 4 KB aligned even with a new NDK. + python3 - "$apk" --zipalign "$(dirname "$aapt")/zipalign" <<'PY_16KB' + #!/usr/bin/env python3 + """Check 64-bit ELF LOAD alignment and uncompressed APK library offsets. + + Read-only; uses Python's standard library. Optionally also run SDK zipalign. + This verifies packaging/linker alignment, not runtime page-size assumptions. + """ + + import argparse + import struct + import subprocess + import sys + import zipfile + from pathlib import Path + + PAGE_SIZE = 16384 + MACHINES = {"arm64-v8a": 183, "x86_64": 62} + + + def check_elf(stream, abi): + header = stream.read(64) + if (len(header) < 64 or header[:4] != b"\x7fELF" or + header[4:6] != b"\x02\x01"): + raise ValueError("expected little-endian ELF64") + if struct.unpack_from(" + + + diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt b/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt index 5d7cbcf3..39a1c5c6 100644 --- a/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt +++ b/android/app/src/main/kotlin/club/geekpie/techpie/MainActivity.kt @@ -14,6 +14,7 @@ import android.provider.CalendarContract.Events import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import club.geekpie.techpie.ecardbind.EcardBindVpnService +import club.geekpie.techpie.wear.WearEngineBridge import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodCall @@ -25,6 +26,7 @@ class MainActivity : FlutterActivity() { private val mainHandler = Handler(Looper.getMainLooper()) private var ecardWidgets: EcardWidgetBridge? = null private var ecardFeedback: EcardFeedback? = null + private var wearEngine: WearEngineBridge? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) @@ -32,6 +34,7 @@ class MainActivity : FlutterActivity() { it.capture(intent, notifyFlutter = false) } ecardFeedback = EcardFeedback(this, flutterEngine.dartExecutor.binaryMessenger) + wearEngine = WearEngineBridge(this, flutterEngine.dartExecutor.binaryMessenger) MethodChannel( flutterEngine.dartExecutor.binaryMessenger, @@ -82,6 +85,8 @@ class MainActivity : FlutterActivity() { ecardWidgets = null ecardFeedback?.dispose() ecardFeedback = null + wearEngine?.dispose() + wearEngine = null super.cleanUpFlutterEngine(flutterEngine) } diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearEngineBridge.kt b/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearEngineBridge.kt new file mode 100644 index 00000000..bfdb8e19 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearEngineBridge.kt @@ -0,0 +1,218 @@ +package club.geekpie.techpie.wear + +import android.app.Activity +import android.os.Handler +import android.os.Looper +import android.util.Log +import com.huawei.wearengine.HiWear +import com.huawei.wearengine.WearEngineException +import com.huawei.wearengine.auth.AuthCallback +import com.huawei.wearengine.auth.Permission +import com.huawei.wearengine.client.ServiceConnectionListener +import com.huawei.wearengine.device.Device +import com.huawei.wearengine.p2p.Message +import com.huawei.wearengine.p2p.Receiver +import com.huawei.wearengine.p2p.SendCallback +import com.huawei.wearengine.p2p.PingCallback +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import java.util.concurrent.atomic.AtomicBoolean + +/** Native transport only. Product acknowledgements are processed in Dart. */ +class WearEngineBridge(private val activity: Activity, messenger: BinaryMessenger) { + private val channel = MethodChannel(messenger, "techpie/wear_engine") + private val handler = Handler(Looper.getMainLooper()) + private var selected: Device? = null + private var receiver: Receiver? = null + private var disposed = false + private var serviceReady = false + private var releasing = false + private var generation = 0 + private val poll = object : Runnable { + override fun run() { + val device = selected ?: return + val epoch = generation + HiWear.getDeviceClient(activity).bondedDevices.addOnSuccessListener { devices -> + if (epoch == generation && devices.none { it.uuid == device.uuid && it.isConnected }) { + closeTransport() + event("state", mapOf("device" to "disconnected")) + } + }.addOnFailureListener { event("state", mapOf("service" to "unavailable")) } + handler.postDelayed(this, 5000) + } + } + private val p2p by lazy { HiWear.getP2pClient(activity) } + private val auth by lazy { HiWear.getAuthClient(activity) } + private val service by lazy { + HiWear.getWearEngineClient(activity, object : ServiceConnectionListener { + override fun onServiceConnect() { + if (!releasing && !disposed) { serviceReady = true; emitState("ready") } + } + override fun onServiceDisconnect() { + serviceReady = false + if (!releasing && selected != null) { + generation++ + selected = null + receiver = null + emitState("unavailable") + } + } + }) + } + + init { channel.setMethodCallHandler(::handle) } + + private fun event(method: String, data: Any?) = handler.post { + if (!disposed) channel.invokeMethod(method, data) + } + private fun emitState(state: String) = event("state", mapOf("service" to state)) + private fun fail(result: MethodChannel.Result, error: Exception) { + val code = (error as? WearEngineException)?.errorCode + Log.w("TechPieWear", "SDK failure: code=$code, type=${error.javaClass.simpleName}") + handler.post { result.error("SERVICE_UNAVAILABLE", "Wear Engine operation failed", code) } + } + private fun handle(call: MethodCall, result: MethodChannel.Result) { + try { + when (call.method) { + "status" -> { + auth.checkPermissions(arrayOf(Permission.DEVICE_MANAGER, Permission.NOTIFY)) + .addOnSuccessListener { grants -> + handler.post { result.success(mapOf( + "service" to if (serviceReady) "ready" else "unavailable", + "device" to if (selected?.isConnected == true) "connected" else "disconnected", + "permission" to mapOf("p2p" to (grants.getOrNull(0) == true), + "notify" to (grants.getOrNull(1) == true)))) } + }.addOnFailureListener { fail(result, it) } + } + "authorize" -> { + Log.i("TechPieWear", "Requesting device authorization") + val includeNotify = call.argument("notify") == true + val permissions = if (includeNotify) arrayOf(Permission.DEVICE_MANAGER, Permission.NOTIFY) + else arrayOf(Permission.DEVICE_MANAGER) + val answered = AtomicBoolean(false) + auth.requestPermission(object : AuthCallback { + override fun onOk(grants: Array) { + Log.i("TechPieWear", "Device authorization granted=${grants.contains(Permission.DEVICE_MANAGER)}") + if (answered.compareAndSet(false, true)) handler.post { + result.success(mapOf("p2p" to grants.contains(Permission.DEVICE_MANAGER), + "notify" to grants.contains(Permission.NOTIFY))) + } + } + override fun onCancel() { + if (answered.compareAndSet(false, true)) handler.post { + result.error("PERMISSION_DENIED", "Wear Engine authorization cancelled", null) + } + } + }, *permissions).addOnFailureListener { + if (answered.compareAndSet(false, true)) fail(result, it) + } + } + "devices" -> HiWear.getDeviceClient(activity).bondedDevices + .addOnSuccessListener { devices -> handler.post { + Log.i("TechPieWear", "Device query count=${devices.size}") + result.success(devices.map { mapOf("id" to it.uuid, "name" to it.name, + "model" to it.model, "connected" to it.isConnected) }) + } }.addOnFailureListener { fail(result, it) } + "open" -> { + val id = requireNotNull(call.argument("deviceId")) + val fingerprint = requireNotNull(call.argument("fingerprint")) + require(fingerprint.length in 1..512 && fingerprint.none { it.isWhitespace() }) + closeTransport() + val epoch = generation + HiWear.getDeviceClient(activity).bondedDevices.addOnSuccessListener { devices -> + if (epoch != generation || disposed) { + handler.post { result.error("SESSION_MISMATCH", "Connection was cancelled", null) } + return@addOnSuccessListener + } + val device = devices.firstOrNull { it.uuid == id && it.isConnected } + if (device == null) { + handler.post { result.error("DEVICE_DISCONNECTED", "Selected device is not connected", null) } + return@addOnSuccessListener + } + p2p.setPeerPkgName("com.geekpie.techpie.watch").setPeerFingerPrint(fingerprint) + val listener = Receiver { message -> + if (epoch == generation && message.type == Message.MESSAGE_TYPE_DATA) { + message.data?.let { event("frame", it) } + } + } + receiver = listener + selected = device + p2p.registerReceiver(device, listener).addOnSuccessListener { + if (epoch == generation && !disposed) { + service.registerServiceConnectionListener() + serviceReady = true + handler.postDelayed(poll, 5000) + val answered = AtomicBoolean(false) + p2p.ping(device, object : PingCallback { + override fun onPingResult(code: Int) { + if (answered.compareAndSet(false, true)) handler.post { + if (epoch != generation || disposed) result.error("SESSION_MISMATCH", "Connection was cancelled", null) + else if (code == 202) result.success(null) + else result.error("PEER_NOT_READY", "Watch app is not ready", code) + } + } + }).addOnFailureListener { if (answered.compareAndSet(false, true)) fail(result, it) } + } else handler.post { result.error("SESSION_MISMATCH", "Connection was cancelled", null) } + }.addOnFailureListener { closeTransport(); fail(result, it) } + }.addOnFailureListener { fail(result, it) } + } + "send" -> { + val data = requireNotNull(call.argument("bytes")) + require(data.size <= 1024) + val device = selected ?: run { + result.error("DEVICE_DISCONNECTED", "No active device", null); return + } + val answered = AtomicBoolean(false) + p2p.send(device, Message.Builder().setPayload(data).build(), object : SendCallback { + override fun onSendProgress(progress: Long) {} + override fun onSendResult(code: Int) { + if (answered.compareAndSet(false, true)) handler.post { + if (code == 207) result.success(null) + else result.error("TRANSPORT_FAILED", "Wear Engine send failed", code) + } + } + }).addOnFailureListener { if (answered.compareAndSet(false, true)) fail(result, it) } + } + "close" -> { closeTransport(); releaseService(result) } + "scheduleReminders" -> { + val json = requireNotNull(call.argument("json")) + WearReminders.replace(activity, json) + result.success(null) + } + "cancelReminders" -> { WearReminders.clear(activity); result.success(null) } + "sendReminder" -> WearReminders.send(activity, + requireNotNull(call.argument("json")), + { value -> handler.post { result.success(value) } }, + { error -> fail(result, error) }) + else -> result.notImplemented() + } + } catch (error: Exception) { fail(result, error) } + } + + private fun closeTransport() { + generation++ + handler.removeCallbacks(poll) + receiver?.let { p2p.unregisterReceiver(it) } + receiver = null + selected = null + } + private fun releaseService(result: MethodChannel.Result? = null) { + if (!serviceReady) { result?.success(null); return } + releasing = true + serviceReady = false + // Finish teardown before a new open; an intentional disconnect is not a peer failure. + service.unregisterServiceConnectionListener().addOnCompleteListener { + service.releaseConnection().addOnCompleteListener { + releasing = false + handler.post { result?.success(null) } + } + } + } + fun dispose() { + closeTransport() + releaseService() + disposed = true + channel.setMethodCallHandler(null) + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearReminders.kt b/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearReminders.kt new file mode 100644 index 00000000..56c56e94 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearReminders.kt @@ -0,0 +1,155 @@ +package club.geekpie.techpie.wear + +import android.content.Context +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import com.huawei.hmf.tasks.Tasks +import com.huawei.wearengine.HiWear +import com.huawei.wearengine.auth.Permission +import com.huawei.wearengine.notify.Notification +import com.huawei.wearengine.notify.NotificationTemplate +import org.json.JSONObject +import java.security.MessageDigest +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import java.util.concurrent.TimeUnit + +/** WorkManager reminders survive Flutter shutdown; Android may delay execution. */ +object WearReminders { + private const val TAG = "techpie-wear-reminders" + private val lock = Any() + private fun prefs(context: Context) = context.getSharedPreferences(TAG, Context.MODE_PRIVATE) + private fun key(id: String) = MessageDigest.getInstance("SHA-256") + .digest(id.toByteArray()).joinToString("") { "%02x".format(it) } + + fun replace(context: Context, json: String) = synchronized(lock) { + val spec = JSONObject(json) + require(spec.getString("deviceId").isNotBlank()) + require(spec.getString("bindingId").isNotBlank()) + require(spec.getLong("leaseUntilMs") > System.currentTimeMillis()) + val items = spec.getJSONArray("items") + require(items.length() <= 500) + for (i in 0 until items.length()) validate(items.getJSONObject(i)) + val store = prefs(context) + val old = store.getString("spec", null)?.let { JSONObject(it) } + if (old?.optString("bindingId") != spec.getString("bindingId")) { + check(store.edit().clear().commit()) + } + check(store.edit().putString("spec", spec.toString()).commit()) + val manager = WorkManager.getInstance(context) + // Same reminder keeps its unique work (including its original due time). + val ids = mutableSetOf() + for (i in 0 until items.length()) { + val reminder = items.getJSONObject(i) + val id = reminder.getString("reminderId") + val name = "$TAG-${key(id)}" + ids.add(name) + if (store.contains("sent:${key(id)}")) continue + val delay = (reminder.getLong("scheduledAtMs") - System.currentTimeMillis()).coerceAtLeast(0) + val request = OneTimeWorkRequestBuilder() + .setInputData(workDataOf("reminderId" to id)) + .setInitialDelay(delay, TimeUnit.MILLISECONDS).addTag(TAG).build() + manager.enqueueUniqueWork(name, ExistingWorkPolicy.KEEP, request) + } + val previous = store.getStringSet("workNames", emptySet()) ?: emptySet() + (previous - ids).forEach { manager.cancelUniqueWork(it) } + check(store.edit().putStringSet("workNames", ids).commit()) + } + + fun clear(context: Context) = synchronized(lock) { + // Leave sent receipts for this installation to avoid duplicating old reminders. + check(prefs(context).edit().remove("spec").commit()) + WorkManager.getInstance(context).cancelAllWorkByTag(TAG) + } + + private fun validate(reminder: JSONObject) { + require(reminder.getString("reminderId").length in 1..128) + require(reminder.getString("title").isNotBlank()) + require(reminder.getLong("expiresAtMs") > reminder.getLong("scheduledAtMs")) + require(reminder.getLong("expiresAtMs") - reminder.getLong("scheduledAtMs") <= 600_000) + require(reminder.getLong("dueAtMs") > 0) + } + + private fun current(context: Context, id: String): Pair? { + val raw = prefs(context).getString("spec", null) ?: return null + val spec = JSONObject(raw) + if (spec.getLong("leaseUntilMs") <= System.currentTimeMillis()) return null + val items = spec.getJSONArray("items") + for (i in 0 until items.length()) { + val item = items.getJSONObject(i) + if (item.getString("reminderId") == id) return spec to item + } + return null + } + + fun send(context: Context, json: String, success: (String) -> Unit, failure: (Exception) -> Unit) { + // SDK tasks and permission/device lookups never block Flutter's UI thread. + java.util.concurrent.Executors.newSingleThreadExecutor().let { executor -> + executor.execute { + try { + val requested = JSONObject(json) + val id = requested.getString("reminderId") + success(deliver(context, id)) + } catch (error: Exception) { failure(error) } + finally { executor.shutdown() } + } + } + } + + fun deliver(context: Context, id: String): String { + val pair = synchronized(lock) { current(context, id) } ?: return "expired" + val (spec, reminder) = pair + validate(reminder) + val now = System.currentTimeMillis() + if (now < reminder.getLong("scheduledAtMs")) return "notDue" + if (now >= reminder.getLong("expiresAtMs")) return "expired" + val receipt = "sent:${key(id)}" + prefs(context).getString(receipt, null)?.let { return it } + if (!Tasks.await(HiWear.getAuthClient(context).checkPermission(Permission.NOTIFY), 15, TimeUnit.SECONDS)) { + return "unsupported" + } + val device = Tasks.await(HiWear.getDeviceClient(context).bondedDevices, 15, TimeUnit.SECONDS) + .firstOrNull { it.uuid == spec.getString("deviceId") && it.isConnected } + ?: return "disconnected" + val format = SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).apply { timeZone = TimeZone.getTimeZone("Asia/Shanghai") } + val text = reminder.getString("title").take(16) + " " + format.format(Date(reminder.getLong("dueAtMs"))) + val notification = Notification.Builder() + .setTemplateId(NotificationTemplate.NOTIFICATION_TEMPLATE_NO_BUTTON) + .setPackageName(context.packageName).setTitle("DDL 提醒").setText(text).build() + val task = synchronized(lock) { + val latest = current(context, id) ?: return "expired" + if (latest.first.getString("bindingId") != spec.getString("bindingId") || + latest.first.getString("deviceId") != spec.getString("deviceId") || + System.currentTimeMillis() >= latest.second.getLong("expiresAtMs")) return "expired" + prefs(context).getString(receipt, null)?.let { return it } + // Persist before the irreversible call. A crash/timeout must not auto-send twice. + check(prefs(context).edit().putString(receipt, "deliveryUnknown").commit()) + HiWear.getNotifyClient(context).notify(device, notification) + } + return try { + Tasks.await(task, 15, TimeUnit.SECONDS) + synchronized(lock) { prefs(context).edit().putString(receipt, "submitted").commit() } + "submitted" + } catch (_: Exception) { "deliveryUnknown" } + } +} + +class WearReminderWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) { + override fun doWork(): Result { + val id = inputData.getString("reminderId") ?: return Result.failure() + return try { + when (WearReminders.deliver(applicationContext, id)) { + "disconnected" -> if (runAttemptCount == 0) Result.retry() else Result.success() + else -> Result.success() + } + } catch (_: Exception) { + if (runAttemptCount == 0) Result.retry() else Result.failure() + } + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 22fe4558..95fe6bac 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -1,8 +1,32 @@ +buildscript { + repositories { + maven(url = "https://maven.aliyun.com/repository/google") + maven(url = "https://maven.aliyun.com/repository/central") + maven(url = "https://developer.huawei.com/repo/") + } + dependencies { + // Keep AGConnect's buildscript AGP lookup aligned with settings.gradle.kts. + classpath("com.android.tools.build:gradle:8.11.1") + classpath("com.huawei.agconnect:agcp:1.9.3.301") + } +} + allprojects { + configurations.configureEach { + resolutionStrategy.eachDependency { + // The OHOS mobile_scanner fork still requests CameraX 1.3.4, + // whose image-processing JNI library has 4 KB ELF LOAD alignment. + if (requested.group == "androidx.camera" && requested.version == "1.3.4") { + useVersion("1.4.2") + because("CameraX 1.4.2 ships 16 KB aligned JNI libraries") + } + } + } repositories { maven(url = "https://maven.aliyun.com/repository/google") maven(url = "https://maven.aliyun.com/repository/central") maven(url = "https://maven.aliyun.com/repository/public") + maven(url = "https://developer.huawei.com/repo/") // google() // mavenCentral() } diff --git a/assets/icon/appgallery-216.png b/assets/icon/appgallery-216.png new file mode 100644 index 00000000..e4034093 Binary files /dev/null and b/assets/icon/appgallery-216.png differ diff --git a/docs/genai-gateway-validation.md b/docs/genai-gateway-validation.md new file mode 100644 index 00000000..0bfd3ecf --- /dev/null +++ b/docs/genai-gateway-validation.md @@ -0,0 +1,42 @@ +# GenAI 网关修复与验收 + +2026-10-28,已同步本地上游 `b517039`,以及其工作区的原生工具增量、空回复重试更新。对照 `/proj/GenAI2OpenAI/docs/TechPie工具链问题交接.md`。 + +## 已修复 + +- 先接收最后一段正文,再处理结束原因。保留 `length`、`content_filter`;没有 finish 或 DONE 的 EOF 返回错误。 +- 工具解析支持标准对象、嵌套 function、顶层数组、尾随链接、多个 JSON 对象、多个 XML 块。保留全部调用及已有 ID。 +- 工具名称必须在本次声明中,arguments 必须能解析为 JSON 对象。只在上游正常结束、调用及参数已完整时补齐外层数组或唯一 tool_calls 包装对象的闭合符;不补调用、参数、字符串或逗号后缺失的值。未知工具、错误参数不回退成成功正文。普通 name 字段、字段说明和空 tool_calls 数组保留为普通答案。这里不做完整 JSON Schema 校验。 +- 支持 Responses 的函数工具定义、function_call / function_call_output 历史、函数输出和 SSE added/delta/done/completed 生命周期。截断为 incomplete,错误为 failed。 +- 补充执行任务时应当返回工具调用的提示,落实 required 和指定函数;auto 仍允许正常总结。仅在上游正常结束且正文和原生工具调用均为空时,使用相同历史重试一次;首轮纯推理不向客户端发布。两次均为空时报错。错误、EOF、length、已输出正文或工具调用均不重试,不重放工具副作用。 +- Chat 优先采用 max_completion_tokens,其次 max_tokens;Responses 使用 max_output_tokens。 +- 原生 tool_calls 按 index 聚合名称及参数分片,兼容 message 和旧 function_call 字段,聚合后统一校验名称及参数;未启用工具时不接收原生调用。 +- SSE 在等待上游响应头时发送心跳,客户端断开时取消等待并关闭对应上游连接。 +- 请求日志前缀 `genai_request`。只记录请求 ID、路径、模型、计数、tool_choice、输出上限、耗时、结束原因、DONE、取消状态、异常类别,不记录凭据、正文或工具结果。`saw_done=false` 表示本次没有读到 DONE;已有 finish_reason 时也正常结束读取。 + +## 本机验证 + +- `flutter test test/genai_gateway_test.dart --no-pub`:62 项通过。 +- `flutter test --no-pub`:全套 740 项通过;更新了截止日期空状态断言,以及设置页日志入口的滚动定位。 +- 对修改的 Dart 文件定向运行 `flutter analyze --no-pub`:无问题。 +- `flutter build linux --release --no-pub`:成功。 +- `tool/genai_gateway_smoke.dart`:真实 ChatGLM,在 Chat Completions 和 Responses 上分别完成流式请求工具、夹具返回、非流式总结;开发网关和安装版各验证一次。只提供 fixture_read 夹具,结果为固定编号,没有执行文件或 Git 操作,没有测试 GPT。 +- 安装路径:`/home/jdz/.local/opt/techpie-linux-widgets-v1/bundle`。 +- 本轮安装进程 PID 404337,`127.0.0.1:5000` 属于该进程;核对其加载的 libapp.so 与构建产物一致。 +- libapp.so SHA256:`41666b4dfccc439d6d1622a0f084f4d8816766d204fa11f061cb06e068b7510d`。 +- 上一版备份:`/home/jdz/.local/opt/techpie-linux-widgets-v1/bundle-backup-20261028-194654`。 +- 本次通过 `techpie --genai-api` 恢复 API 服务。平常仍可从 GenAI API 页启动。 + +日志: + +- `/tmp/techpie-all-sync-tests-final.log` +- `/tmp/techpie-genai-sync-tests.log` +- `/tmp/techpie-genai-sync-analyze.log` +- `/tmp/techpie-linux-build-sync.log` +- `/tmp/techpie-real-chatglm-sync.log` +- `/tmp/techpie-installed-chatglm-sync.log` +- `/tmp/techpie-installed-genai-sync.log` + +## VS Code 原客户端 + +尚未完成原客户端的文件读取、编辑验收;本机无该会话的客户端工具记录。原截图的实际 API 路径和停止原因仍未确定。重测时,用请求日志中的 request_id、path、结束原因与客户端工具记录对应。不要以模型声称完成或界面步骤计数认定实际执行成功。 diff --git a/harmonyos_watch/.gitignore b/harmonyos_watch/.gitignore new file mode 100644 index 00000000..286a03ad --- /dev/null +++ b/harmonyos_watch/.gitignore @@ -0,0 +1,9 @@ +/node_modules/ +/oh_modules/ +/.hvigor/ +/.idea/ +/local.properties +/build-profile.json5 +/signature/ +**/build/ +**/.preview/ diff --git a/harmonyos_watch/BUILDING.md b/harmonyos_watch/BUILDING.md new file mode 100644 index 00000000..a96c790e --- /dev/null +++ b/harmonyos_watch/BUILDING.md @@ -0,0 +1,34 @@ +# Watch companion builds + +On a clean checkout, `build.ps1` creates an unsigned local `build-profile.json5` +from `build-profile.template.json5`. It never overwrites an existing profile. +The generated profile is ignored by Git. Configure device installation signing +locally in DevEco Studio; signing material and passwords must stay local. + +The committed phone identity matches the signed Android release certificate. +Both `build.ps1` and the Lite packaging hook validate it against +`.github/workflows/android-release.yml` before packaging and signing. + +For a local Android debug APK, explicitly supply its public certificate SHA256: + +```powershell +$env:HUAWEI_PHONE_FINGERPRINT = '<64 hexadecimal characters from your debug certificate>' +./build.ps1 +Remove-Item Env:HUAWEI_PHONE_FINGERPRINT +``` + +The override changes generated watch JavaScript only. Never commit a debug +certificate into `wear-config.js`, and leave this environment variable unset +when packaging the companion for Android release users. The build mode named +`debug` is the SDK's Lite BIN packaging path; it does not select the phone's +certificate. A fresh compilation is required when changing the override. + +Run the portable checks without the Huawei SDK: + +```sh +node --test harmonyos_watch/scripts/*.test.cjs harmonyos_watch/scripts/*.test.mjs +``` + +Before distribution, verify pairing using the signed phone and watch artifacts, +then check code scanning, code expiry, reconnect, logout, and reminder delivery +on a supported watch. Unit tests cannot verify vendor authorization or optics. diff --git a/harmonyos_watch/build-profile.template.json5 b/harmonyos_watch/build-profile.template.json5 new file mode 100644 index 00000000..bec60439 --- /dev/null +++ b/harmonyos_watch/build-profile.template.json5 @@ -0,0 +1,26 @@ +{ + "app": { + "products": [ + { + "name": "default", + "compileSdkVersion": "26.0.0", + "compatibleSdkVersion": "4.0.0(10)", + "targetSdkVersion": "4.0.0(10)", + "runtimeOS": "HarmonyOS" + } + ], + "buildModeSet": [ + { "name": "debug" }, + { "name": "release" } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { "name": "default", "applyToProducts": ["default"] } + ] + } + ] +} diff --git a/harmonyos_watch/build.ps1 b/harmonyos_watch/build.ps1 new file mode 100644 index 00000000..50657397 --- /dev/null +++ b/harmonyos_watch/build.ps1 @@ -0,0 +1,49 @@ +param( + [string]$DevEcoHome = 'D:\Program Files\Huawei\DevEco Studio', + [ValidateSet('debug', 'release')][string]$BuildMode = 'debug' +) + +$ErrorActionPreference = 'Stop' +if ($BuildMode -eq 'release') { + throw 'Lite watch installation requires the debug BIN packaging path. Use -BuildMode debug; its JS is minified before signing.' +} +$taskNode = Join-Path $DevEcoHome 'tools\node\node.exe' +$taskHvigor = Join-Path $DevEcoHome 'tools\hvigor\bin\hvigorw.js' +if (!(Test-Path -LiteralPath $taskNode) -or !(Test-Path -LiteralPath $taskHvigor)) { + throw 'DevEco tools not found. Pass -DevEcoHome with your installation directory.' +} +$env:DEVECO_SDK_HOME = Join-Path $DevEcoHome 'sdk' +$env:HOS_SDK_HOME = $env:DEVECO_SDK_HOME +$env:JAVA_HOME = Join-Path $DevEcoHome 'jbr' +$env:Path = "$DevEcoHome\tools\node;$DevEcoHome\tools\ohpm\bin;$DevEcoHome\tools\hvigor\bin;$env:Path" + +Push-Location $PSScriptRoot +try { + $taskProfilePath = Join-Path $PSScriptRoot 'build-profile.json5' + if (!(Test-Path -LiteralPath $taskProfilePath)) { + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'build-profile.template.json5') -Destination $taskProfilePath + Write-Output 'Created local unsigned build-profile.json5. Configure signing in DevEco Studio for device installation.' + } + & $taskNode (Join-Path $PSScriptRoot 'scripts\validate-signing-config.cjs') + if ($LASTEXITCODE -ne 0) { throw 'Invalid phone companion signing configuration.' } + & $taskNode $taskHvigor --mode module -p module=entry@default -p product=default -p "buildMode=$BuildMode" assembleHap --no-daemon + if ($LASTEXITCODE -ne 0) { throw "Hvigor failed with exit code $LASTEXITCODE" } + $taskProfileText = [IO.File]::ReadAllText((Join-Path $PSScriptRoot 'build-profile.json5')) + $taskSigned = [regex]::IsMatch($taskProfileText, '"signingConfig"\s*:\s*"[^"]+"') + $taskSuffix = if ($taskSigned) { 'signed' } else { 'unsigned' } + $taskHap = Join-Path $PSScriptRoot "entry\build\default\outputs\default\entry-default-$taskSuffix.hap" + if (!(Test-Path -LiteralPath $taskHap)) { throw "$taskSuffix HAP was not generated." } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $taskArchive = [IO.Compression.ZipFile]::OpenRead($taskHap) + try { + $taskExpectedBin = "entry-default-$taskSuffix.bin" + if ($taskArchive.Entries.Count -ne 1 -or $taskArchive.Entries[0].FullName -ne $taskExpectedBin) { + throw 'Invalid Lite installation HAP: expected a single application BIN.' + } + } finally { + $taskArchive.Dispose() + } + Write-Output "$taskSuffix $BuildMode HAP: $taskHap" +} finally { + Pop-Location +} diff --git a/harmonyos_watch/entry/build-profile.json5 b/harmonyos_watch/entry/build-profile.json5 new file mode 100644 index 00000000..13ee5526 --- /dev/null +++ b/harmonyos_watch/entry/build-profile.json5 @@ -0,0 +1,5 @@ +{ + "apiType": "faMode", + "buildOption": {}, + "targets": [{ "name": "default" }] +} diff --git a/harmonyos_watch/entry/hvigorfile.ts b/harmonyos_watch/entry/hvigorfile.ts new file mode 100644 index 00000000..0d89acdd --- /dev/null +++ b/harmonyos_watch/entry/hvigorfile.ts @@ -0,0 +1,39 @@ +import { legacyHapTasks } from '@ohos/hvigor-ohos-plugin'; +import { hvigor } from '@ohos/hvigor'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; + +const { normalizeFile, readSdkRange } = require('../scripts/lite-profile.cjs'); + +hvigor.nodesEvaluated(() => { + const node = hvigor.getNodeByName('entry'); + const task = node?.getTaskByName('default@LegacyGenerateLiteCode'); + if (!task) throw new Error('Lite BIN packaging task was not found.'); + task.beforeRun(() => { + // Debug is the SDK's Lite BIN packaging path. Minify before that task + // rather than switching to release, which creates a different HAP layout. + const sdkHome = process.env.DEVECO_SDK_HOME; + if (!sdkHome) throw new Error('DEVECO_SDK_HOME is required for Lite minification.'); + execFileSync(process.execPath, [ + path.join(__dirname, '../scripts/validate-signing-config.cjs'), + '--compiled-dir', + path.join(__dirname, 'build/default/intermediates/loader_out_lite/default/js'), + ], { stdio: 'inherit' }); + execFileSync(process.execPath, [ + path.join(__dirname, '../scripts/minify-lite.cjs'), + path.join(__dirname, 'build/default/intermediates/loader_out_lite/default/js'), + path.join(sdkHome, 'default/openharmony/js/build-tools/ace-loader/node_modules/terser'), + ], { stdio: 'inherit' }); + const [compatible, target] = readSdkRange(path.join(__dirname, '../build-profile.json5')); + normalizeFile( + path.join(__dirname, 'build/default/intermediates/res/default/config.json'), + compatible, + target + ); + }); +}); + +export default { + system: legacyHapTasks, + plugins: [] +}; diff --git a/harmonyos_watch/entry/oh-package.json5 b/harmonyos_watch/entry/oh-package.json5 new file mode 100644 index 00000000..d9d7f235 --- /dev/null +++ b/harmonyos_watch/entry/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Lite Wearable entry module", + "dependencies": {} +} diff --git a/harmonyos_watch/entry/src/main/config.json b/harmonyos_watch/entry/src/main/config.json new file mode 100644 index 00000000..b4bde6fb --- /dev/null +++ b/harmonyos_watch/entry/src/main/config.json @@ -0,0 +1,26 @@ +{ + "app": { + "bundleName": "com.geekpie.techpie.watch", + "vendor": "geekpie", + "version": { "code": 1, "name": "0.1.0" } + }, + "deviceConfig": {}, + "module": { + "deviceType": ["liteWearable"], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [{ + "name": ".MainAbility", + "srcLanguage": "js", + "srcPath": "MainAbility", + "icon": "$media:icon", + "description": "$string:app_description", + "label": "$string:app_name", + "type": "page" + }], + "js": [{ "name": ".MainAbility", "pages": ["pages/index/index"] }] + } +} diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/app.js b/harmonyos_watch/entry/src/main/js/MainAbility/app.js new file mode 100644 index 00000000..0304d6c2 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/app.js @@ -0,0 +1,4 @@ +export default { + onCreate() {}, + onDestroy() {} +}; diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/common/LICENSE.wearengine b/harmonyos_watch/entry/src/main/js/MainAbility/common/LICENSE.wearengine new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/LICENSE.wearengine @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-config.js b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-config.js new file mode 100644 index 00000000..b4cd6681 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-config.js @@ -0,0 +1,6 @@ +// Public certificate SHA256 used by the signed Android release workflow. +// For local debugging use the explicit build override documented in BUILDING.md. +export default { + phonePackage: 'club.geekpie.techpie', + phoneFingerprint: '1C8155EE7940F2BEF76816F24FCE3044A7A083ED2032BB9DCEF3DE7BE4284A98' +}; diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-connection.js b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-connection.js new file mode 100644 index 00000000..9ed2ef51 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-connection.js @@ -0,0 +1,303 @@ +// Product protocol v1, with optional binary-preserving QR matrix display. +// Byte framing works on Lite JS without browser-only TextEncoder/btoa globals. +var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +function utf8(text) { + var encoded = encodeURIComponent(text), bytes = []; + for (var i = 0; i < encoded.length; i++) { + if (encoded.charAt(i) === '%') { + bytes.push(parseInt(encoded.substr(i + 1, 2), 16)); i += 2; + } else { bytes.push(encoded.charCodeAt(i)); } + } + return bytes; +} +function text(bytes) { + var encoded = ''; + for (var i = 0; i < bytes.length; i++) { + encoded += '%' + ('0' + bytes[i].toString(16)).slice(-2); + } + return decodeURIComponent(encoded); +} +function base64(bytes) { + var result = ''; + for (var i = 0; i < bytes.length; i += 3) { + var a = bytes[i], b = bytes[i + 1] || 0, c = bytes[i + 2] || 0; + result += alphabet.charAt(a >> 2) + alphabet.charAt(((a & 3) << 4) | (b >> 4)) + + (i + 1 < bytes.length ? alphabet.charAt(((b & 15) << 2) | (c >> 6)) : '=') + + (i + 2 < bytes.length ? alphabet.charAt(c & 63) : '='); + } + return result; +} +function unbase64(value) { + if (typeof value !== 'string' || value.length % 4 !== 0) { + throw new Error('INVALID_PAYLOAD'); + } + var padding = 0; + for (var k = 0; k < value.length; k++) { + if (value.charAt(k) === '=') { + padding++; + if (k < value.length - 2 || padding > 2) throw new Error('INVALID_PAYLOAD'); + } else if (padding || alphabet.indexOf(value.charAt(k)) < 0) { + throw new Error('INVALID_PAYLOAD'); + } + } + var bytes = []; + for (var i = 0; i < value.length; i += 4) { + var a = alphabet.indexOf(value.charAt(i)), b = alphabet.indexOf(value.charAt(i + 1)); + var c = alphabet.indexOf(value.charAt(i + 2)), d = alphabet.indexOf(value.charAt(i + 3)); + bytes.push((a << 2) | (b >> 4)); + if (c >= 0) bytes.push(((b & 15) << 4) | (c >> 2)); + if (d >= 0) bytes.push(((c & 3) << 6) | d); + } + if (base64(bytes) !== value) throw new Error('INVALID_PAYLOAD'); + return bytes; +} +function integer(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } +function token(value) { + if (typeof value !== 'string' || !value.length || value.length > 32) return false; + var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; + for (var i = 0; i < value.length; i++) { + if (allowed.indexOf(value.charAt(i)) < 0) return false; + } + return true; +} +function characters(value) { + var count = 0; + for (var i = 0; i < value.length; i++) { + var code = value.charCodeAt(i); + if (code >= 0xD800 && code <= 0xDBFF && i + 1 < value.length) { + var next = value.charCodeAt(i + 1); + if (next >= 0xDC00 && next <= 0xDFFF) i++; + } + count++; + } + return count; +} + +export function WatchConnection(send, changed, now) { + this.send = send; + this.changed = changed; + this.now = now || function() { return Date.now(); }; + this.counter = 0; + this.reset(); +} +WatchConnection.prototype.reset = function() { + this.session = null; this.binding = null; this.nonce = null; + this.assembly = null; this.replies = []; this.account = null; + this.revision = 0; this.accountContent = null; this.ready = false; + this.remaining = 0; this.silence = 0; this.lastTick = this.now(); + this.ddl = []; this.ddlRevision = 0; this.ddlContent = null; + this.ddlUntil = 0; this.accountUntil = 0; this.code = null; + this.pending = {}; this.error = ''; this.truncated = false; + this.updatedAt = 0; this.phoneTime = 0; this.phoneElapsed = 0; this.publish(); +}; +WatchConnection.prototype.phoneNow = function() { + return this.phoneTime + this.phoneElapsed + Math.max(0, this.now() - this.lastTick); +}; +WatchConnection.prototype.publish = function() { + if (this.code && this.code.until <= this.phoneNow()) this.code = null; + this.changed({connected: this.ready, name: this.account ? this.account.name : '', + studentId: this.account ? this.account.studentId : '', ddl: this.ddl, + ddlReady: this.ddlUntil > this.phoneNow(), truncated: this.truncated, + updatedAt: this.updatedAt, code: this.code, + codeSeconds: this.code ? Math.max(0, Math.ceil((this.code.until - this.phoneNow()) / 1000)) : 0, + syncing: !!this.pending.sync, codeLoading: !!this.pending.code, error: this.error}); +}; +WatchConnection.prototype.tick = function() { + var delta = Math.max(0, this.now() - this.lastTick); + this.lastTick = this.now(); + if (this.assembly && this.now() - this.assembly.at >= 30000) this.assembly = null; + if (!this.ready) return; + this.remaining -= delta; this.silence += delta; + this.phoneElapsed += delta; + if (this.remaining <= 0 || this.silence >= 30000) { this.reset(); return; } + if (this.code && this.code.until <= this.phoneNow()) this.code = null; + if (this.accountUntil <= this.phoneNow()) this.account = null; + if (this.ddlUntil <= this.phoneNow()) this.ddl = []; + for (var key in this.pending) { + if (this.now() - this.pending[key].at >= 30000) { + delete this.pending[key]; this.error = '唔…手机怎么没有响应呢(⊙ω⊙?)'; + } + } + this.publish(); +}; +WatchConnection.prototype.write = function(response) { + var bytes = utf8(JSON.stringify(response)), count = Math.ceil(bytes.length / 512), frames = []; + for (var i = 0; i < count; i++) { + frames.push(JSON.stringify({v: 1, mid: response.id, i: i, n: count, + data: base64(bytes.slice(i * 512, (i + 1) * 512))})); + } + for (var j = 0; j < frames.length; j++) this.send(frames[j]); + return frames; +}; +WatchConnection.prototype.request = function(kind) { + if (!this.ready) { this.error = '请先连接手机 TechPie'; this.publish(); return false; } + if (this.pending[kind]) return false; + var id = 'w' + (++this.counter); + this.pending[kind] = {id: id, at: this.now()}; this.error = ''; + // Keep the previous valid code until replacement succeeds or it expires. + this.publish(); + this.write({v: 1, id: id, replyTo: null, sessionId: this.session, + bindingId: this.binding, type: kind === 'code' ? 'campusCode.request' : 'sync.request', + sentAtMs: this.now(), body: kind === 'code' ? {purpose: 'campus', format: 'qrBytes'} : {resources: ['account', 'ddl']}}); + return true; +}; +WatchConnection.prototype.hideCode = function() { + this.code = null; delete this.pending.code; this.publish(); +}; +WatchConnection.prototype.reply = function(request, type, body, handshake) { + var response = {v: 1, id: 'w' + (++this.counter), replyTo: request.id, + sessionId: handshake ? null : request.sessionId, + bindingId: handshake ? null : request.bindingId, + type: type, sentAtMs: this.now(), body: body}; + var frames = this.write(response); + this.replies.push({id: request.id, content: JSON.stringify(request), frames: frames}); + if (this.replies.length > 16) this.replies.shift(); +}; +WatchConnection.prototype.receive = function(raw) { + try { + if (typeof raw !== 'string' || utf8(raw).length > 1024) throw new Error('INVALID_PAYLOAD'); + var f = JSON.parse(raw); + if (f.v !== 1 || !token(f.mid) || !integer(f.i) || !integer(f.n) || + f.n < 1 || f.n > 64 || f.i < 0 || f.i >= f.n) throw new Error('INVALID_PAYLOAD'); + var part = unbase64(f.data); + if (!part.length || part.length > 512 || (f.i < f.n - 1 && part.length !== 512)) throw new Error('INVALID_PAYLOAD'); + if (this.assembly && this.now() - this.assembly.at >= 30000) this.assembly = null; + if (this.assembly && this.assembly.id !== f.mid) return; + var a = this.assembly || {id: f.mid, n: f.n, parts: {}, at: this.now()}; + if (a.n !== f.n || (a.parts[f.i] && base64(a.parts[f.i]) !== f.data)) throw new Error('INVALID_PAYLOAD'); + a.parts[f.i] = part; a.at = this.now(); this.assembly = a; + var bytes = []; + for (var i = 0; i < a.n; i++) { + if (!a.parts[i]) return; + bytes = bytes.concat(a.parts[i]); + } + this.assembly = null; + var message = JSON.parse(text(bytes)); + if (message.v !== 1 || message.id !== f.mid || typeof message.type !== 'string' || + !message.body || typeof message.body !== 'object' || !integer(message.sentAtMs)) throw new Error('INVALID_PAYLOAD'); + this.handle(message); + } catch (_) { this.assembly = null; } +}; +WatchConnection.prototype.handle = function(m) { + var b = m.body, handshake = m.type === 'session.hello' || m.type === 'session.open'; + if (handshake && (m.sessionId != null || m.bindingId != null)) return; + if (!handshake && (!this.ready || m.sessionId !== this.session || m.bindingId !== this.binding)) return; + // The opening message's transit time can differ from a later snapshot's. + // Advance to the trusted peer's send time, but never move the clock backwards. + if (!handshake && integer(m.sentAtMs)) { + var correction = Math.max(0, m.sentAtMs - this.phoneNow()); + this.phoneTime += correction; this.remaining -= correction; + } + for (var i = 0; i < this.replies.length; i++) { + var cached = this.replies[i]; + if (cached.id === m.id) { + if (cached.content === JSON.stringify(m)) { + for (var j = 0; j < cached.frames.length; j++) this.send(cached.frames[j]); + } + return; + } + } + if (m.type === 'session.hello') { + if (!token(b.nonce) || !Array.isArray(b.versions) || b.versions.indexOf(1) < 0) return; + this.reset(); this.nonce = b.nonce; this.helloAt = this.now(); + this.reply(m, 'session.welcome', {nonce: b.nonce, version: 1, + watchInstanceId: 'techpie-lite', capabilities: ['account.display', 'ddl.display', 'campusCode.qrMatrix', 'connection.heartbeat'], + maxQrPayloadBytes: 1024}, true); + } else if (m.type === 'session.open') { + if (b.nonce !== this.nonce || this.now() - this.helloAt > 5000 || + !token(b.sessionId) || !token(b.bindingId) || !integer(b.phoneTimeMs) || + !integer(b.leaseUntilMs) || b.leaseUntilMs <= b.phoneTimeMs) return; + this.session = b.sessionId; this.binding = b.bindingId; + this.phoneTime = b.phoneTimeMs; this.phoneElapsed = 0; + this.remaining = Math.min(86400000, b.leaseUntilMs - b.phoneTimeMs); + this.ready = true; this.silence = 0; this.lastTick = this.now(); + this.reply(m, 'session.opened', {sessionId: this.session}, true); + this.publish(); + } else if (m.type === 'session.ping') { + this.silence = 0; + this.reply(m, 'result', {status: 'ok', code: 'OK'}); + } else if (m.type === 'session.close' || m.type === 'session.clear') { + this.reply(m, 'result', {status: 'ok', code: 'OK'}); + this.reset(); + } else if (m.type === 'account.snapshot') { + var d = b.data; + if (!integer(b.revision) || b.revision < 1 || !integer(b.validUntilMs) || + b.validUntilMs <= this.phoneNow() || !d || + typeof d.name !== 'string' || typeof d.studentId !== 'string' || + !d.name.trim() || !d.studentId.trim() || characters(d.name) > 64 || characters(d.studentId) > 64) { + this.reply(m, 'result', {status: 'error', code: 'INVALID_PAYLOAD', retryable: false}); return; + } + var content = JSON.stringify(d); + if (b.revision < this.revision || (b.revision === this.revision && this.accountContent !== content)) { + this.reply(m, 'result', {status: 'error', code: 'STALE_REVISION', retryable: false}); return; + } + this.revision = b.revision; this.accountContent = content; + this.account = {name: d.name, studentId: d.studentId}; this.silence = 0; + this.accountUntil = b.validUntilMs; this.publish(); + this.reply(m, 'result', {status: 'ok', code: 'OK', resource: 'account', revision: b.revision}); + } else if (m.type === 'ddl.snapshot') { + if (!integer(b.revision) || b.revision < 1 || !integer(b.validUntilMs) || + b.validUntilMs <= this.phoneNow() || !Array.isArray(b.items) || b.items.length > 50) { + this.reject(m, 'INVALID_PAYLOAD'); return; + } + var ids = {}, items = []; + for (var k = 0; k < b.items.length; k++) { + var item = b.items[k]; + if (!item || typeof item.id !== 'string' || !item.id.length || item.id.length > 128 || ids[item.id] || + typeof item.title !== 'string' || !item.title.trim() || characters(item.title) > 80 || + typeof item.courseName !== 'string' || characters(item.courseName) > 40 || + !integer(item.dueAtMs) || item.dueAtMs < 1 || + ['open', 'completed'].indexOf(item.status) < 0) { + this.reject(m, 'INVALID_PAYLOAD'); return; + } + ids[item.id] = true; items.push(item); + } + var ddlContent = JSON.stringify(b.items); + if (b.revision < this.ddlRevision || (b.revision === this.ddlRevision && this.ddlContent !== ddlContent)) { + this.reject(m, 'STALE_REVISION'); return; + } + items.sort(function(a, c) { return a.dueAtMs - c.dueAtMs; }); + this.ddl = items; this.ddlContent = ddlContent; this.ddlRevision = b.revision; + this.ddlUntil = b.validUntilMs; this.truncated = b.truncated === true; + this.updatedAt = integer(b.generatedAtMs) ? b.generatedAtMs : this.phoneNow(); + delete this.pending.sync; this.error = ''; this.silence = 0; this.publish(); + this.reply(m, 'result', {status: 'ok', code: 'OK', resource: 'ddl', revision: b.revision}); + } else if (m.type === 'campusCode.snapshot') { + var pending = this.pending.code; + if (!pending || pending.id !== m.replyTo || !token(b.codeId) || b.purpose !== 'campus' || b.format !== 'qrBytes' || + b.matrixEncoding !== 'base64-msb' || !integer(b.matrixSize) || + b.matrixSize < 21 || b.matrixSize > 121 || (b.matrixSize - 17) % 4 !== 0 || + !integer(b.validFromMs) || b.validFromMs > this.phoneNow() || + !integer(b.validUntilMs) || b.validUntilMs <= this.phoneNow() || + b.validUntilMs - this.phoneNow() > 120000) { + this.reject(m, 'INVALID_PAYLOAD'); return; + } + var matrix; + try { matrix = unbase64(b.matrix); } catch (_) { this.reject(m, 'INVALID_PAYLOAD'); return; } + if (matrix.length !== Math.ceil(b.matrixSize * b.matrixSize / 8)) { + this.reject(m, 'INVALID_PAYLOAD'); return; + } + this.code = {id: b.codeId, size: b.matrixSize, bytes: matrix, requestAt: pending.at, + until: Math.min(b.validUntilMs, this.phoneNow() + this.remaining)}; + delete this.pending.code; this.error = ''; this.silence = 0; this.publish(); + this.reply(m, 'result', {status: 'ok', code: 'OK'}); + } else if (m.type === 'result') { + for (var kind in this.pending) { + if (this.pending[kind].id === m.replyTo && b.status === 'error') { + delete this.pending[kind]; this.error = failureText(b.code); this.publish(); + } + } + } else { + this.reply(m, 'result', {status: 'error', code: 'UNSUPPORTED_OPERATION', retryable: false}); + } +}; +WatchConnection.prototype.reject = function(m, code) { + this.reply(m, 'result', {status: 'error', code: code, retryable: false}); +}; +function failureText(code) { + if (code === 'ACCOUNT_NOT_READY') return '你还没在手机端绑定校园卡哦~'; + if (code === 'RATE_LIMITED') return '唔诶~!你点的太快了┭┮﹏┭┮'; + if (code === 'PAYLOAD_TOO_LARGE') return '你の校园码太大了……我展示不了呢,问问开发者吧'; + if (code === 'CODE_EXPIRED') return '校园码过期了呢,重新获取吧!'; + return '更新失败了呢,检查一下手机后重试吧!'; +} diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-link.js b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-link.js new file mode 100644 index 00000000..aeb46973 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-link.js @@ -0,0 +1,78 @@ +import { P2pClient, Message, Builder } from './wearengine.js'; +import config from './wear-config.js'; +import { WatchConnection } from './wear-connection.js'; + +export function WearLink(changed) { + this.changed = changed; this.client = null; this.timer = null; + this.queue = []; this.sending = false; this.generation = 0; + var link = this; + this.connection = new WatchConnection(function(frame) { link.enqueue(frame); }, changed); +} +WearLink.prototype.start = function() { + if (this.client) return; + var link = this, epoch = ++this.generation, attempts = 0; + try { this.client = new P2pClient(); } catch (_) { this.failed(); return; } + // The official SDK obtains its native service version asynchronously. + this.timer = setInterval(function() { + if (epoch !== link.generation) return; + attempts++; + if (typeof link.client.version === 'undefined') { + if (attempts >= 10) link.failed(); + return; + } + clearInterval(link.timer); link.timer = null; + if (Number(link.client.version) < 401) { link.failed(); return; } + link.client.setPeerPkgName(config.phonePackage); + link.client.setPeerFingerPrint(config.phoneFingerprint); + link.client.registerReceiver({ + onSuccess: function() {}, + onFailure: function() { if (epoch === link.generation) link.failed(); }, + onReceiveMessage: function(data) { + if (epoch === link.generation && typeof data === 'string') link.connection.receive(data); + } + }); + link.timer = setInterval(function() { + if (epoch === link.generation) link.connection.tick(); + }, 1000); + }, 200); +}; +WearLink.prototype.enqueue = function(frame) { + if (this.queue.length >= 64) { this.failed(); return; } + this.queue.push(frame); this.flush(); +}; +WearLink.prototype.flush = function() { + if (this.sending || !this.client || !this.queue.length) return; + this.sending = true; + var link = this, epoch = this.generation, done = false; + var builder = new Builder(); builder.setDescription(this.queue.shift()); + var message = new Message(); message.builder = builder; + function finish(ok) { + if (done || epoch !== link.generation) return; + done = true; clearTimeout(link.sendTimer); link.sendTimer = null; + link.sending = false; + if (ok) link.flush(); else link.failed(); + } + this.sendTimer = setTimeout(function() { finish(false); }, 8000); + try { + this.client.send(message, { + onSuccess: function() {}, + onFailure: function() { finish(false); }, + onSendProgress: function() {}, + onSendResult: function(result) { finish(result && result.code === 207); } + }); + } catch (_) { finish(false); } +}; +WearLink.prototype.failed = function() { + this.stop(); + this.changed({connected: false, name: '', studentId: '', error: '连接服务不可用,请重新打开应用'}); +}; +WearLink.prototype.stop = function() { + this.generation++; + if (this.timer) clearInterval(this.timer); + if (this.sendTimer) clearTimeout(this.sendTimer); + this.timer = null; this.sendTimer = null; this.queue = []; this.sending = false; + if (this.client) { + try { this.client.unregisterReceiver({onSuccess: function() {}, onFailure: function() {}}); } catch (_) {} + } + this.client = null; this.connection.reset(); +}; diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/common/wearengine.js b/harmonyos_watch/entry/src/main/js/MainAbility/common/wearengine.js new file mode 100644 index 00000000..a87b50da --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wearengine.js @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 + * + * http://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. + * Version: lite wearable 5.0.2.306 + * Description: wearEngine SDK + */ + +import wearengine from "@system.wearengine"; + +var WearEngineConst = { + DELAY_FILEAPP_VALUE: "internal://app/", // Default file storage path of third-party apps + DEFAULT_EMPTY_VALUE: "", // Default empty string +}; +var ErrorCode = { + ERROR_CODE_INVALID_ARGUMENT: 5, // Invalid argument + ERROR_CODE_DEVICE_VERSION_NOT_SUPPORT: 13, // Device version is not supported + MSG_ERROR_PING_WATCH_APP_NOT_EXIST: 200, // App has not been installed on the wearable device + MSG_ERROR_PING_WATCH_APP_NOT_RUNNING: 201, // App has been installed but not opened + MSG_ERROR_PING_WATCH_APP_EXIST_RUNNING: 202, // App has been installed and opened。 + MSG_ERROR_PING_OTHER: 203, // Other error + MSG_ERROR_PING_PHONE_APP_NOT_EXIST: 204, // App has not been installed on the phone + MSG_ERROR_PING_PHONE_APP_NOT_RUNNING: 205, // App has been installed on the phone + MSG_ERROR_SEND_FAIL: 206, // Failed to send the message + MSG_ERROR_SEND_SUCCESS: 207, // The message is sent successfully + MSG_ERROR_CODE_VERSION_TOO_LOW: 208 // The wearEngine version of the watch is too early +}; +var MessageType = { + MESSAGE_TYPE_DATA: 0, // Text Messages + MESSAGE_TYPE_FILE: 1, // File Messages + MESSAGE_TYPE_OFFLINE_MSG: 2 // Offline Messages +}; + +var WEARENGINE_SERVICE_VISION_302 = 302; +var WEARENGINE_SERVICE_VISION_303 = 303; +var WEARENGINE_SERVICE_VISION_401 = 401; +var WEARENGINE_SDK_VERSION = "3"; +var FILE_PUNLIC_PATH_INTERCETPED = 15; +var DEFAULT_EMPTY_FINGERPRINT = " "; +var isTransferring = false; + +var P2pClient = (function() { + var peerPkgName; + var peerFingerPrint; + var version; + + function P2pClient() { + try { + var jsSdk = this; + var getVersionCallBack = function(data) { + if (data) { + var versionArray = data.split("."); + jsSdk.version = versionArray[versionArray.length - 1]; + console.info("service sdk version is: " + data); + } else { + jsSdk.version = 0; + console.info("get service sdk version failed"); + } + }; + wearengine.getWearEngineVersion({ + complete: getVersionCallBack, + sdkVersion: WEARENGINE_SDK_VERSION + }); + } catch (error) { + jsSdk.version = 0; + console.info("service sdk version is too low" + error.message); + } + } + /** + * Set the package name of the phone app + * peerPkgName: string + */ + P2pClient.prototype.setPeerPkgName = function(peerPkgName) { + var successCallBack = function() { + console.info("setPeerPkgName success."); + }; + var failCallBack = function() { + console.info("setPeerPkgName fail."); + }; + this.peerPkgName = peerPkgName; + if (this.version < WEARENGINE_SERVICE_VISION_303) { + console.info("ERROR_CODE_VERSION_TOO_LOW setPackageName is invalid"); + return; + } + wearengine.setPackageName({ + appName: peerPkgName, + complete: successCallBack, + fail: failCallBack + }); + }; + /** + * Set the app fingerprint information on the phone + * fingerPrint: string + */ + P2pClient.prototype.setPeerFingerPrint = function(fingerPrint) { + if (this.version < WEARENGINE_SERVICE_VISION_302) { + console.info("setPeerFingerPrint interface invalid"); + var obj = { + data: "ERROR_CODE_VERSION_TOO_LOW", + code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW + }; + return obj; + } + if (isEmpty(fingerPrint)) { + fingerPrint = DEFAULT_EMPTY_FINGERPRINT; + } + this.peerFingerPrint = fingerPrint; + var successCallBack = function() { + console.info("setPeerFingerPrint success."); + }; + var failCallBack = function() { + console.error("setPeerFingerPrint failed."); + }; + wearengine.setFingerprint({ + appName: this.peerPkgName, + appCert: fingerPrint, + complete: successCallBack, + fail: failCallBack + }); + }; + /** + * Check whether the specified application has been installed on the peer device + * pingCallback: object:onSuccess(),onFailure(),onPingResult(resultCode) + */ + P2pClient.prototype.ping = function(pingCallback) { + var successCode = { + data: " ERROR_CODE_P2P_PHONE_APP_EXIST", + code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_RUNNING + }; + var successCallBack = function() { + pingCallback.onSuccess(); + pingCallback.onPingResult(successCode); + console.info("ping success."); + }; + var notInstallCode = { + data: "ERROR_CODE_P2P_PHONE_APP_NOT_EXIST", + code: ErrorCode.MSG_ERROR_PING_PHONE_APP_NOT_EXIST + }; + var failCode = { + data: "ERROR_CODE_P2P_OTHER_ERROR", + code: ErrorCode.MSG_ERROR_PING_OTHER + }; + if (isEmpty(this.peerPkgName)) { + pingCallback.onFailure(); + pingCallback.onPingResult(notInstallCode); + return; + } + var failCallBack = function(data, code) { + if (!data && !code) { + pingCallback.onFailure(); + pingCallback.onPingResult(notInstallCode); + } else { + pingCallback.onFailure(); + pingCallback.onPingResult(failCode); + } + console.error("ping failed."); + }; + + if (this.version >= WEARENGINE_SERVICE_VISION_401) { + wearengine.detect({ + bundleName: this.peerPkgName, + success: successCallBack, + fail: failCallBack + }); + } else { + FeatureAbility.detect({ + bundleName: this.peerPkgName, + success: successCallBack, + fail: failCallBack + }); + } + }; + /** + * Register message listener + * receiver:object:onSuccess(),onFailure(),onReceiveMessage(message) + */ + P2pClient.prototype.registerReceiver = function(receiver) { + if (!receiver) { + receiver.onReceiveMessage( + { + isFileType: false, + message: "receiver is null", + } + ); + return; + } + if (this.version > WEARENGINE_SERVICE_VISION_302) { + if (isEmpty(this.peerPkgName)) { + console.error("peerPkgName cannot be empty"); + receiver.onFailure(); + return; + } + var setPeerPkgNameSuccessCallBack = function() { + console.info("registerReceiver setPeerPkgName success."); + }; + var setPeerPkgNameFailCallBack = function() { + console.info("registerReceiver setPeerPkgName fail."); + return; + }; + wearengine.setPackageName({ + appName: this.peerPkgName, + complete: setPeerPkgNameSuccessCallBack, + fail: setPeerPkgNameFailCallBack + }); + } + if (isEmpty(this.peerFingerPrint)) { + console.error("peerFingerPrint cannot be empty"); + receiver.onFailure(); + return; + } + var successCallBack = function(data) { + if (data) { + if (data.isRegister) { + receiver.onSuccess(); + } else if (data.isFileType){ + var fileObj = { + isFileType: true, + name: data.file, + mode: "", + mode2: "" + }; + receiver.onReceiveMessage(fileObj); + console.info("receive file name:" + fileObj.name); + } else { + receiver.onReceiveMessage(data.message); + // TechPie modification: messages may contain personal account data. + console.info("receive message bytes: " + data.message.length); + } + } else { + receiver.onSuccess(); + } + }; + if (this.version >= WEARENGINE_SERVICE_VISION_401) { + wearengine.unsubscribeMsg(); + wearengine.subscribeMsg({ + success: successCallBack, + fail: receiver.onFailure + }); + } else { + FeatureAbility.subscribeMsg({ + success: successCallBack, + fail: receiver.onFailure + }); + } + }; + /** + * Send messages + * message: Message + * sendCallback: object:onSuccess(),onFailure(),onSendResult(resultCode),onSendProgress(count) + * resultCode: SUCCESS 207, FAILURE 206 + */ + P2pClient.prototype.send = function(message, sendCallback) { + if (!message || !sendCallback) { + return; + } + + var failCode = { + data: "peerPkgName or peerFingerPrint empty", + code: ErrorCode.MSG_ERROR_SEND_FAIL + }; + if (isEmpty(this.peerPkgName) || isEmpty(this.peerFingerPrint)) { + console.error("peerPkgName or peerFingerPrint cannot be empty"); + sendCallback.onFailure(); + sendCallback.onSendResult(failCode); + return; + } + + if (message.getType() == MessageType.MESSAGE_TYPE_DATA) { + var successCallBack = function() { + var successCode = { + data: "ERROR_CODE_COMM_SUCCESS", + code: ErrorCode.MSG_ERROR_SEND_SUCCESS + }; + sendCallback.onSuccess(); + sendCallback.onSendResult(successCode); + sendCallback.onSendProgress(100 + "%"); + console.info("send message success."); + }; + + var failCallBack = function(errorMessage, code) { + var failCode = { + data: errorMessage, + code: ErrorCode.MSG_ERROR_SEND_FAIL + }; + sendCallback.onFailure(); + sendCallback.onSendResult(failCode); + sendCallback.onSendProgress(0 + "%"); + console.error("send message failed."); + }; + if (this.version >= WEARENGINE_SERVICE_VISION_401) { + wearengine.sendMsg({ + deviceId: "remote", + bundleName: this.peerPkgName, + abilityName: "", + message: message.getData(), + success: successCallBack, + fail: failCallBack + }); + } else { + FeatureAbility.sendMsg({ + deviceId: "remote", + bundleName: this.peerPkgName, + abilityName: "", + message: message.getData(), + success: successCallBack, + fail: failCallBack + }); + } + } else { + if (this.version < WEARENGINE_SERVICE_VISION_302) { + console.info("not support send file"); + var obj = { + data: "ERROR_CODE_VERSION_TOO_LOW", + code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW + }; + sendCallback.onFailure(); + sendCallback.onSendResult(obj); + return; + } + + var fileName = message.getFile().name; + // Service version earlier than 303 does not support the internal://app/ directory + if (this.version < WEARENGINE_SERVICE_VISION_303) { + var TempPath = fileName.substring(0, FILE_PUNLIC_PATH_INTERCETPED); + if (TempPath == WearEngineConst.DELAY_FILEAPP_VALUE) { + var obj = { + data: "ERROR_CODE_VERSION_TOO_LOW", + code: ErrorCode.MSG_ERROR_CODE_VERSION_TOO_LOW + }; + sendCallback.onFailure(); + sendCallback.onSendResult(obj); + console.info("wearEngine service version too low, file path not support"); + return; + } + } + var successCallBack = function() { + var successCode = { + data: "ERROR_CODE_COMM_SUCCESS", + code: ErrorCode.MSG_ERROR_SEND_SUCCESS + }; + sendCallback.onSuccess(); + sendCallback.onSendResult(successCode); + console.info("send file success."); + isTransferring = false; + }; + + var failCallBack = function(errorMessage, code) { + var failCode = { + data: errorMessage, + code: ErrorCode.MSG_ERROR_SEND_FAIL + }; + sendCallback.onFailure(); + sendCallback.onSendResult(failCode); + console.info("send file failed."); + isTransferring = false; + }; + if (isTransferring) { + console.error("send file failed,there is already a file being sent."); + failCallBack(); + return; + } + isTransferring = true; + + var progressCallBack = function(data) { + sendCallback.onSendProgress(data.progressNum + "%"); + console.info("progress of sending file: " + data.progressNum + "%"); + }; + + wearengine.uploadFile({ + fileName: fileName, + filePath: this.peerPkgName, + peerPackageName: this.peerPkgName, + success: successCallBack, + fail: failCallBack, + progress: progressCallBack + }); + } + }; + /** + * Deregister message listener + * receiver: onSuccess() + */ + P2pClient.prototype.unregisterReceiver = function(receiver) { + if (this.version >= WEARENGINE_SERVICE_VISION_401) { + wearengine.unsubscribeMsg(); + } else { + FeatureAbility.unsubscribeMsg(); + } + receiver.onSuccess(); + }; + /** + * Check whether the parameter is empty + * parameter: string + */ + function isEmpty(parameter) { + return parameter == "undefined" || parameter == null || parameter == "" || parameter == " "; + } + return P2pClient; +})(); + +/** + * File format type + * name: file name with path + * mode: 'text' or 'binary' + * mode2: 'R', 'W', 'RW' + */ +var File = (function() { + var name; + var mode; + var mode2; + + function File() {} + + return File; +})(); + +var Builder = (function() { + var messageInfo; + + function Builder() {} + + Builder.prototype.setDescription = function(description) { + this.messageInfo = description; + this.messageType = MessageType.MESSAGE_TYPE_DATA; + }; + /** + * Set the message information (either of the two formats) + * data: ArrayBuffer + * data: File(Not supported currently) + */ + Builder.prototype.setPayload = function(data) { + if (!data) { + return; + } + if (typeof data == "object" && data.name) { + this.messageType = MessageType.MESSAGE_TYPE_FILE; + return this.setFilePlayload(data); + } else { + this.messageType = MessageType.MESSAGE_TYPE_DATA; + return this.setBufferPlayload(data); + } + }; + Builder.prototype.setBufferPlayload = function(data) { + this.messageInfo = String.fromCharCode.apply(null, new Uint16Array(data)); + }; + Builder.prototype.setFilePlayload = function(data) { + this.messageInfo = JSON.stringify(data); + }; + return Builder; +})(); + +var Message = (function() { + var builder = new Builder(); + + function Message() {} + + Message.prototype.describeContents = function() { + return this.builder.messageInfo; + }; + /** + * Get information during transmission + */ + Message.prototype.getData = function() { + return this.builder.messageInfo; + }; + Message.prototype.getDescription = function() { + return this.builder.messageInfo; + }; + /** + * Get File Information + */ + Message.prototype.getFile = function() { + if (this.builder.messageType == MessageType.MESSAGE_TYPE_FILE) { + return JSON.parse(this.builder.messageInfo); + } + return null; + }; + /** + * Get the transmission data type + * 0 string + * 1 File + */ + Message.prototype.getType = function() { + return this.builder.messageType; + }; + return Message; +})(); + +var PeerDeviceClient = (function () { + var version; + function PeerDeviceClient() { + try { + var jsSdk = this; + var getVersionCallBack = function(data) { + if (data) { + var versionArray = data.split("."); + jsSdk.version = versionArray[versionArray.length - 1]; + console.info("service sdk version is: " + data); + } else { + jsSdk.version = 0; + console.info("get service sdk version failed"); + } + }; + wearengine.getWearEngineVersion({ + complete: getVersionCallBack, + sdkVersion: WEARENGINE_SDK_VERSION + }); + } catch (error) { + jsSdk.version = 0; + console.info("service sdk version is too low" + error.message); + } + } + + /** + * Get the peer device object + * sendCallback: object:onSuccess(data),onFailure(data) + */ + PeerDeviceClient.prototype.getPeerDevice = function (peerDeviceCallback) { + if (!peerDeviceCallback) { + console.error("getPeerDevice peerDeviceCallback is null"); + var obj = { + data: "ERROR_CODE_INVALID_ARGUMENT", + errorCode: ErrorCode.ERROR_CODE_INVALID_ARGUMENT + }; + return obj; + } + + if (this.version < WEARENGINE_SERVICE_VISION_401) { + console.error("getPeerDevice wearengine service verison is low"); + var obj = { + data: "ERROR_CODE_DEVICE_VERSION_NOT_SUPPORT", + errorCode: ErrorCode.ERROR_CODE_DEVICE_VERSION_NOT_SUPPORT + }; + peerDeviceCallback.onFailure(obj); + return; + } + + var successCallBack = function(data) { + peerDeviceCallback.onSuccess(data); + }; + var failCallBack = function(data) { + peerDeviceCallback.onFailure(data); + }; + + wearengine.getPeerDevice({ + success: successCallBack, + fail: failCallBack + }); + + return; + }; + + return PeerDeviceClient; +})(); + +export { P2pClient, Message, Builder, PeerDeviceClient }; diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.css b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.css new file mode 100644 index 00000000..96c8a852 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.css @@ -0,0 +1,22 @@ +.screen { width: 100%; height: 100%; background-color: #101412; } +.content { width: 100%; height: 100%; flex-direction: column; } +.spacer { height: 52px; width: 100%; } +.section { width: 100%; flex-direction: column; align-items: center; } +.brand { width: 280px; font-size: 28px; color: #f0f5ef; text-align: center; } +.status { width: 280px; font-size: 18px; color: #94d5b1; text-align: center; margin-top: 6px; margin-bottom: 16px; } +.card { width: 300px; padding: 18px; margin-bottom: 12px; flex-direction: column; background-color: #1c211e; border-radius: 24px; } +.caption { width: 264px; font-size: 18px; color: #94d5b1; margin-bottom: 6px; } +.headline { width: 264px; font-size: 24px; color: #f0f5ef; } +.support { width: 264px; font-size: 18px; color: #bec9c0; margin-top: 6px; margin-bottom: 10px; } +.due { width: 264px; font-size: 22px; color: #d9e7dd; margin-top: 10px; } +.primary { width: 300px; height: 60px; border-radius: 30px; background-color: #94d5b1; color: #003822; font-size: 22px; margin-bottom: 12px; } +.secondary { width: 300px; height: 60px; border-radius: 30px; background-color: #273e32; color: #c9ecd7; font-size: 22px; margin-bottom: 12px; } +.text-action { width: 264px; height: 56px; border-radius: 28px; background-color: #101412; color: #94d5b1; font-size: 20px; margin-bottom: 8px; } +.error { width: 264px; color: #ffb4ab; font-size: 18px; margin-top: 8px; margin-bottom: 12px; } +.code-page { width: 100%; height: 100%; flex-direction: column; align-items: center; justify-content: center; background-color: #ffffff; } +.code-title { width: 220px; height: 32px; text-align: center; font-size: 22px; color: #17231c; } +.qr { width: 264px; height: 264px; background-color: #ffffff; } +.code-empty { width: 250px; height: 264px; text-align: center; font-size: 22px; color: #384c40; } +.code-countdown { width: 250px; height: 24px; font-size: 18px; text-align: center; color: #384c40; } +.code-refresh { width: 250px; height: 48px; border-radius: 24px; background-color: #d3ecdd; color: #003822; font-size: 20px; margin-top: 6px; } +.code-back { width: 200px; height: 38px; border-radius: 19px; background-color: #ffffff; color: #384c40; font-size: 18px; } diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.hml b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.hml new file mode 100644 index 00000000..a9a79f99 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.hml @@ -0,0 +1,75 @@ +
+ + + + {{ view === 'home' ? 'TechPie' : (view === 'ddl' ? '待办 DDL' : (view === 'account' ? '我的账号' : '连接帮助')) }} + {{ status }} + + +
+ 即将截止 + {{ nextTitle }} + {{ nextDue }} +
+ + + + +
+ + {{ updated }} + {{ ddlEmpty }} + + + +
+ {{ $item.hint }} + {{ $item.title }} + {{ $item.course }} + {{ $item.due }} +
+
+ + {{ pageLabel }} + + + 更多待办请在手机查看 + 在手机连接页开启 DDL 提醒 + + +
+ 姓名 + {{ name || '待同步' }} + 学号 + {{ studentId || '待同步' }} +
+ {{ detail }} + +
+ +
+ 1. 配对手表 + 在华为运动健康中确认手表已连接。 +
+
+ 2. 手机授权 + 打开 TechPie 的 Settings → HUAWEI WATCH,查找并连接手表。 +
+ 连接时保持此应用打开。离开应用会隐藏账号与校园码。 + +
+ + {{ error }} + + + +
+
+ 校园码 + + {{ error || codeMessage }} + {{ codeMessage }} + + +
+
diff --git a/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.js b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.js new file mode 100644 index 00000000..72bdda78 --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.js @@ -0,0 +1,127 @@ +import { WearLink } from '../../common/wear-link.js'; + +var link, paintTimer, refreshTimer; +function short(value, length) { return value.length > length ? value.slice(0, length - 1) + '…' : value; } +function dueLabel(ms) { + var date = new Date(ms + 28800000); + return (date.getUTCMonth() + 1) + '/' + date.getUTCDate() + ' ' + + ('0' + date.getUTCHours()).slice(-2) + ':' + ('0' + date.getUTCMinutes()).slice(-2); +} +export default { + data: { + view: 'home', connected: false, status: '未连接', name: '', studentId: '', + detail: '打开手机 TechPie 连接手表', nextTitle: '连接后同步待办', nextDue: '', + deadlines: [], ddlReady: false, ddlEmpty: '等待手机同步', pageNumber: 0, + pageLabel: '', hasPrevious: false, hasNext: false, truncated: false, + syncing: false, syncLabel: '更新待办', codeVisible: false, codeLoading: false, + codeLabel: '获取校园码', codeMessage: '校园码仅在连接期间可用', codeSeconds: 0, + error: '', updated: '' + }, + onInit() { + var page = this; + link = new WearLink(function(state) { page.applyState(state); }); + link.start(); + }, + onShow() { if (link) link.start(); }, + onReady() { this.drawCode(); }, + onHide() { + this.view = 'home'; this.codeVisible = false; + if (paintTimer) clearTimeout(paintTimer); + if (refreshTimer) clearTimeout(refreshTimer); + if (link) link.stop(); + }, + onDestroy() { + if (paintTimer) clearTimeout(paintTimer); + if (refreshTimer) clearTimeout(refreshTimer); + if (link) link.stop(); link = null; + }, + onBackPress() { + if (this.view !== 'home') { this.goHome(); return true; } + return false; + }, + applyState(state) { + this.connected = state.connected; this.status = state.connected ? '已连接' : '未连接'; + this.name = state.name || ''; this.studentId = state.studentId || ''; + this.error = state.error || ''; this.syncing = state.syncing || false; + this.syncLabel = this.syncing ? '正在更新…' : '更新待办'; + this.ddlReady = state.ddlReady || false; this.truncated = state.truncated || false; + this.updated = state.updatedAt ? '更新于 ' + dueLabel(state.updatedAt) : ''; + var all = (state.ddl || []).filter(function(item) { return item.status === 'open'; }); + this.pageNumber = Math.min(this.pageNumber, Math.max(0, Math.ceil(all.length / 6) - 1)); + var now = link && link.connection.ready ? link.connection.phoneNow() : Date.now(); + this.deadlines = all.slice(this.pageNumber * 6, (this.pageNumber + 1) * 6).map(function(item) { + return {id: item.id, title: short(item.title, 32), course: short(item.courseName, 20), + due: dueLabel(item.dueAtMs), hint: item.dueAtMs <= now ? '已逾期' : + (item.dueAtMs - now < 86400000 ? '24 小时内截止' : '待完成')}; + }); + this.ddlEmpty = this.ddlReady ? '暂时没有待办' : '等待手机同步'; + this.pageLabel = all.length ? (this.pageNumber + 1) + ' / ' + Math.ceil(all.length / 6) : ''; + this.hasPrevious = this.pageNumber > 0; this.hasNext = (this.pageNumber + 1) * 6 < all.length; + var next = all.filter(function(item) { return item.dueAtMs > now; })[0]; + this.nextTitle = next ? short(next.title, 20) : (this.ddlReady ? '还没有即将截止的待办哦' : '连接后同步待办'); + this.nextDue = next ? dueLabel(next.dueAtMs) + ' 截止' : ''; + this.detail = state.connected ? '与手机 TechPie 保持连接' : '打开手机 TechPie 连接手表'; + this.codeLoading = state.codeLoading || false; + this.codeLabel = this.codeLoading ? '正在获取…' : '刷新校园码'; + this.codeSeconds = state.codeSeconds || 0; + this.codeVisible = this.view === 'code' && !!state.code; + this.codeMessage = this.codeLoading ? '正在向手机获取校园码' : + (this.codeVisible ? '剩余 ' + this.codeSeconds + ' 秒' : + (state.connected ? '点击刷新获取有效校园码' : '请先连接手机 TechPie')); + if (this.codeVisible && this._paintedCode !== state.code.id) this.drawCode(); + if (!this.codeVisible) this._paintedCode = null; + if (this.codeVisible && !this.codeLoading && this.codeSeconds <= 10 && + this._autoRequested !== state.code.id && link.connection.now() - state.code.requestAt >= 6000) { + this._autoRequested = state.code.id; + var page = this, id = state.code.id; + refreshTimer = setTimeout(function() { + if (link && page.view === 'code' && link.connection.code && link.connection.code.id === id) { + link.connection.request('code'); + } + }, 0); + } + }, + goHome() { + this.view = 'home'; this.codeVisible = false; + if (refreshTimer) clearTimeout(refreshTimer); + if (link) link.connection.hideCode(); + }, + showDdl() { this.view = 'ddl'; this.pageNumber = 0; if (link) link.connection.publish(); }, + showAccount() { this.view = 'account'; }, + showGuide() { this.view = 'guide'; }, + showCode() { this.view = 'code'; this.refreshCode(); }, + refreshCode() { + if (link && !this.codeLoading) link.connection.request('code'); + if (link) link.connection.publish(); + }, + refreshDdl() { if (link && !this.syncing) link.connection.request('sync'); }, + previousPage() { if (this.hasPrevious) { this.pageNumber--; link.connection.publish(); } }, + nextPage() { if (this.hasNext) { this.pageNumber++; link.connection.publish(); } }, + retryConnection() { if (link) { link.stop(); link.start(); } }, + drawCode() { + var page = this; + if (paintTimer) clearTimeout(paintTimer); + paintTimer = setTimeout(function() { + if (!link || page.view !== 'code' || !page.codeVisible || !link.connection.code) return; + var code = link.connection.code; + try { + var ctx = page.$refs.qr.getContext('2d'), size = code.size; + var cell = Math.floor(264 / (size + 8)), offset = Math.floor((264 - size * cell) / 2); + ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, 264, 264); + ctx.fillStyle = '#000000'; + for (var row = 0; row < size; row++) { + for (var col = 0; col < size; col++) { + var bit = row * size + col; + if (code.bytes[Math.floor(bit / 8)] & (1 << (7 - bit % 8))) { + ctx.fillRect(offset + col * cell, offset + row * cell, cell, cell); + } + } + } + page._paintedCode = code.id; + } catch (_) { + page.codeVisible = false; link.connection.hideCode(); + page.codeMessage = '呜呜,显示失败了…使用手机校园码吧!可以和开发者反馈哦~'; + } + }, 0); + } +}; diff --git a/harmonyos_watch/entry/src/main/resources/base/element/string.json b/harmonyos_watch/entry/src/main/resources/base/element/string.json new file mode 100644 index 00000000..09956414 --- /dev/null +++ b/harmonyos_watch/entry/src/main/resources/base/element/string.json @@ -0,0 +1,6 @@ +{ + "string": [ + { "name": "app_name", "value": "TechPie Watch" }, + { "name": "app_description", "value": "TechPie 校园服务手表端" } + ] +} diff --git a/harmonyos_watch/entry/src/main/resources/base/media/icon.png b/harmonyos_watch/entry/src/main/resources/base/media/icon.png new file mode 100644 index 00000000..74988639 Binary files /dev/null and b/harmonyos_watch/entry/src/main/resources/base/media/icon.png differ diff --git a/harmonyos_watch/entry/src/main/resources/base/media/icon_small.png b/harmonyos_watch/entry/src/main/resources/base/media/icon_small.png new file mode 100644 index 00000000..a8c01b00 Binary files /dev/null and b/harmonyos_watch/entry/src/main/resources/base/media/icon_small.png differ diff --git a/harmonyos_watch/hvigor/hvigor-config.json5 b/harmonyos_watch/hvigor/hvigor-config.json5 new file mode 100644 index 00000000..50aa5812 --- /dev/null +++ b/harmonyos_watch/hvigor/hvigor-config.json5 @@ -0,0 +1,4 @@ +{ + "modelVersion": "5.0.0", + "dependencies": {} +} diff --git a/harmonyos_watch/hvigorfile.ts b/harmonyos_watch/hvigorfile.ts new file mode 100644 index 00000000..a1929432 --- /dev/null +++ b/harmonyos_watch/hvigorfile.ts @@ -0,0 +1,6 @@ +import { legacyAppTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: legacyAppTasks, + plugins: [] +}; diff --git a/harmonyos_watch/oh-package.json5 b/harmonyos_watch/oh-package.json5 new file mode 100644 index 00000000..69ff201a --- /dev/null +++ b/harmonyos_watch/oh-package.json5 @@ -0,0 +1,7 @@ +{ + "modelVersion": "5.0.0", + "name": "techpie-watch", + "version": "1.0.0", + "description": "TechPie GT 6 Lite Wearable application", + "dependencies": {} +} diff --git a/harmonyos_watch/ohos/.gitignore b/harmonyos_watch/ohos/.gitignore new file mode 100644 index 00000000..8a9027a4 --- /dev/null +++ b/harmonyos_watch/ohos/.gitignore @@ -0,0 +1,21 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +**/BuildProfile.ets +**/oh-package-lock.json5 +/package.json +/package-lock.json + +**/src/main/resources/rawfile/flutter_assets/ +**/libs/**/libapp.so +**/libs/**/libflutter.so +**/libs/**/libvmservice_snapshot.so +signature/ \ No newline at end of file diff --git a/harmonyos_watch/ohos/AppScope/app.template.json5 b/harmonyos_watch/ohos/AppScope/app.template.json5 new file mode 100644 index 00000000..2d3a8010 --- /dev/null +++ b/harmonyos_watch/ohos/AppScope/app.template.json5 @@ -0,0 +1,20 @@ +// Template for ohos/AppScope/app.json5. +// +// The real file is generated by ohos/scripts/generate-build-profile.mjs, which +// hvigorfile.ts runs on every hvigor invocation (so DevEco builds too), and is +// gitignored. The version placeholders are filled from pubspec.yaml: that file +// is the single source of truth for the app version, and `flutter build hap` +// already stamps the packed bundle from it. Rendering the same numbers here +// keeps a DevEco-only build from disagreeing with a Flutter build. +// +// Bump the version in pubspec.yaml (`version: X.Y.Z+N`), never in this template. +{ + "app": { + "bundleName": "com.geekpie.techpie", + "vendor": "geekpie", + "versionCode": __APP_VERSION_CODE__, + "versionName": "__APP_VERSION_NAME__", + "icon": "$media:layered_image", + "label": "$string:app_name" + } +} diff --git a/harmonyos_watch/ohos/AppScope/resources/base/element/string.json b/harmonyos_watch/ohos/AppScope/resources/base/element/string.json new file mode 100644 index 00000000..5825f332 --- /dev/null +++ b/harmonyos_watch/ohos/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "TechPie" + } + ] +} diff --git a/harmonyos_watch/ohos/AppScope/resources/base/media/background.png b/harmonyos_watch/ohos/AppScope/resources/base/media/background.png new file mode 100644 index 00000000..fdd826fe Binary files /dev/null and b/harmonyos_watch/ohos/AppScope/resources/base/media/background.png differ diff --git a/harmonyos_watch/ohos/AppScope/resources/base/media/foreground.png b/harmonyos_watch/ohos/AppScope/resources/base/media/foreground.png new file mode 100644 index 00000000..0d41d0ff Binary files /dev/null and b/harmonyos_watch/ohos/AppScope/resources/base/media/foreground.png differ diff --git a/harmonyos_watch/ohos/AppScope/resources/base/media/layered_image.json b/harmonyos_watch/ohos/AppScope/resources/base/media/layered_image.json new file mode 100644 index 00000000..fb499204 --- /dev/null +++ b/harmonyos_watch/ohos/AppScope/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/build-profile.template.json5 b/harmonyos_watch/ohos/build-profile.template.json5 new file mode 100644 index 00000000..c1166013 --- /dev/null +++ b/harmonyos_watch/ohos/build-profile.template.json5 @@ -0,0 +1,56 @@ +// Template for ohos/build-profile.json5. +// The real file is generated by ohos/scripts/generate-build-profile.mjs +// (invoked automatically from hvigorfile.ts) and is gitignored. +// Placeholders are substituted with values from the OHOS_* environment variables. +{ + "app": { + "signingConfigs": [ + { + "name": "default", + "type": "HarmonyOS", + "material": { + "certpath": "__OHOS_CERT_PATH__", + "storePassword": "__OHOS_STORE_PASSWORD__", + "keyAlias": "__OHOS_KEY_ALIAS__", + "keyPassword": "__OHOS_KEY_PASSWORD__", + "profile": "__OHOS_PROFILE_PATH__", + "signAlg": "__OHOS_SIGN_ALG__", + "storeFile": "__OHOS_STORE_FILE__" + } + } + ], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS", + } + ], + "buildModeSet": [ + { + "name": "debug" + }, + { + "name": "profile" + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} diff --git a/harmonyos_watch/ohos/entry/.gitignore b/harmonyos_watch/ohos/entry/.gitignore new file mode 100644 index 00000000..5254b880 --- /dev/null +++ b/harmonyos_watch/ohos/entry/.gitignore @@ -0,0 +1,7 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test +GeneratedPluginRegistrant.ets \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/hvigorfile.ts b/harmonyos_watch/ohos/entry/hvigorfile.ts new file mode 100644 index 00000000..ff3bfe08 --- /dev/null +++ b/harmonyos_watch/ohos/entry/hvigorfile.ts @@ -0,0 +1,7 @@ + +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/harmonyos_watch/ohos/entry/libs/arm64-v8a/libecardbind_reader.so b/harmonyos_watch/ohos/entry/libs/arm64-v8a/libecardbind_reader.so new file mode 100644 index 00000000..80c317a4 Binary files /dev/null and b/harmonyos_watch/ohos/entry/libs/arm64-v8a/libecardbind_reader.so differ diff --git a/harmonyos_watch/ohos/entry/oh-package.json5 b/harmonyos_watch/ohos/entry/oh-package.json5 new file mode 100644 index 00000000..f1c24eeb --- /dev/null +++ b/harmonyos_watch/ohos/entry/oh-package.json5 @@ -0,0 +1,14 @@ + +{ + "name": "entry", + // hvigor module version — NOT the app version. The app version lives in + // pubspec.yaml alone; ohos/AppScope/app.json5 is generated from it. + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "libecardbind_reader.so": "file:./src/main/cpp/types/libecardbind_reader" + }, +} diff --git a/harmonyos_watch/ohos/entry/src/main/cpp/CMakeLists.txt b/harmonyos_watch/ohos/entry/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000..a98d4ecf --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/cpp/CMakeLists.txt @@ -0,0 +1,45 @@ +# CMake for the eCard bind packet reader (libecardbind_reader.so). +# +# hvigor does NOT run this file. The .so is built on a developer machine by +# ohos/scripts/build-ecardbind-reader.sh and committed under +# ohos/entry/libs/arm64-v8a/, so the release image needs no C++ toolchain (see +# CLAUDE.md -> OHOS-specific gotchas). The digest below is what keeps that +# committed artifact honest: it is embedded in the .so at compile time and +# recomputed from the source tree by test/ecard_bind_reader_artifact_test.dart. +cmake_minimum_required(VERSION 3.10) +project(ecardbind_reader) + +set(CMAKE_CXX_STANDARD 17) + +add_library(ecardbind_reader SHARED ecardbind_reader.cpp) + +# NAPI is provided by the OHOS NDK. +target_link_libraries(ecardbind_reader PUBLIC + libace_napi.z.so +) + +# Every file that can change the artifact, in one digest. The recipe is a line +# per file — " " — over the files of +# this directory, path-sorted, minus types/ (those are the ArkTS-facing +# declarations, not compiled here). CMakeLists.txt is included, so adding a +# source invalidates the digest too. +# +# Two implementations of that recipe exist (this one and the Dart test's). +# They are meant to agree; the test failing is how a disagreement is noticed. +file(GLOB_RECURSE ECARDBIND_SOURCES + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/*") +list(FILTER ECARDBIND_SOURCES EXCLUDE REGEX "^types/") +list(SORT ECARDBIND_SOURCES) + +set(ECARDBIND_SOURCE_LINES "") +foreach(source IN LISTS ECARDBIND_SOURCES) + file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${source}" source_hash) + string(APPEND ECARDBIND_SOURCE_LINES "${source} ${source_hash}\n") +endforeach() +string(SHA256 ECARDBIND_SOURCE_SHA256 "${ECARDBIND_SOURCE_LINES}") + +target_compile_definitions(ecardbind_reader PRIVATE + ECARDBIND_SOURCE_SHA256="${ECARDBIND_SOURCE_SHA256}") +message(STATUS "ecardbind_reader source digest ${ECARDBIND_SOURCE_SHA256}") diff --git a/harmonyos_watch/ohos/entry/src/main/cpp/ecardbind_reader.cpp b/harmonyos_watch/ohos/entry/src/main/cpp/ecardbind_reader.cpp new file mode 100644 index 00000000..1915799a --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/cpp/ecardbind_reader.cpp @@ -0,0 +1,246 @@ +// Packet I/O for the eCard bind tunnel's DNS responder. +// +// The interface the VPN extension creates is handed over as a file descriptor, +// and it is not a file: it is a non-seekable character device. Reading it from +// ArkTS is the one link of this tunnel that has no precedent — the OHOS VPN +// guide's own sample and the Tailscale port both do their packet I/O in native +// code — so the reads and writes happen here and everything else (DNS parsing, +// the reply, forwarding) stays in ArkTS where it can be read as one piece. +// +// Exposes three calls: +// startReading(fd, onPacket, onError) one packet per call, on the JS thread +// writePacket(fd, data, length) 0, or -errno +// stopReading() ends the loop; the fd outlives it + +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef ECARDBIND_SOURCE_SHA256 +#error "ECARDBIND_SOURCE_SHA256 is missing — build through ohos/scripts/build-ecardbind-reader.sh." +#endif + +// The .so this compiles to is committed (ohos/entry/libs/arm64-v8a/), not +// rebuilt by hvigor, so an ordinary build would never notice a source edit that +// was not compiled. The build script passes a digest of everything in this +// directory in as ECARDBIND_SOURCE_SHA256; the text below is where it lands, and +// test/ecard_bind_reader_artifact_test.dart is what reads it back and compares +// it against the source tree. Exported and marked used so no linker or strip +// pass can drop it. +extern "C" __attribute__((visibility("default"), used)) +const char kTechPieEcardBindSourceDigest[] = + "TECHPIE-ECARDBIND-SRC-SHA256=" ECARDBIND_SOURCE_SHA256; + +namespace { + +constexpr int kPacketSize = 2048; + +std::thread g_reader; +std::atomic g_reading{false}; +napi_threadsafe_function g_on_packet = nullptr; +napi_threadsafe_function g_on_error = nullptr; + +struct Packet { + uint8_t* bytes; + int32_t length; +}; + +/** Runs on the JS thread: hands one packet to ArkTS, then frees it. */ +void DeliverPacket(napi_env env, napi_value js_callback, void* context, void* data) { + Packet* packet = static_cast(data); + if (env != nullptr && js_callback != nullptr && packet != nullptr) { + void* raw = nullptr; + napi_value buffer = nullptr; + if (napi_create_arraybuffer(env, packet->length, &raw, &buffer) == napi_ok && raw != nullptr) { + memcpy(raw, packet->bytes, packet->length); + napi_value result = nullptr; + napi_call_function(env, nullptr, js_callback, 1, &buffer, &result); + } + } + if (packet != nullptr) { + free(packet->bytes); + free(packet); + } +} + +/** Runs on the JS thread: reports why the loop stopped. */ +void DeliverError(napi_env env, napi_value js_callback, void* context, void* data) { + char* message = static_cast(data); + if (env != nullptr && js_callback != nullptr && message != nullptr) { + napi_value text = nullptr; + if (napi_create_string_utf8(env, message, NAPI_AUTO_LENGTH, &text) == napi_ok) { + napi_value result = nullptr; + napi_call_function(env, nullptr, js_callback, 1, &text, &result); + } + } + free(message); +} + +void ReportError(const char* reason, int error_number) { + if (g_on_error == nullptr) { + return; + } + const char* detail = error_number != 0 ? strerror(error_number) : ""; + const size_t size = strlen(reason) + strlen(detail) + 32; + char* message = static_cast(malloc(size)); + if (message == nullptr) { + return; + } + snprintf(message, size, "%s (%s, errno=%d)", reason, detail, error_number); + if (napi_call_threadsafe_function(g_on_error, message, napi_tsfn_nonblocking) != napi_ok) { + free(message); + } +} + +void ReadLoop(int fd) { + auto* buffer = static_cast(malloc(kPacketSize)); + if (buffer == nullptr) { + ReportError("cannot allocate the packet buffer", 0); + return; + } + while (g_reading.load()) { + const ssize_t length = read(fd, buffer, kPacketSize); + if (length > 0) { + auto* packet = static_cast(malloc(sizeof(Packet))); + if (packet == nullptr) { + continue; + } + packet->bytes = static_cast(malloc(static_cast(length))); + if (packet->bytes == nullptr) { + free(packet); + continue; + } + memcpy(packet->bytes, buffer, static_cast(length)); + packet->length = static_cast(length); + if (napi_call_threadsafe_function(g_on_packet, packet, napi_tsfn_nonblocking) != napi_ok) { + free(packet->bytes); + free(packet); + } + continue; + } + if (length < 0 && (errno == EINTR || errno == EAGAIN)) { + continue; + } + // Zero bytes or a real error: the interface is gone, and there is nothing + // left to read from it. + ReportError(length == 0 ? "the interface stopped delivering packets" + : "cannot read the interface", + length == 0 ? 0 : errno); + break; + } + free(buffer); + g_reading.store(false); +} + +napi_value StartReading(napi_env env, napi_callback_info info) { + size_t argc = 3; + napi_value argv[3] = {nullptr, nullptr, nullptr}; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + if (argc < 3) { + return nullptr; + } + int32_t fd = -1; + if (napi_get_value_int32(env, argv[0], &fd) != napi_ok || fd < 0) { + return nullptr; + } + // A second start replaces the first: same fd, same job. + if (g_reader.joinable()) { + g_reading.store(false); + g_reader.detach(); + } + if (g_on_packet != nullptr) { + napi_release_threadsafe_function(g_on_packet, napi_tsfn_abort); + g_on_packet = nullptr; + } + if (g_on_error != nullptr) { + napi_release_threadsafe_function(g_on_error, napi_tsfn_abort); + g_on_error = nullptr; + } + napi_value name = nullptr; + if (napi_create_string_utf8(env, "ecardbind_packet", NAPI_AUTO_LENGTH, &name) != napi_ok) { + return nullptr; + } + if (napi_create_threadsafe_function(env, argv[1], nullptr, name, 0, 1, nullptr, nullptr, nullptr, + DeliverPacket, &g_on_packet) != napi_ok) { + g_on_packet = nullptr; + return nullptr; + } + if (napi_create_string_utf8(env, "ecardbind_error", NAPI_AUTO_LENGTH, &name) != napi_ok) { + return nullptr; + } + if (napi_create_threadsafe_function(env, argv[2], nullptr, name, 0, 1, nullptr, nullptr, nullptr, + DeliverError, &g_on_error) != napi_ok) { + g_on_error = nullptr; + return nullptr; + } + g_reading.store(true); + g_reader = std::thread(ReadLoop, static_cast(fd)); + return nullptr; +} + +/** Writes `length` bytes of `data` into the interface. Returns 0, or -errno. */ +napi_value WritePacket(napi_env env, napi_callback_info info) { + size_t argc = 3; + napi_value argv[3] = {nullptr, nullptr, nullptr}; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + napi_value result = nullptr; + if (argc < 3) { + napi_create_int32(env, -EINVAL, &result); + return result; + } + int32_t fd = -1; + void* data = nullptr; + size_t total = 0; + int32_t length = 0; + if (napi_get_value_int32(env, argv[0], &fd) != napi_ok || + napi_get_arraybuffer_info(env, argv[1], &data, &total) != napi_ok || + napi_get_value_int32(env, argv[2], &length) != napi_ok || data == nullptr) { + napi_create_int32(env, -EINVAL, &result); + return result; + } + if (length < 0 || static_cast(length) > total) { + napi_create_int32(env, -EINVAL, &result); + return result; + } + const ssize_t written = write(fd, data, static_cast(length)); + napi_create_int32(env, written < 0 ? -errno : 0, &result); + return result; +} + +napi_value StopReading(napi_env env, napi_callback_info info) { + g_reading.store(false); + if (g_on_packet != nullptr) { + napi_release_threadsafe_function(g_on_packet, napi_tsfn_abort); + g_on_packet = nullptr; + } + if (g_on_error != nullptr) { + napi_release_threadsafe_function(g_on_error, napi_tsfn_abort); + g_on_error = nullptr; + } + if (g_reader.joinable()) { + // The loop ends when its blocked read returns: either a packet arrives or + // the interface goes away. + g_reader.detach(); + } + return nullptr; +} + +napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor properties[] = { + {"startReading", nullptr, StartReading, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"writePacket", nullptr, WritePacket, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"stopReading", nullptr, StopReading, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties); + return exports; +} + +} // namespace + +NAPI_MODULE(ecardbind_reader, Init) diff --git a/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/index.d.ts b/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/index.d.ts new file mode 100644 index 00000000..78ca443f --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/index.d.ts @@ -0,0 +1,14 @@ +// Types for libecardbind_reader.so (the NAPI module in src/main/cpp). + +/** Reads one packet per call, on the JS thread, until stopReading. */ +export const startReading: ( + fd: number, + onPacket: (data: ArrayBuffer) => void, + onError: (message: string) => void +) => void; + +/** Writes `length` bytes of `data` into the interface. 0, or -errno. */ +export const writePacket: (fd: number, data: ArrayBuffer, length: number) => number; + +/** Ends the loop. The fd itself is the caller's to destroy. */ +export const stopReading: () => void; diff --git a/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/oh-package.json5 b/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/oh-package.json5 new file mode 100644 index 00000000..37837832 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/cpp/types/libecardbind_reader/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libecardbind_reader.so", + "types": "./index.d.ts", + "version": "1.0.0", + "description": "Packet I/O for the eCard bind tunnel's DNS responder (HarmonyOS)" +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/campuscard/CampusCardPlatformPlugin.ets b/harmonyos_watch/ohos/entry/src/main/ets/campuscard/CampusCardPlatformPlugin.ets new file mode 100644 index 00000000..a238c475 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/campuscard/CampusCardPlatformPlugin.ets @@ -0,0 +1,67 @@ +import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos'; +import MethodChannel, { MethodCallHandler, MethodResult } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; +import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; +import EventChannel, { EventSink } from '@ohos/flutter_ohos/src/main/ets/plugin/common/EventChannel'; +import connection from '@ohos.net.connection'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export class CampusCardPlatformPlugin implements FlutterPlugin, MethodCallHandler { + private methods: MethodChannel | null = null; + private events: EventChannel | null = null; + private network: connection.NetConnection | null = null; + private sink: EventSink | null = null; + + getUniqueClassName(): string { return 'CampusCardPlatformPlugin'; } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.methods = new MethodChannel(binding.getBinaryMessenger(), 'techpie/campus_card'); + this.methods.setMethodCallHandler(this); + this.events = new EventChannel(binding.getBinaryMessenger(), 'techpie/campus_card/connectivity'); + this.events.setStreamHandler({ + onListen: (_args: Object, sink: EventSink) => { + this.stopListening(); + this.sink = sink; + const network = connection.createNetConnection(); + this.network = network; + network.on('netAvailable', () => { this.updateNetwork(network); }); + network.on('netLost', () => { this.updateNetwork(network); }); + network.register((error: BusinessError) => { + if (this.network !== network) return; + if (error) sink.error('NETWORK_LISTENER_FAILED', 'Cannot observe network state', null); + else this.updateNetwork(network); + }); + }, + onCancel: () => { this.stopListening(); } + }); + } + + private updateNetwork(network: connection.NetConnection): void { + connection.hasDefaultNet().then((online: boolean) => { + if (this.network === network) this.sink?.success(online); + }).catch(() => { + if (this.network === network) this.sink?.success(false); + }); + } + + private stopListening(): void { + const network = this.network; + this.network = null; + this.sink = null; + network?.unregister(() => {}); + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + if (call.method === 'isOnline') { + connection.hasDefaultNet().then((online: boolean) => result.success(online)) + .catch(() => result.error('NETWORK_STATE_FAILED', 'Cannot read network state', null)); + } else result.notImplemented(); + } + + onDetachedFromEngine(_binding: FlutterPluginBinding): void { + this.stopListening(); + this.methods?.setMethodCallHandler(null); + this.events?.setStreamHandler(null); + this.methods = null; + this.events = null; + } +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindDns.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindDns.ets new file mode 100644 index 00000000..f7733b85 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindDns.ets @@ -0,0 +1,121 @@ +/** + * The DNS wire format the bind tunnel speaks: echo the question, then either + * append an A record pointing at the mirror or answer with no records at all so + * the client falls back to IPv4. + * + * The layout — 0x8180 in the flags, a compressed name pointer 0xC00C for the + * answer — is the one the Android service and the desktop hijack script already + * serve the same records with. + */ + +const HEADER_SIZE: number = 12; +const QUESTION_TAIL: number = 4; +const ANSWER_SIZE: number = 16; +const COMPRESSION_MASK: number = 0xc0; +const RESPONSE_FLAGS: number = 0x80; +const RECURSION_DESIRED: number = 0x01; +const TRUNCATED: number = 0x02; +const CLASS_IN: number = 1; +const TTL_SECONDS: number = 60; + +export const TYPE_A: number = 1; +export const RCODE_SERVFAIL: number = 2; + +/** The question of a DNS message, with where its type field sits. */ +export interface EcardBindQuestion { + name: string; + type: number; + typeOffset: number; +} + +export function queryId(payload: Uint8Array): number { + return (payload[0] << 8) | payload[1]; +} + +/** The question of a DNS message, or null when it is not one we can read. */ +export function parseQuestion(payload: Uint8Array, length: number): EcardBindQuestion | null { + let name = ''; + let offset = HEADER_SIZE; + let terminated = false; + while (offset < length) { + const labelLength = payload[offset]; + if (labelLength === 0) { + offset += 1; + terminated = true; + break; + } + // Compression pointers never appear in a question. + if ((labelLength & COMPRESSION_MASK) !== 0) { + return null; + } + if (offset + 1 + labelLength > length) { + return null; + } + if (name.length > 0) { + name += '.'; + } + for (let index = 0; index < labelLength; index++) { + name += String.fromCharCode(payload[offset + 1 + index]); + } + offset += 1 + labelLength; + } + if (!terminated || offset + QUESTION_TAIL > length) { + return null; + } + const type = (payload[offset] << 8) | payload[offset + 1]; + return { name: name, type: type, typeOffset: offset }; +} + +/** + * The reply for `question`: the question echoed back, and — when `address` is + * given — a single A record pointing at it. A null address answers with no + * records at all, which is how the other types for the hijacked name are told to + * use the A record instead; `rcode` other than 0 is a failure answer. + */ +export function buildReply( + id: number, + payload: Uint8Array, + question: EcardBindQuestion, + address: number[] | null, + rcode: number = 0, + truncated: boolean = false, +): Uint8Array { + const questionLength = question.typeOffset + QUESTION_TAIL - HEADER_SIZE; + const reply = new Uint8Array( + HEADER_SIZE + questionLength + (address === null ? 0 : ANSWER_SIZE), + ); + reply[0] = id >> 8; + reply[1] = id; + // Response, recursion available, and the query's own RD bit echoed back: a + // resolver that asked for recursion is entitled to see it mirrored. + reply[2] = RESPONSE_FLAGS | (payload[2] & RECURSION_DESIRED) | (truncated ? TRUNCATED : 0); + reply[3] = RESPONSE_FLAGS | rcode; + // One question, one answer at most, and no authority or additional records. + reply[5] = 1; + if (address !== null) { + reply[7] = 1; + } + reply.set(payload.subarray(HEADER_SIZE, HEADER_SIZE + questionLength), HEADER_SIZE); + if (address === null) { + return reply; + } + + let offset = HEADER_SIZE + questionLength; + reply[offset++] = 0xc0; + reply[offset++] = 0x0c; + reply[offset++] = 0; + reply[offset++] = TYPE_A; + reply[offset++] = 0; + reply[offset++] = CLASS_IN; + reply[offset++] = 0; + reply[offset++] = 0; + reply[offset++] = 0; + reply[offset++] = TTL_SECONDS; + reply[offset++] = 0; + reply[offset++] = 4; + reply[offset++] = address[0]; + reply[offset++] = address[1]; + reply[offset++] = address[2]; + reply[offset++] = address[3]; + return reply; +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPackets.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPackets.ets new file mode 100644 index 00000000..e2ed71e9 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPackets.ets @@ -0,0 +1,143 @@ +/** + * The little bit of IPv4/UDP the bind tunnel needs: recognise a DNS query taken + * off the interface queue, and build the reply packet to put back into it. + * + * A socket on port 53 is not an option — port 53 is privileged, so binding to + * it fails — while reading and writing the interface needs no privilege at all. + * This is the same packet layout the Android service uses + * (android/.../ecardbind/EcardBindPackets.kt), so both platforms answer with + * identical bytes. + */ + +const IPV4_HEADER: number = 20; +const UDP_HEADER: number = 8; +const VERSION_IPV4: number = 0x40; +const FRAGMENT_MASK: number = 0x3fff; +const DEFAULT_TTL: number = 64; +const FLAG_DONT_FRAGMENT: number = 0x4000; + +export const UDP_PROTOCOL: number = 17; +export const DNS_PORT: number = 53; + +/** A whole IPv4/UDP datagram, with its payload located in the packet. */ +export interface EcardBindDatagram { + sourceAddress: number[]; + destinationAddress: number[]; + sourcePort: number; + destinationPort: number; + identification: number; + payloadOffset: number; + payloadLength: number; +} + +/** The UDP datagram inside `packet`, or null when it is not a whole IPv4 one. */ +export function parseUdp(packet: Uint8Array, length: number): EcardBindDatagram | null { + if (length < IPV4_HEADER) { + return null; + } + if ((packet[0] & 0xf0) !== VERSION_IPV4) { + return null; + } + const headerLength = (packet[0] & 0x0f) * 4; + if (headerLength < IPV4_HEADER || headerLength + UDP_HEADER > length) { + return null; + } + if (packet[9] !== UDP_PROTOCOL) { + return null; + } + // Anything but a whole datagram (fragment offset, more fragments) is not a + // DNS query; the resolver does not fragment them. + const offsetAndFlags = (packet[6] << 8) | packet[7]; + if ((offsetAndFlags & FRAGMENT_MASK) !== 0) { + return null; + } + const udpLength = (packet[headerLength + 4] << 8) | packet[headerLength + 5]; + if (udpLength < UDP_HEADER || headerLength + udpLength > length) { + return null; + } + return { + sourceAddress: [packet[12], packet[13], packet[14], packet[15]], + destinationAddress: [packet[16], packet[17], packet[18], packet[19]], + sourcePort: portAt(packet, headerLength), + destinationPort: portAt(packet, headerLength + 2), + identification: (packet[4] << 8) | packet[5], + payloadOffset: headerLength + UDP_HEADER, + payloadLength: udpLength - UDP_HEADER, + }; +} + +/** An IPv4/UDP packet carrying `payload`, addressed back at `query`'s sender. */ +export function buildUdpReply(query: EcardBindDatagram, payload: Uint8Array): Uint8Array { + const totalLength = IPV4_HEADER + UDP_HEADER + payload.length; + const packet = new Uint8Array(totalLength); + packet[0] = VERSION_IPV4 | (IPV4_HEADER / 4); + packet[2] = totalLength >> 8; + packet[3] = totalLength; + packet[4] = query.identification >> 8; + packet[5] = query.identification; + packet[6] = FLAG_DONT_FRAGMENT >> 8; + packet[7] = FLAG_DONT_FRAGMENT; + packet[8] = DEFAULT_TTL; + packet[9] = UDP_PROTOCOL; + // Bytes 10..11 stay zero until the header checksum is written. + packet[12] = query.destinationAddress[0]; + packet[13] = query.destinationAddress[1]; + packet[14] = query.destinationAddress[2]; + packet[15] = query.destinationAddress[3]; + packet[16] = query.sourceAddress[0]; + packet[17] = query.sourceAddress[1]; + packet[18] = query.sourceAddress[2]; + packet[19] = query.sourceAddress[3]; + const headerChecksum = complement(sumWords(0, packet, 0, IPV4_HEADER)); + packet[10] = headerChecksum >> 8; + packet[11] = headerChecksum; + + const udpLength = UDP_HEADER + payload.length; + packet[IPV4_HEADER] = query.destinationPort >> 8; + packet[IPV4_HEADER + 1] = query.destinationPort; + packet[IPV4_HEADER + 2] = query.sourcePort >> 8; + packet[IPV4_HEADER + 3] = query.sourcePort; + packet[IPV4_HEADER + 4] = udpLength >> 8; + packet[IPV4_HEADER + 5] = udpLength; + packet.set(payload, IPV4_HEADER + UDP_HEADER); + + // Pseudo header: both addresses, then the zero byte and protocol as the word + // 0x0011, then the UDP length. + let running = sumWords(0, packet, 12, 8); + running += UDP_PROTOCOL + udpLength; + running += sumWords(0, packet, IPV4_HEADER, UDP_HEADER + payload.length); + let udpChecksum = complement(running); + // Zero means "not computed" for UDP, which some receivers reject. + if (udpChecksum === 0) { + udpChecksum = 0xffff; + } + packet[IPV4_HEADER + 6] = udpChecksum >> 8; + packet[IPV4_HEADER + 7] = udpChecksum; + return packet; +} + +function portAt(packet: Uint8Array, offset: number): number { + return (packet[offset] << 8) | packet[offset + 1]; +} + +function sumWords(initial: number, packet: Uint8Array, from: number, count: number): number { + let total = initial; + const end = from + count; + let index = from; + while (index + 1 < end) { + total += (packet[index] << 8) | packet[index + 1]; + index += 2; + } + if (index < end) { + total += packet[index] << 8; + } + return total; +} + +function complement(sum: number): number { + let folded = sum; + while (folded > 0xffff) { + folded = (folded >> 16) + (folded & 0xffff); + } + return (~folded) & 0xffff; +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPlugin.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPlugin.ets new file mode 100644 index 00000000..74f47a52 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindPlugin.ets @@ -0,0 +1,230 @@ +/** + * The app's side of the eCard bind tunnel: the `techpie/ecard_bind` channel the + * Dart service calls, matching the Android implementation in MainActivity. + * + * The tunnel itself lives in a VPN extension process + * (EcardBindVpnAbility), which the system starts here and which reports back + * through the shared state file. Starting is the interactive step: the first + * start shows the system's VPN authorization dialog, so `start` waits for the + * extension's verdict instead of guessing. + * + * While the tunnel is up so is a DATA_TRANSFER long task: the flow is read in + * the mini program, which leaves this app in the background, and the VPN + * extension process would otherwise be frozen mid-flow. + */ + +import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos'; +import { AbilityAware, AbilityPluginBinding } from '@ohos/flutter_ohos/index'; +import MethodChannel, { MethodCallHandler, MethodResult } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; +import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import vpnExtension from '@ohos.net.vpnExtension'; +import Want from '@ohos.app.ability.Want'; +import wantAgent from '@ohos.app.ability.wantAgent'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import hilog from '@ohos.hilog'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { clearState, readState, writeState } from './EcardBindState'; + +const DOMAIN: number = 0x0000; +const TAG: string = 'EcardBind'; +const CHANNEL: string = 'techpie/ecard_bind'; +const EXTENSION_ABILITY: string = 'EcardBindVpnAbility'; +const ENTRY_ABILITY: string = 'EntryAbility'; + +/** How long the system's authorization dialog is given to be answered. */ +const START_TIMEOUT_MS: number = 20000; +const POLL_INTERVAL_MS: number = 120; + +export class EcardBindPlugin implements FlutterPlugin, MethodCallHandler, AbilityAware { + private methods: MethodChannel | null = null; + private ability: UIAbility | null = null; + private bundleName: string = ''; + private longTask: boolean = false; + + getUniqueClassName(): string { + return 'EcardBindPlugin'; + } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.methods = new MethodChannel(binding.getBinaryMessenger(), CHANNEL); + this.methods.setMethodCallHandler(this); + } + + onDetachedFromEngine(binding: FlutterPluginBinding): void { + this.methods?.setMethodCallHandler(null); + this.methods = null; + } + + onAttachedToAbility(binding: AbilityPluginBinding): void { + this.ability = binding.getAbility(); + this.bundleName = this.ability.context.abilityInfo.bundleName; + } + + onDetachedFromAbility(): void { + this.ability = null; + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + if (call.method === 'start') { + this.start(call) + .then((status: string) => result.success(status)) + .catch((error: BusinessError) => { + hilog.error(DOMAIN, TAG, 'start failed: %{public}s', JSON.stringify(error)); + result.success('inactive'); + }); + } else if (call.method === 'stop') { + this.stop() + .then(() => result.success(null)) + .catch((error: BusinessError) => { + hilog.error(DOMAIN, TAG, 'stop failed: %{public}s', JSON.stringify(error)); + result.success(null); + }); + } else if (call.method === 'status') { + result.success(this.status()); + } else { + result.notImplemented(); + } + } + + private status(): string { + const filesDir = this.ability?.context.filesDir; + if (filesDir === undefined) { + return 'inactive'; + } + const state = readState(filesDir); + if (state === null) { + return 'inactive'; + } + if (state.status === 'active') { + return 'active'; + } + if (state.status === 'denied') { + return 'denied'; + } + return 'inactive'; + } + + /** + * Records the request, starts the extension, and waits for what it says. + * + * The result is the extension's, not this method's: only the process that + * holds the interface knows whether there is one. + */ + private async start(call: MethodCall): Promise { + const filesDir = this.ability?.context.filesDir; + const host: string = (call.argument('host') ?? '').toString().trim().toLowerCase(); + const ip: string = (call.argument('ip') ?? '').toString().trim(); + if (filesDir === undefined || host.length === 0 || ip.length === 0) { + hilog.error(DOMAIN, TAG, 'start ignored: incomplete parameters'); + return 'inactive'; + } + hilog.info(DOMAIN, TAG, 'start host=%{public}s answer=%{public}s', host, ip); + writeState(filesDir, 'requested', host, ip); + + const want: Want = { + deviceId: '', + bundleName: this.bundleName, + abilityName: EXTENSION_ABILITY, + }; + try { + await vpnExtension.startVpnExtensionAbility(want); + } catch (error) { + const failure = error as BusinessError; + hilog.error(DOMAIN, TAG, 'startVpnExtensionAbility failed: %{public}s', JSON.stringify(error)); + // Not being able to start it at all is a refusal or a packaging mistake; + // both are worth telling apart in the UI. + const missing = failure.code === 16000001 || failure.code === 16000002 || + failure.code === 16000011; + return missing ? 'inactive' : 'denied'; + } + + const deadline = Date.now() + START_TIMEOUT_MS; + while (Date.now() < deadline) { + const state = readState(filesDir); + if (state !== null && state.status !== 'requested') { + if (state.status === 'active') { + await this.startLongTask(); + return 'active'; + } + return state.status === 'denied' ? 'denied' : 'inactive'; + } + await sleep(POLL_INTERVAL_MS); + } + hilog.warn(DOMAIN, TAG, 'the extension did not report a tunnel in time'); + return 'inactive'; + } + + private async stop(): Promise { + const want: Want = { + deviceId: '', + bundleName: this.bundleName, + abilityName: EXTENSION_ABILITY, + }; + try { + await vpnExtension.stopVpnExtensionAbility(want); + } catch (error) { + hilog.warn(DOMAIN, TAG, 'stopVpnExtensionAbility failed: %{public}s', JSON.stringify(error)); + } + const filesDir = this.ability?.context.filesDir; + if (filesDir !== undefined) { + clearState(filesDir); + } + await this.stopLongTask(); + } + + private async startLongTask(): Promise { + if (this.longTask) { + return; + } + const ability = this.ability; + if (ability === null) { + return; + } + try { + const info: wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: this.bundleName, + abilityName: ENTRY_ABILITY, + }, + ], + actionType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + }; + const agent: WantAgent = await wantAgent.getWantAgent(info); + await backgroundTaskManager.startBackgroundRunning(ability.context, ['dataTransfer'], agent); + this.longTask = true; + hilog.info(DOMAIN, TAG, 'long task started for the bind flow'); + } catch (error) { + // The tunnel is up either way; without the long task it only has to + // survive while the app is in front. + hilog.warn(DOMAIN, TAG, 'cannot start the long task: %{public}s', JSON.stringify(error)); + } + } + + private async stopLongTask(): Promise { + if (!this.longTask) { + return; + } + const ability = this.ability; + this.longTask = false; + if (ability === null) { + return; + } + try { + await backgroundTaskManager.stopBackgroundRunning(ability.context); + hilog.info(DOMAIN, TAG, 'long task stopped'); + } catch (error) { + hilog.warn(DOMAIN, TAG, 'cannot stop the long task: %{public}s', JSON.stringify(error)); + } + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve: () => void) => { + setTimeout(resolve, ms); + }); +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindState.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindState.ets new file mode 100644 index 00000000..693b2694 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindState.ets @@ -0,0 +1,129 @@ +/** + * The record of what the bind tunnel is doing, shared between the two processes + * that care about it: the VPN extension ability (which runs in its own process + * and owns the tunnel) and the app (which starts, stops and reports on it). + * + * It is a file rather than preferences on purpose — preferences cache in memory + * per process, so the app would keep reading the value it last wrote while the + * extension process was the one changing it. + * + * The counters are for diagnosis: a tunnel that says `active` with `reads` stuck + * at zero has an interface nothing is arriving on, which is a different fault + * from one that answers wrongly. + */ + +import fs from '@ohos.file.fs'; + +const STATE_FILE = 'ecard_bind_state.json'; + +/** `requested` until the extension has an opinion; then one of the others. */ +export type EcardBindStateStatus = 'requested' | 'active' | 'denied' | 'failed'; + +export interface EcardBindStateFile { + status: EcardBindStateStatus; + /** The name the tunnel answers for. */ + host: string; + /** The address it answers with. */ + ip: string; + /** Packets read off the interface. */ + reads: number; + /** Queries answered from the hijacked name's own A record. */ + answered: number; + /** Queries relayed to the upstream resolver. */ + forwarded: number; + /** Why the tunnel stopped, when it stopped on its own. */ + error: string; + /** When this record was written, in milliseconds. */ + at: number; +} + +export function writeState( + filesDir: string, + status: EcardBindStateStatus, + host: string, + ip: string, + error: string = '', +): void { + writeRecord(filesDir, { + status: status, + host: host, + ip: ip, + reads: 0, + answered: 0, + forwarded: 0, + error: error, + at: Date.now(), + }); +} + +/** Updates the counters of the record that is already there. */ +export function recordStats( + filesDir: string, + reads: number, + answered: number, + forwarded: number, + error: string, +): void { + const current = readState(filesDir); + if (current === null) { + return; + } + current.reads = reads; + current.answered = answered; + current.forwarded = forwarded; + current.error = error; + current.at = Date.now(); + writeRecord(filesDir, current); +} + +/** The record, or null when there is none (or it is unreadable). */ +export function readState(filesDir: string): EcardBindStateFile | null { + const path = filesDir + '/' + STATE_FILE; + let file: fs.File | null = null; + try { + const stat = fs.statSync(path); + if (stat.size <= 0) { + return null; + } + file = fs.openSync(path, fs.OpenMode.READ_ONLY); + const buffer = new ArrayBuffer(stat.size); + const read = fs.readSync(file.fd, buffer); + if (read <= 0) { + return null; + } + return JSON.parse(bufferToString(buffer, read)) as EcardBindStateFile; + } catch (error) { + return null; + } finally { + if (file !== null) { + fs.closeSync(file); + } + } +} + +export function clearState(filesDir: string): void { + try { + fs.unlinkSync(filesDir + '/' + STATE_FILE); + } catch (error) { + // Already gone: nothing to clear. + } +} + +function writeRecord(filesDir: string, record: EcardBindStateFile): void { + const path = filesDir + '/' + STATE_FILE; + const file = fs.openSync(path, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE | fs.OpenMode.TRUNC); + try { + fs.writeSync(file.fd, JSON.stringify(record)); + } finally { + fs.closeSync(file); + } +} + +function bufferToString(buffer: ArrayBuffer, length: number): string { + const bytes = new Uint8Array(buffer, 0, length); + let text = ''; + for (let index = 0; index < bytes.length; index++) { + text += String.fromCharCode(bytes[index]); + } + return text; +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindVpnAbility.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindVpnAbility.ets new file mode 100644 index 00000000..afa6c699 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardbind/EcardBindVpnAbility.ets @@ -0,0 +1,471 @@ +/** + * The OHOS side of the eCard bind tunnel: a DNS-only VPN. + * + * The interface carries a /32 route for its own address and another for the + * resolver address it hands out, and this ability answers the resulting queries + * itself. Only name resolution changes, for every app: their TCP keeps leaving + * through the underlying network, because nothing else is routed into this + * tunnel. No app list is configured on purpose — the lookup that matters can + * come from any of them, and a list would quietly stop covering the ones it does + * not name. + * + * It is the same design as the Android service + * (android/.../ecardbind/EcardBindVpnService.kt), including the reason the + * resolver address is routed rather than assigned to the interface — that is + * also what Tailscale's HarmonyOS port does with its own 100.100.100.100, where + * the address is not one of the interface's `addresses` either. + * + * One thing deliberately differs. The reference Tailscale tunnel protects its + * whole process with `protectProcessNet()`; here that would defeat the tunnel, + * because this app is itself in the trusted list — its own lookup of the eCard + * host has to go through the tunnel. No protection is needed either: the only + * routes are the two /32s, so the upstream query this ability sends to the real + * resolver leaves through the underlying network and cannot loop back. + * + * Packets are read and written by libecardbind_reader.so: the interface is a + * non-seekable character device, and the OHOS VPN guide's own sample does its + * packet I/O natively for the same reason. + */ + +import VpnExtensionAbility from '@ohos.app.ability.VpnExtensionAbility'; +import vpnExtension from '@ohos.net.vpnExtension'; +import connection from '@ohos.net.connection'; +import socket from '@ohos.net.socket'; +import Want from '@ohos.app.ability.Want'; +import hilog from '@ohos.hilog'; +import { BusinessError } from '@kit.BasicServicesKit'; +import reader from 'libecardbind_reader.so'; +import { EcardBindStateFile, clearState, readState, recordStats, writeState } from './EcardBindState'; +import { EcardBindDatagram, buildUdpReply, parseUdp, DNS_PORT } from './EcardBindPackets'; +import { + EcardBindQuestion, + RCODE_SERVFAIL, + TYPE_A, + buildReply, + parseQuestion, + queryId, +} from './EcardBindDns'; + +const DOMAIN: number = 0x0000; +const TAG: string = 'EcardBindVpn'; + +/** The interface's own address. */ +const TUN_ADDRESS: string = '10.111.222.1'; +/** + * The address the tunnel answers DNS for. It sits next to [TUN_ADDRESS] but is + * deliberately never assigned to the interface: see the config below. + */ +const DNS_ADDRESS: string = '10.111.222.2'; +const FALLBACK_UPSTREAM: string = '223.5.5.5'; +const DEFAULT_MTU: number = 1500; +/** One IP packet has to fit the interface MTU, headers included. */ +const MAX_REPLY_PACKET: number = 1500; +const UPSTREAM_TIMEOUT_MS: number = 4000; +const ADDRESS_FAMILY_IPV4: number = 1; +/** How many queries may wait on the upstream at once. */ +const MAX_PENDING_QUERIES: number = 64; + +/** One query in flight to the upstream resolver. */ +interface PendingQuery { + resolve: (answer: Uint8Array | null) => void; +} + +export default class EcardBindVpnAbility extends VpnExtensionAbility { + private connection: vpnExtension.VpnConnection | null = null; + private tunFd: number = -1; + private serving: boolean = false; + private host: string = ''; + private answerText: string = ''; + private answer: number[] = []; + private relay: socket.UDPSocket | null = null; + private upstream: string = FALLBACK_UPSTREAM; + private reads: number = 0; + private answered: number = 0; + private forwarded: number = 0; + private lastError: string = ''; + /** Sources we have already seen asking: the interface shows no app identity. */ + private clients: Set = new Set(); + /** Queries waiting on the upstream, by their DNS transaction id. */ + private pending: Map = new Map(); + + onCreate(want: Want): void { + const request = readState(this.context.filesDir); + if (request === null || request.host.length === 0 || request.ip.length === 0) { + hilog.error(DOMAIN, TAG, 'no bind request in the state file; nothing to serve'); + return; + } + this.answer = parseIpv4(request.ip); + if (this.answer.length !== 4) { + hilog.error(DOMAIN, TAG, 'answer is not an IPv4 address: %{public}s', request.ip); + return; + } + this.host = request.host.toLowerCase(); + this.answerText = request.ip; + hilog.info(DOMAIN, TAG, 'serving %{public}s as %{public}s', this.host, this.answerText); + this.start(); + } + + onDestroy(): void { + hilog.info(DOMAIN, TAG, 'onDestroy (reads=%{public}d answered=%{public}d forwarded=%{public}d)', + this.reads, this.answered, this.forwarded); + this.teardown(); + // A verdict the app has not read yet stays in place: a start that was + // refused has nothing to tear down, and the app still has to hear why. + const state = readState(this.context.filesDir); + if (state === null || state.status === 'active' || state.status === 'requested') { + clearState(this.context.filesDir); + } + } + + private async start(): Promise { + try { + // Read the upstream resolver before the interface exists: afterwards this + // app's own lookups are answered by the tunnel. + this.upstream = await underlyingResolver(); + hilog.info(DOMAIN, TAG, 'upstream resolver is %{public}s', this.upstream); + + this.connection = vpnExtension.createVpnConnection(this.context); + const config: vpnExtension.VpnConfig = { + addresses: [ + { + address: { address: TUN_ADDRESS, family: ADDRESS_FAMILY_IPV4 }, + prefixLength: 32, + }, + ], + routes: [ + routeTo(TUN_ADDRESS), + routeTo(DNS_ADDRESS), + ], + dnsAddresses: [DNS_ADDRESS], + mtu: DEFAULT_MTU, + isIPv4Accepted: true, + // IPv6 is left on the underlying network rather than captured and then + // black-holed: only name resolution is hijacked here. + isIPv6Accepted: false, + // Every app keeps its ordinary network for everything that is not + // routed into this tunnel — which is everything but DNS. With no + // trustedApplications list the tunnel applies to all of them, which is + // also what Tailscale's HarmonyOS port relies on. + isBlocking: false, + }; + hilog.info(DOMAIN, TAG, 'creating the tunnel: %{public}s', JSON.stringify(config)); + const tunFd = await this.connection.create(config); + this.tunFd = tunFd; + hilog.info(DOMAIN, TAG, 'tunnel is up, tun fd = %{public}d', tunFd); + await this.openRelay(); + this.serving = true; + writeState(this.context.filesDir, 'active', this.host, this.answerText); + this.startReading(); + } catch (error) { + const failure = error as BusinessError; + // Without the authorization there is no interface to read; everything + // else is a configuration or platform failure. + const denied = failure.code !== 2200001 && failure.code !== 401; + const reason = JSON.stringify(error); + hilog.error(DOMAIN, TAG, 'cannot serve the bind host: %{public}s', reason); + writeState( + this.context.filesDir, + denied ? 'denied' : 'failed', + this.host, + this.answerText, + reason, + ); + this.teardown(); + } + } + + private startReading(): void { + reader.startReading( + this.tunFd, + (packet: ArrayBuffer) => { + this.onPacket(packet); + }, + (message: string) => { + this.onReadFailure(message); + }, + ); + hilog.info(DOMAIN, TAG, 'reading packets from the interface'); + } + + /** Drops the interface and stops reading from it. */ + private teardown(): void { + this.serving = false; + for (const waiting of this.pending.values()) { + waiting.resolve(null); + } + this.pending.clear(); + reader.stopReading(); + this.relay?.close(); + this.relay = null; + const connection = this.connection; + this.connection = null; + if (connection !== null) { + connection.destroy().catch((error: BusinessError) => { + hilog.warn(DOMAIN, TAG, 'destroy failed: %{public}s', JSON.stringify(error)); + }); + } + } + + private onPacket(packet: ArrayBuffer): void { + this.reads += 1; + if (this.reads === 1) { + // The first packet is the proof that the interface is readable at all. + hilog.info(DOMAIN, TAG, 'first packet off the interface'); + this.publishStats(); + } + // Each packet is answered on its own. A query that has to wait on the + // upstream must not hold up the ones behind it — the hijacked name is + // usually asked for while some unrelated name is still in flight. + this.servePacket(new Uint8Array(packet)); + } + + /** Parses one packet and injects whatever reply it is owed. */ + private async servePacket(packet: Uint8Array): Promise { + try { + const reply = await this.replyTo(packet, packet.length); + if (reply === null || !this.serving) { + return; + } + const written = reader.writePacket( + this.tunFd, + reply.buffer as ArrayBuffer, + reply.length, + ); + if (written < 0) { + hilog.warn(DOMAIN, TAG, 'cannot inject the reply: errno=%{public}d', written); + } + } catch (error) { + hilog.warn(DOMAIN, TAG, 'cannot answer a query: %{public}s', JSON.stringify(error)); + } + } + + /** The interface stopped being readable: the tunnel cannot answer anything. */ + private onReadFailure(message: string): void { + this.lastError = message; + hilog.error(DOMAIN, TAG, 'cannot read the interface: %{public}s', message); + if (!this.serving) { + return; + } + this.serving = false; + const filesDir = this.context.filesDir; + recordStats(filesDir, this.reads, this.answered, this.forwarded, message); + writeState(filesDir, 'failed', this.host, this.answerText, message); + this.teardown(); + } + + private publishStats(): void { + recordStats(this.context.filesDir, this.reads, this.answered, this.forwarded, this.lastError); + } + + private async openRelay(): Promise { + const relay = socket.constructUDPSocketInstance(); + await relay.bind({ address: '0.0.0.0', family: ADDRESS_FAMILY_IPV4, port: 0 }); + relay.on('message', (info: socket.SocketMessageInfo) => { + const answer = new Uint8Array(info.message); + if (answer.length < 2) { + return; + } + const id = queryId(answer); + const waiting = this.pending.get(id); + if (waiting === undefined) { + return; + } + this.pending.delete(id); + waiting.resolve(answer); + }); + this.relay = relay; + } + + /** The whole IPv4/UDP packet to inject, or null when nothing is owed. */ + private async replyTo(packet: Uint8Array, length: number): Promise { + const datagram: EcardBindDatagram | null = parseUdp(packet, length); + if (datagram === null || datagram.destinationPort !== DNS_PORT) { + return null; + } + if (!sameAddress(datagram.destinationAddress, parseIpv4(DNS_ADDRESS))) { + return null; + } + const payload = packet.subarray( + datagram.payloadOffset, + datagram.payloadOffset + datagram.payloadLength, + ); + const question = parseQuestion(payload, payload.length); + if (question === null) { + return null; + } + const id = queryId(payload); + const client = describeSource(datagram); + const isNewClient = !this.clients.has(client); + if (isNewClient) { + this.clients.add(client); + hilog.info(DOMAIN, TAG, 'new client %{public}s asks %{public}s/%{public}d', + client, question.name, question.type); + } + + let dnsReply: Uint8Array; + if (question.name.toLowerCase() === this.host) { + // The A record points at the mirror; every other type for this host + // answers empty, so clients fall back to that A record. + const address = question.type === TYPE_A ? this.answer : null; + this.answered += 1; + // The A answers are the ones that matter and the empty ones repeat with + // every connection, so only the first of those is worth a line. + if (address !== null || isNewClient) { + hilog.info(DOMAIN, TAG, 'hijack %{public}s/%{public}d %{public}s -> %{public}s', + question.name, question.type, client, address === null ? 'empty' : this.answerText); + } + dnsReply = buildReply(id, payload, question, address); + } else { + dnsReply = await this.forward(payload, id, question, client); + } + if (this.answered % 32 === 0 || this.forwarded % 32 === 0) { + this.publishStats(); + } + + const reply = buildUdpReply(datagram, dnsReply); + if (reply.length <= MAX_REPLY_PACKET) { + return reply; + } + // Bigger than one interface write: hand back an empty truncated answer so + // the resolver retries this over TCP, which leaves through the underlying + // network instead of this tunnel. + hilog.warn(DOMAIN, TAG, 'reply for %{public}s is too big; asking for TCP', question.name); + return buildUdpReply(datagram, buildReply(id, payload, question, null, 0, true)); + } + + /** The upstream answer for a query the tunnel does not answer itself. */ + private async forward( + payload: Uint8Array, + id: number, + question: EcardBindQuestion, + client: string, + ): Promise { + const relay = this.relay; + if (relay === null || this.pending.size >= MAX_PENDING_QUERIES) { + return buildReply(id, payload, question, null, RCODE_SERVFAIL); + } + this.forwarded += 1; + const answered = new Promise((resolve: (answer: Uint8Array | null) => void) => { + this.pending.set(id, { resolve: resolve }); + }); + try { + await relay.send({ + // Exactly the DNS message: `payload` is a view into the packet that came + // off the interface, so its `buffer` is that whole IP packet — headers, + // padding and all. + data: payload.slice().buffer as ArrayBuffer, + address: { + address: this.upstream, + family: ADDRESS_FAMILY_IPV4, + port: DNS_PORT, + }, + }); + const answer = await settledWithin(answered, UPSTREAM_TIMEOUT_MS); + if (answer !== null) { + return answer; + } + hilog.warn(DOMAIN, TAG, 'upstream %{public}s timed out for %{public}s (asked by %{public}s)', + this.upstream, question.name, client); + } catch (error) { + hilog.warn(DOMAIN, TAG, 'upstream %{public}s failed for %{public}s (asked by %{public}s): %{public}s', + this.upstream, question.name, client, JSON.stringify(error)); + } finally { + this.pending.delete(id); + } + // No answer in time: the client is better off retrying than waiting. + return buildReply(id, payload, question, null, RCODE_SERVFAIL); + } +} + +/** A route that sends one address into this interface. */ +function routeTo(address: string): connection.RouteInfo { + return { + interface: '', + destination: { + address: { address: address, family: ADDRESS_FAMILY_IPV4 }, + prefixLength: 32, + }, + gateway: { address: '0.0.0.0', family: ADDRESS_FAMILY_IPV4 }, + hasGateway: false, + isDefaultRoute: false, + }; +} + +/** The resolver of the network underneath, or a public one if unreadable. */ +async function underlyingResolver(): Promise { + try { + const net = await connection.getDefaultNet(); + const properties = await connection.getConnectionProperties(net); + for (const server of properties.dnses) { + if (server.family !== ADDRESS_FAMILY_IPV4) { + continue; + } + if (server.address === TUN_ADDRESS || server.address === DNS_ADDRESS) { + continue; + } + return server.address; + } + } catch (error) { + hilog.warn(DOMAIN, TAG, 'cannot read the underlying resolver: %{public}s', + JSON.stringify(error)); + } + return FALLBACK_UPSTREAM; +} + +/** A dotted quad as four bytes, or an empty array when it is not one. */ +function parseIpv4(text: string): number[] { + const parts = text.split('.'); + if (parts.length !== 4) { + return []; + } + const bytes: number[] = []; + for (const part of parts) { + const value = Number.parseInt(part, 10); + if (Number.isNaN(value) || value < 0 || value > 255) { + return []; + } + bytes.push(value); + } + return bytes; +} + +/** "a.b.c.d:port" — the interface does not say which app a packet came from. */ +function describeSource(datagram: EcardBindDatagram): string { + const address = datagram.sourceAddress; + return `${address[0]}.${address[1]}.${address[2]}.${address[3]}:${datagram.sourcePort}`; +} + +function sameAddress(left: number[], right: number[]): boolean { + if (left.length !== right.length) { + return false; + } + for (let index = 0; index < left.length; index++) { + if (left[index] !== right[index]) { + return false; + } + } + return true; +} + +/** `pending`, or null when it has not settled within `ms`. */ +function settledWithin( + pending: Promise, + ms: number, +): Promise { + return new Promise((resolve: (answer: Uint8Array | null) => void) => { + let done = false; + const timer = setTimeout(() => { + if (!done) { + done = true; + resolve(null); + } + }, ms); + pending.then((answer: Uint8Array | null) => { + if (!done) { + done = true; + clearTimeout(timer); + resolve(answer); + } + }); + }); +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/ecardshortcut/EcardShortcutPlugin.ets b/harmonyos_watch/ohos/entry/src/main/ets/ecardshortcut/EcardShortcutPlugin.ets new file mode 100644 index 00000000..2876fac1 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/ecardshortcut/EcardShortcutPlugin.ets @@ -0,0 +1,75 @@ +import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos'; +import MethodChannel, { MethodCallHandler, MethodResult } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; +import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; +import Want from '@ohos.app.ability.Want'; + +const CHANNEL = 'techpie/ecard_deep_link'; +// The static shortcut marks itself in the launch Want's parameters; the value is +// the only thing this plugin trusts, never the shortcut's icon or label. +const TARGET_KEY = 'techpie_ecard_target'; +const TARGET_PAY = 'pay'; + +/** + * Routes a long-press shortcut (or any Want carrying the pay-code marker) to the + * payment page, mirroring Android's EcardWidgetBridge on the same channel. + * + * This is the OHOS 快捷方式 (App Shortcut) counterpart — the equivalent of the + * home-screen widget here is a 服务卡片 (Form), not this. Cold start: the + * EntryAbility captures the Want before the Dart entrypoint runs and stashes + * `pendingRoute`; Flutter's EcardWidgetService consumes it during initialize(). + * Warm start: onNewWant invokes `openPayCode` directly. + */ +export class EcardShortcutPlugin implements FlutterPlugin, MethodCallHandler { + private methods: MethodChannel | null = null; + private pendingRoute: string | null = null; + + getUniqueClassName(): string { + return 'EcardShortcutPlugin'; + } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.methods = new MethodChannel(binding.getBinaryMessenger(), CHANNEL); + this.methods.setMethodCallHandler(this); + } + + onDetachedFromEngine(_binding: FlutterPluginBinding): void { + this.methods?.setMethodCallHandler(null); + this.methods = null; + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + if (call.method === 'consumePendingRoute') { + result.success(this.pendingRoute); + } else if (call.method === 'acknowledgePendingRoute') { + this.pendingRoute = null; + result.success(null); + } else if (call.method === 'widgetAvailability') { + // OHOS has no home-screen widget pinning on this channel; the shortcut is + // the pay-code entry here. Unsupported hides the "add widget" affordance. + result.success('unsupported'); + } else if (call.method === 'requestPinWidget') { + result.success(false); + } else { + result.notImplemented(); + } + } + + capture(want: Want, notifyFlutter: boolean): void { + if (this.readTarget(want) !== TARGET_PAY) { + return; + } + this.pendingRoute = TARGET_PAY; + if (notifyFlutter) { + this.methods?.invokeMethod('openPayCode', null); + } + } + + private readTarget(want: Want): string { + const params = want.parameters; + if (params == null) { + return ''; + } + const value: Object | undefined = params[TARGET_KEY]; + return typeof value === 'string' ? value as string : ''; + } +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/entryability/EntryAbility.ets b/harmonyos_watch/ohos/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 00000000..211da3ab --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,35 @@ +import { FlutterAbility, FlutterEngine } from '@ohos/flutter_ohos'; +import { CampusCardPlatformPlugin } from '../campuscard/CampusCardPlatformPlugin'; +import { EcardBindPlugin } from '../ecardbind/EcardBindPlugin'; +import { EcardShortcutPlugin } from '../ecardshortcut/EcardShortcutPlugin'; +import SystemFeedbackPlugin from '../platform/SystemFeedbackPlugin'; +import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant'; +import Want from '@ohos.app.ability.Want'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + +export default class EntryAbility extends FlutterAbility { + private ecardShortcuts: EcardShortcutPlugin | null = null; + + configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + GeneratedPluginRegistrant.registerWith(flutterEngine) + flutterEngine.getPlugins()?.add(new CampusCardPlatformPlugin()) + flutterEngine.getPlugins()?.add(new EcardBindPlugin()) + flutterEngine.getPlugins()?.add(new SystemFeedbackPlugin()) + this.ecardShortcuts = new EcardShortcutPlugin() + flutterEngine.getPlugins()?.add(this.ecardShortcuts) + } + + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + // Cold start: stash the shortcut marker before the Dart entrypoint runs, so + // EcardWidgetService.initialize() can consume it via consumePendingRoute. + super.onCreate(want, launchParam) + this.ecardShortcuts?.capture(want, false) + } + + onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { + // Warm start: the app is already running, so push the target to Dart. + super.onNewWant(want, launchParam) + this.ecardShortcuts?.capture(want, true) + } +} diff --git a/harmonyos_watch/ohos/entry/src/main/ets/pages/Index.ets b/harmonyos_watch/ohos/entry/src/main/ets/pages/Index.ets new file mode 100644 index 00000000..7bb6543f --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,24 @@ + +import common from '@ohos.app.ability.common'; +import { FlutterPage } from '@ohos/flutter_ohos' + +let storage = LocalStorage.getShared() +const EVENT_BACK_PRESS = 'EVENT_BACK_PRESS' + +@Entry(storage) +@Component +struct Index { + private context = getContext(this) as common.UIAbilityContext + @LocalStorageLink('viewId') viewId: string = ""; + + build() { + Column() { + FlutterPage({ viewId: this.viewId }) + } + } + + onBackPress(): boolean { + this.context.eventHub.emit(EVENT_BACK_PRESS) + return true + } +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/main/ets/platform/SystemFeedbackPlugin.ets b/harmonyos_watch/ohos/entry/src/main/ets/platform/SystemFeedbackPlugin.ets new file mode 100644 index 00000000..3352106b --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/ets/platform/SystemFeedbackPlugin.ets @@ -0,0 +1,735 @@ +import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos'; +import MethodChannel, { MethodCallHandler, MethodResult } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; +import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; +import vibrator from '@ohos.vibrator'; +import deviceInfo from '@ohos.deviceInfo'; +import fs from '@ohos.file.fs'; +import media from '@ohos.multimedia.media'; +import audioHaptic from '@ohos.multimedia.audioHaptic'; +import resourceManager from '@ohos.resourceManager'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { Context } from '@kit.AbilityKit'; + +/** A vibration that waits for its sound to start before it plays. */ +interface PendingVibration { + id: string; + pulses: FeedbackPulse[]; +} + +/** One vibration pulse, as the Dart side sends it (lib/utils/haptics.dart). */ +interface FeedbackPulse { + atMs: number; + durationMs: number; + intensity: number; +} + +/** The haptic configuration file's shape, as the vibrator guideline defines it. */ +interface HapticParameters { + Intensity: number; + Frequency: number; +} + +interface HapticEvent { + Type: string; + StartTime: number; + Duration?: number; + Parameters: HapticParameters; +} + +interface HapticPattern { + Event: HapticEvent; +} + +interface HapticChannel { + Parameters: HapticChannelIndex; + Pattern: HapticPattern[]; +} + +interface HapticChannelIndex { + Index: number; +} + +interface HapticMetaData { + Version: number; + ChannelNumber: number; + Description?: string; +} + +interface HapticDocument { + MetaData: HapticMetaData; + Channels: HapticChannel[]; +} + +/** + * Plays the app's waveforms on HarmonyOS NEXT. + * + * The engine's own HapticFeedback answers every type with one fixed vibration — + * 100 ms for a selection click, 150 ms for a medium impact, both at full + * strength — so a light tap and a held button feel the same, and both feel like + * a long buzz. This plugin takes the waveform instead and plays it through the + * three forms the vibrator guideline actually defines: + * + * - `time`: a fixed duration at the device's own strength. This is what the + * ticks use, and the shortest we send is 20 ms: the waveform set is built + * from 5-20 ms pulses, and 5 ms played nothing at all on the phone we tested. + * - `file`: a haptic configuration file — the guideline's custom-vibration + * form, available since API 10 — written from the pulses the Dart side sent, + * so per-pulse intensity and timing survive. The two designed patterns + * (`paymentSuccess`, `networkDisconnected`) use this, because they are the + * waveforms whose strength carries meaning. + * - `preset`: system effects (`haptic.clock.timer`, `haptic.notice.*`). Not + * used: their character is the system's, not the one we designed, and a + * device test is cheaper than guessing which ids exist on which phones. + * + * A device that will not take the file form is caught, replayed through `time` + * in the same call, and remembered — a rejected form costs a call, never the + * feedback. The motor-pattern builder (`VibratorPatternBuilder`) is deliberately + * absent: the guideline does not use it for this, and on the hardware we can + * test it played nothing at all. + * + * Sound: the engine's `playSystemSound` is an empty implementation, so the two + * designed patterns play their asset through AVPlayer instead, from the copy the + * build puts in the module's rawfile (`flutter_assets/`). A sound that + * will not play is logged and dropped: it never takes the vibration with it. + */ +export default class SystemFeedbackPlugin implements FlutterPlugin, MethodCallHandler { + /** + * The shortest pulse this platform will actually play. Asking for 5 ms on a + * phone here produced nothing at all; the shortest that was felt was around + * 20 ms, so that is the floor we send. + */ + private static readonly MIN_PULSE_MS = 20; + private static readonly MAX_PULSE_MS = 60; + /** + * A pulse at or below this reads as a tick, and the guideline's `transient` + * event is exactly that: a single short hit. Longer pulses are `continuous`, + * which is the only form that takes a duration. + */ + private static readonly TRANSIENT_MS = 24; + /** Intensity and Frequency are both a percentage, 0-100. */ + private static readonly MAX_PERCENT = 100; + /** `VibratorPatternBuilder` and its events arrive with API 18. */ + private static readonly PATTERN_API = 18; + /** 55 is where a motor with frequency control reaches resonance. */ + private static readonly RESONANT_FREQUENCY = 55; + /** Capability not supported: stop asking this device for vibrations. */ + private static readonly ERROR_UNSUPPORTED = 801; + /** How long a vibration waits for its sound before playing anyway. */ + private static readonly SOUND_START_WAIT_MS = 120; + + /** + * The waveforms whose strength carries meaning — a card payment landing, and + * the app noticing it went offline. The light ticks are deliberately not here: + * their feel comes from the duration, and `time` already plays that exactly. + */ + private static readonly DESIGNED_PATTERNS: string[] = [ + 'paymentSuccess', + 'networkDisconnected', + ]; + + private channel: MethodChannel | null = null; + private context: Context | null = null; + private timers: number[] = []; + private unsupported: boolean = false; + private fileUnusable: boolean = false; + private patternUnusable: boolean = false; + private described: boolean = false; + private readonly files: Map = new Map(); + private readonly sounds: Map = new Map(); + private soundPlayer: media.AVPlayer | null = null; + private soundPath: string = ''; + private soundWatchdog: number = -1; + /** Bumped whenever a sound is stopped or replaced, so a late player cannot + * stop the sound that replaced it. */ + private soundGeneration: number = 0; + /** + * A vibration waiting for its sound to start. The two are meant to land + * together: the sound assets begin with a few milliseconds of silence, and the + * player needs to create, prepare and start before any of it is audible, so a + * vibration fired immediately would lead by tens of milliseconds. It fires + * when the player reaches 'playing', and at the latest after the wait below. + */ + private pendingVibration: PendingVibration | null = null; + /** Player from the audio-haptic manager, and the source it was made from. */ + private togetherPlayer: audioHaptic.AudioHapticPlayer | null = null; + private togetherSource: number = -1; + private vibrationFallback: number = -1; + + getUniqueClassName(): string { + return 'SystemFeedbackPlugin'; + } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.channel = new MethodChannel(binding.getBinaryMessenger(), 'techpie/feedback'); + this.channel.setMethodCallHandler(this); + this.context = binding.getApplicationContext(); + } + + onDetachedFromEngine(_binding: FlutterPluginBinding): void { + this.cancel(); + this.channel?.setMethodCallHandler(null); + this.channel = null; + this.context = null; + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + if (call.method !== 'play') { + result.notImplemented(); + return; + } + this.cancel(); + const vibration = call.argument('vibration') === true; + const rawId: Object | null = call.argument('id'); + const id: string = typeof rawId === 'string' ? rawId as string : ''; + const pulses = this.parsePulses(call.argument('pulses')); + this.describeDevice(); + const wantsVibration = vibration && !this.unsupported && pulses.length > 0; + if (call.argument('sound') === true) { + const rawAsset: Object | null = call.argument('soundAsset'); + const asset: string = typeof rawAsset === 'string' ? rawAsset as string : ''; + const durationMs = this.toNumber(call.argument('soundDurationMs')); + // The system pairs an audio file with a haptic file and plays them + // together (AudioHaptic), which is the alignment this used to do by hand: + // the vibration waits for the sound's first audible sample there, and the + // manual path below stays as the fallback for a device or form it refuses. + this.playTogether(id, asset, pulses, wantsVibration, durationMs); + } else if (wantsVibration) { + this.startVibration(id, pulses); + } + result.success(null); + } + + private parsePulses(raw: Object | null): FeedbackPulse[] { + const pulses: FeedbackPulse[] = []; + if (raw === null || raw === undefined) { + return pulses; + } + try { + for (const entry of raw as Object[]) { + const pulse = entry as Map; + const intensity = this.toNumber(pulse.get('intensity')); + pulses.push({ + atMs: Math.max(0, Math.round(this.toNumber(pulse.get('atMs')))), + durationMs: Math.round(this.toNumber(pulse.get('durationMs'))), + intensity: Math.min(Math.max(intensity, 0), 1), + }); + } + } catch (error) { + console.error(`SystemFeedback: could not read the waveform (${error})`); + } + return pulses; + } + + private toNumber(value: Object | undefined): number { + return typeof value === 'number' ? value as number : 0; + } + + private isDesigned(id: string): boolean { + return SystemFeedbackPlugin.DESIGNED_PATTERNS.indexOf(id) >= 0; + } + + /** + * The haptic configuration file for a waveform, written once per id into the + * app's cache directory. An empty string means it could not be written, and + * the caller falls back to `time`. + */ + private hapticFile(id: string, pulses: FeedbackPulse[]): string { + if (this.fileUnusable) { + return ''; + } + const cached = this.files.get(id); + if (cached !== undefined) { + return cached; + } + const cacheDir = this.context?.cacheDir; + if (cacheDir === undefined || cacheDir.length === 0) { + return ''; + } + try { + const document = this.hapticDocument(id, pulses); + const json = JSON.stringify(document); + // Keyed by content, not only by name: a waveform we tune later must not + // keep playing the file an older build wrote. + const path = `${cacheDir}/techpie-haptics-${id}-${SystemFeedbackPlugin.fingerprint(json)}.json`; + const previous = this.files.get(id); + if (previous !== undefined && previous !== path) { + this.remove(previous); + } + this.files.set(id, path); + if (!fs.accessSync(path)) { + const file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC); + fs.writeSync(file.fd, json); + fs.closeSync(file); + } + return path; + } catch (error) { + console.error(`SystemFeedback: could not write the haptic file for ${id} (${error})`); + this.fileUnusable = true; + return ''; + } + } + + /** A short, stable name for one configuration, so a changed one is a new file. */ + private static fingerprint(text: string): string { + let hash = 2166136261; + for (let index = 0; index < text.length; index++) { + hash = ((hash ^ text.charCodeAt(index)) * 16777619) & 0xFFFFFFFF; + } + return hash.toString(16); + } + + private remove(path: string): void { + try { + if (fs.accessSync(path)) { + fs.unlinkSync(path); + } + } catch (error) { + console.debug(`SystemFeedback: could not remove ${path}`); + } + } + + private hapticDocument(id: string, pulses: FeedbackPulse[]): HapticDocument { + const pattern: HapticPattern[] = []; + for (const pulse of pulses) { + const duration = this.clampDuration(pulse.durationMs); + const parameters: HapticParameters = { + Intensity: Math.max(1, Math.round(pulse.intensity * SystemFeedbackPlugin.MAX_PERCENT)), + Frequency: SystemFeedbackPlugin.RESONANT_FREQUENCY, + }; + if (duration <= SystemFeedbackPlugin.TRANSIENT_MS) { + pattern.push({ Event: { Type: 'transient', StartTime: pulse.atMs, Parameters: parameters } }); + } else { + pattern.push({ + Event: { Type: 'continuous', StartTime: pulse.atMs, Duration: duration, Parameters: parameters }, + }); + } + } + const channel: HapticChannel = { Parameters: { Index: 0 }, Pattern: pattern }; + return { + MetaData: { Version: 1.0, ChannelNumber: 1, Description: `techpie ${id}` }, + Channels: [channel], + }; + } + + private playFile(path: string, pulses: FeedbackPulse[]): void { + try { + const file = fs.openSync(path, fs.OpenMode.READ_ONLY); + const length = fs.statSync(path).size; + vibrator.startVibration( + { type: 'file', hapticFd: { fd: file.fd, offset: 0, length: length } }, + { id: 0, usage: 'touch' }, + ) + .then(() => { fs.closeSync(file); }) + .catch((error: BusinessError) => { + // A file this device will not take must not become silence: the same + // pulses are replayed on the other forms before giving up. + this.failed('file', error); + this.fileUnusable = true; + fs.closeSync(file); + this.playAfterFile(pulses); + }); + } catch (error) { + this.failed('file', error as BusinessError); + this.fileUnusable = true; + this.playAfterFile(pulses); + } + } + + /** What to do when the file form is not available here. */ + private playAfterFile(pulses: FeedbackPulse[]): void { + if (deviceInfo.sdkApiVersion >= SystemFeedbackPlugin.PATTERN_API && + !this.patternUnusable) { + console.info('SystemFeedback: falling back to the pattern form'); + this.playPattern(pulses); + return; + } + this.playScheduled(pulses); + } + + /** + * The programming form of the same idea (the guideline's own sample): the + * builder arrives with API 18. Its transient parameter wants the strength as a + * percentage — 0-100, the same scale the configuration file uses — plus a + * frequency and the channel index, and the attribute names the device. + */ + private playPattern(pulses: FeedbackPulse[]): void { + try { + const builder = new vibrator.VibratorPatternBuilder(); + for (const pulse of pulses) { + const duration = this.clampDuration(pulse.durationMs); + const intensity = Math.max(1, Math.round(pulse.intensity * SystemFeedbackPlugin.MAX_PERCENT)); + if (duration <= SystemFeedbackPlugin.TRANSIENT_MS) { + builder.addTransientEvent(pulse.atMs, { + intensity: intensity, + frequency: SystemFeedbackPlugin.RESONANT_FREQUENCY, + index: 0, + }); + } else { + builder.addContinuousEvent(pulse.atMs, duration, { + intensity: intensity, + frequency: SystemFeedbackPlugin.RESONANT_FREQUENCY, + index: 0, + }); + } + } + vibrator.startVibration( + { type: 'pattern', pattern: builder.build() }, + { id: 0, deviceId: -1, usage: 'touch' }, + ) + .catch((error: BusinessError) => { + this.failed('pattern', error); + this.patternUnusable = true; + this.playScheduled(pulses); + }); + } catch (error) { + this.failed('pattern', error as BusinessError); + this.patternUnusable = true; + this.playScheduled(pulses); + } + } + + /** One short vibration per pulse, scheduled on our own clock. */ + private playScheduled(pulses: FeedbackPulse[]): void { + for (const pulse of pulses) { + const duration = this.clampDuration(pulse.durationMs); + if (pulse.atMs === 0) { + this.buzz(duration); + } else { + this.timers.push(setTimeout(() => { this.buzz(duration); }, pulse.atMs)); + } + } + } + + private buzz(duration: number): void { + vibrator.startVibration({ type: 'time', duration: duration }, { id: 0, usage: 'touch' }) + .catch((error: BusinessError) => { this.failed('time', error); }); + } + + private clampDuration(durationMs: number): number { + if (durationMs < SystemFeedbackPlugin.MIN_PULSE_MS) { + return SystemFeedbackPlugin.MIN_PULSE_MS; + } + if (durationMs > SystemFeedbackPlugin.MAX_PULSE_MS) { + return SystemFeedbackPlugin.MAX_PULSE_MS; + } + return durationMs; + } + + /** What this phone can do, once, in the log a device test can be read from. */ + private describeDevice(): void { + if (this.described) { + return; + } + this.described = true; + console.info(`SystemFeedback: api=${deviceInfo.sdkApiVersion} ` + + `designed=${SystemFeedbackPlugin.DESIGNED_PATTERNS.join('|')} file=${!this.fileUnusable}`); + } + + private failed(kind: string, error: BusinessError): void { + if (error !== undefined && error.code === SystemFeedbackPlugin.ERROR_UNSUPPORTED) { + // Capability not supported: this device has no vibrator we can drive. + this.unsupported = true; + console.warn(`SystemFeedback: vibration is unsupported here (${kind})`); + return; + } + console.error(`SystemFeedback: ${kind} vibration failed ` + + `(${error === undefined ? 'unknown' : error.code})`); + } + + /** Fires the vibration that was waiting for a sound, once, if there is one. */ + private vibratePending(): void { + if (this.vibrationFallback !== -1) { + clearTimeout(this.vibrationFallback); + this.vibrationFallback = -1; + } + const pending = this.pendingVibration; + this.pendingVibration = null; + if (pending !== null) { + this.startVibration(pending.id, pending.pulses); + } + } + + private startVibration(id: string, pulses: FeedbackPulse[]): void { + if (this.isDesigned(id)) { + const file = this.hapticFile(id, pulses); + if (file.length > 0) { + console.info(`SystemFeedback: playing ${id} via file (${pulses.length} pulse(s))`); + this.playFile(file, pulses); + return; + } + } + console.info(`SystemFeedback: playing ${id} via time (${pulses.length} pulse(s))`); + this.playScheduled(pulses); + } + + /** + * Plays a sound and its waveform as one thing through the audio-haptic manager: + * `registerSource` pairs the two files and the system plays them together, so + * there is no timing to get wrong here. Registered per play and unregistered + * when the player is released, which keeps the 128-source limit far away. + * + * Anything it refuses falls back to the manual pair (AVPlayer + the vibration + * path), which is what shipped before this and is confirmed working on + * hardware: a sound may lose its system alignment, never its playback. + */ + private playTogether( + id: string, + asset: string, + pulses: FeedbackPulse[], + vibration: boolean, + durationMs: number, + ): void { + const haptic = this.isDesigned(id) ? this.hapticFile(id, pulses) : ''; + const audio = this.soundFile(asset); + if (haptic.length === 0 || audio.length === 0) { + this.playSound(id, asset, pulses, vibration, durationMs); + return; + } + const manager = audioHaptic.getAudioHapticManager(); + let source = -1; + manager.registerSource(audio, haptic) + .then((registered: number) => { + source = registered; + if (registered < 0) { + throw new Error('audio-haptic source limit reached'); + } + try { + // A feedback sound wants the low-latency path. + manager.setAudioLatencyMode(registered, + audioHaptic.AudioLatencyMode.AUDIO_LATENCY_MODE_FAST); + } catch (error) { + console.debug('SystemFeedback: latency mode was refused'); + } + return manager.createPlayer(registered, { muteHaptics: !vibration }); + }) + .then((player: audioHaptic.AudioHapticPlayer) => { + this.stopTogether(); + this.togetherPlayer = player; + this.togetherSource = source; + console.info(`SystemFeedback: playing ${id} as audio+haptic (source ${source})`); + player.start().catch((error: BusinessError) => { + this.togetherFailed(id, asset, pulses, vibration, durationMs, error); + }); + const window = durationMs > 0 ? durationMs : 1000; + this.soundWatchdog = setTimeout(() => { this.stopTogether(); }, window + 300); + }) + .catch((error: BusinessError) => { + this.togetherFailed(id, asset, pulses, vibration, durationMs, error); + }); + } + + private togetherFailed( + id: string, + asset: string, + pulses: FeedbackPulse[], + vibration: boolean, + durationMs: number, + error: BusinessError, + ): void { + console.error(`SystemFeedback: audio+haptic failed ` + + `(${error === undefined ? 'unknown' : error.code}); falling back`); + this.stopTogether(); + this.playSound(id, asset, pulses, vibration, durationMs); + } + + private stopTogether(): void { + if (this.soundWatchdog !== -1) { + clearTimeout(this.soundWatchdog); + this.soundWatchdog = -1; + } + const player = this.togetherPlayer; + this.togetherPlayer = null; + if (player !== null) { + player.release().catch((error: BusinessError) => { + console.debug(`SystemFeedback: together release returned ${error.code}`); + }); + } + const source = this.togetherSource; + this.togetherSource = -1; + if (source >= 0) { + audioHaptic.getAudioHapticManager().unregisterSource(source) + .catch((error: BusinessError) => { + console.debug(`SystemFeedback: unregister returned ${error.code}`); + }); + } + } + + /** The asset, copied once into the cache so both players can read a real path. */ + private soundFile(asset: string): string { + const cached = this.sounds.get(asset); + if (cached !== undefined) { + return cached; + } + const resources = this.context?.resourceManager; + const cacheDir = this.context?.cacheDir; + if (resources === undefined || cacheDir === undefined || cacheDir.length === 0) { + return ''; + } + const path = `${cacheDir}/techpie-sound-${asset.split('/').pop() ?? 'sound.wav'}`; + try { + if (!fs.accessSync(path)) { + const raw = resources.getRawFdSync(`flutter_assets/${asset}`); + const buffer = new ArrayBuffer(raw.length); + const read = fs.readSync(raw.fd, buffer, { offset: raw.offset, length: raw.length }); + const file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC); + fs.writeSync(file.fd, buffer, { length: read }); + fs.closeSync(file); + resources.closeRawFdSync(`flutter_assets/${asset}`); + } + this.sounds.set(asset, path); + return path; + } catch (error) { + console.error(`SystemFeedback: could not stage the sound ${asset} (${error})`); + return ''; + } + } + + /** + * The manual pair: the sound through AVPlayer, and the vibration held until + * the player reports that it is actually playing (or SOUND_START_WAIT_MS has + * passed, so a slow or failing sound can never swallow it). + * + * Plays one of the app's sound assets through AVPlayer, from the copy the + * build leaves in the module's rawfile (`flutter_assets/` — the hap + * carries it, verified). + * + * Fire and forget: a sound that fails is logged and dropped. It is never + * surfaced to the caller and never takes the vibration with it, and the file + * descriptor is closed when the player is released rather than right after the + * call, so playback cannot read a closed file. + */ + private playSound( + id: string, + asset: string, + pulses: FeedbackPulse[], + vibration: boolean, + durationMs: number, + ): void { + const resources = this.context?.resourceManager; + if (resources === undefined || asset.length === 0) { + return; + } + if (vibration) { + // The vibration waits for the sound's first audible sample: it is fired + // when the player reaches 'playing', and at the latest after + // SOUND_START_WAIT_MS so a slow or failing sound can never swallow it. + this.pendingVibration = { id: id, pulses: pulses }; + this.vibrationFallback = setTimeout(() => { this.vibratePending(); }, + SystemFeedbackPlugin.SOUND_START_WAIT_MS); + } + const path = `flutter_assets/${asset}`; + let descriptor: resourceManager.RawFileDescriptor; + try { + descriptor = resources.getRawFdSync(path); + } catch (error) { + console.error(`SystemFeedback: no sound asset at ${path} (${error})`); + return; + } + this.soundPath = path; + const generation = ++this.soundGeneration; + media.createAVPlayer() + .then((player: media.AVPlayer) => { + if (generation !== this.soundGeneration) { + // Superseded while the player was being created. + player.release().catch((error: BusinessError) => { + console.debug(`SystemFeedback: early release returned ${error.code}`); + }); + return; + } + this.soundPlayer = player; + player.on('stateChange', (state: string) => { + if (generation !== this.soundGeneration) { + return; + } + console.info(`SystemFeedback: sound state=${state}`); + if (state === 'initialized') { + // AVPlayer will not play straight from 'initialized': prepare first + // and play once it is 'prepared' (playing early is 5400102, + // "operation not allowed", which is what this used to do). + player.prepare().catch((error: BusinessError) => { + if (generation === this.soundGeneration) { + this.soundFailed(error); + } + }); + } else if (state === 'playing') { + // The first sample is audible now: this is what the vibration was + // waiting for. + this.vibratePending(); + } else if (state === 'prepared') { + console.info(`SystemFeedback: playing sound ${asset}`); + player.play().catch((error: BusinessError) => { + if (generation === this.soundGeneration) { + this.soundFailed(error); + } + }); + } else if (state === 'completed' || state === 'error') { + this.stopSound(); + } + }); + player.fdSrc = { fd: descriptor.fd, offset: descriptor.offset, length: descriptor.length }; + // Some devices never report completion; the declared window is the + // authority, with a little room for the tail. + const window = durationMs > 0 ? durationMs : 1000; + this.soundWatchdog = setTimeout(() => { + if (generation === this.soundGeneration) { + this.stopSound(); + } + }, window + 250); + }) + .catch((error: BusinessError) => { + if (generation === this.soundGeneration) { + this.soundFailed(error); + } + }); + } + + private soundFailed(error: BusinessError): void { + console.error(`SystemFeedback: sound failed ` + + `(${error === undefined ? 'unknown' : error.code})`); + // A sound that will not play must not take the vibration with it. + this.vibratePending(); + this.stopSound(); + } + + private stopSound(): void { + this.soundGeneration++; + if (this.soundWatchdog !== -1) { + clearTimeout(this.soundWatchdog); + this.soundWatchdog = -1; + } + const player = this.soundPlayer; + this.soundPlayer = null; + if (player !== null) { + player.release().catch((error: BusinessError) => { + console.debug(`SystemFeedback: player release returned ${error.code}`); + }); + } + const path = this.soundPath; + this.soundPath = ''; + if (path.length > 0) { + try { + this.context?.resourceManager.closeRawFdSync(path); + } catch (error) { + // Already closed, or closed by the platform: nothing to do about it. + } + } + } + + private cancel(): void { + if (this.vibrationFallback !== -1) { + clearTimeout(this.vibrationFallback); + this.vibrationFallback = -1; + } + this.pendingVibration = null; + this.stopTogether(); + this.stopSound(); + for (const timer of this.timers) { + clearTimeout(timer); + } + this.timers = []; + vibrator.stopVibration().catch((error: BusinessError) => { + // Nothing playing is not a failure. + console.debug(`SystemFeedback: stop returned ${error.code}`); + }); + } +} diff --git a/harmonyos_watch/ohos/entry/src/main/module.json5 b/harmonyos_watch/ohos/entry/src/main/module.json5 new file mode 100644 index 00000000..3a6f985a --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/module.json5 @@ -0,0 +1,70 @@ + +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "backgroundModes": [ + "dataTransfer" + ], + "metadata": [ + { + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + } + ], + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EcardBindVpnAbility", + "srcEntry": "./ets/ecardbind/EcardBindVpnAbility.ets", + "type": "vpn", + "exported": false + } + ], + "requestPermissions": [ + {"name" : "ohos.permission.INTERNET"}, + {"name": "ohos.permission.GET_NETWORK_INFO"}, + {"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"}, + {"name": "ohos.permission.VIBRATE"}, + { + "name": "ohos.permission.CAMERA", + "reason": "$string:camera_reason", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "inuse" + } + }, + ] + } +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/element/color.json b/harmonyos_watch/ohos/entry/src/main/resources/base/element/color.json new file mode 100644 index 00000000..3c712962 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/element/string.json b/harmonyos_watch/ohos/entry/src/main/resources/base/element/string.json new file mode 100644 index 00000000..64329d9e --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/base/element/string.json @@ -0,0 +1,24 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "TechPie" + }, + { + "name": "camera_reason", + "value": "Use the camera to scan check-in codes and campus-card payment codes" + }, + { + "name": "ecard_shortcut_label", + "value": "Pay Code" + } + ] +} diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/media/ic_ecard_shortcut.png b/harmonyos_watch/ohos/entry/src/main/resources/base/media/ic_ecard_shortcut.png new file mode 100644 index 00000000..4104a9cf Binary files /dev/null and b/harmonyos_watch/ohos/entry/src/main/resources/base/media/ic_ecard_shortcut.png differ diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/media/icon.png b/harmonyos_watch/ohos/entry/src/main/resources/base/media/icon.png new file mode 100644 index 00000000..d1ba46b7 Binary files /dev/null and b/harmonyos_watch/ohos/entry/src/main/resources/base/media/icon.png differ diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/profile/main_pages.json b/harmonyos_watch/ohos/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 00000000..1898d94f --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/harmonyos_watch/ohos/entry/src/main/resources/base/profile/shortcuts_config.json b/harmonyos_watch/ohos/entry/src/main/resources/base/profile/shortcuts_config.json new file mode 100644 index 00000000..9331eedf --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/base/profile/shortcuts_config.json @@ -0,0 +1,19 @@ +{ + "shortcuts": [ + { + "shortcutId": "open_pay_code", + "label": "$string:ecard_shortcut_label", + "icon": "$media:ic_ecard_shortcut", + "wants": [ + { + "bundleName": "com.geekpie.techpie", + "moduleName": "entry", + "abilityName": "EntryAbility", + "parameters": { + "techpie_ecard_target": "pay" + } + } + ] + } + ] +} diff --git a/harmonyos_watch/ohos/entry/src/main/resources/en_US/element/string.json b/harmonyos_watch/ohos/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 00000000..64329d9e --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,24 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "TechPie" + }, + { + "name": "camera_reason", + "value": "Use the camera to scan check-in codes and campus-card payment codes" + }, + { + "name": "ecard_shortcut_label", + "value": "Pay Code" + } + ] +} diff --git a/harmonyos_watch/ohos/entry/src/main/resources/rawfile/buildinfo.json5 b/harmonyos_watch/ohos/entry/src/main/resources/rawfile/buildinfo.json5 new file mode 100644 index 00000000..6125c99c --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/rawfile/buildinfo.json5 @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "enable_impeller", + "value": "true" + } + ] +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/main/resources/rawfile/framesconfig.json b/harmonyos_watch/ohos/entry/src/main/resources/rawfile/framesconfig.json new file mode 100644 index 00000000..34d41c8d --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/rawfile/framesconfig.json @@ -0,0 +1,37 @@ +{ + "SWITCH": 1, + "TRANSLATE": [ + { + "serial_number": 1, + "min": 800, + "max": -1, + "preferred_fps": 90 + }, + { + "serial_number": 2, + "min": 77, + "max": 800, + "preferred_fps": 120 + }, + { + "serial_number": 3, + "min": 46, + "max": 77, + "preferred_fps": 90 + }, + { + "serial_number": 4, + "min": 10, + "max": 46, + "preferred_fps": 72 + }, + { + "serial_number": 5, + "min": 0, + "max": 10, + "preferred_fps": 60 + } + ], + "SCALE": [], + "ROTATION": [] +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/main/resources/zh_CN/element/string.json b/harmonyos_watch/ohos/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 00000000..34edb233 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,24 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "TechPie" + }, + { + "name": "camera_reason", + "value": "使用相机扫描签到码与校园卡付款二维码" + }, + { + "name": "ecard_shortcut_label", + "value": "消费码" + } + ] +} diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/Ability.test.ets b/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 00000000..8abf7f2f --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,35 @@ +import hilog from '@ohos.hilog'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +export default function abilityTest() { + describe('ActsAbilityTest', function () { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(function () { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(function () { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(function () { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(function () { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain',0, function () { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc' + let b = 'b' + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b) + expect(a).assertEqual(a) + }) + }) +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/List.test.ets b/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 00000000..d766fe24 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,5 @@ +import abilityTest from './Ability.test' + +export default function testsuite() { + abilityTest() +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets new file mode 100644 index 00000000..e3f6e911 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets @@ -0,0 +1,48 @@ +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import hilog from '@ohos.hilog'; +import { Hypium } from '@ohos/hypium'; +import testsuite from '../test/List.test'; +import window from '@ohos.window'; + +export default class TestAbility extends UIAbility { + onCreate(want, launchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate'); + hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); + hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:'+ JSON.stringify(launchParam) ?? ''); + var abilityDelegator: any + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var abilityDelegatorArguments: any + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!'); + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + onDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate'); + windowStage.loadContent('testability/pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', + JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy'); + } + + onForeground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground'); + } + + onBackground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground'); + } +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets new file mode 100644 index 00000000..545843d3 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets @@ -0,0 +1,36 @@ + + +import hilog from '@ohos.hilog'; + +@Entry +@Component +struct Index { + aboutToAppear() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear'); + } + @State message: string = 'Hello World' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('35%') + .height('5%') + .onClick(()=>{ + }) + } + .width('100%') + } + .height('100%') + } + } \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts new file mode 100644 index 00000000..47fc89b4 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,50 @@ + +import hilog from '@ohos.hilog'; +import TestRunner from '@ohos.application.testRunner'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +async function onAbilityCreateCallback() { + hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); +} + +async function addAbilityMonitorCallback(err: any) { + hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); + } + + async onRun() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName + var debug = abilityDelegatorArguments.parameters['-D'] + if (debug == 'true') + { + cmd += ' -D' + } + hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); + }) + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); + } +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/module.json5 b/harmonyos_watch/ohos/entry/src/ohosTest/module.json5 new file mode 100644 index 00000000..3b02a75a --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/module.json5 @@ -0,0 +1,37 @@ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "description": "$string:module_test_desc", + "mainElement": "TestAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:test_pages", + "abilities": [ + { + "name": "TestAbility", + "srcEntry": "./ets/testability/TestAbility.ets", + "description": "$string:TestAbility_desc", + "icon": "$media:icon", + "label": "$string:TestAbility_label", + "exported": true, + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/color.json b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/color.json new file mode 100644 index 00000000..3c712962 --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/string.json b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/string.json new file mode 100644 index 00000000..65d8fa5a --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_test_desc", + "value": "test ability description" + }, + { + "name": "TestAbility_desc", + "value": "the test ability" + }, + { + "name": "TestAbility_label", + "value": "test label" + } + ] +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/media/icon.png b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/media/icon.png new file mode 100644 index 00000000..ce307a88 Binary files /dev/null and b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/media/icon.png differ diff --git a/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json new file mode 100644 index 00000000..b7e7343c --- /dev/null +++ b/harmonyos_watch/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "testability/pages/Index" + ] +} diff --git a/harmonyos_watch/ohos/hvigor/hvigor-config.json5 b/harmonyos_watch/ohos/hvigor/hvigor-config.json5 new file mode 100644 index 00000000..f1aa7e54 --- /dev/null +++ b/harmonyos_watch/ohos/hvigor/hvigor-config.json5 @@ -0,0 +1,6 @@ + +{ + "modelVersion": "5.0.0", + "dependencies": { + } +} diff --git a/harmonyos_watch/ohos/hvigorconfig.ts b/harmonyos_watch/ohos/hvigorconfig.ts new file mode 100644 index 00000000..fc2b2086 --- /dev/null +++ b/harmonyos_watch/ohos/hvigorconfig.ts @@ -0,0 +1,4 @@ +import path from 'path' +import { injectNativeModules } from 'flutter-hvigor-plugin'; + +injectNativeModules(__dirname, path.dirname(__dirname)) \ No newline at end of file diff --git a/harmonyos_watch/ohos/hvigorfile.ts b/harmonyos_watch/ohos/hvigorfile.ts new file mode 100644 index 00000000..f66c2170 --- /dev/null +++ b/harmonyos_watch/ohos/hvigorfile.ts @@ -0,0 +1,17 @@ +import path from 'path' +import { execFileSync } from 'child_process'; +import { appTasks } from '@ohos/hvigor-ohos-plugin'; +import { flutterHvigorPlugin } from 'flutter-hvigor-plugin'; + +// Generate build-profile.json5 from the template + OHOS_* env vars before +// hvigor parses the profile. Synchronous so the file is on disk in time. +execFileSync( + 'node', + [path.join(__dirname, 'scripts', 'generate-build-profile.mjs')], + { stdio: 'inherit' }, +); + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[flutterHvigorPlugin(path.dirname(__dirname))] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/harmonyos_watch/ohos/oh-package.json5 b/harmonyos_watch/ohos/oh-package.json5 new file mode 100644 index 00000000..68cddaed --- /dev/null +++ b/harmonyos_watch/ohos/oh-package.json5 @@ -0,0 +1,15 @@ +{ + "modelVersion": "5.0.0", + "name": "TechPie", + // hvigor module version — NOT the app version. The app version lives in + // pubspec.yaml alone; ohos/AppScope/app.json5 is generated from it. + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {}, + "devDependencies": { + "@ohos/hypium": "1.0.6" + } +} diff --git a/harmonyos_watch/ohos/scripts/build-ecardbind-reader.sh b/harmonyos_watch/ohos/scripts/build-ecardbind-reader.sh new file mode 100644 index 00000000..bd803998 --- /dev/null +++ b/harmonyos_watch/ohos/scripts/build-ecardbind-reader.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Build the prebuilt eCard bind packet reader (libecardbind_reader.so). +# +# ohos/scripts/build-ecardbind-reader.sh +# +# hvigor does not compile ohos/entry/src/main/cpp. The module ships a committed +# .so under ohos/entry/libs/arm64-v8a/ instead, so the release image needs no C++ +# toolchain — worth 4.5 GB of image and a manual republish step (CLAUDE.md -> +# OHOS-specific gotchas). Run this whenever anything under src/main/cpp changes: +# test/ecard_bind_reader_artifact_test.dart fails until the committed .so carries +# the digest of the source it was built from. +# +# The SDK is a local dependency; override CLD_DIR if it is not where .envrc says. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +CPP_DIR="$ROOT/ohos/entry/src/main/cpp" +OUT="$ROOT/ohos/entry/libs/arm64-v8a/libecardbind_reader.so" +CLD_DIR="${CLD_DIR:-$HOME/dev/command-line-tools}" +SDK="$CLD_DIR/sdk/default" +NATIVE="$SDK/openharmony/native" +HMS="$SDK/hms/native" +CMAKE="$NATIVE/build-tools/cmake/bin/cmake" +NINJA="$NATIVE/build-tools/cmake/bin/ninja" +STRIP="$NATIVE/llvm/bin/llvm-strip" + +for tool in "$CMAKE" "$NINJA" "$STRIP"; do + if [[ ! -x "$tool" ]]; then + printf 'missing %s — is CLD_DIR=%s the command-line-tools root?\n' "$tool" "$CLD_DIR" >&2 + exit 1 + fi +done + +build="$(mktemp -d "${TMPDIR:-/tmp}/ecardbind-build.XXXXXX")" +trap 'rm -rf "$build"' EXIT + +# The same variables hvigor passes for externalNativeOptions — the toolchain file +# comes from hms/native, the sysroots and clang from openharmony/native (hvigor's +# own CMakeCache.txt under ohos/entry/.cxx lists them all). +"$CMAKE" -S "$CPP_DIR" -B "$build" -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE="$HMS/build/cmake/hmos.toolchain.cmake" \ + -DCMAKE_MAKE_PROGRAM="$NINJA" \ + -DCMAKE_BUILD_TYPE=Release \ + -DOHOS_ARCH=arm64-v8a \ + -DOHOS_SDK_NATIVE="$NATIVE" \ + -DHMOS_SDK_NATIVE="$HMS" +"$CMAKE" --build "$build" + +# Stripped: this file is what the repository keeps, and the hap carries it as is. +# 644 because a shared library is data here, not something anyone runs. +"$STRIP" --strip-all "$build/libecardbind_reader.so" +mkdir -p "$(dirname "$OUT")" +cp "$build/libecardbind_reader.so" "$OUT" +chmod 644 "$OUT" +ls -l "$OUT" diff --git a/harmonyos_watch/ohos/scripts/generate-build-profile.mjs b/harmonyos_watch/ohos/scripts/generate-build-profile.mjs new file mode 100644 index 00000000..70ca6440 --- /dev/null +++ b/harmonyos_watch/ohos/scripts/generate-build-profile.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node +// Generate the OHOS manifests hvigor needs from committed templates: +// +// ohos/AppScope/app.json5 <- AppScope/app.template.json5 + pubspec.yaml version +// ohos/build-profile.json5 <- build-profile.template.json5 + OHOS_* env vars +// +// With OHOS_UNSIGNED=1 the profile is written without any signing material, so +// hvigor packs `-default-unsigned.hap` instead of a signed one. That is +// the build CI publishes (no signing secrets on the runner) and the one a +// contributor without signing material can run. +// +// hvigorfile.ts runs this on every hvigor invocation (DevEco builds included), +// and it can also be invoked directly: +// +// node ohos/scripts/generate-build-profile.mjs +// +// Both outputs are gitignored: pubspec.yaml is the single source of truth for +// the app version, .envrc (or the CI environment) for the signing material. + +import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const ohosDir = resolve(here, '..'); +const repoRoot = resolve(ohosDir, '..'); + +const templatePath = resolve(ohosDir, 'build-profile.template.json5'); +const outputPath = resolve(ohosDir, 'build-profile.json5'); + +const REQUIRED = [ + 'OHOS_CERT_PATH', + 'OHOS_STORE_PASSWORD', + 'OHOS_KEY_ALIAS', + 'OHOS_KEY_PASSWORD', + 'OHOS_PROFILE_PATH', + 'OHOS_SIGN_ALG', + 'OHOS_STORE_FILE', +]; + +/// The app version, read from pubspec.yaml. +/// +/// `flutter build hap` stamps the packed bundle from this file already, so a +/// DevEco-only build must be rendered from the same numbers or the two build +/// paths disagree. Returns the name and the numeric versionCode; the code +/// mirrors Flutter's own rule (the `+N` suffix, or 1 when absent). +function readAppVersion() { + const pubspecPath = resolve(repoRoot, 'pubspec.yaml'); + const match = /^version:\s*(\S+)\s*$/m.exec(readFileSync(pubspecPath, 'utf8')); + if (!match) { + throw new Error(`No "version:" line in ${pubspecPath}`); + } + const raw = match[1]; + const separator = raw.indexOf('+'); + const name = separator < 0 ? raw : raw.slice(0, separator); + const codeText = separator < 0 ? '' : raw.slice(separator + 1); + const code = separator < 0 ? 1 : Number(codeText); + if (!name || !Number.isInteger(code) || code <= 0) { + throw new Error(`Unusable version "${raw}" in ${pubspecPath}`); + } + if (separator < 0) { + console.warn( + `[generate-ohos-manifests] pubspec version "${raw}" carries no "+N" ` + + `build number; rendering versionCode 1. Add "+N" (e.g. "${raw}+1") ` + + `so stores and iOS get a numeric build number.`, + ); + } + return { name, code }; +} + +/// AppScope/app.json5 — bundle identity plus the version pubspec declares. +function generateAppManifest() { + const templatePath = resolve(ohosDir, 'AppScope', 'app.template.json5'); + const outputPath = resolve(ohosDir, 'AppScope', 'app.json5'); + if (!existsSync(templatePath)) { + throw new Error(`Template not found: ${templatePath}`); + } + + const { name, code } = readAppVersion(); + let content = readFileSync(templatePath, 'utf8'); + content = content + .replaceAll('__APP_VERSION_NAME__', name) + .replaceAll('__APP_VERSION_CODE__', String(code)); + if (content.includes('__APP_VERSION_')) { + throw new Error(`Unsubstituted version placeholder in ${templatePath}`); + } + writeFileSync(outputPath, content); +} + +function generateBuildProfile() { + if (!existsSync(templatePath)) { + throw new Error(`Template not found: ${templatePath}`); + } + + let content = readFileSync(templatePath, 'utf8'); + + if (process.env.OHOS_UNSIGNED === '1') { + // Drop the signing block and the product's reference to it: hvigor then has + // nothing to sign with and writes `entry-default-unsigned.hap`. + content = content + .replace(/"signingConfigs":\s*\[[\s\S]*?\r?\n \],\r?\n/, '') + .replace(/"signingConfig": "default",\r?\n/, ''); + if (content.includes('signingConfig')) { + throw new Error('Could not strip the signing block from the template'); + } + writeFileSync(outputPath, content); + return; + } + + const missing = REQUIRED.filter((k) => !process.env[k]); + if (missing.length === REQUIRED.length) { + // No signing env at all — likely a contributor without signing material. + // Leave any existing build-profile.json5 alone so DevEco's automatic signing + // (or a previously generated file) can still be used. + if (existsSync(outputPath)) return; + throw new Error( + `No OHOS_* signing env vars set and ${outputPath} does not exist. ` + + `Source .envrc (direnv) or copy .envrc.example, fill in the values, then retry.`, + ); + } + if (missing.length > 0) { + throw new Error( + `Missing required OHOS signing env vars: ${missing.join(', ')}. ` + + `See .envrc.example.`, + ); + } + + for (const key of REQUIRED) { + content = content.replaceAll(`__${key}__`, process.env[key]); + } + writeFileSync(outputPath, content); +} + +try { + // The app manifest never depends on the signing environment, so it is + // rendered first and survives a contributor without signing material. + generateAppManifest(); + generateBuildProfile(); +} catch (err) { + console.error(`[generate-ohos-manifests] ${err.message}`); + process.exit(1); +} diff --git a/harmonyos_watch/scripts/lite-profile.cjs b/harmonyos_watch/scripts/lite-profile.cjs new file mode 100644 index 00000000..9017db37 --- /dev/null +++ b/harmonyos_watch/scripts/lite-profile.cjs @@ -0,0 +1,69 @@ +const fs = require('node:fs'); + +function apiLevel(value) { + if (Number.isInteger(value) && value >= 10) return value; + const match = /\((\d+)\)$/.exec(value); + if (!match) throw new Error('Unsupported Lite API version: ' + value); + return Number(match[1]); +} + +function select(object, allowed) { + const result = {}; + for (const key of allowed) { + if (Object.prototype.hasOwnProperty.call(object, key)) result[key] = object[key]; + } + return result; +} + +// This is a COMPILED profile: resource IDs generated by restool are required +// by the Lite bundle parser, even though source configSchema_lite omits them. +// Adapt BEFORE HAP-to-BIN packaging and signing, never after signing. +function normalize(profile, compatible, target) { + if (!profile.module.deviceType.includes('liteWearable')) { + throw new Error('This adapter only accepts Lite Wearable profiles.'); + } + const app = select(profile.app, ['bundleName', 'vendor', 'version', 'smartWindowSize', 'smartWindowDeviceType']); + app.apiVersion = { compatible: apiLevel(compatible), target: apiLevel(target), releaseType: 'Release' }; + if (app.apiVersion.compatible > app.apiVersion.target) throw new Error('Invalid Lite API range.'); + const module = select(profile.module, [ + 'description', 'abilities', 'js', 'reqPermissions', 'deviceType', 'distro', + 'reqCapabilities', 'metaData', 'resizeable', 'distroFilter' + ]); + module.abilities = profile.module.abilities.map(ability => select(ability, [ + 'name', 'description', 'icon', 'type', 'label', 'visible', 'deviceCapability', + 'resizeable', 'srcLanguage', 'srcPath', 'metaData', 'skills', + 'iconId', 'labelId', 'descriptionId' + ])); + for (const ability of module.abilities) { + for (const [field, id] of [['icon', 'iconId'], ['label', 'labelId'], ['description', 'descriptionId']]) { + if (typeof ability[field] === 'string' && /^\$(media|string):/.test(ability[field]) && + (!Number.isInteger(ability[id]) || ability[id] <= 0)) { + throw new Error('Compiled Lite resource reference ' + field + ' requires ' + id + '. Rebuild resources.'); + } + } + } + const deviceConfig = {}; + for (const type of ['default', 'liteWearable', 'smartVision']) { + if (profile.deviceConfig[type]) deviceConfig[type] = select(profile.deviceConfig[type], ['keepAlive']); + } + return { app, deviceConfig, module }; +} + +function normalizeFile(file, compatible, target) { + const input = JSON.parse(fs.readFileSync(file, 'utf8')); + const output = normalize(input, compatible, target); + fs.writeFileSync(file, JSON.stringify(output, null, 2) + '\n', 'utf8'); + console.log('[techpie-lite] Packaged configuration uses API ' + output.app.apiVersion.target); +} + +function readSdkRange(file) { + const text = fs.readFileSync(file, 'utf8'); + function read(key) { + const match = new RegExp('"' + key + '"\\s*:\\s*(?:"([^"]+)"|(\\d+))').exec(text); + if (!match) throw new Error('Missing ' + key + ' in the build profile.'); + return match[1] || Number(match[2]); + } + return [read('compatibleSdkVersion'), read('targetSdkVersion')]; +} + +module.exports = { apiLevel, normalize, normalizeFile, readSdkRange }; diff --git a/harmonyos_watch/scripts/lite-profile.test.cjs b/harmonyos_watch/scripts/lite-profile.test.cjs new file mode 100644 index 00000000..4680dc7b --- /dev/null +++ b/harmonyos_watch/scripts/lite-profile.test.cjs @@ -0,0 +1,59 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { normalize } = require('./lite-profile.cjs'); + +function generatedProfile() { + return { + app: { + bundleName: 'com.geekpie.techpie.watch', vendor: 'geekpie', + version: { code: 1, name: '0.1.0' }, appEnvironments: [], + apiVersion: { compatible: 50100018, target: 50100018, compileSdkVersion: '26.0.0' } + }, + deviceConfig: { default: { debug: true }, liteWearable: { keepAlive: false } }, + module: { + deviceType: ['liteWearable'], package: 'com.example.myapplication', mainAbility: '.MainAbility', + distro: { deliveryWithInstall: true, moduleName: 'entry', moduleType: 'entry' }, + abilities: [{ name: '.MainAbility', label: '$string:app_name', labelId: 16777217, + icon: '$media:icon', iconId: 16777218, + description: '$string:app_description', descriptionId: 16777219, type: 'page' }], + js: [{ name: '.MainAbility', pages: ['pages/index/index'] }] + } + }; +} + +test('SDK 26 profile becomes Lite API 18 without changing app identity or entry', () => { + const source = generatedProfile(); + const output = normalize(source, '5.1.0(18)', '5.1.0(18)'); + assert.deepEqual(output.app.apiVersion, { compatible: 18, target: 18, releaseType: 'Release' }); + assert.equal(output.app.bundleName, source.app.bundleName); + assert.deepEqual(output.app.version, source.app.version); + assert.deepEqual(output.module.js, source.module.js); + assert.equal(output.module.abilities[0].label, '$string:app_name'); + assert.deepEqual(output.deviceConfig, { default: {}, liteWearable: { keepAlive: false } }); + assert.equal('appEnvironments' in output.app, false); + assert.equal('package' in output.module, false); + for (const id of ['labelId', 'iconId', 'descriptionId']) { + assert.equal(output.module.abilities[0][id], source.module.abilities[0][id]); + } + assert.equal(source.app.apiVersion.compatible, 50100018); +}); + +test('rejects compiled resource references without their generated IDs', () => { + for (const id of ['labelId', 'iconId', 'descriptionId']) { + const source = generatedProfile(); + delete source.module.abilities[0][id]; + assert.throws(() => normalize(source, 10, 10), new RegExp(id)); + } +}); + +test('rejects non-Lite devices and invalid API ranges', () => { + const phone = generatedProfile(); + phone.module.deviceType = ['phone']; + assert.throws(() => normalize(phone, 18, 18)); + assert.throws(() => normalize(generatedProfile(), 20, 18)); +}); + +test('API 10 comparison build reads the declared range rather than retaining API 18', () => { + const output = normalize(generatedProfile(), '4.0.0(10)', '4.0.0(10)'); + assert.deepEqual(output.app.apiVersion, { compatible: 10, target: 10, releaseType: 'Release' }); +}); diff --git a/harmonyos_watch/scripts/minify-lite.cjs b/harmonyos_watch/scripts/minify-lite.cjs new file mode 100644 index 00000000..43c6b0a4 --- /dev/null +++ b/harmonyos_watch/scripts/minify-lite.cjs @@ -0,0 +1,30 @@ +// Compress compiled Lite pages before BIN generation and signing. +const fs = require('node:fs'); +const path = require('node:path'); +const { minify } = require(process.argv[3]); + +async function visit(directory) { + for (const name of fs.readdirSync(directory)) { + const file = path.join(directory, name); + if (fs.statSync(file).isDirectory()) { + await visit(file); + } else if (name.endsWith('.js')) { + const original = fs.readFileSync(file, 'utf8'); + const result = await minify(original, { + ecma: 5, + compress: false, + mangle: true, + format: { comments: false, ascii_only: true }, + }); + if (!result.code) throw new Error('Empty minified page: ' + file); + const size = Buffer.byteLength(result.code); + if (size > 48 * 1024) throw new Error('Lite JS page exceeds 48 KB: ' + file); + fs.writeFileSync(file, result.code, 'utf8'); + console.log('[techpie-lite] ' + name + ': ' + Buffer.byteLength(original) + ' -> ' + size + ' bytes'); + } else if (name.endsWith('.map')) { + // Maps are debug tools, not runtime assets; exclude them before packaging. + fs.unlinkSync(file); + } + } +} +visit(process.argv[2]).catch(error => { console.error(error.message); process.exitCode = 1; }); diff --git a/harmonyos_watch/scripts/signing-config.test.cjs b/harmonyos_watch/scripts/signing-config.test.cjs new file mode 100644 index 00000000..711f6a8f --- /dev/null +++ b/harmonyos_watch/scripts/signing-config.test.cjs @@ -0,0 +1,48 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { fingerprint, validateConfig, prepareCompiled } = require('./validate-signing-config.cjs'); + +const release = '1C8155EE7940F2BEF76816F24FCE3044A7A083ED2032BB9DCEF3DE7BE4284A98'; +const debug = 'A13C448FF7A7E886027767B8C6687937BCD2B7C481645C6492F4341A721E4D9E'; +const workflow = `EXPECTED_CERT_SHA256: ${release.toLowerCase()}`; +const config = `export default {phonePackage: 'club.geekpie.techpie', phoneFingerprint: '${release}'};`; + +test('release source matches actual Android release workflow', () => { + const root = path.resolve(__dirname, '../..'); + const source = fs.readFileSync(path.join(root, 'harmonyos_watch/entry/src/main/js/MainAbility/common/wear-config.js'), 'utf8'); + const workflow = fs.readFileSync(path.join(root, '.github/workflows/android-release.yml'), 'utf8'); + assert.equal(validateConfig(source, workflow).selected, release); +}); + +test('rejects wrong package, stale release certificate and malformed overrides', () => { + assert.throws(() => validateConfig(config.replace(release, debug), workflow)); + assert.throws(() => validateConfig(config.replace('club.geekpie.techpie', 'wrong.package'), workflow)); + for (const value of ['', 'secret', debug + '0', debug + '\n']) { + assert.throws(() => validateConfig(config, workflow, value)); + } + assert.equal(fingerprint(debug.toLowerCase()), debug); +}); + +test('explicit debug override rewrites only generated JavaScript', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'techpie-watch-signing-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const bundle = path.join(dir, 'index.js'); + fs.writeFileSync(bundle, `const fingerprint = '${release}';`); + fs.writeFileSync(path.join(dir, 'note.txt'), release); + prepareCompiled(dir, validateConfig(config, workflow, debug)); + assert.ok(fs.readFileSync(bundle, 'utf8').includes(debug)); + assert.equal(fs.readFileSync(path.join(dir, 'note.txt'), 'utf8'), release); + assert.ok(config.includes(release)); + // A cached debug bundle must never silently ship as a release companion. + assert.throws(() => prepareCompiled(dir, validateConfig(config, workflow)), /Cannot locate/); +}); + +test('debug override fails if compiled identity is missing', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'techpie-watch-signing-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.writeFileSync(path.join(dir, 'index.js'), 'var other = 1;'); + assert.throws(() => prepareCompiled(dir, validateConfig(config, workflow, debug)), /Cannot locate/); +}); diff --git a/harmonyos_watch/scripts/validate-signing-config.cjs b/harmonyos_watch/scripts/validate-signing-config.cjs new file mode 100644 index 00000000..d9e73e56 --- /dev/null +++ b/harmonyos_watch/scripts/validate-signing-config.cjs @@ -0,0 +1,57 @@ +// Validate public companion identity before signing; never read signing secrets. +const fs = require('node:fs'); +const path = require('node:path'); + +function fingerprint(value) { + if (typeof value !== 'string' || !/^[a-fA-F0-9]{64}$/.test(value)) { + throw new Error('Phone fingerprint must be a certificate SHA256 (64 hex characters).'); + } + return value.toUpperCase(); +} + +function validateConfig(source, workflow, override) { + const expected = fingerprint(workflow.match(/EXPECTED_CERT_SHA256:\s*([a-fA-F0-9]{64})/)?.[1]); + const actual = fingerprint(source.match(/phoneFingerprint:\s*'([^']+)'/)?.[1]); + if (!/phonePackage:\s*'club\.geekpie\.techpie'/.test(source) || actual !== expected) { + throw new Error('Watch companion must match the Android release package and signing certificate.'); + } + return { expected, selected: override === undefined ? expected : fingerprint(override) }; +} + +function prepareCompiled(directory, identity) { + let replaced = 0; + function visit(dir) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, entry.name); + if (entry.isDirectory()) visit(file); + else if (entry.name.endsWith('.js')) { + const source = fs.readFileSync(file, 'utf8'); + if (source.includes(identity.selected)) { replaced++; continue; } + if (!source.includes(identity.expected)) continue; + fs.writeFileSync(file, source.split(identity.expected).join(identity.selected)); + replaced++; + } + } + } + visit(directory); + if (!replaced) throw new Error('Cannot locate the companion fingerprint in compiled watch JavaScript.'); +} + +function main(args) { + const root = path.resolve(__dirname, '../..'); + const source = fs.readFileSync(path.join(root, 'harmonyos_watch/entry/src/main/js/MainAbility/common/wear-config.js'), 'utf8'); + const workflow = fs.readFileSync(path.join(root, '.github/workflows/android-release.yml'), 'utf8'); + const identity = validateConfig(source, workflow, process.env.HUAWEI_PHONE_FINGERPRINT); + if (args.length) { + if (args.length !== 2 || args[0] !== '--compiled-dir') throw new Error('Usage: --compiled-dir DIRECTORY'); + prepareCompiled(args[1], identity); + } + console.log('[techpie-lite] Companion signing configuration verified' + + (identity.selected === identity.expected ? ' (Android release).' : ' (explicit local debug override).')); +} + +if (require.main === module) { + try { main(process.argv.slice(2)); } + catch (error) { console.error(error.message); process.exitCode = 1; } +} +module.exports = { fingerprint, validateConfig, prepareCompiled }; diff --git a/harmonyos_watch/scripts/wear-connection.test.mjs b/harmonyos_watch/scripts/wear-connection.test.mjs new file mode 100644 index 00000000..3dfb3f1f --- /dev/null +++ b/harmonyos_watch/scripts/wear-connection.test.mjs @@ -0,0 +1,200 @@ +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +const source = readFileSync(new URL('../entry/src/main/js/MainAbility/common/wear-connection.js', import.meta.url), 'utf8'); +const { WatchConnection } = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')); +function frames(message) { + const bytes = Buffer.from(JSON.stringify(message)); + return Array.from({length: Math.ceil(bytes.length / 512)}, (_, i) => JSON.stringify({ + v: 1, mid: message.id, i, n: Math.ceil(bytes.length / 512), + data: bytes.subarray(i * 512, (i + 1) * 512).toString('base64') + })); +} +function fixture() { + let now = 1000000, state; + const outgoing = []; + const link = new WatchConnection(frame => outgoing.push(JSON.parse(frame)), s => {state = s;}, () => now); + function send(type, body = {}, extra = {}) { + const m = {v: 1, id: 'p' + (++send.count), type, body, sentAtMs: now, + sessionId: type.startsWith('session.h') || type === 'session.open' ? null : 'session', + bindingId: type.startsWith('session.h') || type === 'session.open' ? null : 'binding', ...extra}; + frames(m).forEach(f => link.receive(f)); return m; + } + send.count = 0; + const last = () => JSON.parse(Buffer.from(outgoing.at(-1).data, 'base64').toString()); + function open() { + send('session.hello', {nonce: 'nonce', versions: [1]}); + send('session.open', {nonce: 'nonce', sessionId: 'session', bindingId: 'binding', + phoneTimeMs: now, leaseUntilMs: now + 86400000}); + } + return {link, send, last, open, outgoing, state: () => state, + advance: ms => {now += ms; link.tick();}, + advanceWithoutTick: ms => {now += ms;}}; +} +test('two-stage handshake advertises only implemented capabilities', () => { + const f = fixture(); + f.send('session.hello', {nonce: 'nonce', versions: [1]}); + assert.equal(f.state().connected, false); + assert.deepEqual(f.last().body.capabilities, ['account.display', 'ddl.display', 'campusCode.qrMatrix', 'connection.heartbeat']); + f.send('session.open', {nonce: 'wrong', sessionId: 'session', bindingId: 'binding', phoneTimeMs: 1000000, leaseUntilMs: 2000000}); + assert.equal(f.state().connected, false); + f.open(); assert.equal(f.state().connected, true); + assert.equal(f.last().type, 'session.opened'); +}); +test('Dart-compatible UTF8 fragmentation accepts Chinese and out-of-order parts', () => { + const f = fixture(); f.open(); + const m = {v: 1, id: 'chinese', type: 'account.snapshot', sentAtMs: 1000000, + sessionId: 'session', bindingId: 'binding', body: { + revision: 1, validUntilMs: 2000000, padding: 'x'.repeat(600), + data: {name: '测试😀'.repeat(20), studentId: '00123'} + }}; + assert.ok(frames(m).length > 1); + frames(m).reverse().forEach(frame => f.link.receive(frame)); + assert.equal(f.state().name, m.body.data.name); + assert.equal(f.last().body.revision, 1); +}); +test('duplicate acknowledgements are idempotent; old sessions cannot change the user', () => { + const f = fixture(); f.open(); + const m = f.send('account.snapshot', {revision: 1, validUntilMs: 2000000, data: {name: '张三', studentId: '00123'}}); + const ack = f.last(); frames(m).forEach(frame => f.link.receive(frame)); + assert.deepEqual(f.last(), ack); + f.send('account.snapshot', {revision: 2, validUntilMs: 2000000, data: {name: '李四', studentId: '9'}}, {sessionId: 'old'}); + assert.equal(f.state().name, '张三'); + f.send('account.snapshot', {revision: 1, validUntilMs: 2000000, data: {name: '李四', studentId: '9'}}); + assert.equal(f.last().body.status, 'error'); assert.equal(f.state().name, '张三'); +}); +test('heartbeat loss and explicit close hide account and reset connection', () => { + const f = fixture(); f.open(); + f.advance(20000); f.send('session.ping'); f.advance(20000); + assert.equal(f.state().connected, true); + f.advance(10000); assert.equal(f.state().connected, false); + f.open(); f.send('session.close'); assert.equal(f.state().connected, false); + assert.equal(f.state().name, ''); +}); +test('malformed/oversized/conflicting fragments and account payloads are rejected', () => { + const f = fixture(); f.open(); + f.link.receive('x'.repeat(1025)); f.link.receive('{'); + f.send('account.snapshot', {revision: 1, validUntilMs: 2000000, data: {name: '', studentId: '123'}}); + assert.equal(f.last().body.status, 'error'); assert.equal(f.state().name, ''); + const m = f.send('session.ping', {padding: 'x'.repeat(900)}); + const partial = JSON.parse(frames({...m, id: 'conflict'})[0]); + f.link.receive(JSON.stringify(partial)); + partial.data = Buffer.alloc(512, 65).toString('base64'); f.link.receive(JSON.stringify(partial)); + assert.equal(f.link.assembly, null); +}); + +test('DDL snapshots replace atomically, sort, reject stale revisions and expire', () => { + const f = fixture(); f.open(); + const items = [ + {id: 'later', title: '实验报告', courseName: '物理', dueAtMs: 1500000, status: 'open'}, + {id: 'earlier', title: '作业', courseName: '数学', dueAtMs: 1200000, status: 'completed'} + ]; + f.send('ddl.snapshot', {revision: 2, validUntilMs: 1020000, items}); + assert.deepEqual(f.state().ddl.map(i => i.id), ['earlier', 'later']); + assert.equal(f.last().body.revision, 2); + f.send('ddl.snapshot', {revision: 1, validUntilMs: 1020000, items: []}); + assert.equal(f.last().body.code, 'STALE_REVISION'); + f.send('ddl.snapshot', {revision: 3, validUntilMs: 1020000, items: [...items, {...items[0]}]}); + assert.equal(f.last().body.code, 'INVALID_PAYLOAD'); + assert.equal(f.state().ddl.length, 2); + f.advance(20000); + assert.equal(f.state().connected, true); + assert.equal(f.state().ddlReady, false); + assert.equal(f.state().ddl.length, 0); +}); + +test('QR only accepts a requested matrix and hides expired or dismissed codes', () => { + const f = fixture(); f.open(); + const body = {codeId: 'code1', purpose: 'campus', format: 'qrBytes', + matrixSize: 21, matrixEncoding: 'base64-msb', matrix: Buffer.alloc(56, 255).toString('base64'), + validFromMs: 1000000, validUntilMs: 1005000}; + f.send('campusCode.snapshot', body, {replyTo: 'unsolicited'}); + assert.equal(f.state().code, null); + f.link.request('code'); const id = f.last().id; + assert.equal(f.state().codeLoading, true); + f.send('campusCode.snapshot', {...body, matrix: 'AA=='}, {replyTo: id}); + assert.equal(f.last().body.code, 'INVALID_PAYLOAD'); + f.send('campusCode.snapshot', body, {replyTo: id}); + assert.equal(f.state().code.bytes.length, 56); + assert.equal(f.state().codeSeconds, 5); + f.advance(5000); assert.equal(f.state().code, null); + f.link.request('code'); const dismissed = f.last().id; + f.link.hideCode(); + f.send('campusCode.snapshot', {...body, validUntilMs: 1010000}, {replyTo: dismissed}); + assert.equal(f.state().code, null); +}); + +test('requests surface phone errors and timeouts without corrupting cached account', () => { + const f = fixture(); f.open(); + f.link.request('code'); const id = f.last().id; + f.send('result', {status: 'error', code: 'ACCOUNT_NOT_READY'}, {replyTo: id}); + assert.match(f.state().error, /绑定校园卡/); + assert.equal(f.state().codeLoading, false); + f.link.request('sync'); + f.advance(20000); f.send('session.ping'); f.advance(10000); + assert.equal(f.state().syncing, false); + assert.match(f.state().error, /没有响应/); + f.send('session.close'); + assert.deepEqual(f.state().ddl, []); + assert.equal(f.state().code, null); +}); + + +test('accepts newly issued QR between ticks without accepting a future code', () => { + const f = fixture(); f.open(); + f.link.request('code'); const replyTo = f.last().id; + f.advanceWithoutTick(100); + const body = {codeId: 'newCode', purpose: 'campus', format: 'qrBytes', + matrixSize: 21, matrixEncoding: 'base64-msb', matrix: Buffer.alloc(56).toString('base64'), + validFromMs: 1000100, validUntilMs: 1030100}; + f.send('campusCode.snapshot', {...body, validFromMs: 1001100}, {replyTo}); + assert.equal(f.state().code, null); + f.send('campusCode.snapshot', body, {replyTo}); + assert.equal(f.state().code.id, 'newCode'); + assert.equal(f.link.phoneNow(), 1000100); + f.advance(900); + assert.equal(f.link.phoneNow(), 1001000); +}); + +test('refresh failure retains valid QR, but publish hides it at actual expiry', () => { + const f = fixture(); f.open(); + f.link.request('code'); const first = f.last().id; + f.send('campusCode.snapshot', {codeId: 'oldCode', purpose: 'campus', format: 'qrBytes', + matrixSize: 21, matrixEncoding: 'base64-msb', matrix: Buffer.alloc(56).toString('base64'), + validFromMs: 1000000, validUntilMs: 1005000}, {replyTo: first}); + f.link.request('code'); const retry = f.last().id; + assert.equal(f.state().code.id, 'oldCode'); + assert.equal(f.state().codeLoading, true); + f.send('result', {status: 'error', code: 'RATE_LIMITED'}, {replyTo: retry}); + assert.equal(f.state().code.id, 'oldCode'); + assert.equal(f.state().codeLoading, false); + f.advanceWithoutTick(5000); f.link.publish(); + assert.equal(f.state().code, null); +}); + +test('successful refresh atomically replaces previous code', () => { + const f = fixture(); f.open(); + function code(id) { + f.link.request('code'); const replyTo = f.last().id; + f.send('campusCode.snapshot', {codeId: id, purpose: 'campus', format: 'qrBytes', + matrixSize: 21, matrixEncoding: 'base64-msb', matrix: Buffer.alloc(56).toString('base64'), + validFromMs: 1000000, validUntilMs: 1005000}, {replyTo}); + } + code('oldCode'); code('newCode'); + assert.equal(f.state().code.id, 'newCode'); + assert.equal(f.state().codeLoading, false); +}); + +test('snapshot resynchronizes a delayed opening clock without moving it backwards', () => { + const f = fixture(); f.open(); + f.link.request('code'); const replyTo = f.last().id; + f.advanceWithoutTick(100); + f.send('campusCode.snapshot', {codeId: 'fresh', purpose: 'campus', format: 'qrBytes', + matrixSize: 21, matrixEncoding: 'base64-msb', matrix: Buffer.alloc(56).toString('base64'), + validFromMs: 1000250, validUntilMs: 1030250}, {replyTo, sentAtMs: 1000250}); + assert.equal(f.state().code.id, 'fresh'); + assert.equal(f.link.phoneNow(), 1000250); + f.send('session.ping', {}, {sentAtMs: 1000100}); + assert.equal(f.link.phoneNow(), 1000250); +}); diff --git a/lib/main.dart b/lib/main.dart index 41ffecb8..38c81704 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -13,10 +13,12 @@ import 'models/third_party_account.dart'; import 'services/assignment_service.dart'; import 'services/auth_service.dart'; import 'services/campus_card_service.dart'; +import 'services/deadline_widget_service.dart'; import 'services/debug_logger.dart'; import 'services/ecard_bind_service.dart'; import 'services/ecard_widget_service.dart'; import 'services/egate_app_service.dart'; +import 'services/genai_api_service.dart'; import 'services/http_client.dart'; import 'services/oa_gym_service.dart'; import 'services/schedule_service.dart'; @@ -27,6 +29,10 @@ import 'services/theme_service.dart'; import 'services/third_party_auth_service.dart'; import 'services/uni_auth_service.dart'; import 'services/update_service.dart'; +import 'services/wear/android_wear_transport.dart'; +import 'services/wear/techpie_wear_data_source.dart'; +import 'services/wear/wear_engine_service.dart'; +import 'services/wear/wear_protocol.dart'; import 'widgets/adaptive_feedback.dart'; import 'widgets/app_shell/app_shell.dart'; import 'widgets/update_dialogs.dart'; @@ -56,16 +62,24 @@ void main(List args) async { // } final prefs = await SharedPreferences.getInstance(); - await _realMain(prefs); + await _realMain(prefs, startGenaiApi: args.contains('--genai-api')); } -Future _realMain(SharedPreferences prefs) async { +Future _realMain(SharedPreferences prefs, {bool startGenaiApi = false}) async { final storageService = StorageService(prefs); + configureAppProxy(storageService.appProxyEnabled ? storageService.appProxyUrl : ''); final debugLogger = DebugLogger()..enabled = storageService.debugMode; final httpClient = LoggingHttpClient(debugLogger); - final uniAuthService = UniAuthService(logger: debugLogger); - final authService = AuthService(storageService, httpClient, uniAuthService, - logger: debugLogger,); + final uniAuthService = UniAuthService( + logger: debugLogger, + proxyUrl: storageService.appProxyEnabled ? storageService.appProxyUrl : '', + ); + final authService = AuthService( + storageService, + httpClient, + uniAuthService, + logger: debugLogger, + ); final themeService = ThemeService(storageService); final campusCardService = CampusCardService(debugLogger: debugLogger, storage: storageService); @@ -98,6 +112,21 @@ Future _realMain(SharedPreferences prefs) async { thirdPartyAuthService, scheduleService, ); + final deadlineWidgetService = !kIsWeb && defaultTargetPlatform == TargetPlatform.linux + ? DeadlineWidgetService(assignmentService, enabled: storageService.deadlineWidgetsEnabled) + : null; + final wearEngineService = isAndroid() + ? WearEngineService( + transport: AndroidWearTransport(), + metadata: PreferencesWearMetadata(prefs), + source: TechPieWearDataSource( + auth: authService, + accounts: thirdPartyAuthService, + assignments: assignmentService, + campusCard: campusCardService, + ), + ) + : null; final syncService = SyncService( authService, thirdPartyAuthService, @@ -109,6 +138,8 @@ Future _realMain(SharedPreferences prefs) async { // It talks to GitHub rather than our backend, so it keeps its own client // instead of the logging one the API services share. final updateService = UpdateService(); + final genaiApiService = GenaiApiService(storageService); + if (startGenaiApi) unawaited(genaiApiService.start()); authService.onLogout = () async { // Third-party bindings persist across logouts — they will be used by the @@ -183,10 +214,14 @@ Future _realMain(SharedPreferences prefs) async { campusCardService: campusCardService, ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, + wearEngineService: wearEngineService, + deadlineWidgetService: deadlineWidgetService, + genaiApiService: genaiApiService, ), ); bootMark('cached data ready'); + deadlineWidgetService?.initialize(); oaGymService.startProfileSync(); unawaited(campusCardService.refreshAccount()); @@ -199,6 +234,29 @@ Future _realMain(SharedPreferences prefs) async { // pass does not pay for it. Nothing session-related happens here: a request // that needs a session issues one itself. campusCardService.prepare(); + if (wearEngineService != null) { + void accountChanged() => unawaited(wearEngineService.reconcileAccount()); + void deadlinesChanged() { + if (wearEngineService.ready && + !assignmentService.loading && + (wearEngineService.getStatus()['capabilities'] as List) + .contains('ddl.display')) { + unawaited( + wearEngineService.refresh(resources: ['ddl']).catchError( + (Object error) { + if (error is! WearFailure) throw error; + }, + ), + ); + } + } + + authService.addListener(accountChanged); + thirdPartyAuthService.addListener(accountChanged); + campusCardService.addListener(accountChanged); + assignmentService.addListener(deadlinesChanged); + unawaited(wearEngineService.reconcileAccount()); + } // -- Background: renew tokens first (main SSO session + third-party in // parallel — they touch independent state), then fan out fetches that @@ -311,6 +369,9 @@ class TechPieApp extends StatefulWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final WearEngineService? wearEngineService; + final DeadlineWidgetService? deadlineWidgetService; + final GenaiApiService? genaiApiService; const TechPieApp({ super.key, @@ -329,6 +390,9 @@ class TechPieApp extends StatefulWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.wearEngineService, + this.deadlineWidgetService, + this.genaiApiService, }); @override @@ -352,11 +416,16 @@ class _TechPieAppState extends State with WidgetsBindingObserver { WidgetsBinding.instance.addObserver(this); unawaited(_checkForUpdatesQuietly()); widget.ecardWidgetService?.setOpenPayHandler(_openEcardPayCode); + widget.deadlineWidgetService?.setOpenHandler(_openDeadlines); } @override void didUpdateWidget(covariant TechPieApp oldWidget) { super.didUpdateWidget(oldWidget); + if (oldWidget.deadlineWidgetService != widget.deadlineWidgetService) { + oldWidget.deadlineWidgetService?.clearOpenHandler(); + widget.deadlineWidgetService?.setOpenHandler(_openDeadlines); + } if (oldWidget.ecardWidgetService == widget.ecardWidgetService) return; oldWidget.ecardWidgetService?.clearOpenPayHandler(); widget.ecardWidgetService?.setOpenPayHandler(_openEcardPayCode); @@ -366,7 +435,10 @@ class _TechPieAppState extends State with WidgetsBindingObserver { void dispose() { WidgetsBinding.instance.removeObserver(this); widget.ecardWidgetService?.clearOpenPayHandler(); + widget.deadlineWidgetService?.dispose(); widget.campusCardService.dispose(); + widget.wearEngineService?.dispose(); + widget.genaiApiService?.dispose(); super.dispose(); } @@ -380,6 +452,11 @@ class _TechPieAppState extends State with WidgetsBindingObserver { } } + Future _openDeadlines() async { + _navigatorKey.currentState?.popUntil((route) => route.isFirst); + appShellPendingDeadlines.value = true; + } + /// The check nobody asked for. /// /// It may raise the update dialog, and says nothing else: a network the user @@ -405,8 +482,10 @@ class _TechPieAppState extends State with WidgetsBindingObserver { } if (release == null || !mounted) return; + final dialogContext = _navigatorKey.currentState?.overlay?.context; + if (dialogContext == null || !dialogContext.mounted) return; _promptedThisLaunch = true; - await showUpdateAvailableDialog(context, release); + await showUpdateAvailableDialog(dialogContext, release); } Future _openEcardPayCode() async { @@ -450,6 +529,9 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + wearEngineService: widget.wearEngineService, + deadlineWidgetService: widget.deadlineWidgetService, + genaiApiService: widget.genaiApiService, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, diff --git a/lib/models/feature.dart b/lib/models/feature.dart index 70600584..b7ecb339 100644 --- a/lib/models/feature.dart +++ b/lib/models/feature.dart @@ -5,6 +5,7 @@ import '../pages/campus_card_page.dart'; import '../pages/egate_app_page.dart'; import '../pages/elrc_recordings_page.dart'; import '../pages/oa_gym_page.dart'; +import '../pages/genai_api_page.dart'; import '../widgets/adaptive_page_navigation.dart'; enum FeatureMode { @@ -39,6 +40,16 @@ class Feature { } final featureEntries = [ + Feature( + id: 'genai_api', + description: 'GenAI API', + mode: FeatureMode.native, + nativeEntry: (context) => pushAdaptivePage( + context, + builder: (_) => const GenaiApiPage(), + ), + icon: const Icon(Icons.auto_awesome_outlined), + ), Feature( id: 'elrc_recordings', description: '课程录播', diff --git a/lib/pages/assignments_page.dart b/lib/pages/assignments_page.dart index ccca0982..31cbf53e 100644 --- a/lib/pages/assignments_page.dart +++ b/lib/pages/assignments_page.dart @@ -18,6 +18,7 @@ import '../widgets/blurred_app_bar.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/swipeable_card.dart'; import 'hidden_assignments_page.dart'; +import 'third_party_accounts_page.dart'; class AssignmentsPage extends StatefulWidget { const AssignmentsPage({super.key}); @@ -453,6 +454,8 @@ class _AssignmentsPageState extends State { Widget _emptyState(BuildContext context, AssignmentService service) { final theme = Theme.of(context); + final hasSources = ServiceProvider.of(context) + .thirdPartyAuthService.boundPlatforms.isNotEmpty; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -463,7 +466,25 @@ class _AssignmentsPageState extends State { color: theme.colorScheme.onSurfaceVariant, ), const SizedBox(height: 16), - Text('No upcoming deadlines', style: theme.textTheme.titleMedium), + Text( + !hasSources ? '连接课程平台以获取Deadlines' : service.loading + ? '正在同步截止日期…' : !service.hasCachedData + ? '尚未成功同步截止日期' : 'No upcoming deadlines', + style: theme.textTheme.titleMedium, + ), + if (!hasSources) ...[ + const SizedBox(height: 16), + FilledButton.icon( + icon: const Icon(Icons.link), + label: const Text('连接课程平台'), + onPressed: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const ThirdPartyAccountsPage(), + ), + ), + ), + ], if (service.error != null) ...[ const SizedBox(height: 8), Padding( diff --git a/lib/pages/genai_api_page.dart b/lib/pages/genai_api_page.dart new file mode 100644 index 00000000..ae0fb170 --- /dev/null +++ b/lib/pages/genai_api_page.dart @@ -0,0 +1,360 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../services/genai_api_service.dart'; +import '../services/service_provider.dart'; +import '../utils/platform.dart'; +import '../widgets/adaptive_button.dart'; +import '../widgets/adaptive_feedback.dart'; +import '../widgets/adaptive_page_navigation.dart'; +import '../widgets/adaptive_select.dart'; +import '../widgets/blurred_app_bar.dart'; +import '../widgets/ios/ios_native_navigation_bar.dart'; + +class GenaiApiPage extends StatefulWidget { + const GenaiApiPage({super.key, this.service}); + final GenaiApiService? service; + + @override + State createState() => _GenaiApiPageState(); +} + +class _GenaiApiPageState extends State { + GenaiApiService? _service; + final _apiToken = TextEditingController(); + final _port = TextEditingController(text: '5000'); + String _host = '127.0.0.1'; + bool _ready = false; + bool _showToken = false; + bool _ownsService = false; + bool _saving = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_service != null) return; + final provider = widget.service == null ? ServiceProvider.of(context) : null; + _service = widget.service ?? provider?.genaiApiService; + if (_service == null) { + _service = GenaiApiService(provider!.storageService); + _ownsService = true; + } + unawaited(_load()); + } + + Future _load() async { + try { + await _service!.load(); + if (!mounted) return; + _apiToken.text = _service!.apiToken; + _port.text = '${_service!.port}'; + _host = _service!.host; + setState(() => _ready = true); + } catch (_) { + if (mounted) setState(() {}); + } + } + + @override + void dispose() { + if (_ownsService) _service?.dispose(); + _apiToken.dispose(); + _port.dispose(); + super.dispose(); + } + + Future _start() async { + if (_saving) return; + setState(() => _saving = true); + try { + await _service!.saveSettings(apiToken: _apiToken.text, port: _port.text, host: _host); + await _service!.start(); + } on FormatException catch (e) { + if (mounted) { + showAdaptiveFeedback( + context: context, + message: e.message, + style: AdaptiveFeedbackStyle.error, + ); + } + } catch (_) { + if (mounted) { + showAdaptiveFeedback( + context: context, + message: '保存失败,请重试', + style: AdaptiveFeedbackStyle.error, + ); + } + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _save() async { + if (_saving) return; + setState(() => _saving = true); + try { + await _service!.saveSettings(apiToken: _apiToken.text, port: _port.text, host: _host); + if (mounted) showAdaptiveFeedback(context: context, message: '已保存'); + } catch (e) { + if (mounted) { + showAdaptiveFeedback( + context: context, + message: e is FormatException ? e.message : '保存失败,请重试', + ); + } + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _copy(String text) async { + await Clipboard.setData(ClipboardData(text: text)); + if (mounted) showAdaptiveFeedback(context: context, message: '已复制'); + } + + @override + Widget build(BuildContext context) { + final service = _service!; + final useIosChrome = isIos(); + final top = useIosChrome || usesLegacyIosChrome() + ? 16.0 + : adaptiveTopBarHeight() + MediaQuery.viewPaddingOf(context).top + 16; + return ListenableBuilder( + listenable: service, + builder: (context, _) { + final editable = _ready && !service.busy && !service.running && !_saving; + return Scaffold( + extendBodyBehindAppBar: !useIosChrome && !usesLegacyIosChrome(), + appBar: useIosChrome + ? IosNativeNavigationBar( + title: 'GenAI API', + leadingItems: const [ + IosNativeNavigationBarItem(id: 'back', title: '返回', sfSymbol: 'chevron.left'), + ], + onItemPressed: (_) => Navigator.of(context).maybePop(), + ) + : const BlurredAppBar(title: Text('GenAI API')), + body: ListView( + padding: + EdgeInsets.fromLTRB(16, top, 16, MediaQuery.viewPaddingOf(context).bottom + 24), + children: [ + Card.outlined( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListTile( + contentPadding: EdgeInsets.zero, + leading: Icon( + service.loggedIn ? Icons.check_circle_outline : Icons.person_outline,), + title: Text(service.loggedIn ? '已登录 GenAI' : '登录 GenAI'), + trailing: editable + ? TextButton( + onPressed: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => _GenaiLoginPage(service: service), + ), + ), + child: Text(service.loggedIn ? '切换账号' : '登录'), + ) + : null, + ), + if (service.loggedIn && editable) + TextButton( + onPressed: () async { + try { + await service.logout(); + } catch (_) { + if (context.mounted) { + showAdaptiveFeedback(context: context, message: '退出失败,请重试'); + } + } + }, + child: const Text('退出登录'), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + Card.outlined( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('本地 API', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 12), + TextField( + controller: _port, + enabled: editable, + decoration: const InputDecoration(labelText: '端口'), + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + ), + const SizedBox(height: 12), + TextField( + controller: _apiToken, + enabled: editable, + obscureText: !_showToken, + autocorrect: false, + enableSuggestions: false, + decoration: InputDecoration( + labelText: 'API Token', + suffixIcon: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + tooltip: _showToken ? '隐藏' : '显示', + onPressed: () => setState(() => _showToken = !_showToken), + icon: Icon( + _showToken + ? Icons.visibility_off_outlined + : Icons.visibility_outlined, + ), + ), + IconButton( + tooltip: '复制 Token', + onPressed: _ready ? () => unawaited(_copy(_apiToken.text)) : null, + icon: const Icon(Icons.copy_outlined), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + const Text('监听范围'), + const SizedBox(height: 8), + IgnorePointer( + ignoring: !editable, + child: AdaptiveSelect( + value: _host, + accessibilityLabel: '监听范围', + options: const [ + AdaptiveSelectOption(value: '127.0.0.1', label: '仅本机'), + AdaptiveSelectOption(value: '0.0.0.0', label: '局域网'), + ], + onChanged: (value) => setState(() => _host = value), + ), + ), + TextButton( + onPressed: editable ? () => unawaited(_save()) : null, + child: const Text('保存设置'), + ), + const SizedBox(height: 20), + AdaptiveButton( + onPressed: !_ready || + service.busy || + _saving || + (!service.running && !service.loggedIn) + ? null + : () => unawaited(service.running ? service.stop() : _start()), + icon: service.running ? Icons.stop_rounded : Icons.play_arrow_rounded, + sfSymbol: service.running ? 'stop.fill' : 'play.fill', + label: service.running ? '停止服务' : '启动服务', + loading: service.busy, + role: AdaptiveButtonRole.prominent, + ), + const SizedBox(height: 12), + Text(service.running ? '运行中' : '未启动', textAlign: TextAlign.center), + if (service.running) ...[ + const SizedBox(height: 12), + SelectableText(service.endpoint), + TextButton( + onPressed: () => unawaited(_copy(service.endpoint)), + child: const Text('复制地址'), + ), + ], + ], + ), + ), + ), + if (service.error != null) + Padding( + padding: const EdgeInsets.all(16), + child: Text(service.error!), + ), + if (!_ready && service.error != null) + TextButton(onPressed: () => unawaited(_load()), child: const Text('重试')), + ], + ), + ); + }, + ); + } +} + +class _GenaiLoginPage extends StatefulWidget { + const _GenaiLoginPage({required this.service}); + final GenaiApiService service; + @override + State<_GenaiLoginPage> createState() => _GenaiLoginPageState(); +} + +class _GenaiLoginPageState extends State<_GenaiLoginPage> { + final _account = TextEditingController(); + final _password = TextEditingController(); + @override + void dispose() { + _account.dispose(); + _password.dispose(); + super.dispose(); + } + + Future _login() async { + final ok = await widget.service.login(_account.text, _password.text); + if (!mounted) return; + if (ok) Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.service, + builder: (context, _) => Scaffold( + appBar: AppBar(title: const Text('登录 GenAI')), + body: ListView( + padding: const EdgeInsets.all(24), + children: [ + TextField( + controller: _account, + enabled: !widget.service.busy, + decoration: const InputDecoration(labelText: '学号'), + keyboardType: TextInputType.text, + textInputAction: TextInputAction.next, + autocorrect: false, + enableSuggestions: false, + ), + const SizedBox(height: 12), + TextField( + controller: _password, + enabled: !widget.service.busy, + decoration: const InputDecoration(labelText: '密码'), + obscureText: true, + onSubmitted: (_) { + if (!widget.service.busy) unawaited(_login()); + }, + ), + const SizedBox(height: 24), + AdaptiveButton( + onPressed: widget.service.busy ? null : () => unawaited(_login()), + icon: Icons.login, + sfSymbol: 'person.crop.circle', + label: '登录', + loading: widget.service.busy, + role: AdaptiveButtonRole.prominent, + ), + if (widget.service.error != null) + Padding( + padding: const EdgeInsets.only(top: 16), + child: Text(widget.service.error!), + ), + ], + ), + ), + ); +} diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index d58445c4..33d96192 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -381,7 +381,8 @@ class _HomePageState extends State with TickerProviderStateMixin { } void _handleFeatureTap(Feature feature) { - if (!ServiceProvider.of(context).authService.isLoggedIn) { + if (feature.id != 'genai_api' && + !ServiceProvider.of(context).authService.isLoggedIn) { unawaited(presentLoginPage(context)); return; } diff --git a/lib/pages/huawei_watch_page.dart b/lib/pages/huawei_watch_page.dart new file mode 100644 index 00000000..990d9c23 --- /dev/null +++ b/lib/pages/huawei_watch_page.dart @@ -0,0 +1,482 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../services/service_provider.dart'; +import '../services/wear/wear_engine_service.dart'; +import '../services/wear/wear_protocol.dart'; +import '../widgets/adaptive_button.dart'; + +class HuaweiWatchPage extends StatelessWidget { + const HuaweiWatchPage({super.key}); + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('HUAWEI WATCH')), + body: SafeArea( + child: HuaweiWatchContent( + service: ServiceProvider.of(context).wearEngineService, + ), + ), + ); +} + +class HuaweiWatchContent extends StatefulWidget { + const HuaweiWatchContent({super.key, required this.service}); + final WearEngineService? service; + + @override + State createState() => _HuaweiWatchContentState(); +} + +class _HuaweiWatchContentState extends State + with WidgetsBindingObserver { + bool _busy = false; + String _busyLabel = '正在连接'; + String? _error; + String? _deviceName; + List> _devices = []; + bool _queried = false; + final _fingerprint = TextEditingController( + text: const String.fromEnvironment( + 'HUAWEI_WATCH_FINGERPRINT', + defaultValue: + 'com.geekpie.techpie.watch_BFjBt5qvHo/1DXUCrRMIVMWeFuJfD6GS2ugQUhvqU5jnzucWokWlHWfpowxvojMSEXfV3n792x8buDocrZ7J6Uw=', + ), + ); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + widget.service?.addListener(_changed); + unawaited(widget.service?.refreshStatus()); + } + + @override + void didUpdateWidget(covariant HuaweiWatchContent oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.service != widget.service) { + oldWidget.service?.removeListener(_changed); + widget.service?.addListener(_changed); + _devices = []; + _queried = false; + _error = null; + unawaited(widget.service?.refreshStatus()); + } + } + + void _changed() { + if (mounted) setState(() {}); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + unawaited(widget.service?.refreshStatus()); + } + } + + Future _run( + Future Function() operation, { + String label = '正在连接', + }) async { + if (_busy) return; + setState(() { + _busy = true; + _busyLabel = label; + _error = null; + }); + try { + await operation(); + } catch (error) { + if (mounted) setState(() => _error = _failure(error)); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + String _failure(Object error) { + if (error is WearFailure && error.nativeCode != null) { + final message = switch (error.nativeCode) { + 2 => '请先安装华为运动健康。', + 3 => '请先在华为运动健康中登录华为账号。', + 4 => '请打开运动健康,确认手表已完成配对。', + 7 => '请先在运动健康中完成用户协议及隐私授权。', + 8 => '应用授权校验未通过,请稍后重试或联系开发者。', + 9 => '未获得设备访问权限,请重新授权。', + 13 || 18 => '当前设备或系统暂不支持此功能。', + 14 => '请更新华为运动健康后重试。', + 15 => '请允许运动健康自启动和后台运行,启动后重试。', + 16 => '请在运动健康中重新连接手表。', + 19 => '连接超时,请打开运动健康后重试。', + _ => '连接未完成,请检查运动健康和应用授权。', + }; + return '$message(SDK 错误码:${error.nativeCode})'; + } + final code = error is WearFailure ? error.code : ''; + return switch (code) { + 'PERMISSION_DENIED' => '未获得所需授权,请重新授权。', + 'ACCOUNT_NOT_READY' => '请先登录 TechPie', + 'DEVICE_DISCONNECTED' => '手表未连接,请先在运动健康中完成配对。', + 'SYNC_TIMEOUT' || 'PEER_NOT_READY' => '手表未响应,请保持手表上的 TechPie 打开后重试。', + 'INVALID_PAYLOAD' => '连接配置不匹配,请联系开发者。', + 'UNSUPPORTED_OPERATION' => '手表端 TechPie 需要更新,请前往运动健康完成更新。', + _ => '操作未完成,请检查两端连接后重试。', + }; + } + + Future _findDevices() => _run( + () async { + setState(() { + _queried = false; + _devices = []; + }); + final service = widget.service!; + final permissions = await service.requestPermissions(); + if (permissions['p2p'] != true) { + throw const WearFailure('PERMISSION_DENIED'); + } + final devices = await service.devices(); + if (mounted) { + setState(() { + _devices = devices; + _queried = true; + }); + } + }, + label: '正在查找手表', + ); + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + widget.service?.removeListener(_changed); + _fingerprint.dispose(); + super.dispose(); + } + + Widget _panel(BuildContext context, Widget child) => Container( + width: double.infinity, + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(24), + ), + child: child, + ); + + String _syncLabel(WearEngineService service, String resource) { + final sync = (service.getStatus()['sync'] as Map)[resource] as Map?; + return switch (sync?['state']) { + 'applied' => '已同步', + 'pending' => '正在同步', + 'failed' => '同步未完成,请重试', + _ => '等待同步', + }; + } + + @override + Widget build(BuildContext context) { + final service = widget.service; + final connected = service?.ready == true; + final user = service?.displayAccount; + final theme = Theme.of(context); + final colors = theme.colorScheme; + return Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 640), + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 32), + children: [ + _panel( + context, + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: connected + ? colors.primaryContainer + : colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(20), + ), + child: Icon( + Icons.watch_outlined, + size: 30, + color: connected + ? colors.onPrimaryContainer + : colors.onSurfaceVariant, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + connected + ? (_deviceName ?? 'HUAWEI WATCH') + : '连接你的手表', + style: theme.textTheme.titleLarge, + ), + const SizedBox(height: 4), + Semantics( + liveRegion: true, + child: Text( + _busy + ? _busyLabel + : connected + ? '已连接' + : '未连接', + key: const Key('huawei-watch-connection'), + style: theme.textTheme.bodyMedium + ?.copyWith(color: colors.primary), + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + Text( + connected + ? '在手表上查看待办、校园码与账号信息。' + : '先在运动健康中配对,再保持手表上的 TechPie 打开。', + style: theme.textTheme.bodyMedium + ?.copyWith(color: colors.onSurfaceVariant), + ), + const SizedBox(height: 20), + if (service != null) + AdaptiveButton( + label: connected ? '同步到手表' : '授权并查找手表', + sfSymbol: connected + ? 'arrow.triangle.2.circlepath' + : 'magnifyingglass', + icon: connected ? Icons.sync : Icons.search, + role: AdaptiveButtonRole.prominent, + loading: _busy, + width: double.infinity, + onPressed: _busy + ? null + : () => unawaited( + connected + ? _run( + () => service.refresh( + resources: [ + 'account', + if (service.supports('ddl.display')) + 'ddl', + ], + ), + label: '正在同步', + ) + : _findDevices(), + ), + ) + else + const Text('当前平台暂不支持此连接方式,请使用 Android 手机连接。'), + ], + ), + ), + if (_error != null) ...[ + const SizedBox(height: 12), + Semantics( + liveRegion: true, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: colors.errorContainer, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.info_outline, + color: colors.onErrorContainer, + ), + const SizedBox(width: 12), + Expanded( + child: SelectableText( + _error!, + style: TextStyle( + color: colors.onErrorContainer, + ), + ), + ), + ], + ), + ), + ), + ], + if (!connected && _devices.isNotEmpty) ...[ + const SizedBox(height: 24), + Text('选择手表', style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + for (final device in _devices) + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + leading: const Icon(Icons.watch_outlined), + title: Text( + '${device['name'] ?? device['model'] ?? 'HUAWEI WATCH'}', + ), + subtitle: Text( + device['connected'] == true ? '点击连接 TechPie' : '请先在运动健康中连接', + ), + trailing: device['connected'] == true + ? const Icon(Icons.chevron_right) + : null, + enabled: !_busy && device['connected'] == true, + onTap: () => unawaited( + _run(() async { + _deviceName = + '${device['name'] ?? device['model'] ?? 'HUAWEI WATCH'}'; + await service!.open( + device['id'] as String, + watchFingerprint: _fingerprint.text.trim(), + ); + }), + ), + ), + ], + if (!connected && _queried && _devices.isEmpty && _error == null) + const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Text('尚未发现手表,请完成配对后重新查找。'), + ), + const SizedBox(height: 24), + Text('设备用户', style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + leading: const Icon(Icons.person_outline), + title: Text(user?['name'] ?? '暂无设备用户'), + subtitle: Text( + user == null ? '连接并同步后显示姓名与学号' : '学号:${user['studentId']}', + ), + ), + if (connected) ...[ + const SizedBox(height: 16), + Text('手表功能', style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + leading: const Icon(Icons.event_note_outlined), + title: const Text('待办 DDL'), + subtitle: Text( + service!.supports('ddl.display') + ? _syncLabel(service, 'ddl') + : '请更新手表应用以使用此功能', + ), + ), + if (service.supports('ddl.display')) + SwitchListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + secondary: const Icon(Icons.notifications_none), + title: const Text('DDL 提醒'), + subtitle: const Text( + '截止前 1 小时提醒 · 本次授权 24 小时', + ), + value: service.remindersEnabled, + onChanged: _busy + ? null + : (enabled) => unawaited( + _run( + () => service.setRemindersEnabled(enabled), + label: '正在更新提醒', + ), + ), + ), + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + leading: const Icon(Icons.qr_code_rounded), + title: const Text('校园码'), + subtitle: Text( + service.supports('campusCode.qrMatrix') || + service.supports('campusCode.qrBytes') + ? '在手表上打开校园码,即时获取,过期自动隐藏。' + : '请更新手表应用以使用此功能', + ), + ), + const SizedBox(height: 12), + TextButton.icon( + icon: const Icon(Icons.link_off), + label: const Text('断开连接'), + onPressed: _busy + ? null + : () => unawaited(_run(service.close, label: '正在断开')), + ), + ], + const SizedBox(height: 16), + const ExpansionTile( + tilePadding: EdgeInsets.symmetric(horizontal: 8), + title: Text('连接帮助'), + leading: Icon(Icons.help_outline), + children: [ + _GuideStep( + number: '1', + title: '在运动健康中配对', + detail: '开启蓝牙,确认手表显示已连接。', + ), + _GuideStep( + number: '2', + title: '打开手表上的 TechPie', + detail: '连接与查看校园码时保持应用打开。', + ), + _GuideStep( + number: '3', + title: '登录并授权手机 TechPie', + detail: '点击“授权并查找手表”,选择你的手表。', + ), + Padding( + padding: EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Text('接收 DDL 提醒需允许运动健康后台运行。授权满 24 小时后,请重新连接并开启提醒。'), + ), + ], + ), + if (kDebugMode) + ExpansionTile( + tilePadding: const EdgeInsets.symmetric(horizontal: 8), + title: const Text('开发连接配置'), + childrenPadding: const EdgeInsets.fromLTRB(8, 0, 8, 16), + children: [ + TextField( + controller: _fingerprint, + enabled: !_busy && !connected, + autocorrect: false, + decoration: const InputDecoration( + labelText: '手表应用通信指纹', + helperText: '使用已签名手表应用的 Wear Engine 指纹', + ), + ), + ], + ), + ], + ), + ), + ); + } +} + +class _GuideStep extends StatelessWidget { + const _GuideStep({ + required this.number, + required this.title, + required this.detail, + }); + final String number, title, detail; + + @override + Widget build(BuildContext context) => ListTile( + leading: CircleAvatar(radius: 16, child: Text(number)), + title: Text(title), + subtitle: Text(detail), + ); +} diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 6de9c254..c7f4854f 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -7,9 +7,12 @@ import 'package:package_info_plus/package_info_plus.dart'; import 'package:techpie/services/auth_service.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../services/http_client.dart'; import '../services/service_provider.dart'; +import '../services/storage_service.dart'; import '../services/sync_service.dart'; import '../services/theme_service.dart'; +import '../services/uni_auth_service.dart'; import '../services/update_service.dart'; import '../utils/adaptive_layout.dart'; import '../utils/platform.dart'; @@ -23,15 +26,16 @@ import '../widgets/adaptive_switch.dart'; import '../widgets/app_shell/app_shell_metrics.dart'; import '../widgets/blurred_app_bar.dart'; import '../widgets/desktop_popup.dart'; +import '../widgets/feedback_entry.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/update_dialogs.dart'; import 'debug_log_page.dart'; import 'debug_webview_page.dart'; import 'developer_lab_page.dart'; +import 'huawei_watch_page.dart'; import 'login_page.dart'; import 'sync_settings_page.dart'; import 'third_party_accounts_page.dart'; -import 'watch_settings_page.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -265,7 +269,8 @@ class _SettingsPageState extends State { onTap: () => unawaited( launchUrl( Uri.parse( - 'https://techpie.geekpie.club/privacy#account-deletion',), + 'https://techpie.geekpie.club/privacy#account-deletion', + ), mode: LaunchMode.externalApplication, ), ), @@ -329,6 +334,7 @@ class _SettingsPageState extends State { ), const Divider(), + const FeedbackEntry(), ListTile( leading: const Icon(Icons.privacy_tip_outlined), title: const Text('隐私政策与使用支持'), @@ -341,16 +347,38 @@ class _SettingsPageState extends State { ), ), const Divider(), - if (isIos()) + + if (kIsWeb || defaultTargetPlatform != TargetPlatform.linux) ...[ + // Watch section + _sectionHeader(theme, 'Watch'), + ListTile( + leading: const Icon(Icons.watch_outlined), + title: const Text('Huawei Watch'), + subtitle: const Text('华为运动手表'), + trailing: const Icon(Icons.chevron_right), + onTap: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const HuaweiWatchPage(), + ), + ), + ), ListTile( leading: const Icon(Icons.watch_outlined), title: const Text('Apple Watch'), + subtitle: const Text('苹果手表'), trailing: const Icon(Icons.chevron_right), onTap: () => unawaited( - pushAdaptivePage(context, - builder: (_) => const WatchSettingsPage(),), + showAdaptiveAlertDialog( + context: context, + title: 'APPLE WATCH', + message: '抱歉,APPLE WATCH控制端尚在开发中。敬请期待!', + actions: const [AdaptiveAlertAction(label: '好')], + ), ), ), + const Divider(), + ], // Appearance section _sectionHeader(theme, 'Appearance'), @@ -409,6 +437,20 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), + if (sp.deadlineWidgetService != null) + _AdaptiveSwitchTile( + usesIosLiquidGlass: useIosChrome, + secondary: const Icon(Icons.widgets_outlined), + title: 'Deadline widgets', + subtitle: 'Share task titles and dates with your desktop. ' + 'Widgets use cached data while TechPie is closed.', + value: storage.deadlineWidgetsEnabled, + onChanged: (value) async { + await storage.setDeadlineWidgetsEnabled(value); + await sp.deadlineWidgetService!.setEnabled(value); + if (mounted) setState(() {}); + }, + ), _AdaptiveSwitchTile( usesIosLiquidGlass: useIosChrome, secondary: const Icon(Icons.visibility_off_outlined), @@ -422,6 +464,28 @@ class _SettingsPageState extends State { }); }, ), + ListTile( + leading: const Icon(Icons.lan_outlined), + title: const Text('Application proxy'), + subtitle: Text( + storage.appProxyEnabled && storage.appProxyUrl.isNotEmpty + ? storage.appProxyUrl + : 'Disabled', + ), + onTap: () => _showProxySettings(storage, sp.uniAuthService), + ), + SwitchListTile( + secondary: const Icon(Icons.power_settings_new), + title: const Text('Enable application proxy'), + value: storage.appProxyEnabled, + onChanged: (value) async { + await storage.setAppProxyEnabled(value); + final proxy = value ? storage.appProxyUrl : ''; + configureAppProxy(proxy); + sp.uniAuthService.setProxyUrl(proxy); + if (mounted) setState(() {}); + }, + ), ListTile( leading: const Icon(Icons.info_outline), title: const Text('About'), @@ -538,6 +602,43 @@ class _SettingsPageState extends State { } } + Future _showProxySettings(StorageService storage, UniAuthService uniAuth) async { + final controller = TextEditingController(text: storage.appProxyUrl); + final value = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Application proxy'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: '127.0.0.1:7890'), + keyboardType: TextInputType.url, + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')), + FilledButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text('Save')), + ], + ), + ); + controller.dispose(); + if (value == null || !mounted) return; + final proxy = value.trim(); + if (proxy.isNotEmpty && !RegExp(r'^[^\s:]+:\d{1,5}$').hasMatch(proxy)) { + await showAdaptiveAlertDialog( + context: context, + title: 'Invalid proxy', + message: 'Use host:port, for example 127.0.0.1:7890.', + actions: const [AdaptiveAlertAction(label: 'OK')], + ); + return; + } + await storage.setAppProxyUrl(proxy); + await storage.setAppProxyEnabled(proxy.isNotEmpty); + configureAppProxy(proxy); + uniAuth.setProxyUrl(proxy); + setState(() {}); + } + void _showThemePicker(BuildContext context, ThemeService themeService) { if (usesSidebarLayout(context)) { showDesktopPopover( diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index 18f4e390..d87fd8fd 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -26,6 +26,14 @@ class AssignmentService extends ChangeNotifier { List _assignments = []; AssignmentOverrides _overrides = AssignmentOverrides(); bool _loading = false; + int _identityEpoch = 0; + bool _hasCachedData = false; + bool _cacheHydrated = false; + bool _refetchPending = false; + bool _signedOut = false; + bool _disposed = false; + String? _primaryIdentity; + Map _sourceIdentities = {}; String? _error; // Per-platform error messages (keyed by lowercase platform id). final Map _platformErrors = {}; @@ -43,6 +51,8 @@ class AssignmentService extends ChangeNotifier { AssignmentOverrides get overrides => _overrides; bool get loading => _loading; + int get identityEpoch => _identityEpoch; + bool get hasCachedData => _hasCachedData; String? get error => _error; Map get platformErrors => Map.unmodifiable(_platformErrors); @@ -58,6 +68,8 @@ class AssignmentService extends ChangeNotifier { this._tpAuth, this._schedule, ) { + _primaryIdentity = _auth.session?.userId; + _sourceIdentities = _currentSources(); // Refetch when bindings or auth change *after* initial app boot. // The initial fetch is kicked off explicitly from main.dart so we // don't double-fire during service initialization. @@ -81,13 +93,65 @@ class AssignmentService extends ChangeNotifier { _lastRefetchedSemesterId = _schedule.selectedSemesterId; } - /// Auth or binding changed — always refetch (tokens, accounts differ). + /// Queue a refetch during an active sync only when the identity changes. void _onBindingsOrAuthChanged() { + final primary = _auth.session?.userId; + final sources = _currentSources(); + final primaryChanged = primary != _primaryIdentity; + final changed = { + for (final key in {..._sourceIdentities.keys, ...sources.keys}) + if (_sourceIdentities[key] != sources[key]) key, + }; + if (primaryChanged || changed.isNotEmpty) { + if (_cacheHydrated) { + _identityEpoch++; + if (primaryChanged) { + _signedOut = _primaryIdentity != null && primary == null; + } + if (primary != null) _signedOut = false; + _assignments = primaryChanged + ? [] + : _assignments.where((a) { + final source = + (a.platform == 'blackboard' || a.platform == 'exam') ? 'cpdaily' : a.platform; + return !changed.contains(source); + }).toList(); + if (primaryChanged) { + _hasCachedData = false; + unawaited(_storage.clearCachedAssignments()); + } else if (_hasCachedData) { + unawaited( + _storage.saveCachedAssignments( + _assignments.map((a) => a.toJson()).toList(), + ), + ); + } + notifyListeners(); + } + _primaryIdentity = primary; + _sourceIdentities = sources; + } if (!_autoRefetchEnabled) return; + if (_signedOut) return; _lastRefetchedSemesterId = _schedule.selectedSemesterId; + if (_loading) { + // Renewal status notifications must not retry the active sync. + if (primaryChanged || changed.isNotEmpty) _refetchPending = true; + return; + } unawaited(fetchAssignments()); } + Map _currentSources() => { + for (final account in _tpAuth.accounts) + account.platform.id: jsonEncode([ + account.account, + account.sid, + account.hydroOrigin, + account.hydroDomains, + ]), + }; + /// Schedule changed — only refetch if the selected semester actually /// changed, not on every loading/error/course_table flip. This prevents /// a cascade of redundant blackboard+exam fetches during a semester switch. @@ -106,6 +170,7 @@ class AssignmentService extends ChangeNotifier { @override void dispose() { + _disposed = true; _tpAuth.removeListener(_onBindingsOrAuthChanged); _auth.removeListener(_onBindingsOrAuthChanged); _schedule.removeListener(_onScheduleChanged); @@ -115,6 +180,8 @@ class AssignmentService extends ChangeNotifier { /// Clear cached + in-memory deadlines (called on primary logout). Future clearCache() async { + _identityEpoch++; + _hasCachedData = false; _assignments = []; _platformErrors.clear(); _error = null; @@ -125,6 +192,8 @@ class AssignmentService extends ChangeNotifier { /// Hydrate from local cache so the UI doesn't flash empty on app start /// or tab switch. Safe to call before login. Also loads overrides. void loadCached() { + _cacheHydrated = true; + _hasCachedData = _storage.hasCachedAssignments; _overrides = _storage.loadAssignmentOverrides(); final raw = _storage.loadCachedAssignments(); if (raw.isEmpty) { @@ -199,7 +268,8 @@ class AssignmentService extends ChangeNotifier { }; Future fetchAssignments() async { - if (_loading) return; // 避免启动时 listener 链触发的并发重复调用 + if (_loading || _signedOut || _disposed) return; + final epoch = _identityEpoch; _loading = true; _error = null; _platformErrors.clear(); @@ -246,11 +316,14 @@ class AssignmentService extends ChangeNotifier { try { await Future.wait(futures); + if (_disposed || epoch != _identityEpoch) return; final merged = _mergeAssignments( successfulResults: successfulResults, ); _assignments = merged; + _hasCachedData = _hasCachedData || successfulResults.isNotEmpty; + if (!_hasCachedData) return; await _storage.saveCachedAssignments( merged.map((a) => a.toJson()).toList(), ); @@ -258,7 +331,11 @@ class AssignmentService extends ChangeNotifier { _error = '同步失败,请检查网络或稍后重试'; } finally { _loading = false; - notifyListeners(); + if (!_disposed) notifyListeners(); + if (_refetchPending && !_disposed) { + _refetchPending = false; + unawaited(fetchAssignments()); + } } } @@ -278,6 +355,8 @@ class AssignmentService extends ChangeNotifier { } Future fetchPlatform(String platformId) async { + if (_loading || _signedOut || _disposed) return; + final epoch = _identityEpoch; _loading = true; _error = null; _platformErrors.remove(platformId); @@ -311,24 +390,31 @@ class AssignmentService extends ChangeNotifier { } } - if (future != null) { - try { + try { + if (future != null) { await future; + if (_disposed || epoch != _identityEpoch) return; final merged = _mergeAssignments( successfulResults: successfulResults, ); _assignments = merged; + _hasCachedData = _hasCachedData || successfulResults.isNotEmpty; + if (!_hasCachedData) return; await _storage.saveCachedAssignments( merged.map((a) => a.toJson()).toList(), ); - } catch (e) { - _error = e.toString(); + } + } catch (e) { + if (epoch == _identityEpoch) _error = e.toString(); + } finally { + _loading = false; + if (!_disposed) notifyListeners(); + if (_refetchPending && !_disposed) { + _refetchPending = false; + unawaited(fetchAssignments()); } } - - _loading = false; - notifyListeners(); } Future?> _fetchBlackboard() async { diff --git a/lib/services/deadline_widget_service.dart b/lib/services/deadline_widget_service.dart new file mode 100644 index 00000000..6b6b5a8f --- /dev/null +++ b/lib/services/deadline_widget_service.dart @@ -0,0 +1,192 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../models/assignment.dart'; +import '../models/assignment_overrides.dart'; +import 'assignment_service.dart'; + +typedef OpenDeadlinesHandler = Future Function(); + +/// Publishes display-only data; native widgets never receive account credentials. +class DeadlineWidgetService with WidgetsBindingObserver { + DeadlineWidgetService( + this._assignments, { + MethodChannel? channel, + DateTime Function()? now, + bool enabled = true, + }) : _channel = channel ?? const MethodChannel('techpie/deadline_widgets'), + _enabled = enabled, + _now = now ?? DateTime.now; + + final AssignmentService _assignments; + final MethodChannel _channel; + final DateTime Function() _now; + bool _enabled; + bool get enabled => _enabled; + + Future setEnabled(bool enabled) async { + _enabled = enabled; + _lastPublished = null; + await _publish(); + } + + OpenDeadlinesHandler? _handler; + bool _pendingRoute = false; + bool _dispatching = false; + bool _disposed = false; + bool _initialized = false; + String? _lastPublished; + Future _writes = Future.value(); + + void initialize() { + if (_initialized) return; + _initialized = true; + _assignments.addListener(_changed); + WidgetsBinding.instance.addObserver(this); + _channel.setMethodCallHandler((call) async { + if (call.method == 'openDeadlines') await _open(); + }); + unawaited(_consumeRoute()); + _changed(); + } + + static List> displayItems( + Iterable assignments, + bool Function(Assignment) completed, + DateTime now, + ) { + final items = assignments.where((a) => !completed(a) && a.due.isAfter(now)).toList() + ..sort((a, b) { + final order = a.due.compareTo(b.due); + return order != 0 + ? order + : AssignmentOverrides.keyFor(a).compareTo(AssignmentOverrides.keyFor(b)); + }); + final result = >[]; + final ids = {}; + var bytes = 1024; // Reserve the envelope and list separators. + for (final a in items) { + final id = AssignmentOverrides.keyFor(a); + final due = a.due.toUtc().millisecondsSinceEpoch / 1000; + if (utf8.encode(id).length > 4096 || !ids.add(id) || due < 0 || due > 253402300799) continue; + final row = { + 'id': id, + 'kind': a.kind.id, + 'title': String.fromCharCodes(a.title.runes.take(256)), + 'course': String.fromCharCodes(a.course.runes.take(128)), + 'dueAt': due, + }; + final size = utf8.encode(jsonEncode(row)).length + 1; + if (bytes + size > 262144) break; + result.add(row); + bytes += size; + if (result.length == 512) break; + } + return result; + } + + void _changed() => unawaited(_publish()); + + Future _publish() async { + final epoch = _assignments.identityEpoch; + // Publish an empty valid snapshot as soon as sharing is enabled. This + // keeps the desktop card truthful before the first sync. + final ready = _enabled; + final items = _assignments.hasCachedData ? displayItems( + _assignments.visibleAssignments, + _assignments.isCompleted, + _now(), + ) : >[]; + final content = ready ? jsonEncode(items) : null; + _writes = _writes.then((_) async { + if (_disposed || + epoch != _assignments.identityEpoch || + ready != _enabled) { + return; + } + if (_lastPublished == content && content != null) return; + try { + if (!ready) { + await _channel.invokeMethod('clear'); + } else { + await _channel.invokeMethod( + 'publish', + jsonEncode({ + 'schemaVersion': 1, + 'writtenAt': _now().toUtc().millisecondsSinceEpoch / 1000, + 'items': items, + }), + ); + } + _lastPublished = content; + } on MissingPluginException { + // Unsupported platforms keep using the regular deadlines page. + } on PlatformException { + // Retry on the next change/foreground event; never block the app. + } + }); + await _writes; + } + + Future flush() => _writes; + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed || _disposed) return; + _changed(); + } + + void setOpenHandler(OpenDeadlinesHandler handler) { + _handler = handler; + if (_pendingRoute) unawaited(_open()); + } + + void clearOpenHandler() => _handler = null; + + Future _consumeRoute() async { + try { + if (await _channel.invokeMethod('consumePendingRoute') == true) { + await _open(); + } + } on MissingPluginException { + // A missing native bridge does not delay app navigation. + } on PlatformException { + // Retry when a later native route event arrives. + } + } + + Future _open() async { + if (_disposed) return; + if (_handler == null || _dispatching) { + _pendingRoute = true; + return; + } + _pendingRoute = false; + _dispatching = true; + try { + await _handler!(); + try { + await _channel.invokeMethod('acknowledgePendingRoute'); + } on MissingPluginException { + // Tests may dispatch without a native peer. + } on PlatformException { + // The destination is already visible. + } + } finally { + _dispatching = false; + if (_pendingRoute) unawaited(_open()); + } + } + + void dispose() { + _disposed = true; + _handler = null; + if (!_initialized) return; + _assignments.removeListener(_changed); + WidgetsBinding.instance.removeObserver(this); + _channel.setMethodCallHandler(null); + } +} diff --git a/lib/services/genai/genai_gateway.dart b/lib/services/genai/genai_gateway.dart new file mode 100644 index 00000000..d0933708 --- /dev/null +++ b/lib/services/genai/genai_gateway.dart @@ -0,0 +1,664 @@ +// GenAI request mapping adapted from GenAI2OpenAI. +// See third_party/GenAI2OpenAI/LICENSE. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'genai_tools.dart'; + +class GenaiGateway { + GenaiGateway({ + Uri? upstream, + HttpClient Function()? clientFactory, + this.onDiagnostic, + this.heartbeatInterval = const Duration(seconds: 5), + }) : upstream = upstream ?? Uri.parse('https://genai.shanghaitech.edu.cn'), + _clientFactory = clientFactory ?? HttpClient.new; + + final void Function(Map)? onDiagnostic; + final Uri upstream; + final HttpClient Function() _clientFactory; + final Duration heartbeatInterval; + final Set _streams = {}; + HttpServer? _server; + HttpClient? _client; + String _genaiToken = ''; + String _apiToken = ''; + final Map _routes = {}; + int? get port => _server?.port; + bool get running => _server != null; + + Future start({ + required String host, + required int port, + required String genaiToken, + required String apiToken, + }) async { + if (_server != null) return; + _genaiToken = genaiToken; + _apiToken = apiToken; + _client = _clientFactory()..connectionTimeout = const Duration(seconds: 15); + try { + _server = await HttpServer.bind(host, port); + _server!.listen((request) => unawaited(_handle(request))); + } catch (_) { + _client!.close(force: true); + _client = null; + rethrow; + } + } + + Future stop() async { + final server = _server; + _server = null; + _client?.close(force: true); + _client = null; + for (final client in _streams) { + client.close(force: true); + } + _streams.clear(); + _genaiToken = ''; + _apiToken = ''; + _routes.clear(); + await server?.close(force: true); + } + + void _json(HttpResponse response, Object body, [int status = 200]) { + response.statusCode = status; + response.headers.contentType = ContentType.json; + response.write(jsonEncode(body)); + } + + Future _upstream(String path, {Object? body, HttpClient? client}) async { + final uri = upstream.resolve(path); + final request = await (client ?? _client!).openUrl(body == null ? 'GET' : 'POST', uri); + request.headers.set('X-Access-Token', _genaiToken); + request.headers.set('Origin', 'https://genai.shanghaitech.edu.cn'); + request.headers.set('Referer', 'https://genai.shanghaitech.edu.cn/dialogue'); + request.headers.set(HttpHeaders.acceptHeader, 'application/json, text/event-stream'); + request.headers.contentType = ContentType.json; + if (body != null) request.write(jsonEncode(body)); + return request.close().timeout(const Duration(seconds: 180)); + } + + Future>> _models() async { + final res = await _upstream('/htk/ai/aiModel/list?pageNo=1&pageSize=999&showStatusList=2%2C3'); + final data = jsonDecode(await utf8.decoder.bind(res).join()); + if (res.statusCode != 200 || + data is! Map || + data['success'] != true || + data['result'] is! Map || + data['result']['records'] is! List) { + throw const FormatException('获取模型失败,请重新登录'); + } + final records = (data['result']['records'] as List).whereType>(); + final models = >[]; + final seen = {}; + for (final record in records) { + final id = record['aiType']; + if (id is! String || id.isEmpty || !seen.add(id)) continue; + if (record['rootAiType'] is String) { + _routes[id] = record['rootAiType'] as String; + } + models.add({'id': id, 'object': 'model', 'owned_by': 'genai'}); + } + return models; + } + + Future _handle(HttpRequest request) async { + final watch = Stopwatch()..start(); + final diagnostic = { + 'request_id': 'req_${DateTime.now().microsecondsSinceEpoch}', + 'path': request.uri.path, + 'cancelled': false, + 'call_count': 0, + 'content_chars': 0, + 'saw_done': false, + }; + request.response.headers.set('X-Request-Id', diagnostic['request_id']!); + var completed = false; + var streaming = false; + Timer? heartbeat; + StreamController>? sse; + Future? ssePump; + final cancelled = Completer(); + HttpClient? streamClient; + void closeStream() { + heartbeat?.cancel(); + streamClient?.close(force: true); + _streams.remove(streamClient); + } + + void cancelRequest() { + if (completed) return; + diagnostic['cancelled'] = true; + if (!cancelled.isCompleted) cancelled.complete(); + closeStream(); + } + + void writeSse(String value) { + if (cancelled.isCompleted) throw const HttpException('Client disconnected'); + sse!.add(utf8.encode(value)); + } + + try { + final path = request.uri.path; + if (path == '/health' && request.method == 'GET') { + _json(request.response, {'status': 'ok'}); + return; + } + var key = request.headers.value(HttpHeaders.authorizationHeader) ?? ''; + if (key.toLowerCase().startsWith('bearer ')) key = key.substring(7).trim(); + key = key.isNotEmpty + ? key + : request.headers.value('x-api-key') ?? request.headers.value('api-key') ?? ''; + if (key != _apiToken) { + _json( + request.response, + { + 'error': {'message': 'API Token 不对', 'type': 'authentication_error'}, + }, + 401, + ); + return; + } + if (path == '/v1/models' && request.method == 'GET') { + _json(request.response, {'object': 'list', 'data': await _models()}); + return; + } + if (request.method != 'POST' || (path != '/v1/chat/completions' && path != '/v1/responses')) { + _json( + request.response, + { + 'error': {'message': '接口不存在'}, + }, + 404, + ); + return; + } + final data = jsonDecode(await utf8.decoder.bind(request).join()); + if (data is! Map) throw const FormatException('请求格式不对'); + final model = data['model']; + if (model is! String || model.isEmpty) throw const FormatException('请选择模型'); + final isResponses = path == '/v1/responses'; + var messages = isResponses ? _responseMessages(data) : data['messages']; + if (messages is! List || messages.isEmpty || messages.any((m) => m is! Map)) { + throw const FormatException('消息不能为空'); + } + messages = messages.map((m) => Map.from(m as Map)).toList(); + diagnostic.addAll({'model': model, 'message_count': messages.length}); + final tools = data['tools']; + final toolList = tools is List + ? tools.whereType>().toList() + : >[]; + final allowed = toolList + .map((t) => (t['function'] is Map ? t['function']['name'] : t['name'])) + .whereType() + .toSet(); + final choice = data['tool_choice']; + final selected = choice is Map + ? (choice['function'] is Map ? choice['function']['name'] : choice['name']) + : null; + if ((choice == 'required' && allowed.isEmpty) || + (selected != null && !allowed.contains(selected))) { + throw const FormatException('请选择可用工具'); + } + final limit = isResponses + ? data['max_output_tokens'] ?? 30000 + : data['max_completion_tokens'] ?? data['max_tokens'] ?? 30000; + if (limit is! int || limit < 1) throw const FormatException('输出上限必须是正整数'); + diagnostic.addAll({ + 'tool_count': toolList.length, + 'tool_choice': selected ?? (choice is String ? choice : 'auto'), + 'output_limit': limit, + }); + final hasTools = tools is List && tools.isNotEmpty && data['tool_choice'] != 'none'; + if (hasTools) { + messages = [ + ...messages, + { + 'role': 'system', + 'content': '需要调用工具时,只输出 JSON:' + '{"tool_calls":[{"name":"工具名","arguments":{}}]}。' + '如果需要通过工具查看文件或执行操作,本轮必须输出工具调用,不能只描述接下来要做什么;完成后再总结。' + '不需要工具时正常回答。tool_choice: ${jsonEncode(data['tool_choice'] ?? 'auto')}。' + '工具:${jsonEncode(tools)}', + } + ]; + } + final upstreamMessages = messages.map((dynamic m) { + if (m['role'] == 'tool') { + return { + 'role': 'user', + 'content': '工具 ${m['name'] ?? m['tool_call_id']} 返回:${m['content']}', + }; + } + if (m['role'] == 'assistant' && m['tool_calls'] != null) { + return { + 'role': 'assistant', + 'content': '${m['content'] ?? ''}\n已请求调用工具:${jsonEncode(m['tool_calls'])}', + }; + } + return m; + }).toList(); + final root = _routes[model] ?? + (RegExp(r'^(gpt|o3|o4-mini)', caseSensitive: false).hasMatch(model) + ? 'azure' + : 'xinference'); + final wantsStream = data['stream'] == true; + streamClient = _clientFactory()..connectionTimeout = const Duration(seconds: 10); + _streams.add(streamClient); + unawaited( + request.response.done.then( + (_) { + if (!completed) diagnostic['cancelled'] = true; + closeStream(); + }, + onError: (Object error, StackTrace stack) { + diagnostic['cancelled'] = true; + closeStream(); + }, + ), + ); + if (wantsStream) { + streaming = true; + request.response.headers.contentType = + ContentType('text', 'event-stream', charset: 'utf-8'); + request.response.headers.set(HttpHeaders.cacheControlHeader, 'no-cache'); + request.response.headers.set('X-Accel-Buffering', 'no'); + request.response.bufferOutput = false; + sse = StreamController>(onCancel: cancelRequest); + ssePump = request.response.addStream(sse.stream).then( + (_) { + if (!completed) cancelRequest(); + }, + onError: (Object error, StackTrace stack) => cancelRequest(), + ); + writeSse(': keep-alive\n\n'); + heartbeat = Timer.periodic(heartbeatInterval, (timer) { + if (!cancelled.isCompleted) writeSse(': keep-alive\n\n'); + }); + } + final id = '${isResponses ? 'resp' : 'chatcmpl'}-${DateTime.now().microsecondsSinceEpoch}'; + final created = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final content = StringBuffer(); + final reasoning = StringBuffer(); + Future emit(Object event, [String? name]) async { + if (name != null) writeSse('event: $name\n'); + writeSse('data: ${event is String ? event : jsonEncode(event)}\n\n'); + } + + Map chunk(Map delta, [String? finish]) => { + 'id': id, + 'object': 'chat.completion.chunk', + 'created': created, + 'model': model, + 'choices': [ + {'index': 0, 'delta': delta, 'finish_reason': finish}, + ], + }; + if (wantsStream && isResponses) { + await emit( + { + 'type': 'response.created', + 'sequence_number': 0, + 'response': { + 'id': id, + 'object': 'response', + 'status': 'in_progress', + 'output': [], + }, + }, + 'response.created', + ); + } + String? upstreamFinish; + var sawDone = false; + var nativeCalls = GenaiToolAccumulator(); + for (var attempt = 1; attempt <= 2; attempt++) { + if (cancelled.isCompleted) throw const HttpException('Client disconnected'); + diagnostic['attempts'] = attempt; + if (attempt > 1) { + streamClient!.close(force: true); + _streams.remove(streamClient); + streamClient = _clientFactory()..connectionTimeout = const Duration(seconds: 10); + _streams.add(streamClient); + content.clear(); + reasoning.clear(); + nativeCalls = GenaiToolAccumulator(); + upstreamFinish = null; + sawDone = false; + } + var published = false; + final upstreamResponse = await Future.any([ + cancelled.future + .then((_) => throw const HttpException('Client disconnected')), + _upstream( + '/htk/chat/start/chat', + client: streamClient, + body: { + 'chatInfo': '', + 'messages': upstreamMessages, + 'type': '3', + 'stream': true, + 'aiType': model, + 'aiSecType': '1', + 'promptTokens': 0, + 'rootAiType': root, + 'maxToken': limit, + }, + ), + ]); + diagnostic['connect_ms'] = watch.elapsedMilliseconds; + if (upstreamResponse.statusCode != 200) { + await upstreamResponse.drain(); + throw FormatException('GenAI 返回 ${upstreamResponse.statusCode}'); + } + + await for (final line in upstreamResponse + .transform(utf8.decoder) + .transform(const LineSplitter()) + .timeout(const Duration(seconds: 180))) { + final text = line.startsWith('data:') ? line.substring(5).trim() : line.trim(); + if (text == '[DONE]') { + sawDone = true; + break; + } + if (text.isEmpty) continue; + dynamic event; + try { + event = jsonDecode(text); + } on FormatException { + continue; + } + if (event is! Map) continue; + if (event['errMsg'] != null || event['success'] == false || event['error'] != null) { + throw FormatException('${event['errMsg'] ?? event['message'] ?? event['error']}'); + } + final choices = event['choices']; + if (choices is! List || choices.isEmpty) continue; + final choice = choices.first as Map; + final delta = choice['delta'] ?? choice['message']; + if (delta is Map) { + final fragments = delta['tool_calls'] ?? + (delta['function_call'] == null + ? null + : [ + {'index': 0, 'function': delta['function_call']}, + ]); + nativeCalls.add(fragments); + if (nativeCalls.isNotEmpty && !hasTools) throw const FormatException('本次请求未启用工具'); + final body = delta['content']; + final thought = delta['reasoning'] ?? delta['reasoning_content']; + if (body is String && body.isNotEmpty) { + diagnostic.putIfAbsent('first_content_ms', () => watch.elapsedMilliseconds); + content.write(body); + } + if (thought is String) reasoning.write(thought); + if (wantsStream && !hasTools && !isResponses && content.toString().trim().isNotEmpty) { + await emit( + chunk({ + 'role': 'assistant', + if (body is String) 'content': published ? body : content.toString(), + if (reasoning.isNotEmpty) + 'reasoning_content': published ? (thought ?? '') : reasoning.toString(), + }), + ); + published = true; + } + } + if (choice['finish_reason'] != null) { + upstreamFinish = choice['finish_reason'].toString(); + break; + } + } + final empty = content.toString().trim().isEmpty && !nativeCalls.isNotEmpty; + final normalEnd = upstreamFinish == 'stop' || (upstreamFinish == null && sawDone); + if (empty && normalEnd && attempt == 1) continue; + break; + } + diagnostic.addAll({ + 'content_chars': content.length, + 'upstream_finish_reason': upstreamFinish, + 'saw_done': sawDone, + }); + if (upstreamFinish == null && !sawDone) { + throw const FormatException('GenAI 回复中断'); + } + if (content.toString().trim().isEmpty && !nativeCalls.isNotEmpty) { + throw const FormatException('GenAI 没有回复,请重试'); + } + heartbeat?.cancel(); + final truncated = upstreamFinish != null && + upstreamFinish != 'stop' && + upstreamFinish != 'tool_calls' && + upstreamFinish != 'function_call'; + if (hasTools && + truncated && + (nativeCalls.isNotEmpty || looksLikeToolProtocol(content.toString()))) { + throw const FormatException('工具调用未完成,请重试'); + } + final calls = hasTools && !truncated + ? parseGenaiToolCalls( + nativeCalls.isNotEmpty + ? jsonEncode({'tool_calls': nativeCalls.result()}) + : content.toString(), + allowed, + choice, + ) + : >[]; + if ((upstreamFinish == 'tool_calls' || upstreamFinish == 'function_call') && calls.isEmpty) { + throw const FormatException('GenAI 未返回完整工具调用'); + } + diagnostic['call_count'] = calls.length; + final finish = truncated + ? upstreamFinish + : calls.isEmpty + ? (upstreamFinish ?? 'stop') + : 'tool_calls'; + if (isResponses) { + final response = { + 'id': id, + 'object': 'response', + 'created_at': created, + 'status': truncated ? 'incomplete' : 'completed', + if (truncated) + 'incomplete_details': {'reason': finish == 'length' ? 'max_output_tokens' : finish}, + 'model': model, + 'output_text': calls.isEmpty ? content.toString() : '', + 'output': [ + for (final call in calls) + { + 'id': 'fc_${call['id']}', + 'type': 'function_call', + 'status': 'completed', + 'call_id': call['id'], + 'name': call['function']['name'], + 'arguments': call['function']['arguments'], + }, + if (calls.isEmpty) + { + 'id': 'msg_$id', + 'type': 'message', + 'role': 'assistant', + 'status': truncated ? 'incomplete' : 'completed', + 'content': [ + {'type': 'output_text', 'text': content.toString(), 'annotations': []}, + ], + }, + ], + }; + if (wantsStream) { + var sequence = 1; + Future responseEvent(String type, Map fields) => + emit({'type': type, 'sequence_number': sequence++, ...fields}, type); + final output = response['output'] as List; + for (var i = 0; i < output.length; i++) { + final item = output[i] as Map; + final isCall = item['type'] == 'function_call'; + await responseEvent('response.output_item.added', { + 'output_index': i, + 'item': { + ...item, + 'status': 'in_progress', + if (isCall) 'arguments': '', + if (!isCall) 'content': [], + }, + }); + if (isCall) { + await responseEvent( + 'response.function_call_arguments.delta', + {'item_id': item['id'], 'output_index': i, 'delta': item['arguments']}, + ); + await responseEvent( + 'response.function_call_arguments.done', + {'item_id': item['id'], 'output_index': i, 'arguments': item['arguments']}, + ); + } else { + final part = (item['content'] as List).first; + final fields = {'item_id': item['id'], 'output_index': i, 'content_index': 0}; + await responseEvent('response.content_part.added', { + ...fields, + 'part': {'type': 'output_text', 'text': '', 'annotations': []}, + }); + await responseEvent( + 'response.output_text.delta', + {...fields, 'delta': content.toString()}, + ); + await responseEvent( + 'response.output_text.done', + {...fields, 'text': content.toString()}, + ); + await responseEvent('response.content_part.done', {...fields, 'part': part}); + } + await responseEvent('response.output_item.done', {'output_index': i, 'item': item}); + } + final terminal = truncated ? 'response.incomplete' : 'response.completed'; + await responseEvent(terminal, {'response': response}); + } else { + _json(request.response, response); + } + } else if (wantsStream) { + if (hasTools) { + await emit( + chunk( + calls.isEmpty + ? {'content': content.toString()} + : { + 'tool_calls': [ + for (var i = 0; i < calls.length; i++) {'index': i, ...calls[i]}, + ], + }, + ), + ); + } + await emit(chunk({}, finish)); + await emit('[DONE]'); + } else { + _json(request.response, { + 'id': id, + 'object': 'chat.completion', + 'created': created, + 'model': model, + 'choices': [ + { + 'index': 0, + 'finish_reason': finish, + 'message': { + 'role': 'assistant', + 'content': calls.isEmpty ? content.toString() : null, + if (calls.isNotEmpty) 'tool_calls': calls, + if (reasoning.isNotEmpty) 'reasoning_content': reasoning.toString(), + }, + } + ], + }); + } + completed = true; + } catch (e) { + diagnostic['exception_category'] = e.runtimeType.toString(); + final message = e is FormatException ? e.message : '请求失败,请重试'; + try { + if (streaming) { + if (request.uri.path == '/v1/responses') { + writeSse('event: response.failed\ndata: ${jsonEncode({ + 'type': 'response.failed', + 'response': { + 'object': 'response', + 'status': 'failed', + 'error': {'code': 'upstream_error', 'message': message}, + }, + })}\n\n'); + } else { + writeSse('data: ${jsonEncode({ + 'error': {'message': message, 'type': 'upstream_error'}, + })}\n\ndata: [DONE]\n\n'); + } + } else { + _json( + request.response, + { + if (request.uri.path == '/v1/responses') ...{ + 'id': 'resp_${diagnostic['request_id']}', + 'object': 'response', + 'status': 'failed', + 'output': [], + }, + 'error': {'message': message, 'code': 'upstream_error'}, + }, + e is FormatException ? 400 : 502, + ); + } + } catch (_) {/* Client already disconnected. */} + } finally { + completed = true; + await sse?.close(); + await ssePump; + diagnostic['completion_ms'] = watch.elapsedMilliseconds; + try { + onDiagnostic?.call(Map.unmodifiable(diagnostic)); + } catch (_) {} + closeStream(); + try { + await request.response.close(); + } catch (_) {/* Client disconnected. */} + } + } + + List> _responseMessages(Map data) { + final input = data['input']; + return [ + if (data['instructions'] is String) {'role': 'system', 'content': data['instructions']}, + if (input is String) {'role': 'user', 'content': input}, + if (input is List) + for (final m in input.whereType>()) + if (m['type'] == 'function_call') + { + 'role': 'assistant', + 'tool_calls': [ + { + 'id': m['call_id'], + 'type': 'function', + 'function': {'name': m['name'], 'arguments': m['arguments']}, + } + ], + } + else if (m['type'] == 'function_call_output') + { + 'role': 'tool', + 'tool_call_id': m['call_id'], + 'content': m['output'] is String ? m['output'] : jsonEncode(m['output']), + } + else + { + 'role': m['role'] ?? 'user', + 'content': m['content'] is List + ? (m['content'] as List) + .whereType>() + .map((part) => part['text'] ?? '') + .join('\n') + : m['content'], + }, + ]; + } +} diff --git a/lib/services/genai/genai_login.dart b/lib/services/genai/genai_login.dart new file mode 100644 index 00000000..dac0956e --- /dev/null +++ b/lib/services/genai/genai_login.dart @@ -0,0 +1,118 @@ +// Adapted from GenAI2OpenAI's CAS login. See third_party/GenAI2OpenAI/LICENSE. +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:pointycastle/export.dart'; + +class GenaiLogin { + GenaiLogin({HttpClient Function()? clientFactory, Uri? genaiBase, Uri? idsBase}) + : _clientFactory = clientFactory ?? HttpClient.new, + _genaiBase = genaiBase ?? Uri.parse('https://genai.shanghaitech.edu.cn'), + _idsBase = idsBase ?? Uri.parse('https://ids.shanghaitech.edu.cn'); + + final HttpClient Function() _clientFactory; + final Uri _genaiBase; + final Uri _idsBase; + + static String encryptPassword(String password, String salt) { + final cipher = PaddedBlockCipher('AES/CBC/PKCS7') + ..init( + true, + PaddedBlockCipherParameters( + ParametersWithIV( + KeyParameter(Uint8List.fromList(utf8.encode(salt))), + Uint8List.fromList(utf8.encode('Nu1LNu1LNu1LNu1L')), + ), + null, + ), + ); + return base64Encode( + cipher.process(Uint8List.fromList(utf8.encode('${List.filled(16, 'Nu1L').join()}$password'))), + ); + } + + static String field(String html, String name) { + final input = RegExp(r']*>', caseSensitive: false) + .allMatches(html) + .map((m) => m.group(0)!) + .where( + (tag) => RegExp('(?:name|id)=["\u0027]${RegExp.escape(name)}["\u0027]').hasMatch(tag), + ); + if (input.isEmpty) return ''; + return RegExp('value=["\u0027]([^"\u0027]*)["\u0027]').firstMatch(input.first)?.group(1) ?? ''; + } + + Future login(String account, String password) async { + final client = _clientFactory()..connectionTimeout = const Duration(seconds: 15); + final cookies = >{}; + Future<({HttpClientResponse response, String body})> request(Uri uri, {String? form}) async { + final req = await client.openUrl(form == null ? 'GET' : 'POST', uri); + req.followRedirects = false; + req.headers.set(HttpHeaders.userAgentHeader, 'Mozilla/5.0 TechPie'); + req.cookies.addAll(cookies[uri.host]?.values ?? []); + if (form != null) { + req.headers.contentType = + ContentType('application', 'x-www-form-urlencoded', charset: 'utf-8'); + req.write(form); + } + final res = await req.close().timeout(const Duration(seconds: 30)); + for (final cookie in res.cookies) { + (cookies[uri.host] ??= {})[cookie.name] = cookie; + } + return ( + response: res, + body: await utf8.decoder.bind(res).join().timeout(const Duration(seconds: 30)) + ); + } + + try { + var uri = _genaiBase.resolve('/htk/user/login'); + var result = await request(uri); + for (var i = 0; i < 12; i++) { + final token = uri.queryParameters['token']; + if (token != null && token.isNotEmpty) return token; + final location = result.response.headers.value(HttpHeaders.locationHeader); + if (result.response.statusCode >= 300 && + result.response.statusCode < 400 && + location != null) { + uri = uri.resolve(location); + final redirectedToken = uri.queryParameters['token']; + if (redirectedToken != null && redirectedToken.isNotEmpty) return redirectedToken; + result = await request(uri); + continue; + } + final salt = field(result.body, 'pwdEncryptSalt'); + final execution = field(result.body, 'execution'); + if (salt.isNotEmpty && execution.isNotEmpty) { + final form = Uri( + queryParameters: { + 'username': account.trim(), + 'password': encryptPassword(password, salt), + 'lt': field(result.body, 'lt'), + 'dllt': 'generalLogin', + 'execution': execution, + '_eventId': 'submit', + 'rmShown': '1', + }, + ).query; + result = await request(uri, form: form); + if (result.response.statusCode < 300 || result.response.statusCode >= 400) { + if (result.body.contains('captcha') || result.body.contains('验证码')) { + throw const FormatException('请在网页登录后重试'); + } + throw const FormatException('学号或密码不对'); + } + continue; + } + final service = RegExp(r'var service = \["(.*?)"').firstMatch(result.body)?.group(1); + if (service == null) throw const FormatException('登录失败,请重试'); + uri = _idsBase.resolve('/authserver/login?service=$service'); + result = await request(uri); + } + throw const FormatException('登录失败,请重试'); + } finally { + client.close(force: true); + } + } +} diff --git a/lib/services/genai/genai_tools.dart b/lib/services/genai/genai_tools.dart new file mode 100644 index 00000000..1292b2eb --- /dev/null +++ b/lib/services/genai/genai_tools.dart @@ -0,0 +1,173 @@ +import 'dart:convert'; + +bool _isToolObject(dynamic value) => + value is Map && + ((value['function'] is Map && (value['function'] as Map).containsKey('name')) || + (value.containsKey('name') && value.containsKey('arguments'))); + +bool looksLikeToolProtocol(String text) => + text.contains('') || + (RegExp(r'^\s*[\[{]\s*(?:[\[{" ]|$)').hasMatch(text) && + RegExp(r'"tool_calls"\s*:|"function"\s*:\s*\{|"name"\s*:\s*"[^"\n]+"\s*,\s*"arguments"\s*:') + .hasMatch(text)); + +/// Only missing outer array/wrapper closures may be added. Calls, arguments, +/// strings and comma-separated values must already be complete. +dynamic _repairWrapper(String text, List stack, bool quoted) { + final shape = stack.join(); + if (quoted || !['[', '{', '{['].contains(shape)) return null; + try { + final suffix = stack.reversed.map((c) => c == '[' ? ']' : '}').join(); + final value = jsonDecode(text + suffix); + final calls = value is Map ? value['tool_calls'] : value; + if (value is Map && (value.length != 1 || !value.containsKey('tool_calls'))) return null; + if (calls is! List || calls.isEmpty || !calls.every(_isToolObject)) return null; + return value; + } on FormatException { + return null; + } +} + +/// Parses outer containers atomically, never salvaging a truncated inner call. +/// Validates declared names and object arguments, not full JSON Schema. +List> parseGenaiToolCalls(String text, Set allowed, dynamic choice) { + final values = []; + final xml = text.contains(''); + final blocks = xml + ? RegExp(r'\s*([\s\S]*?)\s*') + .allMatches(text) + .map((m) => m[1]!) + .toList() + : [text]; + if (xml && blocks.length != ''.allMatches(text).length) { + throw const FormatException('工具调用未完成'); + } + for (final block in blocks) { + var cursor = 0; + while (cursor < block.length) { + final start = block.indexOf(RegExp(r'[\[{]'), cursor); + if (start < 0) break; + final stack = []; + var quoted = false; + var escaped = false; + var end = -1; + for (var i = start; i < block.length; i++) { + final c = block[i]; + if (quoted) { + if (escaped) { + escaped = false; + } else if (c == '\\') { + escaped = true; + } else if (c == '"') { + quoted = false; + } + continue; + } + if (c == '"') { + quoted = true; + continue; + } + if (c == '{' || c == '[') stack.add(c); + if (c == '}' || c == ']') { + if (stack.isEmpty || (stack.removeLast() == '{' ? c != '}' : c != ']')) break; + if (stack.isEmpty) { + end = i + 1; + break; + } + } + } + dynamic repaired; + if (end < 0) { + if (xml || looksLikeToolProtocol(block.substring(start))) { + repaired = _repairWrapper(block.substring(start), stack, quoted); + if (repaired == null) throw const FormatException('工具调用 JSON 未完成'); + end = block.length; + } else { + break; + } + } + final segment = block.substring(start, end); + try { + final value = repaired ?? jsonDecode(segment); + if (value is Map && value.containsKey('tool_calls')) { + if (value['tool_calls'] is! List) throw const FormatException('tool_calls 必须是数组'); + values.addAll(value['tool_calls'] as List); + } else if (_isToolObject(value) || (xml && value is Map && value.containsKey('name'))) { + values.add(value); + } else if (value is List && value.any(_isToolObject)) { + values.addAll(value); + } else if (xml) { + throw const FormatException('工具调用格式不对'); + } + } on FormatException { + if (xml || looksLikeToolProtocol(segment)) rethrow; + } + cursor = end; + } + } + final calls = >[]; + for (final raw in values) { + if (raw is! Map) throw const FormatException('工具调用必须是对象'); + final function = raw['function'] is Map ? raw['function'] as Map : raw; + final name = function['name']; + if (name is! String || !allowed.contains(name)) throw const FormatException('工具名称不在本次请求中'); + dynamic args = function['arguments'] ?? {}; + if (args is String) args = jsonDecode(args); + if (args is! Map) throw const FormatException('工具参数必须是 JSON 对象'); + calls.add({ + 'id': raw['id'] is String && (raw['id'] as String).isNotEmpty + ? raw['id'] + : 'call_${DateTime.now().microsecondsSinceEpoch}_${calls.length}', + 'type': 'function', + 'function': {'name': name, 'arguments': jsonEncode(args)}, + }); + } + final selected = choice is Map + ? (choice['function'] is Map ? choice['function']['name'] : choice['name']) + : null; + if ((choice == 'required' && calls.isEmpty) || + (selected != null && + (calls.isEmpty || calls.any((c) => c['function']['name'] != selected)))) { + throw const FormatException('GenAI 未返回指定工具调用'); + } + return calls; +} + +/// Aggregate native tool deltas by index before validating their full arguments. +class GenaiToolAccumulator { + final _calls = >{}; + bool get isNotEmpty => _calls.isNotEmpty; + void add(dynamic fragments) { + if (fragments == null) return; + if (fragments is! List) throw const FormatException('工具增量必须是数组'); + for (var position = 0; position < fragments.length; position++) { + final fragment = fragments[position]; + if (fragment is! Map) throw const FormatException('工具增量格式不对'); + final index = fragment['index'] ?? position; + if (index is! int || index < 0) throw const FormatException('工具序号不对'); + final call = _calls.putIfAbsent( + index, + () => { + 'type': 'function', + 'function': {'name': '', 'arguments': ''}, + }, + ); + if (fragment['id'] is String && (fragment['id'] as String).isNotEmpty) { + call['id'] = fragment['id']; + } + final function = fragment['function']; + if (function is! Map) continue; + for (final field in ['name', 'arguments']) { + dynamic value = function[field]; + if (value == null) continue; + if (field == 'arguments' && value is Map) value = jsonEncode(value); + if (value is! String) throw const FormatException('工具增量字段格式不对'); + final target = call['function'] as Map; + target[field] = (target[field] as String) + value; + } + } + } + + List> result() => + [for (final index in (_calls.keys.toList()..sort())) _calls[index]!]; +} diff --git a/lib/services/genai_api_service.dart b/lib/services/genai_api_service.dart new file mode 100644 index 00000000..f5055de5 --- /dev/null +++ b/lib/services/genai_api_service.dart @@ -0,0 +1,161 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/foundation.dart'; + +import 'genai/genai_gateway.dart'; +import 'genai/genai_login.dart'; +import 'storage_service.dart'; + +class GenaiApiService extends ChangeNotifier { + GenaiApiService(this.storage, {GenaiGateway? gateway, GenaiLogin? login}) + : _gateway = gateway ?? + GenaiGateway( + onDiagnostic: (metadata) { + // Request metadata only; never log prompts, tool results or credentials. + stdout.writeln('genai_request ${jsonEncode(metadata)}'); + }, + ), + _login = login ?? GenaiLogin(); + + final StorageService storage; + final GenaiGateway _gateway; + final GenaiLogin _login; + Future? _loading; + bool _disposed = false; + bool busy = false; + String? error; + String? _genaiToken; + String _apiToken = ''; + String _host = '127.0.0.1'; + int _port = 5000; + + bool get running => _gateway.running; + bool get loggedIn => (_genaiToken ?? '').isNotEmpty; + String get host => _host; + int get port => _port; + String get apiToken => _apiToken; + String get endpoint => 'http://127.0.0.1:${_gateway.port ?? _port}/v1'; + + void _notify() { + if (!_disposed) notifyListeners(); + } + + Future load() => _loading ??= _load(); + Future _load() async { + try { + _genaiToken = await storage.loadGenaiToken(); + _apiToken = await storage.loadGenaiApiToken() ?? ''; + if (_apiToken.isEmpty) { + final random = Random.secure(); + _apiToken = + 'sk-${List.generate(24, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0')).join()}'; + await storage.saveGenaiApiToken(_apiToken); + } + _host = storage.genaiApiHost; + _port = storage.genaiApiPort; + } catch (_) { + _loading = null; + error = '读取设置失败,请重试'; + rethrow; + } finally { + _notify(); + } + } + + Future login(String account, String password) async { + if (busy || running) return false; + if (account.trim().isEmpty || password.isEmpty) { + error = '请输入学号和密码'; + _notify(); + return false; + } + busy = true; + error = null; + _notify(); + try { + final token = await _login.login(account, password); + await storage.saveGenaiToken(token); + _genaiToken = token; + return true; + } on FormatException catch (e) { + error = e.message; + return false; + } catch (_) { + error = '登录失败,请重试'; + return false; + } finally { + busy = false; + _notify(); + } + } + + Future logout() async { + if (busy) return; + await stop(); + await storage.clearGenaiToken(); + _genaiToken = null; + error = null; + _notify(); + } + + Future saveSettings({ + required String apiToken, + required String port, + required String host, + }) async { + if (running) return; + final parsed = int.tryParse(port); + if (parsed == null || parsed < 1 || parsed > 65535) { + throw const FormatException('端口填 1–65535'); + } + if (apiToken.trim().isEmpty) throw const FormatException('请输入 API Token'); + final nextHost = host == '0.0.0.0' ? host : '127.0.0.1'; + await storage.saveGenaiApiToken(apiToken.trim()); + await storage.setGenaiApiPort(parsed); + await storage.setGenaiApiHost(nextHost); + _apiToken = apiToken.trim(); + _port = parsed; + _host = nextHost; + _notify(); + } + + Future start() async { + if (busy || running) return running; + busy = true; + error = null; + _notify(); + try { + await load(); + if (!loggedIn) throw const FormatException('请先登录 GenAI'); + await _gateway.start(host: _host, port: _port, genaiToken: _genaiToken!, apiToken: _apiToken); + return true; + } on FormatException catch (e) { + error = e.message; + return false; + } on SocketException catch (_) { + error = '端口已占用,换一个试试'; + return false; + } catch (_) { + error = '启动失败,请重试'; + return false; + } finally { + busy = false; + _notify(); + } + } + + Future stop() async { + await _gateway.stop(); + _notify(); + } + + @override + void dispose() { + _disposed = true; + unawaited(_gateway.stop()); + super.dispose(); + } +} diff --git a/lib/services/http_client.dart b/lib/services/http_client.dart index 72799b95..137f81db 100644 --- a/lib/services/http_client.dart +++ b/lib/services/http_client.dart @@ -1,9 +1,27 @@ import 'dart:convert'; +import 'dart:io'; import 'package:http/http.dart' as http; import 'debug_logger.dart'; +String _appProxy = ''; + +class TechPieHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + final client = super.createHttpClient(context); + // Read the current choice on every request, including existing clients. + client.findProxy = (_) => _appProxy.isEmpty ? 'DIRECT' : 'PROXY $_appProxy'; + return client; + } +} + +void configureAppProxy(String value) { + _appProxy = value.trim(); + HttpOverrides.global = TechPieHttpOverrides(); +} + class LoggingHttpClient { final http.Client _inner; final DebugLogger _logger; diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..f49da76e 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -3,7 +3,9 @@ import 'package:flutter/widgets.dart'; import 'assignment_service.dart'; import 'auth_service.dart'; import 'campus_card_service.dart'; +import 'deadline_widget_service.dart'; import 'debug_logger.dart'; +import 'genai_api_service.dart'; import 'ecard_bind_service.dart'; import 'ecard_widget_service.dart'; import 'egate_app_service.dart'; @@ -15,6 +17,7 @@ import 'theme_service.dart'; import 'third_party_auth_service.dart'; import 'uni_auth_service.dart'; import 'update_service.dart'; +import 'wear/wear_engine_service.dart'; class ServiceProvider extends InheritedWidget { final AuthService authService; @@ -32,6 +35,9 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final WearEngineService? wearEngineService; + final DeadlineWidgetService? deadlineWidgetService; + final GenaiApiService? genaiApiService; const ServiceProvider({ super.key, @@ -50,6 +56,9 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.wearEngineService, + this.deadlineWidgetService, + this.genaiApiService, required super.child, }); @@ -76,5 +85,8 @@ class ServiceProvider extends InheritedWidget { updateService != oldWidget.updateService || campusCardService != oldWidget.campusCardService || ecardBindService != oldWidget.ecardBindService || - ecardWidgetService != oldWidget.ecardWidgetService; + ecardWidgetService != oldWidget.ecardWidgetService || + wearEngineService != oldWidget.wearEngineService || + deadlineWidgetService != oldWidget.deadlineWidgetService || + genaiApiService != oldWidget.genaiApiService; } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index b42ed5c3..bbdb68c2 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -33,6 +33,10 @@ class StorageService { static const _syncMasterKeyKey = 'sync_master_key'; // secure storage static const _deviceIdKey = 'device_id'; static const _maskPersonalInfoKey = 'mask_personal_info'; + static const _proxyUrlKey = 'app_proxy_url'; + static const _proxyEnabledKey = 'app_proxy_enabled'; + static const _genaiApiPortKey = 'genai_api_port'; + static const _genaiApiHostKey = 'genai_api_host'; final FlutterSecureStorage _secure; final SharedPreferences _prefs; @@ -203,11 +207,26 @@ class StorageService { Future setMaskPersonalInfo(bool value) => _prefs.setBool(_maskPersonalInfoKey, value); + String get appProxyUrl => _prefs.getString(_proxyUrlKey) ?? ''; + Future setAppProxyUrl(String value) => _prefs.setString(_proxyUrlKey, value); + bool get appProxyEnabled => _prefs.getBool(_proxyEnabledKey) ?? false; + Future setAppProxyEnabled(bool value) => _prefs.setBool(_proxyEnabledKey, value); + bool get useLocalhost => !kReleaseMode && (_prefs.getBool(_useLocalhostKey) ?? false); Future setUseLocalhost(bool value) => _prefs.setBool(_useLocalhostKey, value); + String get genaiApiHost => _prefs.getString(_genaiApiHostKey) ?? '127.0.0.1'; + Future setGenaiApiHost(String value) => _prefs.setString(_genaiApiHostKey, value); + int get genaiApiPort => _prefs.getInt(_genaiApiPortKey) ?? 5000; + Future setGenaiApiPort(int value) => _prefs.setInt(_genaiApiPortKey, value); + Future loadGenaiToken() => _secure.read(key: 'genai_upstream_token'); + Future saveGenaiToken(String value) => _secure.write(key: 'genai_upstream_token', value: value); + Future clearGenaiToken() => _secure.delete(key: 'genai_upstream_token'); + Future loadGenaiApiToken() => _secure.read(key: 'genai_local_api_token'); + Future saveGenaiApiToken(String value) => _secure.write(key: 'genai_local_api_token', value: value); + // Cloud-sync settings. The master-password-derived key is the one sensitive // piece — it lives in secure storage, never in SharedPreferences. bool get syncEnabled => _prefs.getBool(_syncEnabledKey) ?? false; @@ -315,6 +334,14 @@ class StorageService { // Assignments cache (non-sensitive — stored as JSON in SharedPreferences) static const _assignmentsKey = 'cached_assignments'; + bool get hasCachedAssignments => _prefs.containsKey(_assignmentsKey); + + bool get deadlineWidgetsEnabled => _prefs.getBool('deadline_widgets_enabled') ?? false; + + Future setDeadlineWidgetsEnabled(bool enabled) async { + await _prefs.setBool('deadline_widgets_enabled', enabled); + } + Future saveCachedAssignments(List> items) => _prefs.setString(_assignmentsKey, jsonEncode(items)); diff --git a/lib/services/uni_auth_service.dart b/lib/services/uni_auth_service.dart index b68ffbd9..ccd81263 100644 --- a/lib/services/uni_auth_service.dart +++ b/lib/services/uni_auth_service.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:casdoor_flutter_sdk/casdoor_flutter_sdk.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import '../pages/macos_casdoor_auth_page.dart'; @@ -69,7 +70,13 @@ class UniAuthService extends ChangeNotifier { bool get loading => _loading; - UniAuthService({DebugLogger? logger}) : _logger = logger; + UniAuthService({DebugLogger? logger, String proxyUrl = ''}) + : _logger = logger, + _proxyUrl = proxyUrl; + + String _proxyUrl; + String get proxyUrl => _proxyUrl; + void setProxyUrl(String value) => _proxyUrl = value.trim(); final DebugLogger? _logger; @@ -142,6 +149,17 @@ class UniAuthService extends ChangeNotifier { callbackUrl = await _showOhosLogin(navigator, casdoor); } else if (defaultTargetPlatform == TargetPlatform.macOS) { callbackUrl = await _showMacosLogin(navigator, casdoor); + } else if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) { + try { + callbackUrl = await const MethodChannel('techpie/uni_auth') + .invokeMethod('authenticate', { + 'url': casdoor.getSigninUrl().toString(), + 'proxy': proxyUrl, + }) ?? ''; + } on PlatformException catch (error) { + if (error.code == 'CANCELLED') throw CasdoorAuthCancelledException(); + rethrow; + } } else { callbackUrl = await casdoor.showFullscreen(context); } diff --git a/lib/services/wear/android_wear_transport.dart b/lib/services/wear/android_wear_transport.dart new file mode 100644 index 00000000..57950655 --- /dev/null +++ b/lib/services/wear/android_wear_transport.dart @@ -0,0 +1,99 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'wear_protocol.dart'; + +class AndroidWearTransport implements WearTransport { + AndroidWearTransport({MethodChannel? channel}) + : _channel = channel ?? const MethodChannel('techpie/wear_engine') { + _channel.setMethodCallHandler((call) async { + if (call.method == 'frame' && call.arguments is Uint8List) { + _frames.add(call.arguments as Uint8List); + } else if (call.method == 'state' && call.arguments is Map) { + _states.add(Map.from(call.arguments as Map)); + } + }); + } + final MethodChannel _channel; + final _frames = StreamController.broadcast(); + final _states = StreamController>.broadcast(); + @override + Stream get frames => _frames.stream; + @override + Stream> get states => _states.stream; + Future _call(String method, [Object? args]) async { + try { + return await _channel.invokeMethod(method, args); + } on MissingPluginException { + throw const WearFailure('SERVICE_UNAVAILABLE'); + } on PlatformException catch (error) { + throw WearFailure( + error.code, + nativeCode: error.details is int ? error.details as int : null, + retryable: const { + 'SERVICE_UNAVAILABLE', + 'DEVICE_DISCONNECTED', + 'TRANSPORT_FAILED', + }.contains(error.code), + ); + } + } + + @override + Future> status() async => Map.from( + await _call>('status') ?? {}, + ); + @override + Future>> devices() async => + (await _call>('devices') ?? []) + .map((e) => Map.from(e as Map)) + .toList(); + @override + Future> authorize({required bool notify}) async => + Map.from( + await _call>('authorize', {'notify': notify}) ?? + {}, + ); + @override + Future open(String deviceId, String fingerprint) async => + _call('open', {'deviceId': deviceId, 'fingerprint': fingerprint}); + @override + Future send(Uint8List bytes) async => + _call('send', {'bytes': bytes}); + @override + Future close() async => _call('close'); + @override + Future scheduleReminders(Map spec) async => + _call('scheduleReminders', {'json': jsonEncode(spec)}); + @override + Future cancelReminders() async => _call('cancelReminders'); + @override + Future sendReminder(String id) async => + await _call('sendReminder', { + 'json': jsonEncode({'reminderId': id}), + }) ?? + 'deliveryUnknown'; + @override + void dispose() { + _channel.setMethodCallHandler(null); + unawaited(_frames.close()); + unawaited(_states.close()); + } +} + +class PreferencesWearMetadata implements WearMetadata { + PreferencesWearMetadata(this.preferences); + final SharedPreferences preferences; + static const key = 'techpie.wear.metadata.v1'; + @override + String? read() => preferences.getString(key); + @override + Future write(String value) async { + if (!await preferences.setString(key, value)) { + throw const WearFailure('STORAGE_FAILED'); + } + } +} diff --git a/lib/services/wear/techpie_wear_data_source.dart b/lib/services/wear/techpie_wear_data_source.dart new file mode 100644 index 00000000..5d812409 --- /dev/null +++ b/lib/services/wear/techpie_wear_data_source.dart @@ -0,0 +1,107 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart'; + +import '../../features/campus_card/domain/models/card_models.dart'; +import '../../models/assignment_overrides.dart'; +import '../assignment_service.dart'; +import '../auth_service.dart'; +import '../campus_card_service.dart'; +import '../third_party_auth_service.dart'; +import 'wear_protocol.dart'; + +class TechPieWearDataSource implements WearDataSource { + TechPieWearDataSource({ + required this.auth, + required this.accounts, + required this.assignments, + required this.campusCard, + this.reminderOffsets = const [Duration(hours: 1)], + }); + final AuthService auth; + final ThirdPartyAuthService accounts; + final AssignmentService assignments; + final CampusCardService campusCard; + + /// Product default: one hour before each open deadline; opt-in at WearLink.open. + final List reminderOffsets; + + @override + Future account() async { + final session = auth.session; + if (session == null) throw const WearFailure('ACCOUNT_NOT_READY'); + final campus = accounts.cpdailyNode.account; + // Use a single identity source for both fields, never combine unrelated accounts. + final name = campus == null ? session.userName : campus.name ?? ''; + final studentId = campus == null ? session.studentId : campus.sid ?? ''; + final ecardId = await campusCard.readOpenId(); + return WearAccount( + scope: + jsonEncode([session.userId, campus?.account, campus?.sid, ecardId]), + name: name, + studentId: studentId, + )..toJson(); + } + + @override + Future> deadlines() async { + if (assignments.loading) { + throw const WearFailure('PEER_NOT_READY', retryable: true); + } + if (assignments.error != null || assignments.platformErrors.isNotEmpty) { + throw const WearFailure('SERVICE_UNAVAILABLE', retryable: true); + } + return assignments.visibleAssignments.map((assignment) { + final id = sha256 + .convert(utf8.encode(AssignmentOverrides.keyFor(assignment))) + .toString(); + final complete = assignments.isCompleted(assignment); + return WearDdl( + id: id, + title: _truncate(assignment.title, 80), + courseName: _truncate(assignment.course, 40), + dueAt: assignment.due.toUtc(), + completed: complete, + remindAt: complete + ? [] + : reminderOffsets + .take(3) + .map((offset) => assignment.due.subtract(offset).toUtc()) + .toList(), + ); + }).toList(); + } + + @override + Future campusCode(String purpose) async { + if (purpose != 'campus') throw const WearFailure('UNSUPPORTED_PURPOSE'); + final before = await account(); + final card = await campusCard.runtime.cards.currentCard(); + if (card == null || !card.status.permitsPayment) { + throw const WearFailure('ACCOUNT_NOT_READY'); + } + // Existing eCard is independently bound: only display for the same named campus account. + if (card.ownerName.trim() != before.name.trim()) { + throw const WearFailure('ACCOUNT_NOT_READY'); + } + final frame = await campusCard.runtime.paymentCodes.generateOnlineCode(); + final after = await account(); + if (before.scope != after.scope) { + throw const WearFailure('SESSION_MISMATCH'); + } + // Binary eCard payloads are stored as Latin-1 by the existing QR codec. + // Other online payloads are textual and use their original UTF-8 representation. + final bytes = frame.rawQrCode.startsWith('5638') + ? latin1.encode(frame.qrPayload) + : utf8.encode(frame.qrPayload); + return WearCampusCode( + bytes: Uint8List.fromList(bytes), + issuedAt: frame.generatedAt, + validUntil: frame.generatedAt.add(const Duration(seconds: 30)), + ); + } + + String _truncate(String value, int count) => + String.fromCharCodes(value.runes.take(count)); +} diff --git a/lib/services/wear/wear_engine_service.dart b/lib/services/wear/wear_engine_service.dart new file mode 100644 index 00000000..25fce839 --- /dev/null +++ b/lib/services/wear/wear_engine_service.dart @@ -0,0 +1,893 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; + +import 'wear_protocol.dart'; +import 'wear_qr_matrix.dart'; + +/// Android product services. The transport never decides whether data was applied. +class WearEngineService extends ChangeNotifier { + WearEngineService({ + required this.transport, + required this.source, + required this.metadata, + DateTime Function()? now, + this.timeout = const Duration(seconds: 30), + this.retryDelays = const [Duration(seconds: 2), Duration(seconds: 5)], + }) : now = now ?? DateTime.now { + final raw = metadata.read(); + if (raw != null) { + try { + final stored = jsonDecode(raw) as Map; + _binding = stored['binding'] as String?; + _scopeHash = stored['scopeHash'] as String?; + _pendingClear = stored['pendingClear'] as String?; + for (final resource in ['account', 'ddl']) { + _revisions[resource] = + (stored['revisions'] as Map?)?[resource] as int? ?? 0; + } + } catch (_) { + _binding = null; + _scopeHash = null; + _pendingClear = 'userRevoked'; + } + } + _subscriptions.add( + transport.frames.listen((frame) { + try { + final message = _codec.accept(frame, this.now()); + if (message != null) unawaited(_receive(message)); + } on WearFailure catch (error) { + _error(error); + } + }), + ); + _subscriptions.add( + transport.states.listen((state) { + _native.addAll(state); + if (state['service'] == 'unavailable' || + state['device'] == 'disconnected') { + _invalidate('DEVICE_DISCONNECTED'); + } + _changed(); + }), + ); + } + + final WearTransport transport; + final WearDataSource source; + final WearMetadata metadata; + final DateTime Function() now; + final Duration timeout; + final List retryDelays; + final _codec = WearFrames(); + final List> _subscriptions = []; + final Map _pending = {}; + final Map _replies = {}; + final Map _inbound = {}; + final Map _revisions = {'account': 0, 'ddl': 0}; + final Map _sync = {}; + final Map _native = { + 'service': 'unavailable', + 'device': 'none', + 'permission': {'p2p': false, 'notify': false}, + }; + Future _tx = Future.value(); + Future _refreshTail = Future.value(); + String? _binding, _scopeHash, _session, _device, _pendingClear; + int _epoch = 0; + int _leaseUntil = 0; + int _maxCodeBytes = 512; + bool _ready = false, _opening = false, _disposed = false, _codeBusy = false; + DateTime? _lastCodeRequest; + Set _capabilities = {}; + Map? _lastError; + Timer? _leaseTimer; + Timer? _heartbeatTimer; + bool _heartbeatBusy = false; + Map? _displayAccount; + bool _remindersEnabled = false; + bool get remindersEnabled => ready && _remindersEnabled; + bool supports(String capability) => + ready && _capabilities.contains(capability); + Map? get displayAccount => ready && _displayAccount != null + ? Map.unmodifiable(_displayAccount!) + : null; + bool get ready => _ready && now().millisecondsSinceEpoch < _leaseUntil; + + String _id() { + final random = Random.secure(); + return List.generate( + 12, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + } + + void _changed() { + if (!_disposed) notifyListeners(); + } + + void _error(WearFailure failure) { + _lastError = {'code': failure.code, 'retryable': failure.retryable}; + if (failure.nativeCode != null) { + _lastError!['nativeCode'] = failure.nativeCode; + } + _changed(); + } + + void _invalidate(String reason) { + _epoch++; + _ready = false; + _session = null; + _leaseTimer?.cancel(); + _heartbeatTimer?.cancel(); + _displayAccount = null; + _codec.clear(); + _replies.clear(); + for (final pending in _pending.values) { + if (!pending.done.isCompleted) { + pending.done.completeError(WearFailure(reason, retryable: true)); + } + } + _pending.clear(); + } + + Future _persist() => metadata.write( + jsonEncode({ + 'binding': _binding, + 'scopeHash': _scopeHash, + 'pendingClear': _pendingClear, + 'revisions': _revisions, + }), + ); + Map getStatus() => { + ..._native, + 'peer': ready ? 'ready' : 'waiting', + 'capabilities': _capabilities.toList(), + 'sync': Map.from(_sync), + 'pendingClear': _pendingClear != null, + 'lastError': _lastError, + }; + Future> refreshStatus() async { + try { + _native.addAll(await transport.status().timeout(timeout)); + if (_native['device'] == 'disconnected') { + _invalidate('DEVICE_DISCONNECTED'); + } + } on WearFailure catch (error) { + _error(error); + } on TimeoutException { + _error(const WearFailure('SERVICE_UNAVAILABLE', retryable: true)); + } + _changed(); + return getStatus(); + } + + Future>> devices() => + transport.devices().timeout(timeout); + + /// Called by the device picker before querying devices; never called at boot. + Future> requestPermissions({bool notify = false}) async { + final permissions = + await transport.authorize(notify: notify).timeout(timeout); + _native['permission'] = permissions; + _changed(); + return permissions; + } + + Future open( + String deviceId, { + required String watchFingerprint, + bool notify = false, + }) async { + if (_opening) throw const WearFailure('RATE_LIMITED'); + if (watchFingerprint.isEmpty || + watchFingerprint.length > 512 || + RegExp(r'\s').hasMatch(watchFingerprint)) { + throw const WearFailure('INVALID_PAYLOAD'); + } + _opening = true; + try { + await close(); + var epoch = _epoch; + await requestPermissions(notify: notify); + _remindersEnabled = + notify && (_native['permission'] as Map)['notify'] == true; + if ((_native['permission'] as Map)['p2p'] != true) { + throw const WearFailure('PERMISSION_DENIED'); + } + await transport.open(deviceId, watchFingerprint).timeout(timeout); + _checkEpoch(epoch); + _device = deviceId; + _native.addAll({'service': 'ready', 'device': 'connected'}); + // Drain a durable revocation before binding the newly logged-in account. + if (_pendingClear != null && _binding != null) { + await _handshake(epoch); + await _clearConnected(_pendingClear!); + _invalidate('SESSION_MISMATCH'); + epoch = _epoch; + } + final account = await source.account(); + account.toJson(); + _checkEpoch(epoch); + final scopeHash = sha256.convert(utf8.encode(account.scope)).toString(); + if (_scopeHash != scopeHash || _binding == null) { + await transport.cancelReminders(); + _checkEpoch(epoch); + _scopeHash = scopeHash; + _binding = _id(); + _revisions.updateAll((_, __) => 0); + _sync.clear(); + } + _pendingClear = + null; // Explicit open authorizes a new binding after revocation. + await _persist(); + _checkEpoch(epoch); + await _handshake(epoch); + // A business refresh failure must not tear down a working transport. + try { + await refresh( + resources: [ + if (_capabilities.contains('account.display')) 'account', + if (_capabilities.contains('ddl.display')) 'ddl', + ], + ); + } on WearFailure catch (error) { + _error(error); + } + } catch (error) { + _invalidate('SESSION_MISMATCH'); + await transport.close(); + final failure = error is WearFailure + ? error + : const WearFailure('SERVICE_UNAVAILABLE', retryable: true); + _error(failure); + throw failure; + } finally { + _opening = false; + _changed(); + } + } + + Future _handshake(int epoch) async { + final nonce = _id(); + final welcome = await _request( + 'session.hello', + { + 'nonce': nonce, + 'versions': [1], + 'capabilities': [ + 'account.display', + 'ddl.display', + 'campusCode.qrBytes', + 'campusCode.qrMatrix', + 'connection.heartbeat', + ], + }, + expected: 'session.welcome', + handshake: true, + ); + _checkEpoch(epoch); + final body = Map.from(welcome['body'] as Map); + if (body['nonce'] != nonce || + body['version'] != 1 || + body['watchInstanceId'] is! String || + body['capabilities'] is! List) { + throw const WearFailure('UNSUPPORTED_VERSION'); + } + _capabilities = (body['capabilities'] as List) + .whereType() + .toSet() + .intersection({ + 'account.display', + 'ddl.display', + 'campusCode.qrBytes', + 'campusCode.qrMatrix', + 'connection.heartbeat', + }); + if (_remindersEnabled && (_native['permission'] as Map)['notify'] == true) { + _capabilities.add('reminder.phoneNotify'); + } + final max = body['maxQrPayloadBytes']; + _maxCodeBytes = max is int && max > 0 ? max.clamp(1, 1024) : 512; + final session = _id(); + _leaseUntil = now().add(const Duration(hours: 24)).millisecondsSinceEpoch; + await _request( + 'session.open', + { + 'nonce': nonce, + 'sessionId': session, + 'bindingId': _binding, + 'phoneTimeMs': now().millisecondsSinceEpoch, + 'leaseUntilMs': _leaseUntil, + }, + expected: 'session.opened', + handshake: true, + ); + _checkEpoch(epoch); + _session = session; + _ready = true; + _lastError = null; + _heartbeatTimer?.cancel(); + _heartbeatTimer = Timer.periodic(const Duration(seconds: 10), (_) { + if (_capabilities.contains('connection.heartbeat')) { + unawaited(_heartbeat()); + } + }); + _leaseTimer?.cancel(); + _leaseTimer = Timer(const Duration(hours: 24), () { + _invalidate('SESSION_MISMATCH'); + unawaited(transport.cancelReminders()); + _changed(); + }); + _changed(); + } + + void _checkEpoch(int epoch) { + if (_disposed || epoch != _epoch) { + throw const WearFailure('SESSION_MISMATCH'); + } + } + + Future _heartbeat() async { + if (_heartbeatBusy || !ready) return; + _heartbeatBusy = true; + final epoch = _epoch; + try { + await _request( + 'session.ping', + {}, + retry: false, + responseTimeout: const Duration(seconds: 8), + ); + } catch (_) { + if (epoch == _epoch) { + _invalidate('DEVICE_DISCONNECTED'); + await transport.close(); + _native['device'] = 'disconnected'; + _changed(); + } + } finally { + _heartbeatBusy = false; + } + } + + void _requireReady() { + if (!ready || _pendingClear != null) { + throw const WearFailure('PEER_NOT_READY', retryable: true); + } + } + + Future _checkAccount(int epoch) async { + final account = await source.account(); + _checkEpoch(epoch); + if (sha256.convert(utf8.encode(account.scope)).toString() != _scopeHash) { + throw const WearFailure('ACCOUNT_NOT_READY'); + } + } + + Future _write(Map message) { + final epoch = _epoch; + final frames = WearFrames.encode(message); + final operation = _tx.catchError((Object _) {}).then((_) async { + for (final frame in frames) { + _checkEpoch(epoch); + await transport.send(frame).timeout(timeout); + } + }); + _tx = operation.catchError((Object _) {}); + return operation; + } + + Map _message( + String type, + Map body, { + String? replyTo, + bool handshake = false, + }) => + { + 'v': 1, + 'id': _id(), + 'replyTo': replyTo, + 'sessionId': handshake ? null : _session, + 'bindingId': handshake ? null : _binding, + 'type': type, + 'sentAtMs': now().millisecondsSinceEpoch, + 'body': body, + }; + Future> _request( + String type, + Map body, { + String expected = 'result', + bool handshake = false, + bool retry = true, + Duration? responseTimeout, + String? replyTo, + }) async { + final message = + _message(type, body, handshake: handshake, replyTo: replyTo); + final pending = _Pending(expected); + final id = message['id'] as String; + _pending[id] = pending; + // Attach an error handler immediately: invalidate can finish before send returns. + final answer = pending.done.future; + unawaited(answer.then((_) {}, onError: (Object _, StackTrace __) {})); + try { + for (var attempt = 0;; attempt++) { + await _write(message); + try { + return await answer.timeout(responseTimeout ?? timeout); + } on TimeoutException { + if (!retry || + attempt >= retryDelays.length || + (!handshake && !ready)) { + throw const WearFailure('SYNC_TIMEOUT', retryable: true); + } + await Future.delayed(retryDelays[attempt]); + } + } + } finally { + _pending.remove(id); + } + } + + Future _receive(Map message) async { + try { + final type = message['type'] as String; + final pending = _pending[message['replyTo']]; + final handshake = type == 'session.welcome' || + type == 'session.opened' || + (type == 'result' && pending != null && pending.expected != 'result'); + if (handshake) { + if (!_opening || + message['sessionId'] != null || + message['bindingId'] != null) { + return; + } + } else if (!ready || + message['sessionId'] != _session || + message['bindingId'] != _binding) { + return; // Old session/account must never cause side effects or finish a request. + } + if (pending != null && (type == pending.expected || type == 'result')) { + final body = message['body'] as Map; + if (!pending.done.isCompleted) { + if (type == 'result' && body['status'] == 'error') { + pending.done.completeError( + WearFailure( + body['code'] as String? ?? 'INVALID_PAYLOAD', + retryable: body['retryable'] == true, + ), + ); + } else if (type == pending.expected && + (type != 'result' || body['status'] == 'ok')) { + pending.done.complete(message); + } + } + return; + } + if (type == 'result' || handshake || _pendingClear != null) return; + final id = message['id'] as String; + final content = jsonEncode(message); + final cached = _replies[id]; + if (cached != null) { + if (cached.content != content) { + throw const WearFailure('INVALID_PAYLOAD'); + } + await _write(cached.message); + return; + } + final running = _inbound[id]; + if (running != null) { + if (running.content != content) { + throw const WearFailure('INVALID_PAYLOAD'); + } + await running.done; + return; + } + final work = _handleRequest(message, content); + _inbound[id] = _Incoming(content, work); + try { + await work; + } finally { + _inbound.remove(id); + } + } on WearFailure catch (error) { + _error(error); + } catch (_) { + _error(const WearFailure('INVALID_PAYLOAD')); + } + } + + Future _reply( + Map request, + String content, + Map body, + ) async { + final reply = _message('result', body, replyTo: request['id'] as String); + if (_replies.length >= 64) _replies.remove(_replies.keys.first); + _replies[request['id'] as String] = _Reply(content, reply); + await _write(reply); + } + + Future _handleRequest( + Map message, + String content, + ) async { + final epoch = _epoch; + try { + await _checkAccount(epoch); + final body = Map.from(message['body'] as Map); + switch (message['type']) { + case 'sync.request': + final resources = + (body['resources'] as List?)?.whereType().toList(); + if (resources == null || + resources.isEmpty || + resources.any((r) => !['account', 'ddl'].contains(r))) { + throw const WearFailure('INVALID_PAYLOAD'); + } + await _reply(message, content, {'status': 'ok', 'code': 'OK'}); + await refresh(resources: resources); + case 'campusCode.request': + if (body['format'] != 'qrBytes' || body['purpose'] is! String) { + throw const WearFailure('UNSUPPORTED_FORMAT'); + } + await _sendCode( + body['purpose'] as String, + replyTo: message['id'] as String, + ); + await _reply(message, content, {'status': 'ok', 'code': 'OK'}); + default: + throw const WearFailure('UNSUPPORTED_OPERATION'); + } + } catch (error) { + if (epoch != _epoch || !ready) return; + final failure = + error is WearFailure ? error : const WearFailure('INVALID_PAYLOAD'); + await _reply(message, content, { + 'status': 'error', + 'code': failure.code, + 'retryable': failure.retryable, + }); + } + } + + Future refresh({List resources = const ['account', 'ddl']}) { + final operation = + _refreshTail.catchError((Object _) {}).then((_) => _refresh(resources)); + _refreshTail = operation.catchError((Object _) {}); + return operation; + } + + Future _refresh(List resources) async { + _requireReady(); + if (resources.isEmpty || + resources.any((r) => !['account', 'ddl'].contains(r))) { + throw const WearFailure('INVALID_PAYLOAD'); + } + final epoch = _epoch; + await _checkAccount(epoch); + WearFailure? firstError; + for (final resource in resources.toSet()) { + try { + if (!_capabilities.contains('$resource.display')) { + throw const WearFailure('UNSUPPORTED_OPERATION'); + } + Map body; + if (resource == 'account') { + body = {'data': (await source.account()).toJson()}; + } else { + final items = await source.deadlines(); + body = _ddlSnapshot(items); + await _checkAccount(epoch); + await _schedule(items); + } + await _checkAccount(epoch); + final revision = _revisions[resource]! + 1; + _revisions[resource] = revision; + await _persist(); // Increment before transmission; never reuse a revision after restart. + _checkEpoch(epoch); + body.addAll({ + 'revision': revision, + 'generatedAtMs': now().millisecondsSinceEpoch, + 'validUntilMs': _leaseUntil, + }); + _sync[resource] = {'state': 'pending', 'revision': revision}; + _changed(); + final answer = await _request('$resource.snapshot', body); + _checkEpoch(epoch); + final result = answer['body'] as Map; + if (result['resource'] != resource || result['revision'] != revision) { + throw const WearFailure('INVALID_PAYLOAD'); + } + _sync[resource] = { + 'state': 'applied', + 'revision': revision, + 'atMs': now().millisecondsSinceEpoch, + }; + if (resource == 'account') { + _displayAccount = Map.from(body['data'] as Map); + } + } catch (error) { + final failure = error is WearFailure + ? error + : const WearFailure('SERVICE_UNAVAILABLE', retryable: true); + _sync[resource] = {'state': 'failed', 'code': failure.code}; + firstError ??= failure; + _error(failure); + } + if (epoch != _epoch) break; + } + _changed(); + if (firstError != null) throw firstError; + } + + Map _ddlSnapshot(List items) { + final from = now().subtract(const Duration(days: 7)).millisecondsSinceEpoch; + final to = now().add(const Duration(days: 30)).millisecondsSinceEpoch; + final selected = items + .where( + (item) => + item.dueAt.millisecondsSinceEpoch >= from && + item.dueAt.millisecondsSinceEpoch < to, + ) + .toList() + ..sort((a, b) { + final order = a.dueAt.compareTo(b.dueAt); + return order == 0 ? a.id.compareTo(b.id) : order; + }); + final result = >[]; + var truncated = selected.length > 50; + for (final item in selected.take(50)) { + result.add(item.toJson()); + // Reserve room for the envelope and metadata, truncate whole items only. + if (utf8.encode(jsonEncode(result)).length > WearFrames.maxBytes - 1024) { + result.removeLast(); + truncated = true; + break; + } + } + return { + 'timeZone': 'Asia/Shanghai', + 'window': {'fromMs': from, 'toMs': to}, + 'truncated': truncated, + 'items': result, + }; + } + + Future _schedule(List deadlines) async { + _requireReady(); + if (!_capabilities.contains('reminder.phoneNotify')) { + await transport.cancelReminders(); + return; + } + final reminders = >[]; + for (final item in deadlines.where((item) => !item.completed)) { + for (final at in item.remindAt.take(3)) { + if (now().isAfter(at.add(const Duration(minutes: 10))) || + at.millisecondsSinceEpoch >= _leaseUntil) { + continue; + } + reminders.add({ + 'reminderId': sha256 + .convert( + utf8.encode( + '$_binding:${item.id}:${at.millisecondsSinceEpoch}', + ), + ) + .toString(), + 'ddlId': item.id, + 'title': item.title, + 'dueAtMs': item.dueAt.millisecondsSinceEpoch, + 'scheduledAtMs': at.millisecondsSinceEpoch, + 'expiresAtMs': + at.add(const Duration(minutes: 10)).millisecondsSinceEpoch, + 'ddlRevision': _revisions['ddl']! + 1, + }); + } + } + if (reminders.length > 500) throw const WearFailure('PAYLOAD_TOO_LARGE'); + await transport.scheduleReminders({ + 'deviceId': _device, + 'bindingId': _binding, + 'leaseUntilMs': _leaseUntil, + 'items': reminders, + }); + } + + Future sendReminder(String reminderId) => + transport.sendReminder(reminderId); + + Future setRemindersEnabled(bool enabled) async { + _requireReady(); + final epoch = _epoch; + if (enabled) { + if (_remindersEnabled) return; + final permissions = await requestPermissions(notify: true); + _checkEpoch(epoch); + if (permissions['notify'] != true) { + throw const WearFailure('PERMISSION_DENIED'); + } + _capabilities.add('reminder.phoneNotify'); + try { + await refresh(resources: ['ddl']); + _checkEpoch(epoch); + } catch (_) { + if (epoch == _epoch) { + _capabilities.remove('reminder.phoneNotify'); + _remindersEnabled = false; + try { + await transport.cancelReminders(); + } catch (_) { + // Keep the original scheduling failure available to the caller. + } + _changed(); + } + rethrow; + } + } else { + await transport.cancelReminders(); + _checkEpoch(epoch); + _capabilities.remove('reminder.phoneNotify'); + } + _remindersEnabled = enabled; + _changed(); + } + + Future _sendCode(String purpose, {required String replyTo}) async { + _requireReady(); + if (!_capabilities.contains('campusCode.qrBytes') && + !_capabilities.contains('campusCode.qrMatrix')) { + throw const WearFailure('UNSUPPORTED_FORMAT'); + } + if (_codeBusy || + (_lastCodeRequest != null && + now().difference(_lastCodeRequest!) < const Duration(seconds: 5))) { + throw const WearFailure('RATE_LIMITED', retryable: true); + } + _codeBusy = true; + _lastCodeRequest = now(); + final epoch = _epoch; + final elapsed = Stopwatch()..start(); + try { + final code = await source.campusCode(purpose).timeout(timeout); + await _checkAccount(epoch); + if (code.bytes.isEmpty || code.bytes.length > _maxCodeBytes) { + throw const WearFailure('PAYLOAD_TOO_LARGE'); + } + final expiry = [ + code.validUntil.millisecondsSinceEpoch, + code.issuedAt.add(const Duration(seconds: 120)).millisecondsSinceEpoch, + _leaseUntil, + ].reduce(min); + if (expiry <= + now().add(const Duration(seconds: 5)).millisecondsSinceEpoch) { + throw const WearFailure('CODE_EXPIRED'); + } + final remaining = const Duration(seconds: 30) - elapsed.elapsed; + if (remaining <= Duration.zero) { + throw const WearFailure('SYNC_TIMEOUT', retryable: true); + } + await _request( + 'campusCode.snapshot', + { + 'codeId': _id(), + 'purpose': purpose, + 'format': 'qrBytes', + 'issuedAtMs': code.issuedAt.millisecondsSinceEpoch, + 'validFromMs': code.issuedAt.millisecondsSinceEpoch, + 'validUntilMs': expiry, + 'payloadEncoding': 'base64', + 'payload': base64Encode(code.bytes), + if (_capabilities.contains('campusCode.qrMatrix')) + ...wearQrMatrix(code.bytes), + }, + replyTo: replyTo, + retry: false, + responseTimeout: remaining < timeout ? remaining : timeout, + ); + } finally { + _codeBusy = false; + } + } + + /// Call immediately on logout/account mutation. Persist first, then drain on reconnect. + Future clear({String reason = 'userRevoked'}) async { + if (!['logout', 'accountChanged', 'userRevoked'].contains(reason)) { + throw const WearFailure('INVALID_PAYLOAD'); + } + _pendingClear = reason; + // Stop existing sends/requests synchronously before issuing the clear command. + final oldSession = _session; + _invalidate('SESSION_MISMATCH'); + await transport.cancelReminders(); + await _persist(); + _session = oldSession; + _ready = oldSession != null; + try { + if (ready) await _clearConnected(reason); + } finally { + await close(); + } + } + + Future reconcileAccount() async { + if (_binding == null || _pendingClear != null || _disposed) return; + final epoch = _epoch; + try { + final current = await source.account(); + _checkEpoch(epoch); + if (sha256.convert(utf8.encode(current.scope)).toString() != _scopeHash) { + await clear(reason: 'accountChanged'); + } + } on WearFailure catch (error) { + if (epoch == _epoch && error.code == 'ACCOUNT_NOT_READY') { + await clear(reason: 'logout'); + } + } + } + + Future _clearConnected(String reason) async { + await _request('session.clear', {'reason': reason}); + _pendingClear = null; + _binding = null; + _scopeHash = null; + _revisions.updateAll((_, __) => 0); + _sync.clear(); + await _persist(); + } + + Future close() async { + if (ready && _capabilities.contains('connection.heartbeat')) { + try { + await _request( + 'session.close', + {}, + retry: false, + responseTimeout: const Duration(seconds: 2), + ); + } catch (_) { + // A disconnected peer is released even when the final acknowledgement is lost. + } + } + _invalidate('PEER_NOT_READY'); + _remindersEnabled = false; + await transport.cancelReminders(); + await transport.close(); + _native['device'] = 'disconnected'; + _changed(); + } + + @override + void dispose() { + _disposed = true; + _invalidate('PEER_NOT_READY'); + for (final subscription in _subscriptions) { + unawaited(subscription.cancel()); + } + transport.dispose(); + super.dispose(); + } +} + +class _Pending { + _Pending(this.expected); + final String expected; + final done = Completer>(); +} + +class _Incoming { + _Incoming(this.content, this.done); + final String content; + final Future done; +} + +class _Reply { + _Reply(this.content, this.message); + final String content; + final Map message; +} diff --git a/lib/services/wear/wear_protocol.dart b/lib/services/wear/wear_protocol.dart new file mode 100644 index 00000000..91da663e --- /dev/null +++ b/lib/services/wear/wear_protocol.dart @@ -0,0 +1,205 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +class WearFailure implements Exception { + const WearFailure(this.code, {this.retryable = false, this.nativeCode}); + final String code; + final bool retryable; + final int? nativeCode; + @override + String toString() => 'WearFailure($code)'; +} + +/// Byte-oriented framing: never splits a multi-byte UTF-8 character as text. +class WearFrames { + static const maxBytes = 32768; + static const chunkBytes = 512; + final Map _pending = {}; + + static List encode(Map message) { + final id = message['id']; + if (id is! String || !RegExp(r'^[A-Za-z0-9_-]{1,32}$').hasMatch(id)) { + throw const WearFailure('INVALID_PAYLOAD'); + } + final bytes = utf8.encode(jsonEncode(message)); + if (bytes.length > maxBytes) throw const WearFailure('PAYLOAD_TOO_LARGE'); + final count = (bytes.length + chunkBytes - 1) ~/ chunkBytes; + return List.generate(count, (i) { + final end = (i + 1) * chunkBytes; + return Uint8List.fromList( + utf8.encode( + jsonEncode({ + 'v': 1, + 'mid': id, + 'i': i, + 'n': count, + 'data': base64Encode( + bytes.sublist(i * chunkBytes, end.clamp(0, bytes.length)), + ), + }), + ), + ); + }); + } + + Map? accept(Uint8List frame, DateTime now) { + _pending + .removeWhere((_, value) => now.difference(value.at).inSeconds >= 30); + if (frame.length > 1024) throw const WearFailure('PAYLOAD_TOO_LARGE'); + try { + final json = jsonDecode(utf8.decode(frame)); + if (json is! Map || + json['v'] != 1 || + json['mid'] is! String || + !RegExp(r'^[A-Za-z0-9_-]{1,32}$').hasMatch(json['mid'] as String) || + json['i'] is! int || + json['n'] is! int || + json['data'] is! String) { + throw const WearFailure('INVALID_PAYLOAD'); + } + final id = json['mid'] as String; + final index = json['i'] as int; + final count = json['n'] as int; + if (count < 1 || count > 64 || index < 0 || index >= count) { + _pending.remove(id); + throw const WearFailure('INVALID_PAYLOAD'); + } + final data = base64Decode(json['data'] as String); + if (data.isEmpty || + data.length > chunkBytes || + (index < count - 1 && data.length != chunkBytes)) { + _pending.remove(id); + throw const WearFailure('INVALID_PAYLOAD'); + } + // One in-flight logical message per native peer; the transport selects one peer. + if (_pending.isNotEmpty && !_pending.containsKey(id)) { + throw const WearFailure('RATE_LIMITED', retryable: true); + } + final assembly = _pending.putIfAbsent(id, () => _Assembly(count, now)); + if (assembly.count != count || + (assembly.parts[index] != null && + base64Encode(assembly.parts[index]!) != base64Encode(data))) { + _pending.remove(id); + throw const WearFailure('INVALID_PAYLOAD'); + } + assembly.parts[index] = data; + assembly.at = now; + if (assembly.parts.length != count) return null; + _pending.remove(id); + final bytes = BytesBuilder(copy: false); + for (var i = 0; i < count; i++) { + bytes.add(assembly.parts[i]!); + } + final message = jsonDecode(utf8.decode(bytes.takeBytes())); + if (message is! Map || + message['id'] != id || + message['v'] != 1 || + message['type'] is! String || + message['body'] is! Map || + message['sentAtMs'] is! int) { + throw const WearFailure('INVALID_PAYLOAD'); + } + return message; + } on WearFailure { + rethrow; + } catch (_) { + throw const WearFailure('INVALID_PAYLOAD'); + } + } + + void clear() => _pending.clear(); +} + +class _Assembly { + _Assembly(this.count, this.at); + final int count; + DateTime at; + final Map parts = {}; +} + +class WearAccount { + const WearAccount({ + required this.scope, + required this.name, + required this.studentId, + }); + + /// Local opaque identity only. Never sent to the watch. + final String scope; + final String name; + final String studentId; + Map toJson() { + if (scope.isEmpty || + name.trim().isEmpty || + studentId.trim().isEmpty || + name.runes.length > 64 || + studentId.runes.length > 64) { + throw const WearFailure('ACCOUNT_NOT_READY'); + } + return {'name': name, 'studentId': studentId}; + } +} + +class WearDdl { + const WearDdl({ + required this.id, + required this.title, + required this.courseName, + required this.dueAt, + required this.completed, + this.remindAt = const [], + }); + final String id; + final String title; + final String courseName; + final DateTime dueAt; + final bool completed; + final List remindAt; + Map toJson() => { + 'id': id, + 'title': title, + 'courseName': courseName, + 'dueAtMs': dueAt.millisecondsSinceEpoch, + 'status': completed ? 'completed' : 'open', + 'remindAtMs': completed + ? [] + : remindAt.map((t) => t.millisecondsSinceEpoch).toList(), + }; +} + +class WearCampusCode { + WearCampusCode({ + required this.bytes, + required this.issuedAt, + required this.validUntil, + }); + final Uint8List bytes; + final DateTime issuedAt; + final DateTime validUntil; +} + +abstract interface class WearDataSource { + Future account(); + Future> deadlines(); + Future campusCode(String purpose); +} + +abstract interface class WearTransport { + Stream get frames; + Stream> get states; + Future> status(); + Future>> devices(); + Future> authorize({required bool notify}); + Future open(String deviceId, String fingerprint); + Future send(Uint8List bytes); + Future close(); + Future scheduleReminders(Map spec); + Future cancelReminders(); + Future sendReminder(String id); + void dispose(); +} + +abstract interface class WearMetadata { + String? read(); + Future write(String value); +} diff --git a/lib/services/wear/wear_qr_matrix.dart b/lib/services/wear/wear_qr_matrix.dart new file mode 100644 index 00000000..3005f111 --- /dev/null +++ b/lib/services/wear/wear_qr_matrix.dart @@ -0,0 +1,35 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:qr_flutter/qr_flutter.dart'; + +import 'wear_protocol.dart'; + +/// Row-major, MSB-first QR modules. The original binary payload is never +/// converted to a String; the watch adds a four-module quiet zone when drawing. +Map wearQrMatrix(Uint8List bytes) { + if (bytes.isEmpty || bytes.length > 1024) { + throw const WearFailure('PAYLOAD_TOO_LARGE'); + } + final image = QrImage( + QrCode.fromUint8List( + data: bytes, + errorCorrectLevel: QrErrorCorrectLevel.M, + ), + ); + final size = image.moduleCount; + // 264 logical pixels with >= 2 pixels/module, including the quiet zone. + if (size > 121) throw const WearFailure('PAYLOAD_TOO_LARGE'); + final packed = Uint8List((size * size + 7) ~/ 8); + for (var row = 0; row < size; row++) { + for (var col = 0; col < size; col++) { + final bit = row * size + col; + if (image.isDark(row, col)) packed[bit ~/ 8] |= 1 << (7 - bit % 8); + } + } + return { + 'matrixSize': size, + 'matrixEncoding': 'base64-msb', + 'matrix': base64Encode(packed), + }; +} diff --git a/lib/widgets/app_shell/app_shell.dart b/lib/widgets/app_shell/app_shell.dart index 477618a0..b050a707 100644 --- a/lib/widgets/app_shell/app_shell.dart +++ b/lib/widgets/app_shell/app_shell.dart @@ -24,6 +24,7 @@ import 'mobile_shell.dart'; /// root navigator on a phone. A value set before the shell mounts waits for it, /// which is what a cold start needs. final appShellPendingEcardEntry = ValueNotifier(null); +final appShellPendingDeadlines = ValueNotifier(false); class AppShell extends StatefulWidget { const AppShell({super.key}); @@ -87,6 +88,10 @@ class _AppShellState extends State { void initState() { super.initState(); appShellPendingEcardEntry.addListener(_showPendingEcardEntry); + appShellPendingDeadlines.addListener(_showDeadlines); + if (appShellPendingDeadlines.value) { + WidgetsBinding.instance.addPostFrameCallback((_) => _showDeadlines()); + } if (appShellPendingEcardEntry.value != null) { // Deferred: a push during the first build is a build-time side effect. WidgetsBinding.instance.addPostFrameCallback( @@ -98,9 +103,17 @@ class _AppShellState extends State { @override void dispose() { appShellPendingEcardEntry.removeListener(_showPendingEcardEntry); + appShellPendingDeadlines.removeListener(_showDeadlines); super.dispose(); } + void _showDeadlines() { + if (!mounted || !appShellPendingDeadlines.value) return; + appShellPendingDeadlines.value = false; + _contentNavigatorKeys[2]?.currentState?.popUntil((route) => route.isFirst); + _onDestinationSelected(2); + } + /// Pushes the entry the host asked for into the destination the user is on. void _showPendingEcardEntry() { final entry = appShellPendingEcardEntry.value; diff --git a/lib/widgets/feedback_entry.dart b/lib/widgets/feedback_entry.dart new file mode 100644 index 00000000..dfd8e015 --- /dev/null +++ b/lib/widgets/feedback_entry.dart @@ -0,0 +1,59 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'adaptive_alert_dialog.dart'; + +/// Opens the public feedback page and provides a usable fallback on failure. +class FeedbackEntry extends StatefulWidget { + const FeedbackEntry({super.key, this.launcher}); + + final Future Function(Uri)? launcher; + + @override + State createState() => _FeedbackEntryState(); +} + +class _FeedbackEntryState extends State { + static final _url = Uri.parse('https://techpie-feedback.dzhes.app'); + bool _opening = false; + + Future _open() async { + if (_opening) return; + setState(() => _opening = true); + try { + var opened = false; + try { + opened = await (widget.launcher?.call(_url) ?? + launchUrl(_url, mode: LaunchMode.externalApplication)); + } catch (_) { + // Both a false result and a platform failure need the same recovery. + } + if (opened || !mounted) return; + final copy = await showAdaptiveAlertDialog( + context: context, + title: '无法打开反馈页面', + message: '请复制链接后在浏览器中打开。\n$_url', + actions: const [ + AdaptiveAlertAction(label: '关闭', value: false), + AdaptiveAlertAction(label: '复制链接', value: true, isDefault: true), + ], + ); + if (copy == true) await Clipboard.setData(ClipboardData(text: '$_url')); + } finally { + if (mounted) setState(() => _opening = false); + } + } + + @override + Widget build(BuildContext context) => ListTile( + leading: const Icon(Icons.feedback_outlined), + title: const Text('用户反馈与工单'), + subtitle: const Text('提交问题、建议,或查看工单进度'), + trailing: const Icon(Icons.open_in_new), + enabled: !_opening, + onTap: () => unawaited(_open()), + ); +} diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt index e97dabc7..e9392049 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -9,6 +9,8 @@ project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} "main.cc" "my_application.cc" + "deadline_snapshot_store.cc" + "uni_auth_window.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) @@ -22,5 +24,9 @@ add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +pkg_check_modules(JSON_GLIB REQUIRED IMPORTED_TARGET json-glib-1.0) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::JSON_GLIB) +pkg_check_modules(WEBKIT REQUIRED IMPORTED_TARGET webkit2gtk-4.1) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::WEBKIT) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/deadline_snapshot_store.cc b/linux/runner/deadline_snapshot_store.cc new file mode 100644 index 00000000..befd0603 --- /dev/null +++ b/linux/runner/deadline_snapshot_store.cc @@ -0,0 +1,92 @@ +#include "deadline_snapshot_store.h" + +#include +#include +#include +#include + +static gboolean number(JsonObject* object, const char* key) { + if (!json_object_has_member(object, key)) return FALSE; + JsonNode* node = json_object_get_member(object, key); + if (!JSON_NODE_HOLDS_VALUE(node)) return FALSE; + const GType type = json_node_get_value_type(node); + if (type != G_TYPE_INT64 && type != G_TYPE_DOUBLE) return FALSE; + const double value = json_node_get_double(node); + return std::isfinite(value) && value >= 0 && value <= 253402300799.0; +} + +static const gchar* string(JsonObject* object, const char* key, gsize limit) { + if (!json_object_has_member(object, key)) return nullptr; + JsonNode* node = json_object_get_member(object, key); + if (!JSON_NODE_HOLDS_VALUE(node) || json_node_get_value_type(node) != G_TYPE_STRING) + return nullptr; + const gchar* value = json_node_get_string(node); + return value && std::strlen(value) <= limit ? value : nullptr; +} + +gchar* deadline_snapshot_path() { + return g_build_filename(g_get_user_data_dir(), "techpie", "widgets", + "deadline-widget-v1.json", nullptr); +} + +gboolean deadline_snapshot_valid(const gchar* json, gsize length) { + if (!json || length > 262144 || std::strlen(json) != length) return FALSE; + g_autoptr(JsonParser) parser = json_parser_new(); + if (!json_parser_load_from_data(parser, json, length, nullptr)) return FALSE; + JsonNode* root = json_parser_get_root(parser); + if (!root || !JSON_NODE_HOLDS_OBJECT(root)) return FALSE; + JsonObject* object = json_node_get_object(root); + if (json_object_get_size(object) != 3 || !number(object, "schemaVersion") || + json_object_get_double_member(object, "schemaVersion") != 1 || + !number(object, "writtenAt") || !json_object_has_member(object, "items")) + return FALSE; + JsonNode* items_node = json_object_get_member(object, "items"); + if (!JSON_NODE_HOLDS_ARRAY(items_node)) return FALSE; + JsonArray* items = json_node_get_array(items_node); + if (json_array_get_length(items) > 512) return FALSE; + g_autoptr(GHashTable) ids = g_hash_table_new(g_str_hash, g_str_equal); + for (guint i = 0; i < json_array_get_length(items); i++) { + JsonNode* node = json_array_get_element(items, i); + if (!JSON_NODE_HOLDS_OBJECT(node)) return FALSE; + JsonObject* item = json_node_get_object(node); + const gchar* id = string(item, "id", 4096); + const gchar* kind = string(item, "kind", 16); + if (json_object_get_size(item) != 5 || !id || !*id || !kind || + (g_strcmp0(kind, "exam") && g_strcmp0(kind, "assignment")) || + !string(item, "title", 4096) || !string(item, "course", 4096) || + !number(item, "dueAt") || g_hash_table_contains(ids, id)) return FALSE; + g_hash_table_add(ids, const_cast(id)); + } + return TRUE; +} + +gboolean deadline_snapshot_write(const gchar* json, GError** error) { + if (!deadline_snapshot_valid(json, json ? std::strlen(json) : 0)) { + g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Invalid deadline snapshot"); + return FALSE; + } + g_autofree gchar* path = deadline_snapshot_path(); + g_autofree gchar* directory = g_path_get_dirname(path); + if (g_mkdir_with_parents(directory, 0700) != 0 || g_chmod(directory, 0700) != 0) { + g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_FAILED, "Cannot create widget directory"); + return FALSE; + } + return g_file_set_contents_full(path, json, -1, + static_cast(G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE), + 0600, error); +} + +gboolean deadline_snapshot_clear(GError** error) { + g_autofree gchar* path = deadline_snapshot_path(); + g_autoptr(GFile) file = g_file_new_for_path(path); + g_autoptr(GError) local = nullptr; + if (g_file_delete(file, nullptr, &local) || + g_error_matches(local, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) return TRUE; + g_propagate_error(error, g_steal_pointer(&local)); + return FALSE; +} + +gboolean deadline_uri_valid(const gchar* uri) { + return g_strcmp0(uri, "techpie://deadlines") == 0 || + g_strcmp0(uri, "techpie://deadlines/") == 0; +} diff --git a/linux/runner/deadline_snapshot_store.h b/linux/runner/deadline_snapshot_store.h new file mode 100644 index 00000000..216cac38 --- /dev/null +++ b/linux/runner/deadline_snapshot_store.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +// Display-only v1 snapshot. Paths always belong to the current user's XDG data. +gchar* deadline_snapshot_path(); +gboolean deadline_snapshot_valid(const gchar* json, gsize length); +gboolean deadline_snapshot_write(const gchar* json, GError** error); +gboolean deadline_snapshot_clear(GError** error); +gboolean deadline_uri_valid(const gchar* uri); diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 60d12536..6f5da637 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -1,4 +1,6 @@ #include "my_application.h" +#include "deadline_snapshot_store.h" +#include "uni_auth_window.h" #include #ifdef GDK_WINDOWING_X11 @@ -10,10 +12,38 @@ struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; + FlMethodChannel* deadline_channel; + gboolean pending_deadlines; + UniAuthWindow* uni_auth_window; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) +static void deadline_call(FlMethodChannel* channel, FlMethodCall* call, gpointer data) { + MyApplication* self = MY_APPLICATION(data); + const gchar* method = fl_method_call_get_name(call); + g_autoptr(FlMethodResponse) response = nullptr; + if (g_str_equal(method, "consumePendingRoute")) { + g_autoptr(FlValue) value = fl_value_new_bool(self->pending_deadlines); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(value)); + } else if (g_str_equal(method, "acknowledgePendingRoute")) { + self->pending_deadlines = FALSE; + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } else if (g_str_equal(method, "publish") || g_str_equal(method, "clear")) { + g_autoptr(GError) error = nullptr; + FlValue* args = fl_method_call_get_args(call); + gboolean ok; + if (g_str_equal(method, "clear")) ok = deadline_snapshot_clear(&error); + else ok = deadline_snapshot_write( + args && fl_value_get_type(args) == FL_VALUE_TYPE_STRING ? fl_value_get_string(args) : nullptr, + &error); + response = ok ? FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)) + : FL_METHOD_RESPONSE(fl_method_error_response_new("DEADLINE_WIDGET_STORAGE_UNAVAILABLE", + error ? error->message : "Invalid snapshot", nullptr)); + } else response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(call, response, nullptr); +} + // Called when first Flutter frame received. static void first_frame_cb(MyApplication* self, FlView* view) { gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); @@ -22,6 +52,11 @@ static void first_frame_cb(MyApplication* self, FlView* view) { // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); + GtkWindow* existing = gtk_application_get_active_window(GTK_APPLICATION(application)); + if (existing) { + gtk_window_present(existing); + return; + } GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); @@ -74,6 +109,14 @@ static void my_application_activate(GApplication* application) { gtk_widget_realize(GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + delete self->uni_auth_window; + self->uni_auth_window = new UniAuthWindow( + fl_engine_get_binary_messenger(fl_view_get_engine(view)), window); + g_clear_object(&self->deadline_channel); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + self->deadline_channel = fl_method_channel_new(fl_engine_get_binary_messenger(fl_view_get_engine(view)), + "techpie/deadline_widgets", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(self->deadline_channel, deadline_call, self, nullptr); gtk_widget_grab_focus(GTK_WIDGET(view)); } @@ -93,6 +136,15 @@ static gboolean my_application_local_command_line(GApplication* application, return TRUE; } + for (guint i = 1; (*arguments)[i]; i++) { + if (deadline_uri_valid((*arguments)[i])) { + g_autoptr(GFile) file = g_file_new_for_uri((*arguments)[i]); + GFile* files[] = {file}; + g_application_open(application, files, 1, ""); + *exit_status = 0; + return TRUE; + } + } g_application_activate(application); *exit_status = 0; @@ -108,6 +160,24 @@ static void my_application_startup(GApplication* application) { G_APPLICATION_CLASS(my_application_parent_class)->startup(application); } +static void my_application_open(GApplication* application, GFile** files, gint count, + const gchar*) { + MyApplication* self = MY_APPLICATION(application); + gboolean accepted = FALSE; + for (gint i = 0; i < count; i++) { + g_autofree gchar* uri = g_file_get_uri(files[i]); + if (deadline_uri_valid(uri)) accepted = TRUE; + } + if (!accepted) return; + const gboolean running = self->deadline_channel && + gtk_application_get_active_window(GTK_APPLICATION(application)); + self->pending_deadlines = TRUE; + g_application_activate(application); + if (running) + fl_method_channel_invoke_method(self->deadline_channel, "openDeadlines", nullptr, + nullptr, nullptr, nullptr); +} + // Implements GApplication::shutdown. static void my_application_shutdown(GApplication* application) { // MyApplication* self = MY_APPLICATION(object); @@ -120,12 +190,16 @@ static void my_application_shutdown(GApplication* application) { // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); + delete self->uni_auth_window; + self->uni_auth_window = nullptr; g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + g_clear_object(&self->deadline_channel); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->open = my_application_open; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_APPLICATION_CLASS(klass)->startup = my_application_startup; @@ -144,5 +218,5 @@ MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", - G_APPLICATION_NON_UNIQUE, nullptr)); + G_APPLICATION_HANDLES_OPEN, nullptr)); } diff --git a/linux/runner/uni_auth_window.cc b/linux/runner/uni_auth_window.cc new file mode 100644 index 00000000..273771d2 --- /dev/null +++ b/linux/runner/uni_auth_window.cc @@ -0,0 +1,151 @@ +#include "uni_auth_window.h" + +UniAuthWindow::UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent) + : parent_(parent) { + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + channel_ = fl_method_channel_new(messenger, "techpie/uni_auth", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel_, + [](FlMethodChannel*, FlMethodCall* call, gpointer data) { + auto* self = static_cast(data); + if (g_str_equal(fl_method_call_get_name(call), "authenticate")) { + self->Authenticate(call); + } else { + g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(call, response, nullptr); + } + }, this, nullptr); +} + +UniAuthWindow::~UniAuthWindow() { + if (window_) gtk_widget_destroy(window_); + fl_method_channel_set_method_call_handler(channel_, nullptr, nullptr, nullptr); + g_clear_object(&channel_); +} + +void UniAuthWindow::Complete(const gchar* callback) { + if (!pending_) return; + g_autoptr(FlMethodResponse) response = nullptr; + if (callback) { + g_autoptr(FlValue) value = fl_value_new_string(callback); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(value)); + } else { + response = FL_METHOD_RESPONSE(fl_method_error_response_new("CANCELLED", "Login cancelled", nullptr)); + } + fl_method_call_respond(pending_, response, nullptr); + g_clear_object(&pending_); +} + +void UniAuthWindow::Authenticate(FlMethodCall* call) { + FlValue* args = fl_method_call_get_args(call); + const gchar* url = nullptr; + const gchar* proxy = nullptr; + if (args && fl_value_get_type(args) == FL_VALUE_TYPE_MAP) { + FlValue* url_value = fl_value_lookup_string(args, "url"); + FlValue* proxy_value = fl_value_lookup_string(args, "proxy"); + if (url_value && fl_value_get_type(url_value) == FL_VALUE_TYPE_STRING) url = fl_value_get_string(url_value); + if (proxy_value && fl_value_get_type(proxy_value) == FL_VALUE_TYPE_STRING) proxy = fl_value_get_string(proxy_value); + } + g_autoptr(GUri) uri = url ? g_uri_parse(url, G_URI_FLAGS_NONE, nullptr) : nullptr; + if (!uri || g_strcmp0(g_uri_get_scheme(uri), "https") || + g_strcmp0(g_uri_get_host(uri), "auth.geekpie.club")) { + fl_method_call_respond_error(call, "INVALID_URL", "Invalid authorization URL", nullptr, nullptr); + return; + } + if (pending_) { + gtk_window_present(GTK_WINDOW(window_)); + fl_method_call_respond_error(call, "IN_PROGRESS", "Login already open", nullptr, nullptr); + return; + } + pending_ = FL_METHOD_CALL(g_object_ref(call)); + window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window_), "GeekPie UniAuth"); + gtk_window_set_default_size(GTK_WINDOW(window_), 520, 720); + gtk_window_set_transient_for(GTK_WINDOW(window_), parent_); + gtk_window_set_destroy_with_parent(GTK_WINDOW(window_), TRUE); + gtk_window_set_modal(GTK_WINDOW(window_), TRUE); + g_signal_connect(window_, "destroy", G_CALLBACK(+[](GtkWidget*, gpointer data) { + auto* self = static_cast(data); + self->window_ = self->status_ = nullptr; + self->webview_ = nullptr; + self->Complete(nullptr); + }), this); + + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); + gtk_container_add(GTK_CONTAINER(window_), box); + GtkWidget* header = gtk_header_bar_new(); + gtk_header_bar_set_title(GTK_HEADER_BAR(header), "GeekPie UniAuth"); + gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(header), TRUE); + gtk_window_set_titlebar(GTK_WINDOW(window_), header); + GtkWidget* retry = gtk_button_new_with_label("重新加载"); + gtk_header_bar_pack_start(GTK_HEADER_BAR(header), retry); + g_signal_connect(retry, "clicked", G_CALLBACK(+[](GtkButton*, gpointer data) { + auto* self = static_cast(data); + if (self->webview_) webkit_web_view_reload(self->webview_); + }), this); + status_ = gtk_label_new("正在加载登录页…"); + gtk_label_set_line_wrap(GTK_LABEL(status_), TRUE); + gtk_box_pack_start(GTK_BOX(box), status_, FALSE, FALSE, 4); + g_autoptr(WebKitWebContext) context = webkit_web_context_new_ephemeral(); + if (proxy && *proxy) { + g_autoptr(WebKitNetworkProxySettings) settings = webkit_network_proxy_settings_new(nullptr, nullptr); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "http", proxy); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "https", proxy); + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_CUSTOM, settings); + } else { + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_NO_PROXY, nullptr); + } + webview_ = WEBKIT_WEB_VIEW(webkit_web_view_new_with_context(context)); + // Avoid the WebKit/NVIDIA EGL rendering path in this small login window. + webkit_settings_set_hardware_acceleration_policy(webkit_web_view_get_settings(webview_), + WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER); + gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(webview_), TRUE, TRUE, 0); + g_signal_connect(webview_, "load-changed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent event, gpointer data) { + auto* self = static_cast(data); + if (!self->status_) return; + if (event == WEBKIT_LOAD_STARTED) { + gtk_label_set_text(GTK_LABEL(self->status_), "正在加载登录页…"); + gtk_widget_show(self->status_); + } else if (event == WEBKIT_LOAD_COMMITTED) { + gtk_widget_hide(self->status_); + } + }), this); + g_signal_connect(webview_, "load-failed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent, + const gchar*, GError* error, gpointer data) -> gboolean { + auto* self = static_cast(data); + if (!self->status_ || g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED)) return FALSE; + gtk_label_set_text(GTK_LABEL(self->status_), "登录页加载失败,请检查网络后点击“重新加载”。"); + gtk_widget_show(self->status_); + return TRUE; + }), this); + g_signal_connect(webview_, "decide-policy", G_CALLBACK(+[](WebKitWebView* view, + WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer data) -> gboolean { + if (type != WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION && + type != WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) return FALSE; + auto* self = static_cast(data); + auto* navigation = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + auto* action = webkit_navigation_policy_decision_get_navigation_action(navigation); + const gchar* url = webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)); + g_autoptr(GUri) uri = g_uri_parse(url, G_URI_FLAGS_NONE, nullptr); + if (uri && g_strcmp0(g_uri_get_scheme(uri), "techpie") == 0) { + webkit_policy_decision_ignore(decision); + if (g_strcmp0(g_uri_get_host(uri), "auth-callback") == 0) { + self->Complete(url); + // GTK queues the close request instead of destroying inside WebKit. + gtk_window_close(GTK_WINDOW(self->window_)); + } + return TRUE; + } + if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { + webkit_policy_decision_ignore(decision); + if (uri && (g_strcmp0(g_uri_get_scheme(uri), "https") == 0 || + g_strcmp0(g_uri_get_scheme(uri), "http") == 0)) + webkit_web_view_load_uri(view, url); + return TRUE; + } + return FALSE; + }), this); + gtk_widget_show_all(window_); + webkit_web_view_load_uri(webview_, url); +} diff --git a/linux/runner/uni_auth_window.h b/linux/runner/uni_auth_window.h new file mode 100644 index 00000000..a86a5e85 --- /dev/null +++ b/linux/runner/uni_auth_window.h @@ -0,0 +1,24 @@ +#ifndef RUNNER_UNI_AUTH_WINDOW_H_ +#define RUNNER_UNI_AUTH_WINDOW_H_ + +#include +#include + +// A GTK authentication window with no secondary Flutter engine. +class UniAuthWindow { + public: + UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent); + ~UniAuthWindow(); + + private: + void Authenticate(FlMethodCall* call); + void Complete(const gchar* callback); + GtkWindow* parent_; + GtkWidget* window_ = nullptr; + GtkWidget* status_ = nullptr; + WebKitWebView* webview_ = nullptr; + FlMethodChannel* channel_; + FlMethodCall* pending_ = nullptr; +}; + +#endif // RUNNER_UNI_AUTH_WINDOW_H_ diff --git a/linux/widgets/CMakeLists.txt b/linux/widgets/CMakeLists.txt new file mode 100644 index 00000000..e7f30a49 --- /dev/null +++ b/linux/widgets/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.16) +project(techpie_deadline_widgets LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_AUTOMOC ON) +find_package(Qt6 6.4 REQUIRED COMPONENTS Core Gui Qml) +set(KDE_PACKAGE "${CMAKE_CURRENT_BINARY_DIR}/kde") +file(COPY kde/metadata.json kde/contents DESTINATION "${KDE_PACKAGE}") +add_library(techpiedeadlines MODULE kde/backend/plugin.cpp kde/backend/deadline_model.cpp) +target_link_libraries(techpiedeadlines PRIVATE Qt6::Core Qt6::Gui Qt6::Qml) +set_target_properties(techpiedeadlines PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${KDE_PACKAGE}/contents/ui/backend") diff --git a/linux/widgets/README.md b/linux/widgets/README.md new file mode 100644 index 00000000..4a3357b7 --- /dev/null +++ b/linux/widgets/README.md @@ -0,0 +1,104 @@ +# TechPie Linux deadline widgets (first version) + +KDE Plasma 6: a resizable desktop card and compact panel button. GNOME Shell +45–51: a desktop card and top-bar indicator with an expandable deadline list. +GNOME 51 has been checked in an isolated Shell session; other declared versions +and the Plasma desktop still need native visual acceptance. + +The widgets show upcoming, visible, incomplete assignments and exams, sorted by +deadline. They do not contact campus services or receive credentials. They read +the last snapshot published by TechPie; keep the app running for new data. +Expired entries and countdowns are refreshed locally at most every 30 seconds. +The timestamp is when the snapshot was saved, not a claim of a successful server +sync. A widget click opens the app's Deadlines page. + +## Install a release bundle + +Extract the entire Linux release archive to a stable location first. From its +`bundle` directory, using the absolute path to that bundle's executable: + +```bash +python3 widgets/install.py install --desktop kde --app /absolute/path/bundle/techpie +# Or GNOME, or --desktop both: +python3 widgets/install.py install --desktop gnome --app /absolute/path/bundle/techpie +``` + +In TechPie, open **Settings → General → Deadline widgets** to enable sharing. +The setting is off initially. Sharing exposes task titles, course names and +dates to the current user's desktop. Turning it off or signing out clears the +shared task data. Enabled widgets publish an empty list before the first sync. +Widgets are not enabled for the GNOME lock screen. + +- KDE: use the desktop/panel **Add Widgets** picker and select **TechPie Deadlines**. +- GNOME: after a first installation, log out/in if the extension is not listed; + enable **TechPie Deadlines** in Extensions. The installer does not enable it. +- GNOME: drag the card heading to move it. Its position is saved relative to the + primary monitor's work area. The indicator menu can hide the card or reset its + position. It stays below application windows and hides in overview/fullscreen. +- If the app bundle moves, rerun the installer with the new executable path. +- Dependencies: Python 3 for installation, Qt 6 Core/Gui/Qml for KDE; GJS/GNOME + Shell and GLib's `glib-compile-schemas` for GNOME. The app also requires its normal GTK/WebKit/libsecret runtime + dependencies plus json-glib. For Arch, the corresponding widget build packages + are `base-devel cmake qt6-base qt6-declarative json-glib`; Plasma provides its + own QML modules. No root access is required for user installation. + +## Build from source + +Build the normal Linux app using Flutter **3.41.9**. Then build the KDE adapter: + +```bash +cmake -S linux/widgets -B build/linux-widgets -DCMAKE_BUILD_TYPE=Release +cmake --build build/linux-widgets --parallel +python3 linux/widgets/install.py install --desktop kde \ + --kde-package build/linux-widgets/kde \ + --app /absolute/path/build/linux/x64/release/bundle/techpie +``` + +For GNOME, use the same installer with `--desktop gnome`; no Qt build is needed. +The Linux release workflow includes both packages and the compiled Qt adapter. +The Qt plugin must be rebuilt for another architecture and must not require a +newer Qt minor version than the target desktop provides. + +## Uninstall + +Disable the GNOME extension/remove the Plasma widget first, then run: + +```bash +python3 widgets/install.py uninstall --desktop both +``` + +Only marked TechPie widget directories and the managed launcher are removed. +The app and its data are retained. Turn off sharing in the app to erase the +snapshot. No account credentials are ever stored in the widget directory. + +## Data and lifecycle + +The shared v1 protocol follows the macOS branch. Its display-only snapshot is +`$XDG_DATA_HOME/techpie/widgets/deadline-widget-v1.json`, defaulting to +`~/.local/share/techpie/widgets/deadline-widget-v1.json`. Directory permissions +are `0700`, files `0600`; writes are atomic. Readers accept at most 256 KiB / 512 +entries and validate fields, version, timestamps and duplicate IDs. Both watch +directories so atomic replacement and first-time creation are detected. + +The Flutter service serializes writes, ignores superseded account generations, +and uses the same account-isolation changes as the macOS reference. Linux +registers `techpie://deadlines` and activates an existing application instance. +Its existing application ID is retained so saved preferences keep their location. +The existing payment widget and Huawei Watch code remain separate consumers. + +GNOME's `desktopCard.js` owns the desktop actor and placement; `extension.js` +owns the indicator, reader and lifecycle. GSettings stores card visibility and +position. KDE keeps its reader/model in `backend` and presentation in QML. +This version targets an unpacked native bundle; Flatpak/Snap integration is +outside its scope. + +## Desktop card stacking regression + +The GNOME card ignores minimized or hidden window actors when choosing its +stacking position. It restores that position before painting, after Mutter has +finished updating the window stack, so DING's transparent desktop window cannot +cover its buttons after applications are minimized. + +```bash +node --experimental-vm-modules --test linux/widgets/tests/desktop-stacking.test.mjs +``` diff --git a/linux/widgets/common/snapshot.mjs b/linux/widgets/common/snapshot.mjs new file mode 100644 index 00000000..9ae96e6d --- /dev/null +++ b/linux/widgets/common/snapshot.mjs @@ -0,0 +1,41 @@ +export const MAX_BYTES = 262144; +export const MAX_ITEMS = 512; +const timestamp = value => typeof value === 'number' && Number.isFinite(value) && + value >= 0 && value <= 253402300799; +const text = value => typeof value === 'string' && new TextEncoder().encode(value).length <= 4096; + +// Keep this parser independent of Shell/Qt so fixtures run in Node and GJS. +export function decodeSnapshot(json) { + if (typeof json !== 'string' || new TextEncoder().encode(json).length > MAX_BYTES) + throw new Error('Snapshot is too large'); + const snapshot = JSON.parse(json); + if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) || + Object.keys(snapshot).sort().join(',') !== 'items,schemaVersion,writtenAt' || + snapshot.schemaVersion !== 1 || !timestamp(snapshot.writtenAt) || + !Array.isArray(snapshot.items) || snapshot.items.length > MAX_ITEMS) + throw new Error('Invalid snapshot'); + const ids = new Set(); + for (const item of snapshot.items) { + if (!item || typeof item !== 'object' || Array.isArray(item) || + Object.keys(item).sort().join(',') !== 'course,dueAt,id,kind,title' || + !text(item.id) || !item.id || ids.has(item.id) || + !['assignment', 'exam'].includes(item.kind) || !text(item.title) || + !text(item.course) || !timestamp(item.dueAt)) + throw new Error('Invalid item'); + ids.add(item.id); + } + return snapshot; +} + +export function upcoming(snapshot, now = Date.now() / 1000, limit = 8) { + return snapshot.items.filter(item => item.dueAt > now) + .sort((a, b) => a.dueAt - b.dueAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + .slice(0, Math.max(0, limit)); +} + +export function remaining(dueAt, now = Date.now() / 1000) { + const hours = Math.floor((dueAt - now) / 3600); + if (dueAt <= now) return ''; + if (hours === 0) return '<1h'; + return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d ${hours % 24}h`; +} diff --git a/linux/widgets/gnome/desktopCard.js b/linux/widgets/gnome/desktopCard.js new file mode 100644 index 00000000..509963a3 --- /dev/null +++ b/linux/widgets/gnome/desktopCard.js @@ -0,0 +1,164 @@ +import Clutter from 'gi://Clutter'; +import St from 'gi://St'; +import Meta from 'gi://Meta'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import {upcoming, remaining} from './snapshot.mjs'; + +function column(properties = {}) { + const direction = 'orientation' in St.BoxLayout.prototype + ? {orientation: Clutter.Orientation.VERTICAL} : {vertical: true}; + return new St.BoxLayout({...direction, ...properties}); +} + +// Kept below application windows; no reserved screen area or lock-screen actor. +export class DesktopCard { + constructor(settings, open) { + this._settings = settings; + this._open = open; + this.actor = column({style_class: 'popup-menu-content techpie-desktop-card', + reactive: true, width: 360}); + this._header = new St.Label({text: 'TechPie · Deadlines', reactive: true, + style_class: 'techpie-desktop-header'}); + this.actor.add_child(this._header); + this._rows = column({style_class: 'techpie-desktop-rows'}); + this.actor.add_child(this._rows); + this._footer = new St.Label({style_class: 'techpie-deadline-detail'}); + this.actor.add_child(this._footer); + const button = new St.Button({label: 'Open TechPie', can_focus: true, + style_class: 'button'}); + button.connect('clicked', open); + this.actor.add_child(button); + this._windowGroup = global.window_group; + this._windowGroup.add_child(this.actor); + Main.layoutManager.trackChrome(this.actor, {affectsStruts: false}); + this._signals = [ + [settings, settings.connect('changed', () => this._position())], + [Main.layoutManager, Main.layoutManager.connect('monitors-changed', () => this._position())], + [global.display, global.display.connect('workareas-changed', () => this._position())], + [global.display, global.display.connect('in-fullscreen-changed', () => this._position())], + [global.display, global.display.connect('restacked', () => this._queueRestack())], + [this._windowGroup, this._windowGroup.connect('child-added', () => this._queueRestack())], + ]; + this._header.connect('button-press-event', (_actor, event) => { + if (event.get_button() !== 1) return Clutter.EVENT_PROPAGATE; + const [x, y] = event.get_coords(); + this._drag = [x - this.actor.x, y - this.actor.y]; + this._grab = global.stage.grab(this._header); + return Clutter.EVENT_STOP; + }); + this._header.connect('motion-event', (_actor, event) => { + if (!this._drag) return Clutter.EVENT_PROPAGATE; + const [x, y] = event.get_coords(); + const bounds = this._bounds(); + if (bounds) this.actor.set_position( + Math.max(bounds.x, Math.min(bounds.x + bounds.width, x - this._drag[0])), + Math.max(bounds.y, Math.min(bounds.y + bounds.height, y - this._drag[1]))); + return Clutter.EVENT_STOP; + }); + this._header.connect('button-release-event', () => { + if (!this._drag) return Clutter.EVENT_PROPAGATE; + const bounds = this._bounds(); + const x = bounds?.width ? (this.actor.x - bounds.x) / bounds.width : 1; + const y = bounds?.height ? (this.actor.y - bounds.y) / bounds.height : 0; + this._endDrag(); + settings.set_double('position-x', x); + settings.set_double('position-y', y); + return Clutter.EVENT_STOP; + }); + this._queueRestack(); + this._position(); + } + + _queueRestack() { + if (this._restackLater || this._destroyed) return; + // Mutter may still synchronize window actors after display::restacked. + // Move the card only after that work, immediately before painting. + this._restackLater = global.compositor.get_laters().add( + Meta.LaterType.BEFORE_REDRAW, () => { + this._restackLater = 0; + if (!this._destroyed) this._restack(); + return false; + }); + } + + _restack() { + // Desktop icon extensions use a transparent desktop window which still + // receives pointer events. Place the card above it, below normal apps. + const sibling = this._windowGroup.get_children().find(child => { + const window = child.get_meta_window?.(); + // Minimized/off-workspace actors can precede the desktop actor. + // They must not anchor the card underneath the desktop window. + return child.visible && child.mapped && window && + window.get_window_type() !== Meta.WindowType.DESKTOP; + }); + if (sibling) this._windowGroup.set_child_below_sibling(this.actor, sibling); + else this._windowGroup.set_child_above_sibling(this.actor, null); + } + + _bounds() { + const monitor = Main.layoutManager.primaryMonitor; + if (!monitor) return null; + const area = Main.layoutManager.getWorkAreaForMonitor(monitor.index); + const [, height] = this.actor.get_preferred_height(this.actor.width); + this.actor.width = Math.min(360, Math.max(1, area.width - 48)); + return {x: area.x + 24, y: area.y + 24, + width: Math.max(0, area.width - this.actor.width - 48), + height: Math.max(0, area.height - height - 48)}; + } + + _endDrag() { + const grab = this._grab; + this._grab = this._drag = null; + grab?.dismiss(); + } + + _position() { + this._queueRestack(); + this._endDrag(); + const bounds = this._bounds(); + this.actor.visible = Boolean(bounds && this._settings.get_boolean('desktop-visible') && + !Main.layoutManager.primaryMonitor.inFullscreen); + if (bounds) this.actor.set_position( + bounds.x + bounds.width * this._settings.get_double('position-x'), + bounds.y + bounds.height * this._settings.get_double('position-y')); + } + + resetPosition() { + this._settings.reset('position-x'); + this._settings.reset('position-y'); + } + + update(snapshot, state) { + this._rows.destroy_all_children(); + const items = snapshot ? upcoming(snapshot).slice(0, 4) : []; + for (const item of items) { + const row = column({style_class: 'techpie-deadline-row'}); + row.add_child(new St.Label({text: item.title, x_expand: true})); + row.add_child(new St.Label({text: `${item.course} · ${remaining(item.dueAt)}`, + style_class: 'techpie-deadline-detail'})); + const button = new St.Button({child: row, x_expand: true, can_focus: true, + style_class: 'techpie-desktop-item'}); + button.connect('clicked', this._open); + this._rows.add_child(button); + } + if (!items.length) this._rows.add_child(new St.Label({ + text: state === 'unavailable' ? 'Deadline data is unavailable' : snapshot + ? 'No upcoming deadlines' : 'Enable Deadline widgets\nin TechPie Settings', + })); + this._footer.text = snapshot + ? `Cached · ${new Date(snapshot.writtenAt * 1000).toLocaleString()}` : 'Drag the heading to move'; + this._position(); + } + + destroy() { + this._destroyed = true; + if (this._restackLater) { + global.compositor.get_laters().remove(this._restackLater); + this._restackLater = 0; + } + this._endDrag(); + for (const [object, signal] of this._signals) object.disconnect(signal); + Main.layoutManager.untrackChrome(this.actor); + this.actor.destroy(); + } +} diff --git a/linux/widgets/gnome/extension.js b/linux/widgets/gnome/extension.js new file mode 100644 index 00000000..98e8b577 --- /dev/null +++ b/linux/widgets/gnome/extension.js @@ -0,0 +1,167 @@ +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; +import St from 'gi://St'; +import Shell from 'gi://Shell'; +import Clutter from 'gi://Clutter'; +import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js'; +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import {decodeSnapshot, upcoming, remaining, MAX_BYTES} from './snapshot.mjs'; +import {readBounded} from './reader.mjs'; +import {DesktopCard} from './desktopCard.js'; + +export default class TechPieDeadlines extends Extension { + enable() { + this._alive = true; + this._generation = (this._generation ?? 0) + 1; + this._cancellable = new Gio.Cancellable(); + this._settings = this.getSettings(); + this._desktop = new DesktopCard(this._settings, () => this._open()); + this._directory = GLib.build_filenamev([GLib.get_user_data_dir(), 'techpie', 'widgets']); + this._path = GLib.build_filenamev([this._directory, 'deadline-widget-v1.json']); + this._button = new PanelMenu.Button(0.0, 'TechPie Deadlines'); + const box = new St.BoxLayout({style_class: 'panel-status-menu-box'}); + box.add_child(new St.Icon({icon_name: 'view-calendar-symbolic', style_class: 'system-status-icon'})); + this._label = new St.Label({text: 'TechPie', y_align: Clutter.ActorAlign.CENTER}); + box.add_child(this._label); + this._button.add_child(box); + Main.panel.addToStatusArea(this.uuid, this._button); + this._button.menu.connect('open-state-changed', (_menu, open) => { + if (open) this._reload().catch(error => console.error(error)); + }); + this._watch(); + this._reload().catch(error => console.error(error)); + this._timer = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 30, () => { + this._watch(); + this._reload().catch(error => console.error(error)); + return GLib.SOURCE_CONTINUE; + }); + } + + _watch() { + // Watch the closest existing ancestor as the app may not have created + // its directory yet. Reattach after creation or an atomic replacement. + let directory = Gio.File.new_for_path(this._directory); + while (!directory.query_exists(null) && directory.get_parent()) + directory = directory.get_parent(); + const path = directory.get_path(); + if (this._watched === path) return; + this._clearMonitor(); + try { + this._monitor = directory.monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, this._cancellable); + this._watched = path; + this._monitorSignal = this._monitor.connect('changed', () => { + if (!this._alive) return; + if (this._debounce) GLib.Source.remove(this._debounce); + this._debounce = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 100, () => { + this._debounce = 0; + this._watch(); + this._reload().catch(error => console.error(error)); + return GLib.SOURCE_REMOVE; + }); + }); + } catch (_) { /* Retry on the periodic tick. */ } + } + + _clearMonitor() { + if (this._monitor) { + if (this._monitorSignal) this._monitor.disconnect(this._monitorSignal); + this._monitor.cancel(); + } + this._monitor = null; + this._monitorSignal = 0; + this._watched = null; + } + + async _reload() { + const generation = ++this._generation; + try { + const file = Gio.File.new_for_path(this._path); + const json = await readBounded(file, MAX_BYTES, this._cancellable); + if (!this._alive || generation !== this._generation) return; + this._snapshot = decodeSnapshot(json); + this._state = 'ready'; + } catch (error) { + if (!this._alive || generation !== this._generation) return; + this._snapshot = null; + this._state = error.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND) + ? 'notSynced' : 'unavailable'; + } + this._render(); + } + + _open() { + const timestamp = global.get_current_time(); + this._button.menu.close(); + // Activate through Shell as well as delivering the URI: on Wayland an + // existing GTK window cannot always raise itself without user input. + const app = Shell.AppSystem.get_default().lookup_app('com.example.techpie.desktop'); + app?.activate(); + Gio.AppInfo.launch_default_for_uri_async('techpie://deadlines', + global.create_app_launch_context(timestamp, -1), this._cancellable, (_source, result) => { + try { Gio.AppInfo.launch_default_for_uri_finish(result); } + catch (_) { + if (this._alive) Main.notify('TechPie', 'Install the TechPie desktop launcher to open deadlines.'); + } + }); + } + + _render() { + if (!this._alive) return; + const menu = this._button.menu; + menu.removeAll(); + const items = this._snapshot ? upcoming(this._snapshot) : []; + this._desktop.update(this._snapshot, this._state); + this._label.text = items.length ? remaining(items[0].dueAt) : 'TechPie'; + if (!this._snapshot || !items.length) { + const message = this._state === 'unavailable' ? 'Deadline data is unavailable' : + this._snapshot ? 'No upcoming deadlines' : 'Enable Deadline widgets in TechPie Settings'; + menu.addMenuItem(new PopupMenu.PopupMenuItem(message, {reactive: false})); + } + for (const item of items) { + const row = new PopupMenu.PopupMenuItem(''); + const direction = 'orientation' in St.BoxLayout.prototype + ? {orientation: Clutter.Orientation.VERTICAL} : {vertical: true}; + const box = new St.BoxLayout({...direction, style_class: 'techpie-deadline-row'}); + box.add_child(new St.Label({text: `${item.kind === 'exam' ? '◷' : '•'} ${item.title} · ${remaining(item.dueAt)}`})); + box.add_child(new St.Label({text: `${item.course} · ${new Date(item.dueAt * 1000).toLocaleString()}`, + style_class: 'techpie-deadline-detail'})); + row.add_child(box); + row.connect('activate', () => this._open()); + menu.addMenuItem(row); + } + menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + const visible = new PopupMenu.PopupSwitchMenuItem('Desktop card', + this._settings.get_boolean('desktop-visible')); + visible.connect('toggled', (_item, value) => this._settings.set_boolean('desktop-visible', value)); + menu.addMenuItem(visible); + const reset = new PopupMenu.PopupMenuItem('Reset desktop card position'); + reset.connect('activate', () => this._desktop.resetPosition()); + menu.addMenuItem(reset); + const open = new PopupMenu.PopupMenuItem('Open TechPie Deadlines'); + open.connect('activate', () => this._open()); + menu.addMenuItem(open); + if (this._snapshot) { + menu.addMenuItem(new PopupMenu.PopupMenuItem( + `Cached snapshot · ${new Date(this._snapshot.writtenAt * 1000).toLocaleString()}`, + {reactive: false})); + } + } + + disable() { + this._alive = false; + this._generation++; + this._cancellable?.cancel(); + this._clearMonitor(); + if (this._timer) GLib.Source.remove(this._timer); + if (this._debounce) GLib.Source.remove(this._debounce); + this._timer = this._debounce = 0; + this._monitor = this._cancellable = null; + this._watched = this._snapshot = null; + this._button?.destroy(); + this._desktop?.destroy(); + this._desktop = this._settings = null; + this._button = this._label = null; + } +} diff --git a/linux/widgets/gnome/metadata.json b/linux/widgets/gnome/metadata.json new file mode 100644 index 00000000..0141069e --- /dev/null +++ b/linux/widgets/gnome/metadata.json @@ -0,0 +1,9 @@ +{ + "uuid": "deadlines@techpie.geekpie.club", + "name": "TechPie Deadlines", + "description": "Upcoming TechPie assignments and exams from a local display-only snapshot.", + "shell-version": ["45", "46", "47", "48", "49", "50", "51"], + "version": 1, + "settings-schema": "org.gnome.shell.extensions.techpie-deadlines", + "url": "https://github.com/HeZeBang/TechPie-flutter" +} diff --git a/linux/widgets/gnome/reader.mjs b/linux/widgets/gnome/reader.mjs new file mode 100644 index 00000000..ae883005 --- /dev/null +++ b/linux/widgets/gnome/reader.mjs @@ -0,0 +1,39 @@ +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; + +// Bound allocation even if another local process replaces the snapshot with a +// large file. read_bytes_async may return a short read before EOF. +export async function readBounded(file, maximum, cancellable) { + const stream = await new Promise((resolve, reject) => { + file.read_async(GLib.PRIORITY_DEFAULT, cancellable, (source, result) => { + try { resolve(source.read_finish(result)); } + catch (error) { reject(error); } + }); + }); + try { + const parts = []; + let length = 0; + while (length <= maximum) { + const bytes = await new Promise((resolve, reject) => { + stream.read_bytes_async(Math.min(65536, maximum + 1 - length), + GLib.PRIORITY_DEFAULT, cancellable, (input, result) => { + try { resolve(input.read_bytes_finish(result).get_data()); } + catch (error) { reject(error); } + }); + }); + if (!bytes.length) break; + parts.push(bytes); + length += bytes.length; + } + if (length > maximum) throw new Error('Snapshot too large'); + const result = new Uint8Array(length); + let offset = 0; + for (const bytes of parts) { result.set(bytes, offset); offset += bytes.length; } + return new TextDecoder('utf-8', {fatal: true}).decode(result); + } finally { + await new Promise(resolve => stream.close_async(GLib.PRIORITY_DEFAULT, null, (input, result) => { + try { input.close_finish(result); } catch (_) { /* Closing during disable is harmless. */ } + resolve(); + })); + } +} diff --git a/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml b/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml new file mode 100644 index 00000000..cc467e55 --- /dev/null +++ b/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml @@ -0,0 +1,18 @@ + + + + true + Show the desktop deadline card + + + + 1.0 + Horizontal position within the primary work area + + + + 0.0 + Vertical position within the primary work area + + + diff --git a/linux/widgets/gnome/stylesheet.css b/linux/widgets/gnome/stylesheet.css new file mode 100644 index 00000000..2062b5ee --- /dev/null +++ b/linux/widgets/gnome/stylesheet.css @@ -0,0 +1,7 @@ +.techpie-deadline-row { spacing: 4px; max-width: 420px; } +.techpie-deadline-detail { font-size: 0.85em; } +.techpie-desktop-card { padding: 18px; spacing: 14px; border-radius: 16px; } +.techpie-desktop-header { font-weight: bold; padding: 8px 0; } +.techpie-desktop-rows { spacing: 12px; } +.techpie-desktop-item { text-align: left; border-radius: 8px; padding: 8px; } +.techpie-desktop-item:hover { background-color: rgba(128, 128, 128, 0.2); } diff --git a/linux/widgets/install.py b/linux/widgets/install.py new file mode 100644 index 00000000..8f49637d --- /dev/null +++ b/linux/widgets/install.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Install only TechPie's launcher and selected widgets for the current user.""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess + +ROOT = Path(__file__).resolve().parent +KDE_ID = "club.geekpie.techpie.deadlines" +GNOME_ID = "deadlines@techpie.geekpie.club" +MARKER = ".techpie-widget-install" +# Keep the runner's existing ID: path_provider uses it for app preferences. +DESKTOP_NAME = "com.example.techpie.desktop" + + +def desktop_quote(path): + value = str(path).replace("%", "%%") + for char in ('\\', '"', '`', '$'): + value = value.replace(char, '\\' + char) + # Desktop Entry string escaping is applied before Exec argument escaping. + return ('"' + value + '"').replace('\\', '\\\\') + + +def managed_copy(source, target): + if target.is_symlink() or (target.exists() and not (target / MARKER).is_file()): + raise ValueError(f"Refusing to replace an unmanaged directory: {target}") + # Source validation occurs before any existing installation is replaced. + temporary = target.with_name(target.name + ".techpie-staging") + if temporary.exists(): + raise ValueError(f"Staging directory already exists: {temporary}") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copytree(source, temporary) + (temporary / MARKER).write_text("TechPie deadline widgets v1\n", encoding="utf-8") + if target.exists(): + shutil.rmtree(target) + temporary.rename(target) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["install", "uninstall"]) + parser.add_argument("--desktop", choices=["kde", "gnome", "both"], required=True) + parser.add_argument("--app", type=Path, help="Absolute path to the built bundle/techpie") + parser.add_argument("--kde-package", type=Path, default=ROOT / "kde", + help="Built KDE package from cmake, or the bundled package") + parser.add_argument("--data-home", type=Path, + default=Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))) + args = parser.parse_args(argv) + if not args.data_home.is_absolute(): + parser.error("--data-home must be absolute") + data = args.data_home.resolve() + targets = [] + if args.desktop in ("kde", "both"): + targets.append((args.kde_package, data / "plasma/plasmoids" / KDE_ID)) + if args.desktop in ("gnome", "both"): + targets.append((ROOT / "gnome", data / "gnome-shell/extensions" / GNOME_ID)) + launcher = data / "applications" / DESKTOP_NAME + if args.action == "install": + if args.desktop in ("gnome", "both") and not shutil.which("glib-compile-schemas"): + parser.error("GNOME installation requires glib-compile-schemas (GLib)") + if not args.app or not args.app.is_absolute() or not args.app.is_file() or not os.access(args.app, os.X_OK): + parser.error("--app must name an absolute executable TechPie bundle path") + app = args.app.resolve() + icon = app.parent / "techpie.png" + if not icon.is_file(): + icon = ROOT.parents[1] / "assets/icon/icon.png" + icon_name = str(icon).replace('\\', '\\\\') if icon.is_file() else "view-calendar-tasks" + if '\n' in str(app) or '\r' in str(app): + parser.error("Application path cannot contain newlines") + for source, target in targets: + if not (source / "metadata.json").is_file(): + parser.error(f"Missing widget package: {source}") + if target.is_symlink() or (target.exists() and not (target / MARKER).is_file()): + parser.error(f"Existing directory is not managed by this installer: {target}") + if source == args.kde_package and args.desktop in ("kde", "both") and not ( + source / "contents/ui/backend/libtechpiedeadlines.so").is_file(): + parser.error("Build the KDE backend first; pass --kde-package BUILD/kde") + if launcher.exists() and "X-TechPie-Managed=true" not in launcher.read_text(encoding="utf-8"): + parser.error(f"Launcher already exists and is not managed: {launcher}") + for source, target in targets: + managed_copy(source, target) + if target.name == GNOME_ID: + shutil.copy2(ROOT / "common/snapshot.mjs", target / "snapshot.mjs") + subprocess.run(["glib-compile-schemas", "--strict", str(target / "schemas")], check=True) + launcher.parent.mkdir(parents=True, exist_ok=True) + launcher.write_text( + "[Desktop Entry]\nType=Application\nName=TechPie\n" + f"Exec={desktop_quote(app)} %u\nIcon={icon_name}\n" + "Terminal=false\nCategories=Education;\nMimeType=x-scheme-handler/techpie;\n" + "StartupWMClass=com.example.techpie\nX-TechPie-Managed=true\n", encoding="utf-8") + print("Installed. Enable Deadline widgets in TechPie Settings.") + if args.desktop in ("gnome", "both"): + print(f"GNOME: log out/in if newly installed, then enable {GNOME_ID} in Extensions.") + if args.desktop in ("kde", "both"): + print("KDE: use Add Widgets and select TechPie Deadlines (restart Plasma session if needed).") + else: + for _, target in targets: + if target.is_symlink(): + parser.error(f"Refusing to remove a symlink: {target}") + if target.exists(): + if not (target / MARKER).is_file(): + parser.error(f"Refusing to remove an unmanaged directory: {target}") + for _, target in targets: + if target.exists(): + shutil.rmtree(target) + # Keep the launcher if the other desktop's widget is still installed. + other_installed = any((path / MARKER).exists() for path in ( + data / "plasma/plasmoids" / KDE_ID, data / "gnome-shell/extensions" / GNOME_ID)) + if not other_installed and launcher.exists() and "X-TechPie-Managed=true" in launcher.read_text(encoding="utf-8"): + launcher.unlink() + print("Removed selected widget packages. Application and snapshots are retained.") + update = shutil.which("update-desktop-database") + if update and launcher.parent.exists(): + subprocess.run([update, str(launcher.parent)], check=True) + + +if __name__ == "__main__": + main() diff --git a/linux/widgets/kde/backend/deadline_model.cpp b/linux/widgets/kde/backend/deadline_model.cpp new file mode 100644 index 00000000..8733a89d --- /dev/null +++ b/linux/widgets/kde/backend/deadline_model.cpp @@ -0,0 +1,83 @@ +#include "deadline_model.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool timestamp(const QJsonValue& value) { + return value.isDouble() && std::isfinite(value.toDouble()) && value.toDouble() >= 0 && + value.toDouble() <= 253402300799.0; +} +static bool text(const QJsonValue& value) { + return value.isString() && value.toString().toUtf8().size() <= 4096; +} + +DeadlineModel::DeadlineModel(QObject* parent) : QObject(parent) { + m_path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + + "/techpie/widgets/deadline-widget-v1.json"; + connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &DeadlineModel::refresh); + connect(&m_timer, &QTimer::timeout, this, &DeadlineModel::refresh); + m_timer.start(30000); + refresh(); +} + +void DeadlineModel::refresh() { + m_now = QDateTime::currentMSecsSinceEpoch() / 1000.0; + m_items.clear(); + m_writtenAt = 0; + m_state = "unavailable"; + QString directory = QFileInfo(m_path).absolutePath(); + while (!QDir(directory).exists() && directory != "/") + directory = QFileInfo(directory).absolutePath(); + if (m_watcher.directories() != QStringList{directory}) { + if (!m_watcher.directories().isEmpty()) m_watcher.removePaths(m_watcher.directories()); + m_watcher.addPath(directory); + } + QFile file(m_path); + if (!file.exists()) { m_state = "notSynced"; emit changed(); return; } + if (!file.open(QIODevice::ReadOnly)) { emit changed(); return; } + const QByteArray data = file.read(262145); + if (data.size() > 262144) { emit changed(); return; } + const auto document = QJsonDocument::fromJson(data); + const auto object = document.object(); + const auto array = object.value("items").toArray(); + if (!document.isObject() || object.size() != 3 || object.value("schemaVersion").toDouble() != 1 || + !timestamp(object.value("writtenAt")) || !object.value("items").isArray() || array.size() > 512) { + emit changed(); return; + } + QSet ids; + for (const auto& value : array) { + const auto item = value.toObject(); + const QString id = item.value("id").toString(); + const QString kind = item.value("kind").toString(); + if (!value.isObject() || item.size() != 5 || !text(item.value("id")) || id.isEmpty() || + ids.contains(id) || (kind != "assignment" && kind != "exam") || + !text(item.value("title")) || !text(item.value("course")) || !timestamp(item.value("dueAt"))) { + m_items.clear(); emit changed(); return; + } + ids.insert(id); + if (item.value("dueAt").toDouble() > m_now) m_items.append(item.toVariantMap()); + } + std::sort(m_items.begin(), m_items.end(), [](const QVariant& a, const QVariant& b) { + const auto x = a.toMap(), y = b.toMap(); + const double dx = x.value("dueAt").toDouble(), dy = y.value("dueAt").toDouble(); + return dx == dy ? x.value("id").toString() < y.value("id").toString() : dx < dy; + }); + m_writtenAt = object.value("writtenAt").toDouble(); + m_state = "ready"; + emit changed(); +} + +bool DeadlineModel::openApp() { + return QDesktopServices::openUrl(QUrl(QStringLiteral("techpie://deadlines"))); +} diff --git a/linux/widgets/kde/backend/deadline_model.h b/linux/widgets/kde/backend/deadline_model.h new file mode 100644 index 00000000..eeef1966 --- /dev/null +++ b/linux/widgets/kde/backend/deadline_model.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include + +class DeadlineModel : public QObject { + Q_OBJECT + Q_PROPERTY(QString state READ state NOTIFY changed) + Q_PROPERTY(QVariantList items READ items NOTIFY changed) + Q_PROPERTY(double writtenAt READ writtenAt NOTIFY changed) + Q_PROPERTY(double now READ now NOTIFY changed) +public: + explicit DeadlineModel(QObject* parent = nullptr); + QString state() const { return m_state; } + QVariantList items() const { return m_items; } + double writtenAt() const { return m_writtenAt; } + double now() const { return m_now; } + Q_INVOKABLE void refresh(); + Q_INVOKABLE bool openApp(); +signals: + void changed(); +private: + QFileSystemWatcher m_watcher; + QTimer m_timer; + QString m_path; + QString m_state = "notSynced"; + QVariantList m_items; + double m_writtenAt = 0; + double m_now = 0; +}; diff --git a/linux/widgets/kde/backend/plugin.cpp b/linux/widgets/kde/backend/plugin.cpp new file mode 100644 index 00000000..377c6993 --- /dev/null +++ b/linux/widgets/kde/backend/plugin.cpp @@ -0,0 +1,13 @@ +#include "deadline_model.h" +#include +#include + +class DeadlinePlugin : public QQmlExtensionPlugin { + Q_OBJECT + Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) +public: + void registerTypes(const char* uri) override { + qmlRegisterType(uri, 1, 0, "DeadlineModel"); + } +}; +#include "plugin.moc" diff --git a/linux/widgets/kde/contents/ui/backend/qmldir b/linux/widgets/kde/contents/ui/backend/qmldir new file mode 100644 index 00000000..116972d1 --- /dev/null +++ b/linux/widgets/kde/contents/ui/backend/qmldir @@ -0,0 +1 @@ +plugin techpiedeadlines diff --git a/linux/widgets/kde/contents/ui/main.qml b/linux/widgets/kde/contents/ui/main.qml new file mode 100644 index 00000000..f77181bf --- /dev/null +++ b/linux/widgets/kde/contents/ui/main.qml @@ -0,0 +1,101 @@ +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as Controls +import org.kde.plasma.plasmoid +import org.kde.plasma.core as PlasmaCore +import org.kde.plasma.components as PlasmaComponents +import org.kde.kirigami as Kirigami +import "backend" as Backend + +PlasmoidItem { + id: root + Backend.DeadlineModel { id: deadlines } + preferredRepresentation: Plasmoid.formFactor === PlasmaCore.Types.Horizontal || + Plasmoid.formFactor === PlasmaCore.Types.Vertical ? compactRepresentation : fullRepresentation + switchWidth: Kirigami.Units.gridUnit * 12 + switchHeight: Kirigami.Units.gridUnit * 8 + + compactRepresentation: PlasmaComponents.ToolButton { + icon.name: "view-calendar-tasks" + text: deadlines.items.length ? root.remaining(deadlines.items[0].dueAt) : "TechPie" + display: Controls.AbstractButton.TextBesideIcon + onClicked: root.expanded = !root.expanded + } + + function remaining(dueAt) { + const hours = Math.floor((dueAt - deadlines.now) / 3600) + return hours < 1 ? "<1h" : hours < 24 ? hours + "h" : + Math.floor(hours / 24) + "d " + hours % 24 + "h" + } + + fullRepresentation: ColumnLayout { + Layout.minimumWidth: Kirigami.Units.gridUnit * 12 + Layout.minimumHeight: Kirigami.Units.gridUnit * 8 + Layout.preferredWidth: Kirigami.Units.gridUnit * 20 + Layout.preferredHeight: Kirigami.Units.gridUnit * 16 + spacing: Kirigami.Units.smallSpacing + RowLayout { + Layout.fillWidth: true + PlasmaComponents.Label { text: "TechPie Deadlines"; font.bold: true; Layout.fillWidth: true } + PlasmaComponents.ToolButton { + icon.name: "document-open" + Accessible.name: "Open TechPie Deadlines" + onClicked: deadlines.openApp() + } + } + PlasmaComponents.Label { + visible: deadlines.state !== "ready" || deadlines.items.length === 0 + Layout.fillWidth: true + Layout.fillHeight: true + wrapMode: Text.Wrap + text: deadlines.state === "unavailable" ? "Deadline data is unavailable" : + deadlines.state === "notSynced" ? "Enable Deadline widgets in TechPie Settings" : + "No upcoming deadlines" + } + ListView { + id: list + visible: deadlines.state === "ready" && deadlines.items.length > 0 + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + spacing: Kirigami.Units.smallSpacing + model: deadlines.items.slice(0, height < Kirigami.Units.gridUnit * 8 ? 2 : + height < Kirigami.Units.gridUnit * 14 ? 4 : 8) + delegate: PlasmaComponents.ItemDelegate { + required property var modelData + width: list.width + Accessible.name: modelData.title + ", " + modelData.course + ", " + + new Date(modelData.dueAt * 1000).toLocaleString() + onClicked: deadlines.openApp() + contentItem: ColumnLayout { + RowLayout { + Layout.fillWidth: true + Kirigami.Icon { + source: modelData.kind === "exam" ? "view-calendar-tasks" : "document-edit" + Layout.preferredWidth: Kirigami.Units.iconSizes.small + Layout.preferredHeight: Kirigami.Units.iconSizes.small + } + PlasmaComponents.Label { + text: modelData.title; font.bold: true + elide: Text.ElideRight; Layout.fillWidth: true + } + PlasmaComponents.Label { + text: root.remaining(modelData.dueAt) + color: modelData.dueAt - deadlines.now < 3600 ? Kirigami.Theme.negativeTextColor : Kirigami.Theme.textColor + } + } + PlasmaComponents.Label { + text: modelData.course + " · " + new Date(modelData.dueAt * 1000).toLocaleString() + elide: Text.ElideRight; Layout.fillWidth: true; opacity: 0.7 + } + } + } + } + PlasmaComponents.Label { + visible: deadlines.state === "ready" + text: "Cached snapshot · " + new Date(deadlines.writtenAt * 1000).toLocaleString() + font.pointSize: Kirigami.Theme.smallFont.pointSize + elide: Text.ElideRight; Layout.fillWidth: true; opacity: 0.7 + } + } +} diff --git a/linux/widgets/kde/metadata.json b/linux/widgets/kde/metadata.json new file mode 100644 index 00000000..657641af --- /dev/null +++ b/linux/widgets/kde/metadata.json @@ -0,0 +1,14 @@ +{ + "KPlugin": { + "Id": "club.geekpie.techpie.deadlines", + "Name": "TechPie Deadlines", + "Description": "Upcoming assignments and exams from TechPie", + "Icon": "view-calendar-tasks", + "Version": "1.0", + "Authors": [{"Name": "TechPie contributors"}], + "Category": "Date and Time" + }, + "KPackageStructure": "Plasma/Applet", + "X-Plasma-API-Minimum-Version": "6.0", + "X-Plasma-FormFactors": ["desktop", "horizontal", "vertical"] +} diff --git a/linux/widgets/tests/desktop-stacking.test.mjs b/linux/widgets/tests/desktop-stacking.test.mjs new file mode 100644 index 00000000..64c92374 --- /dev/null +++ b/linux/widgets/tests/desktop-stacking.test.mjs @@ -0,0 +1,104 @@ +// Run: node --experimental-vm-modules --test linux/widgets/tests/desktop-stacking.test.mjs +import {readFileSync} from 'node:fs'; +import vm from 'node:vm'; +import assert from 'node:assert/strict'; +import {test} from 'node:test'; + +const pending = new Map(); +let nextId = 1; +const laters = { + add(_phase, callback) { const id = nextId++; pending.set(id, callback); return id; }, + remove(id) { pending.delete(id); }, +}; +const context = vm.createContext({global: {compositor: {get_laters: () => laters}}}); +const modules = new Map([ + ['gi://Clutter', {default: {}}], + ['gi://St', {default: {}}], + ['gi://Meta', {default: {WindowType: {DESKTOP: 1}, LaterType: {BEFORE_REDRAW: 5}}}], + ['resource:///org/gnome/shell/ui/main.js', {layoutManager: {untrackChrome() {}}}], + ['./snapshot.mjs', {upcoming() {}, remaining() {}, urgency() {}}], +]); +const filename = process.env.TECHPIE_CARD_MODULE ?? + new URL('../gnome/desktopCard.js', import.meta.url); +const module = new vm.SourceTextModule(readFileSync(filename, 'utf8'), {context}); +await module.link(specifier => { + const exports = modules.get(specifier); + assert.ok(exports, `unexpected dependency: ${specifier}`); + return new vm.SyntheticModule(Object.keys(exports), function () { + for (const [key, value] of Object.entries(exports)) this.setExport(key, value); + }, {context}); +}); +await module.evaluate(); +const {DesktopCard} = module.namespace; + +function fixture() { + pending.clear(); + const window = (type, shown = true) => ({visible: shown, mapped: shown, + get_meta_window: () => ({get_window_type: () => type})}); + const hiddenApp = window(0, false); + const desktop = window(1); + const visibleApp = window(0); + const actor = {destroy() { this.destroyed = true; }}; + const children = [hiddenApp, actor, desktop, visibleApp]; + const move = (child, sibling, offset) => { + children.splice(children.indexOf(child), 1); + const index = sibling ? children.indexOf(sibling) + offset : children.length; + children.splice(index, 0, child); + }; + const card = Object.create(DesktopCard.prototype); + Object.assign(card, {actor, _signals: [], _windowGroup: { + get_children: () => children, + set_child_below_sibling: (a, sibling) => move(a, sibling, 0), + set_child_above_sibling: (a, sibling) => move(a, sibling, 1), + }}); + const paint = () => { + const callbacks = [...pending.values()]; pending.clear(); + for (const callback of callbacks) callback(); + }; + return {card, actor, children, hiddenApp, desktop, visibleApp, paint}; +} + +test('a minimized actor before DING never pulls the card underneath DING', () => { + const f = fixture(); + f.card._restack(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.visibleApp)); +}); + +test('restacking runs after compositor stack changes, before painting', () => { + const f = fixture(); + f.card._queueRestack(); + assert.equal(pending.size, 1); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.desktop)); + f.children.splice(f.children.indexOf(f.actor), 1); + f.children.unshift(f.actor); // Mutter overwrites the order after restacked. + f.paint(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.visibleApp)); +}); + +test('coalesces repeated events and allows a later restack', () => { + const f = fixture(); + for (let i = 0; i < 20; i++) f.card._queueRestack(); + assert.equal(pending.size, 1); + f.paint(); + f.card._queueRestack(); + assert.equal(pending.size, 1); +}); + +test('with all apps minimized the card stays above the desktop', () => { + const f = fixture(); + f.visibleApp.visible = f.visibleApp.mapped = false; + f.card._restack(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); +}); + +test('destroy cancels queued work and never schedules another callback', () => { + const f = fixture(); + f.card._queueRestack(); + f.card.destroy(); + assert.equal(pending.size, 0); + assert.equal(f.actor.destroyed, true); + f.card._queueRestack(); + assert.equal(pending.size, 0); +}); diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements index 85cd58de..ca757edc 100644 --- a/macos/Runner/Release.entitlements +++ b/macos/Runner/Release.entitlements @@ -6,6 +6,8 @@ com.apple.security.network.client + com.apple.security.network.server + keychain-access-groups $(AppIdentifierPrefix)$(CFBundleIdentifier) diff --git a/ohos/scripts/generate-build-profile.mjs b/ohos/scripts/generate-build-profile.mjs index 3a3460fd..70ca6440 100755 --- a/ohos/scripts/generate-build-profile.mjs +++ b/ohos/scripts/generate-build-profile.mjs @@ -98,8 +98,8 @@ function generateBuildProfile() { // Drop the signing block and the product's reference to it: hvigor then has // nothing to sign with and writes `entry-default-unsigned.hap`. content = content - .replace(/"signingConfigs":\s*\[[\s\S]*?\n \],\n/, '') - .replace(/"signingConfig": "default",\n/, ''); + .replace(/"signingConfigs":\s*\[[\s\S]*?\r?\n \],\r?\n/, '') + .replace(/"signingConfig": "default",\r?\n/, ''); if (content.includes('signingConfig')) { throw new Error('Could not strip the signing block from the template'); } diff --git a/pubspec.yaml b/pubspec.yaml index cfcea275..5d4583f8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -161,8 +161,9 @@ flutter_launcher_icons: android: true min_sdk_android: 21 adaptive_icon_background: "#FFFFFF" - adaptive_icon_foreground: "assets/icon/icon_foreground.png" - adaptive_icon_monochrome: "assets/icon/icon_monochrome.png" + # Use the source directly: Git symlinks may become text files on Windows. + adaptive_icon_foreground: "assets/icon/icon.png" + adaptive_icon_monochrome: "assets/icon/icon.png" ios: true remove_alpha_ios: true web: diff --git a/test/back_navigation_test.dart b/test/back_navigation_test.dart index 9fd4d890..9e046c9c 100644 --- a/test/back_navigation_test.dart +++ b/test/back_navigation_test.dart @@ -1,8 +1,10 @@ import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:techpie/main.dart'; import 'package:techpie/pages/debug_log_page.dart'; +import 'package:techpie/pages/settings_page.dart'; import 'package:techpie/services/assignment_service.dart'; import 'package:techpie/services/auth_service.dart'; import 'package:techpie/services/campus_card_service.dart'; @@ -26,9 +28,7 @@ void main() { testWidgets('the system back leaves a settings subpage rather than the app', ( WidgetTester tester, ) async { - // Wide enough for the non-compact layout, and tall enough that the debug - // tiles at the bottom of the settings list are not under the navigation bar — - // a tap on an obscured tile does nothing, silently. + // Keep the wide layout so the settings subpage uses its nested navigator. tester.view.physicalSize = const Size(1200, 1400); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); @@ -90,8 +90,19 @@ void main() { await tester.tap(find.text('Settings').first); await tester.pumpAndSettle(); - // Only the debug section is reachable without an account; the window above is - // tall enough for it to be on screen. + // Settings can grow as options are added. Scroll the actual settings list + // until the entry can receive taps, including above the bottom navigation. + await tester.scrollUntilVisible( + find.text('View Logs').hitTestable(), + 200, + scrollable: find + .descendant( + of: find.byType(SettingsPage), + matching: find.byType(Scrollable), + ) + .first, + ); + await tester.pumpAndSettle(); await tester.tap(find.text('View Logs')); await tester.pumpAndSettle(); expect(find.byType(DebugLogPage), findsOneWidget); @@ -102,7 +113,8 @@ void main() { expect( platformCalls, isNot(contains('SystemNavigator.pop')), - reason: 'the back gesture left the subpage, so the app must not be asked to close', + reason: + 'the back gesture left the subpage, so the app must not be asked to close', ); expect(find.byType(DebugLogPage), findsNothing); }); diff --git a/test/campus_card/architecture/environment_isolation_test.dart b/test/campus_card/architecture/environment_isolation_test.dart index 2eef7ad0..42df6d76 100644 --- a/test/campus_card/architecture/environment_isolation_test.dart +++ b/test/campus_card/architecture/environment_isolation_test.dart @@ -94,7 +94,9 @@ void main() { // The trace is the one place allowed to log; its own gate is covered by // test/campus_card_http_trace_test.dart. .where( - (file) => !file.path.endsWith('data/api/decrypted_http_trace.dart'), + (file) => !file.path + .replaceAll('\\', '/') + .endsWith('data/api/decrypted_http_trace.dart'), )) { expect( file.readAsStringSync(), diff --git a/test/campus_card/architecture/platform_contract_test.dart b/test/campus_card/architecture/platform_contract_test.dart index fe6afee2..cd78ab32 100644 --- a/test/campus_card/architecture/platform_contract_test.dart +++ b/test/campus_card/architecture/platform_contract_test.dart @@ -91,7 +91,11 @@ void main() { ); for (final entity in presentation.listSync(recursive: true)) { if (entity is! File || !entity.path.endsWith('.dart')) continue; - if (entity.path.endsWith('/icons/platform_icons.dart')) continue; + if (entity.path + .replaceAll('\\', '/') + .endsWith('/icons/platform_icons.dart')) { + continue; + } expect( entity.readAsStringSync(), isNot(contains('CupertinoIcons.')), diff --git a/test/feedback_entry_test.dart b/test/feedback_entry_test.dart new file mode 100644 index 00000000..19d225de --- /dev/null +++ b/test/feedback_entry_test.dart @@ -0,0 +1,88 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/widgets/feedback_entry.dart'; + +void main() { + testWidgets('successful launch preserves feedback entry without a dialog', + (tester) async { + Uri? opened; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (url) async { + opened = url; + return true; + }, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pumpAndSettle(); + expect(opened.toString(), 'https://techpie-feedback.dzhes.app'); + expect(find.text('无法打开反馈页面'), findsNothing); + }); + + for (final throws in [false, true]) { + testWidgets('launch ${throws ? 'exception' : 'false'} offers copyable link', + (tester) async { + String? copied; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (_) async { + if (throws) throw PlatformException(code: 'unavailable'); + return false; + }, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pumpAndSettle(); + expect(find.text('无法打开反馈页面'), findsOneWidget); + await tester.tap(find.text('复制链接')); + await tester.pumpAndSettle(); + expect(copied, 'https://techpie-feedback.dzhes.app'); + }); + } + + testWidgets('late launch failure after navigation does not display a dialog', + (tester) async { + final pending = Completer(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (_) => pending.future, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pump(); + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + pending.complete(false); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('无法打开反馈页面'), findsNothing); + }); +} diff --git a/test/genai_gateway_test.dart b/test/genai_gateway_test.dart new file mode 100644 index 00000000..100d49d3 --- /dev/null +++ b/test/genai_gateway_test.dart @@ -0,0 +1,760 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/services/genai/genai_gateway.dart'; +import 'package:techpie/services/genai/genai_login.dart'; +import 'package:techpie/services/genai/genai_tools.dart'; + +void main() { + late HttpServer upstream; + late GenaiGateway gateway; + late HttpClient client; + final received = {}; + String reply = '你好'; + bool businessError = false; + String? finishReason = 'stop'; + bool done = false; + List>>? attemptPackets; + final bodies = []; + final diagnostics = >[]; + Completer? upstreamGate; + + setUp(() async { + upstream = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + received.clear(); + reply = '你好'; + businessError = false; + finishReason = 'stop'; + done = false; + diagnostics.clear(); + attemptPackets = null; + bodies.clear(); + upstreamGate = null; + upstream.listen((request) async { + received['token'] = request.headers.value('x-access-token'); + if (request.uri.path.endsWith('/list')) { + request.response.headers.contentType = ContentType.json; + request.response.write( + jsonEncode({ + 'success': true, + 'result': { + 'records': [ + {'aiType': 'test-model', 'rootAiType': 'azure'}, + {'aiType': 'test-model'}, + ], + }, + }), + ); + } else { + await upstreamGate?.future; + received['body'] = jsonDecode(await utf8.decoder.bind(request).join()); + bodies.add(received['body']); + request.response.headers.contentType = + ContentType('text', 'event-stream', charset: 'utf-8'); + if (attemptPackets != null) { + final index = bodies.length - 1; + final packets = + attemptPackets![index < attemptPackets!.length ? index : attemptPackets!.length - 1]; + for (final packet in packets) { + request.response.write('data: ${jsonEncode(packet)}\n\n'); + } + } else if (businessError) { + request.response + .write('data: ${jsonEncode({'success': false, 'message': 'Token失效'})}\n\n'); + } else { + // The final text shares an event with finish_reason. + request.response.write('data: ${jsonEncode({ + 'choices': [ + { + 'delta': {'content': reply, 'reasoning': '思考'}, + 'finish_reason': finishReason, + } + ], + })}\n\n'); + } + } + if (done) request.response.write('data: [DONE]\n\n'); + await request.response.close(); + }); + gateway = GenaiGateway( + onDiagnostic: diagnostics.add, + upstream: Uri.parse('http://127.0.0.1:${upstream.port}'), + heartbeatInterval: const Duration(milliseconds: 30), + ); + await gateway.start( + host: '127.0.0.1', + port: 0, + genaiToken: 'upstream-token', + apiToken: 'local-token', + ); + client = HttpClient(); + }); + tearDown(() async { + client.close(force: true); + await gateway.stop(); + await upstream.close(force: true); + }); + + Future<({int status, String body})> request( + String path, { + Object? body, + String? token = 'local-token', + }) async { + final req = await client.openUrl( + body == null ? 'GET' : 'POST', + Uri.parse('http://127.0.0.1:${gateway.port}$path'), + ); + if (token != null) req.headers.set('Authorization', 'Bearer $token'); + if (body != null) { + req.headers.contentType = ContentType.json; + req.write(jsonEncode(body)); + } + final res = await req.close(); + return (status: res.statusCode, body: await utf8.decoder.bind(res).join()); + } + + test('local token is separate from the upstream token', () async { + expect((await request('/v1/models', token: null)).status, 401); + expect((await request('/v1/models', token: 'upstream-token')).status, 401); + final res = await request('/v1/models'); + expect(res.status, 200); + expect((jsonDecode(res.body)['data'] as List).length, 1); + expect(received['token'], 'upstream-token'); + }); + + test('nonstream reply preserves final text and model routing', () async { + await request('/v1/models'); + final res = await request( + '/v1/chat/completions', + body: { + 'model': 'test-model', + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }, + ); + expect(res.status, 200); + expect(jsonDecode(res.body)['choices'][0]['message']['content'], '你好'); + expect(received['body']['rootAiType'], 'azure'); + expect(received['token'], 'upstream-token'); + }); + + test('SSE contains text, reasoning and completion', () async { + final res = await request( + '/v1/chat/completions', + body: { + 'model': 'test-model', + 'stream': true, + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }, + ); + expect(res.status, 200); + expect(res.body, contains('你好')); + expect(res.body, contains('reasoning_content')); + expect(res.body, contains('[DONE]')); + }); + + test('tool JSON becomes tool_calls', () async { + reply = '{"tool_calls":[{"name":"weather","arguments":{"city":"上海"}}]}'; + final res = await request( + '/v1/chat/completions', + body: { + 'model': 'test-model', + 'messages': [ + {'role': 'user', 'content': '天气'}, + ], + 'tools': [ + { + 'type': 'function', + 'function': {'name': 'weather'}, + } + ], + }, + ); + final choice = jsonDecode(res.body)['choices'][0]; + expect(choice['finish_reason'], 'tool_calls'); + expect(choice['message']['tool_calls'][0]['function']['arguments'], '{"city":"上海"}'); + }); + + test('Responses endpoint accepts instructions and input', () async { + final res = await request( + '/v1/responses', + body: {'model': 'test-model', 'input': 'hi', 'instructions': 'test'}, + ); + expect(jsonDecode(res.body)['output_text'], '你好'); + expect(received['body']['messages'][0]['role'], 'system'); + }); + + test('business errors are returned instead of empty replies', () async { + businessError = true; + final res = await request( + '/v1/chat/completions', + body: { + 'model': 'test-model', + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }, + ); + expect(res.status, isNot(200)); + expect(res.body, contains('Token失效')); + }); + + test('server releases the port when stopped', () async { + final port = gateway.port!; + await gateway.stop(); + final replacement = await HttpServer.bind('127.0.0.1', port); + await replacement.close(force: true); + expect(gateway.running, false); + }); + + test('CAS fields accept either attribute order and quote style', () { + expect(GenaiLogin.field('', 'pwdEncryptSalt'), 'salt'); + expect(GenaiLogin.field("", 'execution'), 'e1s1'); + }); + test('CAS password encryption matches GenAI2OpenAI', () { + expect( + GenaiLogin.encryptPassword('test-password', '1234567890123456'), + '2LWYSMdnDJSym1TSN54ueiM+MTqBzvtIizRb62ttRF7LHyqJnnRF7TSKdRbojVUw0FcpVIctqIMgcad48Yo0iXPW9Ddd5+5IsUJRylmMEbw=', + ); + }); + + test('CAS login follows cookies and extracts token from redirect', () async { + final ids = await HttpServer.bind('127.0.0.1', 0); + addTearDown(() => ids.close(force: true)); + ids.listen((req) async { + if (req.uri.path == '/htk/user/login') { + req.response.statusCode = 302; + req.response.headers.set('location', '/authserver/login'); + } else if (req.method == 'GET') { + req.response.cookies.add(Cookie('session', 'fixture')); + req.response.headers.contentType = ContentType.html; + req.response.write('' + ''); + } else { + expect(req.cookies.single.value, 'fixture'); + final form = Uri.splitQueryString(await utf8.decoder.bind(req).join()); + expect(form['username'], 'test-student'); + expect(form['password'], GenaiLogin.encryptPassword('test-password', '1234567890123456')); + req.response.statusCode = HttpStatus.found; + req.response.headers.set('location', '/dialogue?token=fixture-token'); + } + await req.response.close(); + }); + final login = GenaiLogin(genaiBase: Uri.parse('http://127.0.0.1:${ids.port}')); + expect(await login.login('test-student', 'test-password'), 'fixture-token'); + }); + test('tool SSE sends heartbeats before upstream headers arrive', () async { + upstreamGate = Completer(); + final req = + await client.postUrl(Uri.parse('http://127.0.0.1:${gateway.port}/v1/chat/completions')); + req.headers.set('Authorization', 'Bearer local-token'); + req.headers.contentType = ContentType.json; + req.write( + jsonEncode({ + 'model': 'test-model', + 'stream': true, + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + 'tools': [ + { + 'type': 'function', + 'function': {'name': 'weather'}, + } + ], + }), + ); + final res = await req.close().timeout(const Duration(seconds: 2)); + expect(res.statusCode, 200); + final lines = StreamIterator(res.transform(utf8.decoder).transform(const LineSplitter())); + try { + expect(await lines.moveNext().timeout(const Duration(seconds: 2)), true); + expect(lines.current, ': keep-alive'); + expect(upstreamGate!.isCompleted, false); + await lines.moveNext(); // Empty separator. + expect(await lines.moveNext().timeout(const Duration(seconds: 2)), true); + expect(lines.current, ': keep-alive'); + upstreamGate!.complete(); + final text = StringBuffer(); + while (await lines.moveNext()) { + text.writeln(lines.current); + } + expect(text.toString(), contains('[DONE]')); + expect(text.toString(), contains('你好')); + } finally { + if (!upstreamGate!.isCompleted) upstreamGate!.complete(); + await lines.cancel(); + } + }); + + test('empty tool streams return an error and terminate', () async { + reply = ''; + final res = await request( + '/v1/chat/completions', + body: { + 'model': 'test-model', + 'stream': true, + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + 'tools': [ + { + 'type': 'function', + 'function': {'name': 'weather'}, + } + ], + }, + ); + expect(res.body, contains('upstream_error')); + expect(res.body, contains('[DONE]')); + expect(res.body, isNot(contains('"finish_reason":"stop"'))); + }); + final tool = { + 'type': 'function', + 'function': {'name': 'weather'}, + }; + Map payload({bool stream = false, bool tools = false}) => { + 'model': 'test-model', + 'stream': stream, + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + if (tools) 'tools': [tool], + }; + for (final stream in [false, true]) { + for (final reason in ['length', 'content_filter']) { + test('$reason is preserved, stream=$stream', () async { + finishReason = reason; + final res = await request('/v1/chat/completions', body: payload(stream: stream)); + expect(res.body, contains('"finish_reason":"$reason"')); + expect(res.body, contains('你好')); + }); + } + test('EOF is an error, stream=$stream', () async { + finishReason = null; + final res = await request('/v1/chat/completions', body: payload(stream: stream)); + expect(res.body, contains('回复中断')); + expect(res.body, isNot(contains('"finish_reason":"stop"'))); + }); + test('explicit DONE succeeds, stream=$stream', () async { + finishReason = null; + done = true; + final res = await request('/v1/chat/completions', body: payload(stream: stream)); + expect(res.body, contains('"finish_reason":"stop"')); + expect(diagnostics.last['saw_done'], true); + }); + test('truncated tool is never executed, stream=$stream', () async { + finishReason = 'length'; + reply = '{"name":"weather","arguments":{}}'; + final res = await request('/v1/chat/completions', body: payload(stream: stream, tools: true)); + expect(res.body, contains('工具调用未完成')); + expect(res.body, isNot(contains('"finish_reason":"tool_calls"'))); + }); + test('multiple tools survive HTTP, stream=$stream', () async { + reply = + '[{"function":{"name":"weather","arguments":"{}"}},{"name":"weather","arguments":{}}] https://example.org'; + final res = await request('/v1/chat/completions', body: payload(stream: stream, tools: true)); + expect(res.body, contains('"finish_reason":"tool_calls"')); + expect(diagnostics.last['call_count'], 2); + }); + test('invalid tools fail HTTP, stream=$stream', () async { + reply = '[{"name":"unknown","arguments":{}}]'; + final res = await request('/v1/chat/completions', body: payload(stream: stream, tools: true)); + expect(res.body, contains('工具名称不在本次请求中')); + }); + test('Responses tools native lifecycle, stream=$stream', () async { + reply = '{"function":{"name":"weather","arguments":"{}"}}'; + final res = await request( + '/v1/responses', + body: { + 'model': 'test-model', + 'stream': stream, + 'input': '天气', + 'tools': [ + { + 'type': 'function', + 'name': 'weather', + 'parameters': {'type': 'object'}, + } + ], + }, + ); + expect(res.body, contains('"type":"function_call"')); + expect(res.body, isNot(contains('"type":"message"'))); + if (stream) { + expect(res.body, contains('response.function_call_arguments.delta')); + expect(res.body, contains('response.output_item.done')); + expect(res.body, contains('response.completed')); + } + }); + } + final goodCalls = [ + '{"tool_calls":[{"name":"weather","arguments":{}}]}', + '[{"id":"call_x","type":"function","function":{"name":"weather","arguments":"{}"}}] link', + '{"function":{"name":"weather","arguments":{}}}', + '{"name":"weather"}{"name":"weather"}', + '{"name":"weather","arguments":{}} {"name":"weather","arguments":{}}', + ]; + for (var i = 0; i < goodCalls.length; i++) { + test('parser supported format $i', () { + final calls = parseGenaiToolCalls(goodCalls[i], {'weather'}, null); + expect(calls.length, i >= 3 ? 2 : 1); + expect(calls.first['function']['arguments'], '{}'); + if (i == 1) expect(calls.first['id'], 'call_x'); + }); + } + final badCalls = [ + '{"tool_calls":[{"name":"weather"},', + '{"name":"weather"}', + '{"name":"unknown","arguments":{}}', + '{"name":"weather","arguments":"oops"}', + '{"name":"weather","arguments":[]}', + '{"name":"weather","arguments":"[]"}', + '{"tool_calls":"oops"}', + '[{"name":"weather","arguments":{}},4]', + ]; + for (var i = 0; i < badCalls.length; i++) { + test('parser rejects invalid format $i', () { + expect(() => parseGenaiToolCalls(badCalls[i], {'weather'}, null), throwsFormatException); + }); + } + test('required and selected tools are enforced; final text stays valid', () async { + expect(parseGenaiToolCalls('已完成', {'weather'}, null), isEmpty); + for (final choice in [ + 'required', + { + 'type': 'function', + 'function': {'name': 'weather'}, + } + ]) { + final res = await request( + '/v1/chat/completions', + body: {...payload(tools: true), 'tool_choice': choice}, + ); + expect(res.body, contains('未返回指定工具调用')); + } + }); + test('completion limit precedence and diagnostics contain metadata only', () async { + await request( + '/v1/chat/completions', + body: {...payload(), 'max_completion_tokens': 321, 'max_tokens': 12}, + ); + expect(received['body']['maxToken'], 321); + expect(diagnostics.last['output_limit'], 321); + expect(jsonEncode(diagnostics), isNot(contains('你好'))); + expect(jsonEncode(diagnostics), isNot(contains('upstream-token'))); + }); + test('Responses history preserves call IDs, arguments, output and assistant content', () async { + final res = await request( + '/v1/responses', + body: { + 'model': 'test-model', + 'input': [ + { + 'type': 'message', + 'role': 'user', + 'content': [ + {'type': 'input_text', 'text': '天气'}, + ], + }, + {'type': 'function_call', 'call_id': 'call_x', 'name': 'weather', 'arguments': '{}'}, + {'type': 'function_call_output', 'call_id': 'call_x', 'output': '夹具:晴'}, + ], + 'max_output_tokens': 77, + }, + ); + expect(jsonDecode(res.body)['output_text'], '你好'); + expect(jsonEncode(received['body']['messages']), contains('call_x')); + expect(jsonEncode(received['body']['messages']), contains('夹具:晴')); + expect(received['body']['maxToken'], 77); + await request( + '/v1/chat/completions', + body: { + ...payload(), + 'messages': [ + { + 'role': 'assistant', + 'content': '先看天气', + 'tool_calls': [ + { + 'id': 'call_x', + 'function': {'name': 'weather', 'arguments': '{}'}, + } + ], + }, + {'role': 'tool', 'tool_call_id': 'call_x', 'content': '晴'}, + ], + }, + ); + expect(received['body']['messages'][0]['content'], contains('先看天气')); + }); + test('Responses length is incomplete and EOF streaming is failed', () async { + finishReason = 'length'; + var res = await request('/v1/responses', body: {'model': 'test-model', 'input': 'hi'}); + expect(jsonDecode(res.body)['status'], 'incomplete'); + finishReason = null; + res = await request( + '/v1/responses', + body: {'model': 'test-model', 'input': 'hi', 'stream': true}, + ); + expect(res.body, contains('response.failed')); + expect(res.body, isNot(contains('response.completed'))); + }); + test('client cancellation closes the pending upstream request', () async { + upstreamGate = Completer(); + final req = + await client.postUrl(Uri.parse('http://127.0.0.1:${gateway.port}/v1/chat/completions')); + req.headers.set('Authorization', 'Bearer local-token'); + req.headers.contentType = ContentType.json; + req.write(jsonEncode(payload(stream: true))); + final res = await req.close(); + final subscription = res.listen((_) {}); + await Future.delayed(const Duration(milliseconds: 50)); + await subscription.cancel(); + client.close(force: true); + try { + for (var i = 0; i < 100 && diagnostics.isEmpty; i++) { + await Future.delayed(const Duration(milliseconds: 20)); + } + expect(diagnostics, isNotEmpty); + expect(diagnostics.last['cancelled'], true); + } finally { + upstreamGate!.complete(); + await subscription.cancel(); + } + }); + test('Responses text lifecycle orders added, delta, done, completed', () async { + final res = await request( + '/v1/responses', + body: {'model': 'test-model', 'input': 'hi', 'stream': true}, + ); + final events = const LineSplitter() + .convert(res.body) + .where((l) => l.startsWith('data:')) + .map((l) => jsonDecode(l.substring(5))) + .toList(); + expect(events.map((e) => e['type']).toList(), [ + 'response.created', + 'response.output_item.added', + 'response.content_part.added', + 'response.output_text.delta', + 'response.output_text.done', + 'response.content_part.done', + 'response.output_item.done', + 'response.completed', + ]); + expect(events.map((e) => e['sequence_number']).toList(), List.generate(8, (i) => i)); + finishReason = 'length'; + final incomplete = await request( + '/v1/responses', + body: {'model': 'test-model', 'input': 'hi', 'stream': true}, + ); + expect(incomplete.body, contains('response.incomplete')); + expect(incomplete.body, isNot(contains('response.completed'))); + }); + test('Responses EOF nonstream has failed status', () async { + finishReason = null; + final res = await request('/v1/responses', body: {'model': 'test-model', 'input': 'hi'}); + expect(jsonDecode(res.body)['status'], 'failed'); + }); + test('only complete calls with missing outer wrappers are repaired', () { + const full = '{"tool_calls":[{"id":"call_x","function":{"name":"weather","arguments":"{}"}}]}'; + for (final text in [ + full.substring(0, full.length - 1), + full.substring(0, full.length - 2), + '[{"name":"weather","arguments":{}}', + ]) { + expect(parseGenaiToolCalls(text, {'weather'}, null).length, 1); + } + for (final text in [ + full.substring(0, full.length - 3), + '${full.substring(0, full.length - 2)},', + '{"tool_calls":[{"name":"weather","arguments":{"path":"abc', + '[{"name":"weather","arguments":{"path":"abc"}', + '${full.substring(0, full.length - 1)},"other":[', + ]) { + expect(() => parseGenaiToolCalls(text, {'weather'}, null), throwsFormatException); + } + }); + test('normal JSON and field explanations are final answers', () { + for (final text in [ + '已完成,字段为 `"name": "demo"`。', + '```json\n{"name":"demo","version":"1.0"}\n```', + '检查结果:{"ok":true}\n字段示例包含 "name": "weather"。', + '{"tool_calls":[]}', + '{"function":"documentation","description":"API 示例"}', + '[{"name":"demo","version":"1.0"}]', + ]) { + expect(parseGenaiToolCalls(text, {'weather'}, null), isEmpty); + } + }); + Map packet(Map delta, [String? finish]) => { + 'choices': [ + {'delta': delta, 'finish_reason': finish}, + ], + }; + for (final stream in [false, true]) { + test('empty generation retries once with identical history, stream=$stream', () async { + attemptPackets = [ + [ + packet({'reasoning': 'discard this thought'}, 'stop'), + ], + [ + packet({'content': 'recovered'}, 'stop'), + ] + ]; + final res = await request('/v1/chat/completions', body: payload(stream: stream)); + expect(res.body, contains('recovered')); + expect(res.body, isNot(contains('discard this thought'))); + expect(bodies.length, 2); + expect(bodies[0], bodies[1]); + expect(diagnostics.last['attempts'], 2); + }); + test('two empty generations stop, stream=$stream', () async { + reply = ''; + final res = await request('/v1/chat/completions', body: payload(stream: stream, tools: true)); + expect(res.body, contains('没有回复')); + expect(bodies.length, 2); + }); + test('errors, EOF, length and partial output never retry, stream=$stream', () async { + for (final scenario in ['error', 'eof', 'length', 'partial']) { + bodies.clear(); + attemptPackets = [ + [ + if (scenario == 'error') + { + 'error': 'fixture failure', + } + else + packet( + {'content': scenario == 'partial' ? 'partial' : ''}, + scenario == 'length' ? 'length' : null, + ), + ] + ]; + await request('/v1/chat/completions', body: payload(stream: stream)); + expect(bodies.length, 1, reason: scenario); + } + }); + test('native tool fragments accumulate and do not retry, stream=$stream', () async { + attemptPackets = [ + [ + packet({ + 'tool_calls': [ + { + 'index': 0, + 'id': 'call_native', + 'function': {'name': 'wea', 'arguments': '{"city":'}, + } + ], + }), + packet( + { + 'tool_calls': [ + { + 'index': 0, + 'function': {'name': 'ther', 'arguments': '"上海"}'}, + } + ], + }, + 'tool_calls', + ), + ] + ]; + final res = await request('/v1/chat/completions', body: payload(stream: stream, tools: true)); + expect(res.body, contains('call_native')); + expect(res.body, contains('weather')); + expect(res.body, contains('上海')); + expect(bodies.length, 1); + expect(diagnostics.last['call_count'], 1); + }); + test('native calls with disabled tools or bad arguments fail, stream=$stream', () async { + for (final tools in [false, true]) { + attemptPackets = [ + [ + packet( + { + 'tool_calls': [ + { + 'function': {'name': 'weather', 'arguments': '[]'}, + } + ], + }, + 'tool_calls', + ), + ] + ]; + final res = + await request('/v1/chat/completions', body: payload(stream: stream, tools: tools)); + expect(res.body, contains('error')); + expect(res.body, isNot(contains('"finish_reason":"tool_calls"'))); + } + }); + } + test('native message fallback and legacy function call', () async { + for (final legacy in [false, true]) { + attemptPackets = [ + [ + { + 'choices': [ + { + 'message': legacy + ? { + 'function_call': {'name': 'weather', 'arguments': '{}'}, + } + : { + 'tool_calls': [ + { + 'id': 'call_message', + 'function': {'name': 'weather', 'arguments': {}}, + } + ], + }, + 'finish_reason': legacy ? 'function_call' : 'tool_calls', + } + ], + } + ] + ]; + final res = await request('/v1/chat/completions', body: payload(tools: true)); + expect(jsonDecode(res.body)['choices'][0]['finish_reason'], 'tool_calls'); + } + }); + test('Responses supports native calls after empty retry', () async { + attemptPackets = [ + [packet({}, 'stop')], + [ + packet( + { + 'tool_calls': [ + { + 'id': 'call_r', + 'function': {'name': 'weather', 'arguments': '{}'}, + } + ], + }, + 'tool_calls', + ), + ] + ]; + final res = await request( + '/v1/responses', + body: { + 'model': 'test-model', + 'input': 'hi', + 'stream': true, + 'tools': [ + {'type': 'function', 'name': 'weather'}, + ], + }, + ); + expect(res.body, contains('"type":"function_call"')); + expect(res.body, contains('call_r')); + expect(bodies.length, 2); + }); +} diff --git a/test/services/huawei_watch_page_test.dart b/test/services/huawei_watch_page_test.dart new file mode 100644 index 00000000..320678b8 --- /dev/null +++ b/test/services/huawei_watch_page_test.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/pages/huawei_watch_page.dart'; +import 'package:techpie/services/wear/wear_engine_service.dart'; +import 'package:techpie/services/wear/wear_protocol.dart'; + +import 'wear_engine_service_test.dart' + show Peer, Source, MemoryMetadata, fingerprint, testNow; + +class DevicePeer extends Peer { + @override + Future>> devices() async => [ + {'id': 'watch', 'name': 'GT 6 Pro', 'connected': true}, + {'id': 'offline', 'name': 'GT 3', 'connected': false}, + ]; +} + +class ScopeFailurePeer extends DevicePeer { + @override + Future> authorize({required bool notify}) async => + throw const WearFailure('SERVICE_UNAVAILABLE', nativeCode: 8); +} + +void main() { + testWidgets( + 'SDK authorization failure shows code without claiming empty device list', + (tester) async { + final service = WearEngineService( + transport: ScopeFailurePeer(), + source: Source(), + metadata: MemoryMetadata(), + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: HuaweiWatchContent(service: service)), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('授权并查找手表')); + await tester.pumpAndSettle(); + expect(find.textContaining('SDK 错误码:8'), findsOneWidget); + expect(find.text('尚未发现手表,请完成配对后重新查找。'), findsNothing); + await tester.pumpWidget(const SizedBox()); + service.dispose(); + }); + testWidgets( + 'connection-only watch capability and heartbeat loss are reflected accurately', + (tester) async { + final peer = DevicePeer() + ..capabilities = ['account.display', 'connection.heartbeat']; + final service = WearEngineService( + transport: peer, + source: Source(), + metadata: MemoryMetadata(), + now: () => testNow, + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: HuaweiWatchContent(service: service)), + ), + ); + await tester.pumpAndSettle(); + final opened = service.open('watch', watchFingerprint: fingerprint); + await tester.pumpAndSettle(); + await opened; + expect(peer.received.where((m) => m['type'] == 'ddl.snapshot'), isEmpty); + expect(find.text('张三'), findsOneWidget); + peer.ignoreHeartbeat = true; + await tester.pump(const Duration(seconds: 10)); + await tester.pump(const Duration(seconds: 9)); + expect(service.ready, false); + expect(find.text('张三'), findsNothing); + await tester.pumpWidget(const SizedBox()); + service.dispose(); + }); + testWidgets('unsupported platform keeps connection guide visible', + (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold(body: HuaweiWatchContent(service: null)), + ), + ); + expect(find.text('未连接'), findsOneWidget); + expect(find.textContaining('Android 手机'), findsOneWidget); + expect(find.text('暂无设备用户'), findsOneWidget); + }); + + testWidgets( + 'authorization lists devices; handshake shows user; disconnect hides user', + (tester) async { + final peer = DevicePeer(); + final service = WearEngineService( + transport: peer, + source: Source(), + metadata: MemoryMetadata(), + now: () => testNow, + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: HuaweiWatchContent(service: service)), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('未连接'), findsOneWidget); + await tester.tap(find.text('授权并查找手表')); + await tester.pumpAndSettle(); + expect(find.text('GT 6 Pro'), findsOneWidget); + final offlineTile = + tester.widget(find.widgetWithText(ListTile, 'GT 3')); + expect(offlineTile.enabled, false); + final opened = service.open('watch', watchFingerprint: fingerprint); + await tester.pumpAndSettle(); + await opened; + expect(find.text('已连接'), findsOneWidget); + expect(find.text('张三'), findsOneWidget); + expect(find.text('学号:00123'), findsOneWidget); + await tester.scrollUntilVisible(find.text('断开连接'), 240); + await tester.tap(find.text('断开连接')); + await tester.pumpAndSettle(); + await tester.scrollUntilVisible(find.text('未连接'), -240); + expect(find.text('未连接'), findsOneWidget); + expect(find.text('张三'), findsNothing); + await tester.pumpWidget(const SizedBox()); + service.dispose(); + }); +} diff --git a/test/services/wear_engine_service_test.dart b/test/services/wear_engine_service_test.dart new file mode 100644 index 00000000..deb27f61 --- /dev/null +++ b/test/services/wear_engine_service_test.dart @@ -0,0 +1,552 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:qr_flutter/qr_flutter.dart'; +import 'package:techpie/services/wear/wear_engine_service.dart'; +import 'package:techpie/services/wear/wear_protocol.dart'; + +final testNow = DateTime.utc(2026, 10, 13); +const fingerprint = + '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + +class MemoryMetadata implements WearMetadata { + String? value; + @override + String? read() => value; + @override + Future write(String value) async { + this.value = value; + } +} + +class Source implements WearDataSource { + String scope = 'account-a'; + bool failDdl = false; + List items = []; + Completer? delayedCode; + Completer>? delayedDdl; + Completer? delayedAccount; + @override + Future account() async => delayedAccount == null + ? WearAccount(scope: scope, name: '张三', studentId: '00123') + : delayedAccount!.future; + @override + Future> deadlines() async { + if (failDdl) throw const WearFailure('SERVICE_UNAVAILABLE'); + return delayedDdl == null ? items : delayedDdl!.future; + } + + @override + Future campusCode(String purpose) async => delayedCode == null + ? WearCampusCode( + bytes: Uint8List.fromList([0, 128, 255]), + issuedAt: testNow, + validUntil: testNow.add(const Duration(seconds: 30)), + ) + : delayedCode!.future; +} + +class Peer implements WearTransport { + final received = >[]; + final codec = WearFrames(); + final frameStream = StreamController.broadcast(); + final stateStream = StreamController>.broadcast(); + bool ignoreAccount = false; + bool rejectDdl = false; + bool ignoreHeartbeat = false; + List capabilities = [ + 'account.display', + 'ddl.display', + 'campusCode.qrBytes', + ]; + bool staleAck = false; + int droppedAcks = 0, counter = 0, clears = 0; + Map? schedule; + String? session, binding; + @override + Stream get frames => frameStream.stream; + @override + Stream> get states => stateStream.stream; + @override + Future> status() async => { + 'service': 'ready', + 'device': 'connected', + 'permission': {'p2p': true, 'notify': true}, + }; + @override + Future>> devices() async => [ + {'id': 'watch'}, + ]; + @override + Future> authorize({required bool notify}) async => + {'p2p': true, 'notify': notify}; + @override + Future open(String deviceId, String fingerprint) async {} + @override + Future close() async { + codec.clear(); + } + + void respond( + Map request, + String type, + Map body, { + bool handshake = false, + }) { + emit({ + 'v': 1, + 'id': 'w${counter++}', + 'replyTo': request['id'], + 'sessionId': handshake + ? null + : staleAck + ? 'old' + : session, + 'bindingId': handshake ? null : binding, + 'type': type, + 'sentAtMs': testNow.millisecondsSinceEpoch, + 'body': body, + }); + } + + void emit(Map message) { + for (final frame in WearFrames.encode(message)) { + frameStream.add(frame); + } + } + + void request(String type, Map body) => emit({ + 'v': 1, + 'id': 'q${counter++}', + 'replyTo': null, + 'sessionId': session, + 'bindingId': binding, + 'type': type, + 'sentAtMs': testNow.millisecondsSinceEpoch, + 'body': body, + }); + @override + Future send(Uint8List bytes) async { + expectSync(bytes.length, lessThanOrEqualTo(1024)); + final message = codec.accept(bytes, testNow); + if (message == null) return; + received.add(message); + final body = message['body'] as Map; + switch (message['type']) { + case 'session.hello': + respond( + message, + 'session.welcome', + { + 'nonce': body['nonce'], + 'version': 1, + 'watchInstanceId': 'watch-install', + 'capabilities': capabilities, + }, + handshake: true, + ); + case 'session.open': + session = body['sessionId'] as String; + binding = body['bindingId'] as String; + respond(message, 'session.opened', {}, handshake: true); + case 'account.snapshot': + if (ignoreAccount) return; + if (droppedAcks > 0) { + droppedAcks--; + return; + } + respond(message, 'result', { + 'status': 'ok', + 'code': 'OK', + 'resource': 'account', + 'revision': body['revision'], + }); + case 'ddl.snapshot': + if (rejectDdl) { + respond(message, 'result', { + 'status': 'error', + 'code': 'SERVICE_UNAVAILABLE', + }); + return; + } + respond(message, 'result', { + 'status': 'ok', + 'code': 'OK', + 'resource': 'ddl', + 'revision': body['revision'], + }); + case 'session.clear': + respond(message, 'result', {'status': 'ok', 'code': 'OK'}); + case 'session.close': + respond(message, 'result', {'status': 'ok', 'code': 'OK'}); + case 'session.ping': + if (!ignoreHeartbeat) { + respond(message, 'result', {'status': 'ok', 'code': 'OK'}); + } + case 'campusCode.snapshot': + respond(message, 'result', {'status': 'ok', 'code': 'OK'}); + } + } + + @override + Future scheduleReminders(Map spec) async { + schedule = spec; + } + + @override + Future cancelReminders() async { + clears++; + schedule = null; + } + + @override + Future sendReminder(String id) async => 'submitted'; + @override + void dispose() { + unawaited(frameStream.close()); + unawaited(stateStream.close()); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Peer peer; + late Source source; + late MemoryMetadata metadata; + late WearEngineService service; + setUp(() { + peer = Peer(); + source = Source(); + metadata = MemoryMetadata(); + service = WearEngineService( + transport: peer, + source: source, + metadata: metadata, + now: () => testNow, + timeout: const Duration(milliseconds: 25), + retryDelays: [Duration.zero], + ); + }); + tearDown(() { + service.dispose(); + }); + Future open({bool notify = false}) async => await service.open( + 'watch', + watchFingerprint: fingerprint, + notify: notify, + ); + + test('UTF-8 Chinese framing roundtrips out of order without exceeding 1KB', + () { + final message = { + 'v': 1, + 'id': 'm1', + 'type': 'account.snapshot', + 'sentAtMs': 1, + 'body': {'text': '校园任务' * 1200}, + }; + final frames = WearFrames.encode(message); + final codec = WearFrames(); + Map? result; + for (final frame in frames.reversed) { + expect(frame.length, lessThanOrEqualTo(1024)); + result = codec.accept(frame, testNow) ?? result; + } + expect(result, message); + }); + test('matrix-capable watch receives a byte-preserving QR matrix', () async { + peer.capabilities = [ + 'account.display', + 'ddl.display', + 'campusCode.qrMatrix', + ]; + await open(); + peer.request( + 'campusCode.request', + {'purpose': 'campus', 'format': 'qrBytes'}, + ); + await Future.delayed(const Duration(milliseconds: 20)); + final body = peer.received + .firstWhere((m) => m['type'] == 'campusCode.snapshot')['body'] as Map; + final bytes = Uint8List.fromList([0, 128, 255]); + final reference = QrImage( + QrCode.fromUint8List( + data: bytes, + errorCorrectLevel: QrErrorCorrectLevel.M, + ), + ); + expect(body['matrixSize'], reference.moduleCount); + final bits = base64Decode(body['matrix'] as String); + for (var row = 0; row < reference.moduleCount; row++) { + for (var col = 0; col < reference.moduleCount; col++) { + final index = row * reference.moduleCount + col; + expect( + (bits[index ~/ 8] & (1 << (7 - index % 8))) != 0, + reference.isDark(row, col), + ); + } + } + expect(base64Decode(body['payload'] as String), bytes); + }); + test( + 'reminder toggle schedules after consent and cancels on disable or close', + () async { + source.items = [ + WearDdl( + id: 'task', + title: '作业', + courseName: '数学', + dueAt: testNow.add(const Duration(hours: 2)), + completed: false, + remindAt: [testNow.add(const Duration(hours: 1))], + ), + ]; + await open(); + expect(service.remindersEnabled, false); + expect(peer.schedule, isNull); + await service.setRemindersEnabled(true); + expect(service.remindersEnabled, true); + expect(peer.schedule!['items'], hasLength(1)); + await service.setRemindersEnabled(false); + expect(peer.schedule, isNull); + await service.setRemindersEnabled(true); + await service.close(); + expect(peer.schedule, isNull); + expect(service.remindersEnabled, false); + }); + test('failed reminder enable rolls back consent and supports retry', + () async { + await open(); + source.failDdl = true; + await expectLater( + service.setRemindersEnabled(true), + throwsA(isA()), + ); + expect(service.remindersEnabled, false); + expect(service.supports('reminder.phoneNotify'), false); + expect(peer.schedule, isNull); + source.failDdl = false; + await service.setRemindersEnabled(true); + expect(service.remindersEnabled, true); + expect(peer.schedule, isNotNull); + }); + + test('failed watch receipt cancels partially scheduled reminders', () async { + source.items = [ + WearDdl( + id: 'task', + title: '作业', + courseName: '数学', + dueAt: testNow.add(const Duration(hours: 2)), + completed: false, + remindAt: [testNow.add(const Duration(hours: 1))], + ), + ]; + await open(); + peer.rejectDdl = true; + await expectLater( + service.setRemindersEnabled(true), + throwsA(isA()), + ); + expect(service.remindersEnabled, false); + expect(peer.schedule, isNull); + }); + + test('disconnect during reminder enrollment cannot re-enable reminders', + () async { + await open(); + source.delayedDdl = Completer>(); + final pending = service.setRemindersEnabled(true); + final failure = expectLater(pending, throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 5)); + await service.close(); + source.delayedDdl!.complete([]); + await failure; + expect(service.remindersEnabled, false); + expect(peer.schedule, isNull); + }); + + test('rejects oversized data and conflicting duplicate fragments', () { + expect( + () => WearFrames.encode({ + 'v': 1, + 'id': 'm', + 'body': {'data': 'a' * 40000}, + }), + throwsA(isA()), + ); + final codec = WearFrames(); + Uint8List fragment(int byte) => Uint8List.fromList( + utf8.encode( + jsonEncode({ + 'v': 1, + 'mid': 'm', + 'i': 0, + 'n': 2, + 'data': base64Encode(List.filled(512, byte)), + }), + ), + ); + codec.accept(fragment(1), testNow); + expect( + () => codec.accept(fragment(2), testNow), + throwsA(isA()), + ); + }); + test('handshake and application receipts publish only minimal account fields', + () async { + await open(); + expect(service.ready, true); + expect((service.getStatus()['sync'] as Map)['account']['state'], 'applied'); + final account = + peer.received.firstWhere((m) => m['type'] == 'account.snapshot'); + expect(account['body']['data'], {'name': '张三', 'studentId': '00123'}); + expect(jsonEncode(account), isNot(contains('account-a'))); + }); + test('SDK sends without application acknowledgements stay failed', () async { + peer.ignoreAccount = true; + await open(); + expect(service.ready, true); + expect((service.getStatus()['sync'] as Map)['account']['state'], 'failed'); + expect((service.getStatus()['sync'] as Map)['ddl']['state'], 'applied'); + }); + test('lost receipt retries the identical message id and revision', () async { + peer.droppedAcks = 1; + await open(); + final snapshots = + peer.received.where((m) => m['type'] == 'account.snapshot').toList(); + expect(snapshots.length, 2); + expect(snapshots[0], snapshots[1]); + }); + test('old session receipt cannot acknowledge new data', () async { + peer.staleAck = true; + await open(); + expect((service.getStatus()['sync'] as Map)['account']['state'], 'failed'); + }); + test('DDL selection truncates whole items and retains binary code bytes', + () async { + source.items = List.generate( + 60, + (i) => WearDdl( + id: 'ddl-$i', + title: '任务 $i', + courseName: '课程', + dueAt: testNow.add(Duration(hours: i + 1)), + completed: false, + ), + ); + await open(); + final ddl = + peer.received.firstWhere((m) => m['type'] == 'ddl.snapshot')['body']; + expect(ddl['items'].length, 50); + expect(ddl['truncated'], true); + peer.request( + 'campusCode.request', + {'purpose': 'campus', 'format': 'qrBytes'}, + ); + await Future.delayed(const Duration(milliseconds: 20)); + final code = peer.received + .firstWhere((m) => m['type'] == 'campusCode.snapshot')['body']; + expect(base64Decode(code['payload'] as String), [0, 128, 255]); + expect( + code['validUntilMs'], + testNow.add(const Duration(seconds: 30)).millisecondsSinceEpoch, + ); + }); + test( + 'reminders require separate notify consent and account mutation clears them', + () async { + source.items = [ + WearDdl( + id: 'd', + title: '任务', + courseName: '课', + dueAt: testNow.add(const Duration(hours: 2)), + completed: false, + remindAt: [testNow.add(const Duration(hours: 1))], + ), + ]; + await open(notify: true); + expect(peer.schedule!['items'].length, 1); + source.scope = 'account-b'; + await service.reconcileAccount(); + expect(service.ready, false); + expect(peer.schedule, isNull); + expect(peer.received.any((m) => m['type'] == 'session.clear'), true); + expect(jsonDecode(metadata.value!)['binding'], isNull); + }); + test('late campus code response is dropped when the account changes', + () async { + await open(); + source.delayedCode = Completer(); + peer.request( + 'campusCode.request', + {'purpose': 'campus', 'format': 'qrBytes'}, + ); + await Future.delayed(const Duration(milliseconds: 5)); + source.scope = 'other-account'; + source.delayedCode!.complete( + WearCampusCode( + bytes: Uint8List.fromList([1]), + issuedAt: testNow, + validUntil: testNow.add(const Duration(seconds: 30)), + ), + ); + await Future.delayed(const Duration(milliseconds: 10)); + expect(peer.received.any((m) => m['type'] == 'campusCode.snapshot'), false); + }); + test('revocation while disconnected remains durable until clear receipt', + () async { + await open(); + await service.close(); + await service.clear(reason: 'logout'); + expect(jsonDecode(metadata.value!)['pendingClear'], 'logout'); + await open(); + final messages = peer.received.map((m) => m['type']).toList(); + final clearIndex = messages.indexOf('session.clear'); + expect(clearIndex, greaterThan(0)); + expect(messages.sublist(clearIndex + 1), contains('account.snapshot')); + expect(jsonDecode(metadata.value!)['pendingClear'], isNull); + }); + test('account switch during DDL fetch cannot schedule or transmit old tasks', + () async { + await open(notify: true); + source.delayedDdl = Completer>(); + final refresh = service.refresh(resources: ['ddl']); + final failure = expectLater(refresh, throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 5)); + source.scope = 'new-account'; + await service.reconcileAccount(); + source.delayedDdl!.complete([ + WearDdl( + id: 'old', + title: '旧账号任务', + courseName: '旧课', + dueAt: testNow.add(const Duration(hours: 2)), + completed: false, + remindAt: [testNow.add(const Duration(hours: 1))], + ), + ]); + await failure; + expect(peer.schedule, isNull); + expect(peer.received.where((m) => m['type'] == 'ddl.snapshot').length, 1); + }); + test('revocation wins over delayed connection enrollment', () async { + source.delayedAccount = Completer(); + final enrollment = open(); + final failure = expectLater(enrollment, throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 5)); + await service.clear(); + source.delayedAccount!.complete( + const WearAccount(scope: 'account-a', name: '张三', studentId: '00123'), + ); + await failure; + expect(service.ready, false); + expect(peer.received.any((m) => m['type'] == 'account.snapshot'), false); + source.delayedAccount = null; + await open(); + expect(service.ready, true); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 882e8125..2a93d020 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -170,7 +170,7 @@ void main() { // Tap Deadlines await tester.tap(find.text('Deadlines').first); await tester.pumpAndSettle(); - expect(find.text('No upcoming deadlines'), findsOneWidget); + expect(find.text('连接课程平台以获取Deadlines'), findsOneWidget); expect(find.byType(FloatingActionButton), findsNothing); // Tap Settings diff --git a/third_party/GenAI2OpenAI/LICENSE b/third_party/GenAI2OpenAI/LICENSE new file mode 100644 index 00000000..708ceb52 --- /dev/null +++ b/third_party/GenAI2OpenAI/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 GeekPie_ Association @ ShanghaiTech University + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tool/genai_gateway_smoke.dart b/tool/genai_gateway_smoke.dart new file mode 100644 index 00000000..c2d7e12c --- /dev/null +++ b/tool/genai_gateway_smoke.dart @@ -0,0 +1,157 @@ +// Supply credentials as one JSON line on stdin; nothing sensitive is printed. +// Performs fixture calls only: no filesystem or command execution tools. +import 'dart:convert'; +import 'dart:io'; +import 'package:techpie/services/genai/genai_gateway.dart'; + +Future main(List args) async { + final credentials = + jsonDecode(await stdin.transform(utf8.decoder).transform(const LineSplitter()).first) + as Map; + final gateway = GenaiGateway(onDiagnostic: (d) => stdout.writeln(jsonEncode(d))); + final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); + final existing = args.contains('--installed'); + try { + if (!existing) { + await gateway.start( + host: '127.0.0.1', + port: 0, + genaiToken: credentials['upstream'] as String, + apiToken: credentials['local'] as String, + ); + } + final base = 'http://127.0.0.1:${existing ? 5000 : gateway.port}'; + Future send(String path, [Map? body]) async { + final req = await client.openUrl(body == null ? 'GET' : 'POST', Uri.parse('$base$path')); + req.headers.set('Authorization', 'Bearer ${credentials['local']}'); + if (body != null) { + req.headers.contentType = ContentType.json; + req.write(jsonEncode(body)); + } + final res = await req.close(); + final text = await utf8.decoder.bind(res).join().timeout(const Duration(seconds: 180)); + if (res.statusCode != 200) throw StateError('HTTP ${res.statusCode}'); + if (body?['stream'] == true) { + final events = const LineSplitter() + .convert(text) + .where((l) => l.startsWith('data:') && !l.contains('[DONE]')) + .map((l) => jsonDecode(l.substring(5))) + .toList(); + if (events.any((e) => e['error'] != null || e['type'] == 'response.failed')) { + throw StateError('SSE error'); + } + if (path.endsWith('responses')) return events.last['response']; + final calls = []; + final content = StringBuffer(); + String? finish; + for (final e in events) { + final c = e['choices'][0]; + final d = c['delta']; + if (d['tool_calls'] is List) calls.addAll(d['tool_calls'] as List); + if (d['content'] is String) content.write(d['content']); + finish = c['finish_reason'] as String? ?? finish; + } + return { + 'choices': [ + { + 'finish_reason': finish, + 'message': { + 'role': 'assistant', + 'content': content.toString(), + if (calls.isNotEmpty) 'tool_calls': calls, + }, + } + ], + }; + } + return jsonDecode(text); + } + + final models = await send('/v1/models'); + final model = (models['data'] as List) + .map((m) => m['id'] as String) + .firstWhere((m) => m.toLowerCase().contains('chatglm')); + for (final responses in [false, true]) { + final path = responses ? '/v1/responses' : '/v1/chat/completions'; + final tools = [ + responses + ? { + 'type': 'function', + 'name': 'fixture_read', + 'description': '读取测试夹具编号', + 'parameters': {'type': 'object', 'properties': {}}, + } + : { + 'type': 'function', + 'function': { + 'name': 'fixture_read', + 'description': '读取测试夹具编号', + 'parameters': {'type': 'object', 'properties': {}}, + }, + }, + ]; + final prompt = '调用 fixture_read 获取测试编号。收到结果后用一句话原样报告编号。工具只读取测试夹具。'; + final initial = {'role': 'user', 'content': prompt}; + final first = await send(path, { + 'model': model, + 'stream': true, + 'tools': tools, + 'tool_choice': 'required', + if (responses) 'input': prompt else 'messages': [initial], + if (responses) 'max_output_tokens': 1024 else 'max_completion_tokens': 1024, + }); + dynamic call; + if (responses) { + if (first['status'] != 'completed') throw StateError('incomplete response'); + call = (first['output'] as List).singleWhere((x) => x['type'] == 'function_call'); + if (call['name'] != 'fixture_read') throw StateError('unexpected tool'); + } else { + if (first['choices'][0]['finish_reason'] != 'tool_calls') { + throw StateError('missing tool finish'); + } + call = first['choices'][0]['message']['tool_calls'][0]; + if (call['function']['name'] != 'fixture_read') throw StateError('unexpected tool'); + } + final second = await send(path, { + 'model': model, + 'stream': false, + 'tools': tools, + 'tool_choice': 'auto', + if (responses) + 'input': [ + initial, + call, + { + 'type': 'function_call_output', + 'call_id': call['call_id'], + 'output': '测试编号:FIXTURE-731', + } + ] + else + 'messages': [ + initial, + first['choices'][0]['message'], + { + 'role': 'tool', + 'tool_call_id': call['id'], + 'name': 'fixture_read', + 'content': '测试编号:FIXTURE-731', + } + ], + if (responses) 'max_output_tokens': 1024 else 'max_completion_tokens': 1024, + }); + final answer = responses ? second['output_text'] : second['choices'][0]['message']['content']; + if (answer is! String || !answer.contains('FIXTURE-731')) { + throw StateError('fixture summary missing'); + } + stdout.writeln( + jsonEncode( + {'api': path, 'model': model, 'fixture_round_trip': 'passed', 'installed': existing}, + ), + ); + } + } finally { + client.close(force: true); + await gateway.stop(); + } +} diff --git a/web/feedback/.gitignore b/web/feedback/.gitignore new file mode 100644 index 00000000..6d9d5d79 --- /dev/null +++ b/web/feedback/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.vercel/ +.env* +!.env.example +.data/ diff --git a/web/feedback/README.md b/web/feedback/README.md new file mode 100644 index 00000000..5dd6a9ed --- /dev/null +++ b/web/feedback/README.md @@ -0,0 +1,9 @@ +# TechPie 反馈入口 + +本目录只包含反馈表单与工单查询界面。API、存储、后台管理、测试和部署配置独立放在 E:\Projects\techpie-feedback-api。 + +接口地址:https://techpie-feedback.dzhes.app/api/feedback。API 项目部署时同步这里的公开界面到 public/,因此该域名也提供反馈入口,后台地址为 /miku。 + +表单包含 GeekPie-UniAuth 用户名(非学号)、反馈类型、平台与版本、使用场景、标题、具体问题、复现步骤、期望结果与联系方式。用户名自行填写,未做 SSO 身份验证,不传递 SSO Token。提交后生成工单 ID,可下载凭证并查看公开回复与处理进度。 + +Flutter 设置页通过“用户反馈与工单”打开入口。API 的账户密码、存储凭据及运行数据均不在本目录。 \ No newline at end of file diff --git a/web/feedback/public/app.js b/web/feedback/public/app.js new file mode 100644 index 00000000..55799e44 --- /dev/null +++ b/web/feedback/public/app.js @@ -0,0 +1,93 @@ +import { api, el, details } from "./common.js"; +let receipt; +function tab(mode) { + for (const name of ["new", "lookup"]) { + el(`${name}-panel`).hidden = name !== mode; + el(`${name}-tab`).setAttribute("aria-selected", String(name === mode)); + } +} +el("new-tab").onclick = () => tab("new"); +el("lookup-tab").onclick = () => tab("lookup"); +document.querySelector(".tabs").onkeydown = (event) => { + if (["ArrowLeft", "ArrowRight"].includes(event.key)) { + event.preventDefault(); + const mode = el("new-panel").hidden ? "new" : "lookup"; + tab(mode); + el(`${mode}-tab`).focus(); + } +}; +const form = el("feedback-form"); +el("another-feedback").onclick = () => { + receipt = null; + form.reset(); + form.hidden = false; + el("receipt").hidden = true; + form.elements.contact.type = "email"; + form.elements.contact.autocomplete = "email"; + el("receipt-id").textContent = ""; + form.elements.userId.focus(); +}; +form.elements.contactType.onchange = () => { + form.elements.contact.type = + form.elements.contactType.value === "邮箱" ? "email" : "text"; + form.elements.contact.autocomplete = + form.elements.contactType.value === "邮箱" ? "email" : "off"; +}; +form.onsubmit = async (event) => { + event.preventDefault(); + const button = form.querySelector("button"); + button.disabled = true; + el("form-message").textContent = ""; + try { + receipt = await api("create", { + ...Object.fromEntries(new FormData(form)), + consent: form.elements.consent.checked, + }); + el("receipt-id").textContent = receipt.id; + form.hidden = true; + el("receipt").hidden = false; + el("receipt").focus(); + } catch (error) { + el("form-message").textContent = error.message; + } finally { + button.disabled = false; + } +}; +el("save-receipt").onclick = () => { + const file = new Blob( + [ + `TechPie 工单凭证\n工单 ID:${receipt.id}\n查询入口:${location.origin}/\n请妥善保存工单 ID。\n`, + ], + { type: "text/plain;charset=utf-8" }, + ); + const url = URL.createObjectURL(file); + const a = document.createElement("a"); + a.href = url; + a.download = `${receipt.id}.txt`; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +}; +el("view-receipt").onclick = () => { + el("lookup-form").elements.id.value = receipt.id; + tab("lookup"); + el("lookup-form").requestSubmit(); +}; +el("lookup-form").onsubmit = async (event) => { + event.preventDefault(); + const form = event.currentTarget; + const button = form.querySelector("button"); + button.disabled = true; + el("lookup-message").textContent = ""; + el("lookup-result").replaceChildren(); + try { + const { ticket } = await api("lookup", { + ...Object.fromEntries(new FormData(form)), + id: form.elements.id.value.trim().toUpperCase(), + }); + details(ticket, el("lookup-result")); + } catch (error) { + el("lookup-message").textContent = error.message; + } finally { + button.disabled = false; + } +}; diff --git a/web/feedback/public/common.js b/web/feedback/public/common.js new file mode 100644 index 00000000..ba4f041d --- /dev/null +++ b/web/feedback/public/common.js @@ -0,0 +1,145 @@ +const TIMEOUT_MS = 15000; +const NETWORK_MESSAGE = "网络连接失败,请检查网络后重试"; +const timeoutMessage = (action) => + action === "create" + ? "请求超时,提交结果尚未确认,请勿连续重复提交" + : "请求超时,请稍后重试"; +function withTimeout(action, run) { + let timer; + const controller = + typeof AbortController === "function" ? new AbortController() : null; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error(timeoutMessage(action))); + if (controller) controller.abort(); + }, TIMEOUT_MS); + }); + const work = Promise.resolve().then(() => run(controller)); + return Promise.race([work, timeout]).finally(() => clearTimeout(timer)); +} +export async function api(action, data = {}) { + const endpoint = + location.hostname === "techpie-feedback.dzhes.app" || + location.hostname === "localhost" + ? "/api/feedback" + : "https://techpie-feedback.dzhes.app/api/feedback"; + let result; + try { + // No automatic retry: create must not risk duplicate submissions. + const outcome = await withTimeout(action, async (controller) => { + const response = await fetch(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...data, action }), + ...(controller ? { signal: controller.signal } : {}), + }); + let json; + try { + json = await response.json(); + } catch { + throw new Error("服务暂时不可用,请稍后重试"); + } + return { response, json }; + }); + result = outcome.json; + if (!outcome.response.ok) { + const error = new Error(result.error || "请求失败"); + error.status = outcome.response.status; + throw error; + } + return result; + } catch (error) { + if (error && (error.name === "AbortError" || error.name === "TimeoutError")) { + throw new Error(timeoutMessage(action)); + } + if (error instanceof TypeError) { + throw new Error(NETWORK_MESSAGE); + } + throw error; + } +} +export const el = (id) => document.getElementById(id); +export const date = (value) => + new Date(value).toLocaleString("zh-CN", { hour12: false }); +export function node(tag, text, className) { + const result = document.createElement(tag); + if (text !== undefined) result.textContent = text; + if (className) result.className = className; + return result; +} +export function details(ticket, target, admin = false) { + target.replaceChildren(); + const heading = node("div", undefined, "split"); + heading.append( + node("h2", ticket.title), + node("span", ticket.status, "badge"), + ); + target.append( + heading, + node("p", `${ticket.id} · ${date(ticket.createdAt)}`, "muted"), + ); + for (const [label, value] of [ + ["反馈类型", ticket.category], + ["使用场景", ticket.scenario], + ["平台 / 版本", `${ticket.platform} / ${ticket.version || "未填写"}`], + ["具体问题", ticket.problem], + ["复现步骤", ticket.steps], + ["期望结果", ticket.expected], + ...(admin + ? [ + ["用户 ID", ticket.userId], + ["联系方式", `${ticket.contactType}:${ticket.contact}`], + ["优先级", ticket.priority], + ["负责人", ticket.assignee || "未分配"], + ["归档", ticket.archived ? "已归档" : "未归档"], + ] + : []), + ]) { + if (!value) continue; + const section = node("section", undefined, "section"); + section.append(node("h3", label), node("p", value)); + target.append(section); + } + const timeline = node( + "div", + undefined, + admin ? "timeline admin-history" : "timeline", + ); + const labels = { + reply: "公开回复", + note: "内部备注", + status: "修改状态", + priority: "设置优先级", + category: "修改分类", + assign: "分配负责人", + archive: "归档操作", + }; + for (const event of ticket.history) { + const item = node( + "article", + undefined, + event.action === "note" ? "internal" : "", + ); + item.append( + node("div", labels[event.action], "history-label"), + node("small", date(event.at)), + node( + "p", + event.action === "archive" + ? event.value === "true" + ? "已归档" + : "已恢复" + : event.value, + ), + ); + timeline.append(item); + } + const section = node("section", undefined, "section"); + section.append( + node("h3", admin ? "操作记录" : "处理记录"), + ticket.history.length + ? timeline + : node("p", "工单已提交,状态为待处理。", "muted"), + ); + target.append(section); +} diff --git a/web/feedback/public/icon.png b/web/feedback/public/icon.png new file mode 100644 index 00000000..04c8cbc9 Binary files /dev/null and b/web/feedback/public/icon.png differ diff --git a/web/feedback/public/index.html b/web/feedback/public/index.html new file mode 100644 index 00000000..bad15873 --- /dev/null +++ b/web/feedback/public/index.html @@ -0,0 +1,239 @@ + + + + + + + + 用户反馈 · TechPie + + + + + + +
+
+

用户反馈

+

提交使用问题或功能建议,或通过工单 ID 查询处理结果。用户群:1130168501

+
+
+ +
+

提交反馈

+

带 * 的项目为必填项。提交成功后将生成工单 ID。

+
+
+

用户与使用环境

+
+ + + + + +
+
+
+

反馈内容

+
+ + + + +
+
+
+

联系方式

+
+ +
+
+ + +
+ +
+
+ +
+ +
+
+ + + diff --git a/web/feedback/public/style.css b/web/feedback/public/style.css new file mode 100644 index 00000000..5545bd4c --- /dev/null +++ b/web/feedback/public/style.css @@ -0,0 +1,404 @@ +:root { + color-scheme: light; + --ink: #172b45; + --muted: #526680; + --blue: #087ff5; + --line: #dce7f1; + --paper: #f7fbff; + --soft: #eaf4ff; + font-family: + -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", + sans-serif; + color: var(--ink); + background: #fff; + font-synthesis: none; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + font-size: 17px; + line-height: 1.8; +} +a { + color: #096ace; + text-underline-offset: 4px; +} +a:hover { + color: #064d99; +} +button, +input, +textarea, +select { + font: inherit; +} +button { + cursor: pointer; +} +button:disabled { + opacity: 0.55; + cursor: wait; +} +a:focus-visible, +button:focus-visible { + outline: 3px solid #1181ee; + outline-offset: 5px; +} +[hidden] { + display: none !important; +} +.wrap { + max-width: 1320px; + margin: auto; + padding: 0 36px; +} +.nav { + min-height: 92px; + border-bottom: 1px solid var(--line); + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; +} +.brand { + display: flex; + align-items: center; + gap: 12px; + font-size: 22px; + font-weight: 740; + letter-spacing: -0.7px; + text-decoration: none; + color: var(--ink); +} +.brand img { + width: 48px; + height: 48px; + border-radius: 9px; +} +.navlinks { + display: flex; + align-items: center; + gap: 28px; +} +.navlinks a { + font-size: 15px; + text-decoration: none; + color: var(--muted); +} +.navlinks a[aria-current="page"] { + color: var(--blue); +} +.feedback-page { + max-width: 920px; + margin: auto; + padding: 56px 36px 80px; +} +.page-heading h1 { + font-size: 40px; + font-weight: 760; + line-height: 1.35; + letter-spacing: -0.04em; + margin: 12px 0 16px; +} +.page-heading p { + color: var(--muted); + margin: 0 0 36px; + font-size: 16px; +} +.tabs { + display: flex; + gap: 32px; + border-bottom: 1px solid var(--line); + margin-bottom: 32px; +} +.tabs button { + position: relative; + border: 0; + background: none; + padding: 12px 0; + color: var(--muted); + font-size: 16px; +} +.tabs button[aria-selected="true"] { + color: var(--blue); + font-weight: 600; +} +.tabs button[aria-selected="true"]:after { + content: ""; + height: 2px; + position: absolute; + bottom: -1px; + left: 0; + right: 0; + background: var(--blue); +} +.card { + min-width: 0; +} +h2 { + font-size: 24px; + line-height: 1.5; + margin: 0 0 8px; +} +h3 { + font-size: 18px; + font-weight: 600; + margin: 0 0 20px; +} +.muted { + color: var(--muted); + font-size: 14px; + margin: 8px 0 24px; +} +.section { + border-top: 1px solid var(--line); + padding-top: 24px; + margin-top: 32px; +} +.fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 22px 28px; +} +.full { + grid-column: 1/-1; +} +label { + display: block; + font-size: 15px; + font-weight: 500; +} +.required { + color: #b3261e; +} +.hint { + display: block; + font-size: 13px; + color: var(--muted); + font-weight: 400; + margin-top: 6px; +} +input:not([type="checkbox"]), +textarea, +select { + display: block; + width: 100%; + margin-top: 8px; + padding: 10px 12px; + border: 1px solid #bccdde; + border-radius: 6px; + background: #fff; + color: var(--ink); + font-size: 15px; + line-height: 1.6; + outline: none; +} +textarea { + resize: vertical; + min-height: 110px; +} +input:focus, +textarea:focus, +select:focus { + border-color: var(--blue); + box-shadow: 0 0 0 2px var(--soft); +} +.check { + display: flex; + gap: 10px; + color: var(--muted); + font-size: 13px; + font-weight: 400; + margin-top: 28px; + line-height: 1.7; +} +.check input { + margin-top: 5px; + accent-color: var(--blue); +} +.actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 20px; + margin-top: 24px; +} +.primary { + display: inline-block; + background: var(--blue); + color: #fff; + border: 0; + border-radius: 11px; + padding: 11px 22px; + font-size: 16px; + font-weight: 600; + text-decoration: none; +} +.primary:hover { + background: #066acb; + color: #fff; +} +.quiet { + border: 1px solid var(--line); + background: #fff; + color: var(--ink); + border-radius: 6px; + padding: 9px 16px; + font-size: 14px; +} +.message { + color: #b3261e; + background: #fff3f2; + border-left: 3px solid #b3261e; + padding: 12px 16px; + font-size: 14px; + white-space: pre-wrap; + margin-top: 20px; +} +.message:empty { + display: none; +} +.success { + border-top: 1px solid var(--line); + margin-top: 28px; + padding-top: 28px; +} +.credential { + display: block; + font: + 15px/1.8 ui-monospace, + Consolas, + monospace; + background: var(--paper); + border: 1px solid var(--line); + padding: 12px 16px; + overflow-wrap: anywhere; + margin: 8px 0 20px; + border-radius: 6px; +} +.badge { + display: inline-block; + background: var(--soft); + color: #096ace; + border-radius: 4px; + font-size: 13px; + line-height: 1.6; + padding: 3px 10px; + white-space: nowrap; +} +.split { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} +.detail { + margin-top: 32px; +} +.detail p { + font-size: 15px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.detail h3 { + margin-bottom: 12px; +} +.timeline { + border-left: 2px solid var(--line); + padding-left: 20px; +} +.timeline article { + margin: 0 0 24px; +} +.timeline small { + font-size: 12px; + color: var(--muted); +} +.history-label { + font-size: 14px; + font-weight: 600; +} +.trap { + position: absolute; + left: -10000px; +} +.footer { + display: flex; + gap: 28px; + border-top: 1px solid var(--line); + padding: 24px 0 34px; + font-size: 13px; + color: #667991; +} +.footer a { + color: inherit; + text-decoration: none; +} +@media (max-width: 800px) { + .wrap { + padding: 0 24px; + } + .nav { + min-height: 78px; + } + .navlinks { + gap: 16px; + } + .feedback-page { + padding: 34px 23px 55px; + } + .page-heading h1 { + font-size: 32px; + } + .page-heading p { + margin-bottom: 24px; + } + .fields { + gap: 20px; + } + .section { + margin-top: 26px; + } + .navlinks a { + font-size: 13px; + } +} +@media (max-width: 520px) { + .fields { + grid-template-columns: 1fr; + } + .brand { + font-size: 20px; + } + .brand img { + width: 40px; + height: 40px; + } + .nav { + gap: 14px; + flex-wrap: wrap; + padding: 16px 0; + } + .navlinks { + gap: 18px; + } + .navlinks a:first-child { + display: none; + } + .actions { + gap: 12px; + } + .split { + align-items: flex-start; + } + .feedback-page { + padding-top: 28px; + } +} +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } +} diff --git a/web/feedback/test/app.test.mjs b/web/feedback/test/app.test.mjs new file mode 100644 index 00000000..24639438 --- /dev/null +++ b/web/feedback/test/app.test.mjs @@ -0,0 +1,96 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +function element() { + return { + hidden: false, disabled: false, value: '', textContent: '', + setAttribute() {}, focus() {}, replaceChildren() {}, reset() {}, + querySelector() { return this.button ||= element(); }, + }; +} + +async function fixture(fetchImpl) { + const elements = new Map(); + const get = (id) => { + if (!elements.has(id)) elements.set(id, element()); + return elements.get(id); + }; + const form = get('feedback-form'); + form.elements = { + userId: { value: 'student' }, + problem: { value: '请保留已经填写的反馈内容' }, + consent: { checked: true }, contact: {}, contactType: {}, + }; + get('lookup-form').elements = { id: { value: 'TP-TEST' } }; + const timers = new Map(); + let nextTimer = 0, calls = 0; + const context = vm.createContext({ + location: { hostname: 'localhost', origin: 'http://localhost' }, + document: { getElementById: get, querySelector: () => element() }, + FormData: class { + constructor(form) { this.form = form; } + *[Symbol.iterator]() { + for (const [key, value] of Object.entries(this.form.elements)) { + yield [key, value.value]; + } + } + }, + TypeError, AbortController, + fetch: (...args) => { calls++; return fetchImpl(...args); }, + setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, + clearTimeout(id) { timers.delete(id); }, + }); + const common = await readFile(new URL('../public/common.js', import.meta.url), 'utf8'); + const app = await readFile(new URL('../public/app.js', import.meta.url), 'utf8'); + vm.runInContext(common.replace(/^export /gm, ''), context); + vm.runInContext(app.replace(/^import .*$/m, ''), context); + return { + get, form, calls: () => calls, + expire() { for (const fn of [...timers.values()]) fn(); }, + pendingTimers: () => timers.size, + }; +} + +test('successful submission reveals its receipt and releases the button', async () => { + const f = await fixture(async () => ({ ok: true, json: async () => ({ id: 'TP-9' }) })); + await f.form.onsubmit({ preventDefault() {} }); + assert.equal(f.get('receipt-id').textContent, 'TP-9'); + assert.equal(f.get('receipt').hidden, false); + assert.equal(f.form.hidden, true); + assert.equal(f.form.querySelector().disabled, false); + assert.equal(f.pendingTimers(), 0); +}); + +test('network failure keeps inputs and releases the submit button', async () => { + const f = await fixture(async () => { throw new TypeError('Failed to fetch'); }); + await f.form.onsubmit({ preventDefault() {} }); + assert.match(f.get('form-message').textContent, /网络连接失败/); + assert.equal(f.form.elements.problem.value, '请保留已经填写的反馈内容'); + assert.equal(f.form.hidden, false); + assert.equal(f.form.querySelector().disabled, false); + assert.equal(f.calls(), 1); +}); + +for (const mode of ['create', 'lookup']) { + test(`${mode} timeout releases button without automatic retries`, async () => { + let signal; + const f = await fixture((_url, options) => { + signal = options.signal; + return new Promise(() => {}); + }); + const form = mode === 'create' ? f.form : f.get('lookup-form'); + const task = form.onsubmit({ preventDefault() {}, currentTarget: form }); + await Promise.resolve(); await Promise.resolve(); + assert.equal(form.querySelector().disabled, true); + f.expire(); + await task; + assert.equal(signal.aborted, true); + assert.equal(form.querySelector().disabled, false); + assert.equal(f.calls(), 1); + assert.equal(f.pendingTimers(), 0); + assert.match(f.get(mode === 'create' ? 'form-message' : 'lookup-message').textContent, /请求超时/); + assert.equal(f.form.elements.problem.value, '请保留已经填写的反馈内容'); + }); +} diff --git a/web/feedback/test/common.test.mjs b/web/feedback/test/common.test.mjs new file mode 100644 index 00000000..287ea4fd --- /dev/null +++ b/web/feedback/test/common.test.mjs @@ -0,0 +1,156 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; + +test.beforeEach((t) => { + const original = globalThis.location; + globalThis.location = { hostname: 'localhost' }; + t.after(() => { + if (original === undefined) delete globalThis.location; + else globalThis.location = original; + }); +}); + +async function loadCommon() { + const source = await readFile( + new URL("../public/common.js", import.meta.url), + "utf8", + ); + const dataUrl = + "data:text/javascript;base64," + Buffer.from(source).toString("base64"); + return import(dataUrl); +} + +function mockFetch(t, impl) { + const original = globalThis.fetch; + const calls = []; + globalThis.fetch = (url, options) => { + calls.push({ url, options }); + return impl(url, options); + }; + t.after(() => { + globalThis.fetch = original; + }); + return calls; +} + +function mockTimers(t) { + const originalSet = globalThis.setTimeout; + const originalClear = globalThis.clearTimeout; + const pending = new Map(); + let nextId = 1; + globalThis.setTimeout = (fn, ms) => { + const id = nextId++; + pending.set(id, { fn, ms }); + return id; + }; + globalThis.clearTimeout = (id) => { + pending.delete(id); + }; + t.after(() => { + globalThis.setTimeout = originalSet; + globalThis.clearTimeout = originalClear; + }); + return { + fire() { + const entries = [...pending.values()]; + pending.clear(); + for (const { fn } of entries) fn(); + }, + get size() { + return pending.size; + }, + }; +} + +test("success resolves parsed result and clears timer", async (t) => { + const timers = mockTimers(t); + const calls = mockFetch(t, () => + Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ id: "TP-1" }), + }), + ); + const { api } = await loadCommon(); + const result = await api("lookup", { id: "TP-1" }); + assert.deepEqual(result, { id: "TP-1" }); + assert.equal(calls.length, 1); + assert.equal(timers.size, 0); +}); + +test("http error surfaces server message and status", async (t) => { + mockTimers(t); + mockFetch(t, () => + Promise.resolve({ + ok: false, + status: 400, + json: () => Promise.resolve({ error: "无效工单" }), + }), + ); + const { api } = await loadCommon(); + await assert.rejects(api("lookup", {}), (error) => { + assert.equal(error.message, "无效工单"); + assert.equal(error.status, 400); + return true; + }); +}); + +test("invalid body json yields friendly message", async (t) => { + mockTimers(t); + mockFetch(t, () => + Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.reject(new SyntaxError("bad json")), + }), + ); + const { api } = await loadCommon(); + await assert.rejects(api("lookup", {}), { message: "服务暂时不可用,请稍后重试" }); +}); + +test("network TypeError maps to translated message", async (t) => { + mockTimers(t); + mockFetch(t, () => Promise.reject(new TypeError("Failed to fetch"))); + const { api } = await loadCommon(); + await assert.rejects(api("create", {}), { + message: "网络连接失败,请检查网络后重试", + }); +}); + +test("hanging fetch aborts on timeout with create wording", async (t) => { + const timers = mockTimers(t); + let aborted = false; + mockFetch(t, (_url, options) => { + options.signal.addEventListener("abort", () => { + aborted = true; + }); + return new Promise(() => {}); + }); + const { api } = await loadCommon(); + const pending = api("create", {}); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(timers.size, 1); + timers.fire(); + await assert.rejects(pending, { + message: "请求超时,提交结果尚未确认,请勿连续重复提交", + }); + assert.equal(aborted, true); +}); + +test("hanging body parse timeouts and clears timer", async (t) => { + const timers = mockTimers(t); + mockFetch(t, () => + Promise.resolve({ ok: true, status: 200, json: () => new Promise(() => {}) }), + ); + const { api } = await loadCommon(); + const pending = api("lookup", {}); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(timers.size, 1); + timers.fire(); + await assert.rejects(pending, { message: "请求超时,请稍后重试" }); + assert.equal(timers.size, 0); +});