-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilityManager.swift
More file actions
305 lines (251 loc) · 7.91 KB
/
UtilityManager.swift
File metadata and controls
305 lines (251 loc) · 7.91 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
//
// UtilityManager.swift
// MistTray
//
import Cocoa
import Foundation
class UtilityManager {
static let shared = UtilityManager()
private init() {}
// MARK: - Data Processing
func formatBytes(_ bytes: Int) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = [.useKB, .useMB, .useGB, .useTB]
formatter.countStyle = .file
return formatter.string(fromByteCount: Int64(bytes))
}
func formatConnectionTime(_ seconds: Int) -> String {
let hours = seconds / 3600
let minutes = (seconds % 3600) / 60
let secs = seconds % 60
if hours > 0 {
return String(format: "%02d:%02d:%02d", hours, minutes, secs)
} else {
return String(format: "%02d:%02d", minutes, secs)
}
}
func formatBandwidth(_ bps: Int) -> String {
let kbps = Double(bps) / 1024.0
let mbps = kbps / 1024.0
let gbps = mbps / 1024.0
if gbps >= 1.0 {
return String(format: "%.2f Gbps", gbps)
} else if mbps >= 1.0 {
return String(format: "%.2f Mbps", mbps)
} else if kbps >= 1.0 {
return String(format: "%.1f Kbps", kbps)
} else {
return "\(bps) bps"
}
}
// MARK: - Shell Commands
func runShellCommand(_ command: String) -> (output: String, exitCode: Int32) {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/sh"
do {
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""
return (
output: output.trimmingCharacters(in: .whitespacesAndNewlines),
exitCode: task.terminationStatus
)
} catch {
return (output: "Error: \(error.localizedDescription)", exitCode: -1)
}
}
func runShellCommandAsync(_ command: String, completion: @escaping (String, Int32) -> Void) {
DispatchQueue.global(qos: .background).async {
let result = self.runShellCommand(command)
DispatchQueue.main.async {
completion(result.output, result.exitCode)
}
}
}
// MARK: - File Operations
func createDirectoryIfNeeded(at url: URL) -> Bool {
do {
try FileManager.default.createDirectory(
at: url, withIntermediateDirectories: true, attributes: nil)
return true
} catch {
print("Failed to create directory: \(error)")
return false
}
}
func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
func removeFile(at path: String) -> Bool {
do {
try FileManager.default.removeItem(atPath: path)
return true
} catch {
print("Failed to remove file: \(error)")
return false
}
}
func copyFile(from sourcePath: String, to destinationPath: String) -> Bool {
do {
try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
return true
} catch {
print("Failed to copy file: \(error)")
return false
}
}
// MARK: - URL Validation
func isValidURL(_ urlString: String) -> Bool {
guard let url = URL(string: urlString) else { return false }
return url.scheme != nil && url.host != nil
}
func isValidStreamingURL(_ urlString: String) -> Bool {
let validSchemes = ["rtmp", "rtmps", "srt", "udp", "http", "https", "file"]
guard let url = URL(string: urlString),
let scheme = url.scheme?.lowercased()
else { return false }
return validSchemes.contains(scheme)
}
// MARK: - String Utilities
func sanitizeStreamName(_ name: String) -> String {
// Remove invalid characters for stream names
let allowedCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
return name.components(separatedBy: allowedCharacters.inverted).joined()
}
func truncateString(_ string: String, maxLength: Int) -> String {
if string.count <= maxLength {
return string
}
let truncated = String(string.prefix(maxLength - 3))
return truncated + "..."
}
// MARK: - Network Utilities
func isPortAvailable(_ port: Int) -> Bool {
let result = runShellCommand("lsof -i :\(port)")
return result.output.isEmpty
}
func getLocalIPAddress() -> String? {
let result = runShellCommand(
"ifconfig | grep 'inet ' | grep -v '127.0.0.1' | head -1 | awk '{print $2}'")
return result.output.isEmpty ? nil : result.output
}
// MARK: - System Information
func getSystemInfo() -> SystemInfo {
let osVersion = ProcessInfo.processInfo.operatingSystemVersionString
let hostName = ProcessInfo.processInfo.hostName
let uptime = ProcessInfo.processInfo.systemUptime
return SystemInfo(
osVersion: osVersion,
hostName: hostName,
uptime: Int(uptime),
localIP: getLocalIPAddress()
)
}
// MARK: - Application Utilities
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else { return }
NSWorkspace.shared.open(url)
}
func showInFinder(path: String) {
let url = URL(fileURLWithPath: path)
NSWorkspace.shared.activateFileViewerSelecting([url])
}
func copyToClipboard(_ text: String) {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
}
func getTotalViewers(from clientsData: [String: Any]) -> Int {
return clientsData.count
}
func getDefaultPort() -> Int {
return 4242
}
func generateStatusText(
isRunning: Bool, serverMode: ServerMode, activeStreams: [String], activePushes: [String: Any],
totalViewers: Int
) -> String {
if !isRunning {
if serverMode == .notFound {
return "MistServer: Not Installed"
}
return "MistServer: Stopped"
}
var statusText = "MistServer: Running"
var details: [String] = []
if !activeStreams.isEmpty {
details.append("\(activeStreams.count) streams")
}
if !activePushes.isEmpty {
details.append("\(activePushes.count) pushes")
}
if totalViewers > 0 {
details.append("\(totalViewers) viewers")
}
if !details.isEmpty {
statusText += " (\(details.joined(separator: ", ")))"
}
return statusText
}
// MARK: - System Stats Formatting
func formatSystemStats(_ capabilities: [String: Any]) -> String {
var parts: [String] = []
// CPU usage percentage
if let cpu = capabilities["cpu"] as? [String: Any],
let usage = cpu["use"] as? Int
{
parts.append("CPU: \(usage)%")
} else if let cpuUse = capabilities["cpu_use"] as? Int {
parts.append("CPU: \(cpuUse)%")
}
// Memory: used / total
if let mem = capabilities["mem"] as? [String: Any],
let used = mem["used"] as? Int,
let total = mem["total"] as? Int
{
let usedGB = Double(used) / 1024.0
let totalGB = Double(total) / 1024.0
parts.append(String(format: "RAM: %.1f/%.1f GB", usedGB, totalGB))
}
// Load average
if let load = capabilities["load"] as? [String: Any],
let avg1 = load["one"] as? Double
{
parts.append(String(format: "Load: %.2f", avg1))
} else if let load = capabilities["load"] as? [String: Any],
let avg1 = load["one"] as? Int
{
parts.append("Load: \(avg1)")
}
return parts.joined(separator: " | ")
}
// MARK: - Protocol Utilities
func getDefaultPort(for protocolName: String) -> String {
switch protocolName.uppercased() {
case "RTMP": return "1935"
case "HLS": return "8080"
case "DASH": return "8080"
case "WEBRTC": return "8080"
case "SRT": return "9999"
case "RTSP": return "554"
case "HTTP": return "8080"
case "WEBSOCKET": return "8080"
default: return "8080"
}
}
}
// MARK: - Supporting Types
struct SystemInfo {
let osVersion: String
let hostName: String
let uptime: Int
let localIP: String?
var formattedUptime: String {
return UtilityManager.shared.formatConnectionTime(uptime)
}
}