DocumentPickerViewController.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. //
  2. // DocumentPickerViewController.swift
  3. // Picker
  4. //
  5. // Created by Marino Faggiana on 27/12/16.
  6. // Copyright © 2017 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. lazy var fileCoordinator: NSFileCoordinator = {
  27. let fileCoordinator = NSFileCoordinator()
  28. fileCoordinator.purposeIdentifier = self.parameterProviderIdentifier
  29. return fileCoordinator
  30. }()
  31. var parameterMode: UIDocumentPickerMode?
  32. var parameterOriginalURL: URL?
  33. var parameterProviderIdentifier: String!
  34. var parameterPasscodeCorrect: Bool = false
  35. var recordMetadata = tableMetadata()
  36. var recordsTableMetadata: [tableMetadata]?
  37. var titleFolder: String = ""
  38. var activeAccount: String = ""
  39. var activeUrl: String = ""
  40. var activeUser: String = ""
  41. var activeUserID: String = ""
  42. var activePassword: String = ""
  43. var directoryUser: String = ""
  44. var serverUrl: String?
  45. var thumbnailInLoading = [String: IndexPath]()
  46. var destinationURL: URL?
  47. var passcodeFailedAttempts: UInt = 0
  48. var passcodeLockUntilDate: Date? = nil
  49. var passcodeIsPush: Bool = false
  50. var serverUrlPush: String = ""
  51. var autoUploadFileName = ""
  52. var autoUploadDirectory = ""
  53. lazy var networkingOperationQueue: OperationQueue = {
  54. var queue = OperationQueue()
  55. queue.name = k_queue
  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. // MARK: - View Life Cycle
  65. override func viewDidLoad() {
  66. super.viewDidLoad()
  67. if let record = NCManageDatabase.sharedInstance.getAccountActive() {
  68. activeAccount = record.account
  69. activePassword = record.password
  70. activeUrl = record.url
  71. activeUser = record.user
  72. activeUserID = record.userID
  73. directoryUser = CCUtility.getDirectoryActiveUser(activeUser, activeUrl: activeUrl)
  74. if serverUrl == nil {
  75. serverUrl = CCUtility.getHomeServerUrlActiveUrl(activeUrl)
  76. } else {
  77. self.navigationItem.title = titleFolder
  78. }
  79. } else {
  80. // Close error no account return nil
  81. let deadlineTime = DispatchTime.now() + 0.1
  82. DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  83. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  84. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  85. self.dismissGrantingAccess(to: nil)
  86. })
  87. self.present(alert, animated: true, completion: nil)
  88. }
  89. return
  90. }
  91. // MARK: - init Object
  92. CCNetworking.shared().delegate = self
  93. hud = CCHud.init(view: self.navigationController?.view)
  94. // Theming
  95. if (NCBrandOptions.sharedInstance.use_themingColor == true) {
  96. let tableCapabilities = NCManageDatabase.sharedInstance.getCapabilites()
  97. if (tableCapabilities != nil) {
  98. CCGraphics.settingThemingColor(tableCapabilities?.themingColor, themingColorElement: tableCapabilities?.themingColorElement, themingColorText: tableCapabilities?.themingColorText)
  99. }
  100. }
  101. // COLOR
  102. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  103. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  104. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: NCBrandColor.sharedInstance.brandText]
  105. self.navigationController?.navigationBar.isTranslucent = false
  106. self.tableView.separatorColor = NCBrandColor.sharedInstance.seperator
  107. self.tableView.tableFooterView = UIView()
  108. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: "NotificationProgressTask"), object: nil)
  109. readFolder()
  110. }
  111. override func viewWillAppear(_ animated: Bool) {
  112. super.viewWillAppear(animated)
  113. // BUGFIX 2.17 - Change user Nextcloud App
  114. CCNetworking.shared().settingAccount()
  115. // (save) mode of presentation -> pass variable for pushViewController
  116. prepareForPresentation(in: parameterMode!)
  117. // String is nil or empty
  118. guard let passcode = CCUtility.getBlockCode(), !passcode.isEmpty else {
  119. return
  120. }
  121. if CCUtility.getOnlyLockDir() == false && parameterPasscodeCorrect == false {
  122. openBKPasscode(NCBrandOptions.sharedInstance.brand)
  123. }
  124. }
  125. override func viewWillDisappear(_ animated: Bool) {
  126. // remove all networking operation
  127. networkingOperationQueue.cancelAllOperations()
  128. super.viewWillDisappear(animated)
  129. }
  130. // MARK: - Overridden Instance Methods
  131. override func prepareForPresentation(in mode: UIDocumentPickerMode) {
  132. // ------------------> Settings parameter ----------------
  133. if parameterMode == nil {
  134. parameterMode = mode
  135. }
  136. // Variable for exportToService or moveToService
  137. if parameterOriginalURL == nil && originalURL != nil {
  138. parameterOriginalURL = originalURL
  139. }
  140. if parameterProviderIdentifier == nil {
  141. parameterProviderIdentifier = providerIdentifier
  142. }
  143. // -------------------------------------------------------
  144. switch mode {
  145. case .exportToService:
  146. print("Document Picker Mode : exportToService")
  147. saveButton.title = NSLocalizedString("_save_document_picker_", comment: "") // Save in this position
  148. case .moveToService:
  149. //Show confirmation button
  150. print("Document Picker Mode : moveToService")
  151. saveButton.title = NSLocalizedString("_save_document_picker_", comment: "") // Save in this position
  152. case .open:
  153. print("Document Picker Mode : open")
  154. saveButton.tintColor = UIColor.clear
  155. case .import:
  156. print("Document Picker Mode : import")
  157. saveButton.tintColor = UIColor.clear
  158. }
  159. }
  160. // MARK: - Read folder
  161. func readFolder() {
  162. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  163. metadataNet.action = actionReadFolder
  164. metadataNet.depth = "1"
  165. metadataNet.serverUrl = self.serverUrl
  166. metadataNet.selector = selectorReadFolder
  167. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withUserID: activeUserID, withPassword: activePassword, withUrl: activeUrl)
  168. networkingOperationQueue.addOperation(ocNetworking)
  169. hud.visibleIndeterminateHud()
  170. }
  171. func readFolderSuccessFailure(_ metadataNet: CCMetadataNet!, metadataFolder: tableMetadata?, metadatas: [Any]!, message: String!, errorCode: Int) {
  172. if (errorCode == 0) {
  173. // remove all record
  174. var predicate = NSPredicate(format: "account = %@ AND directoryID = %@ AND session = ''", activeAccount, metadataNet.directoryID!)
  175. NCManageDatabase.sharedInstance.deleteMetadata(predicate: predicate, clearDateReadDirectoryID: metadataNet.directoryID!)
  176. for metadata in metadatas as! [tableMetadata] {
  177. // Only Directory ?
  178. if (parameterMode == .moveToService || parameterMode == .exportToService) && metadata.directory == false {
  179. continue
  180. }
  181. // Add record
  182. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  183. }
  184. predicate = NSPredicate(format: "account = %@ AND directoryID = %@", activeAccount, metadataNet.directoryID!)
  185. recordsTableMetadata = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate, sorted: "fileName", ascending: true)
  186. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  187. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(activeUrl)
  188. if (CCUtility.isEnd(toEndEnabled: activeAccount)) {
  189. }
  190. tableView.reloadData()
  191. hud.hideHud()
  192. } else {
  193. hud.hideHud()
  194. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  195. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  196. self.dismissGrantingAccess(to: nil)
  197. })
  198. self.present(alert, animated: true, completion: nil)
  199. }
  200. }
  201. // MARK: - Download Thumbnail
  202. func downloadThumbnailSuccessFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  203. if (errorCode == 0) {
  204. if let indexPath = thumbnailInLoading[metadataNet.fileID] {
  205. let path = "\(directoryUser)/\(metadataNet.fileID!).ico"
  206. if FileManager.default.fileExists(atPath: path) {
  207. if let cell = tableView.cellForRow(at: indexPath) as? recordMetadataCell {
  208. cell.fileImageView.image = UIImage(contentsOfFile: path)
  209. }
  210. }
  211. }
  212. } else {
  213. NSLog("[LOG] Thumbnail Error \(metadataNet.fileName) \(message) (error \(errorCode))");
  214. }
  215. }
  216. func downloadThumbnail(_ metadata : tableMetadata) {
  217. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  218. metadataNet.action = actionDownloadThumbnail
  219. metadataNet.fileID = metadata.fileID
  220. metadataNet.fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: self.serverUrl, activeUrl: activeUrl)
  221. metadataNet.options = "m";
  222. metadataNet.selector = selectorDownloadThumbnail;
  223. metadataNet.serverUrl = self.serverUrl
  224. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withUserID: activeUserID, withPassword: activePassword, withUrl: activeUrl)
  225. networkingOperationQueue.addOperation(ocNetworking)
  226. }
  227. // MARK: - Download / Upload
  228. @objc func triggerProgressTask(_ notification: NSNotification) {
  229. let dict = notification.userInfo
  230. let progress = dict?["progress"] as! Float
  231. hud.progress(progress)
  232. }
  233. // MARK: - Download
  234. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!, errorMessage: String!, errorCode: Int) {
  235. hud.hideHud()
  236. if (errorCode == 0) {
  237. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID == %@", activeAccount, fileID!)) else {
  238. self.dismissGrantingAccess(to: nil)
  239. return
  240. }
  241. recordMetadata = metadata
  242. // Save for PickerFileProvide
  243. CCUtility.setFileNameExt(metadata.fileName)
  244. CCUtility.setServerUrlExt(serverUrl)
  245. switch selector {
  246. case selectorLoadFileView :
  247. let sourceFileNamePath = "\(directoryUser)/\(fileID!)"
  248. let destinationFileNameUrl : URL! = appGroupContainerURL()?.appendingPathComponent(recordMetadata.fileName)
  249. let destinationFileNamePath = destinationFileNameUrl.path
  250. // Destination Provider
  251. do {
  252. try FileManager.default.removeItem(at: destinationFileNameUrl)
  253. } catch _ {
  254. print("file do not exists")
  255. }
  256. do {
  257. try FileManager.default.copyItem(atPath: sourceFileNamePath, toPath: destinationFileNamePath)
  258. } catch let error as NSError {
  259. print(error)
  260. }
  261. // Dismiss
  262. self.dismissGrantingAccess(to: destinationFileNameUrl)
  263. default :
  264. print("selector : \(selector!)")
  265. tableView.reloadData()
  266. }
  267. } else {
  268. if selector == selectorLoadFileView && errorCode != -999 {
  269. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
  270. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  271. NSLog("[LOG] Download Error \(fileID) \(errorMessage) (error \(errorCode))");
  272. })
  273. self.present(alert, animated: true, completion: nil)
  274. }
  275. }
  276. }
  277. // MARK: - Upload
  278. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, selectorPost: String!, errorMessage: String!, errorCode: Int) {
  279. hud.hideHud()
  280. if (errorCode == 0) {
  281. dismissGrantingAccess(to: self.destinationURL)
  282. } else {
  283. // remove file
  284. let predicate = NSPredicate(format: "account = %@ AND fileID == %@", activeAccount, fileID)
  285. NCManageDatabase.sharedInstance.deleteMetadata(predicate: predicate, clearDateReadDirectoryID: nil)
  286. if errorCode != -999 {
  287. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
  288. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  289. //self.dismissGrantingAccess(to: nil)
  290. NSLog("[LOG] Download Error \(fileID) \(errorMessage) (error \(errorCode))");
  291. })
  292. self.present(alert, animated: true, completion: nil)
  293. }
  294. }
  295. }
  296. }
  297. // MARK: - IBActions
  298. extension DocumentPickerViewController {
  299. @IBAction func saveButtonTapped(_ sender: AnyObject) {
  300. guard let sourceURL = parameterOriginalURL else {
  301. return
  302. }
  303. switch parameterMode! {
  304. case .moveToService, .exportToService:
  305. let fileName = sourceURL.lastPathComponent
  306. let destinationFileNamePath = "\(directoryUser)/\(fileName)"
  307. destinationURL = appGroupContainerURL()?.appendingPathComponent(fileName)
  308. fileCoordinator.coordinate(readingItemAt: sourceURL, options: .withoutChanges, error: nil, byAccessor: { [weak self] newURL in
  309. // copy sourceURL on directoryUser
  310. do {
  311. try FileManager.default.removeItem(atPath: destinationFileNamePath)
  312. } catch _ {
  313. print("file do not exists")
  314. }
  315. do {
  316. try FileManager.default.copyItem(atPath: sourceURL.path, toPath: destinationFileNamePath)
  317. } catch _ {
  318. print("file do not exists")
  319. self?.dismissGrantingAccess(to: self?.destinationURL)
  320. return
  321. }
  322. do {
  323. try FileManager.default.removeItem(at: (self?.destinationURL)!)
  324. } catch _ {
  325. print("file do not exists")
  326. }
  327. do {
  328. try FileManager.default.copyItem(at: sourceURL, to: (self?.destinationURL)!)
  329. let fileSize = (try! FileManager.default.attributesOfItem(atPath: sourceURL.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  330. if fileSize == 0 {
  331. CCUtility.setFileNameExt(fileName)
  332. CCUtility.setServerUrlExt(self!.serverUrl)
  333. self?.dismissGrantingAccess(to: self?.destinationURL)
  334. } else {
  335. // Upload fileName to Cloud
  336. CCNetworking.shared().uploadFile(fileName, serverUrl: self!.serverUrl, assetLocalIdentifier: nil, session: k_upload_session_foreground, taskStatus: Int(k_taskStatusResume), selector: "", selectorPost: "", errorCode: 0, delegate: self)
  337. self!.hud.visibleHudTitle(NSLocalizedString("_uploading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brandElement)
  338. }
  339. } catch _ {
  340. self?.dismissGrantingAccess(to: self?.destinationURL)
  341. print("error copying file")
  342. }
  343. })
  344. default:
  345. dismissGrantingAccess(to: self.destinationURL)
  346. }
  347. }
  348. func appGroupContainerURL() -> URL? {
  349. guard let groupURL = FileManager.default
  350. .containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups) else {
  351. return nil
  352. }
  353. let storagePathUrl = groupURL.appendingPathComponent("File Provider Storage")
  354. let storagePath = storagePathUrl.path
  355. if !FileManager.default.fileExists(atPath: storagePath) {
  356. do {
  357. try FileManager.default.createDirectory(atPath: storagePath, withIntermediateDirectories: false, attributes: nil)
  358. } catch let error {
  359. print("error creating filepath: \(error)")
  360. return nil
  361. }
  362. }
  363. return storagePathUrl
  364. }
  365. // MARK: - Passcode
  366. func openBKPasscode(_ title : String?) {
  367. let viewController = CCBKPasscode.init()
  368. viewController.delegate = self
  369. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  370. viewController.inputViewTitlePassword = true
  371. if CCUtility.getSimplyBlockCode() {
  372. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  373. viewController.passcodeInputView.maximumLength = 6
  374. } else {
  375. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  376. viewController.passcodeInputView.maximumLength = 64
  377. }
  378. let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain)
  379. touchIDManager?.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  380. viewController.touchIDManager = touchIDManager
  381. viewController.title = title
  382. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(sender:)))
  383. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  384. let navController = UINavigationController.init(rootViewController: viewController)
  385. self.present(navController, animated: true, completion: nil)
  386. }
  387. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  388. return passcodeFailedAttempts
  389. }
  390. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date! {
  391. return passcodeLockUntilDate
  392. }
  393. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  394. passcodeFailedAttempts += 1
  395. if passcodeFailedAttempts > 5 {
  396. var timeInterval: TimeInterval = 60
  397. if passcodeFailedAttempts > 6 {
  398. let multiplier = passcodeFailedAttempts - 6
  399. timeInterval = TimeInterval(5 * 60 * multiplier)
  400. if timeInterval > 3600 * 24 {
  401. timeInterval = 3600 * 24
  402. }
  403. }
  404. passcodeLockUntilDate = Date.init(timeIntervalSinceNow: timeInterval)
  405. }
  406. }
  407. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  408. if aPasscode == CCUtility.getBlockCode() {
  409. passcodeLockUntilDate = nil
  410. passcodeFailedAttempts = 0
  411. aResultHandler(true)
  412. } else {
  413. aResultHandler(false)
  414. }
  415. }
  416. public func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  417. parameterPasscodeCorrect = true
  418. aViewController.dismiss(animated: true, completion: nil)
  419. if self.passcodeIsPush == true {
  420. performSegue()
  421. }
  422. }
  423. @objc func passcodeViewCloseButtonPressed(sender :Any) {
  424. dismiss(animated: true, completion: {
  425. if self.passcodeIsPush == false {
  426. self.dismissGrantingAccess(to: nil)
  427. }
  428. })
  429. }
  430. }
  431. // MARK: - UITableViewDelegate
  432. extension DocumentPickerViewController: UITableViewDelegate {
  433. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  434. return 50
  435. }
  436. }
  437. // MARK: - UITableViewDataSource
  438. extension DocumentPickerViewController: UITableViewDataSource {
  439. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  440. return recordsTableMetadata?.count ?? 0
  441. }
  442. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  443. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  444. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  445. guard let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row] else {
  446. return cell
  447. }
  448. // File Image View
  449. let fileNamePath = "\(directoryUser)/\(metadata.fileID)).ico"
  450. if FileManager.default.fileExists(atPath: fileNamePath) {
  451. cell.fileImageView.image = UIImage(contentsOfFile: fileNamePath)
  452. } else {
  453. if metadata.directory {
  454. if (metadata.e2eEncrypted) {
  455. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folderEncrypted"), color: NCBrandColor.sharedInstance.brandElement)
  456. } else if (metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory) {
  457. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folderphotocamera"), color: NCBrandColor.sharedInstance.brandElement)
  458. } else {
  459. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folder"), color: NCBrandColor.sharedInstance.brandElement)
  460. }
  461. } else {
  462. cell.fileImageView.image = UIImage(named: (metadata.iconName))
  463. if (metadata.thumbnailExists) {
  464. downloadThumbnail(metadata)
  465. thumbnailInLoading[metadata.fileID] = indexPath
  466. }
  467. }
  468. }
  469. // File Name
  470. cell.fileName.text = metadata.fileNameView
  471. // Status Image View
  472. let lockServerUrl = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: metadata.fileName)
  473. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, lockServerUrl!))
  474. if tableDirectory != nil {
  475. if metadata.directory && (tableDirectory?.lock)! && (CCUtility.getBlockCode() != nil) {
  476. cell.StatusImageView.image = UIImage(named: "passcode")
  477. } else {
  478. cell.StatusImageView.image = nil
  479. }
  480. }
  481. return cell
  482. }
  483. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  484. let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  485. tableView.deselectRow(at: indexPath, animated: true)
  486. recordMetadata = metadata!
  487. if metadata!.directory == false {
  488. // Delete old record metadata and file
  489. do {
  490. try FileManager.default.removeItem(atPath: "\(directoryUser)/\(metadata!.fileID)")
  491. } catch _ {
  492. }
  493. do {
  494. try FileManager.default.removeItem(atPath: "\(directoryUser)/\(metadata!.fileID).ico")
  495. } catch {
  496. }
  497. CCNetworking.shared().downloadFile(metadata?.fileName, fileID: metadata?.fileID, serverUrl: self.serverUrl, selector: selectorLoadFileView, selectorPost: nil, session: k_download_session_foreground, taskStatus: Int(k_taskStatusResume), delegate: self)
  498. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brandElement)
  499. } else {
  500. // E2EE DENIED
  501. if (metadata?.e2eEncrypted == true) {
  502. return
  503. }
  504. serverUrlPush = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: recordMetadata.fileName)
  505. var passcode: String? = CCUtility.getBlockCode()
  506. if passcode == nil {
  507. passcode = ""
  508. }
  509. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, serverUrlPush))
  510. if tableDirectory != nil {
  511. if (tableDirectory?.lock)! && (passcode?.count)! > 0 {
  512. self.passcodeIsPush = true
  513. openBKPasscode(recordMetadata.fileName)
  514. } else {
  515. performSegue()
  516. }
  517. } else {
  518. performSegue()
  519. }
  520. }
  521. }
  522. func performSegue() {
  523. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  524. nextViewController.parameterMode = parameterMode
  525. nextViewController.parameterOriginalURL = parameterOriginalURL
  526. nextViewController.parameterProviderIdentifier = parameterProviderIdentifier
  527. nextViewController.parameterPasscodeCorrect = parameterPasscodeCorrect
  528. nextViewController.serverUrl = serverUrlPush
  529. nextViewController.titleFolder = recordMetadata.fileName
  530. self.navigationController?.pushViewController(nextViewController, animated: true)
  531. }
  532. }
  533. // MARK: - Class UITableViewCell
  534. class recordMetadataCell: UITableViewCell {
  535. @IBOutlet weak var fileImageView: UIImageView!
  536. @IBOutlet weak var StatusImageView: UIImageView!
  537. @IBOutlet weak var fileName : UILabel!
  538. }