DocumentPickerViewController.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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, BKPasscodeViewControllerDelegate {
  25. // MARK: - Properties
  26. var providerDB : providerSessionDB?
  27. lazy var fileCoordinator: NSFileCoordinator = {
  28. let fileCoordinator = NSFileCoordinator()
  29. fileCoordinator.purposeIdentifier = self.parameterProviderIdentifier
  30. return fileCoordinator
  31. }()
  32. var parameterMode : UIDocumentPickerMode?
  33. var parameterOriginalURL: URL?
  34. var parameterProviderIdentifier: String!
  35. var metadata : CCMetadata?
  36. var recordsTableMetadata : [TableMetadata]?
  37. var titleFolder : String?
  38. var activeAccount : String?
  39. var activeUrl : String?
  40. var activeUser : String?
  41. var activePassword : String?
  42. var activeUID : String?
  43. var activeAccessToken : String?
  44. var directoryUser : String?
  45. var typeCloud : String?
  46. var serverUrl : String?
  47. var localServerUrl : String?
  48. var thumbnailInLoading = [String: IndexPath]()
  49. var destinationURL : URL?
  50. var failedAttempts : UInt?
  51. var lockUntilDate : Date?
  52. lazy var networkingOperationQueue : OperationQueue = {
  53. var queue = OperationQueue()
  54. queue.name = netQueueName
  55. queue.maxConcurrentOperationCount = 10
  56. return queue
  57. }()
  58. var hud : CCHud!
  59. // MARK: - IBOutlets
  60. @IBOutlet weak var tableView: UITableView!
  61. @IBOutlet weak var toolBar: UIToolbar!
  62. @IBOutlet weak var saveButton: UIBarButtonItem!
  63. // MARK: - View Life Cycle
  64. override func viewDidLoad() {
  65. providerDB = providerSessionDB.sharedInstance
  66. if let record = CCCoreData.getActiveAccount() {
  67. activeAccount = record.account!
  68. activePassword = record.password!
  69. activeUrl = record.url!
  70. activeUser = record.user!
  71. typeCloud = record.typeCloud!
  72. directoryUser = CCUtility.getDirectoryActiveUser(activeUser, activeUrl: activeUrl)
  73. if (localServerUrl == nil) {
  74. localServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeUrl, typeCloud: typeCloud)
  75. } else {
  76. self.navigationItem.title = titleFolder
  77. }
  78. } else {
  79. // Close error no account return nil
  80. let deadlineTime = DispatchTime.now() + 0.1
  81. DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  82. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  83. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  84. self.dismissGrantingAccess(to: nil)
  85. })
  86. self.present(alert, animated: true, completion: nil)
  87. }
  88. return
  89. }
  90. // MARK: - init Object
  91. CCNetworking.shared().settingDelegate(self)
  92. hud = CCHud.init(view: self.navigationController?.view)
  93. // COLOR_SEPARATOR_TABLE
  94. self.tableView.separatorColor = UIColor(colorLiteralRed: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 0.2)
  95. // (save) mode of presentation -> pass variable for pushViewController
  96. if parameterMode != nil {
  97. prepareForPresentation(in: parameterMode!)
  98. }
  99. readFolder()
  100. }
  101. override func viewWillAppear(_ animated: Bool) {
  102. super.viewWillAppear(animated)
  103. if CCUtility.getBlockCode().characters.count > 0 && CCUtility.getOnlyLockDir() == false {
  104. openBKPasscode()
  105. }
  106. }
  107. // MARK: - Overridden Instance Methods
  108. override func prepareForPresentation(in mode: UIDocumentPickerMode) {
  109. // ------------------> Settings parameter ----------------
  110. if parameterMode == nil {
  111. parameterMode = mode
  112. }
  113. if parameterOriginalURL == nil && originalURL != nil {
  114. parameterOriginalURL = originalURL
  115. }
  116. if parameterProviderIdentifier == nil {
  117. parameterProviderIdentifier = providerIdentifier
  118. }
  119. // -------------------------------------------------------
  120. switch mode {
  121. case .exportToService:
  122. print("Document Picker Mode : exportToService")
  123. saveButton.title = "Save in this position"
  124. case .moveToService:
  125. //Show confirmation button
  126. print("Document Picker Mode : moveToService")
  127. saveButton.title = "Save in this position"
  128. case .open:
  129. print("Document Picker Mode : open")
  130. saveButton.tintColor = UIColor.clear
  131. case .import:
  132. print("Document Picker Mode : import")
  133. saveButton.tintColor = UIColor.clear
  134. }
  135. }
  136. // MARK: - Read folder
  137. func readFolder() {
  138. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  139. metadataNet.action = actionReadFolder
  140. metadataNet.serverUrl = localServerUrl
  141. metadataNet.selector = selectorReadFolder
  142. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  143. networkingOperationQueue.addOperation(ocNetworking)
  144. hud.visibleIndeterminateHud()
  145. }
  146. func readFolderFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  147. hud.hideHud()
  148. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  149. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  150. self.dismissGrantingAccess(to: nil)
  151. })
  152. self.present(alert, animated: true, completion: nil)
  153. }
  154. func readFolderSuccess(_ metadataNet: CCMetadataNet!, permissions: String!, rev: String!, metadatas: [Any]!) {
  155. // remove all record
  156. let predicate = NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)') AND ((session == NULL) OR (session == ''))")
  157. CCCoreData.deleteMetadata(with: predicate)
  158. for metadata in metadatas as! [CCMetadata] {
  159. // do not insert crypto file
  160. if CCUtility.isCryptoString(metadata.fileName) {
  161. continue
  162. }
  163. // Only Directory ?
  164. if (parameterMode == .moveToService || parameterMode == .exportToService) && metadata.directory == false {
  165. continue
  166. }
  167. // plist + crypto = completed ?
  168. if CCUtility.isCryptoPlistString(metadata.fileName) && metadata.directory == false {
  169. var isCryptoComplete = false
  170. for completeMetadata in metadatas as! [CCMetadata] {
  171. if completeMetadata.fileName == CCUtility.trasformedFileNamePlist(inCrypto: metadata.fileName) {
  172. isCryptoComplete = true
  173. }
  174. }
  175. if isCryptoComplete == false {
  176. continue
  177. }
  178. }
  179. // Add record
  180. CCCoreData.add(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, context: nil)
  181. // if plist do not exists, download it
  182. if CCUtility.isCryptoPlistString(metadata.fileName) && FileManager.default.fileExists(atPath: "\(directoryUser!)/\(metadata.fileName!)") == false {
  183. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  184. metadataNet.action = actionDownloadFile
  185. metadataNet.metadata = metadata
  186. metadataNet.downloadData = false
  187. metadataNet.downloadPlist = true
  188. metadataNet.selector = selectorLoadPlist
  189. metadataNet.serverUrl = localServerUrl
  190. metadataNet.session = download_session_foreground
  191. metadataNet.taskStatus = Int(taskStatusResume)
  192. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  193. networkingOperationQueue.addOperation(ocNetworking)
  194. }
  195. }
  196. // Get Datasource
  197. recordsTableMetadata = CCCoreData.getTableMetadata(with: NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)')"), fieldOrder: "fileName", ascending: true) as? [TableMetadata]
  198. tableView.reloadData()
  199. hud.hideHud()
  200. }
  201. // MARK: - Download / Upload
  202. func progressTask(_ fileID: String!, serverUrl: String!, cryptated: Bool, progress: Float) {
  203. hud.progress(progress)
  204. }
  205. func cancelTransfer() {
  206. networkingOperationQueue.cancelAllOperations()
  207. }
  208. // MARK: - Download
  209. func downloadFileFailure(_ fileID: String!, serverUrl: String!, selector: String!, message: String!, errorCode: Int) {
  210. hud.hideHud()
  211. if selector == selectorLoadFileView && errorCode != -999 {
  212. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  213. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  214. //self.dismissGrantingAccess(to: nil)
  215. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  216. })
  217. self.present(alert, animated: true, completion: nil)
  218. }
  219. }
  220. func downloadFileSuccess(_ fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!) {
  221. hud.hideHud()
  222. let metadata = CCCoreData.getMetadataWithPreficate(NSPredicate(format: "(account == '\(activeAccount!)') AND (fileID == '\(fileID!)')"), context: nil)
  223. switch selector {
  224. case selectorLoadFileView :
  225. do {
  226. try FileManager.default.moveItem(atPath: "\(directoryUser!)/\(fileID!)", toPath: "\(directoryUser!)/\(metadata!.fileNamePrint!)")
  227. } catch let error as NSError {
  228. print(error)
  229. }
  230. let url = URL(string: "file://\(directoryUser!)/\(metadata!.fileNamePrint!)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
  231. self.dismissGrantingAccess(to: url)
  232. case selectorLoadPlist :
  233. CCCoreData.downloadFilePlist(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, directoryUser: directoryUser)
  234. tableView.reloadData()
  235. default :
  236. print("selector : \(selector!)")
  237. tableView.reloadData()
  238. }
  239. }
  240. // MARK: - Upload
  241. func uploadFileFailure(_ fileID: String!, serverUrl: String!, selector: String!, message: String!, errorCode: Int) {
  242. hud.hideHud()
  243. // remove file
  244. CCCoreData.deleteMetadata(with: NSPredicate(format: "(account == '\(activeAccount!)') AND (fileID == '\(fileID!)')"))
  245. if errorCode != -999 {
  246. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  247. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  248. //self.dismissGrantingAccess(to: nil)
  249. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  250. })
  251. self.present(alert, animated: true, completion: nil)
  252. }
  253. }
  254. func uploadFileSuccess(_ fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!) {
  255. hud.hideHud()
  256. dismissGrantingAccess(to: self.destinationURL)
  257. }
  258. // MARK: - Download Thumbnail
  259. func downloadThumbnailFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  260. NSLog("[LOG] Thumbnail Error \(metadataNet.fileName) \(message) (error \(errorCode))");
  261. }
  262. func downloadThumbnailSuccess(_ metadataNet: CCMetadataNet!) {
  263. if let indexPath = thumbnailInLoading[metadataNet.fileID] {
  264. let path = "\(directoryUser!)/\(metadataNet.fileID!).ico"
  265. if FileManager.default.fileExists(atPath: path) {
  266. if let cell = tableView.cellForRow(at: indexPath) as? recordMetadataCell {
  267. cell.fileImageView.image = UIImage(contentsOfFile: path)
  268. }
  269. }
  270. }
  271. }
  272. func downloadThumbnail(_ metadata : CCMetadata) {
  273. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  274. metadataNet.action = actionDownloadThumbnail
  275. metadataNet.fileID = metadata.fileID
  276. metadataNet.fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: localServerUrl, activeUrl: activeUrl, typeCloud: typeCloud)
  277. metadataNet.fileNameLocal = metadata.fileID;
  278. metadataNet.fileNamePrint = metadata.fileNamePrint;
  279. metadataNet.options = "m";
  280. metadataNet.selector = selectorDownloadThumbnail;
  281. metadataNet.serverUrl = localServerUrl
  282. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  283. networkingOperationQueue.addOperation(ocNetworking)
  284. }
  285. }
  286. // MARK: - IBActions
  287. extension DocumentPickerViewController {
  288. @IBAction func saveButtonTapped(_ sender: AnyObject) {
  289. guard let sourceURL = parameterOriginalURL else {
  290. return
  291. }
  292. switch parameterMode! {
  293. case .moveToService, .exportToService:
  294. let fileName = sourceURL.lastPathComponent
  295. guard let destinationURLDirectoryUser = URL(string: "file://\(directoryUser!)/\(fileName)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!) else {
  296. return
  297. }
  298. self.destinationURL = appGroupContainerURL()?.appendingPathComponent(fileName)
  299. // copy sourceURL on directoryUser
  300. do {
  301. try FileManager.default.removeItem(at: destinationURLDirectoryUser)
  302. } catch _ {
  303. print("file do not exists")
  304. }
  305. do {
  306. try FileManager.default.copyItem(at: sourceURL, to: destinationURLDirectoryUser)
  307. } catch _ {
  308. print("file do not exists")
  309. return
  310. }
  311. fileCoordinator.coordinate(readingItemAt: sourceURL, options: .withoutChanges, error: nil, byAccessor: { [weak self] newURL in
  312. do {
  313. try FileManager.default.removeItem(at: (self?.destinationURL)!)
  314. } catch _ {
  315. print("file do not exists")
  316. }
  317. do {
  318. try FileManager.default.copyItem(at: sourceURL, to: (self?.destinationURL)!)
  319. // Upload fileName to Cloud
  320. let metadataNet = CCMetadataNet.init(account: self!.activeAccount)!
  321. metadataNet.action = actionUploadFile
  322. metadataNet.cryptated = false
  323. metadataNet.fileName = fileName
  324. metadataNet.fileNamePrint = fileName
  325. metadataNet.serverUrl = self!.localServerUrl
  326. metadataNet.session = upload_session_foreground
  327. metadataNet.taskStatus = Int(taskStatusResume)
  328. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self!, metadataNet: metadataNet, withUser: self!.activeUser, withPassword: self!.activePassword, withUrl: self!.activeUrl, withTypeCloud: self!.typeCloud, activityIndicator: false)
  329. self!.networkingOperationQueue.addOperation(ocNetworking)
  330. self!.hud.visibleHudTitle(NSLocalizedString("_uploading_", comment: ""), mode: MBProgressHUDMode.determinateHorizontalBar, color: self!.navigationController?.view.tintColor)
  331. self!.hud.addButtonCancel(withTarget: self, selector: "cancelTransfer")
  332. } catch _ {
  333. print("error copying file")
  334. }
  335. })
  336. default:
  337. dismiss(animated: true, completion: nil)
  338. }
  339. }
  340. func appGroupContainerURL() -> URL? {
  341. guard let groupURL = FileManager.default
  342. .containerURL(forSecurityApplicationGroupIdentifier: capabilitiesGroups) else {
  343. return nil
  344. }
  345. let storagePathUrl = groupURL.appendingPathComponent("File Provider Storage")
  346. let storagePath = storagePathUrl.path
  347. if !FileManager.default.fileExists(atPath: storagePath) {
  348. do {
  349. try FileManager.default.createDirectory(atPath: storagePath, withIntermediateDirectories: false, attributes: nil)
  350. } catch let error {
  351. print("error creating filepath: \(error)")
  352. return nil
  353. }
  354. }
  355. return storagePathUrl
  356. }
  357. func openBKPasscode() {
  358. let viewController = CCBKPasscode.init()
  359. viewController.delegate = self
  360. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  361. viewController.inputViewTitlePassword = true
  362. if CCUtility.getSimplyBlockCode() {
  363. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  364. viewController.passcodeInputView.maximumLength = 6
  365. } else {
  366. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  367. viewController.passcodeInputView.maximumLength = 64
  368. }
  369. let touchIDManager = BKTouchIDManager.init(keychainServiceName: BKPasscodeKeychainServiceName)
  370. touchIDManager?.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  371. viewController.touchIDManager = touchIDManager
  372. #if CC
  373. viewController.title = "Crypto Cloud"
  374. #endif
  375. #if NC
  376. viewController.title = "Nextcloud"
  377. #endif
  378. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(sender:)))
  379. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor(colorLiteralRed: 241.0/255.0, green: 90.0/255.0, blue: 34.0/255.0, alpha: 1.0) // COLOR_ENCRYPTED
  380. let navController = UINavigationController.init(rootViewController: viewController)
  381. self.present(navController, animated: true, completion: nil)
  382. }
  383. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  384. return 0
  385. }
  386. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date! {
  387. return nil
  388. }
  389. func passcodeViewCloseButtonPressed(sender :Any) {
  390. dismiss(animated: true, completion: {
  391. self.dismissGrantingAccess(to: nil)
  392. })
  393. }
  394. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  395. if aPasscode == CCUtility.getBlockCode() {
  396. lockUntilDate = nil
  397. failedAttempts = 0
  398. aResultHandler(true)
  399. } else {
  400. aResultHandler(false)
  401. }
  402. }
  403. public func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  404. aViewController.dismiss(animated: true, completion: nil)
  405. }
  406. }
  407. // MARK: - UITableViewDelegate
  408. extension DocumentPickerViewController: UITableViewDelegate {
  409. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  410. return 50
  411. }
  412. }
  413. // MARK: - UITableViewDataSource
  414. extension DocumentPickerViewController: UITableViewDataSource {
  415. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  416. if (recordsTableMetadata == nil) {
  417. return 0
  418. } else {
  419. return recordsTableMetadata!.count
  420. }
  421. }
  422. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  423. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  424. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  425. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  426. let metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  427. // File Image View
  428. let filePath = "\(directoryUser!)/\(metadata.fileID!).ico"
  429. if FileManager.default.fileExists(atPath: filePath) {
  430. cell.fileImageView.image = UIImage(contentsOfFile: filePath)
  431. } else {
  432. cell.fileImageView.image = UIImage(named: metadata.iconName!)
  433. if metadata.thumbnailExists && metadata.directory == false {
  434. downloadThumbnail(metadata)
  435. thumbnailInLoading[metadata.fileID] = indexPath
  436. }
  437. }
  438. // File Name
  439. cell.FileName.text = metadata.fileNamePrint
  440. return cell
  441. }
  442. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  443. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  444. tableView.deselectRow(at: indexPath, animated: true)
  445. if recordTableMetadata!.directory == 0 {
  446. let metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  447. if FileManager.default.fileExists(atPath: "\(directoryUser!)/\(metadata.fileID!)") {
  448. downloadFileSuccess(metadata.fileID!, serverUrl: localServerUrl!, selector: selectorLoadFileView, selectorPost: nil)
  449. } else {
  450. // Download file
  451. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  452. metadataNet.action = actionDownloadFile
  453. metadataNet.downloadData = true
  454. metadataNet.downloadPlist = false
  455. metadataNet.metadata = metadata
  456. metadataNet.selector = selectorLoadFileView
  457. metadataNet.serverUrl = localServerUrl
  458. metadataNet.session = download_session_foreground
  459. metadataNet.taskStatus = Int(taskStatusResume)
  460. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  461. networkingOperationQueue.addOperation(ocNetworking)
  462. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinateHorizontalBar, color: self.navigationController?.view.tintColor)
  463. hud.addButtonCancel(withTarget: self, selector: "cancelTransfer")
  464. }
  465. } else {
  466. var dir : String! = recordTableMetadata!.fileName
  467. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  468. if recordTableMetadata?.cryptated == 1 {
  469. dir = CCUtility.trasformedFileNamePlist(inCrypto: recordTableMetadata!.fileName)
  470. }
  471. nextViewController.parameterMode = parameterMode
  472. nextViewController.parameterOriginalURL = parameterOriginalURL
  473. nextViewController.parameterProviderIdentifier = parameterProviderIdentifier
  474. nextViewController.localServerUrl = CCUtility.stringAppendServerUrl(localServerUrl!, addServerUrl: dir)
  475. nextViewController.titleFolder = recordTableMetadata?.fileNamePrint
  476. self.navigationController?.pushViewController(nextViewController, animated: true)
  477. }
  478. }
  479. }
  480. // MARK: - Class UITableViewCell
  481. class recordMetadataCell: UITableViewCell {
  482. @IBOutlet weak var fileImageView: UIImageView!
  483. @IBOutlet weak var FileName : UILabel!
  484. }
  485. // MARK: - Class providerSession
  486. class providerSessionDB {
  487. class var sharedInstance : providerSessionDB {
  488. struct Static {
  489. static let instance = providerSessionDB()
  490. }
  491. return Static.instance
  492. }
  493. private init() {
  494. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: capabilitiesGroups)
  495. let pathDB = dirGroup?.appendingPathComponent(appDatabase).appendingPathComponent("cryptocloud")
  496. MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStore(at: pathDB!)
  497. MagicalRecord.setLoggingLevel(MagicalRecordLoggingLevel.off)
  498. }
  499. }