You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.9 KiB
57 lines
1.9 KiB
package net.aiterp.git.ykonsole2.infrastructure
|
|
|
|
import net.aiterp.git.ykonsole2.application.logging.log
|
|
import net.aiterp.git.ykonsole2.domain.models.*
|
|
import net.aiterp.git.ykonsole2.domain.runtime.*
|
|
import net.aiterp.git.ykonsole2.infrastructure.drivers.abstracts.ReactiveDriver
|
|
import java.time.Instant
|
|
import java.time.temporal.ChronoUnit
|
|
|
|
class WorkoutExporter(
|
|
private val workoutRepo: WorkoutRepository,
|
|
private val stateRepo: WorkoutStateRepository,
|
|
private val deviceRepo: DeviceRepository,
|
|
private val programRepo: ProgramRepository,
|
|
private val exportTarget: ExportTarget,
|
|
) : ReactiveDriver() {
|
|
private var workoutId: String = ""
|
|
|
|
override suspend fun onEvent(event: Event, input: FlowBus<Command>) {
|
|
if (event is Connected) {
|
|
workoutId = workoutRepo.findActive()?.id ?: ""
|
|
}
|
|
|
|
if (event is Disconnected && workoutId != "") {
|
|
export(workoutId)
|
|
workoutId = ""
|
|
}
|
|
}
|
|
|
|
override suspend fun start(input: FlowBus<Command>, output: FlowBus<Event>) {
|
|
log.info("Checking recent workouts...")
|
|
val yesterday = Instant.now().minus(24, ChronoUnit.HOURS)
|
|
for (workout in workoutRepo.fetchAll().filter { it.createdAt > yesterday }) {
|
|
export(workout)
|
|
}
|
|
log.info("Recent workouts verified and exported if needed")
|
|
|
|
super.start(input, output)
|
|
}
|
|
|
|
private suspend inline fun export(workoutId: String) {
|
|
val workout = workoutRepo.findById(workoutId) ?: return
|
|
export(workout)
|
|
}
|
|
|
|
private suspend inline fun export(workout: Workout) {
|
|
if (workout.test) return
|
|
|
|
val states = stateRepo.fetchByWorkoutId(workout.id)
|
|
if (states.isEmpty() || exportTarget.isExported(workout)) return
|
|
|
|
val device = deviceRepo.findById(workout.deviceId)
|
|
val program = workout.programId?.let { programRepo.findById(it) }
|
|
|
|
exportTarget.export(workout, states, device, program)
|
|
}
|
|
}
|