jel/Jel/Views/SignIn/AddServerView.swift

112 lines
2.6 KiB
Swift
Raw Normal View History

2023-12-12 06:22:43 +00:00
//
// AddServerView.swift
// Jel
//
// Created by zerocool on 12/11/23.
//
import SwiftUI
struct AddServerView: View {
2023-12-12 22:09:15 +00:00
@EnvironmentObject var jellyfinClient: JellyfinClientController
2023-12-15 15:41:00 +00:00
@ObservedObject var authState: AuthStateController = AuthStateController.shared
2023-12-12 22:09:15 +00:00
@Binding var serverUrlIsValid: Bool
2023-12-12 06:22:43 +00:00
@State var serverUrlString: String = ""
2023-12-12 06:22:43 +00:00
@State var urlHasError: Bool = false
@State var currentErrorMessage: String = ""
2023-12-12 22:09:15 +00:00
@State var isLoading: Bool = false
2023-12-12 06:22:43 +00:00
@FocusState var serverUrlIsFocused: Bool
var body: some View {
VStack {
Text("Connect to a server")
.font(.title)
HStack {
TextField(text: $serverUrlString) {
Text(verbatim: "https://jellyfin.example.com")
2023-12-12 06:22:43 +00:00
}
.keyboardType(.URL)
.textContentType(.URL)
.textFieldStyle(.roundedBorder)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($serverUrlIsFocused)
.onSubmit {
Task {
await checkServerUrl()
}
}
2023-12-12 22:09:15 +00:00
if !isLoading {
2023-12-12 06:22:43 +00:00
Button(action: {
Task {
await checkServerUrl()
}
}) {
Label("Connect", systemImage: "arrow.right")
.labelStyle(.iconOnly)
}
.buttonStyle(.bordered)
} else {
2023-12-12 22:09:15 +00:00
ProgressView()
2023-12-12 06:22:43 +00:00
.progressViewStyle(.circular)
2023-12-12 22:09:15 +00:00
.padding([.leading, .trailing])
2023-12-12 06:22:43 +00:00
}
}
.padding()
2023-12-12 22:09:15 +00:00
.disabled(isLoading)
2023-12-12 06:22:43 +00:00
if urlHasError {
Text(currentErrorMessage)
.font(.callout)
.foregroundStyle(.red)
}
}
.onAppear {
serverUrlString = authState.serverUrl?.absoluteString ?? ""
}
2023-12-12 06:22:43 +00:00
}
func checkServerUrl() async {
2023-12-12 22:09:15 +00:00
isLoading = true
2023-12-12 06:22:43 +00:00
serverUrlIsFocused = false
if isValidUrl(data: serverUrlString) {
let url = URL(string: serverUrlString)!
2023-12-12 22:09:15 +00:00
jellyfinClient.setUrl(url: url)
2023-12-15 15:41:00 +00:00
if await jellyfinClient.getPublicServerInfo() != nil {
2023-12-12 06:22:43 +00:00
authState.serverUrl = url
2023-12-12 22:09:15 +00:00
authState.save()
2023-12-12 06:22:43 +00:00
urlHasError = false
2023-12-12 22:09:15 +00:00
serverUrlIsValid = true
2023-12-12 06:22:43 +00:00
} else {
urlHasError = true
currentErrorMessage = "Server not responding"
}
} else {
urlHasError = true
currentErrorMessage = "Invalid url"
}
2023-12-12 22:09:15 +00:00
isLoading = false
2023-12-12 06:22:43 +00:00
}
func isValidUrl(data: String) -> Bool {
if let url = URL(string: data) {
if UIApplication.shared.canOpenURL(url) {
return true
}
}
return false
}
}
//#Preview {
// AddServerView(serverUrlIsValid: .constant(false))
//
//}