DocumentPickerViewController.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. //
  2. // DocumentPickerViewController.swift
  3. // Picker
  4. //
  5. // Created by Marino Faggiana on 27/12/16.
  6. // Copyright © 2016 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. var providerDB : providerSessionDB?
  27. lazy var fileCoordinator: NSFileCoordinator = {
  28. let fileCoordinator = NSFileCoordinator()
  29. fileCoordinator.purposeIdentifier = self.parameterProviderIdentifier
  30. return fileCoordinator
  31. }()
  32. var parameterMode: UIDocumentPickerMode?
  33. var parameterOriginalURL: URL?
  34. var parameterProviderIdentifier: String!
  35. var parameterPasscodeCorrect: Bool? = false
  36. var parameterEncrypted: Bool? = false
  37. var metadata: CCMetadata?
  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 activeUID: String?
  45. var activeAccessToken: String?
  46. var directoryUser: String?
  47. var typeCloud: String?
  48. var serverUrl: String?
  49. var localServerUrl: String?
  50. var thumbnailInLoading = [String: IndexPath]()
  51. var destinationURL: URL?
  52. var passcodeFailedAttempts: UInt = 0
  53. var passcodeLockUntilDate: Date? = nil
  54. var passcodeIsPush: Bool? = false
  55. var serverUrlPush: String?
  56. lazy var networkingOperationQueue: OperationQueue = {
  57. var queue = OperationQueue()
  58. queue.name = netQueueName
  59. queue.maxConcurrentOperationCount = 10
  60. return queue
  61. }()
  62. let colorEncrypted = UIColor(colorLiteralRed: 241.0/255.0, green: 90.0/255.0, blue: 34.0/255.0, alpha: 1)
  63. var hud : CCHud!
  64. // MARK: - IBOutlets
  65. @IBOutlet weak var tableView: UITableView!
  66. @IBOutlet weak var toolBar: UIToolbar!
  67. @IBOutlet weak var saveButton: UIBarButtonItem!
  68. @IBOutlet weak var encryptedButton: UIBarButtonItem!
  69. // MARK: - View Life Cycle
  70. override func viewDidLoad() {
  71. providerDB = providerSessionDB.sharedInstance
  72. if let record = CCCoreData.getActiveAccount() {
  73. activeAccount = record.account!
  74. activePassword = record.password!
  75. activeUrl = record.url!
  76. activeUser = record.user!
  77. typeCloud = record.typeCloud!
  78. directoryUser = CCUtility.getDirectoryActiveUser(activeUser, activeUrl: activeUrl)
  79. if (localServerUrl == nil) {
  80. localServerUrl = CCUtility.getHomeServerUrlActiveUrl(activeUrl, typeCloud: typeCloud)
  81. } else {
  82. self.navigationItem.title = titleFolder
  83. }
  84. } else {
  85. // Close error no account return nil
  86. let deadlineTime = DispatchTime.now() + 0.1
  87. DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  88. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  89. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  90. self.dismissGrantingAccess(to: nil)
  91. })
  92. self.present(alert, animated: true, completion: nil)
  93. }
  94. return
  95. }
  96. // MARK: - init Object
  97. CCNetworking.shared().settingDelegate(self)
  98. hud = CCHud.init(view: self.navigationController?.view)
  99. // COLOR_SEPARATOR_TABLE
  100. self.tableView.separatorColor = UIColor(colorLiteralRed: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 0.2)
  101. // Encrypted mode
  102. encryptedButton.image = UIImage(named:image_shareExtEncrypt)?.withRenderingMode(.automatic)
  103. // Color Button
  104. if parameterEncrypted == true {
  105. encryptedButton.tintColor = colorEncrypted
  106. } else {
  107. encryptedButton.tintColor = self.view.tintColor
  108. }
  109. saveButton.tintColor = encryptedButton.tintColor
  110. readFolder()
  111. }
  112. override func viewWillAppear(_ animated: Bool) {
  113. super.viewWillAppear(animated)
  114. // (save) mode of presentation -> pass variable for pushViewController
  115. prepareForPresentation(in: parameterMode!)
  116. // String is nil or empty
  117. guard let passcode = CCUtility.getBlockCode(), !passcode.isEmpty else {
  118. return
  119. }
  120. if CCUtility.getOnlyLockDir() == false && parameterPasscodeCorrect == false {
  121. openBKPasscode("Nextcloud")
  122. }
  123. }
  124. override func viewWillDisappear(_ animated: Bool) {
  125. // remove all networking operation
  126. networkingOperationQueue.cancelAllOperations()
  127. super.viewWillDisappear(animated)
  128. }
  129. // MARK: - Overridden Instance Methods
  130. override func prepareForPresentation(in mode: UIDocumentPickerMode) {
  131. // ------------------> Settings parameter ----------------
  132. if parameterMode == nil {
  133. parameterMode = mode
  134. }
  135. // Variable for exportToService or moveToService
  136. if parameterOriginalURL == nil && originalURL != nil {
  137. parameterOriginalURL = originalURL
  138. }
  139. if parameterProviderIdentifier == nil {
  140. parameterProviderIdentifier = providerIdentifier
  141. }
  142. // -------------------------------------------------------
  143. switch mode {
  144. case .exportToService:
  145. print("Document Picker Mode : exportToService")
  146. saveButton.title = NSLocalizedString("_save_document_picker_", comment: "") // Save in this position
  147. case .moveToService:
  148. //Show confirmation button
  149. print("Document Picker Mode : moveToService")
  150. saveButton.title = NSLocalizedString("_save_document_picker_", comment: "") // Save in this position
  151. case .open:
  152. print("Document Picker Mode : open")
  153. saveButton.tintColor = UIColor.clear
  154. encryptedButton.tintColor = UIColor.clear
  155. case .import:
  156. print("Document Picker Mode : import")
  157. saveButton.tintColor = UIColor.clear
  158. encryptedButton.tintColor = UIColor.clear
  159. }
  160. }
  161. // MARK: - Read folder
  162. func readFolder() {
  163. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  164. metadataNet.action = actionReadFolder
  165. metadataNet.serverUrl = localServerUrl
  166. metadataNet.selector = selectorReadFolder
  167. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  168. networkingOperationQueue.addOperation(ocNetworking)
  169. hud.visibleIndeterminateHud()
  170. }
  171. func readFolderFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  172. hud.hideHud()
  173. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  174. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  175. self.dismissGrantingAccess(to: nil)
  176. })
  177. self.present(alert, animated: true, completion: nil)
  178. }
  179. func readFolderSuccess(_ metadataNet: CCMetadataNet!, permissions: String!, rev: String!, metadatas: [Any]!) {
  180. // remove all record
  181. let predicate = NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)') AND ((session == NULL) OR (session == ''))")
  182. CCCoreData.deleteMetadata(with: predicate)
  183. for metadata in metadatas as! [CCMetadata] {
  184. // do not insert crypto file
  185. if CCUtility.isCryptoString(metadata.fileName) {
  186. continue
  187. }
  188. // Only Directory ?
  189. if (parameterMode == .moveToService || parameterMode == .exportToService) && metadata.directory == false {
  190. continue
  191. }
  192. // plist + crypto = completed ?
  193. if CCUtility.isCryptoPlistString(metadata.fileName) && metadata.directory == false {
  194. var isCryptoComplete = false
  195. for completeMetadata in metadatas as! [CCMetadata] {
  196. if completeMetadata.fileName == CCUtility.trasformedFileNamePlist(inCrypto: metadata.fileName) {
  197. isCryptoComplete = true
  198. }
  199. }
  200. if isCryptoComplete == false {
  201. continue
  202. }
  203. }
  204. // Add record
  205. CCCoreData.add(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, context: nil)
  206. // if plist do not exists, download it
  207. if CCUtility.isCryptoPlistString(metadata.fileName) && FileManager.default.fileExists(atPath: "\(directoryUser!)/\(metadata.fileName!)") == false {
  208. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  209. metadataNet.action = actionDownloadFile
  210. metadataNet.metadata = metadata
  211. metadataNet.downloadData = false
  212. metadataNet.downloadPlist = true
  213. metadataNet.selector = selectorLoadPlist
  214. metadataNet.serverUrl = localServerUrl
  215. metadataNet.session = download_session_foreground
  216. metadataNet.taskStatus = Int(taskStatusResume)
  217. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  218. networkingOperationQueue.addOperation(ocNetworking)
  219. }
  220. }
  221. // Get Datasource
  222. recordsTableMetadata = CCCoreData.getTableMetadata(with: NSPredicate(format: "(account == '\(activeAccount!)') AND (directoryID == '\(metadataNet.directoryID!)')"), fieldOrder: "fileName", ascending: true) as? [TableMetadata]
  223. tableView.reloadData()
  224. hud.hideHud()
  225. }
  226. // MARK: - Download Thumbnail
  227. func downloadThumbnailFailure(_ metadataNet: CCMetadataNet!, message: String!, errorCode: Int) {
  228. NSLog("[LOG] Thumbnail Error \(metadataNet.fileName) \(message) (error \(errorCode))");
  229. }
  230. func downloadThumbnailSuccess(_ metadataNet: CCMetadataNet!) {
  231. if let indexPath = thumbnailInLoading[metadataNet.fileID] {
  232. let path = "\(directoryUser!)/\(metadataNet.fileID!).ico"
  233. if FileManager.default.fileExists(atPath: path) {
  234. if let cell = tableView.cellForRow(at: indexPath) as? recordMetadataCell {
  235. cell.fileImageView.image = UIImage(contentsOfFile: path)
  236. }
  237. }
  238. }
  239. }
  240. func downloadThumbnail(_ metadata : CCMetadata) {
  241. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  242. metadataNet.action = actionDownloadThumbnail
  243. metadataNet.fileID = metadata.fileID
  244. metadataNet.fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: localServerUrl, activeUrl: activeUrl, typeCloud: typeCloud)
  245. metadataNet.fileNameLocal = metadata.fileID;
  246. metadataNet.fileNamePrint = metadata.fileNamePrint;
  247. metadataNet.options = "m";
  248. metadataNet.selector = selectorDownloadThumbnail;
  249. metadataNet.serverUrl = localServerUrl
  250. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  251. networkingOperationQueue.addOperation(ocNetworking)
  252. }
  253. // MARK: - Download / Upload
  254. func progressTask(_ fileID: String!, serverUrl: String!, cryptated: Bool, progress: Float) {
  255. hud.progress(progress)
  256. }
  257. func cancelTransfer() {
  258. networkingOperationQueue.cancelAllOperations()
  259. }
  260. // MARK: - Download
  261. func downloadFileFailure(_ fileID: String!, serverUrl: String!, selector: String!, message: String!, errorCode: Int) {
  262. hud.hideHud()
  263. if selector == selectorLoadFileView && errorCode != -999 {
  264. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  265. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  266. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  267. })
  268. self.present(alert, animated: true, completion: nil)
  269. }
  270. }
  271. func downloadFileSuccess(_ fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!) {
  272. hud.hideHud()
  273. let metadata = CCCoreData.getMetadataWithPreficate(NSPredicate(format: "(account == '\(activeAccount!)') AND (fileID == '\(fileID!)')"), context: nil)
  274. switch selector {
  275. case selectorLoadFileView :
  276. do {
  277. try FileManager.default.moveItem(atPath: "\(directoryUser!)/\(fileID!)", toPath: "\(directoryUser!)/\(metadata!.fileNamePrint!)")
  278. } catch let error as NSError {
  279. print(error)
  280. }
  281. let url = URL(string: "file://\(directoryUser!)/\(metadata!.fileNamePrint!)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
  282. self.dismissGrantingAccess(to: url)
  283. case selectorLoadPlist :
  284. CCCoreData.downloadFilePlist(metadata, activeAccount: activeAccount, activeUrl: activeUrl, typeCloud: typeCloud, directoryUser: directoryUser)
  285. tableView.reloadData()
  286. default :
  287. print("selector : \(selector!)")
  288. tableView.reloadData()
  289. }
  290. }
  291. // MARK: - Upload
  292. func uploadFileFailure(_ fileID: String!, serverUrl: String!, selector: String!, message: String!, errorCode: Int) {
  293. hud.hideHud()
  294. // remove file
  295. CCCoreData.deleteMetadata(with: NSPredicate(format: "(account == '\(activeAccount!)') AND (fileID == '\(fileID!)')"))
  296. if errorCode != -999 {
  297. let alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: message, preferredStyle: .alert)
  298. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { action in
  299. //self.dismissGrantingAccess(to: nil)
  300. NSLog("[LOG] Download Error \(fileID) \(message) (error \(errorCode))");
  301. })
  302. self.present(alert, animated: true, completion: nil)
  303. }
  304. }
  305. func uploadFileSuccess(_ fileID: String!, serverUrl: String!, selector: String!, selectorPost: String!) {
  306. hud.hideHud()
  307. dismissGrantingAccess(to: self.destinationURL)
  308. }
  309. }
  310. // MARK: - IBActions
  311. extension DocumentPickerViewController {
  312. @IBAction func encryptedButtonTapped(_ sender: AnyObject) {
  313. parameterEncrypted = !parameterEncrypted!
  314. if parameterEncrypted == true {
  315. encryptedButton.tintColor = colorEncrypted
  316. } else {
  317. encryptedButton.tintColor = self.view.tintColor
  318. }
  319. saveButton.tintColor = encryptedButton.tintColor
  320. }
  321. @IBAction func saveButtonTapped(_ sender: AnyObject) {
  322. guard let sourceURL = parameterOriginalURL else {
  323. return
  324. }
  325. switch parameterMode! {
  326. case .moveToService, .exportToService:
  327. let fileName = sourceURL.lastPathComponent
  328. guard let destinationURLDirectoryUser = URL(string: "file://\(directoryUser!)/\(fileName)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!) else {
  329. return
  330. }
  331. self.destinationURL = appGroupContainerURL()?.appendingPathComponent(fileName)
  332. // copy sourceURL on directoryUser
  333. do {
  334. try FileManager.default.removeItem(at: destinationURLDirectoryUser)
  335. } catch _ {
  336. print("file do not exists")
  337. }
  338. do {
  339. try FileManager.default.copyItem(at: sourceURL, to: destinationURLDirectoryUser)
  340. } catch _ {
  341. print("file do not exists")
  342. return
  343. }
  344. fileCoordinator.coordinate(readingItemAt: sourceURL, options: .withoutChanges, error: nil, byAccessor: { [weak self] newURL in
  345. do {
  346. try FileManager.default.removeItem(at: (self?.destinationURL)!)
  347. } catch _ {
  348. print("file do not exists")
  349. }
  350. do {
  351. try FileManager.default.copyItem(at: sourceURL, to: (self?.destinationURL)!)
  352. // Upload fileName to Cloud
  353. let metadataNet = CCMetadataNet.init(account: self!.activeAccount)!
  354. metadataNet.action = actionUploadFile
  355. metadataNet.cryptated = self!.parameterEncrypted!
  356. metadataNet.fileName = fileName
  357. metadataNet.fileNamePrint = fileName
  358. metadataNet.serverUrl = self!.localServerUrl
  359. metadataNet.session = upload_session_foreground
  360. metadataNet.taskStatus = Int(taskStatusResume)
  361. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self!, metadataNet: metadataNet, withUser: self!.activeUser, withPassword: self!.activePassword, withUrl: self!.activeUrl, withTypeCloud: self!.typeCloud, activityIndicator: false)
  362. self!.networkingOperationQueue.addOperation(ocNetworking)
  363. self!.hud.visibleHudTitle(NSLocalizedString("_uploading_", comment: ""), mode: MBProgressHUDMode.determinateHorizontalBar, color: self!.navigationController?.view.tintColor)
  364. self!.hud.addButtonCancel(withTarget: self, selector: "cancelTransfer")
  365. } catch _ {
  366. print("error copying file")
  367. }
  368. })
  369. default:
  370. dismiss(animated: true, completion: nil)
  371. }
  372. }
  373. func appGroupContainerURL() -> URL? {
  374. guard let groupURL = FileManager.default
  375. .containerURL(forSecurityApplicationGroupIdentifier: capabilitiesGroups) else {
  376. return nil
  377. }
  378. let storagePathUrl = groupURL.appendingPathComponent("File Provider Storage")
  379. let storagePath = storagePathUrl.path
  380. if !FileManager.default.fileExists(atPath: storagePath) {
  381. do {
  382. try FileManager.default.createDirectory(atPath: storagePath, withIntermediateDirectories: false, attributes: nil)
  383. } catch let error {
  384. print("error creating filepath: \(error)")
  385. return nil
  386. }
  387. }
  388. return storagePathUrl
  389. }
  390. // MARK: - Passcode
  391. func openBKPasscode(_ title : String?) {
  392. let viewController = CCBKPasscode.init()
  393. viewController.delegate = self
  394. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  395. viewController.inputViewTitlePassword = true
  396. if CCUtility.getSimplyBlockCode() {
  397. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  398. viewController.passcodeInputView.maximumLength = 6
  399. } else {
  400. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  401. viewController.passcodeInputView.maximumLength = 64
  402. }
  403. let touchIDManager = BKTouchIDManager.init(keychainServiceName: BKPasscodeKeychainServiceName)
  404. touchIDManager?.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  405. viewController.touchIDManager = touchIDManager
  406. viewController.title = title
  407. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(sender:)))
  408. viewController.navigationItem.leftBarButtonItem?.tintColor = colorEncrypted
  409. let navController = UINavigationController.init(rootViewController: viewController)
  410. self.present(navController, animated: true, completion: nil)
  411. }
  412. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  413. return passcodeFailedAttempts
  414. }
  415. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date! {
  416. return passcodeLockUntilDate
  417. }
  418. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  419. passcodeFailedAttempts += 1
  420. if passcodeFailedAttempts > 5 {
  421. var timeInterval: TimeInterval = 60
  422. if passcodeFailedAttempts > 6 {
  423. let multiplier = passcodeFailedAttempts - 6
  424. timeInterval = TimeInterval(5 * 60 * multiplier)
  425. if timeInterval > 3600 * 24 {
  426. timeInterval = 3600 * 24
  427. }
  428. }
  429. passcodeLockUntilDate = Date.init(timeIntervalSinceNow: timeInterval)
  430. }
  431. }
  432. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  433. if aPasscode == CCUtility.getBlockCode() {
  434. passcodeLockUntilDate = nil
  435. passcodeFailedAttempts = 0
  436. aResultHandler(true)
  437. } else {
  438. aResultHandler(false)
  439. }
  440. }
  441. public func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  442. parameterPasscodeCorrect = true
  443. aViewController.dismiss(animated: true, completion: nil)
  444. if self.passcodeIsPush == true {
  445. performSegue()
  446. }
  447. }
  448. func passcodeViewCloseButtonPressed(sender :Any) {
  449. dismiss(animated: true, completion: {
  450. if self.passcodeIsPush == false {
  451. self.dismissGrantingAccess(to: nil)
  452. }
  453. })
  454. }
  455. }
  456. // MARK: - UITableViewDelegate
  457. extension DocumentPickerViewController: UITableViewDelegate {
  458. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  459. return 50
  460. }
  461. }
  462. // MARK: - UITableViewDataSource
  463. extension DocumentPickerViewController: UITableViewDataSource {
  464. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  465. if (recordsTableMetadata == nil) {
  466. return 0
  467. } else {
  468. return recordsTableMetadata!.count
  469. }
  470. }
  471. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  472. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! recordMetadataCell
  473. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  474. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  475. let metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  476. // File Image View
  477. let filePath = "\(directoryUser!)/\(metadata.fileID!).ico"
  478. if FileManager.default.fileExists(atPath: filePath) {
  479. cell.fileImageView.image = UIImage(contentsOfFile: filePath)
  480. } else {
  481. cell.fileImageView.image = UIImage(named: metadata.iconName!)
  482. if metadata.thumbnailExists && metadata.directory == false {
  483. downloadThumbnail(metadata)
  484. thumbnailInLoading[metadata.fileID] = indexPath
  485. }
  486. }
  487. // File Name
  488. cell.fileName.text = metadata.fileNamePrint
  489. // Status Image View
  490. let lockServerUrl = CCUtility.stringAppendServerUrl(localServerUrl!, addServerUrl: metadata.fileNameData)
  491. var passcode: String? = CCUtility.getBlockCode()
  492. if passcode == nil {
  493. passcode = ""
  494. }
  495. if metadata.directory && CCCoreData.isDirectoryLock(lockServerUrl, activeAccount: activeAccount) && (passcode?.characters.count)! > 0 {
  496. cell.StatusImageView.image = UIImage(named: image_passcode)
  497. }
  498. return cell
  499. }
  500. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  501. let recordTableMetadata = recordsTableMetadata?[(indexPath as NSIndexPath).row]
  502. tableView.deselectRow(at: indexPath, animated: true)
  503. // Error passcode ?
  504. if (recordTableMetadata?.errorPasscode == 1) {
  505. return
  506. }
  507. self.metadata = CCCoreData.insertEntity(in: recordTableMetadata)!
  508. if recordTableMetadata!.directory == 0 {
  509. if FileManager.default.fileExists(atPath: "\(directoryUser!)/\(self.metadata?.fileID!)") {
  510. downloadFileSuccess(self.metadata?.fileID!, serverUrl: localServerUrl!, selector: selectorLoadFileView, selectorPost: nil)
  511. } else {
  512. // Download file
  513. let metadataNet = CCMetadataNet.init(account: activeAccount)!
  514. metadataNet.action = actionDownloadFile
  515. metadataNet.downloadData = true
  516. metadataNet.downloadPlist = false
  517. metadataNet.metadata = metadata
  518. metadataNet.selector = selectorLoadFileView
  519. metadataNet.serverUrl = localServerUrl
  520. metadataNet.session = download_session_foreground
  521. metadataNet.taskStatus = Int(taskStatusResume)
  522. let ocNetworking : OCnetworking = OCnetworking.init(delegate: self, metadataNet: metadataNet, withUser: activeUser, withPassword: activePassword, withUrl: activeUrl, withTypeCloud: typeCloud, activityIndicator: false)
  523. networkingOperationQueue.addOperation(ocNetworking)
  524. hud.visibleHudTitle(NSLocalizedString("_loading_", comment: ""), mode: MBProgressHUDMode.determinateHorizontalBar, color: self.navigationController?.view.tintColor)
  525. hud.addButtonCancel(withTarget: self, selector: "cancelTransfer")
  526. }
  527. } else {
  528. var dir : String! = self.metadata?.fileName!
  529. if (self.metadata?.cryptated)! {
  530. dir = CCUtility.trasformedFileNamePlist(inCrypto: self.metadata?.fileName)
  531. }
  532. serverUrlPush = CCUtility.stringAppendServerUrl(localServerUrl!, addServerUrl: dir)
  533. var passcode: String? = CCUtility.getBlockCode()
  534. if passcode == nil {
  535. passcode = ""
  536. }
  537. if CCCoreData.isDirectoryLock(serverUrlPush, activeAccount: activeAccount) && (passcode?.characters.count)! > 0 {
  538. self.passcodeIsPush = true
  539. openBKPasscode(self.metadata?.fileNamePrint)
  540. } else {
  541. performSegue()
  542. }
  543. }
  544. }
  545. func performSegue() {
  546. let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "DocumentPickerViewController") as! DocumentPickerViewController
  547. nextViewController.parameterMode = parameterMode
  548. nextViewController.parameterOriginalURL = parameterOriginalURL
  549. nextViewController.parameterProviderIdentifier = parameterProviderIdentifier
  550. nextViewController.parameterPasscodeCorrect = parameterPasscodeCorrect
  551. nextViewController.parameterEncrypted = parameterEncrypted
  552. nextViewController.localServerUrl = serverUrlPush
  553. nextViewController.titleFolder = self.metadata?.fileNamePrint
  554. self.navigationController?.pushViewController(nextViewController, animated: true)
  555. }
  556. }
  557. // MARK: - Class UITableViewCell
  558. class recordMetadataCell: UITableViewCell {
  559. @IBOutlet weak var fileImageView: UIImageView!
  560. @IBOutlet weak var StatusImageView: UIImageView!
  561. @IBOutlet weak var fileName : UILabel!
  562. }
  563. // MARK: - Class providerSession
  564. class providerSessionDB {
  565. class var sharedInstance : providerSessionDB {
  566. struct Static {
  567. static let instance = providerSessionDB()
  568. }
  569. return Static.instance
  570. }
  571. private init() {
  572. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: capabilitiesGroups)
  573. let pathDB = dirGroup?.appendingPathComponent(appDatabase).appendingPathComponent("cryptocloud")
  574. MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStore(at: pathDB!)
  575. MagicalRecord.setLoggingLevel(MagicalRecordLoggingLevel.off)
  576. }
  577. }