jel/Jel/Views/AddServerView.swift

110 lines
2.4 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 {
@ObservedObject var authState: AuthStateController
@State var serverUrlString: String = ""
@State var urlHasError: Bool = false
@State var currentErrorMessage: String = ""
@State var loading: Bool = false
@FocusState var serverUrlIsFocused: Bool
var body: some View {
VStack {
Text("Connect to a server")
.font(.title)
HStack {
TextField(text: $serverUrlString) {
Text("http://jellyfin.example.com")
.foregroundStyle(.placeholder)
}
.keyboardType(.URL)
.textContentType(.URL)
.textFieldStyle(.roundedBorder)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($serverUrlIsFocused)
.onChange(of: serverUrlIsFocused) {
if serverUrlIsFocused {
urlHasError = false
}
}
.onSubmit {
Task {
await checkServerUrl()
}
}
if !loading {
Button(action: {
Task {
await checkServerUrl()
}
}) {
Label("Connect", systemImage: "arrow.right")
.labelStyle(.iconOnly)
}
.buttonStyle(.bordered)
.disabled(urlHasError)
} else {
ProgressView()
.progressViewStyle(.circular)
.padding()
}
}
.padding()
if urlHasError {
Text(currentErrorMessage)
.font(.callout)
.foregroundStyle(.red)
}
}
}
func checkServerUrl() async {
loading = true
serverUrlIsFocused = false
if isValidUrl(data: serverUrlString) {
let url = URL(string: serverUrlString)!
if await JellyfinClientController(serverUrl: url).isJellyfinServer() {
authState.serverUrl = url
urlHasError = false
} else {
urlHasError = true
currentErrorMessage = "Server not responding"
}
} else {
urlHasError = true
currentErrorMessage = "Invalid url"
}
loading = false
}
func isValidUrl(data: String) -> Bool {
if let url = URL(string: data) {
if UIApplication.shared.canOpenURL(url) {
return true
}
}
return false
}
}
#Preview {
AddServerView(authState: AuthStateController())
}