NCShareExtension.swift 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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, 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. // Download preview
  420. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  421. if let metadataFolder = metadataFolder {
  422. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  423. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  424. }
  425. if dataSource.metadataShare[metadata.ocId] != nil {
  426. tableShare = dataSource.metadataShare[metadata.ocId]
  427. }
  428. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  429. cell.delegate = self
  430. cell.objectId = metadata.ocId
  431. cell.indexPath = indexPath
  432. cell.labelTitle.text = metadata.fileNameView
  433. cell.labelTitle.textColor = NCBrandColor.shared.label
  434. cell.imageSelect.image = nil
  435. cell.imageStatus.image = nil
  436. cell.imageLocal.image = nil
  437. cell.imageFavorite.image = nil
  438. cell.imageShared.image = nil
  439. cell.imageMore.image = nil
  440. cell.imageItem.image = nil
  441. cell.imageItem.backgroundColor = nil
  442. cell.progressView.progress = 0.0
  443. if metadata.directory {
  444. if metadata.e2eEncrypted {
  445. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  446. } else if isShare {
  447. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  448. } else if (tableShare != nil && tableShare?.shareType != 3) {
  449. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  450. } else if (tableShare != nil && tableShare?.shareType == 3) {
  451. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  452. } else if metadata.mountType == "group" {
  453. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  454. } else if isMounted {
  455. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  456. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  457. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  458. } else {
  459. cell.imageItem.image = NCBrandColor.cacheImages.folder
  460. }
  461. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  462. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  463. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  464. // Local image: offline
  465. if tableDirectory != nil && tableDirectory!.offline {
  466. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  467. }
  468. }
  469. // image Favorite
  470. if metadata.favorite {
  471. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  472. }
  473. // Share image
  474. if (isShare) {
  475. cell.imageShared.image = NCBrandColor.cacheImages.shared
  476. } else if (tableShare != nil && tableShare?.shareType == 3) {
  477. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  478. } else if (tableShare != nil && tableShare?.shareType != 3) {
  479. cell.imageShared.image = NCBrandColor.cacheImages.shared
  480. } else {
  481. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  482. }
  483. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  484. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  485. if FileManager.default.fileExists(atPath: fileNameUser) {
  486. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  487. } else {
  488. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  489. if errorCode == 0 && account == self.activeAccount.account {
  490. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  491. }
  492. }
  493. }
  494. }
  495. cell.imageSelect.isHidden = true
  496. cell.backgroundView = nil
  497. cell.hideButtonMore(true)
  498. cell.hideButtonShare(true)
  499. cell.selectMode(false)
  500. // Live Photo
  501. if metadata.livePhoto {
  502. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  503. }
  504. // Remove last separator
  505. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  506. cell.separator.isHidden = true
  507. } else {
  508. cell.separator.isHidden = false
  509. }
  510. return cell
  511. }
  512. }
  513. // MARK: - Table View
  514. extension NCShareExtension: UITableViewDelegate {
  515. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  516. return heightRowTableView
  517. }
  518. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  519. }
  520. }
  521. extension NCShareExtension: UITableViewDataSource {
  522. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  523. filesName.count
  524. }
  525. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  526. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  527. cell.backgroundColor = NCBrandColor.shared.systemBackground
  528. let imageCell = cell.viewWithTag(10) as? UIImageView
  529. let fileNameCell = cell.viewWithTag(20) as? UILabel
  530. let moreButton = cell.viewWithTag(30) as? NCShareExtensionButtonWithIndexPath
  531. let sizeCell = cell.viewWithTag(40) as? UILabel
  532. imageCell?.layer.cornerRadius = 6
  533. imageCell?.layer.masksToBounds = true
  534. let fileName = filesName[indexPath.row]
  535. let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: "", directory: false)
  536. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  537. imageCell?.image = image.resizeImage(size: CGSize(width: 80, height: 80), isAspectRation: true)
  538. } else {
  539. if resultInternalType.iconName.count > 0 {
  540. imageCell?.image = UIImage.init(named: resultInternalType.iconName)
  541. } else {
  542. imageCell?.image = NCBrandColor.cacheImages.file
  543. }
  544. }
  545. fileNameCell?.text = fileName
  546. let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: (NSTemporaryDirectory() + fileName))
  547. sizeCell?.text = CCUtility.transformedSize(fileSize)
  548. moreButton?.setImage(NCUtility.shared.loadImage(named: "more").image(color: NCBrandColor.shared.label, size: 15), for: .normal)
  549. moreButton?.indexPath = indexPath
  550. moreButton?.fileName = fileName
  551. moreButton?.image = imageCell?.image
  552. moreButton?.addTarget(self, action:#selector(moreButtonPressed(sender:)), for: .touchUpInside)
  553. return cell
  554. }
  555. }
  556. // MARK: - NC API & Algorithm
  557. extension NCShareExtension {
  558. @objc func reloadDatasource(withLoadFolder: Bool) {
  559. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  560. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  561. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: layoutForView?.sort, ascending: layoutForView?.ascending, directoryOnTop: layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  562. if withLoadFolder {
  563. loadFolder()
  564. } else {
  565. self.refreshControl.endRefreshing()
  566. }
  567. collectionView.reloadData()
  568. }
  569. func createFolder(with fileName: String) {
  570. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  571. if errorCode == 0 {
  572. self.reloadDatasource(withLoadFolder: true)
  573. } else {
  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. }
  579. }
  580. func loadFolder() {
  581. networkInProgress = true
  582. collectionView.reloadData()
  583. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, _, errorCode, errorDescription) in
  584. if errorCode != 0 {
  585. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  586. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  587. self.present(alertController, animated: true)
  588. }
  589. self.networkInProgress = false
  590. self.metadataFolder = metadataFolder
  591. self.reloadDatasource(withLoadFolder: false)
  592. }
  593. }
  594. func getFilesExtensionContext(completion: @escaping (_ filesName: [String])->()) {
  595. var itemsProvider: [NSItemProvider] = []
  596. var filesName: [String] = []
  597. var conuter = 0
  598. let dateFormatter = DateFormatter()
  599. // ----------------------------------------------------------------------------------------
  600. // Image
  601. func getItem(image: UIImage, fileNameOriginal: String?) {
  602. var fileName: String = ""
  603. if let pngImageData = image.pngData() {
  604. if fileNameOriginal != nil {
  605. fileName = fileNameOriginal!
  606. } else {
  607. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  608. }
  609. let filenamePath = NSTemporaryDirectory() + fileName
  610. if (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil {
  611. filesName.append(fileName)
  612. }
  613. }
  614. }
  615. // URL
  616. func getItem(url: NSURL, fileNameOriginal: String?) {
  617. guard let path = url.path else { return }
  618. var fileName: String = ""
  619. if fileNameOriginal != nil {
  620. fileName = fileNameOriginal!
  621. } else {
  622. if let ext = url.pathExtension {
  623. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  624. }
  625. }
  626. let filenamePath = NSTemporaryDirectory() + fileName
  627. do {
  628. try FileManager.default.removeItem(atPath: filenamePath)
  629. }
  630. catch { }
  631. do {
  632. try FileManager.default.copyItem(atPath: path, toPath:filenamePath)
  633. do {
  634. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  635. if let _attr = attr {
  636. if _attr.fileSize() > 0 {
  637. filesName.append(fileName)
  638. }
  639. }
  640. } catch { }
  641. } catch { }
  642. }
  643. // Data
  644. func getItem(data: Data, fileNameOriginal: String?, description: String) {
  645. var fileName: String = ""
  646. if data.count > 0 {
  647. if fileNameOriginal != nil {
  648. fileName = fileNameOriginal!
  649. } else {
  650. let fullNameArr = description.components(separatedBy: "\"")
  651. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  652. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  653. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  654. }
  655. let filenamePath = NSTemporaryDirectory() + fileName
  656. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  657. filesName.append(fileName)
  658. }
  659. }
  660. // String
  661. func getItem(string: NSString, fileNameOriginal: String?) {
  662. var fileName: String = ""
  663. if string.length > 0 {
  664. fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  665. let filenamePath = NSTemporaryDirectory() + "\(dateFormatter.string(from: Date()))\(conuter).txt"
  666. FileManager.default.createFile(atPath: filenamePath, contents:string.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  667. filesName.append(fileName)
  668. }
  669. }
  670. // ----------------------------------------------------------------------------------------
  671. guard let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] else {
  672. return completion(filesName)
  673. }
  674. for item : NSExtensionItem in inputItems {
  675. if let attachments = item.attachments {
  676. if attachments.isEmpty { continue }
  677. for (_, itemProvider) in (attachments.enumerated()) {
  678. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || itemProvider.hasItemConformingToTypeIdentifier("public.url") {
  679. itemsProvider.append(itemProvider)
  680. }
  681. }
  682. }
  683. }
  684. CCUtility.emptyTemporaryDirectory()
  685. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  686. for itemProvider in itemsProvider {
  687. var typeIdentifier = ""
  688. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  689. if itemProvider.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  690. itemProvider.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  691. if error == nil {
  692. var fileNameOriginal: String?
  693. if let url = item as? NSURL {
  694. if FileManager.default.fileExists(atPath: url.path ?? "") {
  695. fileNameOriginal = url.lastPathComponent!
  696. } else if url.scheme?.lowercased().contains("http") == true {
  697. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter).html"
  698. } else {
  699. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter)"
  700. }
  701. }
  702. if let image = item as? UIImage {
  703. getItem(image: image, fileNameOriginal: fileNameOriginal)
  704. }
  705. if let url = item as? URL {
  706. getItem(url: url as NSURL, fileNameOriginal: fileNameOriginal)
  707. }
  708. if let data = item as? Data {
  709. getItem(data: data, fileNameOriginal: fileNameOriginal, description: itemProvider.description)
  710. }
  711. if let string = item as? NSString {
  712. getItem(string: string, fileNameOriginal: fileNameOriginal)
  713. }
  714. }
  715. conuter += 1
  716. if conuter == itemsProvider.count {
  717. completion(filesName)
  718. }
  719. })
  720. }
  721. }
  722. }
  723. /*
  724. let task = URLSession.shared.downloadTask(with: urlitem) { localURL, urlResponse, error in
  725. if let localURL = localURL {
  726. if fileNameOriginal != nil {
  727. fileName = fileNameOriginal!
  728. } else {
  729. let ext = url.pathExtension
  730. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  731. }
  732. let filenamePath = NSTemporaryDirectory() + fileName
  733. do {
  734. try FileManager.default.removeItem(atPath: filenamePath)
  735. }
  736. catch { }
  737. do {
  738. try FileManager.default.copyItem(atPath: localURL.path, toPath:filenamePath)
  739. do {
  740. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  741. if let _attr = attr {
  742. if _attr.fileSize() > 0 {
  743. filesName.append(fileName)
  744. }
  745. }
  746. } catch let error {
  747. outError = error
  748. }
  749. } catch let error {
  750. outError = error
  751. }
  752. }
  753. if index + 1 == attachments.count {
  754. completion(filesName, outError)
  755. }
  756. }
  757. task.resume()
  758. */
  759. class NCShareExtensionButtonWithIndexPath: UIButton {
  760. var indexPath:IndexPath?
  761. var fileName: String?
  762. var image: UIImage?
  763. }