diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index ff88cc24..904a5221 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -82,3 +82,11 @@ jobs: - name: Test run: flutter test + + - name: Set up Node for watch checks + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Test watch protocol and signing + run: node --test harmonyos_watch/scripts/*.test.cjs harmonyos_watch/scripts/*.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f2d15e34..992bc15a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -127,6 +127,17 @@ jobs: flutter analyze --no-pub flutter test + + - name: Set up Node for watch checks + if: steps.plan.outputs.skip == 'false' + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Test watch protocol and signing + if: steps.plan.outputs.skip == 'false' + run: node --test harmonyos_watch/scripts/*.test.cjs harmonyos_watch/scripts/*.test.mjs + tag: name: Tag the release needs: plan diff --git a/.gitignore b/.gitignore index d5e343af..58b38253 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,23 @@ dist/ # Local agent/editor state (omp) .omp/ + +# Local notes and verification tools produced during watch development +/android/WEAR_ENGINE.md +/harmonyos_watch/README.md +/harmonyos_watch/docs/ +/scripts/check-android-16kb.py + +# Local Huawei service credentials +/android/app/agconnect-services.json + +# Local platform operation audit logs +/.local/ + +# Local HarmonyOS watch development artifacts +/harmonyos_watch/README.md +/harmonyos_watch/docs/ +/harmonyos_watch/.gitignore +/harmonyos_watch/build-profile.json5 + +/outputs/ diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 40ffed0b..ee4c2ed6 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -122,7 +122,8 @@ android { applicationId = "club.geekpie.techpie" // You can update the following values to match your application needs. // For more information, see: https://flutter.dev/to/review-gradle-config. - minSdk = flutter.minSdkVersion + // Wear Engine 5.0.3.300 requires Android 6.0 (API 23). + minSdk = maxOf(flutter.minSdkVersion, 23) targetSdk = flutter.targetSdkVersion versionCode = flutter.versionCode versionName = flutter.versionName @@ -146,3 +147,14 @@ tasks.named("preBuild") { dependsOn(prepareEcardWidgetResources) } flutter { source = "../.." } + +dependencies { + implementation("com.huawei.agconnect:agconnect-core:1.5.2.300") + implementation("com.huawei.hms:wearengine:5.0.3.300") + implementation("androidx.work:work-runtime:2.9.1") +} + +// Local AGConnect settings contain credentials and are not checked into Git. +if (file("agconnect-services.json").isFile) { + apply(plugin = "com.huawei.agconnect") +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 854b54b6..493de25a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -12,6 +12,8 @@ android:icon="@mipmap/ic_launcher" android:allowBackup="false" android:usesCleartextTraffic="false"> + + + 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..c1e3c8b4 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/wear/WearEngineBridge.kt @@ -0,0 +1,221 @@ +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)) + .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 false))) } + }.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) { + // Permission is Parcelable and does not implement value equality. + val p2pGranted = grants.any { it.name == Permission.DEVICE_MANAGER.name } + val notifyGranted = grants.any { it.name == Permission.NOTIFY.name } + Log.i("TechPieWear", "Device authorization granted=$p2pGranted") + if (answered.compareAndSet(false, true)) handler.post { + result.success(mapOf("p2p" to p2pGranted, + "notify" to notifyGranted)) + } + } + 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..d0f28436 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -1,8 +1,22 @@ +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 { 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/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..039df5b3 --- /dev/null +++ b/harmonyos_watch/BUILDING.md @@ -0,0 +1,86 @@ +# 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. + + +## Approved Wear Engine scope + +The Android companion is `club.geekpie.techpie`, App ID `119331345`. The +approved service is device basic information, including P2P. The normal status, +device discovery and connection flow only checks/requests `DEVICE_MANAGER`. +Account, DDL, timetable and campus-code snapshots use that P2P channel. + +The watch advertises `schedule.display` and `reminder.watchLocal` alongside the +existing capabilities. Timetable snapshots contain the next seven campus days +(Asia/Shanghai), including fetched courses, custom sessions and exams from the +phone's selected semester. A snapshot contains at most 50 complete course +blocks; the watch shows a truncation message when needed. Old peers negotiate +their supported resources. Each resource has its own revision and receipt. + +The phone's DDL reminder switch sends an opt-in in `ddl.snapshot`. The watch +checks `remindAtMs` against the phone-calibrated clock and vibrates locally using +`@system.vibrator` / `ohos.permission.VIBRATE`. Opt-in is off on each connection. +Only future triggers fire, once, while the watch app is open and the P2P session +is valid. Hiding/closing the app, disconnecting, logging out or the 24-hour lease +expiring clears the session. There is no background delivery through this path. +The existing native phone-notification integration is not exposed by this +switch; Wear Engine `NOTIFY` and remote-app launch remain unapproved. + +For device acceptance, install matching signed companions, open the watch app, +and connect through Settings → HUAWEI WATCH on Android. Check name/student ID, +DDL receipt, seven-day courses (including a custom session and exam), QR scan +and expiry, and a future reminder while the watch app stays open. Then check +app hide, disconnect, account switch and reconnect clear old data and reminder +consent. Confirm the Android certificate matches the watch's configured phone +fingerprint; a debug APK needs the explicit debug-fingerprint override above. + +Vendor vibration API: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-system-vibrate/ + +Android authorization callbacks contain Parcelable `Permission` objects. +Compare their `name` values when reading grants; this SDK does not implement +value equality for those objects. + + +The local-vibration permission declares its reason and `MainAbility` in-use +scene in `module.reqPermissions`. Keep permission declarations there; the +source Lite schema does not accept `abilities.permissions`. + +The page loads Wear Engine after first render (`onReady`) and the vibration +module when a reminder fires. Each list item has one child flex container. +Initialization errors appear on screen and in the lifecycle log. Startup after +the reported black screen and the circular icons await GT 6 Pro acceptance. + +Version 0.3.0 rebuilds the interface around glanceable content, capsule actions +and vertical browsing. See [interaction design](DESIGN.md) for the HIG mapping, +pixel values, platform features and pending device checks. diff --git a/harmonyos_watch/DESIGN.md b/harmonyos_watch/DESIGN.md new file mode 100644 index 00000000..643237b2 --- /dev/null +++ b/harmonyos_watch/DESIGN.md @@ -0,0 +1,66 @@ +# Watch interaction design + +TechPie Watch provides quick access to campus codes, the next class, deadlines and account identity on HUAWEI WATCH GT 6 Pro. Its interface follows Apple's watchOS Human Interface Guidelines for glanceable content, shallow navigation, readable text and direct actions. The implementation uses HarmonyOS Lite components and the device's system font. + +## Information hierarchy + +The home screen presents the next class and the campus-code action first. Scrolling reveals the timetable entry, the next deadline, the deadline list, account details and connection help. Each destination returns directly home through a visible button or the system back action. + +| View | Primary content | Actions | +| --- | --- | --- | +| Home | Next class, start time and location; next deadline | Open campus code, timetable, deadlines, account or help | +| Timetable | One campus day, ordered course blocks | Previous/next day across the seven-day snapshot, sync, home | +| Deadlines | Open tasks, due time, overdue/near-due label | Scroll, previous/next six-item group, sync, home | +| Campus code | Black modules on a white canvas and remaining validity | Refresh, home | +| Account | Name, student ID and connection state | Sync, text size, home | +| Connection help | Pair in Huawei Health, then connect from TechPie | Retry, home | + +Read-only cards carry content. Capsule buttons carry actions. Text names every action; status and urgency also have explicit labels. The app uses native vertical lists for touch and Crown scrolling. Huawei's Lite Wearable guide identifies `list`, `slider` and `swiper` as Crown-enabled components. Crown behavior on the target firmware awaits GT 6 Pro acceptance. Crown presses remain system-owned. + +## Visual system + +The 466-logical-pixel round target uses a black canvas, neutral cards and one blue action accent. Amber marks due-state labels, accompanied by text. Device system fonts provide Chinese and Latin glyphs. Apple font binaries and SF Symbols are not embedded. + +| Role | Source size | +| --- | --- | +| Page title | 38 px | +| Card headline | 32 px | +| Primary action | 45 px | +| Standard action | 42 px | +| Supporting text | 26 px | +| Caption / status | 24 px | +| Primary and secondary action height | 88 px | +| Card / primary action width | 336 px | +| Round-edge leading/trailing space | 56 px | + +Apple's watchOS typography guidance specifies a 16-point default and 12-point minimum. Its accessibility guidance gives a 44-by-44-point default control size and a 28-by-28-point minimum. The pixel values above are implementation choices for GT 6 Pro; physical readability and touch comfort require device acceptance. The account view provides a 140-percent text option for the current app session. +Content text scales by semantic role. Action labels use large fixed sizes; controls retain their touch area and content +remains vertically scrollable. Source defaults are in `pages/index/index.css`; +the scale values live in `pages/index/index.js`. + +Standard actions fill the available content width. Day navigation places two text buttons in one row. Content rows scroll vertically, with one flex child per Lite `list-item`. Each view keeps contextual actions close to its content. The QR view also scrolls so refresh and back retain full-height touch targets. + +The QR canvas is 264 by 264 pixels. Integer-sized black modules retain a quiet zone of at least four modules. The code's expiry and refresh behavior continue to use the phone-calibrated session clock. The launcher icons retain the original red P pixels inside an exact circular alpha mask. + +## Lifecycle and permissions + +First paint precedes native Wear Engine initialization. Startup failures appear on screen and in the lifecycle log. Vibration loads when a reminder fires. Account, timetable, deadline and code data continue over the approved device-manager P2P channel. Local reminders require phone opt-in, a valid connection and a foreground watch app. Hiding the app clears the session and code. + +Apple-specific system integrations such as SwiftUI controls, Dynamic Type, complications, Always On and watchOS notifications require an Apple Watch target. The GT 6 Pro build uses its available platform features. Its approved Wear Engine scope covers basic device information and P2P; notification delivery and remote app launch remain unapproved. + +## Acceptance status + +The Huawei SDK compiled the redesigned page, and its minified output fits the 48 KiB project page limit. Device testing is deferred at the user's request. Pending checks cover first paint after the reported black screen, round-screen clipping, long names, empty/loading/error states, touch and Crown navigation, code scanning/expiry, all synchronized resources and reminder/session cleanup. A successful build records source compatibility; device results determine runtime acceptance. + +## Design references + +- [Designing for watchOS](https://developer.apple.com/design/human-interface-guidelines/designing-for-watchos) +- [Layout](https://developer.apple.com/design/human-interface-guidelines/layout) +- [Buttons](https://developer.apple.com/design/human-interface-guidelines/buttons) +- [Typography](https://developer.apple.com/design/human-interface-guidelines/typography) +- [Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility) +- [Digital Crown](https://developer.apple.com/design/human-interface-guidelines/digital-crown) +- [Scroll views](https://developer.apple.com/design/human-interface-guidelines/scroll-views) +- [Apple Design Resources](https://developer.apple.com/design/resources/#watchos-apps) + +- [Huawei Lite Wearable guide](https://developer.huawei.com/consumer/cn/doc/lite-wearable-guides/lite-wearable-bpta-guide/) 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..54838182 --- /dev/null +++ b/harmonyos_watch/entry/src/main/config.json @@ -0,0 +1,31 @@ +{ + "app": { + "bundleName": "com.geekpie.techpie.watch", + "vendor": "geekpie", + "version": { "code": 4, "name": "0.3.0" } + }, + "deviceConfig": {}, + "module": { + "deviceType": ["liteWearable"], + "reqPermissions": [{ + "name": "ohos.permission.VIBRATE", + "reason": "用于待办截止前的振动提醒", + "usedScene": { "ability": ["MainAbility"], "when": "inuse" } + }], + "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..33879f1b --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-connection.js @@ -0,0 +1,356 @@ +// 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.schedule = []; this.scheduleRevision = 0; this.scheduleContent = null; this.scheduleUntil = 0; + this.scheduleTruncated = false; this.resources = ['account', 'ddl']; + this.remindersEnabled = false; this.reminderCursor = 0; this.alert = 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, + schedule: this.schedule, scheduleReady: this.scheduleUntil > this.phoneNow(), + scheduleTruncated: this.scheduleTruncated, alert: this.alert, remindersEnabled: this.remindersEnabled, + 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 = []; this.alert = null; } + if (this.scheduleUntil <= this.phoneNow()) this.schedule = []; + if (this.remindersEnabled) { + var current = this.phoneNow(), due = []; + for (var i = 0; i < this.ddl.length; i++) { + var item = this.ddl[i]; + if (item.status !== 'open' || item.dueAtMs <= current) continue; + var times = item.remindAtMs || []; + for (var j = 0; j < times.length; j++) { + if (times[j] > this.reminderCursor && times[j] <= current && current - times[j] < 60000) { due.push(item); break; } + } + } + this.reminderCursor = current; + if (due.length) this.alert = {id: 'r' + current, title: due[0].title, count: due.length}; + } + 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(), remaining: this.resources.slice()}; 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: this.resources}}); + return true; +}; +WatchConnection.prototype.applied = function(resource) { + var pending = this.pending.sync; + if (!pending) return; + pending.remaining = pending.remaining.filter(function(value) { return value !== resource; }); + if (!pending.remaining.length) delete this.pending.sync; +}; +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(); + if (Array.isArray(b.capabilities) && b.capabilities.indexOf('schedule.display') >= 0) this.resources.push('schedule'); + this.reply(m, 'session.welcome', {nonce: b.nonce, version: 1, + watchInstanceId: 'techpie-lite', capabilities: ['account.display', 'ddl.display', 'schedule.display', 'reminder.watchLocal', '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.applied('account'); 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 || + (item.remindAtMs !== undefined && (!Array.isArray(item.remindAtMs) || item.remindAtMs.length > 3 || + item.remindAtMs.some(function(t) { return !integer(t) || t < 1 || t > item.dueAtMs; })))) { + this.reject(m, 'INVALID_PAYLOAD'); return; + } + ids[item.id] = true; items.push(item); + } + var ddlContent = JSON.stringify({items: b.items, remindersEnabled: b.remindersEnabled === true}); + 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; + if (!this.remindersEnabled && b.remindersEnabled === true) this.reminderCursor = this.phoneNow(); + this.remindersEnabled = b.remindersEnabled === true; + if (!this.remindersEnabled || (this.alert && !items.some(function(item) { + return item.status === 'open' && item.title === this.alert.title; + }, this))) this.alert = null; + this.updatedAt = integer(b.generatedAtMs) ? b.generatedAtMs : this.phoneNow(); + this.applied('ddl'); this.error = ''; this.silence = 0; this.publish(); + this.reply(m, 'result', {status: 'ok', code: 'OK', resource: 'ddl', revision: b.revision}); + } else if (m.type === 'schedule.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 valid = b.items.every(function(item) { + return item && typeof item.name === 'string' && item.name.trim() && characters(item.name) <= 80 && + typeof item.location === 'string' && characters(item.location) <= 40 && + integer(item.startAtMs) && item.startAtMs > 0 && integer(item.endAtMs) && item.endAtMs > item.startAtMs; + }); + if (!valid) { this.reject(m, 'INVALID_PAYLOAD'); return; } + var content = JSON.stringify(b.items); + if (b.revision < this.scheduleRevision || (b.revision === this.scheduleRevision && content !== this.scheduleContent)) { + this.reject(m, 'STALE_REVISION'); return; + } + this.schedule = b.items.slice().sort(function(a, c) { return a.startAtMs - c.startAtMs; }); + this.scheduleRevision = b.revision; this.scheduleContent = content; + this.scheduleUntil = b.validUntilMs; this.scheduleTruncated = b.truncated === true; + this.silence = 0; this.applied('schedule'); this.error = ''; this.publish(); + this.reply(m, 'result', {status: 'ok', code: 'OK', resource: 'schedule', 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/wear-vibrator.js b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-vibrator.js new file mode 100644 index 00000000..6cd0985b --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/common/wear-vibrator.js @@ -0,0 +1,4 @@ +// Keep the native vibration module out of the page's initial load. +import vibrator from '@system.vibrator'; + +export default vibrator; 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..329ffc8e --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.css @@ -0,0 +1,37 @@ +.screen { width: 100%; height: 100%; background-color: #000000; } +.content { width: 100%; height: 100%; flex-direction: column; } +.edge-space { height: 56px; width: 100%; } +.section { width: 100%; flex-direction: column; align-items: center; } +.header { margin-bottom: 20px; } +.title { width: 300px; font-size: 38px; color: #ffffff; text-align: center; } +.status { width: 300px; font-size: 24px; color: #b5b5bd; text-align: center; margin-top: 4px; } +.card { width: 336px; padding: 20px; margin-bottom: 12px; flex-direction: column; background-color: #1c1c1e; border-radius: 28px; } +.caption { width: 296px; font-size: 24px; color: #b5b5bd; margin-bottom: 8px; } +.accent { color: #64b5ff; } +.urgent { color: #ffd080; } +.headline { width: 296px; font-size: 32px; color: #ffffff; } +.support { width: 296px; font-size: 26px; color: #c7c7cc; margin-top: 8px; margin-bottom: 8px; } +.due { width: 296px; font-size: 30px; color: #ffffff; margin-top: 12px; } +.primary { width: 336px; height: 88px; border-radius: 44px; background-color: #0a64cc; color: #ffffff; font-size: 45px; margin-bottom: 12px; } +.secondary { width: 336px; height: 88px; border-radius: 44px; background-color: #2c2c2e; color: #ffffff; font-size: 42px; margin-bottom: 12px; } +.day-title { width: 300px; font-size: 32px; color: #ffffff; text-align: center; margin-bottom: 16px; } +.day-actions { width: 336px; justify-content: center; margin-bottom: 12px; } +.day-button { width: 160px; height: 88px; border-radius: 44px; background-color: #2c2c2e; color: #ffffff; font-size: 39px; margin-left: 4px; margin-right: 4px; } +.centered { text-align: center; } +.empty { width: 296px; font-size: 32px; color: #c7c7cc; text-align: center; margin-top: 28px; margin-bottom: 28px; } +.identity-label { margin-top: 24px; } +.error { width: 296px; color: #ffb4ab; font-size: 26px; margin-top: 12px; margin-bottom: 16px; } +.code-page { width: 100%; height: 100%; flex-direction: column; background-color: #ffffff; } +.code-title { width: 220px; height: 52px; text-align: center; font-size: 28px; color: #000000; } +.qr { width: 264px; height: 264px; background-color: #ffffff; } +.code-empty { width: 264px; height: 216px; text-align: center; font-size: 30px; color: #242426; } +.code-countdown { width: 264px; height: 48px; font-size: 24px; text-align: center; color: #48484a; } +.code-action { width: 264px; height: 88px; border-radius: 44px; background-color: #0a64cc; color: #ffffff; font-size: 37px; margin-top: 4px; } +.code-back { width: 220px; background-color: #e5e5ea; color: #000000; } +.startup-error { width: 300px; height: 260px; margin-left: 83px; margin-top: 100px; color: #ffb4ab; font-size: 28px; } + +.primary:active { background-color: #084c9e; } +.secondary:active { background-color: #48484a; } +.day-button:active { background-color: #48484a; } +.code-action:active { background-color: #084c9e; } +.code-back:active { background-color: #c7c7cc; } 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..c7cba94c --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.hml @@ -0,0 +1,147 @@ +
+ {{ error }} + +
+ +
+ {{ view === 'home' ? 'TechPie' : (view === 'ddl' ? '待办 DDL' : (view === 'schedule' ? '课表' : (view === 'account' ? '我的账号' : '连接帮助'))) }} + {{ status }} +
+
+ +
+
+ {{ alertHint }} + {{ alertTitle }} + {{ vibrationError }} +
+ +
+
+ +
+ +
+ 下一节课 + {{ nextCourse }} + {{ nextCourseTime }} + {{ nextLocation }} +
+
+
+ +
+ +
+ 即将截止 + {{ nextTitle }} + {{ nextDue }} +
+ + + +
+
+ +
+ {{ dayLabel }} +
+ + +
+ {{ scheduleEmpty }} +
+
+ +
+
+ {{ $item.time }} + {{ $item.name }} + {{ $item.location }} +
+
+
+ +
+ 课程较多,已同步前 50 项 + +
+
+ +
+ {{ updated }} + {{ ddlEmpty }} +
+
+ +
+
+ {{ $item.hint }} + {{ $item.title }} + {{ $item.course }} + {{ $item.due }} +
+
+
+ +
+ {{ pageLabel }} + + + + 更多待办请在手机查看 + {{ reminderText }} +
+
+ +
+
+ 姓名 + {{ 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..520069cf --- /dev/null +++ b/harmonyos_watch/entry/src/main/js/MainAbility/pages/index/index.js @@ -0,0 +1,184 @@ +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', startupFailed: false, connected: false, status: '未连接', name: '', studentId: '', + detail: '打开手机 TechPie 连接手表', nextTitle: '连接后查看待办', nextDue: '', + nextCourse: '连接后查看课表', nextCourseTime: '', nextLocation: '', + 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: '', courses: [], scheduleReady: false, dayOffset: 0, dayLabel: '', + scheduleEmpty: '等待手机同步', scheduleTruncated: false, + reminderText: '提醒未开启', alertTitle: '', alertHint: '', vibrationError: '', + largeText: false, titleSize: 38, headlineSize: 32, bodySize: 26, + captionSize: 24, actionSize: 30 + }, + onInit() { console.info('TechPie watch page created'); }, + onShow() { if (link) link.start(); }, + onReady() { + // Paint the page before loading native integrations; startup failures stay visible. + var page = this; + this.drawCode(); + try { + var WearLink = require('../../common/wear-link.js').WearLink; + link = new WearLink(function(state) { page.applyState(state); }); + link.start(); + console.info('TechPie watch initialized'); + } catch (error) { + this.startupFailed = true; + this.error = '启动失败:' + String(error); + console.error(this.error); + } + }, + 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.alertTitle = state.alert ? state.alert.title : ''; + this.alertHint = state.alert ? (state.alert.count > 1 ? '另有 ' + (state.alert.count - 1) + ' 项待办即将截止' : '截止前 1 小时提醒') : ''; + this.reminderText = state.remindersEnabled ? '提醒已开启 · 保持手表应用打开并连接' : '在手机中开启 DDL 提醒'; + if (!state.alert) this._alertId = null; + if (state.alert && this._alertId !== state.alert.id) { + this._alertId = state.alert.id; this.vibrationError = ''; + var page = this; + try { + var vibrator = require('../../common/wear-vibrator.js').default; + vibrator.vibrate({mode: 'long', fail: function() { page.vibrationError = '振动失败,请查看待办'; }}); + } catch (error) { + this.vibrationError = '振动不可用,请查看待办'; + console.error('TechPie watch vibration: ' + String(error)); + } + } + 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 小时内截止' : '待完成')}; + }); + var day = new Date(now + 28800000 + this.dayOffset * 86400000); + var from = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate()) - 28800000; + this.dayLabel = (day.getUTCMonth() + 1) + '/' + day.getUTCDate() + ' 周' + '日一二三四五六'.charAt(day.getUTCDay()); + this.courses = (state.schedule || []).filter(function(item) { + return item.startAtMs >= from && item.startAtMs < from + 86400000; + }).map(function(item) { return {name: short(item.name, 32), location: short(item.location, 20), + time: dueLabel(item.startAtMs).split(' ')[1] + '–' + dueLabel(item.endAtMs).split(' ')[1]}; }); + this.scheduleReady = state.scheduleReady || false; + this.scheduleTruncated = state.scheduleTruncated || false; + this.scheduleEmpty = this.scheduleReady ? '当天没有课程' : '等待手机同步课表'; + 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) + ' 截止' : ''; + var upcoming = (state.schedule || []).filter(function(item) { return item.endAtMs > now; })[0]; + this.nextCourse = upcoming ? short(upcoming.name, 20) : + (this.scheduleReady ? '未来 7 天暂无课程' : '连接后查看课表'); + this.nextCourseTime = upcoming ? (upcoming.startAtMs <= now ? '正在上课 · ' : '') + + dueLabel(upcoming.startAtMs) : ''; + this.nextLocation = upcoming ? short(upcoming.location, 20) : ''; + 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(); }, + showSchedule() { this.view = 'schedule'; this.dayOffset = 0; if (link) link.connection.publish(); }, + previousDay() { if (this.dayOffset > 0) { this.dayOffset--; link.connection.publish(); } }, + nextDay() { if (this.dayOffset < 6) { this.dayOffset++; link.connection.publish(); } }, + dismissAlert() { if (link) { link.connection.alert = null; link.connection.publish(); } }, + showAccount() { this.view = 'account'; }, + toggleTextSize() { + this.largeText = !this.largeText; + var scale = this.largeText ? 1.4 : 1; + this.titleSize = Math.ceil(38 * scale); + this.headlineSize = Math.ceil(32 * scale); + this.bodySize = Math.ceil(26 * scale); + this.captionSize = Math.ceil(24 * scale); + this.actionSize = Math.ceil(30 * scale); + }, + 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..5295067b 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..7fff296e 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..57b166a3 --- /dev/null +++ b/harmonyos_watch/scripts/wear-connection.test.mjs @@ -0,0 +1,242 @@ +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', 'schedule.display', 'reminder.watchLocal', '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); +}); + + +test('timetable is atomic, revisioned, expires and clears with the session', () => { + const f = fixture(); f.open(); + const item = {name: '物理😀', location: '教学楼 201', startAtMs: 1050000, endAtMs: 1100000}; + f.send('schedule.snapshot', {revision: 2, validUntilMs: 1020000, items: [item]}); + assert.equal(f.state().scheduleReady, true); + assert.equal(f.last().body.resource, 'schedule'); + f.send('schedule.snapshot', {revision: 1, validUntilMs: 1020000, items: []}); + assert.equal(f.last().body.code, 'STALE_REVISION'); + f.send('schedule.snapshot', {revision: 3, validUntilMs: 1020000, items: [{...item, endAtMs: 0}]}); + assert.equal(f.last().body.code, 'INVALID_PAYLOAD'); + assert.equal(f.state().schedule.length, 1); + f.advance(20000); assert.equal(f.state().schedule.length, 0); + f.send('schedule.snapshot', {revision: 3, validUntilMs: 1050000, items: [item]}); + f.send('session.clear'); assert.equal(f.state().schedule.length, 0); +}); +test('sync requests negotiate timetable support from the phone hello', () => { + const f = fixture(); f.open(); f.link.request('sync'); + assert.deepEqual(f.last().body.resources, ['account', 'ddl']); + f.send('session.hello', {nonce: 'nonce', versions: [1], capabilities: ['schedule.display']}); + f.send('session.open', {nonce: 'nonce', sessionId: 'session', bindingId: 'binding', phoneTimeMs: 1000000, leaseUntilMs: 2000000}); + f.link.request('sync'); assert.deepEqual(f.last().body.resources, ['account', 'ddl', 'schedule']); +}); +test('local reminder fires once, ignores old or completed deadlines, and clears on revoke', () => { + const f = fixture(); f.open(); + const item = {id: 'ddl', title: '实验报告', courseName: '物理', dueAtMs: 1100000, status: 'open', remindAtMs: [1002000]}; + f.send('ddl.snapshot', {revision: 1, validUntilMs: 1200000, remindersEnabled: true, items: [item, + {...item, id: 'old', remindAtMs: [999000]}, {...item, id: 'done', status: 'completed'}]}); + assert.equal(f.state().alert, null); + f.advance(2000); assert.equal(f.state().alert.title, '实验报告'); assert.equal(f.state().alert.count, 1); + f.link.alert = null; f.advance(1000); assert.equal(f.state().alert, null); + f.send('ddl.snapshot', {revision: 2, validUntilMs: 1200000, remindersEnabled: false, items: [item]}); + assert.equal(f.state().remindersEnabled, false); + f.send('session.close'); assert.equal(f.state().alert, null); +}); +test('malformed reminder times reject the entire snapshot', () => { + const f = fixture(); f.open(); + f.send('ddl.snapshot', {revision: 1, validUntilMs: 1200000, items: [ + {id: 'a', title: '作业', courseName: '', dueAtMs: 1100000, status: 'open', remindAtMs: ['invalid']} ]}); + assert.equal(f.last().body.code, 'INVALID_PAYLOAD'); assert.equal(f.state().ddlReady, false); +}); diff --git a/lib/main.dart b/lib/main.dart index af85bf5a..02a5af51 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -29,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/privacy_consent.dart'; @@ -101,6 +105,19 @@ Future _realMain(SharedPreferences prefs) async { thirdPartyAuthService, scheduleService, ); + final wearEngineService = isAndroid() + ? WearEngineService( + transport: AndroidWearTransport(), + metadata: PreferencesWearMetadata(prefs), + source: TechPieWearDataSource( + auth: authService, + accounts: thirdPartyAuthService, + assignments: assignmentService, + campusCard: campusCardService, + timetable: scheduleService, + ), + ) + : null; final deadlineWidgetService = DeadlineWidgetService(assignmentService); final syncService = SyncService( authService, @@ -187,6 +204,7 @@ Future _realMain(SharedPreferences prefs) async { campusCardService: campusCardService, ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, + wearEngineService: wearEngineService, deadlineWidgetService: deadlineWidgetService, ), ); @@ -209,6 +227,44 @@ 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; + }, + ), + ); + } + } + + void scheduleChanged() { + if (wearEngineService.ready && + !scheduleService.loading && + wearEngineService.supports('schedule.display')) { + unawaited( + wearEngineService + .refresh(resources: ['schedule']).catchError((Object error) { + if (error is! WearFailure) throw error; + }), + ); + } + } + + scheduleService.addListener(scheduleChanged); + assignmentService.addListener(scheduleChanged); + 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 @@ -321,6 +377,7 @@ class TechPieApp extends StatefulWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final WearEngineService? wearEngineService; final DeadlineWidgetService? deadlineWidgetService; const TechPieApp({ @@ -340,6 +397,7 @@ class TechPieApp extends StatefulWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.wearEngineService, this.deadlineWidgetService, }); @@ -386,6 +444,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { widget.ecardWidgetService?.clearOpenPayHandler(); widget.deadlineWidgetService?.dispose(); widget.campusCardService.dispose(); + widget.wearEngineService?.dispose(); super.dispose(); } @@ -481,6 +540,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + wearEngineService: widget.wearEngineService, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, diff --git a/lib/pages/huawei_watch_page.dart b/lib/pages/huawei_watch_page.dart new file mode 100644 index 00000000..641fc6ba --- /dev/null +++ b/lib/pages/huawei_watch_page.dart @@ -0,0 +1,492 @@ +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') + : '请更新手表应用以使用此功能', + ), + ), + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + leading: const Icon(Icons.calendar_month_outlined), + title: const Text('未来 7 天课表'), + subtitle: Text( + service.supports('schedule.display') + ? _syncLabel(service, 'schedule') + : '请更新手表应用以使用此功能', + ), + ), + if (service.supports('reminder.watchLocal')) + SwitchListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + secondary: const Icon(Icons.notifications_none), + title: const Text('DDL 提醒'), + subtitle: const Text( + '截止前 1 小时振动 · 手表应用打开且连接时生效', + ), + value: service.watchRemindersEnabled, + onChanged: _busy + ? null + : (enabled) => unawaited( + _run( + () => service.setWatchRemindersEnabled(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 18a42df3..1963b510 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -35,6 +35,7 @@ import 'debug_log_page.dart'; import 'debug_webview_page.dart'; import 'developer_lab_page.dart'; import 'feedback_page.dart'; +import 'huawei_watch_page.dart'; import 'sync_settings_page.dart'; import 'third_party_accounts_page.dart'; import 'watch_settings_page.dart'; @@ -361,16 +362,36 @@ 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('Apple Watch'), + title: const Text('Huawei Watch'), + subtitle: const Text('华为运动手表'), trailing: const Icon(Icons.chevron_right), onTap: () => unawaited( - pushAdaptivePage(context, - builder: (_) => const WatchSettingsPage(),), + pushAdaptivePage( + context, + builder: (_) => const HuaweiWatchPage(), + ), ), ), + if (isIos()) + ListTile( + leading: const Icon(Icons.watch_outlined), + title: const Text('Apple Watch'), + trailing: const Icon(Icons.chevron_right), + onTap: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const WatchSettingsPage(), + ), + ), + ), + const Divider(), + ], // Appearance section _sectionHeader(theme, 'Appearance'), diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..a4672e35 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -15,6 +15,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 +33,7 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final WearEngineService? wearEngineService; const ServiceProvider({ super.key, @@ -50,6 +52,7 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.wearEngineService, required super.child, }); @@ -76,5 +79,6 @@ class ServiceProvider extends InheritedWidget { updateService != oldWidget.updateService || campusCardService != oldWidget.campusCardService || ecardBindService != oldWidget.ecardBindService || - ecardWidgetService != oldWidget.ecardWidgetService; + ecardWidgetService != oldWidget.ecardWidgetService || + wearEngineService != oldWidget.wearEngineService; } 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..b855348a --- /dev/null +++ b/lib/services/wear/techpie_wear_data_source.dart @@ -0,0 +1,138 @@ +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 '../../models/exam_course.dart'; +import '../assignment_service.dart'; +import '../auth_service.dart'; +import '../campus_card_service.dart'; +import '../schedule_service.dart'; +import '../third_party_auth_service.dart'; +import 'wear_protocol.dart'; +import 'wear_schedule.dart'; + +class TechPieWearDataSource implements WearDataSource { + TechPieWearDataSource({ + required this.auth, + required this.accounts, + required this.assignments, + required this.campusCard, + required this.timetable, + this.reminderOffsets = const [Duration(hours: 1)], + }); + final AuthService auth; + final ThirdPartyAuthService accounts; + final AssignmentService assignments; + final CampusCardService campusCard; + final ScheduleService timetable; + + /// 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> schedule(DateTime from) async { + if (timetable.loading) { + throw const WearFailure('PEER_NOT_READY', retryable: true); + } + final table = timetable.courseTable; + final begin = timetable.termBegin; + if (timetable.error != null || + table == null || + begin == null || + assignments.loading || + assignments.platformErrors.containsKey('exam')) { + throw const WearFailure('SERVICE_UNAVAILABLE', retryable: true); + } + return buildWearSchedule( + table: table, + termBegin: begin, + from: from, + customCourses: timetable.customCourses, + exams: examsForSemester( + assignments.assignments, + timetable.selectedSemesterId, + ), + ); + } + + @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..50854ae0 --- /dev/null +++ b/lib/services/wear/wear_engine_service.dart @@ -0,0 +1,941 @@ +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', 'schedule']) { + _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, 'schedule': 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 _watchRemindersEnabled = false; + bool get watchRemindersEnabled => ready && _watchRemindersEnabled; + 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) { + _watchRemindersEnabled = false; + _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', + if (_capabilities.contains('schedule.display')) 'schedule', + ], + ); + } 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', + 'schedule.display', + 'reminder.watchLocal', + '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', + 'schedule.display', + 'reminder.watchLocal', + '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', 'schedule'].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}) { + final selected = resources ?? + ['account', 'ddl', 'schedule'] + .where((resource) => supports('$resource.display')) + .toList(); + final operation = + _refreshTail.catchError((Object _) {}).then((_) => _refresh(selected)); + _refreshTail = operation.catchError((Object _) {}); + return operation; + } + + Future _refresh(List resources) async { + _requireReady(); + if (resources.isEmpty || + resources.any((r) => !['account', 'ddl', 'schedule'].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 if (resource == 'schedule') { + final items = await source.schedule(now()); + body = { + 'timeZone': 'Asia/Shanghai', + 'days': 7, + 'truncated': items.length > 50, + 'items': items.take(50).map((item) => item.toJson()).toList(), + }; + } else { + final items = await source.deadlines(); + body = _ddlSnapshot(items); + if (supports('reminder.watchLocal')) { + body['remindersEnabled'] = _watchRemindersEnabled; + } + 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 setWatchRemindersEnabled(bool enabled) async { + _requireReady(); + if (!supports('reminder.watchLocal')) { + throw const WearFailure('UNSUPPORTED_OPERATION'); + } + final epoch = _epoch; + final previous = _watchRemindersEnabled; + _watchRemindersEnabled = enabled; + try { + await refresh(resources: ['ddl']); + _checkEpoch(epoch); + } catch (error) { + if (epoch == _epoch) { + _watchRemindersEnabled = previous; + // A lost receipt leaves the peer's setting unknown. End that session. + if (error is WearFailure && error.code == 'SYNC_TIMEOUT') await close(); + } + rethrow; + } finally { + _changed(); + } + } + + 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; + _watchRemindersEnabled = 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..de7f9280 --- /dev/null +++ b/lib/services/wear/wear_protocol.dart @@ -0,0 +1,223 @@ +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; +} + +class WearCourse { + const WearCourse({ + required this.name, + required this.location, + required this.startAt, + required this.endAt, + }); + final String name, location; + final DateTime startAt, endAt; + Map toJson() => { + 'name': name, + 'location': location, + 'startAtMs': startAt.millisecondsSinceEpoch, + 'endAtMs': endAt.millisecondsSinceEpoch, + }; +} + +abstract interface class WearDataSource { + Future account(); + Future> deadlines(); + Future> schedule(DateTime from); + 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/services/wear/wear_schedule.dart b/lib/services/wear/wear_schedule.dart new file mode 100644 index 00000000..4acebc04 --- /dev/null +++ b/lib/services/wear/wear_schedule.dart @@ -0,0 +1,81 @@ +import '../../models/assignment.dart'; +import '../../models/course.dart'; +import '../../models/course_table.dart'; +import '../../models/custom_course.dart'; +import '../../models/exam_course.dart'; +import 'wear_protocol.dart'; + +/// Build the same course blocks as the phone for seven campus-calendar days. +List buildWearSchedule({ + required CourseTable table, + required DateTime termBegin, + required DateTime from, + required List customCourses, + required Iterable exams, +}) { + final periods = table.periods.isEmpty + ? defaultPeriods + : table.periods.map((p) => p.toPeriod()).toList(); + DateTime campusClock(DateTime time) { + final value = time.toUtc().add(const Duration(hours: 8)); + return DateTime( + value.year, + value.month, + value.day, + value.hour, + value.minute, + ); + } + + final campusExams = exams + .map( + (exam) => ExamAssignment( + id: exam.id, + title: exam.title, + course: exam.course, + due: campusClock(exam.due), + lateDue: exam.lateDue == null ? null : campusClock(exam.lateDue!), + semesterId: exam.semesterId, + location: exam.location, + batchName: exam.batchName, + ), + ) + .toList(); + final result = []; + // Campus times are Asia/Shanghai, independent of the phone's current zone. + final campusDay = from.toUtc().add(const Duration(hours: 8)); + final first = DateTime.utc(campusDay.year, campusDay.month, campusDay.day); + final term = DateTime.utc(termBegin.year, termBegin.month, termBegin.day); + for (var offset = 0; offset < 7; offset++) { + final day = first.add(Duration(days: offset)); + final week = (day.difference(term).inDays / 7).floor() + 1; + final courses = withExamCourses( + withCustomCourses( + eamsToDisplayCourses(table.courses, week, timetablePeriods: periods), + customCourses, + week, + termBegin, + periods: periods, + ), + campusExams, + week, + termBegin, + periods: periods, + ); + for (final course in courses + .where((c) => c.dayOfWeek == day.weekday && c.occursOn(day))) { + final start = parseClockMinutes(course.startTime)!; + final end = parseClockMinutes(course.endTime)!; + result.add( + WearCourse( + name: String.fromCharCodes(course.name.runes.take(80)), + location: String.fromCharCodes(course.location.runes.take(40)), + startAt: day.add(Duration(minutes: start - 480)), + endAt: day.add(Duration(minutes: end - 480)), + ), + ); + } + } + result.sort((a, b) => a.startAt.compareTo(b.startAt)); + return result; +} 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..e5e9ffc1 --- /dev/null +++ b/test/services/wear_engine_service_test.dart @@ -0,0 +1,637 @@ +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 { + List courses = []; + @override + Future> schedule(DateTime from) async => courses; + 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(); + final authorizations = []; + bool ignoreAccount = false; + bool rejectDdl = false; + bool ignoreDdl = 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 { + authorizations.add(notify); + return {'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 'schedule.snapshot': + respond( + message, + 'result', + { + 'status': 'ok', + 'code': 'OK', + 'resource': 'schedule', + 'revision': body['revision'], + }, + ); + case 'ddl.snapshot': + if (ignoreDdl) return; + 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( + 'approved P2P syncs timetable and enables local reminders without NOTIFY', + () async { + peer.capabilities.addAll(['schedule.display', 'reminder.watchLocal']); + source.courses = [ + WearCourse( + name: '大学物理', + location: '教学楼 201', + startAt: testNow.add(const Duration(hours: 1)), + endAt: testNow.add(const Duration(hours: 2)), + ), + ]; + await open(); + final timetable = peer.received + .singleWhere((m) => m['type'] == 'schedule.snapshot')['body'] as Map; + expect((timetable['items'] as List).single['name'], '大学物理'); + expect(timetable['timeZone'], 'Asia/Shanghai'); + expect(service.watchRemindersEnabled, false); + await service.setWatchRemindersEnabled(true); + expect(service.watchRemindersEnabled, true); + expect( + (peer.received.lastWhere((m) => m['type'] == 'ddl.snapshot')['body'] + as Map)['remindersEnabled'], + true, + ); + expect(peer.authorizations, [false]); + expect(peer.schedule, null); + await service.close(); + expect(service.watchRemindersEnabled, false); + }); + test('failed P2P reminder update retains previous setting', () async { + peer.capabilities.add('reminder.watchLocal'); + await open(); + peer.rejectDdl = true; + await expectLater( + service.setWatchRemindersEnabled(true), + throwsA(isA()), + ); + expect(service.watchRemindersEnabled, false); + expect(peer.authorizations, [false]); + }); + test('lost local-reminder receipt ends the uncertain session', () async { + peer.capabilities.addAll(['reminder.watchLocal', 'connection.heartbeat']); + await open(); + peer.ignoreDdl = true; + await expectLater( + service.setWatchRemindersEnabled(true), + throwsA(isA()), + ); + expect(service.ready, false); + expect(service.watchRemindersEnabled, false); + expect(peer.received.last['type'], 'session.close'); + }); + test('old watch receives only supported resources', () async { + await open(); + expect( + peer.received.where((m) => m['type'] == 'schedule.snapshot'), + isEmpty, + ); + await expectLater( + service.setWatchRemindersEnabled(true), + throwsA(isA()), + ); + }); + + 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/services/wear_schedule_test.dart b/test/services/wear_schedule_test.dart new file mode 100644 index 00000000..eaeaa899 --- /dev/null +++ b/test/services/wear_schedule_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/models/assignment.dart'; +import 'package:techpie/models/course.dart'; +import 'package:techpie/models/course_table.dart'; +import 'package:techpie/models/custom_course.dart'; +import 'package:techpie/services/wear/wear_schedule.dart'; + +void main() { + const table = CourseTable( + periods: [ + CoursePeriod(index: 1, timeRange: '08:00-08:45'), + ], + courses: [ + EamsCourse( + name: '第一周课程', + classroom: '101', + teachers: '', + weeks: '010', + times: { + 1: [1], + }, + ), + EamsCourse( + name: '第二周课程', + classroom: '202', + teachers: '', + weeks: '001', + times: { + 1: [1], + }, + ), + ], + ); + test('campus midnight crosses a teaching-week boundary even on a UTC phone', + () { + final courses = buildWearSchedule( + table: table, + termBegin: DateTime(2026, 11, 9), + from: DateTime.utc(2026, 11, 15, 17), + customCourses: [], + exams: [], + ); + expect(courses.map((c) => c.name), ['第二周课程']); + expect(courses.single.startAt, DateTime.utc(2026, 11, 16)); + expect(courses.single.endAt, DateTime.utc(2026, 11, 16, 0, 45)); + }); + test('custom sessions and exams retain their own campus day and clock range', + () { + final courses = buildWearSchedule( + table: const CourseTable(periods: [], courses: []), + termBegin: DateTime(2026, 11, 9), + from: DateTime.utc(2026, 11, 12, 17), + customCourses: [ + CustomCourse( + id: 'lab', + name: '实验课', + date: DateTime(2026, 11, 13), + time: const ClockCourseTime(startTime: '09:00', endTime: '09:50'), + ), + ], + exams: [ + ExamAssignment( + id: 'exam', + title: '物理考试', + course: '物理', + due: DateTime.utc(2026, 11, 13, 2), + lateDue: DateTime.utc(2026, 11, 13, 4), + semesterId: '1', + location: '201', + batchName: '', + ), + ], + ); + expect(courses.map((c) => c.name), ['实验课', '物理考试']); + expect(courses.first.startAt, DateTime.utc(2026, 11, 13, 1)); + expect(courses.last.endAt, DateTime.utc(2026, 11, 13, 4)); + }); + test('seven-day window excludes ghosts and courses beyond the window', () { + final courses = buildWearSchedule( + table: table, + termBegin: DateTime(2026, 11, 9), + from: DateTime.utc(2026, 11, 9), + customCourses: [], + exams: [], + ); + expect(courses.map((c) => c.name), ['第一周课程']); + expect(courses.every((c) => c.endAt.isAfter(c.startAt)), true); + }); +}