NCShareExtension.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. //
  2. // NCShareExtension.swift
  3. // Share
  4. //
  5. // Created by Marino Faggiana on 20/04/2021.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. // Copyright © 2021 Henrik Storch. All rights reserved.
  8. //
  9. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  10. // Author Henrik Storch <henrik.storch@nextcloud.com>
  11. //
  12. // This program is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. import UIKit
  26. import NextcloudKit
  27. enum NCShareExtensionError: Error {
  28. case cancel, fileUpload, noAccount, noFiles
  29. }
  30. class NCShareExtension: UIViewController {
  31. @IBOutlet weak var collectionView: UICollectionView!
  32. @IBOutlet weak var tableView: UITableView!
  33. @IBOutlet weak var cancelButton: UIBarButtonItem!
  34. @IBOutlet weak var separatorView: UIView!
  35. @IBOutlet weak var commandView: UIView!
  36. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  37. @IBOutlet weak var commandViewHeightConstraint: NSLayoutConstraint!
  38. @IBOutlet weak var createFolderView: UIView!
  39. @IBOutlet weak var createFolderImage: UIImageView!
  40. @IBOutlet weak var createFolderLabel: UILabel!
  41. @IBOutlet weak var uploadView: UIView!
  42. @IBOutlet weak var uploadImage: UIImageView!
  43. @IBOutlet weak var uploadLabel: UILabel!
  44. // -------------------------------------------------------------
  45. var serverUrl = ""
  46. var filesName: [String] = []
  47. // -------------------------------------------------------------
  48. let keyLayout = NCGlobal.shared.layoutViewShareExtension
  49. var metadataFolder: tableMetadata?
  50. var dataSourceTask: URLSessionTask?
  51. var dataSource = NCCollectionViewDataSource()
  52. let heightRowTableView: CGFloat = 50
  53. let heightCommandView: CGFloat = 170
  54. var autoUploadFileName = ""
  55. var autoUploadDirectory = ""
  56. let refreshControl = UIRefreshControl()
  57. var progress: CGFloat = 0
  58. var counterUploaded: Int = 0
  59. var uploadErrors: [tableMetadata] = []
  60. var uploadMetadata: [tableMetadata] = []
  61. var uploadStarted = false
  62. let hud = NCHud()
  63. let utilityFileSystem = NCUtilityFileSystem()
  64. let utility = NCUtility()
  65. let database = NCManageDatabase.shared
  66. var account: String = ""
  67. var session: NCSession.Session {
  68. if !account.isEmpty,
  69. let tableAccount = self.database.getTableAccount(account: account) {
  70. return NCSession.Session(account: tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId)
  71. } else if let activeTableAccount = self.database.getActiveTableAccount() {
  72. self.account = activeTableAccount.account
  73. return NCSession.Session(account: activeTableAccount.account, urlBase: activeTableAccount.urlBase, user: activeTableAccount.user, userId: activeTableAccount.userId)
  74. } else {
  75. return NCSession.Session(account: "", urlBase: "", user: "", userId: "")
  76. }
  77. }
  78. // MARK: - View Life Cycle
  79. override func viewDidLoad() {
  80. super.viewDidLoad()
  81. self.navigationController?.navigationBar.prefersLargeTitles = false
  82. collectionView.register(UINib(nibName: "NCSectionFirstHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionFirstHeaderEmptyData")
  83. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  84. collectionView.collectionViewLayout = NCListLayout()
  85. collectionView.refreshControl = refreshControl
  86. refreshControl.tintColor = NCBrandColor.shared.iconImageColor
  87. refreshControl.backgroundColor = .systemBackground
  88. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  89. commandView.backgroundColor = .secondarySystemBackground
  90. separatorView.backgroundColor = .separator
  91. separatorHeightConstraint.constant = 0.5
  92. tableView.separatorColor = .separator
  93. tableView.layer.cornerRadius = 10
  94. tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
  95. commandViewHeightConstraint.constant = heightCommandView
  96. createFolderView.layer.cornerRadius = 10
  97. createFolderImage.image = utility.loadImage(named: "folder.badge.plus", colors: [NCBrandColor.shared.iconImageColor])
  98. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  99. let createFolderGesture = UITapGestureRecognizer(target: self, action: #selector(actionCreateFolder))
  100. createFolderView.addGestureRecognizer(createFolderGesture)
  101. uploadView.layer.cornerRadius = 10
  102. uploadLabel.text = NSLocalizedString("_upload_", comment: "")
  103. uploadLabel.textColor = .systemBlue
  104. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(actionUpload))
  105. uploadView.addGestureRecognizer(uploadGesture)
  106. // LOG
  107. let levelLog = NCKeychain().logLevel
  108. let isSimulatorOrTestFlight = utility.isSimulatorOrTestFlight()
  109. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  110. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  111. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  112. if isSimulatorOrTestFlight {
  113. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  114. } else {
  115. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS)
  116. }
  117. NCBrandColor.shared.createUserColors()
  118. NotificationCenter.default.addObserver(self, selector: #selector(didCreateFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  119. }
  120. override func viewWillAppear(_ animated: Bool) {
  121. super.viewWillAppear(animated)
  122. guard !session.account.isEmpty,
  123. !NCPasscode.shared.isPasscodeReset else {
  124. return showAlert(description: "_no_active_account_") {
  125. self.cancel(with: .noAccount)
  126. }
  127. }
  128. accountRequestChangeAccount(account: account, controller: nil)
  129. guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
  130. cancel(with: .noFiles)
  131. return
  132. }
  133. NCFilesExtensionHandler(items: inputItems) { fileNames in
  134. self.filesName = fileNames
  135. DispatchQueue.main.async { self.setCommandView() }
  136. }
  137. if NCKeychain().presentPasscode {
  138. NCPasscode.shared.presentPasscode(viewController: self, delegate: self) {
  139. NCPasscode.shared.enableTouchFaceID()
  140. }
  141. }
  142. }
  143. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  144. super.viewWillTransition(to: size, with: coordinator)
  145. coordinator.animate(alongsideTransition: nil) { _ in
  146. self.collectionView?.collectionViewLayout.invalidateLayout()
  147. }
  148. }
  149. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  150. super.traitCollectionDidChange(previousTraitCollection)
  151. collectionView.reloadData()
  152. tableView.reloadData()
  153. }
  154. // MARK: -
  155. func cancel(with error: NCShareExtensionError) {
  156. // make sure no uploads are continued
  157. uploadStarted = false
  158. extensionContext?.cancelRequest(withError: error)
  159. }
  160. func showAlert(title: String = "_error_", description: String, onDismiss: (() -> Void)? = nil) {
  161. let description = description.replacingOccurrences(of: "\t", with: "\n")
  162. let alertController = UIAlertController(title: NSLocalizedString(title, comment: ""), message: NSLocalizedString(description, comment: ""), preferredStyle: .alert)
  163. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  164. onDismiss?()
  165. }))
  166. self.present(alertController, animated: true)
  167. }
  168. func setNavigationBar(navigationTitle: String) {
  169. navigationItem.title = navigationTitle
  170. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  171. // BACK BUTTON
  172. let backButton = UIButton(type: .custom)
  173. backButton.setImage(UIImage(named: "back"), for: .normal)
  174. backButton.tintColor = .systemBlue
  175. backButton.semanticContentAttribute = .forceLeftToRight
  176. backButton.setTitle(" " + NSLocalizedString("_back_", comment: ""), for: .normal)
  177. backButton.setTitleColor(.systemBlue, for: .normal)
  178. backButton.action(for: .touchUpInside) { _ in
  179. if !self.uploadStarted {
  180. while self.serverUrl.last != "/" { self.serverUrl.removeLast() }
  181. self.serverUrl.removeLast()
  182. self.reloadDatasource(withLoadFolder: true)
  183. var navigationTitle = (self.serverUrl as NSString).lastPathComponent
  184. if self.utilityFileSystem.getHomeServer(session: self.session) == self.serverUrl {
  185. navigationTitle = NCBrandOptions.shared.brand
  186. }
  187. self.setNavigationBar(navigationTitle: navigationTitle)
  188. }
  189. }
  190. let tableAccount = self.database.getTableAccount(account: session.account)
  191. let image = utility.loadUserImage(for: session.user, displayName: tableAccount?.displayName, urlBase: session.urlBase)
  192. let profileButton = UIButton(type: .custom)
  193. profileButton.setImage(image, for: .normal)
  194. if serverUrl == utilityFileSystem.getHomeServer(session: self.session) {
  195. var title = " "
  196. if let userAlias = tableAccount?.alias, !userAlias.isEmpty {
  197. title += userAlias
  198. } else {
  199. title += tableAccount?.displayName ?? ""
  200. }
  201. profileButton.setTitle(title, for: .normal)
  202. profileButton.setTitleColor(.systemBlue, for: .normal)
  203. }
  204. profileButton.semanticContentAttribute = .forceLeftToRight
  205. profileButton.sizeToFit()
  206. profileButton.action(for: .touchUpInside) { _ in
  207. if !self.uploadStarted {
  208. self.showAccountPicker()
  209. }
  210. }
  211. var navItems = [UIBarButtonItem(customView: profileButton)]
  212. if serverUrl != utilityFileSystem.getHomeServer(session: self.session) {
  213. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  214. space.width = 20
  215. navItems.append(contentsOf: [UIBarButtonItem(customView: backButton), space])
  216. }
  217. navigationItem.setLeftBarButtonItems(navItems, animated: true)
  218. }
  219. func setCommandView() {
  220. guard !filesName.isEmpty else {
  221. cancel(with: .noFiles)
  222. return
  223. }
  224. let counter = min(CGFloat(filesName.count), 3)
  225. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  226. if filesName.count <= 3 {
  227. self.tableView.isScrollEnabled = false
  228. }
  229. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  230. self.tableView.reloadData()
  231. }
  232. // MARK: ACTION
  233. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  234. cancel(with: .cancel)
  235. }
  236. @objc func actionCreateFolder() {
  237. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, session: session) { error in
  238. guard error != .success else { return }
  239. self.showAlert(title: "_error_createsubfolders_upload_", description: error.errorDescription)
  240. }
  241. self.present(alertController, animated: true)
  242. }
  243. }
  244. // MARK: - Upload
  245. extension NCShareExtension {
  246. @objc func actionUpload() {
  247. guard !uploadStarted else { return }
  248. guard !filesName.isEmpty else { return showAlert(description: "_files_no_files_") }
  249. counterUploaded = 0
  250. uploadErrors = []
  251. var dismissAfterUpload = true
  252. var conflicts: [tableMetadata] = []
  253. var invalidNameIndexes: [Int] = []
  254. for (index, fileName) in filesName.enumerated() {
  255. let newFileName = FileAutoRenamer.shared.rename(fileName, account: session.account)
  256. if fileName != newFileName {
  257. renameFile(oldName: fileName, newName: newFileName, account: session.account)
  258. }
  259. if let fileNameError = FileNameValidator.shared.checkFileName(newFileName, account: session.account) {
  260. if filesName.count == 1 {
  261. showRenameFileDialog(named: fileName, account: account)
  262. return
  263. } else {
  264. present(UIAlertController.warning(message: "\(fileNameError.errorDescription) \(NSLocalizedString("_please_rename_file_", comment: ""))") {
  265. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  266. }, animated: true)
  267. invalidNameIndexes.append(index)
  268. dismissAfterUpload = false
  269. continue
  270. }
  271. }
  272. }
  273. for index in invalidNameIndexes.reversed() {
  274. filesName.remove(at: index)
  275. }
  276. for fileName in filesName {
  277. let ocId = NSUUID().uuidString
  278. let toPath = utilityFileSystem.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)
  279. guard utilityFileSystem.copyFile(atPath: (NSTemporaryDirectory() + fileName), toPath: toPath) else { continue }
  280. let metadataForUpload = self.database.createMetadata(fileName: fileName,
  281. fileNameView: fileName,
  282. ocId: ocId,
  283. serverUrl: serverUrl,
  284. url: "",
  285. contentType: "",
  286. session: session,
  287. sceneIdentifier: nil)
  288. metadataForUpload.session = NCNetworking.shared.sessionUpload
  289. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFileShareExtension
  290. metadataForUpload.size = utilityFileSystem.getFileSize(filePath: toPath)
  291. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  292. metadataForUpload.sessionDate = Date()
  293. if self.database.getMetadataConflict(account: session.account, serverUrl: serverUrl, fileNameView: fileName) != nil {
  294. conflicts.append(metadataForUpload)
  295. } else {
  296. uploadMetadata.append(metadataForUpload)
  297. }
  298. }
  299. tableView.reloadData()
  300. if !conflicts.isEmpty {
  301. guard let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict
  302. else { return }
  303. conflict.account = session.account
  304. conflict.serverUrl = self.serverUrl
  305. conflict.metadatasUploadInConflict = conflicts
  306. conflict.delegate = self
  307. self.present(conflict, animated: true, completion: nil)
  308. } else {
  309. uploadStarted = true
  310. upload(dismissAfterUpload: dismissAfterUpload)
  311. }
  312. }
  313. func upload(dismissAfterUpload: Bool = true) {
  314. guard uploadStarted else { return }
  315. guard uploadMetadata.count > counterUploaded else { return DispatchQueue.main.async { self.finishedUploading(dismissAfterUpload: dismissAfterUpload) } }
  316. let metadata = uploadMetadata[counterUploaded]
  317. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false, account: session.account)
  318. metadata.contentType = results.mimeType
  319. metadata.iconName = results.iconName
  320. metadata.classFile = results.classFile
  321. // CHUNK
  322. var chunkSize = NCGlobal.shared.chunkSizeMBCellular
  323. if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  324. chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
  325. }
  326. if metadata.size > chunkSize {
  327. metadata.chunk = chunkSize
  328. } else {
  329. metadata.chunk = 0
  330. }
  331. // E2EE
  332. metadata.e2eEncrypted = metadata.isDirectoryE2EE
  333. hud.initHudRing(view: self.view,
  334. text: NSLocalizedString("_upload_file_", comment: "") + " \(self.counterUploaded + 1) " + NSLocalizedString("_of_", comment: "") + " \(self.filesName.count)")
  335. NCNetworking.shared.upload(metadata: metadata, uploadE2EEDelegate: self, controller: self) {
  336. self.hud.progress(0)
  337. } progressHandler: { _, _, fractionCompleted in
  338. self.hud.progress(fractionCompleted)
  339. } completion: { _, error in
  340. if error != .success {
  341. self.database.deleteMetadataOcId(metadata.ocId)
  342. self.utilityFileSystem.removeFile(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  343. self.uploadErrors.append(metadata)
  344. }
  345. self.counterUploaded += 1
  346. self.upload()
  347. }
  348. }
  349. func finishedUploading(dismissAfterUpload: Bool = true) {
  350. uploadStarted = false
  351. if !uploadErrors.isEmpty {
  352. let fileList = "- " + uploadErrors.map({ $0.fileName }).joined(separator: "\n - ")
  353. showAlert(title: "_error_files_upload_", description: fileList) {
  354. self.extensionContext?.cancelRequest(withError: NCShareExtensionError.fileUpload)
  355. }
  356. } else {
  357. hud.success()
  358. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  359. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  360. }
  361. }
  362. }
  363. }
  364. extension NCShareExtension: uploadE2EEDelegate {
  365. func start() {
  366. self.hud.progress(0)
  367. }
  368. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) {
  369. self.hud.progress(fractionCompleted)
  370. }
  371. }
  372. extension NCShareExtension: NCPasscodeDelegate {
  373. func passcodeReset(_ passcodeViewController: TOPasscodeViewController) {
  374. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  375. passcodeViewController.dismiss(animated: false)
  376. self.cancel(with: .noAccount)
  377. }
  378. }
  379. func evaluatePolicy(_ passcodeViewController: TOPasscodeViewController, isCorrectCode: Bool) {
  380. if !isCorrectCode {
  381. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  382. passcodeViewController.dismiss(animated: false)
  383. self.cancel(with: .noAccount)
  384. }
  385. }
  386. }
  387. }