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.
LeCountdown/LeCountdown/Conductor.swift

555 lines
19 KiB

//
// AppEnvironment.swift
// LeCountdown
//
// Created by Laurent Morvillier on 31/01/2023.
//
import Foundation
import BackgroundTasks
import SwiftUI
import Intents
import AudioToolbox
import ActivityKit
import AVFoundation
enum BGTaskIdentifier : String {
case refresh = "com.staxriver.lecountdown.refresh"
}
fileprivate enum Const: String {
case confirmationSound = "ESM_Ambient_Game_Menu_Soft_Wood_Confirm_1_Notification_Button_Settings_UI.wav"
case cancellationSound = "MRKRSTPHR_synth_one_shot_bleep_G.wav"
}
enum CountdownState {
case inprogress
case paused
case finished
case cancelled
}
class Conductor: ObservableObject {
static let maestro: Conductor = Conductor()
@ObservedObject var soundPlayer: SoundPlayer = SoundPlayer()
fileprivate var _delayedSoundPlayers: [TimerID : DelaySoundPlayer] = [:]
fileprivate var beats: Timer? = nil
@UserDefault(PreferenceKey.countdowns.rawValue, defaultValue: [:]) static var savedCountdowns: [String : DateInterval]
@UserDefault(PreferenceKey.pausedCountdowns.rawValue, defaultValue: [:]) static var savedPausedCountdowns: [String : TimeInterval]
@UserDefault(PreferenceKey.stopwatches.rawValue, defaultValue: [:]) static var savedStopwatches: [String : LiveStopWatch]
@Published private (set) var liveTimers: [LiveTimer] = []
@Published var memoryWarningReceived: Bool = false
init() {
self.currentCountdowns = Conductor.savedCountdowns
self.currentStopwatches = Conductor.savedStopwatches
self.pausedCountdowns = Conductor.savedPausedCountdowns
self.beats = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { _ in
self._cleanupCountdowns()
})
}
@Published var cancelledCountdowns: [String] = []
@Published var currentCountdowns: [String : DateInterval] = [:] {
didSet {
Conductor.savedCountdowns = currentCountdowns
// Logger.log("**** currentCountdowns didSet, count = \(currentCountdowns.count)")
withAnimation {
self._buildLiveTimers()
}
}
}
@Published var pausedCountdowns: [String : TimeInterval] = [:] {
didSet {
Conductor.savedPausedCountdowns = pausedCountdowns
withAnimation {
self._buildLiveTimers()
}
}
}
@Published var currentStopwatches: [String : LiveStopWatch] = [:] {
didSet {
Conductor.savedStopwatches = currentStopwatches
withAnimation {
self._buildLiveTimers()
}
}
}
func removeLiveTimer(id: TimerID) {
// Logger.log("removeLiveTimer")
self.liveTimers.removeAll(where: { $0.id == id })
self.cancelledCountdowns.removeAll(where: { $0 == id })
self.pausedCountdowns.removeValue(forKey: id)
self.currentStopwatches.removeValue(forKey: id)
if let soundPlayer = self._delayedSoundPlayers[id] {
FileLogger.log("Stop sound player: \(self._timerName(id))")
soundPlayer.stop()
}
}
fileprivate func _cleanupLiveTimers() {
self.liveTimers.removeAll()
}
fileprivate func _buildLiveTimers() {
let liveCountdowns = self.currentCountdowns.map {
return LiveTimer(id: $0, date: $1.end)
}
// add countdown if not present
for liveCountdown in liveCountdowns {
if let index = self.liveTimers.firstIndex(where: { $0.id == liveCountdown.id }) {
self.liveTimers.remove(at: index)
self.liveTimers.insert(liveCountdown, at: index)
} else {
self.liveTimers.append(liveCountdown)
}
}
let liveStopwatches: [LiveTimer] = self.currentStopwatches.map {
return LiveTimer(id: $0, date: $1.start, endDate: $1.end)
}
for liveStopwatch in liveStopwatches {
if let index = self.liveTimers.firstIndex(where: { $0.id == liveStopwatch.id }) {
self.liveTimers.remove(at: index)
self.liveTimers.insert(liveStopwatch, at: index)
} else {
self.liveTimers.append(liveStopwatch)
}
}
}
func isCountdownCancelled(_ countdown: Countdown) -> Bool {
return self.cancelledCountdowns.contains(where: { $0 == countdown.stringId })
}
// func notifyUser(countdownId: String) {
// // self._playSound(timerId: countdownId)
// self._endCountdown(countdownId: countdownId, cancel: false)
// }
fileprivate func _recordActivity(countdownId: String) {
let context = PersistenceController.shared.container.viewContext
if let countdown: Countdown = context.object(stringId: countdownId),
let dateInterval = self.currentCountdowns[countdownId] {
do {
try CoreDataRequests.recordActivity(timer: countdown, dateInterval: dateInterval)
} catch {
Logger.error(error)
// TODO: show error to user
}
}
}
// MARK: - Countdown
func startCountdown(countdown: Countdown, handler: @escaping (Result<Date?, Error>) -> Void) {
DispatchQueue.main.async {
let countdownId = countdown.stringId
self._cleanupPreviousTimerIfNecessary(countdownId)
do {
let end = try self._scheduleSoundPlayer(countdown: countdown, in: countdown.duration)
if Preferences.playConfirmationSound {
self._playConfirmationSound(timer: countdown)
}
handler(.success(end))
} catch {
FileLogger.log("start error : \(error.localizedDescription)")
Logger.error(error)
handler(.failure(error))
}
}
}
fileprivate func _scheduleSoundPlayer(countdown: Countdown, in interval: TimeInterval) throws -> Date {
let start = Date()
let end = start.addingTimeInterval(interval)
let countdownId = countdown.stringId
FileLogger.log("schedule countdown \(self._timerName(countdownId)) at \(end)")
let sound = countdown.someSound
let soundPlayer = try DelaySoundPlayer(timerID: countdownId, sound: sound)
self._delayedSoundPlayers[countdownId] = soundPlayer
try soundPlayer.start(in: interval,
repeatCount: Int(countdown.repeatCount))
let dateInterval = DateInterval(start: start, end: end)
self.currentCountdowns[countdownId] = dateInterval
self._launchLiveActivity(timer: countdown, date: end)
return end
}
fileprivate func _cleanupPreviousTimerIfNecessary(_ timerId: TimerID) {
self.removeLiveTimer(id: timerId)
if let player = self._delayedSoundPlayers[timerId] {
player.stop() // release resources
}
self._endLiveActivity(timerId: timerId)
}
func cancelCountdown(id: TimerID) {
FileLogger.log("Cancel \(self._timerName(id))")
CountdownScheduler.master.cancelCurrentNotifications(countdownId: id)
self.cancelSoundPlayer(id: id)
self.cancelledCountdowns.append(id)
self._endCountdown(countdownId: id, cancel: true)
self.pausedCountdowns.removeValue(forKey: id)
if Preferences.playCancellationSound {
self._playCancellationSound()
}
self._endLiveActivity(timerId: id)
}
func countdownState(_ countdown: Countdown) -> CountdownState {
let id = countdown.stringId
if self.cancelledCountdowns.contains(id) {
return .cancelled
} else if self.pausedCountdowns[id] != nil {
return .paused
} else if let interval = self.currentCountdowns[id], interval.end > Date() {
return .inprogress
} else {
return .finished
}
}
// func isCountdownPaused(_ countdown: Countdown) -> Bool {
// return self.pausedCountdowns[countdown.stringId] != nil
// }
func remainingPausedCountdownTime(_ countdown: Countdown) -> TimeInterval? {
return self.pausedCountdowns[countdown.stringId]
}
func pauseCountdown(id: TimerID) {
guard let interval = self.currentCountdowns[id] else {
return
}
let remainingTime = interval.end.timeIntervalSince(Date())
self.pausedCountdowns[id] = remainingTime
// cancel stuff
CountdownScheduler.master.cancelCurrentNotifications(countdownId: id)
self.cancelSoundPlayer(id: id)
self._endLiveActivity(timerId: id)
}
func resumeCountdown(id: TimerID) throws {
let context = PersistenceController.shared.container.viewContext
if let countdown: Countdown = context.object(stringId: id),
let remainingTime = self.pausedCountdowns[id] {
_ = try self._scheduleSoundPlayer(countdown: countdown, in: remainingTime)
self.pausedCountdowns.removeValue(forKey: id)
} else {
throw AppError.timerNotFound(id: id)
}
}
fileprivate func _endCountdown(countdownId: String, cancel: Bool) {
DispatchQueue.main.async {
#if DEBUG
if !cancel {
self._recordActivity(countdownId: countdownId)
}
#endif
self.currentCountdowns.removeValue(forKey: countdownId)
self._endLiveActivity(timerId: countdownId)
}
}
// MARK: - Stopwatch
func startStopwatch(_ stopwatchId: TimerID) {
DispatchQueue.main.async {
guard let stopWatch = IntentDataProvider.main.timer(id: stopwatchId) as? Stopwatch else {
return
}
let lsw: LiveStopWatch = LiveStopWatch(start: Date())
self.currentStopwatches[stopWatch.stringId] = lsw
if Preferences.playConfirmationSound {
self._playSound(Const.confirmationSound.rawValue)
}
self._endLiveActivity(timerId: stopWatch.stringId)
self._launchLiveActivity(timer: stopWatch, date: lsw.start)
}
}
func stopStopwatch(_ stopwatch: Stopwatch) {
if let lsw = Conductor.maestro.currentStopwatches[stopwatch.stringId] {
if lsw.end == nil {
let end = Date()
lsw.end = end
Conductor.maestro.currentStopwatches[stopwatch.stringId] = lsw
do {
try CoreDataRequests.recordActivity(timer: stopwatch, dateInterval: DateInterval(start: lsw.start, end: end))
} catch {
Logger.error(error)
}
self._endLiveActivity(timerId: stopwatch.stringId)
}
}
}
func restoreSoundPlayers() {
for (countdownId, interval) in self.currentCountdowns {
if !self._delayedSoundPlayers.contains(where: { $0.key == countdownId }) {
let context = PersistenceController.shared.container.viewContext
if let countdown: Countdown = context.object(stringId: countdownId) {
do {
let sound: Sound = countdown.someSound
let soundPlayer = try DelaySoundPlayer(timerID: countdownId, sound: sound)
self._delayedSoundPlayers[countdownId] = soundPlayer
try soundPlayer.restore(for: interval.end, repeatCount: Int(countdown.repeatCount))
FileLogger.log("Restored sound player for \(self._timerName(countdownId))")
} catch {
Logger.error(error)
}
}
}
}
}
// MARK: - Cleanup
func cleanup() {
self._cleanupCountdowns()
withAnimation {
self._cleanupLiveTimers()
self._buildLiveTimers()
}
if #available(iOS 16.2, *) {
self.cleanupLiveActivities()
}
}
fileprivate func _cleanupCountdowns() {
let now = Date()
for (key, value) in self.currentCountdowns {
if value.end < now || self.cancelledCountdowns.contains(key) {
self._endCountdown(countdownId: key, cancel: false)
}
}
}
// MARK: - Sound
fileprivate func _playSound(timerId: String) {
let context = PersistenceController.shared.container.viewContext
var coolSound: Sound? = nil
let timer = context.object(stringId: timerId)
switch timer {
case let cd as Countdown:
coolSound = cd.someSound
case let sw as Stopwatch:
coolSound = sw.coolSound
default:
break
}
if let coolSound {
self.playSound(coolSound)
} else {
print("No sound to play!")
}
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
fileprivate func _playConfirmationSound(timer: AbstractSoundTimer) {
let fileName: String
if let confirmationSound = timer.confirmationSounds.randomElement() {
fileName = confirmationSound.fileName
} else {
fileName = Const.confirmationSound.rawValue
}
self._playSound(fileName)
}
fileprivate func _playCancellationSound() {
self._playSound(Const.cancellationSound.rawValue)
}
func playSound(_ sound: Sound) {
self._playSound(sound.fileName)
}
func playSound(_ sound: Sound, duration: TimeInterval) {
self._playSound(sound.fileName, duration: duration)
}
fileprivate func _playSound(_ filename: String, duration: TimeInterval? = nil) {
do {
try self.soundPlayer.playOrPauseSound(filename, duration: duration)
} catch {
Logger.error(error)
// TODO: manage error
}
}
func cancelSoundPlayer(id: TimerID) {
if let soundPlayer = self._delayedSoundPlayers[id] {
soundPlayer.stop()
self._delayedSoundPlayers.removeValue(forKey: id)
FileLogger.log("cancelled sound player for \(self._timerName(id))")
}
self.deactivateAudioSessionIfPossible()
}
func deactivateAudioSessionIfPossible() {
if self._delayedSoundPlayers.isEmpty {
// do {
// try AVAudioSession.sharedInstance().setActive(false)
// } catch {
// Logger.error(error)
// }
}
}
// func isSoundPlaying(_ sound: Sound) -> Bool {
// return self.soundPlayer.isSoundPlaying(sound)
// }
func stopMainPlayersIfPossible() {
self.soundPlayer.stop()
}
func activateAudioSession() {
do {
let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playback, options: .duckOthers)
try audioSession.setActive(true)
} catch {
Logger.error(error)
}
}
// MARK: - Intent
// fileprivate func _createTimerIntent(_ timer: AbstractTimer) {
// let intent = LaunchTimerIntent()
//
// let invocationPhrase = String(format: NSLocalizedString("Launch %@", comment: ""), timer.displayName)
// intent.suggestedInvocationPhrase = String(format: invocationPhrase, timer.displayName)
// intent.timer = TimerIdentifier(identifier: timer.stringId, display: timer.displayName)
//
// let interaction = INInteraction(intent: intent, response: nil)
// interaction.donate()
// }
fileprivate func _scheduleAppRefresh(countdown: Countdown) {
let request = BGAppRefreshTaskRequest(identifier: BGTaskIdentifier.refresh.rawValue)
request.earliestBeginDate = Date(timeIntervalSinceNow: countdown.duration)
do {
try BGTaskScheduler.shared.submit(request)
print("request submitted with date: \(String(describing: request.earliestBeginDate))")
} catch {
Logger.error(error)
}
}
// MARK: - Live Activity
fileprivate func _launchLiveActivity(timer: AbstractTimer, date: Date) {
if #available(iOS 16.2, *) {
if ActivityAuthorizationInfo().areActivitiesEnabled {
let contentState = LaunchWidgetAttributes.ContentState(ended: false)
let attributes = LaunchWidgetAttributes(id: timer.stringId, name: timer.displayName, date: date, isTimer: timer is Countdown)
let activityContent = ActivityContent(state: contentState, staleDate: nil)
do {
let _ = try ActivityKit.Activity.request(attributes: attributes, content: activityContent)
// print("Requested a Live Activity: \(String(describing: liveActivity.id))")
} catch {
Logger.error(error)
}
}
} else {
// Fallback on earlier versions
}
}
fileprivate func _liveActivity(timerId: String) -> [ActivityKit.Activity<LaunchWidgetAttributes>] {
return ActivityKit.Activity<LaunchWidgetAttributes>.activities.filter { $0.attributes.id == timerId }
}
fileprivate func _liveActivityIds() -> [String] {
return ActivityKit.Activity<LaunchWidgetAttributes>.activities.map { $0.attributes.id }
}
func cleanupLiveActivities() {
for id in self._liveActivityIds() {
if self.liveTimers.first(where: { $0.id == id} ) == nil {
self._endLiveActivity(timerId: id)
}
}
}
fileprivate func _endLiveActivity(timerId: String) {
if #available(iOS 16.2, *) {
print("Try to end the Live Activity: \(timerId)")
for activity in self._liveActivity(timerId: timerId) {
Task {
let state = LaunchWidgetAttributes.ContentState(ended: true)
let content = ActivityContent(state: state, staleDate: Date())
await activity.end(content, dismissalPolicy: .immediate)
print("Ending the Live Activity: \(activity.id)")
}
}
}
}
fileprivate func _timerName(_ id: TimerID) -> String {
return IntentDataProvider.main.timer(id: id)?.name ?? id
}
deinit {
self.beats?.invalidate()
self.beats = nil
}
}