-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataProcessor.swift
More file actions
588 lines (475 loc) · 17.4 KB
/
DataProcessor.swift
File metadata and controls
588 lines (475 loc) · 17.4 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
//
// DataProcessor.swift
// MistTray
//
import Foundation
// Import the configuration types from DialogManager
extension DataProcessor {
struct PushConfiguration {
let streamName: String
let targetURL: String
}
}
class DataProcessor {
static let shared = DataProcessor()
private init() {}
// MARK: - Stream Data Processing
func processStreamData(_ data: [String: Any]) -> ProcessedStreamData {
var activeStreams: [String] = []
var streamStats: [String: Any] = [:]
var allStreams: [String: Any] = [:]
var serverTotals: [String: Any] = [:]
// Process active streams
if let streams = data["active_streams"] as? [String: Any] {
for (streamName, streamData) in streams {
guard let streamInfo = streamData as? [String: Any] else { continue }
activeStreams.append(streamName)
streamStats[streamName] = streamInfo
// Extract stream statistics
let clients = streamInfo["clients"] as? Int ?? 0
let bandwidth = streamInfo["bps_out"] as? Int ?? 0
let uptime = streamInfo["uptime"] as? Int ?? 0
streamStats[streamName] = [
"clients": clients,
"bps_out": bandwidth,
"uptime": uptime,
"formatted_bandwidth": formatBandwidth(bandwidth),
"formatted_uptime": formatDuration(uptime),
]
}
}
// Process all configured streams
if let config = data["config"] as? [String: Any],
let streams = config["streams"] as? [String: Any]
{
allStreams = streams
}
// Process server totals
if let totals = data["totals"] as? [String: Any] {
serverTotals = totals
}
return ProcessedStreamData(
activeStreams: activeStreams.sorted(),
streamStats: streamStats,
allStreams: allStreams,
serverTotals: serverTotals
)
}
// MARK: - Push Data Processing
func processPushData(_ data: [String: Any]) -> ProcessedPushData {
var activePushes: [String: Any] = [:]
if let pushes = data["active_pushes"] as? [String: Any] {
for (pushKey, pushData) in pushes {
guard let pushInfo = pushData as? [String: Any] else { continue }
// Enhance push data with formatted information
var enhancedPushInfo = pushInfo
if let activeSeconds = pushInfo["active_seconds"] as? Int {
enhancedPushInfo["formatted_duration"] = formatDuration(activeSeconds)
}
if let bytes = pushInfo["bytes"] as? Int {
enhancedPushInfo["formatted_bytes"] = formatBytes(bytes)
}
if let bps = pushInfo["bps"] as? Int {
enhancedPushInfo["formatted_bandwidth"] = formatBandwidth(bps)
}
activePushes[pushKey] = enhancedPushInfo
}
}
return ProcessedPushData(activePushes: activePushes)
}
// MARK: - Client Data Processing
func processClientData(_ data: [String: Any]) -> ProcessedClientData {
var connectedClients: [String: Any] = [:]
var clientsByStream: [String: [String: Any]] = [:]
if let clients = data["clients"] as? [String: Any] {
for (clientId, clientData) in clients {
guard let clientInfo = clientData as? [String: Any] else { continue }
// Enhance client data with formatted information
var enhancedClientInfo = clientInfo
if let connTime = clientInfo["conntime"] as? Int {
let duration = Int(Date().timeIntervalSince1970) - connTime
enhancedClientInfo["formatted_duration"] = formatDuration(duration)
}
if let bytes = clientInfo["bytes_down"] as? Int {
enhancedClientInfo["formatted_bytes"] = formatBytes(bytes)
}
if let bps = clientInfo["bps_down"] as? Int {
enhancedClientInfo["formatted_bandwidth"] = formatBandwidth(bps)
}
connectedClients[clientId] = enhancedClientInfo
// Group by stream
if let streamName = clientInfo["stream"] as? String {
if clientsByStream[streamName] == nil {
clientsByStream[streamName] = [:]
}
clientsByStream[streamName]![clientId] = enhancedClientInfo
}
}
}
return ProcessedClientData(
connectedClients: connectedClients,
clientsByStream: clientsByStream
)
}
// MARK: - Protocol Data Processing
func processProtocolData(_ data: [String: Any]) -> ProcessedProtocolData {
var protocolConfig: [String: Any] = [:]
var enabledProtocols: [String] = []
var disabledProtocols: [String] = []
if let config = data["config"] as? [String: Any],
let protocols = config["protocols"] as? [[String: Any]]
{
protocolConfig["protocols"] = protocols
for protocolInfo in protocols {
guard let connector = protocolInfo["connector"] as? String else { continue }
let port = protocolInfo["port"] as? Int ?? 0
if port > 0 {
enabledProtocols.append(connector)
} else {
disabledProtocols.append(connector)
}
}
}
return ProcessedProtocolData(
protocolConfig: protocolConfig,
enabledProtocols: enabledProtocols.sorted(),
disabledProtocols: disabledProtocols.sorted()
)
}
// MARK: - Server Statistics Processing
func processServerStatistics(_ data: [String: Any]) -> ProcessedServerStats {
var stats = ProcessedServerStats()
if let totals = data["totals"] as? [String: Any] {
stats.totalClients = totals["clients"] as? Int ?? 0
stats.totalBandwidth = totals["bps_out"] as? Int ?? 0
stats.uptime = totals["uptime"] as? Int ?? 0
stats.totalStreams = totals["streams"] as? Int ?? 0
// Format values
stats.formattedBandwidth = formatBandwidth(stats.totalBandwidth)
stats.formattedUptime = formatDuration(stats.uptime)
}
if let memory = data["memory"] as? [String: Any] {
stats.memoryUsage = memory["used"] as? Int ?? 0
stats.memoryTotal = memory["total"] as? Int ?? 0
stats.formattedMemory = formatBytes(stats.memoryUsage)
}
if let cpu = data["cpu"] as? [String: Any] {
stats.cpuUsage = cpu["usage"] as? Double ?? 0.0
}
return stats
}
// MARK: - Configuration Data Processing
func processConfigurationData(_ data: [String: Any]) -> ProcessedConfigData {
var config = ProcessedConfigData()
if let configData = data["config"] as? [String: Any] {
config.rawConfig = configData
// Extract key configuration sections
if let streams = configData["streams"] as? [String: Any] {
config.streamCount = streams.count
config.streamNames = Array(streams.keys).sorted()
}
if let protocols = configData["protocols"] as? [[String: Any]] {
config.protocolCount = protocols.count
config.enabledProtocolCount = protocols.filter { ($0["port"] as? Int ?? 0) > 0 }.count
}
if let triggers = configData["triggers"] as? [String: Any] {
config.triggerCount = triggers.count
}
// Extract server settings
config.serverName = configData["name"] as? String ?? "MistServer"
config.serverPort = configData["port"] as? Int ?? 4242
config.serverInterface = configData["interface"] as? String ?? "0.0.0.0"
}
return config
}
// MARK: - Data Formatting Utilities
func formatBandwidth(_ bytesPerSec: Int) -> String {
let bits = Double(bytesPerSec) * 8
let units = ["bps", "Kbps", "Mbps", "Gbps"]
var value = bits
var unitIndex = 0
while value >= 1000 && unitIndex < units.count - 1 {
value /= 1000
unitIndex += 1
}
return String(format: "%.1f %@", value, units[unitIndex])
}
func formatBytes(_ bytes: Int) -> String {
let units = ["B", "KB", "MB", "GB", "TB"]
var value = Double(bytes)
var unitIndex = 0
while value >= 1024 && unitIndex < units.count - 1 {
value /= 1024
unitIndex += 1
}
return String(format: "%.1f %@", value, units[unitIndex])
}
func formatDuration(_ seconds: Int) -> String {
let hours = seconds / 3600
let minutes = (seconds % 3600) / 60
let secs = seconds % 60
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, minutes, secs)
} else {
return String(format: "%d:%02d", minutes, secs)
}
}
func formatConnectionTime(_ timestamp: Int) -> String {
let connectionDate = Date(timeIntervalSince1970: TimeInterval(timestamp))
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter.string(from: connectionDate)
}
func formatPercentage(_ value: Double) -> String {
return String(format: "%.1f%%", value)
}
// MARK: - Data Validation
func validateStreamConfiguration(_ config: [String: Any]) -> ValidationResult {
var errors: [String] = []
var warnings: [String] = []
// Check required fields
guard let source = config["source"] as? String, !source.isEmpty else {
errors.append("Stream source is required")
return ValidationResult(isValid: false, errors: errors, warnings: warnings)
}
// Validate source format
if !isValidSourceURL(source) {
warnings.append("Source URL format may not be supported")
}
// Check for common issues
if source.hasPrefix("rtmp://") && !source.contains("/live/") {
warnings.append("RTMP URLs typically require a '/live/' path")
}
return ValidationResult(isValid: errors.isEmpty, errors: errors, warnings: warnings)
}
func validatePushConfiguration(_ config: PushConfiguration) -> ValidationResult {
var errors: [String] = []
var warnings: [String] = []
// Validate target URL
if !isValidTargetURL(config.targetURL) {
errors.append("Invalid target URL format")
}
// Check for common issues
if config.targetURL.hasPrefix("rtmp://") && !config.targetURL.contains("/live/") {
warnings.append("RTMP URLs typically require a '/live/' path")
}
return ValidationResult(isValid: errors.isEmpty, errors: errors, warnings: warnings)
}
private func isValidSourceURL(_ url: String) -> Bool {
let supportedSchemes = ["rtmp://", "rtsp://", "http://", "https://", "push://", "file://", "/"]
return supportedSchemes.contains { url.hasPrefix($0) }
}
private func isValidTargetURL(_ url: String) -> Bool {
let supportedSchemes = ["rtmp://", "rtsp://", "http://", "https://"]
return supportedSchemes.contains { url.hasPrefix($0) }
}
// MARK: - Data Aggregation
func aggregateStreamStatistics(_ streamStats: [String: Any]) -> StreamAggregateStats {
var totalClients = 0
var totalBandwidth = 0
var totalUptime = 0
var streamCount = 0
for (_, stats) in streamStats {
guard let streamData = stats as? [String: Any] else { continue }
totalClients += streamData["clients"] as? Int ?? 0
totalBandwidth += streamData["bps_out"] as? Int ?? 0
totalUptime += streamData["uptime"] as? Int ?? 0
streamCount += 1
}
let averageUptime = streamCount > 0 ? totalUptime / streamCount : 0
return StreamAggregateStats(
totalStreams: streamCount,
totalClients: totalClients,
totalBandwidth: totalBandwidth,
averageUptime: averageUptime,
formattedBandwidth: formatBandwidth(totalBandwidth),
formattedAverageUptime: formatDuration(averageUptime)
)
}
// MARK: - Raw Data Processing (from AppDelegate)
func processAllStreams(_ streamsData: Any?) -> [String: Any] {
// Handle null values gracefully (normal for fresh server)
if streamsData == nil || streamsData is NSNull {
return [:]
}
guard var streams = streamsData as? [String: Any] else {
return [:]
}
// Filter out "incomplete list" marker from MistServer partial responses
streams.removeValue(forKey: "incomplete list")
return streams
}
func processStreamStats(_ statsData: Any?) -> [String: Any] {
if statsData == nil || statsData is NSNull {
return [:]
}
guard let stats = statsData as? [String: Any] else {
return [:]
}
return stats
}
func processPushList(_ pushListData: Any?) -> [String: Any] {
// Handle null values gracefully (normal for fresh server)
if pushListData == nil || pushListData is NSNull {
return [:]
}
// MistServer push_list returns array of arrays:
// [[ID, stream, target_original, target_resolved, logs, stats], ...]
if let pushArray = pushListData as? [[Any]] {
var result: [String: Any] = [:]
for entry in pushArray {
guard entry.count >= 4 else { continue }
let pushId: Int
if let id = entry[0] as? Int {
pushId = id
} else if let id = entry[0] as? NSNumber {
pushId = id.intValue
} else {
continue
}
let stream = entry[1] as? String ?? "unknown"
let target = entry[2] as? String ?? "unknown"
let resolvedTarget = entry[3] as? String ?? target
var pushInfo: [String: Any] = [
"id": pushId,
"stream": stream,
"target": target,
"resolved_target": resolvedTarget,
]
// Index 4: logs array [[timestamp, level, message], ...]
if entry.count > 4, let logs = entry[4] as? [[Any]] {
pushInfo["logs"] = logs
}
// Index 5: stats object (keep nested, don't flatten)
if entry.count > 5, let stats = entry[5] as? [String: Any] {
pushInfo["stats"] = stats
}
result[String(pushId)] = pushInfo
}
return result
}
// Fallback: try dict format for backwards compatibility
if let pushes = pushListData as? [String: Any] {
return pushes
}
return [:]
}
func processClients(_ clientsData: Any?) -> [String: Any] {
if clientsData == nil || clientsData is NSNull {
return [:]
}
// Handle MistServer's clients data structure: {"data": <null>, "fields": [...], "time": 123}
if let clientsDict = clientsData as? [String: Any] {
let fields = clientsDict["fields"] as? [String] ?? []
if let data = clientsDict["data"], data is NSNull {
return [:]
} else if let dataArray = clientsDict["data"] as? [[Any]], !fields.isEmpty {
// Array-of-arrays format (MistServer 3.9+): each row is a client, no IDs
var result: [String: Any] = [:]
for (index, row) in dataArray.enumerated() {
var info: [String: Any] = [:]
for (i, field) in fields.enumerated() where i < row.count {
info[field] = row[i]
}
result["client_\(index)"] = info
}
return result
} else if let data = clientsDict["data"] as? [String: Any] {
// Data may be {clientId: {field: value}} or {clientId: [value1, value2, ...]}
var result: [String: Any] = [:]
for (clientId, clientValue) in data {
if let info = clientValue as? [String: Any] {
// Already a named dict
result[clientId] = info
} else if let values = clientValue as? [Any], !fields.isEmpty {
// Positional array — map to named dict using fields
var info: [String: Any] = [:]
for (index, field) in fields.enumerated() where index < values.count {
info[field] = values[index]
}
result[clientId] = info
}
}
return result
} else if !fields.isEmpty {
// No "data" key but has fields — try the dict itself minus metadata keys
var result: [String: Any] = [:]
for (key, value) in clientsDict where key != "fields" && key != "time" {
if let values = value as? [Any] {
var info: [String: Any] = [:]
for (index, field) in fields.enumerated() where index < values.count {
info[field] = values[index]
}
result[key] = info
} else if let info = value as? [String: Any] {
result[key] = info
}
}
return result
} else {
return clientsDict
}
}
guard let clients = clientsData as? [String: Any] else {
return [:]
}
return clients
}
}
// MARK: - Data Structures
struct ProcessedStreamData {
let activeStreams: [String]
let streamStats: [String: Any]
let allStreams: [String: Any]
let serverTotals: [String: Any]
}
struct ProcessedPushData {
let activePushes: [String: Any]
}
struct ProcessedClientData {
let connectedClients: [String: Any]
let clientsByStream: [String: [String: Any]]
}
struct ProcessedProtocolData {
let protocolConfig: [String: Any]
let enabledProtocols: [String]
let disabledProtocols: [String]
}
struct ProcessedServerStats {
var totalClients: Int = 0
var totalBandwidth: Int = 0
var uptime: Int = 0
var totalStreams: Int = 0
var memoryUsage: Int = 0
var memoryTotal: Int = 0
var cpuUsage: Double = 0.0
var formattedBandwidth: String = ""
var formattedUptime: String = ""
var formattedMemory: String = ""
var formattedCPU: String = ""
}
struct ProcessedConfigData {
var rawConfig: [String: Any] = [:]
var streamCount: Int = 0
var streamNames: [String] = []
var protocolCount: Int = 0
var enabledProtocolCount: Int = 0
var triggerCount: Int = 0
var serverName: String = ""
var serverPort: Int = 0
var serverInterface: String = ""
}
struct ValidationResult {
let isValid: Bool
let errors: [String]
let warnings: [String]
}
struct StreamAggregateStats {
let totalStreams: Int
let totalClients: Int
let totalBandwidth: Int
let averageUptime: Int
let formattedBandwidth: String
let formattedAverageUptime: String
}