DocumentPickerViewController.swift 34 KB

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