DocumentPickerViewController.swift 28 KB

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