|
| 1 | +// |
| 2 | +// FileCache.swift |
| 3 | +// RemoteCloud |
| 4 | +// |
| 5 | +// Created by rei8 on 2019/11/20. |
| 6 | +// Copyright © 2019 lithium03. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | +import CoreData |
| 11 | + |
| 12 | +public class FileCache { |
| 13 | + public var cacheMaxSize: Int { |
| 14 | + get { |
| 15 | + return UserDefaults.standard.integer(forKey: "networkCacheSize") |
| 16 | + } |
| 17 | + set { |
| 18 | + UserDefaults.standard.set(newValue, forKey: "networkCacheSize") |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public func getCache(storage: String, id: String, offset: Int64, size: Int64) -> URL? { |
| 23 | + var ret: URL? = nil |
| 24 | + guard cacheMaxSize > 0 else { |
| 25 | + return nil |
| 26 | + } |
| 27 | + if Thread.isMainThread { |
| 28 | + guard let orgItem = CloudFactory.shared.data.getData(storage: storage, fileId: id) else { |
| 29 | + return nil |
| 30 | + } |
| 31 | + |
| 32 | + let viewContext = self.persistentContainer.viewContext |
| 33 | + |
| 34 | + let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FileCacheItem") |
| 35 | + fetchrequest.predicate = NSPredicate(format: "storage == %@ && id == %@ && chunkOffset == %lld", storage, id, offset) |
| 36 | + do{ |
| 37 | + guard let item = try viewContext.fetch(fetchrequest).first as? FileCacheItem else { |
| 38 | + return nil |
| 39 | + } |
| 40 | + if orgItem.mdate != item.mdate || orgItem.size != item.orgSize { |
| 41 | + if let target = item.filename?.uuidString { |
| 42 | + let base = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("NetCache", isDirectory: true) |
| 43 | + let target_path = base.appendingPathComponent(String(target.prefix(2)), isDirectory: true).appendingPathComponent(String(target.prefix(4).suffix(2)), isDirectory: true).appendingPathComponent(target) |
| 44 | + try FileManager.default.removeItem(at: target_path) |
| 45 | + } |
| 46 | + viewContext.delete(item) |
| 47 | + try viewContext.save() |
| 48 | + return nil |
| 49 | + } |
| 50 | + if let target = item.filename?.uuidString, (size == item.chunkSize || size < 0) { |
| 51 | + let base = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("NetCache", isDirectory: true) |
| 52 | + let target_path = base.appendingPathComponent(String(target.prefix(2)), isDirectory: true).appendingPathComponent(String(target.prefix(4).suffix(2)), isDirectory: true).appendingPathComponent(target) |
| 53 | + if FileManager.default.fileExists(atPath: target_path.path) { |
| 54 | + ret = target_path |
| 55 | + item.rdate = Date() |
| 56 | + try? viewContext.save() |
| 57 | + } |
| 58 | + else { |
| 59 | + viewContext.delete(item) |
| 60 | + try viewContext.save() |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + catch{ |
| 65 | + return nil |
| 66 | + } |
| 67 | + return ret |
| 68 | + } |
| 69 | + else { |
| 70 | + DispatchQueue.main.sync { |
| 71 | + ret = getCache(storage: storage, id: id, offset: offset, size: size) |
| 72 | + } |
| 73 | + return ret |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + public func saveCache(storage: String, id: String, offset: Int64, data: Data) { |
| 78 | + guard cacheMaxSize > 0 else { |
| 79 | + increseFreeSpace() |
| 80 | + return |
| 81 | + } |
| 82 | + do { |
| 83 | + let size = Int64(data.count) |
| 84 | + let base = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("NetCache", isDirectory: true) |
| 85 | + let newId = UUID() |
| 86 | + let target = newId.uuidString |
| 87 | + let target_path = base.appendingPathComponent(String(target.prefix(2)), isDirectory: true).appendingPathComponent(String(target.prefix(4).suffix(2)), isDirectory: true) |
| 88 | + try FileManager.default.createDirectory(at: target_path, withIntermediateDirectories: true, attributes: nil) |
| 89 | + try data.write(to: target_path.appendingPathComponent(target)) |
| 90 | + |
| 91 | + if getCacheSize() > cacheMaxSize { |
| 92 | + increseFreeSpace() |
| 93 | + } |
| 94 | + |
| 95 | + DispatchQueue.main.async { |
| 96 | + guard let orgItem = CloudFactory.shared.data.getData(storage: storage, fileId: id) else { |
| 97 | + try? FileManager.default.removeItem(at: target_path.appendingPathComponent(target)) |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + let viewContext = self.persistentContainer.viewContext |
| 102 | + |
| 103 | + let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FileCacheItem") |
| 104 | + fetchrequest.predicate = NSPredicate(format: "storage == %@ && id == %@ && chunkOffset == %lld && chunkSize == %lld", storage, id, offset, size) |
| 105 | + do { |
| 106 | + if let items = try viewContext.fetch(fetchrequest) as? [FileCacheItem], items.count > 0 { |
| 107 | + try FileManager.default.removeItem(at: target_path.appendingPathComponent(target)) |
| 108 | + return |
| 109 | + } |
| 110 | + } |
| 111 | + catch { |
| 112 | + print(error) |
| 113 | + } |
| 114 | + |
| 115 | + let newitem = FileCacheItem(context: viewContext) |
| 116 | + newitem.filename = newId |
| 117 | + newitem.storage = storage |
| 118 | + newitem.id = id |
| 119 | + newitem.chunkSize = size |
| 120 | + newitem.chunkOffset = offset |
| 121 | + newitem.rdate = Date() |
| 122 | + newitem.mdate = orgItem.mdate |
| 123 | + newitem.orgSize = orgItem.size |
| 124 | + |
| 125 | + try? viewContext.save() |
| 126 | + } |
| 127 | + } |
| 128 | + catch { |
| 129 | + print(error) |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + public func increseFreeSpace() { |
| 134 | + guard let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSTemporaryDirectory()) else { |
| 135 | + return |
| 136 | + } |
| 137 | + let freesize = (attributes[.systemFreeSize] as? NSNumber)?.int64Value ?? 0 |
| 138 | + var incSize = getCacheSize() - cacheMaxSize |
| 139 | + if freesize < 512*1024*1024 { |
| 140 | + let incSize2 = 512*1024*1024 - Int(freesize) |
| 141 | + if incSize < 0 { |
| 142 | + incSize = incSize2 |
| 143 | + } |
| 144 | + else { |
| 145 | + incSize += incSize2 |
| 146 | + } |
| 147 | + } |
| 148 | + var delSize = 0 |
| 149 | + guard let base = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("NetCache", isDirectory: true) else { |
| 150 | + return |
| 151 | + } |
| 152 | + DispatchQueue.main.async { |
| 153 | + let viewContext = self.persistentContainer.viewContext |
| 154 | + |
| 155 | + let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FileCacheItem") |
| 156 | + fetchrequest.predicate = NSPredicate(value: true) |
| 157 | + fetchrequest.sortDescriptors = [NSSortDescriptor(key: "rdate", ascending: true)] |
| 158 | + do { |
| 159 | + if let items = try viewContext.fetch(fetchrequest) as? [FileCacheItem], items.count > 0 { |
| 160 | + for item in items { |
| 161 | + if delSize > incSize { |
| 162 | + break |
| 163 | + } |
| 164 | + guard let target = item.filename?.uuidString else { |
| 165 | + continue |
| 166 | + } |
| 167 | + let target_path = base.appendingPathComponent(String(target.prefix(2)), isDirectory: true).appendingPathComponent(String(target.prefix(4).suffix(2)), isDirectory: true).appendingPathComponent(target) |
| 168 | + try FileManager.default.removeItem(at: target_path) |
| 169 | + delSize += Int(item.chunkSize) |
| 170 | + viewContext.delete(item) |
| 171 | + } |
| 172 | + try viewContext.save() |
| 173 | + } |
| 174 | + } |
| 175 | + catch { |
| 176 | + print(error) |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + public func getCacheSize() -> Int { |
| 182 | + guard let base = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("NetCache", isDirectory: true) else { |
| 183 | + return 0 |
| 184 | + } |
| 185 | + |
| 186 | + let resourceKeys = Set<URLResourceKey>([.fileAllocatedSizeKey]) |
| 187 | + let directoryEnumerator = FileManager.default.enumerator(at: base, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)! |
| 188 | + |
| 189 | + var allocSize = 0 |
| 190 | + for case let fileURL as URL in directoryEnumerator { |
| 191 | + guard let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys), |
| 192 | + let size = resourceValues.fileAllocatedSize |
| 193 | + else { |
| 194 | + continue |
| 195 | + } |
| 196 | + allocSize += size |
| 197 | + } |
| 198 | + return allocSize |
| 199 | + } |
| 200 | + |
| 201 | + // MARK: - Core Data stack |
| 202 | + public lazy var persistentContainer: NSPersistentContainer = { |
| 203 | + /* |
| 204 | + The persistent container for the application. This implementation |
| 205 | + creates and returns a container, having loaded the store for the |
| 206 | + application to it. This property is optional since there are legitimate |
| 207 | + error conditions that could cause the creation of the store to fail. |
| 208 | + */ |
| 209 | + let modelURL = Bundle(for: CloudFactory.self).url(forResource: "cache", withExtension: "momd")! |
| 210 | + let mom = NSManagedObjectModel(contentsOf: modelURL)! |
| 211 | + |
| 212 | + let container = NSPersistentContainer(name: "cache", managedObjectModel: mom) |
| 213 | + let location = container.persistentStoreDescriptions.first!.url! |
| 214 | + let description = NSPersistentStoreDescription(url: location) |
| 215 | + description.shouldInferMappingModelAutomatically = true |
| 216 | + description.shouldMigrateStoreAutomatically = true |
| 217 | + description.setOption(FileProtectionType.completeUnlessOpen as NSObject, forKey: NSPersistentStoreFileProtectionKey) |
| 218 | + container.persistentStoreDescriptions = [description] |
| 219 | + |
| 220 | + container.loadPersistentStores(completionHandler: { (storeDescription, error) in |
| 221 | + if let error = error as NSError? { |
| 222 | + // Replace this implementation with code to handle the error appropriately. |
| 223 | + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. |
| 224 | + |
| 225 | + /* |
| 226 | + Typical reasons for an error here include: |
| 227 | + * The parent directory does not exist, cannot be created, or disallows writing. |
| 228 | + * The persistent store is not accessible, due to permissions or data protection when the device is locked. |
| 229 | + * The device is out of space. |
| 230 | + * The store could not be migrated to the current model version. |
| 231 | + Check the error message to determine what the actual problem was. |
| 232 | + */ |
| 233 | + fatalError("Unresolved error \(error), \(error.userInfo)") |
| 234 | + } |
| 235 | + }) |
| 236 | + return container |
| 237 | + }() |
| 238 | + |
| 239 | + // MARK: - Core Data Saving support |
| 240 | + |
| 241 | + public func saveContext () { |
| 242 | + let context = persistentContainer.viewContext |
| 243 | + if context.hasChanges { |
| 244 | + do { |
| 245 | + try context.save() |
| 246 | + } catch { |
| 247 | + // Replace this implementation with code to handle the error appropriately. |
| 248 | + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. |
| 249 | + let nserror = error as NSError |
| 250 | + fatalError("Unresolved error \(nserror), \(nserror.userInfo)") |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | +} |
0 commit comments