IceCubesApp/IceCubesApp/App/IceCubesApp.swift

304 lines
10 KiB
Swift
Raw Normal View History

2023-01-17 10:36:01 +00:00
import Account
import AppAccount
2023-01-09 17:52:53 +00:00
import AVFoundation
2022-12-24 13:55:04 +00:00
import DesignSystem
2023-01-17 10:36:01 +00:00
import Env
import KeychainSwift
import Network
2023-01-07 12:44:13 +00:00
import RevenueCat
2023-01-17 10:36:01 +00:00
import SwiftUI
import Timeline
2022-12-01 08:05:26 +00:00
@main
2023-01-17 10:36:01 +00:00
struct IceCubesApp: App {
2023-01-08 09:22:52 +00:00
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
2023-01-30 06:27:06 +00:00
@Environment(\.scenePhase) private var scenePhase
2023-01-30 06:27:06 +00:00
2023-01-08 09:22:52 +00:00
@StateObject private var appAccountsManager = AppAccountsManager.shared
@StateObject private var currentInstance = CurrentInstance.shared
@StateObject private var currentAccount = CurrentAccount.shared
@StateObject private var userPreferences = UserPreferences.shared
@StateObject private var pushNotificationsService = PushNotificationsService.shared
@StateObject private var watcher = StreamWatcher()
2022-12-22 09:53:36 +00:00
@StateObject private var quickLook = QuickLook()
@StateObject private var theme = Theme.shared
@StateObject private var sidebarRouterPath = RouterPath()
2023-01-30 06:27:06 +00:00
2023-01-04 11:55:09 +00:00
@State private var selectedTab: Tab = .timeline
2022-12-24 10:50:05 +00:00
@State private var popToRootTab: Tab = .other
@State private var sideBarLoadedTabs: Set<Tab> = Set()
@State private var isSupporter: Bool = false
2023-01-30 06:27:06 +00:00
private var availableTabs: [Tab] {
appAccountsManager.currentClient.isAuth ? Tab.loggedInTabs() : Tab.loggedOutTab()
}
2023-01-30 06:27:06 +00:00
2022-12-01 08:05:26 +00:00
var body: some Scene {
WindowGroup {
appView
2023-01-17 10:36:01 +00:00
.applyTheme(theme)
.onAppear {
setNewClientsInEnv(client: appAccountsManager.currentClient)
setupRevenueCat()
refreshPushSubs()
}
.environmentObject(appAccountsManager)
.environmentObject(appAccountsManager.currentClient)
.environmentObject(quickLook)
.environmentObject(currentAccount)
.environmentObject(currentInstance)
.environmentObject(userPreferences)
.environmentObject(theme)
.environmentObject(watcher)
.environmentObject(pushNotificationsService)
.environment(\.isSupporter, isSupporter)
.fullScreenCover(item: $quickLook.url, content: { url in
2023-01-17 10:36:01 +00:00
QuickLookPreview(selectedURL: url, urls: quickLook.urls)
.edgesIgnoringSafeArea(.bottom)
.background(TransparentBackground())
2023-01-17 10:36:01 +00:00
})
2023-02-14 11:17:27 +00:00
.onChange(of: pushNotificationsService.handledNotification) { notification in
if notification != nil {
2023-02-14 11:17:27 +00:00
pushNotificationsService.handledNotification = nil
if appAccountsManager.currentAccount.oauthToken?.accessToken != notification?.account.token.accessToken,
let account = appAccountsManager.availableAccounts.first(where:
2023-02-18 06:26:48 +00:00
{ $0.oauthToken?.accessToken == notification?.account.token.accessToken })
{
2023-02-14 11:17:27 +00:00
appAccountsManager.currentAccount = account
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
selectedTab = .notifications
pushNotificationsService.handledNotification = notification
}
} else {
selectedTab = .notifications
}
}
}
2022-12-01 08:05:26 +00:00
}
.commands {
2023-01-18 07:27:42 +00:00
appMenu
}
.onChange(of: scenePhase) { scenePhase in
2022-12-25 16:39:12 +00:00
handleScenePhase(scenePhase: scenePhase)
}
2022-12-29 09:39:34 +00:00
.onChange(of: appAccountsManager.currentClient) { newClient in
setNewClientsInEnv(client: newClient)
if newClient.isAuth {
watcher.watch(streams: [.user, .direct])
2022-12-29 09:39:34 +00:00
}
}
2022-12-01 08:05:26 +00:00
}
2023-01-30 06:27:06 +00:00
@ViewBuilder
private var appView: some View {
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
2023-01-16 13:40:23 +00:00
sidebarView
} else {
tabBarView
}
}
2023-01-30 06:27:06 +00:00
private func badgeFor(tab: Tab) -> Int {
if tab == .notifications && selectedTab != tab,
2023-02-21 06:23:42 +00:00
let token = appAccountsManager.currentAccount.oauthToken
{
return watcher.unreadNotificationsCount + userPreferences.getNotificationsCount(for: token)
}
return 0
}
2023-01-30 06:27:06 +00:00
2023-01-16 13:40:23 +00:00
private var sidebarView: some View {
2023-01-16 18:51:05 +00:00
SideBarView(selectedTab: $selectedTab,
popToRootTab: $popToRootTab,
tabs: availableTabs,
routerPath: sidebarRouterPath) {
2023-02-22 18:09:39 +00:00
GeometryReader { _ in
HStack(spacing: 0) {
ZStack {
if selectedTab == .profile {
ProfileTab(popToRootTab: $popToRootTab)
}
ForEach(availableTabs) { tab in
if tab == selectedTab || sideBarLoadedTabs.contains(tab) {
tab
.makeContentView(popToRootTab: $popToRootTab)
.opacity(tab == selectedTab ? 1 : 0)
.transition(.opacity)
.id("\(tab)\(appAccountsManager.currentAccount.id)")
.onAppear {
sideBarLoadedTabs.insert(tab)
}
} else {
EmptyView()
2023-01-16 13:40:23 +00:00
}
}
}
if appAccountsManager.currentClient.isAuth,
userPreferences.showiPadSecondaryColumn
2023-01-30 06:27:06 +00:00
{
Divider().edgesIgnoringSafeArea(.all)
notificationsSecondaryColumn
2023-01-16 13:40:23 +00:00
}
}
}
}.onChange(of: $appAccountsManager.currentAccount.id) { _ in
sideBarLoadedTabs.removeAll()
2023-01-16 13:40:23 +00:00
}
}
2023-02-18 06:26:48 +00:00
private var notificationsSecondaryColumn: some View {
NotificationsTab(popToRootTab: $popToRootTab, lockedType: nil)
.environment(\.isSecondaryColumn, true)
2023-02-21 17:46:28 +00:00
.frame(maxWidth: .secondaryColumnWidth)
.id(appAccountsManager.currentAccount.id)
}
2023-01-30 06:27:06 +00:00
private var tabBarView: some View {
TabView(selection: .init(get: {
selectedTab
}, set: { newTab in
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) {
if newTab == selectedTab {
/// Stupid hack to trigger onChange binding in tab views.
popToRootTab = .other
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
popToRootTab = selectedTab
}
}
selectedTab = newTab
if selectedTab == .notifications,
2023-02-21 06:23:42 +00:00
let token = appAccountsManager.currentAccount.oauthToken
{
userPreferences.setNotification(count: 0, token: token)
watcher.unreadNotificationsCount = 0
}
}
HapticManager.shared.fireHaptic(of: .tabSelection)
2023-02-28 17:55:08 +00:00
SoundEffectManager.shared.playSound(of: .tabSelection)
})) {
ForEach(availableTabs) { tab in
tab.makeContentView(popToRootTab: $popToRootTab)
.tabItem {
if userPreferences.showiPhoneTabLabel {
tab.label
.labelStyle(TitleAndIconLabelStyle())
} else {
tab.label
.labelStyle(IconOnlyLabelStyle())
}
}
.tag(tab)
.badge(badgeFor(tab: tab))
.toolbarBackground(theme.primaryBackgroundColor.opacity(0.50), for: .tabBar)
}
}
.id(appAccountsManager.currentClient.id)
}
2023-01-30 06:27:06 +00:00
2022-12-25 16:39:12 +00:00
private func setNewClientsInEnv(client: Client) {
currentAccount.setClient(client: client)
2023-01-01 17:31:23 +00:00
currentInstance.setClient(client: client)
2023-01-09 18:47:54 +00:00
userPreferences.setClient(client: client)
2023-02-03 18:44:55 +00:00
Task {
await currentInstance.fetchCurrentInstance()
watcher.setClient(client: client, instanceStreamingURL: currentInstance.instance?.urls?.streamingApi)
watcher.watch(streams: [.user, .direct])
}
2022-12-25 16:39:12 +00:00
}
2023-01-30 06:27:06 +00:00
2022-12-25 16:39:12 +00:00
private func handleScenePhase(scenePhase: ScenePhase) {
switch scenePhase {
case .background:
2023-02-06 16:53:47 +00:00
watcher.stopWatching()
2022-12-25 16:39:12 +00:00
case .active:
watcher.watch(streams: [.user, .direct])
2023-01-09 17:52:53 +00:00
UIApplication.shared.applicationIconBadgeNumber = 0
2023-01-09 18:47:54 +00:00
Task {
await userPreferences.refreshServerPreferences()
}
2022-12-25 16:39:12 +00:00
default:
break
}
}
2023-01-30 06:27:06 +00:00
2023-01-07 12:44:13 +00:00
private func setupRevenueCat() {
Purchases.logLevel = .error
Purchases.configure(withAPIKey: "appl_JXmiRckOzXXTsHKitQiicXCvMQi")
Purchases.shared.getCustomerInfo { info, _ in
if info?.entitlements.active.isEmpty == false {
isSupporter = true
}
}
2023-01-07 12:44:13 +00:00
}
2023-01-30 06:27:06 +00:00
2023-01-08 09:22:52 +00:00
private func refreshPushSubs() {
2023-01-08 13:16:43 +00:00
PushNotificationsService.shared.requestPushNotifications()
2023-01-08 09:22:52 +00:00
}
2023-01-30 06:27:06 +00:00
2023-01-18 07:27:42 +00:00
@CommandsBuilder
private var appMenu: some Commands {
CommandGroup(replacing: .newItem) {
2023-01-26 05:40:33 +00:00
Button("menu.new-post") {
sidebarRouterPath.presentedSheet = .newStatusEditor(visibility: userPreferences.postVisibility)
2023-01-18 07:27:42 +00:00
}
}
CommandGroup(replacing: .textFormatting) {
2023-01-26 05:40:33 +00:00
Menu("menu.font") {
Button("menu.font.bigger") {
if theme.fontSizeScale < 1.5 {
theme.fontSizeScale += 0.1
2023-01-18 07:27:42 +00:00
}
}
2023-01-26 05:40:33 +00:00
Button("menu.font.smaller") {
if theme.fontSizeScale > 0.5 {
theme.fontSizeScale -= 0.1
2023-01-18 07:27:42 +00:00
}
}
}
}
}
2023-01-08 09:22:52 +00:00
}
class AppDelegate: NSObject, UIApplicationDelegate {
let themeObserver = ThemeObserverViewController(nibName: nil, bundle: nil)
2023-01-30 06:27:06 +00:00
2023-01-17 10:36:01 +00:00
func application(_: UIApplication,
didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool
{
2023-01-09 17:52:53 +00:00
try? AVAudioSession.sharedInstance().setCategory(.ambient, options: .mixWithOthers)
PushNotificationsService.shared.setAccounts(accounts: AppAccountsManager.shared.pushAccounts)
2023-01-08 09:22:52 +00:00
return true
}
2023-01-30 06:27:06 +00:00
2023-01-17 10:36:01 +00:00
func application(_: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
2023-01-08 13:16:43 +00:00
PushNotificationsService.shared.pushToken = deviceToken
Task {
PushNotificationsService.shared.setAccounts(accounts: AppAccountsManager.shared.pushAccounts)
await PushNotificationsService.shared.updateSubscriptions(forceCreate: false)
}
2023-01-08 09:22:52 +00:00
}
2023-01-30 06:27:06 +00:00
2023-01-17 10:36:01 +00:00
func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError _: Error) {}
2023-01-30 06:27:06 +00:00
func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
let configuration = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
if connectingSceneSession.role == .windowApplication {
configuration.delegateClass = SceneDelegate.self
}
return configuration
}
2022-12-01 08:05:26 +00:00
}
class ThemeObserverViewController: UIViewController {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
2023-01-30 06:27:06 +00:00
print(traitCollection.userInterfaceStyle.rawValue)
}
}