-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormViews.swift
More file actions
823 lines (731 loc) · 22.9 KB
/
FormViews.swift
File metadata and controls
823 lines (731 loc) · 22.9 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//
// FormViews.swift
// MistTray
//
import SwiftUI
// MARK: - Create Stream Form
struct CreateStreamForm: View {
@Bindable var appState: AppState
var dismiss: () -> Void
@State private var name = ""
@State private var source = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
TextField("Stream name (e.g. camera1)", text: $name)
.textFieldStyle(.roundedBorder)
} header: {
Text("Stream Name")
}
Section {
TextField("rtmp://source.example.com/live/stream", text: $source)
.textFieldStyle(.roundedBorder)
Text("Supported: RTMP, RTSP, HTTP, file paths, push://")
.font(.caption)
.foregroundStyle(.secondary)
} header: {
Text("Source")
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create Stream") { createStream() }
.keyboardShortcut(.defaultAction)
.disabled(name.trimmed.isEmpty || source.trimmed.isEmpty || isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Create Stream")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func createStream() {
isSubmitting = true
errorMessage = nil
StreamManager.shared.createStream(name: name.trimmed, source: source.trimmed) { result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
appState.onDataChanged?()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Edit Stream Form
struct EditStreamForm: View {
@Bindable var appState: AppState
let streamName: String
var dismiss: () -> Void
@State private var source: String = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
Text(streamName)
.font(.headline)
} header: {
Text("Stream")
}
Section {
TextField("rtmp://source.example.com/live/stream", text: $source)
.textFieldStyle(.roundedBorder)
} header: {
Text("Source")
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Save") { saveChanges() }
.keyboardShortcut(.defaultAction)
.disabled(source.trimmed.isEmpty || isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Edit Stream")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
source = appState.streamSource(streamName)
if source == "Unknown" { source = "" }
}
}
private func saveChanges() {
isSubmitting = true
errorMessage = nil
StreamManager.shared.updateStream(name: streamName, config: ["source": source.trimmed]) {
result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
appState.onDataChanged?()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Create Push Form
struct CreatePushForm: View {
@Bindable var appState: AppState
var dismiss: () -> Void
@State private var selectedStream: String = ""
@State private var targetURL = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
Picker("Stream", selection: $selectedStream) {
if appState.sortedStreamNames.isEmpty {
Text("No streams available").tag("")
}
ForEach(appState.sortedStreamNames, id: \.self) { name in
Text(name).tag(name)
}
}
} header: {
Text("Source Stream")
}
Section {
TextField("rtmp://live.example.com/live/streamkey", text: $targetURL)
.textFieldStyle(.roundedBorder)
Text("Destination URL (RTMP, RTSP, SRT, etc.)")
.font(.caption)
.foregroundStyle(.secondary)
} header: {
Text("Target URL")
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Start Push") { startPush() }
.keyboardShortcut(.defaultAction)
.disabled(selectedStream.isEmpty || targetURL.trimmed.isEmpty || isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Start Push")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
selectedStream = appState.sortedStreamNames.first ?? ""
}
}
private func startPush() {
isSubmitting = true
errorMessage = nil
PushManager.shared.startPush(streamName: selectedStream, targetURL: targetURL.trimmed) {
result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
appState.onDataChanged?()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Protocol Config Form
struct ProtocolConfigForm: View {
@Bindable var appState: AppState
let protocolName: String
let protocolIndex: Int
var dismiss: () -> Void
@State private var port: String = ""
@State private var interfaceAddr: String = "0.0.0.0"
@State private var extraFields: [(key: String, label: String, value: String)] = []
@State private var isSubmitting = false
@State private var errorMessage: String?
private var originalConfig: [String: Any] {
guard protocolIndex < appState.configuredProtocols.count else { return [:] }
return appState.configuredProtocols[protocolIndex]
}
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "\(protocolName) Config")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Port").font(.caption.weight(.medium)).foregroundStyle(.secondary)
TextField("Port number", text: $port)
.textFieldStyle(.roundedBorder)
}
VStack(alignment: .leading, spacing: 4) {
Text("Interface").font(.caption.weight(.medium)).foregroundStyle(.secondary)
TextField("0.0.0.0 (all interfaces)", text: $interfaceAddr)
.textFieldStyle(.roundedBorder)
Text("Leave as 0.0.0.0 to listen on all interfaces")
.font(.system(size: 9)).foregroundStyle(.secondary)
}
// Dynamic fields from capabilities
ForEach(Array(extraFields.enumerated()), id: \.offset) { index, field in
VStack(alignment: .leading, spacing: 4) {
Text(field.label).font(.caption.weight(.medium)).foregroundStyle(.secondary)
TextField("", text: Binding(
get: { extraFields[index].value },
set: { extraFields[index].value = $0 }
))
.textFieldStyle(.roundedBorder)
}
}
if let error = errorMessage {
Text(error).font(.caption).foregroundColor(Color.tnRed)
}
HStack {
Button("Cancel") { dismiss() }
.buttonStyle(.bordered).controlSize(.small).pointerOnHover()
Spacer()
Button("Save") { saveConfig() }
.buttonStyle(.borderedProminent).controlSize(.small).pointerOnHover()
.disabled(port.trimmed.isEmpty || isSubmitting)
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear { prefill() }
}
private func prefill() {
let config = originalConfig
port = (config["port"] as? Int).map(String.init) ?? UtilityManager.shared.getDefaultPort(for: protocolName)
interfaceAddr = config["interface"] as? String ?? "0.0.0.0"
// Load optional fields from capabilities
if let connInfo = appState.availableConnectors[protocolName] as? [String: Any],
let optional = connInfo["optional"] as? [String: Any] {
let skip: Set<String> = ["port", "interface", "connector"]
extraFields = optional.keys.sorted().compactMap { key in
guard !skip.contains(key) else { return nil }
let info = optional[key] as? [String: Any]
let label = info?["name"] as? String ?? key
let current = config[key].map { "\($0)" } ?? ""
return (key: key, label: label, value: current)
}
}
}
private func saveConfig() {
guard let portNum = Int(port.trimmed) else {
errorMessage = "Please enter a valid port number."
return
}
isSubmitting = true
errorMessage = nil
var updated = originalConfig
updated["port"] = portNum
let iface = interfaceAddr.trimmed
updated["interface"] = iface.isEmpty ? "0.0.0.0" : iface
for field in extraFields where !field.value.isEmpty {
// Try to preserve type (int vs string)
if let intVal = Int(field.value) {
updated[field.key] = intVal
} else {
updated[field.key] = field.value
}
}
APIClient.shared.updateProtocol(original: originalConfig, updated: updated) { result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
appState.onDataChanged?()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Add Stream Tag Form
struct AddStreamTagForm: View {
let streamName: String
var dismiss: () -> Void
@State private var tagName = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
TextField("e.g. live, recording, camera1", text: $tagName)
.textFieldStyle(.roundedBorder)
Text("Tags help organize streams by category, purpose, or equipment.")
.font(.caption)
.foregroundStyle(.secondary)
} header: {
Text("Tag Name")
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Add Tag") { addTag() }
.keyboardShortcut(.defaultAction)
.disabled(tagName.trimmed.isEmpty || isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Add Tag to '\(streamName)'")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func addTag() {
isSubmitting = true
errorMessage = nil
StreamManager.shared.addStreamTag(streamName, tag: tagName.trimmed) { result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
(NSApp.delegate as? AppDelegate)?.refreshAllData()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Add Auto-Push Rule Form
struct AddAutoPushRuleForm: View {
var dismiss: () -> Void
@State private var streamPattern = ""
@State private var targetURL = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
TextField("e.g. camera*, live_*", text: $streamPattern)
.textFieldStyle(.roundedBorder)
Text("Use * as wildcard. Exact match: \"camera1\", Pattern: \"camera*\"")
.font(.caption)
.foregroundStyle(.secondary)
} header: {
Text("Stream Pattern")
}
Section {
TextField("rtmp://example.com/live/stream_key", text: $targetURL)
.textFieldStyle(.roundedBorder)
Text("Supported: rtmp://, srt://, http://, file://")
.font(.caption)
.foregroundStyle(.secondary)
} header: {
Text("Target URL")
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create Rule") { createRule() }
.keyboardShortcut(.defaultAction)
.disabled(
streamPattern.trimmed.isEmpty || targetURL.trimmed.isEmpty || isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Add Auto-Push Rule")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func createRule() {
guard UtilityManager.shared.isValidStreamingURL(targetURL.trimmed) else {
errorMessage = "Please enter a valid streaming URL."
return
}
isSubmitting = true
errorMessage = nil
APIClient.shared.createAutoPushRule(
streamPattern: streamPattern.trimmed, targetURL: targetURL.trimmed
) { result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
(NSApp.delegate as? AppDelegate)?.refreshAllData()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - Push Settings Form
struct PushSettingsForm: View {
var dismiss: () -> Void
@State private var maxSpeed = "0"
@State private var waitTime = "5"
@State private var autoRestart = true
@State private var isSubmitting = false
@State private var errorMessage: String?
var body: some View {
Form {
Section {
TextField("0 = unlimited", text: $maxSpeed)
.textFieldStyle(.roundedBorder)
} header: {
Text("Maximum Push Speed (KB/s)")
}
Section {
TextField("Default: 5", text: $waitTime)
.textFieldStyle(.roundedBorder)
} header: {
Text("Wait Time Between Pushes (seconds)")
}
Section {
Toggle("Auto-restart failed pushes", isOn: $autoRestart)
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Apply") { applySettings() }
.keyboardShortcut(.defaultAction)
.disabled(isSubmitting)
}
}
.formStyle(.grouped)
.navigationTitle("Push Settings")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func applySettings() {
guard let speed = Int(maxSpeed.trimmed), let wait = Int(waitTime.trimmed) else {
errorMessage = "Please enter valid numbers."
return
}
isSubmitting = true
errorMessage = nil
APIClient.shared.applyPushSettings(maxSpeed: speed, waitTime: wait, autoRestart: autoRestart) {
result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success:
(NSApp.delegate as? AppDelegate)?.refreshAllData()
dismiss()
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
}
// MARK: - First-Time Setup Form (Inline)
struct SetupFormInline: View {
@Bindable var appState: AppState
@State private var username = ""
@State private var password = ""
@State private var confirmPassword = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
private var isValid: Bool {
!username.trimmed.isEmpty
&& !password.isEmpty
&& password == confirmPassword
&& password.count >= 4
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
Text("Welcome to MistServer")
.font(.title3.weight(.semibold))
Text("Create an admin account to get started.")
.font(.subheadline)
.foregroundStyle(.secondary)
}
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Username")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
TextField("admin", text: $username)
.textFieldStyle(.roundedBorder)
}
VStack(alignment: .leading, spacing: 4) {
Text("Password")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
}
VStack(alignment: .leading, spacing: 4) {
Text("Confirm Password")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
SecureField("Confirm password", text: $confirmPassword)
.textFieldStyle(.roundedBorder)
}
if !confirmPassword.isEmpty && password != confirmPassword {
Text("Passwords do not match")
.font(.caption)
.foregroundColor(Color.tnRed)
}
if !password.isEmpty && password.count < 4 {
Text("Password must be at least 4 characters")
.font(.caption)
.foregroundColor(Color.tnOrange)
}
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
Button {
createAccount()
} label: {
if isSubmitting {
HStack(spacing: 6) {
ProgressView()
.controlSize(.small)
Text("Creating account...")
}
.frame(maxWidth: .infinity)
} else {
Text("Create Account")
.frame(maxWidth: .infinity)
}
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
.disabled(!isValid || isSubmitting)
}
.padding(16)
}
}
private func createAccount() {
isSubmitting = true
errorMessage = nil
APIClient.shared.createAccount(username: username.trimmed, password: password) { result in
DispatchQueue.main.async {
isSubmitting = false
switch result {
case .success(let data):
if let authorize = data["authorize"] as? [String: Any],
let status = authorize["status"] as? String
{
if status == "ACC_MADE" || status == "OK" {
completeSetup()
} else {
errorMessage = "Unexpected response: \(status)"
}
} else {
completeSetup()
}
case .failure(let error):
errorMessage = error.localizedDescription
}
}
}
}
private func completeSetup() {
appState.needsSetup = false
// Reset responder chain so click handling works in the borderless panel
DispatchQueue.main.async {
if let w = NSApp.keyWindow {
w.makeFirstResponder(w.contentView)
}
}
if let appDelegate = NSApp.delegate as? AppDelegate {
// Enable default protocols (like LSP does), then refresh
appDelegate.enableDefaultProtocols {
appDelegate.refreshAllData()
}
}
}
}
// MARK: - Login Form (CHALL Auth)
struct LoginFormInline: View {
@Bindable var appState: AppState
@State private var host = ""
@State private var username = ""
@State private var password = ""
@State private var isSubmitting = false
@State private var errorMessage: String?
private var isValid: Bool {
!username.trimmed.isEmpty && !password.isEmpty
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
Text("Authentication Required")
.font(.title3.weight(.semibold))
Text("This MistServer instance requires login credentials.")
.font(.subheadline)
.foregroundStyle(.secondary)
}
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Server")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
TextField("http://localhost:4242", text: $host)
.textFieldStyle(.roundedBorder)
.font(.caption)
.onChange(of: host) {
let trimmed = host.trimmed
if !trimmed.isEmpty {
appState.serverURL = trimmed
}
}
}
VStack(alignment: .leading, spacing: 4) {
Text("Username")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
TextField("admin", text: $username)
.textFieldStyle(.roundedBorder)
}
VStack(alignment: .leading, spacing: 4) {
Text("Password")
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
.onSubmit { if isValid { login() } }
}
}
if let error = errorMessage {
Text(error)
.font(.caption)
.foregroundColor(Color.tnRed)
}
Button {
login()
} label: {
if isSubmitting {
HStack(spacing: 6) {
ProgressView()
.controlSize(.small)
Text("Logging in...")
}
.frame(maxWidth: .infinity)
} else {
Text("Log In")
.frame(maxWidth: .infinity)
}
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
.disabled(!isValid || isSubmitting)
}
.padding(16)
}
.onAppear { host = appState.serverURL }
}
private func login() {
isSubmitting = true
errorMessage = nil
APIClient.shared.login(username: username.trimmed, rawPassword: password) { success, error in
DispatchQueue.main.async {
isSubmitting = false
if success {
appState.needsAuth = false
appState.authError = nil
// Reset responder chain
if let w = NSApp.keyWindow {
w.makeFirstResponder(w.contentView)
}
if let appDelegate = NSApp.delegate as? AppDelegate {
appDelegate.refreshAllData()
}
} else {
errorMessage = error ?? "Login failed"
}
}
}
}
}
// MARK: - String Extension
extension String {
var trimmed: String {
trimmingCharacters(in: .whitespacesAndNewlines)
}
}