summaryrefslogtreecommitdiff
path: root/Jel/Views/AddServerView.swift
blob: beab5e765b0ae28d48bfdff7060e53b793ddf693 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//
//  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())
}