diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 40ffed0b..fe589da7 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -141,6 +141,11 @@ android { } } +dependencies { + implementation("com.xzakota.hyper.notification:focus-api:1.4") + implementation("androidx.core:core:1.18.0") +} + tasks.named("preBuild") { dependsOn(prepareEcardWidgetResources) } flutter { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 854b54b6..7c158390 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,4 +1,9 @@ - + + + + + + @@ -51,6 +56,13 @@ + + + + + + + () + private val persisted = mutableMapOf() + + @Synchronized + fun next(notifyId: Int, nowMs: Long = System.currentTimeMillis()): Long { + val key = "seq_$notifyId" + val last = cache[notifyId] ?: prefs.getLong(key, 0L) + val seq = FocusSequence.next(last, nowMs) + cache[notifyId] = seq + val lastWritten = persisted[notifyId] ?: prefs.getLong(key, 0L) + if (seq - lastWritten >= PERSIST_STEP_MS) { + persisted[notifyId] = seq + prefs.edit { putLong(key, seq) } + } + return seq + } + + private companion object { + const val PREFS_NAME = "island_focus_seq" + const val PERSIST_STEP_MS = 30_000L + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandAlarms.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandAlarms.kt new file mode 100644 index 00000000..94e029bc --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandAlarms.kt @@ -0,0 +1,272 @@ +package club.geekpie.techpie.island + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.util.Log +import org.json.JSONArray +import org.json.JSONObject + +/** + * Keeps the island on screen while the app is not running. + * + * The Dart side precomputes the frames (it owns the schedule), this side stores + * them and posts each one at its time through AlarmManager. Reboot and package updates restore future frames. A null frame means "nothing to say any more": dismiss. + */ +object IslandAlarms { + const val ACTION = "club.geekpie.techpie.ISLAND_FRAME" + const val EXTRA_FRAME = "frame" + + private const val TAG = "IslandAlarms" + private const val PREFS = "techpie_island_alarms" + private const val ITEMS_KEY = "frames" + private const val MAX_EVENTS = 256 + + /** [frameJson] null asks the receiver to dismiss instead of posting. */ + data class Item(val atMillis: Long, val frameJson: String?) + + fun schedule(context: Context, items: List) { + cancelAll(context) + cancelRepaint(context) + val capped = items + .filter { it.atMillis > System.currentTimeMillis() } + .sortedBy { it.atMillis } + .take(MAX_EVENTS) + persist(context, capped) + register(context, capped) + Log.i(TAG, "scheduled ${capped.size} island frames") + } + + fun cancelAll(context: Context) { + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + for (index in 0 until MAX_EVENTS) { + val pendingIntent = PendingIntent.getBroadcast( + context, + index, + intentFor(context, null), + PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE, + ) ?: continue + alarmManager.cancel(pendingIntent) + pendingIntent.cancel() + } + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .edit().remove(ITEMS_KEY).apply() + } + + /** + * HyperOS gives the floating focus slot to one notification at a time, so + * another app's message takes the island away from a class that is still + * running. Re-posting the same ongoing frame brings it back; this alarm + * repeats that quietly until the frame's own expiry, then stops. + */ + fun scheduleRepaint(context: Context, frameJson: String) { + val frame = IslandFrame.fromJson(frameJson) ?: return + // Only a class is worth holding the slot: a deadline frame would keep + // waking the device for most of a day. + if (frame.kind != "class") return + val expiresAt = frame.expiresAt ?: return + val next = System.currentTimeMillis() + REPAINT_INTERVAL_MS + // The last repaint is one interval before expiry; the expiry itself is + // the dismissal's job (or the notification's own timeout). + if (next >= expiresAt) return + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val pendingIntent = PendingIntent.getBroadcast( + context, + REPAINT_REQUEST_CODE, + intentFor(context, frameJson), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val exact = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + alarmManager.canScheduleExactAlarms() + } else { + true + } + if (exact) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + next, + pendingIntent, + ) + } else { + alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, next, pendingIntent) + } + } + + fun cancelRepaint(context: Context) { + val pendingIntent = PendingIntent.getBroadcast( + context, + REPAINT_REQUEST_CODE, + intentFor(context, null), + PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE, + ) ?: return + (context.getSystemService(Context.ALARM_SERVICE) as AlarmManager).cancel(pendingIntent) + pendingIntent.cancel() + } + + /** Re-register what survived: AlarmManager forgets everything across a reboot. */ + fun restore(context: Context) { + val now = System.currentTimeMillis() + val items = load(context).filter { it.atMillis > now } + if (items.isEmpty()) return + register(context, items) + Log.i(TAG, "restored ${items.size} island frames") + } + + /** + * Runs in the receiver, possibly in a process the alarm just woke: the focus + * grant is a ContentProvider round trip, so a first probe can miss on a cold + * start. Before degrading to a plain notification, probe once more. + */ + fun deliver(context: Context, frameJson: String?, onDone: () -> Unit = {}) { + if (frameJson == null) { + cancelRepaint(context) + dismiss(context) + onDone() + return + } + val frame = IslandFrame.fromJson(frameJson) + if (frame == null || (frame.expiresAt ?: Long.MAX_VALUE) <= System.currentTimeMillis()) { + Log.w(TAG, "unreadable frame; nothing to post") + onDone() + return + } + val probe = IslandCapabilityProbe(context) + val snapshot = probe.snapshot() + if (snapshot.backend == IslandBackend.PLAIN) { + Handler(Looper.getMainLooper()).postDelayed({ + val backend = probe.refresh().backend + publish(context, frame, backend) + scheduleRepaint(context, frameJson) + onDone() + }, RETRY_MS) + return + } + publish(context, frame, snapshot.backend) + scheduleRepaint(context, frameJson) + onDone() + } + + private fun publish( + context: Context, + frame: IslandFrame, + backend: IslandBackend, + ) { + try { + IslandNotificationFactory(context, FocusSequenceStore(context)) + .updateFrame(frame, backend, IslandNotificationFactory.NOTIFICATION_ID) + Log.i(TAG, "posted island frame (${backend.name.lowercase()})") + } catch (error: Exception) { + Log.w(TAG, "posting the island frame failed: ${error.message}") + } + } + + private fun dismiss(context: Context) { + IslandNotificationFactory(context, FocusSequenceStore(context)) + .cancel(IslandNotificationFactory.NOTIFICATION_ID) + } + + private fun register(context: Context, items: List) { + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val exact = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + alarmManager.canScheduleExactAlarms() + } else { + true + } + items.forEachIndexed { index, item -> + val pendingIntent = PendingIntent.getBroadcast( + context, + index, + intentFor(context, item.frameJson), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + if (exact) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + item.atMillis, + pendingIntent, + ) + } else { + // 没有精确闹钟权限时仍尽力送达:晚几分钟也比不出现强。 + alarmManager.setAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + item.atMillis, + pendingIntent, + ) + } + } + } + + private fun persist(context: Context, items: List) { + val array = JSONArray() + items.forEach { item -> + array.put( + JSONObject() + .put("at", item.atMillis) + .put("frame", item.frameJson?.let { JSONObject(it) } ?: JSONObject.NULL), + ) + } + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .edit().putString(ITEMS_KEY, array.toString()).apply() + } + + private fun load(context: Context): List { + val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .getString(ITEMS_KEY, null) ?: return emptyList() + return try { + val array = JSONArray(raw) + val items = mutableListOf() + for (i in 0 until array.length()) { + val entry = array.getJSONObject(i) + val frame = if (entry.isNull("frame")) { + null + } else { + entry.getJSONObject("frame").toString() + } + items.add(Item(entry.getLong("at"), frame)) + } + items + } catch (_: Exception) { + emptyList() + } + } + + private fun intentFor(context: Context, frameJson: String?): Intent = + Intent(context, IslandFrameReceiver::class.java).apply { + action = ACTION + if (frameJson != null) putExtra(EXTRA_FRAME, frameJson) + } + + private const val RETRY_MS = 800L + + /** How often a running class re-asserts its slot after another app takes it. */ + private const val REPAINT_INTERVAL_MS = 5 * 60 * 1000L + + /** Outside the frame range (0 until MAX_EVENTS) so cancelAll never touches it. */ + private const val REPAINT_REQUEST_CODE = 10000 +} + +/** One alarm per precomputed frame; a null extra is the "dismiss" event. */ +class IslandFrameReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != IslandAlarms.ACTION) return + val pending = goAsync() + IslandAlarms.deliver( + context.applicationContext, + intent.getStringExtra(IslandAlarms.EXTRA_FRAME), + ) { runCatching { pending.finish() } } + } +} +/** Recover future cached frames after reboot or an application update. */ +class IslandRestoreReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Intent.ACTION_BOOT_COMPLETED || + intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) { + IslandAlarms.restore(context.applicationContext) + } + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBackend.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBackend.kt new file mode 100644 index 00000000..88825dc9 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBackend.kt @@ -0,0 +1,21 @@ +package club.geekpie.techpie.island + +/** + * The three display tiers for the schedule island, in order of preference. + * + * - [HYPER_ISLAND]: Xiaomi HyperOS focus notification / super-island (V3 template). + * Only floats on whitelisted HyperOS devices with the focus-notification grant. + * - [LIVE_UPDATE]: Android 16 live updates (promoted ongoing), status-bar capsule. + * - [PLAIN]: standard persistent notification, works everywhere. + */ +enum class IslandBackend { HYPER_ISLAND, LIVE_UPDATE, PLAIN } + +object IslandBackends { + + /** Best available tier: island > live update > plain. */ + fun resolve(islandAvailable: Boolean, liveUpdateGranted: Boolean): IslandBackend = when { + islandAvailable -> IslandBackend.HYPER_ISLAND + liveUpdateGranted -> IslandBackend.LIVE_UPDATE + else -> IslandBackend.PLAIN + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBridge.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBridge.kt new file mode 100644 index 00000000..1491b70a --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandBridge.kt @@ -0,0 +1,105 @@ +package club.geekpie.techpie.island + +import android.content.Context +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.json.JSONArray + +/** + * The schedule-island channel: capability probing, frame updates and dismissal. + * + * The activity publishes cached state; native alarms publish later frames + * without a running Flutter engine or foreground service. + */ +class IslandBridge( + private val appContext: Context, + messenger: BinaryMessenger, + private val probe: IslandCapabilityProbe, + private val factory: IslandNotificationFactory, + private val requestPermission: (() -> Boolean)? = null, +) { + private val channel = MethodChannel(messenger, CHANNEL) + + init { + channel.setMethodCallHandler { call, result -> + when (call.method) { + "probe" -> result.success(probe.snapshot().toMap()) + "refreshProbe" -> result.success(probe.refresh().toMap()) + "updateFrame" -> updateFrame(call, result) + "dismiss" -> { + dismiss() + result.success(true) + } + "scheduleFrames" -> scheduleFrames(call, result) + "cancelFrames" -> { + IslandAlarms.cancelAll(appContext) + IslandAlarms.cancelRepaint(appContext) + result.success(true) + } + "requestPermission" -> result.success(requestPermission?.invoke() ?: false) + else -> result.notImplemented() + } + } + } + + private fun dismiss() { + IslandAlarms.cancelRepaint(appContext) + factory.cancel(IslandNotificationFactory.NOTIFICATION_ID) + } + + /** Precomputed frames from the Dart side, posted by AlarmManager later. */ + private fun scheduleFrames(call: MethodCall, result: MethodChannel.Result) { + val raw = call.argument("frames") ?: "[]" + val items = mutableListOf() + try { + val array = JSONArray(raw) + for (i in 0 until array.length()) { + val entry = array.getJSONObject(i) + val frame = if (entry.isNull("frame")) { + null + } else { + entry.getJSONObject("frame").toString() + } + items.add(IslandAlarms.Item(entry.getLong("at"), frame)) + } + } catch (error: Exception) { + result.error("BAD_FRAMES", error.message, null) + return + } + IslandAlarms.schedule(appContext, items) + result.success(items.size) + } + + fun dispose() { + channel.setMethodCallHandler(null) + } + + private fun updateFrame(call: MethodCall, result: MethodChannel.Result) { + val frameJson = call.argument("frame") + val frame = frameJson?.let { IslandFrame.fromJson(it) } + if (frame == null) { + result.error("BAD_FRAME", "missing or unreadable frame json", null) + return + } + // The caller may force a tier for testing; by default the device + // decides, so a phone without the focus grant still gets the capsule + // or a plain ongoing notification instead of nothing. + val backend = call.argument("backend") + ?.let { name -> runCatching { IslandBackend.valueOf(name.uppercase()) }.getOrNull() } + ?: probe.snapshot().backend + try { + factory.updateFrame(frame, backend, IslandNotificationFactory.NOTIFICATION_ID) + // Keep a running class on the island even when the focus slot is + // taken by another app's notification between frames. + IslandAlarms.scheduleRepaint(appContext, frameJson) + result.success(backend.name.lowercase()) + } catch (e: Exception) { + result.error("ISLAND_ERROR", e.message, null) + } + } + + companion object { + const val CHANNEL = "techpie/island" + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandCapabilityProbe.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandCapabilityProbe.kt new file mode 100644 index 00000000..f48017ca --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandCapabilityProbe.kt @@ -0,0 +1,87 @@ +package club.geekpie.techpie.island + +import android.app.NotificationManager +import android.content.Context +import android.os.Build +import android.os.SystemClock +import androidx.core.app.NotificationManagerCompat +import com.xzakota.hyper.notification.focus.util.FocusUtils + +/** + * Reads what this device can show the island as and resolves the active tier. + * + * The focus-permission check is a ContentProvider round trip, so it is cached; + * [refresh] drops the cache after the user returns from system settings. + */ +class IslandCapabilityProbe(context: Context) { + private val appContext = context.applicationContext + private val manager = appContext.getSystemService(NotificationManager::class.java) + + data class Snapshot( + /** The tier that will actually be used. */ + val backend: IslandBackend, + val postNotifications: Boolean, + val liveUpdateAvailable: Boolean, + val liveUpdateGranted: Boolean, + val islandLikely: Boolean, + val islandGranted: Boolean, + ) { + fun toMap(): Map = mapOf( + "backend" to backend.name.lowercase(), + "postNotifications" to postNotifications, + "liveUpdateAvailable" to liveUpdateAvailable, + "liveUpdateGranted" to liveUpdateGranted, + "islandLikely" to islandLikely, + "islandGranted" to islandGranted, + ) + } + + // Protocol version and the island feature flag are read-only system state. + private val islandLikely: Boolean by lazy { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1 && runCatching { + FocusUtils.getFocusProtocolVersion(appContext) >= 3 || FocusUtils.isSupportIsland() + }.getOrDefault(false) + } + + @Volatile + private var islandGrantCache: Pair? = null + + fun snapshot(): Snapshot { + val likely = islandLikely + val granted = likely && islandGranted() + return Snapshot( + backend = IslandBackends.resolve(granted, liveUpdateGranted()), + postNotifications = NotificationManagerCompat.from(appContext).areNotificationsEnabled(), + liveUpdateAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA, + liveUpdateGranted = liveUpdateGranted(), + islandLikely = likely, + islandGranted = granted, + ) + } + + /** Drop the focus-permission cache (user may have just toggled it in settings). */ + fun refresh(): Snapshot { + islandGrantCache = null + return snapshot() + } + + private fun islandGranted(): Boolean { + val now = SystemClock.elapsedRealtime() + islandGrantCache?.let { (at, value) -> if (now - at < ISLAND_GRANT_CACHE_MS) return value } + val granted = runCatching { FocusUtils.hasFocusPermission(appContext) }.getOrDefault(false) + islandGrantCache = now to granted + return granted + } + + private fun liveUpdateGranted(): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return false + // One UI does not expose the system switch; the query is always false + // there but requests still work. + if (Build.MANUFACTURER.equals("samsung", ignoreCase = true)) return true + return runCatching { manager.canPostPromotedNotifications() }.getOrDefault(false) + } + + private companion object { + const val ISLAND_GRANT_CACHE_MS = 30_000L + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandFrame.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandFrame.kt new file mode 100644 index 00000000..1833a582 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandFrame.kt @@ -0,0 +1,53 @@ +package club.geekpie.techpie.island + +import org.json.JSONObject + +/** + * One frame of island content, computed on the Dart side from the cached + * schedule and assignments. + * + * @param kind "class" or "deadline" + * @param title course name / assignment title + * @param subTitle short line under the icon: time range / due date + * @param statusLine capsule status, e.g. 上课中 / 10分钟后开始 / 今天截止 + * @param detail right-column body: classroom / owning course for a deadline + * @param expiresAt epoch millis after which the frame is no longer true: the + * end of a running class, the start of an upcoming one, a deadline's due + * time. Posted as the notification's timeout so a dismissal alarm the system + * never delivered cannot leave a finished class on screen. + */ +data class IslandFrame( + val kind: String, + val title: String, + val subTitle: String?, + val statusLine: String, + val detail: String?, + val expiresAt: Long?, +) { + /** Full notification text line. */ + val text: String? + get() = listOfNotNull(subTitle, detail).joinToString(" · ").takeIf { it.isNotBlank() } + + companion object { + fun fromJson(json: String): IslandFrame? { + val o = try { + JSONObject(json) + } catch (e: Exception) { + return null + } + val title = o.optString("title") + if (title.isBlank()) return null + return IslandFrame( + kind = o.optString("kind", "class"), + title = title, + subTitle = optText(o, "subTitle"), + statusLine = o.optString("statusLine"), + detail = optText(o, "detail"), + expiresAt = o.optLong("expiresAt", 0L).takeIf { it > 0L }, + ) + } + + private fun optText(o: JSONObject, key: String): String? = + if (o.isNull(key)) null else o.optString(key).takeIf { it.isNotBlank() } + } +} diff --git a/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandNotificationFactory.kt b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandNotificationFactory.kt new file mode 100644 index 00000000..e1f25ab7 --- /dev/null +++ b/android/app/src/main/kotlin/club/geekpie/techpie/island/IslandNotificationFactory.kt @@ -0,0 +1,215 @@ +package club.geekpie.techpie.island + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Icon +import android.os.Build +import android.os.Bundle +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import club.geekpie.techpie.MainActivity +import club.geekpie.techpie.R +import com.xzakota.hyper.notification.focus.FocusNotification +import com.xzakota.hyper.notification.island.model.TextInfo + +/** + * Builds the island notification for a frame, per active backend. + * + * - PLAIN: silent ongoing notification with title/text/status line + * - LIVE_UPDATE: same plus promoted-ongoing request and a short capsule text + * - HYPER_ISLAND: V3 focus-notification template on a HIGH-importance silent + * channel (the system will not float low-importance notifications to the island) + */ +class IslandNotificationFactory( + context: Context, + private val sequenceStore: FocusSequenceStore, +) { + private val appContext = context.applicationContext + private val manager = appContext.getSystemService(NotificationManager::class.java) + + @Volatile + private var channelsReady = false + + /** Frames refresh at most once a minute; decoding the icon every time is wasteful. */ + private val appIcon: Icon by lazy { + val drawable = appContext.applicationInfo.loadIcon(appContext.packageManager) + if (drawable is BitmapDrawable) { + Icon.createWithBitmap(drawable.bitmap) + } else { + Icon.createWithResource(appContext, appContext.applicationInfo.icon) + } + } + + fun ensureChannels() { + if (channelsReady || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_ID, + appContext.getString(R.string.island_channel_name), + // HIGH so the island can float; sound and vibration are off on the + // channel itself because setSilent() on the notification would suppress floating. + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = appContext.getString(R.string.island_channel_desc) + setShowBadge(false) + setSound(null, null) + enableVibration(false) + }, + ) + channelsReady = true + } + + /** + * Publish [frame] as [backend]. A user who turned notifications off has no + * channel to post on, so the frame is dropped rather than thrown back at + * the caller — the island has nothing to show in that state anyway. + */ + fun updateFrame(frame: IslandFrame, backend: IslandBackend, notifyId: Int) { + if (!NotificationManagerCompat.from(appContext).areNotificationsEnabled()) return + runCatching { manager.notify(notifyId, build(frame, backend, notifyId)) } + } + + fun cancel(notifyId: Int) { + manager.cancel(notifyId) + } + + /** + * @param firstFloat let the island float up once on the first frame after activation; + * later refreshes must not re-interrupt. + */ + fun build( + frame: IslandFrame, + backend: IslandBackend, + notifyId: Int, + firstFloat: Boolean = false, + ): Notification { + ensureChannels() + val builder = NotificationCompat.Builder(appContext, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_island_notification) + .setContentTitle(frame.title) + .setContentText(frame.text?.takeIf { it.isNotBlank() }) + .setContentIntent(contentIntent(notifyId)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + + // Let the notification retire itself at the moment its content stops + // being true. The dismissal alarm is the primary path; this is what + // covers a system that dropped or delayed it. + frame.expiresAt?.let { at -> + val left = at - System.currentTimeMillis() + if (left > 0L) builder.setTimeoutAfter(left) + } + + if (backend == IslandBackend.HYPER_ISLAND && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { + runCatching { islandExtras(frame, notifyId, firstFloat) } + .onSuccess(builder::addExtras) + } else { + builder.setSilent(true) + if (backend == IslandBackend.LIVE_UPDATE) { + // Below Android 16 the request is ignored; only the query needs a guard. + val canPromote = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { + runCatching { manager.canPostPromotedNotifications() }.getOrDefault(true) + } else { + true + } + builder.setRequestPromotedOngoing(canPromote) + frame.statusLine.takeIf { it.isNotBlank() }?.let(builder::setShortCriticalText) + } + } + return builder.build() + } + + /** + * V3 island template: big-island left column = app icon + course name / time, + * right column = status line / detail; small island = app icon. + */ + private fun islandExtras(frame: IslandFrame, notifyId: Int, firstFloat: Boolean): Bundle { + val headline = frame.title.take(40) + val body = frame.text.orEmpty().take(80) + val status = frame.statusLine.ifBlank { frame.title } + return FocusNotification.buildV3 { + business = BUSINESS_PROGRESS + this.notifyId = notifyId.toString() + updatable = true + isShowNotification = true + reopen = "reopen" + timeout = ONGOING_TIMEOUT_MIN + sequence = sequenceStore.next(notifyId) + aodTitle = status.take(20) + ticker = "$headline $status".trim().take(40) + val appPic = createPicture(PIC_APP, appIcon) + tickerPic = appPic + filterWhenNoPermission = false + showSmallIcon = false + enableFloat = false + islandFirstFloat = firstFloat + hideDeco = false + if (firstFloat) outEffectSrc = "glow" + + chatInfo { + title = headline + content = body + } + island { + islandProperty = 1 + islandTimeout = ONGOING_TIMEOUT_MIN * 60 + dismissIsland = false + islandOrder = false + bigIslandArea { + imageTextInfoLeft { + type = 1 + picInfo { + type = 1 + pic = appPic + } + textInfo { + title = frame.title.take(16) + content = (frame.subTitle ?: "").take(12) + showHighlightColor = true + } + } + textInfo = TextInfo().apply { + title = status.take(18) + content = (frame.detail ?: body).take(32) + showHighlightColor = true + narrowFont = true + } + } + smallIslandArea { + picInfo { + type = 1 + pic = appPic + } + } + } + } + } + + private fun contentIntent(notifyId: Int): PendingIntent { + val intent = Intent(appContext, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP + } + return PendingIntent.getActivity( + appContext, + notifyId, + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + } + + companion object { + const val CHANNEL_ID = "schedule_island" + const val NOTIFICATION_ID = 0x15DA // island + + private const val ONGOING_TIMEOUT_MIN = 24 * 60 + private const val PIC_APP = "miui.focus.pic_progress_app" + private const val BUSINESS_PROGRESS = "download_progress" + } +} diff --git a/android/app/src/main/res/drawable/ic_island_notification.xml b/android/app/src/main/res/drawable/ic_island_notification.xml new file mode 100644 index 00000000..9115be28 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_island_notification.xml @@ -0,0 +1,12 @@ + + + + diff --git a/android/app/src/main/res/values-ja/island_strings.xml b/android/app/src/main/res/values-ja/island_strings.xml new file mode 100644 index 00000000..a020670c --- /dev/null +++ b/android/app/src/main/res/values-ja/island_strings.xml @@ -0,0 +1,5 @@ + + + ライブ時間割 + 授業と課題の締め切りをリアルタイム通知に表示します + diff --git a/android/app/src/main/res/values-zh/island_strings.xml b/android/app/src/main/res/values-zh/island_strings.xml new file mode 100644 index 00000000..d4cd97fb --- /dev/null +++ b/android/app/src/main/res/values-zh/island_strings.xml @@ -0,0 +1,5 @@ + + + 课表动态 + 在灵动岛/实时动态中显示当前课程与日程状态 + diff --git a/android/app/src/main/res/values/island_strings.xml b/android/app/src/main/res/values/island_strings.xml new file mode 100644 index 00000000..1c6eaadf --- /dev/null +++ b/android/app/src/main/res/values/island_strings.xml @@ -0,0 +1,5 @@ + + + Live Schedule + Shows your current class and schedule status on the notification island + diff --git a/docs/android-island.md b/docs/android-island.md new file mode 100644 index 00000000..3e698965 --- /dev/null +++ b/docs/android-island.md @@ -0,0 +1,7 @@ +# Cached schedule and deadline notifications + +This optional Android feature displays the current class, next class within 90 minutes or a pending deadline within 24 hours. It chooses HyperOS focus notifications when granted, Android 16 promoted ongoing notifications when available, and ordinary persistent notifications otherwise. Native alarms carry cached frames for three days, restore future events after reboot/update and expire stale content without a running Flutter process. + +The switch defaults off. The feature requests notification permission, but does not add a foreground service, background network polling, spending alerts or wearable integrations. System scheduling restrictions can delay native updates. Cached alarm content is removed when the feature is disabled; source changes immediately replace the displayed state. + +Upstream version, release workflows, app ID, signing and Android minimum SDK remain unchanged. HyperOS SDK calls are guarded at API 27; API 24–26 use only the ordinary notification path. The library's minSdk declaration is narrowly overridden for that guarded path. Android 16 promoted ongoing APIs are supplied by AndroidX Core 1.18.0. Real HyperOS authorization, notification placement and older-device behavior require device acceptance. diff --git a/lib/main.dart b/lib/main.dart index f87e697c..75c5eb6b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -21,6 +21,7 @@ import 'services/ecard_widget_service.dart'; import 'services/egate_app_service.dart'; import 'services/http_client.dart'; import 'services/ids/ids_client.dart'; +import 'services/island_service.dart'; import 'services/oa_gym_service.dart'; import 'services/schedule_service.dart'; import 'services/service_provider.dart'; @@ -104,6 +105,7 @@ Future _realMain(SharedPreferences prefs) async { thirdPartyAuthService, scheduleService, ); + final islandService = IslandService(storageService, scheduleService, assignmentService); final deadlineWidgetService = DeadlineWidgetService(assignmentService); final syncService = SyncService( authService, @@ -191,6 +193,7 @@ Future _realMain(SharedPreferences prefs) async { ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, deadlineWidgetService: deadlineWidgetService, + islandService: islandService, ), ); @@ -201,6 +204,7 @@ Future _realMain(SharedPreferences prefs) async { deadlineWidgetService.initialize(); } + islandService.start(); oaGymService.startProfileSync(); unawaited(campusCardService.refreshAccount()); @@ -325,6 +329,7 @@ class TechPieApp extends StatefulWidget { final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; final DeadlineWidgetService? deadlineWidgetService; + final IslandService? islandService; const TechPieApp({ super.key, @@ -344,6 +349,7 @@ class TechPieApp extends StatefulWidget { required this.ecardBindService, this.ecardWidgetService, this.deadlineWidgetService, + this.islandService, }); @override @@ -388,6 +394,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { WidgetsBinding.instance.removeObserver(this); widget.ecardWidgetService?.clearOpenPayHandler(); widget.deadlineWidgetService?.dispose(); + widget.islandService?.dispose(); widget.campusCardService.dispose(); super.dispose(); } @@ -398,6 +405,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { // Coming back is a cheap moment to top the SSO token up, and it is // guarded: a token with time left is left alone. unawaited(widget.authService.tryRenewSession()); + unawaited(widget.islandService?.refreshNow(force: true)); unawaited(_checkForUpdatesQuietly()); } } @@ -484,6 +492,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + islandService: widget.islandService, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, diff --git a/lib/models/island_frame.dart b/lib/models/island_frame.dart new file mode 100644 index 00000000..7ab2e08b --- /dev/null +++ b/lib/models/island_frame.dart @@ -0,0 +1,201 @@ +import 'assignment.dart'; +import 'course.dart'; + +/// One frame of schedule-island content, rendered by the platform. +class IslandFrame { + const IslandFrame({ + required this.kind, + required this.title, + required this.statusLine, + this.subTitle, + this.detail, + this.expiresAt, + }); + + /// `class` or `deadline` — what the island is about. + final String kind; + final String title; + + /// The capsule line: 上课中 / 20 分钟后开始 / 今天截止 23:59. + final String statusLine; + final String? subTitle; + final String? detail; + + /// When this content stops being true: the end of a running class, the start + /// of an upcoming one, or a deadline's due time. The platform posts the frame + /// with this expiry, so a dismissal alarm the system never delivered cannot + /// leave a finished class on screen. + final DateTime? expiresAt; + + Map toJson() => { + 'kind': kind, + 'title': title, + 'statusLine': statusLine, + 'subTitle': subTitle, + 'detail': detail, + 'expiresAt': expiresAt?.millisecondsSinceEpoch, + }; + + @override + String toString() => 'IslandFrame($kind, $title, $statusLine)'; +} + +/// A class is worth the island from this long before it starts. +const nextClassLead = Duration(minutes: 90); + +/// A deadline is worth the island until this long before it is due. +const deadlineLead = Duration(hours: 24); + +/// What the island should say at [now], or null when nothing deserves it — a +/// caller dismisses on null rather than leaving a stale frame up. +/// +/// [dayCourses] is one day's sessions in period order and [upcomingDeadlines] +/// is already filtered to what the user still owes; both come from the cached +/// schedule and assignment state, never from a live fetch. +IslandFrame? buildIslandFrame({ + required List dayCourses, + required List upcomingDeadlines, + required DateTime now, +}) { + final minutes = now.hour * 60 + now.minute; + Course? running; + Course? upcoming; + for (final course in dayCourses) { + final start = parseClockMinutes(course.startTime); + final end = parseClockMinutes(course.endTime); + if (start == null || end == null) continue; + if (start <= minutes && minutes < end) { + running = course; + break; + } + if (start > minutes) { + upcoming = course; + break; + } + } + + if (running != null) { + return IslandFrame( + kind: 'class', + title: running.name, + subTitle: '${running.startTime}–${running.endTime}', + statusLine: '上课中', + detail: running.location, + expiresAt: _clockOn(now, parseClockMinutes(running.endTime) ?? 0), + ); + } + + final gap = upcoming == null + ? null + : Duration( + minutes: (parseClockMinutes(upcoming.startTime) ?? 0) - minutes, + ); + final deadline = _nearestDeadline(upcomingDeadlines, now); + + if (gap != null && gap <= nextClassLead) { + return IslandFrame( + kind: 'class', + title: upcoming!.name, + subTitle: '${upcoming.startTime}–${upcoming.endTime}', + statusLine: gap <= const Duration(hours: 1) + ? '${gap.inMinutes} 分钟后开始' + : '${upcoming.startTime} 开始', + detail: upcoming.location, + expiresAt: _clockOn(now, parseClockMinutes(upcoming.startTime) ?? 0), + ); + } + + if (deadline != null) { + return IslandFrame( + kind: 'deadline', + title: deadline.title, + statusLine: _deadlineStatus(deadline.due, now), + detail: '${deadline.course} · ${deadline.kind.label}', + expiresAt: deadline.due, + ); + } + + // Nothing imminent: a class hours away or a deadline tomorrow is the home + // page's business, not the status bar's. + return null; +} + +Assignment? _nearestDeadline( + List deadlines, + DateTime now, { + Duration window = deadlineLead, +}) { + Assignment? best; + for (final assignment in deadlines) { + final left = assignment.due.difference(now); + if (left <= Duration.zero || left > window) continue; + if (best == null || assignment.due.isBefore(best.due)) best = assignment; + } + return best; +} + +String _deadlineStatus(DateTime due, DateTime now) { + final day = _clock(due); + if (due.year == now.year && due.month == now.month && due.day == now.day) { + return '今天截止 $day'; + } + final tomorrow = DateTime(now.year, now.month, now.day + 1); + if (due.year == tomorrow.year && + due.month == tomorrow.month && + due.day == tomorrow.day) { + return '明天截止 $day'; + } + return '${due.difference(now).inHours} 小时后截止'; +} + +/// [minutes] after midnight on [now]'s date. +DateTime _clockOn(DateTime now, int minutes) => + DateTime(now.year, now.month, now.day, minutes ~/ 60, minutes % 60); + +String _clock(DateTime value) => + '${value.hour.toString().padLeft(2, '0')}:${value.minute.toString().padLeft(2, '0')}'; + +/// Event-driven snapshots for the next three days, including days without a +/// class. Each event is evaluated with the courses for its own calendar date. +Map buildIslandTimeline({ + required List Function(DateTime day) coursesForDay, + required List deadlines, + required DateTime now, +}) { + final horizon = DateTime(now.year, now.month, now.day + 3); + final events = {horizon}; + void add(DateTime value) { + if (value.isAfter(now) && !value.isAfter(horizon)) events.add(value); + } + + for (var offset = 0; offset < 3; offset++) { + final day = DateTime(now.year, now.month, now.day + offset); + add(day); + for (final course in coursesForDay(day)) { + final startMinutes = parseClockMinutes(course.startTime); + final endMinutes = parseClockMinutes(course.endTime); + if (startMinutes == null || endMinutes == null) continue; + final start = _clockOn(day, startMinutes); + add(start.subtract(nextClassLead)); + add(start.subtract(const Duration(minutes: 30))); + add(start.subtract(const Duration(minutes: 10))); + add(start); + add(_clockOn(day, endMinutes)); + } + } + for (final deadline in deadlines) { + add(deadline.due.subtract(deadlineLead)); + add(deadline.due); + } + final ordered = events.toList()..sort(); + return { + for (final at in ordered) + at.millisecondsSinceEpoch: at == horizon + ? null + : buildIslandFrame( + dayCourses: coursesForDay(at), + upcomingDeadlines: deadlines, + now: at, + ), + }; +} diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index dabca46e..44b37fd1 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -11,6 +11,7 @@ import 'package:url_launcher/url_launcher.dart'; import '../models/third_party_account.dart'; import '../services/api_base_url.dart'; import '../services/feedback_service.dart'; +import '../services/island_service.dart'; import '../services/service_provider.dart'; import '../services/sync_service.dart'; import '../services/theme_service.dart'; @@ -54,6 +55,7 @@ class _SettingsPageState extends State { bool _checkingUpdate = false; bool? _isPersonalInfoBlurred; bool _wasVisible = false; + IslandCapability? _islandCapability; /// The stack a settings subpage is pushed onto in a wide window. A field, not /// a local: a GlobalKey rebuilt every frame would drop the stack with it. @@ -74,9 +76,33 @@ class _SettingsPageState extends State { _isPersonalInfoBlurred = ServiceProvider.of(context).storageService.maskPersonalInfo; } + if (isVisible && !_wasVisible) unawaited(_loadIslandCapability()); _wasVisible = isVisible; } + Future _loadIslandCapability() async { + final island = ServiceProvider.of(context).islandService; + if (island == null || !island.supported) return; + final capability = await island.capability(); + if (mounted) setState(() => _islandCapability = capability); + } + + Future _setIslandEnabled(IslandService island, bool value) async { + await island.setEnabled(value); + await _loadIslandCapability(); + } + + String get _islandSubtitle { + final capability = _islandCapability; + if (capability == null) return '显示当前课程、下一节课和即将到期的作业'; + if (!capability.notificationsEnabled) return '请允许 TechPie 发送通知'; + return switch (capability.backend) { + 'hyper_island' => '通过 HyperOS 超级岛显示', + 'live_update' => '通过 Android 实时通知显示', + _ => '通过普通常驻通知显示', + }; + } + void _togglePersonalInfoBlur() { setState(() { _isPersonalInfoBlurred = !(_isPersonalInfoBlurred ?? true); @@ -435,6 +461,15 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), + if (sp.islandService case final island? when island.supported) + _AdaptiveSwitchTile( + usesIosLiquidGlass: useIosChrome, + secondary: const Icon(Icons.notifications_active_outlined), + title: '课程与截止日期通知', + subtitle: _islandSubtitle, + value: storage.islandEnabled, + onChanged: (value) => unawaited(_setIslandEnabled(island, value)), + ), _AdaptiveSwitchTile( key: const ValueKey('settings.mask-personal-info'), usesIosLiquidGlass: useIosChrome, diff --git a/lib/services/island_service.dart b/lib/services/island_service.dart new file mode 100644 index 00000000..97c8c1af --- /dev/null +++ b/lib/services/island_service.dart @@ -0,0 +1,237 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; + +import '../models/assignment.dart'; +import '../models/island_frame.dart'; +import '../utils/platform.dart'; +import '../utils/today_courses.dart'; +import 'assignment_service.dart'; +import 'schedule_service.dart'; +import 'storage_service.dart'; + +/// What the device can show the schedule as, as reported by the platform. +class IslandCapability { + const IslandCapability({ + required this.backend, + required this.notificationsEnabled, + required this.islandGranted, + required this.liveUpdateGranted, + }); + + /// `hyper_island`, `live_update` or `plain`. + final String backend; + final bool notificationsEnabled; + + /// The focus-notification grant is Xiaomi's own approval, so a device can be + /// capable and still not allowed to float. + final bool islandGranted; + final bool liveUpdateGranted; + + static IslandCapability? fromMap(Object? map) { + if (map is! Map) return null; + return IslandCapability( + backend: map['backend'] as String? ?? 'plain', + notificationsEnabled: map['postNotifications'] as bool? ?? false, + islandGranted: map['islandGranted'] as bool? ?? false, + liveUpdateGranted: map['liveUpdateGranted'] as bool? ?? false, + ); + } +} + +/// Keeps the status-bar island on one screen of schedule state. +/// +/// The island is a reflection of what the app already cached: it never hits the +/// network, because the campus session lives here and the widget host has no +/// business holding it. +final class IslandService { + IslandService( + this._storage, + this._schedule, + this._assignments, { + MethodChannel? channel, + }) : _channel = channel ?? const MethodChannel('techpie/island'); + + static const _refreshCooldown = Duration(seconds: 30); + static const _tick = Duration(minutes: 1); + + final StorageService _storage; + final ScheduleService _schedule; + final AssignmentService _assignments; + final MethodChannel _channel; + + Timer? _timer; + Timer? _timelineDebounce; + DateTime? _lastRefresh; + bool _showing = false; + bool _started = false; + + bool get supported => isAndroid(); + + bool get enabled => supported && _storage.islandEnabled; + + Future capability() async { + if (!supported) return null; + try { + final map = await _channel.invokeMethod('probe'); + return IslandCapability.fromMap(map); + } on PlatformException { + return null; + } + } + + /// Turn the island on or off. Enabling asks for the notification permission + /// first, since a denied permission means nothing can be shown at all. + Future setEnabled(bool value) async { + await _storage.setIslandEnabled(value); + if (!value) { + await dismiss(force: true); + await _invokeQuiet('cancelFrames'); + return; + } + await _requestNotificationPermission(); + await refreshNow(force: true); + await scheduleTimeline(); + } + + /// Follow the schedule and deadlines while the app runs; the platform side + /// keeps the last frame on screen once this process is gone. + void start() { + if (!supported || _started) return; + _started = true; + // Whatever the last run left on screen is ours to settle: assume it is up, + // so the first refresh either refreshes it or clears it exactly once. + _showing = enabled; + _schedule.addListener(_onDataChanged); + _assignments.addListener(_onDataChanged); + _timer = Timer.periodic(_tick, (_) => unawaited(refreshNow())); + unawaited(refreshNow(force: true)); + // The platform keeps painting frames once this process is gone. + unawaited(scheduleTimeline()); + } + + void dispose() { + _timer?.cancel(); + _timer = null; + _timelineDebounce?.cancel(); + _timelineDebounce = null; + if (!_started) return; + _started = false; + _schedule.removeListener(_onDataChanged); + _assignments.removeListener(_onDataChanged); + } + + Future refreshNow({bool force = false}) async { + if (!enabled) return; + final last = _lastRefresh; + if (!force && + last != null && + DateTime.now().difference(last) < _refreshCooldown) { + return; + } + _lastRefresh = DateTime.now(); + final now = DateTime.now(); + final frame = buildIslandFrame( + dayCourses: coursesOnDay(_schedule, _assignments, now), + upcomingDeadlines: _openDeadlines(), + now: now, + ); + if (frame == null) { + await dismiss(); + return; + } + await _push(frame); + } + + /// [force] clears even what this run never showed — turning the feature off + /// means a frame left up by an earlier run has to go. + Future dismiss({bool force = false}) async { + if (!supported) return; + if (!_showing && !force) return; + _showing = false; + try { + await _channel.invokeMethod('dismiss'); + } on PlatformException { + // Already gone. + } + } + + List _openDeadlines() => _assignments.visibleAssignments + .where( + (assignment) => + !assignment.submitted && !_assignments.isCompleted(assignment), + ) + .toList(); + + Future _push(IslandFrame frame) async { + try { + await _channel.invokeMethod('updateFrame', { + 'frame': jsonEncode(frame.toJson()), + }); + _showing = true; + } on PlatformException { + // A frame that cannot be shown is dropped, not retried: the next tick + // recomputes from state that is by then current. + } + } + + Future _onDataChanged() async { + await refreshNow(force: true); + // A schedule/assignment load arrives as a burst of changes; rescheduling is + // a full alarm rebuild, so let it settle first. + _timelineDebounce?.cancel(); + _timelineDebounce = Timer( + const Duration(seconds: 2), + () => unawaited(scheduleTimeline()), + ); + } + + /// Precompute the frames for the next days so the platform can post them with + /// AlarmManager while this process is gone. A null frame is a dismissal. + Future scheduleTimeline() async { + if (!supported) return; + if (!enabled) { + await _invokeQuiet('cancelFrames'); + return; + } + final events = buildIslandTimeline( + coursesForDay: (day) => coursesOnDay(_schedule, _assignments, day), + deadlines: _openDeadlines(), + now: DateTime.now(), + ).entries; + final payload = [ + for (final entry in events) + {'at': entry.key, 'frame': entry.value?.toJson()}, + ]; + try { + await _channel.invokeMethod('scheduleFrames', { + 'frames': jsonEncode(payload), + }); + } on PlatformException { + // Best effort: the in-process refresh still runs while the app is open. + } on MissingPluginException { + // Non-Android platforms do not register the channel. + } + } + + Future _invokeQuiet(String method) async { + try { + await _channel.invokeMethod(method); + } on PlatformException { + // Best effort. + } on MissingPluginException { + // Non-Android platforms do not register the channel. + } + } + + Future _requestNotificationPermission() async { + if (!supported) return; + try { + await _channel.invokeMethod('requestPermission'); + } on PlatformException { + // The prompt is advisory; the capability probe still says whether the + // island can be shown. + } + } +} diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..10345e6a 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -7,6 +7,7 @@ import 'debug_logger.dart'; import 'ecard_bind_service.dart'; import 'ecard_widget_service.dart'; import 'egate_app_service.dart'; +import 'island_service.dart'; import 'oa_gym_service.dart'; import 'schedule_service.dart'; import 'storage_service.dart'; @@ -32,6 +33,7 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final IslandService? islandService; const ServiceProvider({ super.key, @@ -50,6 +52,7 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.islandService, required super.child, }); @@ -62,6 +65,7 @@ class ServiceProvider extends InheritedWidget { @override bool updateShouldNotify(ServiceProvider oldWidget) => + islandService != oldWidget.islandService || authService != oldWidget.authService || debugLogger != oldWidget.debugLogger || storageService != oldWidget.storageService || diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 7c4e2bab..284bde3a 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -44,6 +44,9 @@ class StorageService { String? get campusWebOwner => _prefs.getString('campus_web_owner'); Future setCampusWebOwner(String owner) => _prefs.setString('campus_web_owner', owner); + bool get islandEnabled => _prefs.getBool('island_enabled') ?? false; + Future setIslandEnabled(bool value) => _prefs.setBool('island_enabled', value); + // Secure session storage Future saveSession(UserSession session) async { await _secure.write(key: _sessionKey, value: jsonEncode(session.toJson())); diff --git a/lib/utils/today_courses.dart b/lib/utils/today_courses.dart new file mode 100644 index 00000000..0f3af23f --- /dev/null +++ b/lib/utils/today_courses.dart @@ -0,0 +1,54 @@ +import '../models/course.dart'; +import '../models/course_table.dart'; +import '../models/custom_course.dart'; +import '../models/exam_course.dart'; +import '../services/assignment_service.dart'; +import '../services/schedule_service.dart'; + +/// The sessions scheduled for [day], timetable + custom + exam entries merged, +/// in period order. The home page and the schedule island read a day through +/// this so the two cannot disagree about what "today's classes" means. +List coursesOnDay( + ScheduleService schedule, + AssignmentService assignments, + DateTime day, +) { + final table = schedule.courseTable; + final periods = table != null && table.periods.isNotEmpty + ? table.periods.map((period) => period.toPeriod()).toList() + : defaultPeriods; + final begin = schedule.termBegin; + final date = DateTime(day.year, day.month, day.day); + final firstDay = begin == null + ? null + : DateTime(begin.year, begin.month, begin.day); + final week = firstDay == null ? 1 : date.difference(firstDay).inDays ~/ 7 + 1; + if (firstDay != null && + (date.isBefore(firstDay) || week > schedule.totalWeeks)) { + return const []; + } + final withCustom = withCustomCourses( + eamsToDisplayCourses( + table?.courses ?? const [], + week, + timetablePeriods: periods, + ), + schedule.customCourses, + week, + schedule.termBegin, + periods: periods, + ); + final all = withExamCourses( + withCustom, + examsForSemester(assignments.assignments, schedule.selectedSemesterId), + week, + schedule.termBegin, + periods: periods, + ); + return all + .where( + (course) => course.dayOfWeek == day.weekday && course.occursOn(day), + ) + .toList() + ..sort((a, b) => a.gridStart.compareTo(b.gridStart)); +} diff --git a/test/island_frame_test.dart b/test/island_frame_test.dart new file mode 100644 index 00000000..a5510547 --- /dev/null +++ b/test/island_frame_test.dart @@ -0,0 +1,227 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/models/assignment.dart'; +import 'package:techpie/models/course.dart'; +import 'package:techpie/models/island_frame.dart'; + +Course _course({ + required String name, + required String start, + required String end, + String location = 'D202', +}) { + return Course( + name: name, + location: location, + dayOfWeek: 1, + placement: CoursePlacement( + startPeriod: 1, + endPeriod: 2, + gridStart: 0, + gridEnd: 2, + usesCustomTime: true, + startTime: start, + endTime: end, + label: '$start – $end', + ), + ); +} + +Assignment _deadline({ + required String title, + required DateTime due, + String course = '离散数学', +}) { + return Assignment( + id: title, + platform: 'blackboard', + title: title, + course: course, + due: due, + ); +} + +void main() { + test('deadlines have native events even without classes', () { + final now = DateTime(2026, 11, 15, 8); + final due = DateTime(2026, 11, 16, 12); + final timeline = buildIslandTimeline( + coursesForDay: (_) => [], + deadlines: [_deadline(title: 'Report', due: due)], + now: now, + ); + expect( + timeline[due.subtract(deadlineLead).millisecondsSinceEpoch]?.title, + 'Report', + ); + expect(timeline.containsKey(due.millisecondsSinceEpoch), isTrue); + expect(timeline[due.millisecondsSinceEpoch], isNull); + expect(timeline.values.last, isNull); + }); + test( + 'next-day frames are computed from that day rather than the current week', + () { + final now = DateTime(2026, 11, 15, 20); + final timeline = buildIslandTimeline( + coursesForDay: (day) => day.day == 16 + ? [_course(name: 'Monday only', start: '08:15', end: '09:55')] + : [], + deadlines: [], + now: now, + ); + expect( + timeline[DateTime(2026, 11, 16, 8, 15).millisecondsSinceEpoch]?.title, + 'Monday only', + ); + expect( + timeline[DateTime(2026, 11, 16, 9, 55).millisecondsSinceEpoch], + isNull, + ); + }, + ); + final mondayMorning = DateTime(2026, 3, 9, 9, 30); + + test('a running class owns the island', () { + final frame = buildIslandFrame( + dayCourses: [ + _course(name: '高等数学', start: '08:15', end: '09:55'), + _course(name: '线性代数', start: '10:15', end: '11:55'), + ], + upcomingDeadlines: [ + _deadline( + title: '作业 3', + due: mondayMorning.add(const Duration(hours: 2)), + ), + ], + now: mondayMorning, + ); + + expect(frame, isNotNull); + expect(frame!.kind, 'class'); + expect(frame.title, '高等数学'); + expect(frame.statusLine, '上课中'); + expect(frame.subTitle, '08:15–09:55'); + expect(frame.detail, 'D202'); + }); + + test('a class starting soon beats a deadline', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '线性代数', start: '10:15', end: '11:55')], + upcomingDeadlines: [ + _deadline( + title: '作业 3', + due: mondayMorning.add(const Duration(hours: 3)), + ), + ], + now: mondayMorning, + ); + + expect(frame?.kind, 'class'); + expect(frame?.statusLine, '45 分钟后开始'); + }); + + test('a class further out is shown by its start time', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '大学英语', start: '11:00', end: '11:55')], + upcomingDeadlines: const [], + now: mondayMorning, + ); + + expect(frame?.statusLine, '11:00 开始'); + }); + + test('a class more than 90 minutes away leaves the island empty', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '大学英语', start: '14:00', end: '15:00')], + upcomingDeadlines: const [], + now: mondayMorning, + ); + + expect(frame, isNull); + }); + + test('a deadline due today is shown when there is no class', () { + final frame = buildIslandFrame( + dayCourses: const [], + upcomingDeadlines: [ + _deadline(title: '期中论文', due: DateTime(2026, 3, 9, 23, 59)), + ], + now: mondayMorning, + ); + + expect(frame?.kind, 'deadline'); + expect(frame?.statusLine, '今天截止 23:59'); + expect(frame?.detail, '离散数学 · 作业'); + }); + + test('the soonest deadline wins and tomorrow is named', () { + final frame = buildIslandFrame( + dayCourses: const [], + upcomingDeadlines: [ + _deadline(title: '实验报告', due: DateTime(2026, 3, 11, 10, 0)), + _deadline(title: 'Reading quiz', due: DateTime(2026, 3, 10, 8, 0)), + ], + now: mondayMorning, + ); + + expect(frame?.title, 'Reading quiz'); + expect(frame?.statusLine, '明天截止 08:00'); + }); + + test('a deadline beyond the window is not shown', () { + final frame = buildIslandFrame( + dayCourses: const [], + upcomingDeadlines: [_deadline(title: '期末', due: DateTime(2026, 3, 20))], + now: mondayMorning, + ); + + expect(frame, isNull); + }); + + test('the frame serializes the keys the platform reads', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '高等数学', start: '09:00', end: '10:00')], + upcomingDeadlines: const [], + now: mondayMorning, + ); + + expect(frame!.toJson().keys.toList(), [ + 'kind', + 'title', + 'statusLine', + 'subTitle', + 'detail', + 'expiresAt', + ]); + }); + + test('a running class expires when it ends', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '高等数学', start: '08:15', end: '09:55')], + upcomingDeadlines: const [], + now: mondayMorning, + ); + + expect(frame!.expiresAt, DateTime(2026, 3, 9, 9, 55)); + }); + + test('an upcoming class expires when it starts', () { + final frame = buildIslandFrame( + dayCourses: [_course(name: '线性代数', start: '10:15', end: '11:55')], + upcomingDeadlines: const [], + now: mondayMorning, + ); + + expect(frame!.expiresAt, DateTime(2026, 3, 9, 10, 15)); + }); + + test('a deadline frame expires at its due time', () { + final due = DateTime(2026, 3, 9, 23, 59); + final frame = buildIslandFrame( + dayCourses: const [], + upcomingDeadlines: [_deadline(title: '期中论文', due: due)], + now: mondayMorning, + ); + + expect(frame!.expiresAt, due); + }); +}