浏览代码

refactor(ios): rm old URL download extension

Andelf 3 年之前
父节点
当前提交
62eed63ed0
共有 2 个文件被更改,包括 76 次插入111 次删除
  1. 50 89
      ios/App/App/FileSync/Extensions.swift
  2. 26 22
      ios/App/App/FileSync/FileSync.swift

+ 50 - 89
ios/App/App/FileSync/Extensions.swift

@@ -10,44 +10,44 @@ import CryptoKit
 
 
 // via https://github.com/krzyzanowskim/CryptoSwift
 // via https://github.com/krzyzanowskim/CryptoSwift
 extension Array where Element == UInt8 {
 extension Array where Element == UInt8 {
-  public init(hex: String) {
-      self = Array.init()
-      self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount)
-      var buffer: UInt8?
-      var skip = hex.hasPrefix("0x") ? 2 : 0
-      for char in hex.unicodeScalars.lazy {
-          guard skip == 0 else {
-              skip -= 1
-              continue
-          }
-          guard char.value >= 48 && char.value <= 102 else {
-              removeAll()
-              return
-          }
-          let v: UInt8
-          let c: UInt8 = UInt8(char.value)
-          switch c {
-          case let c where c <= 57:
-              v = c - 48
-          case let c where c >= 65 && c <= 70:
-              v = c - 55
-          case let c where c >= 97:
-              v = c - 87
-          default:
-              removeAll()
-              return
-          }
-          if let b = buffer {
-              append(b << 4 | v)
-              buffer = nil
-          } else {
-              buffer = v
-          }
-      }
-      if let b = buffer {
-          append(b)
-      }
-  }
+    public init(hex: String) {
+        self = Array.init()
+        self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount)
+        var buffer: UInt8?
+        var skip = hex.hasPrefix("0x") ? 2 : 0
+        for char in hex.unicodeScalars.lazy {
+            guard skip == 0 else {
+                skip -= 1
+                continue
+            }
+            guard char.value >= 48 && char.value <= 102 else {
+                removeAll()
+                return
+            }
+            let v: UInt8
+            let c: UInt8 = UInt8(char.value)
+            switch c {
+            case let c where c <= 57:
+                v = c - 48
+            case let c where c >= 65 && c <= 70:
+                v = c - 55
+            case let c where c >= 97:
+                v = c - 87
+            default:
+                removeAll()
+                return
+            }
+            if let b = buffer {
+                append(b << 4 | v)
+                buffer = nil
+            } else {
+                buffer = v
+            }
+        }
+        if let b = buffer {
+            append(b)
+        }
+    }
 }
 }
 
 
 extension Data {
 extension Data {
@@ -90,7 +90,7 @@ extension String {
         
         
         // strip nonce here, since it's all zero
         // strip nonce here, since it's all zero
         return "e." + (sealed.ciphertext + sealed.tag).hexDescription
         return "e." + (sealed.ciphertext + sealed.tag).hexDescription
-
+        
     }
     }
     
     
     func fnameDecrypt(rawKey: Data) -> String? {
     func fnameDecrypt(rawKey: Data) -> String? {
@@ -107,7 +107,7 @@ extension String {
         
         
         let key = SymmetricKey(data: rawKey)
         let key = SymmetricKey(data: rawKey)
         let nonce = Data(repeating: 0, count: 12)
         let nonce = Data(repeating: 0, count: 12)
-
+        
         guard let sealed = try? ChaChaPoly.SealedBox(combined: nonce + encryptedRaw) else {
         guard let sealed = try? ChaChaPoly.SealedBox(combined: nonce + encryptedRaw) else {
             return nil
             return nil
         }
         }
@@ -142,56 +142,17 @@ extension URL {
         return relComponents.joined(separator: "/")
         return relComponents.joined(separator: "/")
     }
     }
     
     
-    // Download a remote URL to a file
-    func download(toFile file: URL, completion: @escaping (Error?) -> Void) {
-        let task = URLSession.shared.downloadTask(with: self) {
-            (tempURL, response, error) in
-            // Early exit on error
-            guard let tempURL = tempURL else {
-                completion(error)
-                return
-            }
-            
-            if let response = response! as? HTTPURLResponse {
-                if response.statusCode == 404 {
-                    completion(NSError(domain: "",
-                                       code: response.statusCode,
-                                       userInfo: [NSLocalizedDescriptionKey: "remote file not found"]))
-                    return
-                }
-                if response.statusCode != 200 {
-                    completion(NSError(domain: "",
-                                       code: response.statusCode,
-                                       userInfo: [NSLocalizedDescriptionKey: "invalid http status code"]))
-                    return
-                }
-            }
-            
-            do {
-                // Remove any existing document at file
-                if FileManager.default.fileExists(atPath: file.path) {
-                    try FileManager.default.removeItem(at: file)
-                } else {
-                    let baseURL = file.deletingLastPathComponent()
-                    try FileManager.default.createDirectory(at: baseURL, withIntermediateDirectories: true, attributes: nil)
-                }
-                let rawData = try Data(contentsOf: tempURL)
-                guard let decryptedRawData = maybeDecrypt(rawData) else {
-                    throw NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "can not decrypt remote file"])
-                }
-                try decryptedRawData.write(to: file, options: .atomic)
-
-                completion(nil)
-            }
-            
-            // Handle potential file system errors
-            catch {
-                completion(error)
-            }
+    func ensureParentDir() {
+        let dirURL = self.deletingLastPathComponent()
+        try? FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true, attributes: nil)
+    }
+    
+    func writeData(data: Data) throws {
+        self.ensureParentDir()
+        if FileManager.default.fileExists(atPath: self.path) {
+            try FileManager.default.removeItem(at: self)
         }
         }
-        
-        // Start the download
-        task.resume()
+        try data.write(to: self, options: .atomic)
     }
     }
 }
 }
 
 

