Skip to content

Commit

Permalink
Move file handling from Documents to Library
Browse files Browse the repository at this point in the history
  • Loading branch information
martenrebane committed Jan 18, 2024
1 parent 8631a99 commit a7324be
Show file tree
Hide file tree
Showing 16 changed files with 106 additions and 95 deletions.
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/ContainerActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ extension ContainerActions where Self: UIViewController {

let cleanUpDataFilesInDocumentsFolderCode: () -> Void = {
containerFilePaths.forEach {
if $0.hasPrefix(MoppFileManager.shared.documentsDirectoryPath()) {
if $0.hasPrefix(MoppFileManager.cacheDirectory.path) {
MoppFileManager.shared.removeFile(withPath: $0)
}
}
Expand Down
3 changes: 2 additions & 1 deletion MoppApp/MoppApp/ContainerViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ class ContainerViewController : MoppViewController, ContainerActions, PreviewAct
isDatafileReloaded = false
clearIsSaveableCache()
NotificationCenter.default.removeObserver(self)
MoppFileManager.removeFiles()
}

@objc func signatureCreatedFinished() {
Expand Down Expand Up @@ -409,7 +410,7 @@ extension ContainerViewController : LandingViewControllerTabButtonsDelegate {
throw NSError(domain: "ContainerFileDataEmptyError", code: 1)
}

let destinationPath = URL(fileURLWithPath: MoppFileManager.shared.tempDocumentsDirectoryPath(), isDirectory: true).appendingPathComponent(URL(fileURLWithPath: containerPath).lastPathComponent)
let destinationPath = MoppFileManager.shared.tempCacheDirectoryPath().appendingPathComponent(URL(fileURLWithPath: containerPath).lastPathComponent)

if !FileManager.default.fileExists(atPath: destinationPath.path) {
MoppFileManager.shared.createFile(atPath: destinationPath.path, contents: fileData)
Expand Down
4 changes: 2 additions & 2 deletions MoppApp/MoppApp/CryptoViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ class CryptoViewController : MoppViewController {
}

@IBAction func importFilesAction() {
let tempPath = MoppFileManager.shared.tempDocumentsDirectoryPath()
MoppFileManager.shared.removeFile(withPath: tempPath)
let tempPath = MoppFileManager.shared.tempCacheDirectoryPath()
MoppFileManager.shared.removeFile(withPath: tempPath.path)

NotificationCenter.default.post(
name: .startImportingFilesWithDocumentPickerNotificationName,
Expand Down
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/DiagnosticsViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ class DiagnosticsViewController: MoppViewController, UIDocumentPickerDelegate {
}

private func saveDiagnosticsToFile(fileName: String, diagnosticsText: String) {
let fileLocation: URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(fileName)
let fileLocation: URL? = MoppFileManager.cacheDirectory.appendingPathComponent(fileName)

if let fileUrl = fileLocation {
printLog("Diagnostics file location: \(fileUrl)")
Expand Down
6 changes: 3 additions & 3 deletions MoppApp/MoppApp/FileDownloader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ class FileDownloader: NSObject, URLSessionDelegate {
if error != nil { printLog("Unable to download file: \(error?.localizedDescription ?? "Unable to display error")"); return completion(nil) }
if let fileTempUrl: URL = fileTempUrl {
do {
let documentsPathFileURL: URL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("Downloads", isDirectory: true).appendingPathComponent(url.lastPathComponent)
try FileManager.default.createDirectory(at: documentsPathFileURL, withIntermediateDirectories: true, attributes: nil)
let fileLocation: String = MoppFileManager.shared.copyFile(withPath: fileTempUrl.path, toPath: documentsPathFileURL.path)
let cachePathFileURL: URL = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("Downloads", isDirectory: true).appendingPathComponent(url.lastPathComponent)
try FileManager.default.createDirectory(at: cachePathFileURL, withIntermediateDirectories: true, attributes: nil)
let fileLocation: String = MoppFileManager.shared.copyFile(withPath: fileTempUrl.path, toPath: cachePathFileURL.path)
return completion(URL(fileURLWithPath: fileLocation))
} catch let error {
printLog("Failed to download file or create directory: \(error.localizedDescription)")
Expand Down
21 changes: 10 additions & 11 deletions MoppApp/MoppApp/FileLogUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,23 +66,22 @@ class FileLogUtil: LogFileGenerating {

static func logToFile() {
UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
let documentsURL = MoppFileManager.shared.documentsDirectoryPath()
var logsDirectory = MoppFileManager.shared.logsDirectoryPath()
let logsDirURL = MoppFileManager.shared.logsDirectory()
if !MoppFileManager.shared.directoryExists(logsDirURL.path) {
let cacheURL = MoppFileManager.cacheDirectory
var logsDirectory = MoppFileManager.shared.logsDirectory()
if !MoppFileManager.shared.directoryExists(logsDirectory.path) {
do {
try FileManager.default.createDirectory(at: logsDirURL, withIntermediateDirectories: true)
try FileManager.default.createDirectory(at: logsDirectory, withIntermediateDirectories: true)
} catch {
printLog("Unable to create 'logs' directory")
logsDirectory = URL(string: documentsURL)
logsDirectory = cacheURL
}
}
let currentDate = MoppDateFormatter().ddMMYYYY(toString: Date())
let fileName = "\(currentDate).log"
let logFilePath = logsDirectory?.appendingPathComponent(fileName)
freopen(logFilePath?.absoluteString, "a+", stderr)
let logFilePath = logsDirectory.appendingPathComponent(fileName)
freopen(logFilePath.path, "a+", stderr)

printLog("DEBUG mode: Logging to file. File location: \(logFilePath?.path ?? "Unable to log file path")")
printLog("DEBUG mode: Logging to file. File location: \(logFilePath.path )")
}

static func getLogFiles(logsDirURL: URL) throws -> [URL] {
Expand Down Expand Up @@ -111,7 +110,7 @@ class FileLogUtil: LogFileGenerating {

static func combineLogFiles() throws -> URL {
let logsDirURL = MoppFileManager.shared.logsDirectory()
let documentsDirURL = URL(fileURLWithPath: MoppFileManager.shared.documentsDirectoryPath())
let cacheDirURL = MoppFileManager.cacheDirectory
if logsExist(logsDirURL: logsDirURL) {
let combinedLogFile = logsDirURL.appendingPathComponent(DIAGNOSTICS_LOGS_FILE_NAME)
if MoppFileManager.shared.fileExists(combinedLogFile.path) {
Expand All @@ -123,7 +122,7 @@ class FileLogUtil: LogFileGenerating {
logFiles = try getLogFiles(logsDirURL: logsDirURL)
} catch {
printLog("Unable to get files from 'logs' directory")
logFiles = try getLogFiles(logsDirURL: documentsDirURL)
logFiles = try getLogFiles(logsDirURL: cacheDirURL)
}

// Create empty file
Expand Down
75 changes: 43 additions & 32 deletions MoppApp/MoppApp/FileManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,21 @@ class MoppFileManager {
static let shared = MoppFileManager()
var fileManager: FileManager = FileManager()

func documentsDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0]
return documentsDirectory
}

func logsDirectoryPath() -> URL? {
return URL(string: documentsDirectoryPath())?.appendingPathComponent("logs")
static var cacheDirectory: URL {
let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
if #available(iOS 16.0, *) {
return URL(filePath: paths.first ?? "")
} else {
return URL(fileURLWithPath: paths.first ?? "", isDirectory: true)
}
}

func logsDirectory() -> URL {
let documentsURL = URL(fileURLWithPath: documentsDirectoryPath())
return documentsURL.appendingPathComponent("logs")
return MoppFileManager.cacheDirectory.appendingPathComponent("logs")
}

func documentsFiles() -> [String] {
let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
if let urlArr = try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.contentAccessDateKey], options: .skipsHiddenFiles) {
func cacheFiles() -> [String] {
if let urlArr = try? fileManager.contentsOfDirectory(at: MoppFileManager.cacheDirectory, includingPropertiesForKeys: [.contentAccessDateKey], options: .skipsHiddenFiles) {
return urlArr.sorted { (currentFile, nextFile) -> Bool in
guard let currentFileDate = try? currentFile.resourceValues(forKeys: [.contentAccessDateKey]).contentAccessDate,
let nextFileDate = try? nextFile.resourceValues(forKeys: [.contentAccessDateKey]).contentAccessDate else {
Expand All @@ -59,7 +56,7 @@ class MoppFileManager {
}

func removeDocumentsFile(with name: String) {
var directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
var directory = MoppFileManager.cacheDirectory
directory.appendPathComponent(name)
try! fileManager.removeItem(at: directory)
if let inboxDirectoryPath = inboxDirectoryPath() {
Expand All @@ -68,25 +65,33 @@ class MoppFileManager {
}

func inboxDirectoryPath() -> String? {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
return documentsDirectory.appendingPathComponent("Inbox", isDirectory: true).path
return MoppFileManager.cacheDirectory.appendingPathComponent("Inbox", isDirectory: true).path
}

func tempDocumentsDirectoryPath() -> String {
let path: String = documentsDirectoryPath() + ("/temp")
func tempCacheDirectoryPath() -> URL {
var path: URL?
if #available(iOS 16.0, *) {
path = MoppFileManager.cacheDirectory.appending(path: "temp")
} else {
path = MoppFileManager.cacheDirectory.appendingPathComponent("temp")
}

guard let filePath = path else { return URL(fileURLWithPath: "") }
var isDir : ObjCBool = false
if !(fileManager.fileExists(atPath: path, isDirectory: &isDir)) {
try? fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: [FileAttributeKey.protectionKey: FileProtectionType.complete])
if !(fileManager.fileExists(atPath: filePath.path, isDirectory: &isDir)) {
try? fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: [FileAttributeKey.protectionKey: FileProtectionType.complete])
}
return path
return filePath
}

func tempFilePath(withFileName fileName: String) -> String? {
let tempPathURL = URL(fileURLWithPath: tempDocumentsDirectoryPath())
let filePathURL = URL(fileURLWithPath: fileName.sanitize(),
isDirectory: false, relativeTo: tempPathURL).absoluteURL
let tempPathURL = tempCacheDirectoryPath()
var filePathURL = URL(fileURLWithPath: "")
if #available(iOS 16.0, *) {
filePathURL = tempPathURL.appending(path: fileName.sanitize())
} else {
filePathURL = tempPathURL.appendingPathComponent(fileName.sanitize(), isDirectory: false)
}

// Create intermediate directories for possibility of creating temporary
// file if filename contains relative path
Expand All @@ -100,7 +105,7 @@ class MoppFileManager {
}

func filePath(withFileName fileName: String) -> String {
let filePath: String = URL(fileURLWithPath: documentsDirectoryPath()).appendingPathComponent(fileName).path
let filePath: String = MoppFileManager.cacheDirectory.appendingPathComponent(fileName).path
return filePath
}

Expand Down Expand Up @@ -181,7 +186,7 @@ class MoppFileManager {
}

func saveFile(fileURL: URL, _ folderName: String?, completionHandler: @escaping (Bool, URL?) -> Void) {
let tsaCertDirectory: URL? = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(folderName ?? "tsa-cert", isDirectory: true)
let tsaCertDirectory: URL? = MoppFileManager.cacheDirectory.appendingPathComponent(folderName ?? "tsa-cert", isDirectory: true)

guard let saveDir: URL = tsaCertDirectory else { printLog("Failed to get \(tsaCertDirectory?.lastPathComponent ?? "requested") directory"); completionHandler(false, nil); return }
do {
Expand Down Expand Up @@ -213,8 +218,8 @@ class MoppFileManager {
}

func saveFile(containerPath: String, fileName: String, completionHandler: @escaping (Bool, String?) -> Void) {
let savedFilesDirectory: URL? = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Saved Files", isDirectory: true)
let tempFilesDirectory: URL? = URL(string: MoppFileManager.shared.tempDocumentsDirectoryPath())
let savedFilesDirectory: URL? = MoppFileManager.cacheDirectory.appendingPathComponent("Saved Files", isDirectory: true)
let tempFilesDirectory: URL? = MoppFileManager.shared.tempCacheDirectoryPath()

guard let saveDir: URL = savedFilesDirectory else { printLog("Failed to get \(savedFilesDirectory?.lastPathComponent ?? "requested") directory"); completionHandler(false, nil); return }
do {
Expand Down Expand Up @@ -269,9 +274,9 @@ class MoppFileManager {
}
}

func removeTempSavedFilesInDocuments(folderName: String) {
func removeTempSavedFilesInCache(folderName: String) {
do {
let savedFilesDirectory: URL? = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(folderName, isDirectory: true)
let savedFilesDirectory: URL? = MoppFileManager.cacheDirectory.appendingPathComponent(folderName, isDirectory: true)

guard let saveDir: URL = savedFilesDirectory else { printLog("Failed to get \(savedFilesDirectory?.lastPathComponent ?? "requested") directory"); return }
if fileManager.fileExists(atPath: saveDir.path) {
Expand Down Expand Up @@ -471,4 +476,10 @@ class MoppFileManager {
guard let fileSizeBytes = fileSize else { printLog("Could not get file size"); return true }
return fileSizeBytes.isZero
}

static func removeFiles() {
MoppFileManager.shared.removeTempSavedFilesInCache(folderName: "Saved Files")
MoppFileManager.shared.removeTempSavedFilesInCache(folderName: "Downloads")
MoppFileManager.shared.removeFilesFromSharedFolder()
}
}
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/MimeTypeExtractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ class MimeTypeExtractor {
}

private static func unZipFile(filePath: URL, fileName: String) -> URL? {
let outputPath = URL(fileURLWithPath: MoppFileManager.shared.tempDocumentsDirectoryPath(), isDirectory: true).appendingPathComponent(filePath.lastPathComponent).deletingPathExtension()
let outputPath = MoppFileManager.shared.tempCacheDirectoryPath().appendingPathComponent(filePath.lastPathComponent).deletingPathExtension()
guard let archive = Archive(url: filePath, accessMode: .read) else {
return nil
}
Expand Down
12 changes: 6 additions & 6 deletions MoppApp/MoppApp/MoppApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class MoppApp: UIApplication, URLSessionDelegate, URLSessionDownloadDelegate {
}

func didFinishLaunchingWithOptions(launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Log console logs to a file in Documents/logs folder
// Log console logs to a file in Library/Cache/logs folder
if isUsingTestMode() {
setDebugMode(value: true)
FileLogUtil.logToFile()
Expand All @@ -94,6 +94,8 @@ class MoppApp: UIApplication, URLSessionDelegate, URLSessionDownloadDelegate {
setDebugMode(value: false)
}
}

MoppFileManager.removeFiles()

loadNibs()
// Set navBar not translucent by default.
Expand Down Expand Up @@ -322,13 +324,13 @@ class MoppApp: UIApplication, URLSessionDelegate, URLSessionDownloadDelegate {
do {
let newData: Data? = try Data(contentsOf: newUrl)
let fileName: String = newUrl.deletingPathExtension().lastPathComponent.sanitize()
let tempDirectoryPath: String? = MoppFileManager.shared.tempDocumentsDirectoryPath()
let tempDirectoryPath: URL? = MoppFileManager.shared.tempCacheDirectoryPath()
guard let tempDirectory = tempDirectoryPath else {
printLog("Unable to get temporary file directory")
topViewController.showErrorMessage(message: L(.fileImportNewFileOpeningFailedAlertMessage, ["\(fileName).\(pathExtension)"]))
return false
}
let fileURL: URL? = URL(fileURLWithPath: tempDirectory, isDirectory: true).appendingPathComponent(fileName, isDirectory: false).appendingPathExtension(pathExtension)
let fileURL: URL? = URL(fileURLWithPath: tempDirectory.path, isDirectory: true).appendingPathComponent(fileName, isDirectory: false).appendingPathExtension(pathExtension)

guard let newUrlData: Data = newData, let filePath: URL = fileURL else {
printLog("Unable to get file data or file path")
Expand Down Expand Up @@ -437,9 +439,7 @@ class MoppApp: UIApplication, URLSessionDelegate, URLSessionDownloadDelegate {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

// Remove temporarily saved files folder
MoppFileManager.shared.removeTempSavedFilesInDocuments(folderName: "Saved Files")
MoppFileManager.shared.removeTempSavedFilesInDocuments(folderName: "Downloads")
MoppFileManager.shared.removeFilesFromSharedFolder()
MoppFileManager.removeFiles()
}

func handleEventsForBackgroundURLSession(identifier: String, completionHandler: @escaping () -> Void) {
Expand Down
Loading

0 comments on commit a7324be

Please sign in to comment.