-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFileManagerViewModel.swift
416 lines (377 loc) · 15.1 KB
/
FileManagerViewModel.swift
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
import Foundation
import Combine
import UIKit
import MobileCoreServices
import ObjectiveC
import CoreServices
enum FilePermission: String, CaseIterable {
case userRead = "User Read"
case userWrite = "User Write"
case userExecute = "User Execute"
case groupRead = "Group Read"
case groupWrite = "Group Write"
case groupExecute = "Group Execute"
case othersRead = "Others Read"
case othersWrite = "Others Write"
case othersExecute = "Others Execute"
}
struct FileMetadata {
let name: String
let size: String
let creationDate: String
let modificationDate: String
}
class FileManagerViewModel: ObservableObject {
@Published var items: [FileSystemItem] = []
@Published var filteredItems: [FileSystemItem] = []
@Published var rootItems: [FileSystemItem] = []
@Published var selectedItems: Set<UUID> = []
@Published var selectedFile: FileSystemItem?
@Published var sortOption: SortOption = .name {
didSet {
sortItems()
}
}
@Published var showHiddenFiles: Bool = false {
didSet {
filterItems()
}
}
@Published var searchQuery: String = "" {
didSet {
if searchScope == .current {
filterItems()
}
}
}
@Published var searchScope: SearchScope = .current {
didSet {
if searchScope == .root && !searchQuery.isEmpty {
loadRootFiles()
} else {
cancelRootSearch()
filterItems()
}
}
}
@Published var isSearching: Bool = false
var directory: URL
private let fileManager = FileManager.default
private var rootSearchCancellable: AnyCancellable?
init(directory: URL = URL(fileURLWithPath: "/var")) {
self.directory = directory
loadFiles()
}
func formattedFileSize(_ size: Int) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = [.useKB, .useMB, .useGB]
formatter.countStyle = .file
return formatter.string(fromByteCount: Int64(size))
}
func loadFiles() {
isSearching = true
DispatchQueue.global(qos: .userInitiated).async {
do {
let directoryContents = try self.fileManager.contentsOfDirectory(at: self.directory, includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey, .creationDateKey, .contentModificationDateKey, .isSymbolicLinkKey], options: [])
// Clear items before reloading
DispatchQueue.main.async {
self.items.removeAll()
}
for url in directoryContents {
let resourceValues = try? url.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey, .creationDateKey, .contentModificationDateKey, .isSymbolicLinkKey])
let isDirectory = resourceValues?.isDirectory ?? false
let isSymlink = resourceValues?.isSymbolicLink ?? false
let fileSize = resourceValues?.fileSize ?? 0
let creationDate = resourceValues?.creationDate ?? Date()
let modificationDate = resourceValues?.contentModificationDate ?? Date()
let fileSystemItem = FileSystemItem(
name: url.lastPathComponent,
isDirectory: isDirectory,
url: url,
size: fileSize,
creationDate: creationDate,
modificationDate: modificationDate,
isSymlink: isSymlink
)
DispatchQueue.main.async {
self.items.append(fileSystemItem)
}
}
DispatchQueue.main.async {
self.sortItems()
self.filterItems()
self.isSearching = false
}
} catch {
DispatchQueue.main.async {
self.isSearching = false
print("Failed to load files: \(error.localizedDescription)")
}
}
}
}
func showFilePermissions(for item: FileSystemItem) {
selectedFile = item
}
func getFileSize(at url: URL) -> String {
do {
let attributes = try fileManager.attributesOfItem(atPath: url.path)
if let size = attributes[.size] as? NSNumber {
return ByteCountFormatter.string(fromByteCount: size.int64Value, countStyle: .file)
}
} catch {
print("Failed to get file size: \(error.localizedDescription)")
}
return "Unknown"
}
func getCreationDate(at url: URL) -> String {
do {
let attributes = try fileManager.attributesOfItem(atPath: url.path)
if let date = attributes[.creationDate] as? Date {
return DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)
}
} catch {
print("Failed to get creation date: \(error.localizedDescription)")
}
return "Unknown"
}
func getModificationDate(at url: URL) -> String {
do {
let attributes = try fileManager.attributesOfItem(atPath: url.path)
if let date = attributes[.modificationDate] as? Date {
return DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)
}
} catch {
print("Failed to get modification date: \(error.localizedDescription)")
}
return "Unknown"
}
func getFileMetadata(at url: URL) -> FileMetadata {
let name = url.lastPathComponent
let size = getFileSize(at: url)
let creationDate = getCreationDate(at: url)
let modificationDate = getModificationDate(at: url)
return FileMetadata(name: name, size: size, creationDate: creationDate, modificationDate: modificationDate)
}
func isPermissionGranted(for url: URL, permission: FilePermission) -> Bool {
do {
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
let posixInt = posixPermissions.uint16Value
switch permission {
case .userRead:
return (posixInt & UInt16(S_IRUSR)) != 0
case .userWrite:
return (posixInt & UInt16(S_IWUSR)) != 0
case .userExecute:
return (posixInt & UInt16(S_IXUSR)) != 0
case .groupRead:
return (posixInt & UInt16(S_IRGRP)) != 0
case .groupWrite:
return (posixInt & UInt16(S_IWGRP)) != 0
case .groupExecute:
return (posixInt & UInt16(S_IXGRP)) != 0
case .othersRead:
return (posixInt & UInt16(S_IROTH)) != 0
case .othersWrite:
return (posixInt & UInt16(S_IWOTH)) != 0
case .othersExecute:
return (posixInt & UInt16(S_IXOTH)) != 0
}
}
} catch {
print("Failed to retrieve file attributes: \(error.localizedDescription)")
}
return false
}
func toggleFilePermission(at url: URL, permission: FilePermission) {
do {
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
var posixInt = posixPermissions.uint16Value
switch permission {
case .userRead:
posixInt ^= UInt16(S_IRUSR)
case .userWrite:
posixInt ^= UInt16(S_IWUSR)
case .userExecute:
posixInt ^= UInt16(S_IXUSR)
case .groupRead:
posixInt ^= UInt16(S_IRGRP)
case .groupWrite:
posixInt ^= UInt16(S_IWGRP)
case .groupExecute:
posixInt ^= UInt16(S_IXGRP)
case .othersRead:
posixInt ^= UInt16(S_IROTH)
case .othersWrite:
posixInt ^= UInt16(S_IWOTH)
case .othersExecute:
posixInt ^= UInt16(S_IXOTH)
}
let newPermissions = NSNumber(value: posixInt)
try FileManager.default.setAttributes([.posixPermissions: newPermissions], ofItemAtPath: url.path)
}
} catch {
print("Failed to toggle file permission: \(error.localizedDescription)")
}
}
func loadRootFiles() {
isSearching = true
rootSearchCancellable?.cancel()
let searchResults = FileSearchResults()
rootSearchCancellable = searchResults.$items
.receive(on: DispatchQueue.main)
.sink { [weak self] items in
self?.rootItems = items
self?.isSearching = false
self?.filterItems()
}
self.results.removeAll()
startRefreshTimer(searchResults: searchResults)
startRecursion()
}
private var refreshTimer: Timer?
private var workItem: DispatchWorkItem?
private var results = [FileSystemItem]()
func startRecursion() {
workItem?.cancel()
workItem = DispatchWorkItem {
if self.workItem?.isCancelled == true { return }
self.recursiveFileSearch(at: URL(fileURLWithPath: "/"), workItem: self.workItem!)
}
DispatchQueue.global().async(execute: workItem!)
}
func startRefreshTimer(searchResults: FileSearchResults) {
refreshTimer?.invalidate()
refreshTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
let elementsToTransfer = min(1000, self.results.count)
let batch = self.results.prefix(elementsToTransfer)
searchResults.items.append(contentsOf: batch)
self.results.removeFirst(elementsToTransfer)
}
}
private func recursiveFileSearch(at url: URL, workItem: DispatchWorkItem) {
var tempResults = [FileSystemItem]()
do {
let contents = try fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey, .creationDateKey, .contentModificationDateKey, .isSymbolicLinkKey], options: [])
for (_, item) in contents.enumerated() {
if workItem.isCancelled == true { return }
let resourceValues = try? item.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey, .creationDateKey, .contentModificationDateKey, .isSymbolicLinkKey])
let isDirectory = resourceValues?.isDirectory ?? false
let isSymlink = resourceValues?.isSymbolicLink ?? false
let fileSize = resourceValues?.fileSize ?? 0
let creationDate = resourceValues?.creationDate ?? Date()
let modificationDate = resourceValues?.contentModificationDate ?? Date()
let fileSystemItem = FileSystemItem(name: item.lastPathComponent, isDirectory: isDirectory, url: item, size: fileSize, creationDate: creationDate, modificationDate: modificationDate, isSymlink: isSymlink)
tempResults.append(fileSystemItem)
if isDirectory {
recursiveFileSearch(at: item, workItem: workItem)
}
}
DispatchQueue.main.async {
self.results.append(contentsOf: tempResults)
}
} catch {
print("Failed to search files: \(error.localizedDescription)")
}
}
private func cancelRootSearch() {
rootSearchCancellable?.cancel()
isSearching = false
}
func sortItems() {
switch sortOption {
case .name:
items.sort { $0.name.lowercased() < $1.name.lowercased() }
rootItems.sort { $0.name.lowercased() < $1.name.lowercased() }
case .date:
items.sort { $0.creationDate < $1.creationDate }
rootItems.sort { $0.creationDate < $1.creationDate }
case .modified:
items.sort { $0.modificationDate < $1.modificationDate }
rootItems.sort { $0.modificationDate < $1.modificationDate }
case .size:
items.sort { $0.size > $1.size }
rootItems.sort { $0.size > $1.size }
case .reverseName:
items.sort { $0.name.lowercased() > $1.name.lowercased() }
rootItems.sort { $0.name.lowercased() > $1.name.lowercased() }
}
filterItems()
}
func filterItems() {
let sourceItems: [FileSystemItem]
switch searchScope {
case .current:
sourceItems = items
case .root:
sourceItems = rootItems
}
let filteredByQuery: [FileSystemItem]
if searchQuery.isEmpty {
filteredByQuery = searchScope == .current ? sourceItems : []
} else {
filteredByQuery = sourceItems.filter { $0.name.lowercased().contains(searchQuery.lowercased()) }
}
if showHiddenFiles {
filteredItems = filteredByQuery
} else {
filteredItems = filteredByQuery.filter { !$0.name.hasPrefix(".") }
}
}
func deleteFile(at url: URL) {
do {
try fileManager.removeItem(at: url)
loadFiles()
} catch {
print("Failed to delete file: \(error.localizedDescription)")
}
}
func deleteSelectedFiles() {
for id in selectedItems {
if let item = items.first(where: { $0.id == id }) {
deleteFile(at: item.url)
}
}
selectedItems.removeAll()
loadFiles()
}
func createFile(named fileName: String) {
let fileURL = directory.appendingPathComponent(fileName)
let content = "This is a new file."
do {
try content.write(to: fileURL, atomically: true, encoding: .utf8)
loadFiles()
} catch {
print("Failed to create file: \(error.localizedDescription)")
}
}
func createFolder(named folderName: String) {
let folderURL = directory.appendingPathComponent(folderName)
do {
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
loadFiles()
} catch {
print("Failed to create folder: \(error.localizedDescription)")
}
}
func renameFile(at url: URL, to newName: String) {
let newURL = url.deletingLastPathComponent().appendingPathComponent(newName)
do {
try fileManager.moveItem(at: url, to: newURL)
loadFiles()
} catch {
print("Failed to rename file: \(error.localizedDescription)")
}
}
func copyFile(at url: URL, to newName: String) {
let newURL = url.deletingLastPathComponent().appendingPathComponent(newName)
do {
try fileManager.copyItem(at: url, to: newURL)
loadFiles()
} catch {
print("Failed to copy file: \(error.localizedDescription)")
}
}
}