NCShareExtension.swift 17 KB

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