DocumentPickerViewController.swift 28 KB

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