DocumentPickerViewController.swift 28 KB

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