NCShareExtension.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. 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 = .systemBackground
  77. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  78. commandView.backgroundColor = .secondarySystemBackground
  79. separatorView.backgroundColor = .separator
  80. separatorHeightConstraint.constant = 0.5
  81. tableView.separatorColor = .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: .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: .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. NKCommon.shared.levelLog = levelLog
  101. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  102. NKCommon.shared.pathLog = pathDirectoryGroup
  103. }
  104. if isSimulatorOrTestFlight {
  105. NKCommon.shared.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  106. } else {
  107. NKCommon.shared.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS)
  108. }
  109. // Colors
  110. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  111. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  112. } else {
  113. NCBrandColor.shared.createImagesThemingColor()
  114. }
  115. NCBrandColor.shared.createUserColors()
  116. hud.indicatorView = JGProgressHUDRingIndicatorView()
  117. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  118. indicatorView.ringWidth = 1.5
  119. }
  120. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(didCreateFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  122. }
  123. override func viewWillAppear(_ animated: Bool) {
  124. super.viewWillAppear(animated)
  125. guard serverUrl.isEmpty else { return }
  126. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else {
  127. return showAlert(description: "_no_active_account_") {
  128. self.cancel(with: .noAccount)
  129. }
  130. }
  131. accountRequestChangeAccount(account: activeAccount.account)
  132. guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
  133. cancel(with: .noFiles)
  134. return
  135. }
  136. NCFilesExtensionHandler(items: inputItems) { fileNames in
  137. self.filesName = fileNames
  138. DispatchQueue.main.async { self.setCommandView() }
  139. }
  140. }
  141. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  142. super.viewWillTransition(to: size, with: coordinator)
  143. coordinator.animate(alongsideTransition: nil) { _ in
  144. self.collectionView?.collectionViewLayout.invalidateLayout()
  145. }
  146. }
  147. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  148. super.traitCollectionDidChange(previousTraitCollection)
  149. collectionView.reloadData()
  150. tableView.reloadData()
  151. }
  152. // MARK: -
  153. func cancel(with error: NCShareExtensionError) {
  154. // make sure no uploads are continued
  155. uploadStarted = false
  156. extensionContext?.cancelRequest(withError: error)
  157. }
  158. func showAlert(title: String = "_error_", description: String, onDismiss: (() -> Void)? = nil) {
  159. let alertController = UIAlertController(title: NSLocalizedString(title, comment: ""), message: NSLocalizedString(description, comment: ""), preferredStyle: .alert)
  160. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  161. onDismiss?()
  162. }))
  163. self.present(alertController, animated: true)
  164. }
  165. @objc func triggerProgressTask(_ notification: NSNotification) {
  166. guard let progress = notification.userInfo?["progress"] as? Float else { return }
  167. hud.progress = progress
  168. }
  169. func setNavigationBar(navigationTitle: String) {
  170. navigationItem.title = navigationTitle
  171. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  172. // BACK BUTTON
  173. let backButton = UIButton(type: .custom)
  174. backButton.setImage(UIImage(named: "back"), for: .normal)
  175. backButton.tintColor = .systemBlue
  176. backButton.semanticContentAttribute = .forceLeftToRight
  177. backButton.setTitle(" " + NSLocalizedString("_back_", comment: ""), for: .normal)
  178. backButton.setTitleColor(.systemBlue, for: .normal)
  179. backButton.action(for: .touchUpInside) { _ in
  180. if !self.uploadStarted {
  181. while self.serverUrl.last != "/" { self.serverUrl.removeLast() }
  182. self.serverUrl.removeLast()
  183. self.reloadDatasource(withLoadFolder: true)
  184. var navigationTitle = (self.serverUrl as NSString).lastPathComponent
  185. if NCUtilityFileSystem.shared.getHomeServer(urlBase: self.activeAccount.urlBase, userId: self.activeAccount.userId) == self.serverUrl {
  186. navigationTitle = NCBrandOptions.shared.brand
  187. }
  188. self.setNavigationBar(navigationTitle: navigationTitle)
  189. }
  190. }
  191. let image = NCUtility.shared.loadUserImage(for: activeAccount.user, displayName: activeAccount.displayName, userBaseUrl: activeAccount)
  192. let profileButton = UIButton(type: .custom)
  193. profileButton.setImage(image, for: .normal)
  194. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) {
  195. var title = " "
  196. if let userAlias = activeAccount?.alias, !userAlias.isEmpty {
  197. title += userAlias
  198. } else {
  199. title += activeAccount?.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 != NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) {
  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. // Label upload button
  230. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  231. // Empty
  232. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: -50 * counter, delegate: self)
  233. self.tableView.reloadData()
  234. }
  235. // MARK: ACTION
  236. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  237. cancel(with: .cancel)
  238. }
  239. @objc func actionCreateFolder() {
  240. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, urlBase: activeAccount) { error in
  241. guard error != .success else { return }
  242. self.showAlert(title: "_error_createsubfolders_upload_", description: error.errorDescription)
  243. }
  244. self.present(alertController, animated: true)
  245. }
  246. }
  247. // MARK: - Upload
  248. extension NCShareExtension {
  249. @objc func actionUpload() {
  250. guard !uploadStarted else { return }
  251. guard !filesName.isEmpty else { return showAlert(description: "_files_no_files_") }
  252. counterUploaded = 0
  253. uploadStarted = true
  254. uploadErrors = []
  255. var conflicts: [tableMetadata] = []
  256. for fileName in filesName {
  257. let ocId = NSUUID().uuidString
  258. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  259. guard NCUtilityFileSystem.shared.copyFile(atPath: (NSTemporaryDirectory() + fileName), toPath: toPath) else { continue }
  260. let metadata = NCManageDatabase.shared.createMetadata(
  261. account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId,
  262. fileName: fileName, fileNameView: fileName,
  263. ocId: ocId,
  264. serverUrl: serverUrl, urlBase: activeAccount.urlBase, url: "",
  265. contentType: "")
  266. metadata.session = NKCommon.shared.sessionIdentifierUpload
  267. metadata.sessionSelector = NCGlobal.shared.selectorUploadFileShareExtension
  268. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: toPath)
  269. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  270. if NCManageDatabase.shared.getMetadataConflict(account: activeAccount.account, serverUrl: serverUrl, fileName: fileName) != nil {
  271. conflicts.append(metadata)
  272. } else {
  273. uploadMetadata.append(metadata)
  274. }
  275. }
  276. if !conflicts.isEmpty {
  277. guard let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict
  278. else { return }
  279. conflict.serverUrl = self.serverUrl
  280. conflict.metadatasUploadInConflict = conflicts
  281. conflict.delegate = self
  282. conflict.isE2EE = CCUtility.isFolderEncrypted(self.serverUrl, e2eEncrypted: false, account: activeAccount.account, urlBase: activeAccount.urlBase, userId: activeAccount.userId)
  283. self.present(conflict, animated: true, completion: nil)
  284. } else {
  285. upload()
  286. }
  287. }
  288. func upload() {
  289. guard uploadStarted else { return }
  290. guard uploadMetadata.count > counterUploaded else { return finishedUploading() }
  291. let metadata = uploadMetadata[counterUploaded]
  292. let results = NKCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  293. metadata.contentType = results.mimeType
  294. metadata.iconName = results.iconName
  295. metadata.classFile = results.classFile
  296. // E2EE
  297. metadata.e2eEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase, userId: activeAccount.userId)
  298. // CHUNCK
  299. metadata.chunk = chunckSize != 0 && metadata.size > chunckSize
  300. hud.textLabel.text = NSLocalizedString("_upload_file_", comment: "") + " \(counterUploaded + 1) " + NSLocalizedString("_of_", comment: "") + " \(filesName.count)"
  301. hud.progress = 0
  302. hud.show(in: self.view)
  303. NCNetworking.shared.upload(metadata: metadata) { } completion: { error in
  304. if error != .success {
  305. let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  306. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  307. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  308. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  309. self.uploadErrors.append(metadata)
  310. }
  311. self.counterUploaded += 1
  312. self.upload()
  313. }
  314. }
  315. func finishedUploading() {
  316. uploadStarted = false
  317. if !uploadErrors.isEmpty {
  318. let fileList = "- " + uploadErrors.map({ $0.fileName }).joined(separator: "\n - ")
  319. showAlert(title: "_error_files_upload_", description: fileList) {
  320. self.extensionContext?.cancelRequest(withError: NCShareExtensionError.fileUpload)
  321. }
  322. } else {
  323. hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  324. hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  325. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  326. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  327. }
  328. }
  329. }
  330. }