DocumentPickerViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //
  2. // DocumentPickerViewController.swift
  3. // Picker
  4. //
  5. // Created by Marino Faggiana on 27/12/16.
  6. // Copyright © 2016 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 UIKit
  24. class DocumentPickerViewController: UIDocumentPickerExtensionViewController, CCNetworkingDelegate, OCNetworkingDelegate {
  25. // MARK: - Properties
  26. var provider : providerSession?
  27. var metadata : CCMetadata?
  28. var recordsTableMetadata : [TableMetadata]?
  29. var titleFolder : String?
  30. var activeAccount : String?
  31. var activeUrl : String?
  32. var activeUser : String?
  33. var activePassword : String?
  34. var activeUID : String?
  35. var activeAccessToken : String?
  36. var directoryUser : String?
  37. var typeCloud : String?
  38. var serverUrl : String?
  39. var localServerUrl : String?
  40. var thumbnailInLoading = [String: IndexPath]()
  41. lazy var networkingOperationQueue : OperationQueue = {
  42. var queue = OperationQueue()
  43. queue.name = netQueueName
  44. queue.maxConcurrentOperationCount = 10
  45. return queue
  46. }()
  47. var hud : CCHud!
  48. // MARK: - IBOutlets
  49. @IBOutlet weak var tableView: UITableView!
  50. // MARK: - View Life Cycle
  51. override func viewDidLoad() {
  52. provider = providerSession.sharedInstance
  53. if let record = CCCoreData.getActiveAccount() {
  54. activeAccount = record.account!
  55. activePassword = record.password!
  56. activeUrl = record.url!
  57. activeUser = record.user!
  58. typeCloud = record.typeCloud!
  59. directoryUser = CCUtility.getDirectoryActiveUser(activeUser, activeUrl: activeUrl)
  60. if (localServerUrl == nil) {
  61. localServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeUrl, typeCloud: typeCloud)
  62. } else {
  63. self.navigationItem.title = titleFolder
  64. }
  65. } else {
  66. // Close error no account return nil
  67. let deadlineTime = DispatchTime.now() + 0.1
  68. DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  69. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  70. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  71. self.dismissGrantingAccess(to: nil)
  72. })
  73. self.present(alert, animated: true, completion: nil)
  74. }
  75. return
  76. }
  77. // MARK: - init Object
  78. CCNetworking.shared().settingDelegate(self)
  79. hud = CCHud.init(view: self.navigationController?.view)
  80. // COLOR_SEPARATOR_TABLE
  81. self.tableView.separatorColor = UIColor(colorLiteralRed: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 0.2)
  82. readFolder()
  83. }
  84. // MARK: - Read folder
  85. func readFolder() {
  86. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  87. metadataNet.action = actionReadFolder
  88. metadataNet.serverUrl = localServerUrl
  89. metadataNet.selector = selectorReadFolder
  90. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  91. networkingOperationQueue.addOperation(ocNetworking)
  92. hud.visibleIndeterminateHud()
  93. }
  94. func readFolderFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  95. hud.hideHud()
  96. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  97. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  98. self.dismissGrantingAccess(to: nil)
  99. })
  100. self.present(alert, animated: true, completion: nil)
  101. }
  102. func readFolderSuccess(_ metadataNet: CCMetadataNet!, permissions: String!, rev: String!, metadatas: [Any]!) {
  103. // remove all record
  104. let predicate = NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)') AND ((session == NULL) OR (session == ''))")
  105. CCCoreData.deleteMetadata(with: predicate)
  106. for metadata in metadatas as! [CCMetadata] {
  107. // do not insert crypto file
  108. if CCUtility.isCryptoString(metadata.fileName) {
  109. continue
  110. }
  111. // plist + crypto = completed ?
  112. if CCUtility.isCryptoPlistString(metadata.fileName) && metadata.directory == false {
  113. var isCryptoComplete = false
  114. for completeMetadata in metadatas as! [CCMetadata] {
  115. if completeMetadata.fileName == CCUtility.trasformedFileNamePlist(inCrypto: metadata.fileName) {
  116. isCryptoComplete = true
  117. }
  118. }
  119. if isCryptoComplete == false {
  120. continue
  121. }
  122. }
  123. // Add record
  124. CCCoreData.add(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, context: nil)
  125. // if plist do not exists, download it
  126. if CCUtility.isCryptoPlistString(metadata.fileName) && FileManager.default.fileExists(atPath: "\(directoryUser!)/\(metadata.fileName!)") == false {
  127. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  128. metadataNet.action = actionDownloadFile
  129. metadataNet.metadata = metadata
  130. metadataNet.downloadData = false
  131. metadataNet.downloadPlist = true
  132. metadataNet.selector = selectorLoadPlist
  133. metadataNet.serverUrl = localServerUrl
  134. metadataNet.session = download_session_foreground
  135. metadataNet.taskStatus = Int(taskStatusResume)
  136. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  137. networkingOperationQueue.addOperation(ocNetworking)
  138. }
  139. }
  140. // Get Datasource
  141. recordsTableMetadata = CCCoreData.getTableMetadata(with: NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)')"), fieldOrder: "fileName", ascending: true) as? [TableMetadata]
  142. tableView.reloadData()
  143. hud.hideHud()
  144. }
  145. // MARK: - Download
  146. func progressTask(_ fileID: String!, serverUrl: String!, cryptated: Bool, progress: Float) {
  147. hud.progress(progress)
  148. }
  149. func cancelTransfer() {
  150. networkingOperationQueue.cancelAllOperations()
  151. }
  152. func downloadFileFailure(_ fileID: String!, serverUrl: String!, selector: String!, message: String!, errorCode: Int) {
  153. hud.hideHud()
  154. if selector == selectorLoadFileView && errorCode != -999 {
  155. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  156. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  157. //self.dismissGrantingAccess(to: nil)
  158. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  159. })
  160. self.present(alert, animated: true, completion: nil)
  161. }
  162. }
  163. func downloadFileSuccess(_ fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!) {
  164. hud.hideHud()
  165. let metadata = CCCoreData.getMetadataWithPreficate(NSPredicate(format: "(account == '\(activeAccount!)') AND (fileID == '\(fileID!)')"), context: nil)
  166. switch selector {
  167. case selectorLoadFileView :
  168. do {
  169. try FileManager.default.moveItem(atPath: "\(directoryUser!)/\(fileID!)", toPath: "\(directoryUser!)/\(metadata!.fileNamePrint!)")
  170. } catch let error as NSError {
  171. print(error)
  172. }
  173. let url = URL(string: "file://\(directoryUser!)/\(metadata!.fileNamePrint!)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
  174. self.dismissGrantingAccess(to: url)
  175. break
  176. case selectorLoadPlist :
  177. CCCoreData.downloadFilePlist(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, directoryUser: directoryUser)
  178. tableView.reloadData()
  179. default :
  180. break
  181. }
  182. }
  183. // MARK: - Download Thumbnail
  184. func downloadThumbnailFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  185. NSLog("[LOG] Thumbnail Error \(metadataNet.fileName) \(message) (error \(errorCode))");
  186. }
  187. func downloadThumbnailSuccess(_ metadataNet: CCMetadataNet!) {
  188. if let indexPath = thumbnailInLoading[metadataNet.fileID] {
  189. let path = "\(directoryUser!)/\(metadataNet.fileID!).ico"
  190. if FileManager.default.fileExists(atPath: path) {
  191. if let cell = tableView.cellForRow(at: indexPath) as? recordMetadataCell {
  192. cell.fileImageView.image = UIImage(contentsOfFile: path)
  193. }
  194. }
  195. }
  196. }
  197. func downloadThumbnail(_ metadata : CCMetadata) {
  198. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  199. metadataNet.action = actionDownloadThumbnail
  200. metadataNet.fileID = metadata.fileID
  201. metadataNet.fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: localServerUrl, activeUrl: activeUrl, typeCloud: typeCloud)
  202. metadataNet.fileNameLocal = metadata.fileID;
  203. metadataNet.fileNamePrint = metadata.fileNamePrint;
  204. metadataNet.options = "m";
  205. metadataNet.selector = selectorDownloadThumbnail;
  206. metadataNet.serverUrl = localServerUrl
  207. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  208. networkingOperationQueue.addOperation(ocNetworking)
  209. }
  210. }
  211. // MARK: - UITableViewDelegate
  212. extension DocumentPickerViewController: UITableViewDelegate {
  213. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  214. return 50
  215. }
  216. }
  217. // MARK: - UITableViewDataSource
  218. extension DocumentPickerViewController: UITableViewDataSource {
  219. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  220. if (recordsTableMetadata == nil) {
  221. return 0
  222. } else {
  223. return recordsTableMetadata!.count
  224. }
  225. }
  226. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  227. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  228. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  229. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  230. let metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  231. // File Image View
  232. let filePath = "\(directoryUser!)/\(metadata.fileID!).ico"
  233. if FileManager.default.fileExists(atPath: filePath) {
  234. cell.fileImageView.image = UIImage(contentsOfFile: filePath)
  235. } else {
  236. cell.fileImageView.image = UIImage(named: metadata.iconName!)
  237. if metadata.thumbnailExists && metadata.directory == false {
  238. downloadThumbnail(metadata)
  239. thumbnailInLoading[metadata.fileID] = indexPath
  240. }
  241. }
  242. // File Name
  243. cell.FileName.text = metadata.fileNamePrint
  244. return cell
  245. }
  246. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  247. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  248. tableView.deselectRow(at: indexPath, animated: true)
  249. if recordTableMetadata!.directory == 0 {
  250. let metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  251. if FileManager.default.fileExists(atPath: "\(directoryUser!)/\(metadata.fileID!)") {
  252. downloadFileSuccess(metadata.fileID!, serverUrl: localServerUrl!, selector: selectorLoadFileView, selectorPost: nil)
  253. } else {
  254. // Download file
  255. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  256. metadataNet.action = actionDownloadFile
  257. metadataNet.downloadData = true
  258. metadataNet.downloadPlist = false
  259. metadataNet.metadata = metadata
  260. metadataNet.selector = selectorLoadFileView
  261. metadataNet.serverUrl = localServerUrl
  262. metadataNet.session = download_session_foreground
  263. metadataNet.taskStatus = Int(taskStatusResume)
  264. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  265. networkingOperationQueue.addOperation(ocNetworking)
  266. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinateHorizontalBar, color: self.navigationController?.view.tintColor)
  267. hud.addButtonCancel(withTarget: self, selector: "cancelTransfer")
  268. }
  269. } else {
  270. var dir : String! = recordTableMetadata!.fileName
  271. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  272. if recordTableMetadata?.cryptated == 1 {
  273. dir = CCUtility.trasformedFileNamePlist(inCrypto: recordTableMetadata!.fileName)
  274. }
  275. nextViewController.localServerUrl = CCUtility.stringAppendServerUrl(localServerUrl!, addServerUrl: dir)
  276. nextViewController.titleFolder = recordTableMetadata?.fileNamePrint
  277. self.navigationController?.pushViewController(nextViewController, animated: true)
  278. }
  279. }
  280. }
  281. // MARK: - Class UITableViewCell
  282. class recordMetadataCell: UITableViewCell {
  283. @IBOutlet weak var fileImageView: UIImageView!
  284. @IBOutlet weak var FileName : UILabel!
  285. }
  286. // MARK: - Class providerSession
  287. class providerSession {
  288. class var sharedInstance : providerSession {
  289. struct Static {
  290. static let instance = providerSession()
  291. }
  292. return Static.instance
  293. }
  294. private init() {
  295. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: capabilitiesGroups)
  296. let pathDB = dirGroup?.appendingPathComponent(appDatabase).appendingPathComponent("cryptocloud")
  297. MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStore(at: pathDB!)
  298. MagicalRecord.setLoggingLevel(MagicalRecordLoggingLevel.off)
  299. }
  300. }