NCShareExtension.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. //
  2. // NCShareExtension.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 20/04/2021.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import NCCommunication
  25. class NCShareExtension: UIViewController, NCListCellDelegate, NCEmptyDataSetDelegate, NCRenameFileDelegate, NCAccountRequestDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. @IBOutlet weak var tableView: UITableView!
  28. @IBOutlet weak var cancelButton: UIBarButtonItem!
  29. @IBOutlet weak var separatorView: UIView!
  30. @IBOutlet weak var commandView: UIView!
  31. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  32. @IBOutlet weak var commandViewHeightConstraint: NSLayoutConstraint!
  33. @IBOutlet weak var createFolderView: UIView!
  34. @IBOutlet weak var createFolderImage: UIImageView!
  35. @IBOutlet weak var createFolderLabel: UILabel!
  36. @IBOutlet weak var uploadView: UIView!
  37. @IBOutlet weak var uploadImage: UIImageView!
  38. @IBOutlet weak var uploadLabel: UILabel!
  39. // -------------------------------------------------------------
  40. var serverUrl = ""
  41. var filesName: [String] = []
  42. // -------------------------------------------------------------
  43. private var emptyDataSet: NCEmptyDataSet?
  44. private let keyLayout = NCGlobal.shared.layoutViewShareExtension
  45. private var metadataFolder: tableMetadata?
  46. private var networkInProgress = false
  47. private var dataSource = NCDataSource()
  48. private var layoutForView: NCGlobal.layoutForViewType?
  49. private var heightRowTableView: CGFloat = 50
  50. private var heightCommandView: CGFloat = 170
  51. private var autoUploadFileName = ""
  52. private var autoUploadDirectory = ""
  53. private let refreshControl = UIRefreshControl()
  54. private var activeAccount: tableAccount!
  55. private let chunckSize = CCUtility.getChunkSize() * 1000000
  56. // MARK: - View Life Cycle
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. self.navigationController?.navigationBar.prefersLargeTitles = false
  60. // Cell
  61. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  62. collectionView.collectionViewLayout = NCListLayout()
  63. // Add Refresh Control
  64. collectionView.addSubview(refreshControl)
  65. refreshControl.tintColor = NCBrandColor.shared.brandText
  66. refreshControl.backgroundColor = NCBrandColor.shared.systemBackground
  67. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  68. // Command view
  69. commandView.backgroundColor = NCBrandColor.shared.secondarySystemBackground
  70. separatorView.backgroundColor = NCBrandColor.shared.separator
  71. separatorHeightConstraint.constant = 0.5
  72. // Table view
  73. tableView.separatorColor = NCBrandColor.shared.separator
  74. tableView.layer.cornerRadius = 10
  75. tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
  76. commandViewHeightConstraint.constant = heightCommandView
  77. // Create folder
  78. createFolderView.layer.cornerRadius = 10
  79. createFolderImage.image = NCUtility.shared.loadImage(named: "folder.badge.plus", color: NCBrandColor.shared.label)
  80. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  81. let createFolderGesture = UITapGestureRecognizer(target: self, action: #selector(actionCreateFolder))
  82. createFolderView.addGestureRecognizer(createFolderGesture)
  83. // Upload
  84. uploadView.layer.cornerRadius = 10
  85. //uploadImage.image = NCUtility.shared.loadImage(named: "square.and.arrow.up", color: NCBrandColor.shared.label)
  86. uploadLabel.text = NSLocalizedString("_upload_", comment: "")
  87. uploadLabel.textColor = .systemBlue
  88. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(actionUpload))
  89. uploadView.addGestureRecognizer(uploadGesture)
  90. // LOG
  91. let levelLog = CCUtility.getLogLevel()
  92. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  93. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  94. NCCommunicationCommon.shared.levelLog = levelLog
  95. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  96. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  97. }
  98. if isSimulatorOrTestFlight {
  99. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  100. } else {
  101. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  102. }
  103. }
  104. override func viewWillAppear(_ animated: Bool) {
  105. super.viewWillAppear(animated)
  106. if serverUrl == "" {
  107. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  108. setAccount(account: activeAccount.account)
  109. getFilesExtensionContext { (filesName) in
  110. self.filesName = filesName
  111. DispatchQueue.main.async {
  112. var saveHtml: [String] = []
  113. var saveOther: [String] = []
  114. for fileName in self.filesName {
  115. if (fileName as NSString).pathExtension.lowercased() == "html" {
  116. saveHtml.append(fileName)
  117. } else {
  118. saveOther.append(fileName)
  119. }
  120. }
  121. if saveOther.count > 0 && saveHtml.count > 0 {
  122. for file in saveHtml {
  123. self.filesName = self.filesName.filter(){$0 != file}
  124. }
  125. }
  126. self.setCommandView()
  127. }
  128. }
  129. } else {
  130. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  131. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  132. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  133. }))
  134. self.present(alertController, animated: true)
  135. }
  136. }
  137. }
  138. override func viewDidDisappear(_ animated: Bool) {
  139. }
  140. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  141. super.viewWillTransition(to: size, with: coordinator)
  142. coordinator.animate(alongsideTransition: nil) { _ in
  143. self.collectionView?.collectionViewLayout.invalidateLayout()
  144. }
  145. }
  146. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  147. super.traitCollectionDidChange(previousTraitCollection)
  148. collectionView.reloadData()
  149. tableView.reloadData()
  150. }
  151. // MARK: -
  152. func setAccount(account: String) {
  153. guard let activeAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else {
  154. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  155. return
  156. }
  157. self.activeAccount = activeAccount
  158. // NETWORKING
  159. NCCommunicationCommon.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: CCUtility.getUserAgent(), webDav: NCUtilityFileSystem.shared.getWebDAV(account: activeAccount.account), nextcloudVersion: 0, delegate: NCNetworking.shared)
  160. // get auto upload folder
  161. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  162. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  163. serverUrl = NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account)
  164. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  165. reloadDatasource(withLoadFolder: true)
  166. setNavigationBar(navigationTitle: NCBrandOptions.shared.brand)
  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.addTarget(self, action: #selector(backButtonTapped(sender:)), for: .touchUpInside)
  179. // PROFILE BUTTON
  180. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  181. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + activeAccount.user + ".png"
  182. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  183. image = userImage
  184. }
  185. image = NCUtility.shared.createAvatar(image: image, size: 30)
  186. let profileButton = UIButton(type: .custom)
  187. profileButton.setImage(image, for: .normal)
  188. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  189. var title = " "
  190. if activeAccount?.alias == "" {
  191. title = title + (activeAccount?.user ?? "")
  192. } else {
  193. title = title + (activeAccount?.alias ?? "")
  194. }
  195. profileButton.setTitle(title, for: .normal)
  196. profileButton.setTitleColor(.systemBlue, for: .normal)
  197. }
  198. profileButton.semanticContentAttribute = .forceLeftToRight
  199. profileButton.sizeToFit()
  200. profileButton.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  201. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  202. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: profileButton)], animated: true)
  203. } else {
  204. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  205. space.width = 20
  206. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: backButton), space, UIBarButtonItem(customView: profileButton)], animated: true)
  207. }
  208. }
  209. func setCommandView() {
  210. var counter: CGFloat = 0
  211. if filesName.count == 0 {
  212. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  213. return
  214. } else {
  215. if filesName.count < 3 {
  216. counter = CGFloat(filesName.count)
  217. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  218. } else {
  219. counter = 3
  220. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  221. }
  222. if filesName.count <= 3 {
  223. self.tableView.isScrollEnabled = false
  224. }
  225. // Label upload button
  226. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  227. // Empty
  228. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50*counter, delegate: self)
  229. self.tableView.reloadData()
  230. }
  231. }
  232. // MARK: - Empty
  233. func emptyDataSetView(_ view: NCEmptyView) {
  234. if networkInProgress {
  235. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  236. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  237. view.emptyDescription.text = ""
  238. } else {
  239. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  240. view.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  241. view.emptyDescription.text = ""
  242. }
  243. }
  244. // MARK: ACTION
  245. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  246. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  247. }
  248. @objc func actionCreateFolder() {
  249. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  250. alertController.addTextField { (textField) in
  251. textField.autocapitalizationType = UITextAutocapitalizationType.words
  252. }
  253. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  254. if let fileName = alertController.textFields?.first?.text {
  255. self.createFolder(with: fileName)
  256. }
  257. }
  258. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  259. print("You've pressed cancel button")
  260. }
  261. alertController.addAction(actionSave)
  262. alertController.addAction(actionCancel)
  263. self.present(alertController, animated: true, completion:nil)
  264. }
  265. @objc func actionUpload() {
  266. if let fileName = filesName.first {
  267. filesName.removeFirst()
  268. let ocId = NSUUID().uuidString
  269. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  270. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: filePath) {
  271. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
  272. let metadata = NCManageDatabase.shared.createMetadata(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: activeAccount.urlBase, url: "", contentType: "", livePhoto: false)
  273. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  274. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  275. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  276. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  277. // E2EE
  278. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  279. metadata.e2eEncrypted = true
  280. }
  281. // CHUNCK
  282. if chunckSize != 0 && metadata.size > chunckSize {
  283. metadata.chunk = true
  284. }
  285. NCNetworking.shared.upload(metadata: metadata) {
  286. } completion: { (errorCode, errorDescription) in
  287. NCUtility.shared.stopActivityIndicator()
  288. if errorCode == 0 {
  289. self.actionUpload()
  290. } else {
  291. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  292. NCManageDatabase.shared.deleteChunks(account: self.activeAccount.account, ocId: ocId)
  293. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  294. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  295. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  296. return
  297. }))
  298. self.present(alertController, animated: true)
  299. }
  300. }
  301. }
  302. } else {
  303. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  304. return
  305. }
  306. }
  307. @objc func backButtonTapped(sender: Any) {
  308. while serverUrl.last != "/" {
  309. serverUrl.removeLast()
  310. }
  311. serverUrl.removeLast()
  312. reloadDatasource(withLoadFolder: true)
  313. var navigationTitle = (serverUrl as NSString).lastPathComponent
  314. if NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) == serverUrl {
  315. navigationTitle = NCBrandOptions.shared.brand
  316. }
  317. setNavigationBar(navigationTitle: navigationTitle)
  318. }
  319. func rename(fileName: String, fileNameNew: String) {
  320. if let row = self.filesName.firstIndex(where: {$0 == fileName}) {
  321. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: (NSTemporaryDirectory() + fileNameNew)) {
  322. filesName[row] = fileNameNew
  323. tableView.reloadData()
  324. }
  325. }
  326. }
  327. @objc func moreButtonPressed(sender: NCShareExtensionButtonWithIndexPath) {
  328. if let fileName = sender.fileName {
  329. let alertController = UIAlertController(title: "", message: fileName, preferredStyle: .alert)
  330. alertController.addAction(UIAlertAction(title: NSLocalizedString("_delete_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  331. if let index = self.filesName.firstIndex(of: fileName) {
  332. self.filesName.remove(at: index)
  333. if self.filesName.count == 0 {
  334. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  335. } else {
  336. self.setCommandView()
  337. }
  338. }
  339. })
  340. alertController.addAction(UIAlertAction(title: NSLocalizedString("_rename_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  341. if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
  342. vcRename.delegate = self
  343. vcRename.fileName = fileName
  344. vcRename.imagePreview = sender.image
  345. let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
  346. self.present(popup, animated: true)
  347. }
  348. })
  349. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in })
  350. self.present(alertController, animated: true, completion:nil)
  351. }
  352. }
  353. func accountRequestChangeAccount(account: String) {
  354. setAccount(account: account)
  355. }
  356. @objc func profileButtonTapped(sender: Any) {
  357. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  358. if accounts.count > 1 {
  359. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  360. // Only here change the active account
  361. for account in accounts {
  362. if account.account == self.activeAccount.account {
  363. account.active = true
  364. } else {
  365. account.active = false
  366. }
  367. }
  368. vcAccountRequest.activeAccount = self.activeAccount
  369. vcAccountRequest.accounts = accounts.sorted { (sorg, dest) -> Bool in
  370. return sorg.active && !dest.active
  371. }
  372. vcAccountRequest.enableTimerProgress = false
  373. vcAccountRequest.enableAddAccount = false
  374. vcAccountRequest.delegate = self
  375. vcAccountRequest.dismissDidEnterBackground = true
  376. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  377. let numberCell = accounts.count
  378. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  379. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height+20)
  380. self.present(popup, animated: true)
  381. }
  382. }
  383. }
  384. }
  385. // MARK: - Collection View
  386. extension NCShareExtension: UICollectionViewDelegate {
  387. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  388. if let metadata = dataSource.cellForItemAt(indexPath: indexPath) {
  389. if let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) {
  390. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: activeAccount.account) {
  391. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: NSLocalizedString("_e2e_goto_settings_for_enable_", comment: ""), preferredStyle: .alert)
  392. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  393. self.present(alertController, animated: true)
  394. return
  395. }
  396. self.serverUrl = serverUrl
  397. reloadDatasource(withLoadFolder: true)
  398. setNavigationBar(navigationTitle: metadata.fileNameView)
  399. }
  400. }
  401. }
  402. }
  403. extension NCShareExtension: UICollectionViewDataSource {
  404. func numberOfSections(in collectionView: UICollectionView) -> Int {
  405. return 1
  406. }
  407. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  408. let numberOfItems = dataSource.numberOfItems()
  409. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  410. return numberOfItems
  411. }
  412. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  413. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  414. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  415. }
  416. var tableShare: tableShare?
  417. var isShare = false
  418. var isMounted = false
  419. if let metadataFolder = metadataFolder {
  420. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  421. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  422. }
  423. if dataSource.metadataShare[metadata.ocId] != nil {
  424. tableShare = dataSource.metadataShare[metadata.ocId]
  425. }
  426. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  427. cell.delegate = self
  428. cell.objectId = metadata.ocId
  429. cell.labelTitle.text = metadata.fileNameView
  430. cell.labelTitle.textColor = NCBrandColor.shared.label
  431. cell.imageSelect.image = nil
  432. cell.imageStatus.image = nil
  433. cell.imageLocal.image = nil
  434. cell.imageFavorite.image = nil
  435. cell.imageShared.image = nil
  436. cell.imageMore.image = nil
  437. cell.imageItem.image = nil
  438. cell.imageItem.backgroundColor = nil
  439. cell.progressView.progress = 0.0
  440. if metadata.directory {
  441. if metadata.e2eEncrypted {
  442. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  443. } else if isShare {
  444. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  445. } else if (tableShare != nil && tableShare?.shareType != 3) {
  446. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  447. } else if (tableShare != nil && tableShare?.shareType == 3) {
  448. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  449. } else if metadata.mountType == "group" {
  450. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  451. } else if isMounted {
  452. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  453. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  454. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  455. } else {
  456. cell.imageItem.image = NCBrandColor.cacheImages.folder
  457. }
  458. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  459. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  460. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  461. // Local image: offline
  462. if tableDirectory != nil && tableDirectory!.offline {
  463. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  464. }
  465. }
  466. // image Favorite
  467. if metadata.favorite {
  468. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  469. }
  470. // Share image
  471. if (isShare) {
  472. cell.imageShared.image = NCBrandColor.cacheImages.shared
  473. } else if (tableShare != nil && tableShare?.shareType == 3) {
  474. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  475. } else if (tableShare != nil && tableShare?.shareType != 3) {
  476. cell.imageShared.image = NCBrandColor.cacheImages.shared
  477. } else {
  478. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  479. }
  480. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  481. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  482. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, fileNameLocalPath: fileNameLocalPath, placeholder: nil, cell: cell, view: collectionView, indexPath: indexPath)
  483. }
  484. cell.imageSelect.isHidden = true
  485. cell.backgroundView = nil
  486. cell.hideButtonMore(true)
  487. cell.hideButtonShare(true)
  488. cell.selectMode(false)
  489. // Live Photo
  490. if metadata.livePhoto {
  491. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  492. }
  493. // Remove last separator
  494. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  495. cell.separator.isHidden = true
  496. } else {
  497. cell.separator.isHidden = false
  498. }
  499. return cell
  500. }
  501. }
  502. // MARK: - Table View
  503. extension NCShareExtension: UITableViewDelegate {
  504. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  505. return heightRowTableView
  506. }
  507. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  508. }
  509. }
  510. extension NCShareExtension: UITableViewDataSource {
  511. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  512. filesName.count
  513. }
  514. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  515. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  516. cell.backgroundColor = NCBrandColor.shared.systemBackground
  517. let imageCell = cell.viewWithTag(10) as? UIImageView
  518. let fileNameCell = cell.viewWithTag(20) as? UILabel
  519. let moreButton = cell.viewWithTag(30) as? NCShareExtensionButtonWithIndexPath
  520. let sizeCell = cell.viewWithTag(40) as? UILabel
  521. imageCell?.layer.cornerRadius = 6
  522. imageCell?.layer.masksToBounds = true
  523. let fileName = filesName[indexPath.row]
  524. let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: "", directory: false)
  525. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  526. imageCell?.image = image.resizeImage(size: CGSize(width: 80, height: 80), isAspectRation: true)
  527. } else {
  528. if resultInternalType.iconName.count > 0 {
  529. imageCell?.image = UIImage.init(named: resultInternalType.iconName)
  530. } else {
  531. imageCell?.image = NCBrandColor.cacheImages.file
  532. }
  533. }
  534. fileNameCell?.text = fileName
  535. let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: (NSTemporaryDirectory() + fileName))
  536. sizeCell?.text = CCUtility.transformedSize(fileSize)
  537. moreButton?.setImage(NCUtility.shared.loadImage(named: "more").image(color: NCBrandColor.shared.label, size: 15), for: .normal)
  538. moreButton?.indexPath = indexPath
  539. moreButton?.fileName = fileName
  540. moreButton?.image = imageCell?.image
  541. moreButton?.addTarget(self, action:#selector(moreButtonPressed(sender:)), for: .touchUpInside)
  542. return cell
  543. }
  544. }
  545. // MARK: - NC API & Algorithm
  546. extension NCShareExtension {
  547. @objc func reloadDatasource(withLoadFolder: Bool) {
  548. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  549. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  550. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: layoutForView?.sort, ascending: layoutForView?.ascending, directoryOnTop: layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  551. if withLoadFolder {
  552. loadFolder()
  553. } else {
  554. self.refreshControl.endRefreshing()
  555. }
  556. collectionView.reloadData()
  557. }
  558. func createFolder(with fileName: String) {
  559. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  560. if errorCode == 0 {
  561. self.reloadDatasource(withLoadFolder: true)
  562. } else {
  563. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  564. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  565. self.present(alertController, animated: true)
  566. }
  567. }
  568. }
  569. func loadFolder() {
  570. networkInProgress = true
  571. collectionView.reloadData()
  572. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, _, errorCode, errorDescription) in
  573. if errorCode != 0 {
  574. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  575. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  576. self.present(alertController, animated: true)
  577. }
  578. self.networkInProgress = false
  579. self.metadataFolder = metadataFolder
  580. self.reloadDatasource(withLoadFolder: false)
  581. }
  582. }
  583. func getFilesExtensionContext(completion: @escaping (_ filesName: [String])->()) {
  584. var itemsProvider: [NSItemProvider] = []
  585. var filesName: [String] = []
  586. var conuter = 0
  587. let dateFormatter = DateFormatter()
  588. // ----------------------------------------------------------------------------------------
  589. // Image
  590. func getItem(image: UIImage, fileNameOriginal: String?) {
  591. var fileName: String = ""
  592. if let pngImageData = image.pngData() {
  593. if fileNameOriginal != nil {
  594. fileName = fileNameOriginal!
  595. } else {
  596. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  597. }
  598. let filenamePath = NSTemporaryDirectory() + fileName
  599. if (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil {
  600. filesName.append(fileName)
  601. }
  602. }
  603. }
  604. // URL
  605. func getItem(url: NSURL, fileNameOriginal: String?) {
  606. guard let path = url.path else { return }
  607. var fileName: String = ""
  608. if fileNameOriginal != nil {
  609. fileName = fileNameOriginal!
  610. } else {
  611. if let ext = url.pathExtension {
  612. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  613. }
  614. }
  615. let filenamePath = NSTemporaryDirectory() + fileName
  616. do {
  617. try FileManager.default.removeItem(atPath: filenamePath)
  618. }
  619. catch { }
  620. do {
  621. try FileManager.default.copyItem(atPath: path, toPath:filenamePath)
  622. do {
  623. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  624. if let _attr = attr {
  625. if _attr.fileSize() > 0 {
  626. filesName.append(fileName)
  627. }
  628. }
  629. } catch { }
  630. } catch { }
  631. }
  632. // Data
  633. func getItem(data: Data, fileNameOriginal: String?, description: String) {
  634. var fileName: String = ""
  635. if data.count > 0 {
  636. if fileNameOriginal != nil {
  637. fileName = fileNameOriginal!
  638. } else {
  639. let fullNameArr = description.components(separatedBy: "\"")
  640. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  641. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  642. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  643. }
  644. let filenamePath = NSTemporaryDirectory() + fileName
  645. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  646. filesName.append(fileName)
  647. }
  648. }
  649. // String
  650. func getItem(string: NSString, fileNameOriginal: String?) {
  651. var fileName: String = ""
  652. if string.length > 0 {
  653. fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  654. let filenamePath = NSTemporaryDirectory() + "\(dateFormatter.string(from: Date()))\(conuter).txt"
  655. FileManager.default.createFile(atPath: filenamePath, contents:string.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  656. filesName.append(fileName)
  657. }
  658. }
  659. // ----------------------------------------------------------------------------------------
  660. guard let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] else {
  661. return completion(filesName)
  662. }
  663. for item : NSExtensionItem in inputItems {
  664. if let attachments = item.attachments {
  665. if attachments.isEmpty { continue }
  666. for (_, itemProvider) in (attachments.enumerated()) {
  667. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || itemProvider.hasItemConformingToTypeIdentifier("public.url") {
  668. itemsProvider.append(itemProvider)
  669. }
  670. }
  671. }
  672. }
  673. CCUtility.emptyTemporaryDirectory()
  674. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  675. for itemProvider in itemsProvider {
  676. var typeIdentifier = ""
  677. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  678. if itemProvider.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  679. itemProvider.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  680. if error == nil {
  681. var fileNameOriginal: String?
  682. if let url = item as? NSURL {
  683. if FileManager.default.fileExists(atPath: url.path ?? "") {
  684. fileNameOriginal = url.lastPathComponent!
  685. } else if url.scheme?.lowercased().contains("http") == true {
  686. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter).html"
  687. } else {
  688. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter)"
  689. }
  690. }
  691. if let image = item as? UIImage {
  692. getItem(image: image, fileNameOriginal: fileNameOriginal)
  693. }
  694. if let url = item as? URL {
  695. getItem(url: url as NSURL, fileNameOriginal: fileNameOriginal)
  696. }
  697. if let data = item as? Data {
  698. getItem(data: data, fileNameOriginal: fileNameOriginal, description: itemProvider.description)
  699. }
  700. if let string = item as? NSString {
  701. getItem(string: string, fileNameOriginal: fileNameOriginal)
  702. }
  703. }
  704. conuter += 1
  705. if conuter == itemsProvider.count {
  706. completion(filesName)
  707. }
  708. })
  709. }
  710. }
  711. }
  712. /*
  713. let task = URLSession.shared.downloadTask(with: urlitem) { localURL, urlResponse, error in
  714. if let localURL = localURL {
  715. if fileNameOriginal != nil {
  716. fileName = fileNameOriginal!
  717. } else {
  718. let ext = url.pathExtension
  719. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  720. }
  721. let filenamePath = NSTemporaryDirectory() + fileName
  722. do {
  723. try FileManager.default.removeItem(atPath: filenamePath)
  724. }
  725. catch { }
  726. do {
  727. try FileManager.default.copyItem(atPath: localURL.path, toPath:filenamePath)
  728. do {
  729. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  730. if let _attr = attr {
  731. if _attr.fileSize() > 0 {
  732. filesName.append(fileName)
  733. }
  734. }
  735. } catch let error {
  736. outError = error
  737. }
  738. } catch let error {
  739. outError = error
  740. }
  741. }
  742. if index + 1 == attachments.count {
  743. completion(filesName, outError)
  744. }
  745. }
  746. task.resume()
  747. */
  748. class NCShareExtensionButtonWithIndexPath: UIButton {
  749. var indexPath:IndexPath?
  750. var fileName: String?
  751. var image: UIImage?
  752. }