NCShareExtension.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 NCCommunication
  27. import JGProgressHUD
  28. enum NCShareExtensionError: Error {
  29. case cancel, fileUpload, noAccount, noFiles
  30. }
  31. class NCShareExtension: UIViewController {
  32. @IBOutlet weak var collectionView: UICollectionView!
  33. @IBOutlet weak var tableView: UITableView!
  34. @IBOutlet weak var cancelButton: UIBarButtonItem!
  35. @IBOutlet weak var separatorView: UIView!
  36. @IBOutlet weak var commandView: UIView!
  37. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  38. @IBOutlet weak var commandViewHeightConstraint: NSLayoutConstraint!
  39. @IBOutlet weak var createFolderView: UIView!
  40. @IBOutlet weak var createFolderImage: UIImageView!
  41. @IBOutlet weak var createFolderLabel: UILabel!
  42. @IBOutlet weak var uploadView: UIView!
  43. @IBOutlet weak var uploadImage: UIImageView!
  44. @IBOutlet weak var uploadLabel: UILabel!
  45. // -------------------------------------------------------------
  46. var serverUrl = ""
  47. var filesName: [String] = []
  48. // -------------------------------------------------------------
  49. var emptyDataSet: NCEmptyDataSet?
  50. let keyLayout = NCGlobal.shared.layoutViewShareExtension
  51. var metadataFolder: tableMetadata?
  52. var networkInProgress = false
  53. var dataSource = NCDataSource()
  54. var layoutForView: NCGlobal.layoutForViewType?
  55. let heightRowTableView: CGFloat = 50
  56. let heightCommandView: CGFloat = 170
  57. var autoUploadFileName = ""
  58. var autoUploadDirectory = ""
  59. let refreshControl = UIRefreshControl()
  60. var activeAccount: tableAccount!
  61. let chunckSize = CCUtility.getChunkSize() * 1000000
  62. var progress: CGFloat = 0
  63. var counterUploaded: Int = 0
  64. var uploadErrors: [tableMetadata] = []
  65. var uploadMetadata: [tableMetadata] = []
  66. var uploadStarted = false
  67. let hud = JGProgressHUD()
  68. // MARK: - View Life Cycle
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. self.navigationController?.navigationBar.prefersLargeTitles = false
  72. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  73. collectionView.collectionViewLayout = NCListLayout()
  74. collectionView.addSubview(refreshControl)
  75. refreshControl.tintColor = NCBrandColor.shared.brandText
  76. refreshControl.backgroundColor = NCBrandColor.shared.systemBackground
  77. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  78. commandView.backgroundColor = NCBrandColor.shared.secondarySystemBackground
  79. separatorView.backgroundColor = NCBrandColor.shared.separator
  80. separatorHeightConstraint.constant = 0.5
  81. tableView.separatorColor = NCBrandColor.shared.separator
  82. tableView.layer.cornerRadius = 10
  83. tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
  84. commandViewHeightConstraint.constant = heightCommandView
  85. createFolderView.layer.cornerRadius = 10
  86. createFolderImage.image = NCUtility.shared.loadImage(named: "folder.badge.plus", color: NCBrandColor.shared.label)
  87. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  88. let createFolderGesture = UITapGestureRecognizer(target: self, action: #selector(actionCreateFolder))
  89. createFolderView.addGestureRecognizer(createFolderGesture)
  90. uploadView.layer.cornerRadius = 10
  91. // uploadImage.image = NCUtility.shared.loadImage(named: "square.and.arrow.up", color: NCBrandColor.shared.label)
  92. uploadLabel.text = NSLocalizedString("_upload_", comment: "")
  93. uploadLabel.textColor = .systemBlue
  94. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(actionUpload))
  95. uploadView.addGestureRecognizer(uploadGesture)
  96. // LOG
  97. let levelLog = CCUtility.getLogLevel()
  98. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  99. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  100. NCCommunicationCommon.shared.levelLog = levelLog
  101. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  102. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  103. }
  104. if isSimulatorOrTestFlight {
  105. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  106. } else {
  107. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  108. }
  109. hud.indicatorView = JGProgressHUDRingIndicatorView()
  110. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  111. indicatorView.ringWidth = 1.5
  112. }
  113. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(didCreateFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  115. }
  116. override func viewWillAppear(_ animated: Bool) {
  117. super.viewWillAppear(animated)
  118. guard serverUrl.isEmpty else { return }
  119. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else {
  120. return showAlert(description: "_no_active_account_") {
  121. self.cancel(with: .noAccount)
  122. }
  123. }
  124. accountRequestChangeAccount(account: activeAccount.account)
  125. guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
  126. cancel(with: .noFiles)
  127. return
  128. }
  129. NCFilesExtensionHandler(items: inputItems) { fileNames in
  130. self.filesName = fileNames
  131. DispatchQueue.main.async { self.setCommandView() }
  132. }
  133. }
  134. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  135. super.viewWillTransition(to: size, with: coordinator)
  136. coordinator.animate(alongsideTransition: nil) { _ in
  137. self.collectionView?.collectionViewLayout.invalidateLayout()
  138. }
  139. }
  140. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  141. super.traitCollectionDidChange(previousTraitCollection)
  142. collectionView.reloadData()
  143. tableView.reloadData()
  144. }
  145. // MARK: -
  146. func cancel(with error: NCShareExtensionError) {
  147. // make sure no uploads are continued
  148. uploadStarted = false
  149. extensionContext?.cancelRequest(withError: error)
  150. }
  151. func showAlert(title: String = "_error_", description: String, onDismiss: (() -> Void)? = nil) {
  152. let alertController = UIAlertController(title: NSLocalizedString(title, comment: ""), message: NSLocalizedString(description, comment: ""), preferredStyle: .alert)
  153. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  154. onDismiss?()
  155. }))
  156. self.present(alertController, animated: true)
  157. }
  158. @objc func triggerProgressTask(_ notification: NSNotification) {
  159. guard let progress = notification.userInfo?["progress"] as? Float else { return }
  160. hud.progress = progress
  161. }
  162. func setNavigationBar(navigationTitle: String) {
  163. navigationItem.title = navigationTitle
  164. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  165. // BACK BUTTON
  166. let backButton = UIButton(type: .custom)
  167. backButton.setImage(UIImage(named: "back"), for: .normal)
  168. backButton.tintColor = .systemBlue
  169. backButton.semanticContentAttribute = .forceLeftToRight
  170. backButton.setTitle(" " + NSLocalizedString("_back_", comment: ""), for: .normal)
  171. backButton.setTitleColor(.systemBlue, for: .normal)
  172. backButton.action(for: .touchUpInside) { _ in
  173. if !self.uploadStarted {
  174. while self.serverUrl.last != "/" { self.serverUrl.removeLast() }
  175. self.serverUrl.removeLast()
  176. self.reloadDatasource(withLoadFolder: true)
  177. var navigationTitle = (self.serverUrl as NSString).lastPathComponent
  178. if NCUtilityFileSystem.shared.getHomeServer(account: self.activeAccount.account) == self.serverUrl {
  179. navigationTitle = NCBrandOptions.shared.brand
  180. }
  181. self.setNavigationBar(navigationTitle: navigationTitle)
  182. }
  183. }
  184. let image = NCUtility.shared.loadUserImage(for: activeAccount.user, displayName: activeAccount.displayName, userBaseUrl: activeAccount)
  185. let profileButton = UIButton(type: .custom)
  186. profileButton.setImage(image, for: .normal)
  187. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  188. var title = " "
  189. if let userAlias = activeAccount?.alias, !userAlias.isEmpty {
  190. title += userAlias
  191. } else {
  192. title += activeAccount?.displayName ?? ""
  193. }
  194. profileButton.setTitle(title, for: .normal)
  195. profileButton.setTitleColor(.systemBlue, for: .normal)
  196. }
  197. profileButton.semanticContentAttribute = .forceLeftToRight
  198. profileButton.sizeToFit()
  199. profileButton.action(for: .touchUpInside) { _ in
  200. if !self.uploadStarted {
  201. self.showAccountPicker()
  202. }
  203. }
  204. var navItems = [UIBarButtonItem(customView: profileButton)]
  205. if serverUrl != NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  206. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  207. space.width = 20
  208. navItems.append(contentsOf: [UIBarButtonItem(customView: backButton), space])
  209. }
  210. navigationItem.setLeftBarButtonItems(navItems, animated: true)
  211. }
  212. func setCommandView() {
  213. guard !filesName.isEmpty else {
  214. cancel(with: .noFiles)
  215. return
  216. }
  217. let counter = min(CGFloat(filesName.count), 3)
  218. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  219. if filesName.count <= 3 {
  220. self.tableView.isScrollEnabled = false
  221. }
  222. // Label upload button
  223. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  224. // Empty
  225. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: -50 * counter, delegate: self)
  226. self.tableView.reloadData()
  227. }
  228. // MARK: ACTION
  229. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  230. cancel(with: .cancel)
  231. }
  232. @objc func actionCreateFolder() {
  233. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, urlBase: activeAccount) { errorCode, errorDescription in
  234. guard errorCode != 0 else { return }
  235. self.showAlert(title: "_error_createsubfolders_upload_", description: errorDescription)
  236. }
  237. self.present(alertController, animated: true)
  238. }
  239. }
  240. // MARK: - Upload
  241. extension NCShareExtension {
  242. @objc func actionUpload() {
  243. guard !uploadStarted else { return }
  244. guard !filesName.isEmpty else { return showAlert(description: "_files_no_files_") }
  245. counterUploaded = 0
  246. uploadStarted = true
  247. uploadErrors = []
  248. var conflicts: [tableMetadata] = []
  249. for fileName in filesName {
  250. let ocId = NSUUID().uuidString
  251. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  252. guard NCUtilityFileSystem.shared.copyFile(atPath: (NSTemporaryDirectory() + fileName), toPath: toPath) else { continue }
  253. let metadata = NCManageDatabase.shared.createMetadata(
  254. account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId,
  255. fileName: fileName, fileNameView: fileName,
  256. ocId: ocId,
  257. serverUrl: serverUrl, urlBase: activeAccount.urlBase, url: "",
  258. contentType: "",
  259. livePhoto: false)
  260. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  261. metadata.sessionSelector = NCGlobal.shared.selectorUploadFileShareExtension
  262. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: toPath)
  263. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  264. if NCManageDatabase.shared.getMetadataConflict(account: activeAccount.account, serverUrl: serverUrl, fileName: fileName) != nil {
  265. conflicts.append(metadata)
  266. } else {
  267. uploadMetadata.append(metadata)
  268. }
  269. }
  270. if !conflicts.isEmpty {
  271. guard let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict
  272. else { return }
  273. conflict.serverUrl = self.serverUrl
  274. conflict.metadatasUploadInConflict = conflicts
  275. conflict.delegate = self
  276. self.present(conflict, animated: true, completion: nil)
  277. } else {
  278. upload()
  279. }
  280. }
  281. func upload() {
  282. guard uploadStarted else { return }
  283. guard uploadMetadata.count > counterUploaded else { return finishedUploading() }
  284. let metadata = uploadMetadata[counterUploaded]
  285. // E2EE
  286. metadata.e2eEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  287. // CHUNCK
  288. metadata.chunk = chunckSize != 0 && metadata.size > chunckSize
  289. hud.textLabel.text = NSLocalizedString("_upload_file_", comment: "") + " \(counterUploaded + 1) " + NSLocalizedString("_of_", comment: "") + " \(filesName.count)"
  290. hud.progress = 0
  291. hud.show(in: self.view)
  292. NCNetworking.shared.upload(metadata: metadata) { } completion: { errorCode, _ in
  293. if errorCode != 0 {
  294. let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  295. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  296. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  297. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  298. self.uploadErrors.append(metadata)
  299. }
  300. self.counterUploaded += 1
  301. self.upload()
  302. }
  303. }
  304. func finishedUploading() {
  305. uploadStarted = false
  306. if !uploadErrors.isEmpty {
  307. let fileList = "- " + uploadErrors.map({ $0.fileName }).joined(separator: "\n - ")
  308. showAlert(title: "_error_files_upload_", description: fileList) {
  309. self.extensionContext?.cancelRequest(withError: NCShareExtensionError.fileUpload)
  310. }
  311. } else {
  312. hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  313. hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  314. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  315. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  316. }
  317. }
  318. }
  319. }