AndroidLiveUpdateService.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.ev_server.services.notifications

import fr.codetics.ev_server.core.Database
import fr.codetics.ev_server.core.lock
import fr.codetics.ev_server.models.entities.AndroidLiveUpdateEntity
import fr.codetics.ev_server.models.entities.PushDeviceEntity
import fr.codetics.ev_server.models.entities.StationKey
import fr.codetics.ev_server.models.entities.TransactionEntity
import fr.codetics.ev_server.models.sessions.ChargingSessionResponse
import fr.codetics.ev_server.ocpp.AuthorizationStatus
import fr.codetics.ev_server.repositories.AndroidLiveUpdateRepository
import fr.codetics.ev_server.repositories.PushDeviceRepository
import fr.codetics.ev_server.repositories.StationRepository
import fr.codetics.ev_server.repositories.TransactionRepository
import fr.codetics.ev_server.services.sessions.ChargingSessionService
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.util.UUID
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

/**
 * The Android counterpart of the iOS Live Activity: while a session runs, the server sends the driver's
 * Android devices a data message every minute; the app shows it as an ongoing notification (a Live Update
 * on Android 16) and refreshes its widget, even when the app is closed. A last message ends it.
 */
@Service
class AndroidLiveUpdateService(
    private val db: Database,
    private val updates: AndroidLiveUpdateRepository,
    private val devices: PushDeviceRepository,
    private val transactions: TransactionRepository,
    private val stations: StationRepository,
    private val sessions: ChargingSessionService,
    private val gateway: FcmPushGateway,
    private val clock: Clock,
) {
    @Scheduled(fixedDelay = 15000)
    fun publish() {
        if (!gateway.configured) return
        val now = Instant.now(clock)
        val android = devices.findAllByPlatform(PushPlatform.ANDROID).groupBy { it.tenantId to it.userId }
        db.atomic {
            updates.deleteAllByCreatedAtBefore(now.minus(LIFETIME))
            if (android.isNotEmpty()) start(android, now)
            updates.findAllByFinishedFalse()
                .mapNotNull { db.lock<AndroidLiveUpdateEntity>(it.id) }
                .filter { !it.finished }
                .forEach { publish(it, android[it.tenantId to it.userId].orEmpty(), now) }
        }
    }

    /** Opens an update for each running session of a user who has an Android device. */
    private fun start(android: Map<Pair<UUID, UUID>, List<PushDeviceEntity>>, now: Instant) {
        android.keys.map { it.first }.toSet().forEach { tenant ->
            transactions.findAllByTenantIdAndStoppedAtIsNull(tenant)
                .filter { it.authorizationStatus == AuthorizationStatus.Accepted }
                .filter { it.userId != null && (tenant to it.userId!!) in android }
                .forEach { transaction ->
                    val id = AndroidLiveUpdateEntity.key(tenant, requireNotNull(transaction.id))
                    if (!updates.existsById(id)) {
                        updates.save(
                            AndroidLiveUpdateEntity(
                                id = id,
                                tenantId = tenant,
                                transactionId = requireNotNull(transaction.id),
                                userId = requireNotNull(transaction.userId),
                                createdAt = now,
                            )
                        )
                    }
                }
        }
    }

    private fun publish(update: AndroidLiveUpdateEntity, targets: List<PushDeviceEntity>, now: Instant) {
        val transaction = transactions.findByTenantIdAndId(update.tenantId, update.transactionId)
        if (transaction == null || transaction.userId != update.userId || targets.isEmpty()) {
            updates.delete(update)
            return
        }
        val finished = transaction.stoppedAt != null
        if (!finished && update.pushedAt?.let { Duration.between(it, now) < INTERVAL } == true) return
        val data = data(transaction, now)
        val results =
            targets.map { device ->
                gateway.sendData(device, data, "session-${update.transactionId}").also {
                    if (it == PushResult.INVALID_DEVICE) devices.delete(device)
                }
            }
        if (results.any { it == PushResult.DELIVERED } || results.none { it == PushResult.RETRY }) {
            update.pushedAt = now
            update.finished = finished
            updates.save(update)
        }
    }

    /** Data keys read by `EvMessagingService` in the Android app. Every FCM data value is a string. */
    fun data(transaction: TransactionEntity, now: Instant): Map<String, String> {
        val session: ChargingSessionResponse = sessions.views(transaction.tenantId, listOf(transaction)).first()
        val station =
            stations.findById(StationKey(transaction.tenantId, transaction.stationId)).map { it.name }.orElse(transaction.stationId)
        val finished = session.stoppedAt != null
        return buildMap {
            put("type", if (finished) TYPE_ENDED else TYPE_UPDATE)
            put("transaction_id", requireNotNull(transaction.id).toString())
            put("station_name", station.take(100))
            put("connector_id", session.connectorId.toString())
            put("started_at", session.startedAt.epochSecond.toString())
            put("duration_seconds", session.durationSeconds.toString())
            put("updated_at", now.epochSecond.toString())
            session.energyKwh?.let { put("energy_kwh", it.toPlainString()) }
            if (!finished) session.currentPowerKw?.let { put("power_kw", it.toPlainString()) }
            session.stateOfCharge?.let { put("state_of_charge", it.toString()) }
            session.price?.let { put("price", it.toPlainString()) }
            session.currency?.let { put("currency", it) }
            session.stopReason?.let { put("stop_reason", it) }
        }
    }

    companion object {
        const val TYPE_UPDATE = "session_live_update"
        const val TYPE_ENDED = "session_live_ended"
        private val INTERVAL: Duration = Duration.ofSeconds(60)
        private val LIFETIME: Duration = Duration.ofHours(24)
    }
}