NCShareExtension.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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: NCDBLayoutForView?
  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. var progress: CGFloat = 0
  62. var counterUploaded: Int = 0
  63. var uploadErrors: [tableMetadata] = []
  64. var uploadMetadata: [tableMetadata] = []
  65. var uploadStarted = false
  66. let hud = JGProgressHUD()
  67. // MARK: - View Life Cycle
  68. override func viewDidLoad() {
  69. super.viewDidLoad()
  70. self.navigationController?.navigationBar.prefersLargeTitles = false
  71. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  72. collectionView.collectionViewLayout = NCListLayout()
  73. collectionView.refreshControl = refreshControl
  74. refreshControl.tintColor = NCBrandColor.shared.brandText
  75. refreshControl.backgroundColor = .systemBackground
  76. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  77. commandView.backgroundColor = .secondarySystemBackground
  78. separatorView.backgroundColor = .separator
  79. separatorHeightConstraint.constant = 0.5
  80. tableView.separatorColor = .separator
  81. tableView.layer.cornerRadius = 10
  82. tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
  83. commandViewHeightConstraint.constant = heightCommandView
  84. createFolderView.layer.cornerRadius = 10
  85. createFolderImage.image = NCUtility.shared.loadImage(named: "folder.badge.plus", color: .label)
  86. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  87. let createFolderGesture = UITapGestureRecognizer(target: self, action: #selector(actionCreateFolder))
  88. createFolderView.addGestureRecognizer(createFolderGesture)
  89. uploadView.layer.cornerRadius = 10
  90. // uploadImage.image = NCUtility.shared.loadImage(named: "square.and.arrow.up", color: .label)
  91. uploadLabel.text = NSLocalizedString("_upload_", comment: "")
  92. uploadLabel.textColor = .systemBlue
  93. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(actionUpload))
  94. uploadView.addGestureRecognizer(uploadGesture)
  95. // LOG
  96. let levelLog = CCUtility.getLogLevel()
  97. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  98. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  99. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  100. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  101. NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup
  102. }
  103. if isSimulatorOrTestFlight {
  104. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  105. } else {
  106. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS)
  107. }
  108. // Colors
  109. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  110. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  111. } else {
  112. NCBrandColor.shared.createImagesThemingColor()
  113. }
  114. NCBrandColor.shared.createUserColors()
  115. hud.indicatorView = JGProgressHUDRingIndicatorView()
  116. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  117. indicatorView.ringWidth = 1.5
  118. }
  119. NotificationCenter.default.addObserver(self, selector: #selector(didCreateFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  120. }
  121. override func viewWillAppear(_ animated: Bool) {
  122. super.viewWillAppear(animated)
  123. guard serverUrl.isEmpty else { return }
  124. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else {
  125. return showAlert(description: "_no_active_account_") {
  126. self.cancel(with: .noAccount)
  127. }
  128. }
  129. accountRequestChangeAccount(account: activeAccount.account)
  130. guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem] else {
  131. cancel(with: .noFiles)
  132. return
  133. }
  134. NCFilesExtensionHandler(items: inputItems) { fileNames in
  135. self.filesName = fileNames
  136. DispatchQueue.main.async { self.setCommandView() }
  137. }
  138. }
  139. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  140. super.viewWillTransition(to: size, with: coordinator)
  141. coordinator.animate(alongsideTransition: nil) { _ in
  142. self.collectionView?.collectionViewLayout.invalidateLayout()
  143. }
  144. }
  145. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  146. super.traitCollectionDidChange(previousTraitCollection)
  147. collectionView.reloadData()
  148. tableView.reloadData()
  149. }
  150. // MARK: -
  151. func cancel(with error: NCShareExtensionError) {
  152. // make sure no uploads are continued
  153. uploadStarted = false
  154. extensionContext?.cancelRequest(withError: error)
  155. }
  156. func showAlert(title: String = "_error_", description: String, onDismiss: (() -> Void)? = nil) {
  157. let alertController = UIAlertController(title: NSLocalizedString(title, comment: ""), message: NSLocalizedString(description, comment: ""), preferredStyle: .alert)
  158. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  159. onDismiss?()
  160. }))
  161. self.present(alertController, animated: true)
  162. }
  163. func setNavigationBar(navigationTitle: String) {
  164. navigationItem.title = navigationTitle
  165. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  166. // BACK BUTTON
  167. let backButton = UIButton(type: .custom)
  168. backButton.setImage(UIImage(named: "back"), for: .normal)
  169. backButton.tintColor = .systemBlue
  170. backButton.semanticContentAttribute = .forceLeftToRight
  171. backButton.setTitle(" " + NSLocalizedString("_back_", comment: ""), for: .normal)
  172. backButton.setTitleColor(.systemBlue, for: .normal)
  173. backButton.action(for: .touchUpInside) { _ in
  174. if !self.uploadStarted {
  175. while self.serverUrl.last != "/" { self.serverUrl.removeLast() }
  176. self.serverUrl.removeLast()
  177. self.reloadDatasource(withLoadFolder: true)
  178. var navigationTitle = (self.serverUrl as NSString).lastPathComponent
  179. if NCUtilityFileSystem.shared.getHomeServer(urlBase: self.activeAccount.urlBase, userId: self.activeAccount.userId) == self.serverUrl {
  180. navigationTitle = NCBrandOptions.shared.brand
  181. }
  182. self.setNavigationBar(navigationTitle: navigationTitle)
  183. }
  184. }
  185. let image = NCUtility.shared.loadUserImage(for: activeAccount.user, displayName: activeAccount.displayName, userBaseUrl: activeAccount)
  186. let profileButton = UIButton(type: .custom)
  187. profileButton.setImage(image, for: .normal)
  188. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) {
  189. var title = " "
  190. if let userAlias = activeAccount?.alias, !userAlias.isEmpty {
  191. title += userAlias
  192. } else {
  193. title += activeAccount?.displayName ?? ""
  194. }
  195. profileButton.setTitle(title, for: .normal)
  196. profileButton.setTitleColor(.systemBlue, for: .normal)
  197. }
  198. profileButton.semanticContentAttribute = .forceLeftToRight
  199. profileButton.sizeToFit()
  200. profileButton.action(for: .touchUpInside) { _ in
  201. if !self.uploadStarted {
  202. self.showAccountPicker()
  203. }
  204. }
  205. var navItems = [UIBarButtonItem(customView: profileButton)]
  206. if serverUrl != NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId) {
  207. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  208. space.width = 20
  209. navItems.append(contentsOf: [UIBarButtonItem(customView: backButton), space])
  210. }
  211. navigationItem.setLeftBarButtonItems(navItems, animated: true)
  212. }
  213. func setCommandView() {
  214. guard !filesName.isEmpty else {
  215. cancel(with: .noFiles)
  216. return
  217. }
  218. let counter = min(CGFloat(filesName.count), 3)
  219. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  220. if filesName.count <= 3 {
  221. self.tableView.isScrollEnabled = false
  222. }
  223. // Label upload button
  224. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  225. // Empty
  226. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: -50 * counter, delegate: self)
  227. self.tableView.reloadData()
  228. }
  229. // MARK: ACTION
  230. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  231. cancel(with: .cancel)
  232. }
  233. @objc func actionCreateFolder() {
  234. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, urlBase: activeAccount) { error in
  235. guard error != .success else { return }
  236. self.showAlert(title: "_error_createsubfolders_upload_", description: error.errorDescription)
  237. }
  238. self.present(alertController, animated: true)
  239. }
  240. }
  241. // MARK: - Upload
  242. extension NCShareExtension {
  243. @objc func actionUpload() {
  244. guard !uploadStarted else { return }
  245. guard !filesName.isEmpty else { return showAlert(description: "_files_no_files_") }
  246. counterUploaded = 0
  247. uploadStarted = true
  248. uploadErrors = []
  249. var conflicts: [tableMetadata] = []
  250. for fileName in filesName {
  251. let ocId = NSUUID().uuidString
  252. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  253. guard NCUtilityFileSystem.shared.copyFile(atPath: (NSTemporaryDirectory() + fileName), toPath: toPath) else { continue }
  254. let metadata = NCManageDatabase.shared.createMetadata(
  255. account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId,
  256. fileName: fileName, fileNameView: fileName,
  257. ocId: ocId,
  258. serverUrl: serverUrl, urlBase: activeAccount.urlBase, url: "",
  259. contentType: "")
  260. metadata.session = NextcloudKit.shared.nkCommonInstance.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, fileNameView: 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 DispatchQueue.main.async { self.finishedUploading() } }
  284. let metadata = uploadMetadata[counterUploaded]
  285. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  286. metadata.contentType = results.mimeType
  287. metadata.iconName = results.iconName
  288. metadata.classFile = results.classFile
  289. // CHUNK
  290. var chunkSize = NCGlobal.shared.chunkSizeMBCellular
  291. if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  292. chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
  293. }
  294. if metadata.size > chunkSize {
  295. metadata.chunk = chunkSize
  296. } else {
  297. metadata.chunk = 0
  298. }
  299. // E2EE
  300. metadata.e2eEncrypted = metadata.isDirectoryE2EE
  301. hud.textLabel.text = NSLocalizedString("_upload_file_", comment: "") + " \(counterUploaded + 1) " + NSLocalizedString("_of_", comment: "") + " \(filesName.count)"
  302. hud.show(in: self.view)
  303. NCNetworking.shared.upload(metadata: metadata, uploadE2EEDelegate: self) {
  304. self.hud.progress = 0
  305. } progressHandler: { _, _, fractionCompleted in
  306. self.hud.progress = Float(fractionCompleted)
  307. } completion: { error in
  308. if error != .success {
  309. let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  310. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  311. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  312. self.uploadErrors.append(metadata)
  313. }
  314. self.counterUploaded += 1
  315. self.upload()
  316. }
  317. }
  318. func finishedUploading() {
  319. uploadStarted = false
  320. if !uploadErrors.isEmpty {
  321. let fileList = "- " + uploadErrors.map({ $0.fileName }).joined(separator: "\n - ")
  322. showAlert(title: "_error_files_upload_", description: fileList) {
  323. self.extensionContext?.cancelRequest(withError: NCShareExtensionError.fileUpload)
  324. }
  325. } else {
  326. hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  327. hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  328. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  329. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  330. }
  331. }
  332. }
  333. }
  334. extension NCShareExtension: uploadE2EEDelegate {
  335. func start() {
  336. self.hud.progress = 0
  337. }
  338. func uploadE2EEProgress(_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) {
  339. self.hud.progress = Float(fractionCompleted)
  340. }
  341. }