DocumentPickerViewController.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. let tableCapabilities = NCManageDatabase.sharedInstance.getCapabilites()
  96. if (tableCapabilities != nil && NCBrandOptions.sharedInstance.use_themingColor == true) {
  97. if ((tableCapabilities?.themingColor.count)! > 0) {
  98. NCBrandColor.sharedInstance.brand = CCGraphics.color(fromHexString: tableCapabilities?.themingColor)
  99. }
  100. }
  101. // COLOR
  102. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  103. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.navigationBarText
  104. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: NCBrandColor.sharedInstance.navigationBarText]
  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 readFolderFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  172. hud.hideHud()
  173. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  174. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  175. self.dismissGrantingAccess(to: nil)
  176. })
  177. self.present(alert, animated: true, completion: nil)
  178. }
  179. func readFolderSuccess(_ metadataNet: CCMetadataNet!, metadataFolder: tableMetadata?, metadatas: [Any]!) {
  180. // remove all record
  181. var predicate = NSPredicate(format: "account = %@ AND directoryID = %@ AND session = ''", activeAccount, metadataNet.directoryID!)
  182. NCManageDatabase.sharedInstance.deleteMetadata(predicate: predicate, clearDateReadDirectoryID: metadataNet.directoryID!)
  183. for metadata in metadatas as! [tableMetadata] {
  184. // Only Directory ?
  185. if (parameterMode == .moveToService || parameterMode == .exportToService) && metadata.directory == false {
  186. continue
  187. }
  188. // Add record
  189. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  190. }
  191. predicate = NSPredicate(format: "account = %@ AND directoryID = %@", activeAccount, metadataNet.directoryID!)
  192. recordsTableMetadata = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate, sorted: "fileName", ascending: true)
  193. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  194. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(activeUrl)
  195. if (CCUtility.isEnd(toEndEnabled: activeAccount)) {
  196. }
  197. tableView.reloadData()
  198. hud.hideHud()
  199. }
  200. // MARK: - Download Thumbnail
  201. func downloadThumbnailFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  202. NSLog("[LOG] Thumbnail Error \(metadataNet.fileName) \(message) (error \(errorCode))");
  203. }
  204. func downloadThumbnailSuccess(_ metadataNet: CCMetadataNet!) {
  205. if let indexPath = thumbnailInLoading[metadataNet.fileID] {
  206. let path = "\(directoryUser)/\(metadataNet.fileID!).ico"
  207. if FileManager.default.fileExists(atPath: path) {
  208. if let cell = tableView.cellForRow(at: indexPath) as? recordMetadataCell {
  209. cell.fileImageView.image = UIImage(contentsOfFile: path)
  210. }
  211. }
  212. }
  213. }
  214. func downloadThumbnail(_ metadata : tableMetadata) {
  215. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  216. metadataNet.action = actionDownloadThumbnail
  217. metadataNet.fileID = metadata.fileID
  218. metadataNet.fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: self.serverUrl, activeUrl: activeUrl)
  219. metadataNet.options = "m";
  220. metadataNet.selector = selectorDownloadThumbnail;
  221. metadataNet.serverUrl = self.serverUrl
  222. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withUserID: activeUserID, withPassword: activePassword, withUrl: activeUrl)
  223. networkingOperationQueue.addOperation(ocNetworking)
  224. }
  225. // MARK: - Download / Upload
  226. @objc func triggerProgressTask(_ notification: NSNotification) {
  227. let dict = notification.userInfo
  228. let progress = dict?["progress"] as! Float
  229. hud.progress(progress)
  230. }
  231. // MARK: - Download
  232. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!, errorMessage: String!, errorCode: Int) {
  233. hud.hideHud()
  234. if (errorCode == 0) {
  235. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account = %@ AND fileID == %@", activeAccount, fileID!)) else {
  236. self.dismissGrantingAccess(to: nil)
  237. return
  238. }
  239. recordMetadata = metadata
  240. // Save for PickerFileProvide
  241. CCUtility.setFileNameExt(metadata.fileName)
  242. CCUtility.setServerUrlExt(serverUrl)
  243. switch selector {
  244. case selectorLoadFileView :
  245. let sourceFileNamePath = "\(directoryUser)/\(fileID!)"
  246. let destinationFileNameUrl : URL! = appGroupContainerURL()?.appendingPathComponent(recordMetadata.fileName)
  247. let destinationFileNamePath = destinationFileNameUrl.path
  248. // Destination Provider
  249. do {
  250. try FileManager.default.removeItem(at: destinationFileNameUrl)
  251. } catch _ {
  252. print("file do not exists")
  253. }
  254. do {
  255. try FileManager.default.copyItem(atPath: sourceFileNamePath, toPath: destinationFileNamePath)
  256. } catch let error as NSError {
  257. print(error)
  258. }
  259. // Dismiss
  260. self.dismissGrantingAccess(to: destinationFileNameUrl)
  261. default :
  262. print("selector : \(selector!)")
  263. tableView.reloadData()
  264. }
  265. } else {
  266. if selector == selectorLoadFileView && errorCode != -999 {
  267. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
  268. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  269. NSLog("[LOG] Download Error \(fileID) \(errorMessage) (error \(errorCode))");
  270. })
  271. self.present(alert, animated: true, completion: nil)
  272. }
  273. }
  274. }
  275. // MARK: - Upload
  276. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, selectorPost: String!, errorMessage: String!, errorCode: Int) {
  277. hud.hideHud()
  278. if (errorCode == 0) {
  279. dismissGrantingAccess(to: self.destinationURL)
  280. } else {
  281. // remove file
  282. let predicate = NSPredicate(format: "account = %@ AND fileID == %@", activeAccount, fileID)
  283. NCManageDatabase.sharedInstance.deleteMetadata(predicate: predicate, clearDateReadDirectoryID: nil)
  284. if errorCode != -999 {
  285. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorMessage, preferredStyle: .alert)
  286. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  287. //self.dismissGrantingAccess(to: nil)
  288. NSLog("[LOG] Download Error \(fileID) \(errorMessage) (error \(errorCode))");
  289. })
  290. self.present(alert, animated: true, completion: nil)
  291. }
  292. }
  293. }
  294. }
  295. // MARK: - IBActions
  296. extension DocumentPickerViewController {
  297. @IBAction func saveButtonTapped(_ sender: AnyObject) {
  298. guard let sourceURL = parameterOriginalURL else {
  299. return
  300. }
  301. switch parameterMode! {
  302. case .moveToService, .exportToService:
  303. let fileName = sourceURL.lastPathComponent
  304. let destinationFileNamePath = "\(directoryUser)/\(fileName)"
  305. destinationURL = appGroupContainerURL()?.appendingPathComponent(fileName)
  306. fileCoordinator.coordinate(readingItemAt: sourceURL, options: .withoutChanges, error: nil, byAccessor: { [weak self] newURL in
  307. // copy sourceURL on directoryUser
  308. do {
  309. try FileManager.default.removeItem(atPath: destinationFileNamePath)
  310. } catch _ {
  311. print("file do not exists")
  312. }
  313. do {
  314. try FileManager.default.copyItem(atPath: sourceURL.path, toPath: destinationFileNamePath)
  315. } catch _ {
  316. print("file do not exists")
  317. self?.dismissGrantingAccess(to: self?.destinationURL)
  318. return
  319. }
  320. do {
  321. try FileManager.default.removeItem(at: (self?.destinationURL)!)
  322. } catch _ {
  323. print("file do not exists")
  324. }
  325. do {
  326. try FileManager.default.copyItem(at: sourceURL, to: (self?.destinationURL)!)
  327. let fileSize = (try! FileManager.default.attributesOfItem(atPath: sourceURL.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  328. if fileSize == 0 {
  329. CCUtility.setFileNameExt(fileName)
  330. CCUtility.setServerUrlExt(self!.serverUrl)
  331. self?.dismissGrantingAccess(to: self?.destinationURL)
  332. } else {
  333. // Upload fileName to Cloud
  334. CCNetworking.shared().uploadFile(fileName, serverUrl: self!.serverUrl, session: k_upload_session_foreground, taskStatus: Int(k_taskStatusResume), selector: "", selectorPost: "", errorCode: 0, delegate: self)
  335. self!.hud.visibleHudTitle(NSLocalizedString("_uploading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brand)
  336. }
  337. } catch _ {
  338. self?.dismissGrantingAccess(to: self?.destinationURL)
  339. print("error copying file")
  340. }
  341. })
  342. default:
  343. dismissGrantingAccess(to: self.destinationURL)
  344. }
  345. }
  346. func appGroupContainerURL() -> URL? {
  347. guard let groupURL = FileManager.default
  348. .containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups) else {
  349. return nil
  350. }
  351. let storagePathUrl = groupURL.appendingPathComponent("File Provider Storage")
  352. let storagePath = storagePathUrl.path
  353. if !FileManager.default.fileExists(atPath: storagePath) {
  354. do {
  355. try FileManager.default.createDirectory(atPath: storagePath, withIntermediateDirectories: false, attributes: nil)
  356. } catch let error {
  357. print("error creating filepath: \(error)")
  358. return nil
  359. }
  360. }
  361. return storagePathUrl
  362. }
  363. // MARK: - Passcode
  364. func openBKPasscode(_ title : String?) {
  365. let viewController = CCBKPasscode.init()
  366. viewController.delegate = self
  367. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  368. viewController.inputViewTitlePassword = true
  369. if CCUtility.getSimplyBlockCode() {
  370. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  371. viewController.passcodeInputView.maximumLength = 6
  372. } else {
  373. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  374. viewController.passcodeInputView.maximumLength = 64
  375. }
  376. let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain)
  377. touchIDManager?.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  378. viewController.touchIDManager = touchIDManager
  379. viewController.title = title
  380. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(sender:)))
  381. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  382. let navController = UINavigationController.init(rootViewController: viewController)
  383. self.present(navController, animated: true, completion: nil)
  384. }
  385. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  386. return passcodeFailedAttempts
  387. }
  388. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date! {
  389. return passcodeLockUntilDate
  390. }
  391. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  392. passcodeFailedAttempts += 1
  393. if passcodeFailedAttempts > 5 {
  394. var timeInterval: TimeInterval = 60
  395. if passcodeFailedAttempts > 6 {
  396. let multiplier = passcodeFailedAttempts - 6
  397. timeInterval = TimeInterval(5 * 60 * multiplier)
  398. if timeInterval > 3600 * 24 {
  399. timeInterval = 3600 * 24
  400. }
  401. }
  402. passcodeLockUntilDate = Date.init(timeIntervalSinceNow: timeInterval)
  403. }
  404. }
  405. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  406. if aPasscode == CCUtility.getBlockCode() {
  407. passcodeLockUntilDate = nil
  408. passcodeFailedAttempts = 0
  409. aResultHandler(true)
  410. } else {
  411. aResultHandler(false)
  412. }
  413. }
  414. public func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  415. parameterPasscodeCorrect = true
  416. aViewController.dismiss(animated: true, completion: nil)
  417. if self.passcodeIsPush == true {
  418. performSegue()
  419. }
  420. }
  421. @objc func passcodeViewCloseButtonPressed(sender :Any) {
  422. dismiss(animated: true, completion: {
  423. if self.passcodeIsPush == false {
  424. self.dismissGrantingAccess(to: nil)
  425. }
  426. })
  427. }
  428. }
  429. // MARK: - UITableViewDelegate
  430. extension DocumentPickerViewController: UITableViewDelegate {
  431. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  432. return 50
  433. }
  434. }
  435. // MARK: - UITableViewDataSource
  436. extension DocumentPickerViewController: UITableViewDataSource {
  437. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  438. return recordsTableMetadata?.count ?? 0
  439. }
  440. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  441. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  442. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  443. guard let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row] else {
  444. return cell
  445. }
  446. // File Image View
  447. let fileNamePath = "\(directoryUser)/\(metadata.fileID)).ico"
  448. if FileManager.default.fileExists(atPath: fileNamePath) {
  449. cell.fileImageView.image = UIImage(contentsOfFile: fileNamePath)
  450. } else {
  451. if metadata.directory {
  452. if (metadata.e2eEncrypted) {
  453. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folderEncrypted"), color: NCBrandColor.sharedInstance.brand)
  454. } else if (metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory) {
  455. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folderphotocamera"), color: NCBrandColor.sharedInstance.brand)
  456. } else {
  457. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: "folder"), color: NCBrandColor.sharedInstance.brand)
  458. }
  459. } else {
  460. cell.fileImageView.image = UIImage(named: (metadata.iconName))
  461. if (metadata.thumbnailExists) {
  462. downloadThumbnail(metadata)
  463. thumbnailInLoading[metadata.fileID] = indexPath
  464. }
  465. }
  466. }
  467. // File Name
  468. cell.fileName.text = metadata.fileNameView
  469. // Status Image View
  470. let lockServerUrl = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: metadata.fileName)
  471. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, lockServerUrl!))
  472. if tableDirectory != nil {
  473. if metadata.directory && (tableDirectory?.lock)! && (CCUtility.getBlockCode() != nil) {
  474. cell.StatusImageView.image = UIImage(named: "passcode")
  475. } else {
  476. cell.StatusImageView.image = nil
  477. }
  478. }
  479. return cell
  480. }
  481. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  482. let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  483. tableView.deselectRow(at: indexPath, animated: true)
  484. recordMetadata = metadata!
  485. if metadata!.directory == false {
  486. // Delete old record metadata and file
  487. do {
  488. try FileManager.default.removeItem(atPath: "\(directoryUser)/\(metadata!.fileID)")
  489. } catch _ {
  490. }
  491. do {
  492. try FileManager.default.removeItem(atPath: "\(directoryUser)/\(metadata!.fileID).ico")
  493. } catch {
  494. }
  495. 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)
  496. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brand)
  497. } else {
  498. // e2e DENIED
  499. if (metadata?.e2eEncrypted == true) {
  500. return
  501. }
  502. serverUrlPush = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: recordMetadata.fileName)
  503. var passcode: String? = CCUtility.getBlockCode()
  504. if passcode == nil {
  505. passcode = ""
  506. }
  507. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, serverUrlPush))
  508. if tableDirectory != nil {
  509. if (tableDirectory?.lock)! && (passcode?.count)! > 0 {
  510. self.passcodeIsPush = true
  511. openBKPasscode(recordMetadata.fileName)
  512. } else {
  513. performSegue()
  514. }
  515. } else {
  516. performSegue()
  517. }
  518. }
  519. }
  520. func performSegue() {
  521. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  522. nextViewController.parameterMode = parameterMode
  523. nextViewController.parameterOriginalURL = parameterOriginalURL
  524. nextViewController.parameterProviderIdentifier = parameterProviderIdentifier
  525. nextViewController.parameterPasscodeCorrect = parameterPasscodeCorrect
  526. nextViewController.serverUrl = serverUrlPush
  527. nextViewController.titleFolder = recordMetadata.fileName
  528. self.navigationController?.pushViewController(nextViewController, animated: true)
  529. }
  530. }
  531. // MARK: - Class UITableViewCell
  532. class recordMetadataCell: UITableViewCell {
  533. @IBOutlet weak var fileImageView: UIImageView!
  534. @IBOutlet weak var StatusImageView: UIImageView!
  535. @IBOutlet weak var fileName : UILabel!
  536. }