+ 26 - 22
ios/App/App/FileSync/FileSync.swift

@@ -413,7 +413,7 @@ public class FileSync: CAPPlugin, SyncDebugDelegate {
                 
                 
                 let progressHandler = {(fraction: Double) in
                 let progressHandler = {(fraction: Double) in
                     self.debugNotification(["event": "download:progress",
                     self.debugNotification(["event": "download:progress",
-                                            "data": ["filePath": filePath,
+                                            "data": ["file": filePath,
                                                      "fraction": fraction]])
                                                      "fraction": fraction]])
                 }
                 }
                 
                 
@@ -424,21 +424,14 @@ public class FileSync: CAPPlugin, SyncDebugDelegate {
                         print("debug download \(error) in \(filePath)")
                         print("debug download \(error) in \(filePath)")
                     case .success(let tempURL):
                     case .success(let tempURL):
                         do {
                         do {
-                            // Remove any existing document at file
-                            if FileManager.default.fileExists(atPath: localFileURL.path) {
-                                try FileManager.default.removeItem(at: localFileURL)
-                            } else {
-                                let parentURL = localFileURL.deletingLastPathComponent()
-                                try FileManager.default.createDirectory(at: parentURL, withIntermediateDirectories: true, attributes: nil)
-                            }
                             let rawData = try Data(contentsOf: tempURL!)
                             let rawData = try Data(contentsOf: tempURL!)
                             guard let decryptedRawData = maybeDecrypt(rawData) else {
                             guard let decryptedRawData = maybeDecrypt(rawData) else {
-                                throw NSError(domain: FileSyncErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "can not decrypt downloaded file"])
+                                throw NSError(domain: FileSyncErrorDomain,
+                                              code: 0,
+                                              userInfo: [NSLocalizedDescriptionKey: "can not decrypt downloaded file"])
                             }
                             }
-                            try decryptedRawData.write(to: localFileURL, options: .atomic)
-                            
+                            try localFileURL.writeData(data: decryptedRawData)
                             self.debugNotification(["event": "download:file", "data": ["file": filePath]])
                             self.debugNotification(["event": "download:file", "data": ["file": filePath]])
-                            
                             downloaded.append(filePath)
                             downloaded.append(filePath)
                         } catch {
                         } catch {
                             // Handle potential file system errors
                             // Handle potential file system errors
@@ -471,32 +464,43 @@ public class FileSync: CAPPlugin, SyncDebugDelegate {
         client.getVersionFiles(at: filePaths) {  (fileURLDict, error) in
         client.getVersionFiles(at: filePaths) {  (fileURLDict, error) in
             if let error = error {
             if let error = error {
                 print("debug getVersionFiles error \(error)")
                 print("debug getVersionFiles error \(error)")
-                self.debugNotification(["event": "version-download:error", "data": ["message": "error while getting version files \(filePaths)"]])
                 call.reject(error.localizedDescription)
                 call.reject(error.localizedDescription)
             } else {
             } else {
                 // handle multiple completionHandlers
                 // handle multiple completionHandlers
                 let group = DispatchGroup()
                 let group = DispatchGroup()
                 
                 
                 var downloaded: [String] = []
                 var downloaded: [String] = []
-                
                 for (filePath, remoteFileURL) in fileURLDict {
                 for (filePath, remoteFileURL) in fileURLDict {
                     group.enter()
                     group.enter()
                     
                     
                     // NOTE: fileURLs from getFiles API is percent-encoded
                     // NOTE: fileURLs from getFiles API is percent-encoded
                     let localFileURL = baseURL.appendingPathComponent("logseq/version-files/").appendingPathComponent(filePath.removingPercentEncoding!)
                     let localFileURL = baseURL.appendingPathComponent("logseq/version-files/").appendingPathComponent(filePath.removingPercentEncoding!)
-                    remoteFileURL.download(toFile: localFileURL) {error in
-                        if let error = error {
-                            self.debugNotification(["event": "version-download:error", "data": ["message": "error while downloading \(filePath): \(error)"]])
+                    // empty progress handler
+                    let progressHandler = {(fraction: Double) in
+                    }
+                    
+                    client.download(url: remoteFileURL, progressHandler: progressHandler) {result in
+                        switch result {
+                        case .failure(let error):
                             print("debug download \(error) in \(filePath)")
                             print("debug download \(error) in \(filePath)")
-                        } else {
-                            self.debugNotification(["event": "version-download:file", "data": ["file": filePath]])
-                            downloaded.append(filePath)
+                        case .success(let tempURL):
+                            do {
+                                let rawData = try Data(contentsOf: tempURL!)
+                                guard let decryptedRawData = maybeDecrypt(rawData) else {
+                                    throw NSError(domain: FileSyncErrorDomain,
+                                                  code: 0,
+                                                  userInfo: [NSLocalizedDescriptionKey: "can not decrypt remote file"])
+                                }
+                                try localFileURL.writeData(data: decryptedRawData)
+                                downloaded.append(filePath)
+                            } catch {
+                                print(error)
+                            }
                         }
                         }
                         group.leave()
                         group.leave()
                     }
                     }
                 }
                 }
                 group.notify(queue: .main) {
                 group.notify(queue: .main) {
-                    self.debugNotification(["event": "version-download:done"])
                     call.resolve(["ok": true, "data": downloaded])
                     call.resolve(["ok": true, "data": downloaded])
                 }
                 }
                 
                 
@@ -577,7 +581,7 @@ public class FileSync: CAPPlugin, SyncDebugDelegate {
             // 2. upload_temp_file
             // 2. upload_temp_file
             let progressHandler = {(filePath: String, fraction: Double) in
             let progressHandler = {(filePath: String, fraction: Double) in
                 self.debugNotification(["event": "upload:progress",
                 self.debugNotification(["event": "upload:progress",
-                                        "data": ["filePath": filePath,
+                                        "data": ["file": filePath,
                                                  "fraction": fraction]])
                                                  "fraction": fraction]])
             }
             }
             client.uploadTempFiles(files, credentials: credentials!, progressHandler: progressHandler) { (uploadedFileKeyDict, fileMd5Dict, error) in
             client.uploadTempFiles(files, credentials: credentials!, progressHandler: progressHandler) { (uploadedFileKeyDict, fileMd5Dict, error) in