NCShareExtension.swift 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. // Create folder
  77. createFolderView.layer.cornerRadius = 10
  78. createFolderImage.image = NCUtility.shared.loadImage(named: "folder.badge.plus", color: NCBrandColor.shared.label)
  79. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  80. let createFolderGesture = UITapGestureRecognizer(target: self, action: #selector(actionCreateFolder))
  81. createFolderView.addGestureRecognizer(createFolderGesture)
  82. // Upload
  83. uploadView.layer.cornerRadius = 10
  84. //uploadImage.image = NCUtility.shared.loadImage(named: "square.and.arrow.up", color: NCBrandColor.shared.label)
  85. uploadLabel.text = NSLocalizedString("_upload_", comment: "")
  86. uploadLabel.textColor = .systemBlue
  87. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(actionUpload))
  88. uploadView.addGestureRecognizer(uploadGesture)
  89. // LOG
  90. let levelLog = CCUtility.getLogLevel()
  91. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  92. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  93. NCCommunicationCommon.shared.levelLog = levelLog
  94. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  95. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  96. }
  97. if isSimulatorOrTestFlight {
  98. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  99. } else {
  100. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  101. }
  102. }
  103. override func viewWillAppear(_ animated: Bool) {
  104. super.viewWillAppear(animated)
  105. if serverUrl == "" {
  106. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  107. setAccount(account: activeAccount.account)
  108. getFilesExtensionContext { (filesName, error) in
  109. self.filesName = filesName
  110. DispatchQueue.main.async {
  111. var saveHtml: [String] = []
  112. var saveOther: [String] = []
  113. for fileName in self.filesName {
  114. if (fileName as NSString).pathExtension.lowercased() == "html" {
  115. saveHtml.append(fileName)
  116. } else {
  117. saveOther.append(fileName)
  118. }
  119. }
  120. if saveOther.count > 0 && saveHtml.count > 0 {
  121. for file in saveHtml {
  122. self.filesName = self.filesName.filter(){$0 != file}
  123. }
  124. }
  125. self.setCommandView()
  126. }
  127. }
  128. } else {
  129. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_no_active_account_", comment: ""), preferredStyle: .alert)
  130. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  131. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  132. }))
  133. self.present(alertController, animated: true)
  134. }
  135. }
  136. }
  137. override func viewDidDisappear(_ animated: Bool) {
  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 setAccount(account: String) {
  152. guard let activeAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else {
  153. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  154. return
  155. }
  156. self.activeAccount = activeAccount
  157. // NETWORKING
  158. 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), dav: NCUtilityFileSystem.shared.getDAV(), nextcloudVersion: 0, delegate: NCNetworking.shared)
  159. // get auto upload folder
  160. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  161. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  162. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account)
  163. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  164. reloadDatasource(withLoadFolder: true)
  165. setNavigationBar(navigationTitle: NCBrandOptions.shared.brand)
  166. }
  167. func setNavigationBar(navigationTitle: String) {
  168. navigationItem.title = navigationTitle
  169. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  170. // BACK BUTTON
  171. let backButton = UIButton(type: .custom)
  172. backButton.setImage(UIImage(named: "back"), for: .normal)
  173. backButton.tintColor = .systemBlue
  174. backButton.semanticContentAttribute = .forceLeftToRight
  175. backButton.setTitle(" "+NSLocalizedString("_back_", comment: ""), for: .normal)
  176. backButton.setTitleColor(.systemBlue, for: .normal)
  177. backButton.addTarget(self, action: #selector(backButtonTapped(sender:)), for: .touchUpInside)
  178. // PROFILE BUTTON
  179. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  180. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + activeAccount.user + ".png"
  181. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  182. image = userImage
  183. }
  184. image = NCUtility.shared.createAvatar(image: image, size: 30)
  185. let profileButton = UIButton(type: .custom)
  186. profileButton.setImage(image, for: .normal)
  187. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  188. var title = " "
  189. if activeAccount?.alias == "" {
  190. title = title + (activeAccount?.user ?? "")
  191. } else {
  192. title = title + (activeAccount?.alias ?? "")
  193. }
  194. profileButton.setTitle(title, for: .normal)
  195. profileButton.setTitleColor(.systemBlue, for: .normal)
  196. }
  197. profileButton.semanticContentAttribute = .forceLeftToRight
  198. profileButton.sizeToFit()
  199. profileButton.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  200. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  201. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: profileButton)], animated: true)
  202. } else {
  203. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  204. space.width = 20
  205. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: backButton), space, UIBarButtonItem(customView: profileButton)], animated: true)
  206. }
  207. }
  208. func setCommandView() {
  209. var counter: CGFloat = 0
  210. if filesName.count == 0 {
  211. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  212. return
  213. } else {
  214. if filesName.count < 3 {
  215. counter = CGFloat(filesName.count)
  216. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  217. } else {
  218. counter = 3
  219. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  220. }
  221. if filesName.count <= 3 {
  222. self.tableView.isScrollEnabled = false
  223. }
  224. // Empty
  225. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50*counter, delegate: self)
  226. self.tableView.reloadData()
  227. }
  228. }
  229. // MARK: - Empty
  230. func emptyDataSetView(_ view: NCEmptyView) {
  231. if networkInProgress {
  232. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  233. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  234. view.emptyDescription.text = ""
  235. } else {
  236. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  237. view.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  238. view.emptyDescription.text = ""
  239. }
  240. }
  241. // MARK: ACTION
  242. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  243. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  244. }
  245. @objc func actionCreateFolder() {
  246. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  247. alertController.addTextField { (textField) in
  248. textField.autocapitalizationType = UITextAutocapitalizationType.words
  249. }
  250. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  251. if let fileName = alertController.textFields?.first?.text {
  252. self.createFolder(with: fileName)
  253. }
  254. }
  255. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  256. print("You've pressed cancel button")
  257. }
  258. alertController.addAction(actionSave)
  259. alertController.addAction(actionCancel)
  260. self.present(alertController, animated: true, completion:nil)
  261. }
  262. @objc func actionUpload() {
  263. if let fileName = filesName.first {
  264. filesName.removeFirst()
  265. let ocId = NSUUID().uuidString
  266. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  267. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: filePath) {
  268. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
  269. let metadata = NCManageDatabase.shared.createMetadata(account: activeAccount.account, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: activeAccount.urlBase, url: "", contentType: "", livePhoto: false)
  270. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  271. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  272. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  273. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  274. // E2EE
  275. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  276. metadata.e2eEncrypted = true
  277. }
  278. // CHUNCK
  279. if chunckSize != 0 && metadata.size > chunckSize {
  280. metadata.chunk = true
  281. }
  282. NCNetworking.shared.upload(metadata: metadata) {
  283. } completion: { (errorCode, errorDescription) in
  284. NCUtility.shared.stopActivityIndicator()
  285. if errorCode == 0 {
  286. self.actionUpload()
  287. } else {
  288. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  289. NCManageDatabase.shared.deleteChunks(account: self.activeAccount.account, ocId: ocId)
  290. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  291. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  292. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  293. return
  294. }))
  295. self.present(alertController, animated: true)
  296. }
  297. }
  298. }
  299. } else {
  300. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  301. return
  302. }
  303. }
  304. @objc func backButtonTapped(sender: Any) {
  305. while serverUrl.last != "/" {
  306. serverUrl.removeLast()
  307. }
  308. serverUrl.removeLast()
  309. reloadDatasource(withLoadFolder: true)
  310. var navigationTitle = (serverUrl as NSString).lastPathComponent
  311. if NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) == serverUrl {
  312. navigationTitle = NCBrandOptions.shared.brand
  313. }
  314. setNavigationBar(navigationTitle: navigationTitle)
  315. }
  316. func rename(fileName: String, fileNameNew: String) {
  317. if let row = self.filesName.firstIndex(where: {$0 == fileName}) {
  318. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: (NSTemporaryDirectory() + fileNameNew)) {
  319. filesName[row] = fileNameNew
  320. tableView.reloadData()
  321. }
  322. }
  323. }
  324. @objc func moreButtonPressed(sender: NCShareExtensionButtonWithIndexPath) {
  325. if let fileName = sender.fileName {
  326. let alertController = UIAlertController(title: "", message: fileName, preferredStyle: .alert)
  327. alertController.addAction(UIAlertAction(title: NSLocalizedString("_delete_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  328. if let index = self.filesName.firstIndex(of: fileName) {
  329. self.filesName.remove(at: index)
  330. if self.filesName.count == 0 {
  331. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  332. } else {
  333. self.setCommandView()
  334. }
  335. }
  336. })
  337. alertController.addAction(UIAlertAction(title: NSLocalizedString("_rename_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  338. if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
  339. vcRename.delegate = self
  340. vcRename.fileName = fileName
  341. vcRename.imagePreview = sender.image
  342. let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
  343. self.present(popup, animated: true)
  344. }
  345. })
  346. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in })
  347. self.present(alertController, animated: true, completion:nil)
  348. }
  349. }
  350. func accountRequestChangeAccount(account: String) {
  351. setAccount(account: account)
  352. }
  353. @objc func profileButtonTapped(sender: Any) {
  354. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  355. if accounts.count > 1 {
  356. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  357. // Only here change the active account
  358. for account in accounts {
  359. if account.account == self.activeAccount.account {
  360. account.active = true
  361. } else {
  362. account.active = false
  363. }
  364. }
  365. vcAccountRequest.activeAccount = self.activeAccount
  366. vcAccountRequest.accounts = accounts.sorted { (sorg, dest) -> Bool in
  367. return sorg.active && !dest.active
  368. }
  369. vcAccountRequest.enableTimerProgress = false
  370. vcAccountRequest.enableAddAccount = false
  371. vcAccountRequest.delegate = self
  372. vcAccountRequest.dismissDidEnterBackground = true
  373. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  374. let numberCell = accounts.count
  375. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  376. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height+20)
  377. self.present(popup, animated: true)
  378. }
  379. }
  380. }
  381. }
  382. // MARK: - Collection View
  383. extension NCShareExtension: UICollectionViewDelegate {
  384. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  385. if let metadata = dataSource.cellForItemAt(indexPath: indexPath) {
  386. if let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) {
  387. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: activeAccount.account) {
  388. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: NSLocalizedString("_e2e_goto_settings_for_enable_", comment: ""), preferredStyle: .alert)
  389. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  390. self.present(alertController, animated: true)
  391. return
  392. }
  393. self.serverUrl = serverUrl
  394. reloadDatasource(withLoadFolder: true)
  395. setNavigationBar(navigationTitle: metadata.fileNameView)
  396. }
  397. }
  398. }
  399. }
  400. extension NCShareExtension: UICollectionViewDataSource {
  401. func numberOfSections(in collectionView: UICollectionView) -> Int {
  402. return 1
  403. }
  404. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  405. let numberOfItems = dataSource.numberOfItems()
  406. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  407. return numberOfItems
  408. }
  409. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  410. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  411. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  412. }
  413. var tableShare: tableShare?
  414. var isShare = false
  415. var isMounted = false
  416. // Download preview
  417. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  418. if let metadataFolder = metadataFolder {
  419. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  420. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  421. }
  422. if dataSource.metadataShare[metadata.ocId] != nil {
  423. tableShare = dataSource.metadataShare[metadata.ocId]
  424. }
  425. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  426. cell.delegate = self
  427. cell.objectId = metadata.ocId
  428. cell.indexPath = indexPath
  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 fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  482. if FileManager.default.fileExists(atPath: fileNameUser) {
  483. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  484. } else {
  485. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  486. if errorCode == 0 && account == self.activeAccount.account {
  487. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  488. }
  489. }
  490. }
  491. }
  492. cell.imageSelect.isHidden = true
  493. cell.backgroundView = nil
  494. cell.hideButtonMore(true)
  495. cell.hideButtonShare(true)
  496. cell.selectMode(false)
  497. // Live Photo
  498. if metadata.livePhoto {
  499. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  500. }
  501. // Remove last separator
  502. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  503. cell.separator.isHidden = true
  504. } else {
  505. cell.separator.isHidden = false
  506. }
  507. return cell
  508. }
  509. }
  510. // MARK: - Table View
  511. extension NCShareExtension: UITableViewDelegate {
  512. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  513. return heightRowTableView
  514. }
  515. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  516. }
  517. }
  518. extension NCShareExtension: UITableViewDataSource {
  519. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  520. filesName.count
  521. }
  522. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  523. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  524. cell.backgroundColor = NCBrandColor.shared.systemBackground
  525. let imageCell = cell.viewWithTag(10) as? UIImageView
  526. let fileNameCell = cell.viewWithTag(20) as? UILabel
  527. let moreButton = cell.viewWithTag(30) as? NCShareExtensionButtonWithIndexPath
  528. let sizeCell = cell.viewWithTag(40) as? UILabel
  529. imageCell?.layer.cornerRadius = 6
  530. imageCell?.layer.masksToBounds = true
  531. let fileName = filesName[indexPath.row]
  532. let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: "", directory: false)
  533. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  534. imageCell?.image = image
  535. } else {
  536. if resultInternalType.iconName.count > 0 {
  537. imageCell?.image = UIImage.init(named: resultInternalType.iconName)
  538. } else {
  539. imageCell?.image = NCBrandColor.cacheImages.file
  540. }
  541. }
  542. fileNameCell?.text = fileName
  543. let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: (NSTemporaryDirectory() + fileName))
  544. sizeCell?.text = CCUtility.transformedSize(fileSize)
  545. moreButton?.setImage(NCUtility.shared.loadImage(named: "more").image(color: NCBrandColor.shared.label, size: 15), for: .normal)
  546. moreButton?.indexPath = indexPath
  547. moreButton?.fileName = fileName
  548. moreButton?.image = imageCell?.image
  549. moreButton?.addTarget(self, action:#selector(moreButtonPressed(sender:)), for: .touchUpInside)
  550. return cell
  551. }
  552. }
  553. // MARK: - NC API & Algorithm
  554. extension NCShareExtension {
  555. @objc func reloadDatasource(withLoadFolder: Bool) {
  556. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  557. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  558. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: layoutForView?.sort, ascending: layoutForView?.ascending, directoryOnTop: layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  559. if withLoadFolder {
  560. loadFolder()
  561. } else {
  562. self.refreshControl.endRefreshing()
  563. }
  564. collectionView.reloadData()
  565. }
  566. func createFolder(with fileName: String) {
  567. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  568. if errorCode == 0 {
  569. self.reloadDatasource(withLoadFolder: true)
  570. } else {
  571. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  572. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  573. self.present(alertController, animated: true)
  574. }
  575. }
  576. }
  577. func loadFolder() {
  578. networkInProgress = true
  579. collectionView.reloadData()
  580. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, _, errorCode, errorDescription) in
  581. if errorCode != 0 {
  582. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  583. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  584. self.present(alertController, animated: true)
  585. }
  586. self.networkInProgress = false
  587. self.metadataFolder = metadataFolder
  588. self.reloadDatasource(withLoadFolder: false)
  589. }
  590. }
  591. func getFilesExtensionContext(completion: @escaping (_ filesName: [String], _ error: Error?)->()) {
  592. var filesName: [String] = []
  593. var conuter = 0
  594. var outError: Error? = nil
  595. CCUtility.emptyTemporaryDirectory()
  596. if let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] {
  597. for item : NSExtensionItem in inputItems {
  598. if let attachments = item.attachments {
  599. if attachments.isEmpty {
  600. extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  601. completion(filesName, outError)
  602. return
  603. }
  604. for (index, current) in (attachments.enumerated()) {
  605. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || current.hasItemConformingToTypeIdentifier("public.url") {
  606. var typeIdentifier = ""
  607. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  608. if current.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  609. current.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  610. var fileNameOriginal: String?
  611. var fileName: String = ""
  612. let dateFormatter = DateFormatter()
  613. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  614. conuter += 1
  615. if let url = item as? NSURL {
  616. if FileManager.default.fileExists(atPath: url.path ?? "") {
  617. fileNameOriginal = url.lastPathComponent!
  618. } else if url.scheme?.lowercased().contains("http") == true {
  619. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter).html"
  620. } else {
  621. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter)"
  622. }
  623. }
  624. if error == nil {
  625. if let image = item as? UIImage {
  626. print("item as UIImage")
  627. if let pngImageData = image.pngData() {
  628. if fileNameOriginal != nil {
  629. fileName = fileNameOriginal!
  630. } else {
  631. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  632. }
  633. let filenamePath = NSTemporaryDirectory() + fileName
  634. let result = (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil
  635. if result {
  636. filesName.append(fileName)
  637. }
  638. } else {
  639. print("Error image nil")
  640. }
  641. if index + 1 == attachments.count {
  642. completion(filesName, outError)
  643. }
  644. }
  645. if let url = item as? URL {
  646. let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
  647. if let localURL = localURL {
  648. if fileNameOriginal != nil {
  649. fileName = fileNameOriginal!
  650. } else {
  651. let ext = url.pathExtension
  652. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  653. }
  654. let filenamePath = NSTemporaryDirectory() + fileName
  655. do {
  656. try FileManager.default.removeItem(atPath: filenamePath)
  657. }
  658. catch { }
  659. do {
  660. try FileManager.default.copyItem(atPath: localURL.path, toPath:filenamePath)
  661. do {
  662. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  663. if let _attr = attr {
  664. if _attr.fileSize() > 0 {
  665. filesName.append(fileName)
  666. }
  667. }
  668. } catch let error {
  669. outError = error
  670. }
  671. } catch let error {
  672. outError = error
  673. }
  674. }
  675. if index + 1 == attachments.count {
  676. completion(filesName, outError)
  677. }
  678. }
  679. task.resume()
  680. }
  681. if let data = item as? Data {
  682. if data.count > 0 {
  683. print("item as NSdata")
  684. if fileNameOriginal != nil {
  685. fileName = fileNameOriginal!
  686. } else {
  687. let description = current.description
  688. let fullNameArr = description.components(separatedBy: "\"")
  689. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  690. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  691. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  692. }
  693. let filenamePath = NSTemporaryDirectory() + fileName
  694. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  695. filesName.append(fileName)
  696. }
  697. if index + 1 == attachments.count {
  698. completion(filesName, outError)
  699. }
  700. }
  701. if let data = item as? NSString {
  702. if data.length > 0 {
  703. print("item as NSString")
  704. let fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  705. let filenamePath = NSTemporaryDirectory() + fileName
  706. FileManager.default.createFile(atPath: filenamePath, contents:data.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  707. filesName.append(fileName)
  708. }
  709. if index + 1 == attachments.count {
  710. completion(filesName, outError)
  711. }
  712. }
  713. } else {
  714. completion( filesName, error)
  715. }
  716. })
  717. }
  718. } // end for
  719. } else {
  720. completion(filesName, outError)
  721. }
  722. }
  723. } else {
  724. completion(filesName, outError)
  725. }
  726. }
  727. }
  728. class NCShareExtensionButtonWithIndexPath: UIButton {
  729. var indexPath:IndexPath?
  730. var fileName: String?
  731. var image: UIImage?
  732. }