Repository Public
1// SP Drive iOS2// File: Sync/LocalFiles.swift3// Description: Where file contents live on the device. Offline copies and files waiting to be sent sit in Application Support (never purged4// by the system); copies opened once sit in Caches (the system may reclaim them). Names are sanitised: no path can escape its folder.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public struct LocalFiles: Sendable {11 public let persistent: URL12 public let cache: URL1314 public init(persistent: URL, cache: URL) {15 self.persistent = persistent16 self.cache = cache17 for d in [offlineRoot, outbox, partials, chunks, staging, cacheRoot, thumbnails] { try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }18 // re-downloadable content stays out of device backups19 var o = offlineRoot20 var v = URLResourceValues()21 v.isExcludedFromBackup = true22 try? o.setResourceValues(v)23 }2425 /// The app's layout.26 public static func app() -> LocalFiles {27 LocalFiles(persistent: AppGroup.appSupport, cache: FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("SPDrive", isDirectory: true))28 }2930 public var offlineRoot: URL { persistent.appendingPathComponent("Offline", isDirectory: true) }31 /// Snapshots of files being uploaded.32 public var outbox: URL { persistent.appendingPathComponent("Outbox", isDirectory: true) }33 public var partials: URL { persistent.appendingPathComponent("Partials", isDirectory: true) }34 public var chunks: URL { persistent.appendingPathComponent("Chunks", isDirectory: true) }35 public var staging: URL { persistent.appendingPathComponent("Staging", isDirectory: true) }36 public var cacheRoot: URL { cache.appendingPathComponent("Files", isDirectory: true) }37 public var thumbnails: URL { cache.appendingPathComponent("Thumbnails", isDirectory: true) }3839 /// A single safe path component: separators and control characters replaced, never "." or "..", never empty.40 public static func safeName(_ raw: String) -> String {41 var s = raw.precomposedStringWithCanonicalMapping42 s = String(s.unicodeScalars.map { u in (u.value < 0x20 || u.value == 0x7f || u == "/" || u == ":" || u == "\\") ? "_" : Character(u) })43 s = s.trimmingCharacters(in: .whitespaces)44 while s.hasPrefix(".") { s.removeFirst() }45 if s.isEmpty { s = "sans-nom" }46 if s.utf8.count > 240 {47 let ext = (s as NSString).pathExtension48 var stem = (s as NSString).deletingPathExtension49 while stem.utf8.count > 230 - ext.utf8.count { stem.removeLast() }50 s = ext.isEmpty ? stem : "\(stem).\(ext)"51 }52 return s53 }5455 static func safeID(_ id: String) -> String { String(id.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) || $0 == "-" }.prefix(80).map(Character.init)) }5657 public func directory(for itemID: String, location: LocalState.Location) -> URL {58 (location == .offline ? offlineRoot : cacheRoot).appendingPathComponent(Self.safeID(itemID), isDirectory: true)59 }60 public func url(for state: LocalState) -> URL? {61 guard let loc = state.location, let name = state.fileName else { return nil }62 return directory(for: state.itemID, location: loc).appendingPathComponent(Self.safeName(name))63 }64 public func partial(_ transferID: String) -> URL { partials.appendingPathComponent(Self.safeID(transferID)) }65 public func resumeData(_ transferID: String) -> URL { partials.appendingPathComponent(Self.safeID(transferID) + ".resume") }66 public func chunk(_ transferID: String) -> URL { chunks.appendingPathComponent(Self.safeID(transferID)) }67 public func outboxFile(_ transferID: String) -> URL { outbox.appendingPathComponent(Self.safeID(transferID)) }68 public func thumbnail(itemID: String, sha: String) -> URL { thumbnails.appendingPathComponent("\(Self.safeID(itemID))-\(sha.prefix(16)).jpg") }6970 /// Puts `source` in place as the local copy of an item (replacing any previous copy at that location). Returns the stored file name.71 @discardableResult72 public func install(_ source: URL, itemID: String, name: String, location: LocalState.Location, move: Bool) throws -> String {73 let fm = FileManager.default74 let dir = directory(for: itemID, location: location)75 try? fm.removeItem(at: dir)76 try fm.createDirectory(at: dir, withIntermediateDirectories: true)77 let safe = Self.safeName(name)78 let dest = dir.appendingPathComponent(safe)79 if move { try fm.moveItem(at: source, to: dest) } else { try fm.copyItem(at: source, to: dest) }80 try? fm.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: dest.path)81 return safe82 }8384 public func removeCopy(itemID: String, location: LocalState.Location) {85 try? FileManager.default.removeItem(at: directory(for: itemID, location: location))86 }8788 public func removeTransferFiles(_ transferID: String) {89 for u in [partial(transferID), resumeData(transferID), chunk(transferID), outboxFile(transferID)] { try? FileManager.default.removeItem(at: u) }90 }9192 public func removeEverything() {93 for d in [offlineRoot, outbox, partials, chunks, staging, cacheRoot, thumbnails] {94 try? FileManager.default.removeItem(at: d)95 try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)96 }97 }9899 public static func directorySize(_ url: URL) -> Int64 {100 guard let e = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]) else { return 0 }101 var total: Int64 = 0102 for case let f as URL in e {103 if let v = try? f.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]), v.isRegularFile == true { total += Int64(v.totalFileAllocatedSize ?? 0) }104 }105 return total106 }107}108