FileProvider.swift 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. //
  2. // FileProviderExtension.swift
  3. // Files
  4. //
  5. // Created by Marino Faggiana on 26/03/18.
  6. // Copyright © 2018 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import FileProvider
  24. import UIKit
  25. import MobileCoreServices
  26. var ocNetworking: OCnetworking?
  27. var account = ""
  28. var accountUser = ""
  29. var accountUserID = ""
  30. var accountPassword = ""
  31. var accountUrl = ""
  32. var homeServerUrl = ""
  33. var directoryUser = ""
  34. // Directory
  35. var groupURL: URL?
  36. var fileProviderStorageURL: URL?
  37. var importDocumentURL: URL?
  38. var changeDocumentURL: URL?
  39. // List
  40. var listUpdateItems = [NSFileProviderItem]()
  41. var listFavoriteIdentifierRank = [String:NSNumber]()
  42. class FileProvider: NSFileProviderExtension {
  43. var listUpload = [String:URLSessionTask]()
  44. override init() {
  45. super.init()
  46. guard let activeAccount = NCManageDatabase.sharedInstance.getAccountActive() else {
  47. return
  48. }
  49. account = activeAccount.account
  50. accountUser = activeAccount.user
  51. accountUserID = activeAccount.userID
  52. accountPassword = activeAccount.password
  53. accountUrl = activeAccount.url
  54. homeServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeAccount.url)
  55. directoryUser = CCUtility.getDirectoryActiveUser(activeAccount.user, activeUrl: activeAccount.url)
  56. ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: accountUser, withUserID: accountUserID, withPassword: accountPassword, withUrl: accountUrl)
  57. groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  58. fileProviderStorageURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage)
  59. importDocumentURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage).appendingPathComponent(k_fileProviderStorageImportDocument)
  60. changeDocumentURL = groupURL!.appendingPathComponent(k_assetLocalIdentifierFileProviderStorage).appendingPathComponent(k_fileProviderStorageChangeDocument)
  61. // Create dir File Provider Storage
  62. do {
  63. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.path, withIntermediateDirectories: true, attributes: nil)
  64. } catch let error as NSError {
  65. NSLog("Unable to create directory \(error.debugDescription)")
  66. }
  67. // Create dir for Upload
  68. do {
  69. try FileManager.default.createDirectory(atPath: importDocumentURL!.path, withIntermediateDirectories: true, attributes: nil)
  70. } catch let error as NSError {
  71. NSLog("Unable to create directory \(error.debugDescription)")
  72. }
  73. // Create dir for change document
  74. do {
  75. try FileManager.default.createDirectory(atPath: changeDocumentURL!.path, withIntermediateDirectories: true, attributes: nil)
  76. } catch let error as NSError {
  77. NSLog("Unable to create directory \(error.debugDescription)")
  78. }
  79. if #available(iOSApplicationExtension 11.0, *) {
  80. // Only iOS 11
  81. } else {
  82. NSFileCoordinator().coordinate(writingItemAt: self.documentStorageURL, options: [], error: nil, byAccessor: { newURL in
  83. do {
  84. try FileManager.default.createDirectory(at: newURL, withIntermediateDirectories: true, attributes: nil)
  85. } catch let error {
  86. print("error: \(error)")
  87. }
  88. })
  89. }
  90. }
  91. // MARK: - Enumeration
  92. override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator {
  93. /* ONLY iOS 11*/
  94. guard #available(iOS 11, *) else {
  95. throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:])
  96. }
  97. var maybeEnumerator: NSFileProviderEnumerator? = nil
  98. if (containerItemIdentifier == NSFileProviderItemIdentifier.rootContainer) {
  99. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  100. } else if (containerItemIdentifier == NSFileProviderItemIdentifier.workingSet) {
  101. maybeEnumerator = FileProviderEnumeratorWorkingSet(enumeratedItemIdentifier: containerItemIdentifier)
  102. } else {
  103. // determine if the item is a directory or a file
  104. // - for a directory, instantiate an enumerator of its subitems
  105. // - for a file, instantiate an enumerator that observes changes to the file
  106. let item = try self.item(for: containerItemIdentifier)
  107. if item.typeIdentifier == kUTTypeFolder as String {
  108. maybeEnumerator = FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier)
  109. } else {
  110. maybeEnumerator = FileProviderEnumeratorFile(enumeratedItemIdentifier: containerItemIdentifier)
  111. }
  112. }
  113. guard let enumerator = maybeEnumerator else {
  114. throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])
  115. }
  116. return enumerator
  117. }
  118. // MARK: - Item
  119. override func item(for identifier: NSFileProviderItemIdentifier) throws -> NSFileProviderItem {
  120. /* ONLY iOS 11*/
  121. guard #available(iOS 11, *) else {
  122. throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo:[:])
  123. }
  124. if identifier == .rootContainer {
  125. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)) {
  126. let metadata = tableMetadata()
  127. metadata.account = account
  128. metadata.directory = true
  129. metadata.directoryID = directory.directoryID
  130. metadata.fileID = identifier.rawValue
  131. metadata.fileName = NCBrandOptions.sharedInstance.brand
  132. metadata.fileNameView = NCBrandOptions.sharedInstance.brand
  133. metadata.typeFile = k_metadataTypeFile_directory
  134. return FileProviderItem(metadata: metadata, serverUrl: homeServerUrl)
  135. }
  136. } else {
  137. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) {
  138. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND directoryID = %@", account, metadata.directoryID)) {
  139. return FileProviderItem(metadata: metadata, serverUrl: directory.serverUrl)
  140. }
  141. }
  142. }
  143. // implement the actual lookup
  144. throw NSFileProviderError(.noSuchItem)
  145. }
  146. override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? {
  147. /* ONLY iOS 11*/
  148. guard #available(iOS 11, *) else {
  149. return nil
  150. }
  151. // resolve the given identifier to a file on disk
  152. guard let item = try? item(for: identifier) else {
  153. return nil
  154. }
  155. // in this implementation, all paths are structured as <base storage directory>/<item identifier>/<item file name>
  156. let manager = NSFileProviderManager.default
  157. var url = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true)
  158. if item.typeIdentifier == (kUTTypeFolder as String) {
  159. url = url.appendingPathComponent(item.filename, isDirectory:true)
  160. } else {
  161. url = url.appendingPathComponent(item.filename, isDirectory:false)
  162. }
  163. return url
  164. }
  165. override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? {
  166. // resolve the given URL to a persistent identifier using a database
  167. let pathComponents = url.pathComponents
  168. // exploit the fact that the path structure has been defined as
  169. // <base storage directory>/<item identifier>/<item file name> above
  170. assert(pathComponents.count > 2)
  171. let itemIdentifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  172. return itemIdentifier
  173. }
  174. // MARK: - Managing Shared Files
  175. override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) {
  176. if #available(iOSApplicationExtension 11.0, *) {
  177. guard let identifier = persistentIdentifierForItem(at: url) else {
  178. completionHandler(NSFileProviderError(.noSuchItem))
  179. return
  180. }
  181. do {
  182. let fileProviderItem = try item(for: identifier)
  183. let placeholderURL = NSFileProviderManager.placeholderURL(for: url)
  184. try NSFileProviderManager.writePlaceholder(at: placeholderURL,withMetadata: fileProviderItem)
  185. completionHandler(nil)
  186. } catch let error {
  187. print("error: \(error)")
  188. completionHandler(error)
  189. }
  190. } else {
  191. let fileName = url.lastPathComponent
  192. let placeholderURL = NSFileProviderExtension.placeholderURL(for: self.documentStorageURL.appendingPathComponent(fileName))
  193. let fileSize = 0
  194. let metadata = [AnyHashable(URLResourceKey.fileSizeKey): fileSize]
  195. do {
  196. try NSFileProviderExtension.writePlaceholder(at: placeholderURL, withMetadata: metadata as! [URLResourceKey : Any])
  197. } catch let error {
  198. print("error: \(error)")
  199. }
  200. completionHandler(nil)
  201. }
  202. }
  203. override func startProvidingItem(at url: URL, completionHandler: @escaping ((_ error: Error?) -> Void)) {
  204. if #available(iOSApplicationExtension 11.0, *) {
  205. var fileSize : UInt64 = 0
  206. do {
  207. let attr = try FileManager.default.attributesOfItem(atPath: url.path)
  208. fileSize = attr[FileAttributeKey.size] as! UInt64
  209. } catch let error {
  210. print("Error: \(error)")
  211. }
  212. if fileSize > 0 {
  213. completionHandler(nil)
  214. return
  215. }
  216. //let fileName = url.lastPathComponent
  217. let pathComponents = url.pathComponents
  218. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  219. //let changeDocumentPath = changeDocumentURL!.path + "/" + fileName
  220. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) else {
  221. completionHandler(NSFileProviderError(.noSuchItem))
  222. return
  223. }
  224. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  225. completionHandler(NSFileProviderError(.noSuchItem))
  226. return
  227. }
  228. let task = ocNetworking?.downloadFileNameServerUrl("\(serverUrl)/\(metadata.fileName)", fileNameLocalPath: "\(directoryUser)/\(metadata.fileID)", communication: CCNetworking.shared().sharedOCCommunicationExtensionDownload(metadata.fileName), success: { (lenght) in
  229. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  230. // copy download file to url
  231. _ = self.copyFile("\(directoryUser)/\(metadata.fileID)", toPath: url.path)
  232. completionHandler(nil)
  233. }, failure: { (errorMessage, errorCode) in
  234. completionHandler(NSFileProviderError(.serverUnreachable))
  235. })
  236. if task != nil {
  237. NSFileProviderManager.default.register(task!, forItemWithIdentifier: NSFileProviderItemIdentifier(identifier.rawValue)) { (error) in
  238. print("Registe download task")
  239. }
  240. }
  241. } else {
  242. guard let fileData = try? Data(contentsOf: url) else {
  243. completionHandler(nil)
  244. return
  245. }
  246. do {
  247. _ = try fileData.write(to: url, options: NSData.WritingOptions())
  248. completionHandler(nil)
  249. } catch let error {
  250. print("error: \(error)")
  251. completionHandler(error)
  252. }
  253. }
  254. }
  255. override func itemChanged(at url: URL) {
  256. if #available(iOSApplicationExtension 11.0, *) {
  257. let fileName = url.lastPathComponent
  258. let pathComponents = url.pathComponents
  259. let changeDocumentPath = changeDocumentURL!.path + "/" + fileName
  260. let importDocumentPath = importDocumentURL!.path + "/" + fileName
  261. let metadataNet = CCMetadataNet()
  262. assert(pathComponents.count > 2)
  263. let identifier = NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2])
  264. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, identifier.rawValue)) else {
  265. return
  266. }
  267. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  268. return
  269. }
  270. // Refresh
  271. self.refreshEnumerator(identifier: identifier, serverUrl: serverUrl)
  272. // Copy file to Change Document & if exists on Import Document
  273. _ = self.copyFile(url.path, toPath: changeDocumentPath)
  274. if FileManager.default.fileExists(atPath: importDocumentPath) {
  275. _ = self.copyFile(url.path, toPath: importDocumentPath)
  276. }
  277. metadataNet.account = account
  278. metadataNet.assetLocalIdentifier = k_assetLocalIdentifierFileProviderStorage + identifier.rawValue
  279. metadataNet.fileName = fileName
  280. metadataNet.path = changeDocumentPath
  281. metadataNet.selector = selectorUploadFile
  282. metadataNet.selectorPost = ""
  283. metadataNet.serverUrl = serverUrl
  284. metadataNet.session = k_upload_session
  285. metadataNet.taskStatus = Int(k_taskStatusResume)
  286. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  287. // Upload
  288. self.uploadCloud(fileName, serverUrl: serverUrl, fileNameLocalPath: changeDocumentPath, metadata: metadata, identifier: identifier)
  289. } else {
  290. let fileSize = (try! FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  291. NSLog("[LOG] Item changed at URL %@ %lu", url as NSURL, fileSize)
  292. guard let account = NCManageDatabase.sharedInstance.getAccountActive() else {
  293. self.stopProvidingItem(at: url)
  294. return
  295. }
  296. guard let fileName = CCUtility.getFileNameExt() else {
  297. self.stopProvidingItem(at: url)
  298. return
  299. }
  300. // -------> Fix : Clear FileName for twice Office 365
  301. CCUtility.setFileNameExt("")
  302. // --------------------------------------------------
  303. if (fileName != url.lastPathComponent) {
  304. self.stopProvidingItem(at: url)
  305. return
  306. }
  307. guard let serverUrl = CCUtility.getServerUrlExt() else {
  308. self.stopProvidingItem(at: url)
  309. return
  310. }
  311. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) else {
  312. self.stopProvidingItem(at: url)
  313. return
  314. }
  315. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileName == %@ AND directoryID == %@", fileName, directoryID))
  316. if metadata != nil {
  317. // Update
  318. let uploadID = k_uploadSessionID + CCUtility.createRandomString(16)
  319. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  320. let destinationDirectoryUser = "\(directoryUser!)/\(uploadID)"
  321. // copy sourceURL on directoryUser
  322. _ = self.copyFile(url.path, toPath: destinationDirectoryUser)
  323. // Prepare for send Metadata
  324. metadata!.sessionID = uploadID
  325. metadata!.session = k_upload_session
  326. metadata!.sessionTaskIdentifier = Int(k_taskIdentifierWaitStart)
  327. _ = NCManageDatabase.sharedInstance.updateMetadata(metadata!)
  328. } else {
  329. // New
  330. let directoryUser = CCUtility.getDirectoryActiveUser(account.user, activeUrl: account.url)
  331. let destinationDirectoryUser = "\(directoryUser!)/\(fileName)"
  332. _ = self.copyFile(url.path, toPath: destinationDirectoryUser)
  333. CCNetworking.shared().uploadFile(fileName, serverUrl: serverUrl, assetLocalIdentifier: nil, session: k_upload_session, taskStatus: Int(k_taskStatusResume), selector: nil, selectorPost: nil, errorCode: 0, delegate: self)
  334. }
  335. self.stopProvidingItem(at: url)
  336. }
  337. }
  338. override func stopProvidingItem(at url: URL) {
  339. // Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
  340. // Care should be taken that the corresponding placeholder file stays behind after the content file has been deleted.
  341. // Called after the last claim to the file has been released. At this point, it is safe for the file provider to remove the content file.
  342. // look up whether the file has local changes
  343. let fileHasLocalChanges = false
  344. if !fileHasLocalChanges {
  345. // remove the existing file to free up space
  346. do {
  347. _ = try FileManager.default.removeItem(at: url)
  348. } catch let error {
  349. print("error: \(error)")
  350. }
  351. // write out a placeholder to facilitate future property lookups
  352. self.providePlaceholder(at: url, completionHandler: { error in
  353. // handle any error, do any necessary cleanup
  354. })
  355. }
  356. }
  357. // MARK: - Accessing Thumbnails
  358. override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
  359. /* ONLY iOS 11*/
  360. guard #available(iOS 11, *) else {
  361. return Progress(totalUnitCount:0)
  362. }
  363. let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
  364. var counterProgress: Int64 = 0
  365. for itemIdentifier in itemIdentifiers {
  366. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) {
  367. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video) {
  368. let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID)
  369. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: serverUrl, activeUrl: accountUrl)
  370. let fileNameLocal = metadata.fileID
  371. ocNetworking?.downloadThumbnail(withDimOfThumbnail: "m", fileName: fileName, fileNameLocal: fileNameLocal, success: {
  372. do {
  373. let url = URL.init(fileURLWithPath: "\(directoryUser)/\(itemIdentifier.rawValue).ico")
  374. let data = try Data.init(contentsOf: url)
  375. perThumbnailCompletionHandler(itemIdentifier, data, nil)
  376. } catch let error {
  377. print("error: \(error)")
  378. perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.noSuchItem))
  379. }
  380. counterProgress += 1
  381. if (counterProgress == progress.totalUnitCount) {
  382. completionHandler(nil)
  383. }
  384. }, failure: { (errorMessage, errorCode) in
  385. perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.serverUnreachable))
  386. counterProgress += 1
  387. if (counterProgress == progress.totalUnitCount) {
  388. completionHandler(nil)
  389. }
  390. })
  391. } else {
  392. counterProgress += 1
  393. if (counterProgress == progress.totalUnitCount) {
  394. completionHandler(nil)
  395. }
  396. }
  397. } else {
  398. counterProgress += 1
  399. if (counterProgress == progress.totalUnitCount) {
  400. completionHandler(nil)
  401. }
  402. }
  403. }
  404. return progress
  405. }
  406. // MARK: - Actions
  407. override func createDirectory(withName directoryName: String, inParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  408. /* ONLY iOS 11*/
  409. guard #available(iOS 11, *) else {
  410. return
  411. }
  412. // clear list update items
  413. listUpdateItems.removeAll()
  414. var serverUrl = ""
  415. if parentItemIdentifier == .rootContainer {
  416. serverUrl = homeServerUrl
  417. } else {
  418. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)) else {
  419. completionHandler(nil, NSFileProviderError(.noSuchItem))
  420. return
  421. }
  422. serverUrl = directoryParent.serverUrl
  423. }
  424. ocNetworking?.createFolder(directoryName, serverUrl: serverUrl, account: account, success: { (fileID, date) in
  425. let metadata = tableMetadata()
  426. metadata.account = account
  427. metadata.directory = true
  428. metadata.directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl)!
  429. metadata.fileID = fileID!
  430. metadata.fileName = directoryName
  431. metadata.fileNameView = directoryName
  432. metadata.typeFile = k_metadataTypeFile_directory
  433. // METADATA
  434. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  435. completionHandler(nil, NSFileProviderError(.noSuchItem))
  436. return
  437. }
  438. // DIRECTORY
  439. guard let _ = NCManageDatabase.sharedInstance.addDirectory(encrypted: false, favorite: false, fileID: fileID!, permissions: nil, serverUrl: serverUrl + "/" + directoryName) else {
  440. completionHandler(nil, NSFileProviderError(.noSuchItem))
  441. return
  442. }
  443. let item = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  444. completionHandler(item, nil)
  445. }, failure: { (errorMessage, errorCode) in
  446. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  447. })
  448. }
  449. override func deleteItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (Error?) -> Void) {
  450. /* ONLY iOS 11*/
  451. guard #available(iOS 11, *) else {
  452. return
  453. }
  454. // clear list update items
  455. listUpdateItems.removeAll()
  456. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  457. completionHandler(NSFileProviderError(.noSuchItem))
  458. return
  459. }
  460. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  461. completionHandler(NSFileProviderError(.noSuchItem))
  462. return
  463. }
  464. ocNetworking?.deleteFileOrFolder(metadata.fileName, serverUrl: serverUrl, success: {
  465. let fileNamePath = directoryUser + "/" + metadata.fileID
  466. do {
  467. try FileManager.default.removeItem(atPath: fileNamePath)
  468. } catch let error {
  469. print("error: \(error)")
  470. }
  471. do {
  472. try FileManager.default.removeItem(atPath: fileNamePath + ".ico")
  473. } catch let error {
  474. print("error: \(error)")
  475. }
  476. if metadata.directory {
  477. let dirForDelete = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)
  478. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete!)
  479. }
  480. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  481. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: nil)
  482. completionHandler(nil)
  483. }, failure: { (errorMessage, errorCode) in
  484. if errorCode == 404 {
  485. completionHandler(nil)
  486. } else {
  487. completionHandler(NSFileProviderError(.serverUnreachable))
  488. }
  489. })
  490. }
  491. override func renameItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toName itemName: String, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  492. /* ONLY iOS 11*/
  493. guard #available(iOS 11, *) else {
  494. return
  495. }
  496. // clear list update items
  497. listUpdateItems.removeAll()
  498. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  499. completionHandler(nil, NSFileProviderError(.noSuchItem))
  500. return
  501. }
  502. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  503. completionHandler(nil, NSFileProviderError(.noSuchItem))
  504. return
  505. }
  506. guard let directoryTable = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "serverUrl = %@", serverUrl)) else {
  507. completionHandler(nil, NSFileProviderError(.noSuchItem))
  508. return
  509. }
  510. // resolve the given identifier to a file on disk
  511. guard let item = try? item(for: itemIdentifier) else {
  512. completionHandler(nil, NSFileProviderError(.noSuchItem))
  513. return
  514. }
  515. let fileName = serverUrl + "/" + item.filename
  516. let fileNameTo = serverUrl + "/" + itemName
  517. ocNetworking?.moveFileOrFolder(fileName, fileNameTo: fileNameTo, success: {
  518. metadata.fileName = itemName
  519. metadata.fileNameView = itemName
  520. guard let metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  521. completionHandler(nil, NSFileProviderError(.noSuchItem))
  522. return
  523. }
  524. if metadata.directory {
  525. NCManageDatabase.sharedInstance.setDirectory(serverUrl: fileName, serverUrlTo: fileNameTo, etag: nil, fileID: nil, encrypted: directoryTable.e2eEncrypted)
  526. } else {
  527. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: itemName)
  528. }
  529. completionHandler(item, nil)
  530. }, failure: { (errorMessage, errorCode) in
  531. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  532. })
  533. print("[LOG] rename")
  534. completionHandler(nil, nil)
  535. }
  536. override func setFavoriteRank(_ favoriteRank: NSNumber?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  537. /* ONLY iOS 11*/
  538. guard #available(iOS 11, *) else {
  539. return
  540. }
  541. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  542. completionHandler(nil, NSFileProviderError(.noSuchItem))
  543. return
  544. }
  545. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  546. completionHandler(nil, NSFileProviderError(.noSuchItem))
  547. return
  548. }
  549. // Refresh Favorite Identifier Rank
  550. listFavoriteIdentifierRank = NCManageDatabase.sharedInstance.getTableMetadatasDirectoryFavoriteIdentifierRank()
  551. if favoriteRank == nil {
  552. listFavoriteIdentifierRank.removeValue(forKey: itemIdentifier.rawValue)
  553. } else {
  554. let rank = listFavoriteIdentifierRank[itemIdentifier.rawValue]
  555. if rank == nil {
  556. let newRank = listFavoriteIdentifierRank.count + 1
  557. listFavoriteIdentifierRank[itemIdentifier.rawValue] = NSNumber(value: Int64(newRank))
  558. }
  559. }
  560. // Call the completion handler before performing any network activity or other long-running tasks. Defer these tasks to the background
  561. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  562. completionHandler(item, nil)
  563. /*
  564. guard let item = try? item(for: itemIdentifier) else {
  565. completionHandler(nil, NSFileProviderError(.noSuchItem))
  566. return
  567. }
  568. DispatchQueue(label: "com.nextcloud", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil).async {
  569. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  570. completionHandler(nil, NSFileProviderError(.noSuchItem))
  571. return
  572. }
  573. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  574. completionHandler(nil, NSFileProviderError(.noSuchItem))
  575. return
  576. }
  577. if (favorite == true && metadata.favorite == false) || (favorite == false && metadata.favorite == true) {
  578. ocNetworking?.settingFavorite(metadata.fileName, serverUrl: serverUrl, favorite: true, success: {
  579. metadata.favorite = favorite
  580. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  581. }, failure: { (errorMessage, errorCode) in
  582. print("errorMessage")
  583. })
  584. }
  585. }
  586. */
  587. }
  588. override func setLastUsedDate(_ lastUsedDate: Date?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  589. print("[LOG] setLastUsedDate")
  590. completionHandler(nil, nil)
  591. }
  592. override func setTagData(_ tagData: Data?, forItemIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  593. /* ONLY iOS 11*/
  594. guard #available(iOS 11, *) else {
  595. return
  596. }
  597. // Add, Remove (nil)
  598. NCManageDatabase.sharedInstance.addTag(itemIdentifier.rawValue, tagIOS: tagData)
  599. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID = %@", account, itemIdentifier.rawValue)) else {
  600. completionHandler(nil, NSFileProviderError(.noSuchItem))
  601. return
  602. }
  603. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  604. completionHandler(nil, NSFileProviderError(.noSuchItem))
  605. return
  606. }
  607. let item = FileProviderItem(metadata: metadata, serverUrl: serverUrl)
  608. completionHandler(item, nil)
  609. }
  610. /*
  611. override func trashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  612. print("[LOG] trashitem")
  613. completionHandler(nil, nil)
  614. }
  615. override func untrashItem(withIdentifier itemIdentifier: NSFileProviderItemIdentifier, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier?, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  616. print("[LOG] untrashitem")
  617. completionHandler(nil, nil)
  618. }
  619. */
  620. override func importDocument(at fileURL: URL, toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier, completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) {
  621. /* ONLY iOS 11*/
  622. guard #available(iOS 11, *) else {
  623. return
  624. }
  625. var fileName = fileURL.lastPathComponent
  626. let fileCoordinator = NSFileCoordinator()
  627. var error: NSError?
  628. var directoryPredicate: NSPredicate
  629. var size = 0 as Double
  630. var fileNamePathUpload: URL?
  631. if parentItemIdentifier == .rootContainer {
  632. directoryPredicate = NSPredicate(format: "account = %@ AND serverUrl = %@", account, homeServerUrl)
  633. } else {
  634. directoryPredicate = NSPredicate(format: "account = %@ AND fileID = %@", account, parentItemIdentifier.rawValue)
  635. }
  636. guard let directoryParent = NCManageDatabase.sharedInstance.getTableDirectory(predicate: directoryPredicate) else {
  637. completionHandler(nil, NSFileProviderError(.noSuchItem))
  638. return
  639. }
  640. let serverUrl = directoryParent.serverUrl
  641. // --------------------------------------------- Copy file here
  642. if fileURL.startAccessingSecurityScopedResource() == false {
  643. completionHandler(nil, NSFileProviderError(.noSuchItem))
  644. return
  645. }
  646. // exists with same name ? add + 1
  647. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileNameView = %@ AND directoryID = %@", account, fileName, directoryParent.directoryID)) != nil {
  648. var name = NSString(string: fileName).deletingPathExtension
  649. let ext = NSString(string: fileName).pathExtension
  650. let characters = Array(name)
  651. if characters.count < 2 {
  652. fileName = name + " " + "1" + "." + ext
  653. } else {
  654. let space = characters[characters.count-2]
  655. let numChar = characters[characters.count-1]
  656. var num = Int(String(numChar))
  657. if (space == " " && num != nil) {
  658. name = String(name.dropLast())
  659. num = num! + 1
  660. fileName = name + "\(num!)" + "." + ext
  661. } else {
  662. fileName = name + " " + "1" + "." + ext
  663. }
  664. }
  665. }
  666. let fileNameLocalPath = importDocumentURL!.appendingPathComponent(fileName)
  667. fileCoordinator.coordinate(readingItemAt: fileURL, options: NSFileCoordinator.ReadingOptions.withoutChanges, error: &error) { (url) in
  668. _ = self.copyFile( url.path, toPath: fileNameLocalPath.path)
  669. }
  670. fileURL.stopAccessingSecurityScopedResource()
  671. // ------------------------------------------------------------
  672. // ---------------------------------------------- Create file 0
  673. do {
  674. let attributes = try FileManager.default.attributesOfItem(atPath: fileNameLocalPath.path)
  675. size = attributes[FileAttributeKey.size] as! Double
  676. } catch let error {
  677. print("error: \(error)")
  678. }
  679. // Upload file 0 len
  680. if (size == 0) {
  681. fileNamePathUpload = fileNameLocalPath
  682. } else {
  683. fileNamePathUpload = importDocumentURL!.appendingPathComponent(fileName+".000")
  684. do {
  685. try FileManager.default.removeItem(atPath: fileNamePathUpload!.path)
  686. } catch let error {
  687. print("error: \(error)")
  688. }
  689. FileManager.default.createFile(atPath: fileNamePathUpload!.path, contents: nil, attributes: nil)
  690. }
  691. // ------------------------------------------------------------
  692. // upload
  693. _ = ocNetworking?.uploadFileNameServerUrl(serverUrl+"/"+fileName, fileNameLocalPath: fileNamePathUpload?.path, communication: CCNetworking.shared().sharedOCCommunication(), success: { (fileID, etag, date) in
  694. let metadata = tableMetadata()
  695. metadata.account = account
  696. metadata.date = date! as NSDate
  697. metadata.directory = false
  698. metadata.directoryID = directoryParent.directoryID
  699. metadata.etag = etag!
  700. metadata.fileID = fileID!
  701. metadata.fileName = fileName
  702. metadata.fileNameView = fileName
  703. metadata.size = 0
  704. CCUtility.insertTypeFileIconName(fileName, metadata: metadata)
  705. guard let metadataDB = NCManageDatabase.sharedInstance.addMetadata(metadata) else {
  706. completionHandler(nil, NSFileProviderError(.noSuchItem))
  707. return
  708. }
  709. // Create dir <base storage directory>/<item identifier>
  710. do {
  711. try FileManager.default.createDirectory(atPath: fileProviderStorageURL!.appendingPathComponent(metadata.fileID).path, withIntermediateDirectories: true, attributes: nil)
  712. } catch let error {
  713. print("error: \(error)")
  714. }
  715. // copy <base storage directory>/<item identifier>/<item file name>
  716. _ = self.copyFile(fileNameLocalPath.path, toPath: "\(fileProviderStorageURL!.appendingPathComponent(metadata.fileID).path)/\(metadata.fileNameView)")
  717. // add item
  718. let item = FileProviderItem(metadata: metadataDB, serverUrl: serverUrl)
  719. // add queue upload if size > 0
  720. if (size > 0) {
  721. let metadataNet = CCMetadataNet()
  722. metadataNet.account = account
  723. metadataNet.assetLocalIdentifier = k_assetLocalIdentifierFileProviderStorage + fileID!
  724. metadataNet.fileName = fileName
  725. metadataNet.path = importDocumentURL!.path + "/" + metadata.fileNameView
  726. metadataNet.selector = selectorUploadFile
  727. metadataNet.selectorPost = ""
  728. metadataNet.serverUrl = serverUrl
  729. metadataNet.session = k_upload_session
  730. metadataNet.taskStatus = Int(k_taskStatusResume)
  731. _ = NCManageDatabase.sharedInstance.addQueueUpload(metadataNet: metadataNet)
  732. }
  733. if (size > 0) { // MICROSOFT 365
  734. self.refreshEnumerator(identifier: item.itemIdentifier, serverUrl: serverUrl)
  735. }
  736. completionHandler(item, nil)
  737. }, failure: { (errorMessage, errorCode) in
  738. completionHandler(nil, NSFileProviderError(.serverUnreachable))
  739. })
  740. }
  741. // --------------------------------------------------------------------------------------------
  742. // MARK: - User Function
  743. // --------------------------------------------------------------------------------------------
  744. func uploadCloud(_ fileName: String, serverUrl: String, fileNameLocalPath: String, metadata: tableMetadata, identifier: NSFileProviderItemIdentifier) {
  745. if let task = listUpload[identifier.rawValue] {
  746. task.cancel()
  747. }
  748. let task = ocNetworking?.uploadFileNameServerUrl(serverUrl+"/"+fileName, fileNameLocalPath: fileNameLocalPath, communication: CCNetworking.shared().sharedOCCommunicationExtensionUpload(fileName), success: { (fileID, etag, date) in
  749. // Remove file on queueUpload
  750. NCManageDatabase.sharedInstance.deleteQueueUpload(path: fileNameLocalPath)
  751. // Remove from dictionary
  752. self.listUpload.removeValue(forKey: identifier.rawValue)
  753. metadata.date = date! as NSDate
  754. do {
  755. let attributes = try FileManager.default.attributesOfItem(atPath: fileNameLocalPath)
  756. metadata.size = attributes[FileAttributeKey.size] as! Double
  757. } catch let error {
  758. print("error: \(error)")
  759. }
  760. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  761. // Remove file *changeDocument
  762. _ = self.deleteFile(fileNameLocalPath)
  763. // Refresh
  764. self.refreshEnumerator(identifier: identifier, serverUrl: serverUrl)
  765. }, failure: { (errorMessage, errorCode) in
  766. // Remove from dictionary
  767. self.listUpload.removeValue(forKey: identifier.rawValue)
  768. // Refresh
  769. self.refreshEnumerator(identifier: identifier, serverUrl: serverUrl)
  770. })
  771. if (task != nil) {
  772. listUpload[identifier.rawValue] = task
  773. if #available(iOSApplicationExtension 11.0, *) {
  774. NSFileProviderManager.default.register(task!, forItemWithIdentifier: identifier) { (error) in
  775. print("Registe download task")
  776. }
  777. }
  778. }
  779. }
  780. func refreshEnumerator(identifier: NSFileProviderItemIdentifier, serverUrl: String) {
  781. /* ONLY iOS 11*/
  782. guard #available(iOS 11, *) else {
  783. return
  784. }
  785. let item = try? self.item(for: identifier)
  786. if item != nil {
  787. var found = false
  788. for updateItem in listUpdateItems {
  789. if updateItem.itemIdentifier.rawValue == identifier.rawValue {
  790. found = true
  791. }
  792. }
  793. if !found {
  794. listUpdateItems.append(item!)
  795. }
  796. }
  797. if serverUrl == homeServerUrl {
  798. NSFileProviderManager.default.signalEnumerator(for: .rootContainer, completionHandler: { (error) in
  799. print("send signal rootContainer")
  800. })
  801. } else if serverUrl == "WorkingSet" {
  802. NSFileProviderManager.default.signalEnumerator(for: .workingSet, completionHandler: { (error) in
  803. print("send signal workingSet")
  804. })
  805. } else {
  806. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl = %@", account, serverUrl)) {
  807. let itemDirectory = NSFileProviderItemIdentifier(directory.fileID)
  808. NSFileProviderManager.default.signalEnumerator(for: itemDirectory, completionHandler: { (error) in
  809. print("send signal")
  810. })
  811. }
  812. }
  813. }
  814. func copyFile(_ atPath: String, toPath: String) -> Error? {
  815. var errorResult: Error?
  816. do {
  817. try FileManager.default.removeItem(atPath: toPath)
  818. } catch let error {
  819. print("error: \(error)")
  820. }
  821. do {
  822. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  823. } catch let error {
  824. errorResult = error
  825. }
  826. return errorResult
  827. }
  828. func deleteFile(_ atPath: String) -> Error? {
  829. var errorResult: Error?
  830. do {
  831. try FileManager.default.removeItem(atPath: atPath)
  832. } catch let error {
  833. errorResult = error
  834. }
  835. return errorResult
  836. }
  837. }