DocumentPickerViewController.swift 30 KB

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