Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ android {
}
}

dependencies {
implementation("androidx.work:work-runtime-ktx:2.9.1")
testImplementation("junit:junit:4.13.2")
}

tasks.named("preBuild") { dependsOn(prepareEcardWidgetResources) }

flutter {
Expand Down
1 change: 1 addition & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.notification.SpendingNotificationBridge
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
Expand All @@ -25,13 +26,15 @@ class MainActivity : FlutterActivity() {
private val mainHandler = Handler(Looper.getMainLooper())
private var ecardWidgets: EcardWidgetBridge? = null
private var ecardFeedback: EcardFeedback? = null
private var spendingAlerts: SpendingNotificationBridge? = null

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
ecardWidgets = EcardWidgetBridge(this, flutterEngine.dartExecutor.binaryMessenger).also {
it.capture(intent, notifyFlutter = false)
}
ecardFeedback = EcardFeedback(this, flutterEngine.dartExecutor.binaryMessenger)
spendingAlerts = SpendingNotificationBridge(this, flutterEngine.dartExecutor.binaryMessenger, this)

MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
Expand Down Expand Up @@ -82,6 +85,8 @@ class MainActivity : FlutterActivity() {
ecardWidgets = null
ecardFeedback?.dispose()
ecardFeedback = null
spendingAlerts?.dispose()
spendingAlerts = null
super.cleanUpFlutterEngine(flutterEngine)
}

Expand Down Expand Up @@ -193,6 +198,7 @@ class MainActivity : FlutterActivity() {
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 48293) spendingAlerts?.refreshSchedule()

if (requestCode != REQUEST_CALENDAR_PERMISSIONS) return

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package club.geekpie.techpie.notification

/** Pure receipt state. Android persists only opaque keys and timestamps. */
data class SpendingRecord(
val key: String,
val at: Long,
val spending: Boolean,
val title: String = "",
val body: String = "",
)

data class SpendingLedger(
val owner: String? = null,
val generation: Long = 0,
val initialized: Boolean = false,
val floor: Long = Long.MIN_VALUE,
val seen: Map<String, Long> = emptyMap(),
) {
data class Update(val ledger: SpendingLedger, val receipts: List<SpendingRecord>)

fun configure(nextOwner: String?): SpendingLedger =
if (owner == nextOwner) this else SpendingLedger(nextOwner, generation + 1)

fun observe(expectedOwner: String, expectedGeneration: Long,
records: List<SpendingRecord>, now: Long): Update? {
if (owner == null || owner != expectedOwner || generation != expectedGeneration) return null
val page = records.filter { it.at > 0 && it.at <= now + 300_000L }
.distinctBy { it.key }.sortedWith(compareBy({ it.at }, { it.key }))
// An empty first page is still a baseline: the next real payment is news.
val baseline = if (initialized) floor else page.maxOfOrNull { it.at } ?: now
val receipts = if (!initialized) emptyList() else page.filter {
it.spending && it.at >= floor && !seen.containsKey(it.key)
}
val merged = seen.toMutableMap()
page.forEach { merged[it.key] = it.at }
val ordered = merged.entries.sortedWith(compareBy({ it.value }, { it.key }))
val removed = ordered.dropLast(LIMIT)
val nextFloor = maxOf(baseline, removed.maxOfOrNull { it.value + 1 } ?: Long.MIN_VALUE)
return Update(copy(initialized = true, floor = nextFloor,
seen = ordered.takeLast(LIMIT).associate { it.key to it.value }), receipts)
}

companion object { const val LIMIT = 200 }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package club.geekpie.techpie.notification

import android.Manifest
import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import club.geekpie.techpie.MainActivity
import club.geekpie.techpie.R
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject

/** One synchronized native ledger for all Flutter engines in the app process. */
internal object SpendingNotificationState {
private const val PREFS = "techpie_spending_alerts_v1"
private const val TAG = "techpie.spending"
private const val CHANNEL = "spending_alerts"
private const val MAX_NOTIFICATIONS = 3
private val lock = Any()
private val opaqueKey = Regex("^[0-9a-f]{64}$")

private fun read(context: Context): SpendingLedger {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val seen = mutableMapOf<String, Long>()
runCatching {
val json = JSONObject(prefs.getString("seen", "{}") ?: "{}")
for (key in json.keys()) {
if (opaqueKey.matches(key) && seen.size < SpendingLedger.LIMIT) seen[key] = json.getLong(key)
}
}
return SpendingLedger(
owner = prefs.getString("owner", null), generation = prefs.getLong("generation", 0),
initialized = prefs.getBoolean("initialized", false), floor = prefs.getLong("floor", Long.MIN_VALUE),
seen = seen,
)
}

private fun save(context: Context, state: SpendingLedger): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString("owner", state.owner).putLong("generation", state.generation)
.putBoolean("initialized", state.initialized).putLong("floor", state.floor)
.putString("seen", JSONObject(state.seen).toString()).commit()

fun status(context: Context): Map<String, Any?> = synchronized(lock) {
val state = read(context)
mapOf("owner" to state.owner, "generation" to state.generation)
}

fun configure(context: Context, owner: String?): Boolean = synchronized(lock) {
require(owner == null || opaqueKey.matches(owner)) { "Invalid notification scope" }
val before = read(context)
val next = before.configure(owner)
if (before != next) {
if (!save(context, next)) return@synchronized false
SpendingRefreshScheduler.cancel(context)
val manager = context.getSystemService(NotificationManager::class.java)
manager.activeNotifications.filter { it.tag == TAG }.forEach { manager.cancel(TAG, it.id) }
}
updateSchedule(context, next)
true
}

fun refreshSchedule(context: Context) = synchronized(lock) { updateSchedule(context, read(context)) }

private fun updateSchedule(context: Context, state: SpendingLedger) {
if (state.owner != null && NotificationManagerCompat.from(context).areNotificationsEnabled()) {
SpendingRefreshScheduler.schedule(context)
} else {
SpendingRefreshScheduler.cancel(context)
}
}

fun observe(context: Context, owner: String, generation: Long, records: List<SpendingRecord>): Boolean = synchronized(lock) {
val before = read(context)
val update = before.observe(owner, generation, records, System.currentTimeMillis())
?: return@synchronized false
// Persist before notifying: a concurrent engine cannot announce the same batch.
if (!save(context, update.ledger)) return@synchronized false
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return@synchronized true
ensureChannel(context)
val shown = update.receipts.take(MAX_NOTIFICATIONS)
val folded = update.receipts.size - shown.size
shown.forEachIndexed { index, record ->
val id = (owner + record.key).hashCode()
val open = PendingIntent.getActivity(context, id,
Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val tail = if (index == shown.lastIndex && folded > 0) " · 另有 $folded 笔" else ""
val notification = NotificationCompat.Builder(context, CHANNEL)
.setSmallIcon(R.drawable.ic_spending_notification)
.setContentTitle(record.title).setContentText(record.body + tail)
.setStyle(NotificationCompat.BigTextStyle().bigText(record.body + tail))
.setContentIntent(open).setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setGroup(TAG).setSilent(index > 0).build()
try { NotificationManagerCompat.from(context).notify(TAG, id, notification) }
catch (_: SecurityException) { /* Permission can be revoked between the check and post. */ }
}
true
}

private fun ensureChannel(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, context.getString(R.string.spending_channel_name),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = context.getString(R.string.spending_channel_desc)
setShowBadge(false)
lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
})
}
}

class SpendingNotificationBridge(context: Context, messenger: BinaryMessenger,
private val activity: Activity? = null) {
private val appContext = context.applicationContext
private val channel = MethodChannel(messenger, "techpie/spending_alerts")
init {
channel.setMethodCallHandler { call, result ->
try {
when (call.method) {
"configure" -> result.success(SpendingNotificationState.configure(appContext, call.argument<String>("owner")))
"status" -> result.success(SpendingNotificationState.status(appContext))
"observe" -> result.success(observe(call))
"requestPermission" -> result.success(requestPermission())
else -> result.notImplemented()
}
} catch (_: Exception) {
result.error("SPENDING_NOTIFICATION_FAILED", "通知暂不可用", null)
}
}
}

private fun observe(call: MethodCall): Boolean {
val owner = call.argument<String>("owner") ?: return false
val generation = call.argument<Number>("generation")?.toLong() ?: return false
val raw = call.argument<List<Map<String, Any?>>>("records") ?: return false
val records = raw.take(50).mapNotNull { item ->
val key = (item["key"] as? String)?.takeIf { Regex("^[0-9a-f]{64}$").matches(it) } ?: return@mapNotNull null
val at = (item["at"] as? Number)?.toLong() ?: return@mapNotNull null
SpendingRecord(key, at, item["spending"] == true,
(item["title"] as? String).orEmpty().take(80), (item["body"] as? String).orEmpty().take(500))
}
return SpendingNotificationState.observe(appContext, owner, generation, records)
}

private fun requestPermission(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true
val granted = ContextCompat.checkSelfPermission(appContext, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
if (!granted && activity != null) ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.POST_NOTIFICATIONS), 48293)
return granted
}

fun refreshSchedule() = SpendingNotificationState.refreshSchedule(appContext)

fun dispose() = channel.setMethodCallHandler(null)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package club.geekpie.techpie.notification

import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.core.app.NotificationManagerCompat
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean

internal object SpendingRefreshScheduler {
private const val NAME = "techpie-spending-refresh"
fun schedule(context: Context) {
val request = PeriodicWorkRequestBuilder<SpendingRefreshWorker>(15, TimeUnit.MINUTES)
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.KEEP, request)
}
fun cancel(context: Context) { WorkManager.getInstance(context).cancelUniqueWork(NAME) }
}

/** All engine/channel operations are on main; only the bounded wait is on Worker. */
class SpendingRefreshWorker(appContext: Context, params: WorkerParameters) : Worker(appContext, params) {
private val main = Handler(Looper.getMainLooper())
private val active = AtomicBoolean(true)
private val finished = CountDownLatch(1)
private val success = AtomicBoolean(false)
// The fields below are owned exclusively by the main thread.
private var engine: FlutterEngine? = null
private var bridge: SpendingNotificationBridge? = null
private var completion: MethodChannel? = null

override fun doWork(): Result {
main.post {
if (!active.get() || isStopped) { finished.countDown(); return@post }
if (SpendingNotificationState.status(applicationContext)["owner"] == null ||
!NotificationManagerCompat.from(applicationContext).areNotificationsEnabled()) {
success.set(true); finished.countDown(); return@post
}
try {
val loader = FlutterInjector.instance().flutterLoader()
loader.startInitialization(applicationContext)
loader.ensureInitializationComplete(applicationContext, null)
val running = FlutterEngine(applicationContext)
engine = running
val messenger = running.dartExecutor.binaryMessenger
bridge = SpendingNotificationBridge(applicationContext, messenger)
completion = MethodChannel(messenger, "techpie/spending_worker").also { channel ->
channel.setMethodCallHandler { call, result ->
if (call.method == "done") {
success.set(call.argument<Boolean>("success") == true)
result.success(true)
finished.countDown()
} else result.notImplemented()
}
}
running.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint(loader.findAppBundlePath(), "spendingBackgroundRefresh"))
} catch (_: Exception) { finished.countDown() }
}
try { finished.await(60, TimeUnit.SECONDS) }
catch (_: InterruptedException) { Thread.currentThread().interrupt() }
finally { active.set(false); main.post { cleanup() } }
return if (success.get() || runAttemptCount >= 2) Result.success() else Result.retry()
}

override fun onStopped() {
active.set(false)
finished.countDown()
main.post { cleanup() }
super.onStopped()
}

private fun cleanup() {
completion?.setMethodCallHandler(null)
completion = null
bridge?.dispose()
bridge = null
engine?.destroy()
engine = null
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M21,7.5L21,6c0,-1.1 -0.9,-2 -2,-2L5,4C3.9,4 3,4.9 3,6v1.5h18zM3,9.5v6.5c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2L23,9.5L3,9.5zM13,15.5h-2L11,13.5L9,13.5v-2h2L11,9.5h2v2h2v2h-2z" />
</vector>
5 changes: 5 additions & 0 deletions android/app/src/main/res/values-ja/alert_strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spending_channel_name">利用通知</string>
<string name="spending_channel_desc">アプリが利用明細で確認した学生証の支払いを通知します</string>
</resources>
5 changes: 5 additions & 0 deletions android/app/src/main/res/values-zh/alert_strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spending_channel_name">消费提醒</string>
<string name="spending_channel_desc">报告应用刚从账单里读到的校园卡消费</string>
</resources>
5 changes: 5 additions & 0 deletions android/app/src/main/res/values/alert_strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spending_channel_name">Spending alerts</string>
<string name="spending_channel_desc">Reports campus card payments the app has just read from the ledger</string>
</resources>
Loading
Loading