DocumentPickerViewController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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.characters.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 sourceUrl = URL(string: "file://\(directoryUser)/\(fileID!)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)!
  249. let destinationUrl : URL! = appGroupContainerURL()?.appendingPathComponent(recordMetadata.fileName)
  250. // Destination Provider
  251. do {
  252. try FileManager.default.removeItem(at: destinationUrl)
  253. } catch _ {
  254. print("file do not exists")
  255. }
  256. do {
  257. try FileManager.default.copyItem(at: sourceUrl, to: destinationUrl)
  258. } catch let error as NSError {
  259. print(error)
  260. }
  261. // Dismiss
  262. self.dismissGrantingAccess(to: destinationUrl)
  263. default :
  264. print("selector : \(selector!)")
  265. tableView.reloadData()
  266. }
  267. }
  268. // MARK: - Upload
  269. func uploadFileFailure(_ metadataNet: CCMetadataNet, fileID: String, serverUrl: String, selector: String, message: String, errorCode: NSInteger){
  270. hud.hideHud()
  271. // remove file
  272. let predicate = NSPredicate(format: "account = %@ AND fileID == %@", activeAccount, fileID)
  273. NCManageDatabase.sharedInstance.deleteMetadata(predicate: predicate, clearDateReadDirectoryID: nil)
  274. if errorCode != -999 {
  275. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  276. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  277. //self.dismissGrantingAccess(to: nil)
  278. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  279. })
  280. self.present(alert, animated: true, completion: nil)
  281. }
  282. }
  283. func uploadFileSuccess(_ metadataNet: CCMetadataNet, fileID: String, serverUrl: String, selector: String, selectorPost: String) {
  284. hud.hideHud()
  285. dismissGrantingAccess(to: self.destinationURL)
  286. }
  287. }
  288. // MARK: - IBActions
  289. extension DocumentPickerViewController {
  290. @IBAction func saveButtonTapped(_ sender: AnyObject) {
  291. guard let sourceURL = parameterOriginalURL else {
  292. return
  293. }
  294. switch parameterMode! {
  295. case .moveToService, .exportToService:
  296. let fileName = sourceURL.lastPathComponent
  297. let destinationURLDirectoryUser = URL(string: "file://\(directoryUser)/\(fileName)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)!
  298. destinationURL = appGroupContainerURL()?.appendingPathComponent(fileName)
  299. fileCoordinator.coordinate(readingItemAt: sourceURL, options: .withoutChanges, error: nil, byAccessor: { [weak self] newURL in
  300. // copy sourceURL on directoryUser
  301. do {
  302. try FileManager.default.removeItem(at: destinationURLDirectoryUser)
  303. } catch _ {
  304. print("file do not exists")
  305. }
  306. do {
  307. try FileManager.default.copyItem(at: sourceURL, to: destinationURLDirectoryUser)
  308. } catch _ {
  309. print("file do not exists")
  310. self?.dismissGrantingAccess(to: self?.destinationURL)
  311. return
  312. }
  313. do {
  314. try FileManager.default.removeItem(at: (self?.destinationURL)!)
  315. } catch _ {
  316. print("file do not exists")
  317. }
  318. do {
  319. try FileManager.default.copyItem(at: sourceURL, to: (self?.destinationURL)!)
  320. let fileSize = (try! FileManager.default.attributesOfItem(atPath: sourceURL.path)[FileAttributeKey.size] as! NSNumber).uint64Value
  321. if fileSize == 0 {
  322. CCUtility.setFileNameExt(fileName)
  323. CCUtility.setServerUrlExt(self!.serverUrl)
  324. self?.dismissGrantingAccess(to: self?.destinationURL)
  325. } else {
  326. // Upload fileName to Cloud
  327. CCNetworking.shared().uploadFile(fileName, serverUrl: self!.serverUrl, session: k_upload_session_foreground, taskStatus: Int(k_taskStatusResume), selector: "", selectorPost: "", errorCode: 0, delegate: self)
  328. self!.hud.visibleHudTitle(NSLocalizedString("_uploading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brand)
  329. }
  330. } catch _ {
  331. self?.dismissGrantingAccess(to: self?.destinationURL)
  332. print("error copying file")
  333. }
  334. })
  335. default:
  336. dismissGrantingAccess(to: self.destinationURL)
  337. }
  338. }
  339. func appGroupContainerURL() -> URL? {
  340. guard let groupURL = FileManager.default
  341. .containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups) else {
  342. return nil
  343. }
  344. let storagePathUrl = groupURL.appendingPathComponent("File Provider Storage")
  345. let storagePath = storagePathUrl.path
  346. if !FileManager.default.fileExists(atPath: storagePath) {
  347. do {
  348. try FileManager.default.createDirectory(atPath: storagePath, withIntermediateDirectories: false, attributes: nil)
  349. } catch let error {
  350. print("error creating filepath: \(error)")
  351. return nil
  352. }
  353. }
  354. return storagePathUrl
  355. }
  356. // MARK: - Passcode
  357. func openBKPasscode(_ title : String?) {
  358. let viewController = CCBKPasscode.init()
  359. viewController.delegate = self
  360. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  361. viewController.inputViewTitlePassword = true
  362. if CCUtility.getSimplyBlockCode() {
  363. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  364. viewController.passcodeInputView.maximumLength = 6
  365. } else {
  366. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  367. viewController.passcodeInputView.maximumLength = 64
  368. }
  369. let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain)
  370. touchIDManager?.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  371. viewController.touchIDManager = touchIDManager
  372. viewController.title = title
  373. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(sender:)))
  374. //viewController.navigationItem.leftBarButtonItem?.tintColor = NCBrandColor.sharedInstance.cryptocloud
  375. let navController = UINavigationController.init(rootViewController: viewController)
  376. self.present(navController, animated: true, completion: nil)
  377. }
  378. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  379. return passcodeFailedAttempts
  380. }
  381. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date! {
  382. return passcodeLockUntilDate
  383. }
  384. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  385. passcodeFailedAttempts += 1
  386. if passcodeFailedAttempts > 5 {
  387. var timeInterval: TimeInterval = 60
  388. if passcodeFailedAttempts > 6 {
  389. let multiplier = passcodeFailedAttempts - 6
  390. timeInterval = TimeInterval(5 * 60 * multiplier)
  391. if timeInterval > 3600 * 24 {
  392. timeInterval = 3600 * 24
  393. }
  394. }
  395. passcodeLockUntilDate = Date.init(timeIntervalSinceNow: timeInterval)
  396. }
  397. }
  398. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  399. if aPasscode == CCUtility.getBlockCode() {
  400. passcodeLockUntilDate = nil
  401. passcodeFailedAttempts = 0
  402. aResultHandler(true)
  403. } else {
  404. aResultHandler(false)
  405. }
  406. }
  407. public func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  408. parameterPasscodeCorrect = true
  409. aViewController.dismiss(animated: true, completion: nil)
  410. if self.passcodeIsPush == true {
  411. performSegue()
  412. }
  413. }
  414. @objc func passcodeViewCloseButtonPressed(sender :Any) {
  415. dismiss(animated: true, completion: {
  416. if self.passcodeIsPush == false {
  417. self.dismissGrantingAccess(to: nil)
  418. }
  419. })
  420. }
  421. }
  422. // MARK: - UITableViewDelegate
  423. extension DocumentPickerViewController: UITableViewDelegate {
  424. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  425. return 50
  426. }
  427. }
  428. // MARK: - UITableViewDataSource
  429. extension DocumentPickerViewController: UITableViewDataSource {
  430. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  431. return recordsTableMetadata?.count ?? 0
  432. }
  433. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  434. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  435. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  436. let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  437. // File Image View
  438. let fileNamePath = "\(directoryUser)/\(metadata!.fileID)).ico"
  439. if FileManager.default.fileExists(atPath: fileNamePath) {
  440. cell.fileImageView.image = UIImage(contentsOfFile: fileNamePath)
  441. } else {
  442. if metadata!.directory {
  443. cell.fileImageView.image = CCGraphics.changeThemingColorImage(UIImage(named: metadata!.iconName), color: NCBrandColor.sharedInstance.brand)
  444. } else {
  445. cell.fileImageView.image = UIImage(named: (metadata?.iconName)!)
  446. if (metadata?.thumbnailExists)! {
  447. downloadThumbnail(metadata!)
  448. thumbnailInLoading[metadata!.fileID] = indexPath
  449. }
  450. }
  451. }
  452. // File Name
  453. cell.fileName.text = metadata!.fileName
  454. // Status Image View
  455. let lockServerUrl = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: metadata!.fileName)
  456. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, lockServerUrl!))
  457. if tableDirectory != nil {
  458. if metadata!.directory && (tableDirectory?.lock)! && (CCUtility.getBlockCode() != nil) {
  459. cell.StatusImageView.image = UIImage(named: "passcode")
  460. } else {
  461. cell.StatusImageView.image = nil
  462. }
  463. }
  464. return cell
  465. }
  466. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  467. let metadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  468. tableView.deselectRow(at: indexPath, animated: true)
  469. recordMetadata = metadata!
  470. if metadata!.directory == false {
  471. let fileNamePath = "\(directoryUser)/\(metadata!.fileID)"
  472. if FileManager.default.fileExists(atPath: fileNamePath) {
  473. downloadFileSuccess(recordMetadata.fileID, serverUrl: self.serverUrl!, selector: selectorLoadFileView, selectorPost: nil)
  474. } else {
  475. CCNetworking.shared().downloadFile(metadata?.fileID, serverUrl: self.serverUrl, selector: selectorLoadFileView, selectorPost: nil, session: k_download_session_foreground, taskStatus: Int(k_taskStatusResume), delegate: self)
  476. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinate, color: NCBrandColor.sharedInstance.brand)
  477. }
  478. } else {
  479. serverUrlPush = CCUtility.stringAppendServerUrl(self.serverUrl!, addFileName: recordMetadata.fileName)
  480. var passcode: String? = CCUtility.getBlockCode()
  481. if passcode == nil {
  482. passcode = ""
  483. }
  484. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate:NSPredicate(format: "account = %@ AND serverUrl = %@", activeAccount, serverUrlPush))
  485. if tableDirectory != nil {
  486. if (tableDirectory?.lock)! && (passcode?.characters.count)! > 0 {
  487. self.passcodeIsPush = true
  488. openBKPasscode(recordMetadata.fileName)
  489. } else {
  490. performSegue()
  491. }
  492. } else {
  493. performSegue()
  494. }
  495. }
  496. }
  497. func performSegue() {
  498. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  499. nextViewController.parameterMode = parameterMode
  500. nextViewController.parameterOriginalURL = parameterOriginalURL
  501. nextViewController.parameterProviderIdentifier = parameterProviderIdentifier
  502. nextViewController.parameterPasscodeCorrect = parameterPasscodeCorrect
  503. nextViewController.serverUrl = serverUrlPush
  504. nextViewController.titleFolder = recordMetadata.fileName
  505. self.navigationController?.pushViewController(nextViewController, animated: true)
  506. }
  507. }
  508. // MARK: - Class UITableViewCell
  509. class recordMetadataCell: UITableViewCell {
  510. @IBOutlet weak var fileImageView: UIImageView!
  511. @IBOutlet weak var StatusImageView: UIImageView!
  512. @IBOutlet weak var fileName : UILabel!
  513. }