jellyflood/Shared/Services/SessionManager.swift

88 lines
2.2 KiB
Swift

//
// Swiftfin is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2025 Jellyfin & Jellyfin Contributors
//
import Combine
import Defaults
import Factory
import Foundation
/// Manages active provider sessions (Jellyfin and/or Xtream)
final class SessionManager: ObservableObject {
@Published
var jellyfinSession: UserSession?
@Published
var xtreamSession: XtreamSession?
private var cancellables = Set<AnyCancellable>()
init() {
// Initialize with current sessions
self.jellyfinSession = Container.shared.currentUserSession()
self.xtreamSession = Container.shared.currentXtreamSession()
// Listen for session changes
NotificationCenter.default.publisher(for: .didSignIn)
.sink { [weak self] _ in
self?.refreshJellyfinSession()
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: .didSignOut)
.sink { [weak self] _ in
self?.refreshJellyfinSession()
}
.store(in: &cancellables)
// Listen for Xtream session changes
Defaults.publisher(.currentXtreamServerID)
.sink { [weak self] _ in
self?.refreshXtreamSession()
}
.store(in: &cancellables)
}
var hasActiveProvider: Bool {
jellyfinSession != nil || xtreamSession != nil
}
var hasJellyfinProvider: Bool {
jellyfinSession != nil
}
var hasXtreamProvider: Bool {
xtreamSession != nil
}
private func refreshJellyfinSession() {
jellyfinSession = Container.shared.currentUserSession()
}
private func refreshXtreamSession() {
xtreamSession = Container.shared.currentXtreamSession()
}
func signOutJellyfin() {
NotificationCenter.default.post(name: .didSignOut, object: nil)
}
func signOutXtream() {
Defaults[.currentXtreamServerID] = nil
}
}
extension Container {
var sessionManager: Factory<SessionManager> {
self {
SessionManager()
}.singleton
}
}