NCShareExtension.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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 viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  139. super.viewWillTransition(to: size, with: coordinator)
  140. coordinator.animate(alongsideTransition: nil) { _ in
  141. self.collectionView?.collectionViewLayout.invalidateLayout()
  142. }
  143. }
  144. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  145. super.traitCollectionDidChange(previousTraitCollection)
  146. collectionView.reloadData()
  147. tableView.reloadData()
  148. }
  149. // MARK: -
  150. func setAccount(account: String) {
  151. guard let activeAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else {
  152. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  153. return
  154. }
  155. self.activeAccount = activeAccount
  156. // NETWORKING
  157. 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)
  158. // get auto upload folder
  159. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  160. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  161. serverUrl = NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account)
  162. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  163. reloadDatasource(withLoadFolder: true)
  164. setNavigationBar(navigationTitle: NCBrandOptions.shared.brand)
  165. }
  166. func setNavigationBar(navigationTitle: String) {
  167. navigationItem.title = navigationTitle
  168. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  169. // BACK BUTTON
  170. let backButton = UIButton(type: .custom)
  171. backButton.setImage(UIImage(named: "back"), for: .normal)
  172. backButton.tintColor = .systemBlue
  173. backButton.semanticContentAttribute = .forceLeftToRight
  174. backButton.setTitle(" "+NSLocalizedString("_back_", comment: ""), for: .normal)
  175. backButton.setTitleColor(.systemBlue, for: .normal)
  176. backButton.action(for: .touchUpInside) { _ in
  177. while self.serverUrl.last != "/" {
  178. self.serverUrl.removeLast()
  179. }
  180. self.serverUrl.removeLast()
  181. self.reloadDatasource(withLoadFolder: true)
  182. var navigationTitle = (self.serverUrl as NSString).lastPathComponent
  183. if NCUtilityFileSystem.shared.getHomeServer(account: self.activeAccount.account) == self.serverUrl {
  184. navigationTitle = NCBrandOptions.shared.brand
  185. }
  186. self.setNavigationBar(navigationTitle: navigationTitle)
  187. }
  188. // PROFILE BUTTON
  189. var image: UIImage?
  190. if #available(iOS 13.0, *) {
  191. let config = UIImage.SymbolConfiguration(pointSize: 30)
  192. image = NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config)
  193. } else {
  194. image = NCUtility.shared.loadImage(named: "person.crop.circle", size: 30)
  195. }
  196. let fileName = String(CCUtility.getUserUrlBase(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + activeAccount.user + "-original.png"
  197. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  198. if let imageUser = UIImage(contentsOfFile: fileNameLocalPath) {
  199. image = NCUtility.shared.createAvatar(image: imageUser, size: 30)
  200. }
  201. let profileButton = UIButton(type: .custom)
  202. profileButton.setImage(image, for: .normal)
  203. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  204. var title = " "
  205. if activeAccount?.alias == "" {
  206. title = title + (activeAccount?.user ?? "")
  207. } else {
  208. title = title + (activeAccount?.alias ?? "")
  209. }
  210. profileButton.setTitle(title, for: .normal)
  211. profileButton.setTitleColor(.systemBlue, for: .normal)
  212. }
  213. profileButton.semanticContentAttribute = .forceLeftToRight
  214. profileButton.sizeToFit()
  215. profileButton.action(for: .touchUpInside) { _ in
  216. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  217. if accounts.count > 1 {
  218. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  219. // Only here change the active account
  220. for account in accounts {
  221. if account.account == self.activeAccount.account {
  222. account.active = true
  223. } else {
  224. account.active = false
  225. }
  226. }
  227. vcAccountRequest.activeAccount = self.activeAccount
  228. vcAccountRequest.accounts = accounts.sorted { (sorg, dest) -> Bool in
  229. return sorg.active && !dest.active
  230. }
  231. vcAccountRequest.enableTimerProgress = false
  232. vcAccountRequest.enableAddAccount = false
  233. vcAccountRequest.delegate = self
  234. vcAccountRequest.dismissDidEnterBackground = true
  235. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  236. let numberCell = accounts.count
  237. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  238. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height+20)
  239. self.present(popup, animated: true)
  240. }
  241. }
  242. }
  243. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: activeAccount.account) {
  244. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: profileButton)], animated: true)
  245. } else {
  246. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  247. space.width = 20
  248. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: backButton), space, UIBarButtonItem(customView: profileButton)], animated: true)
  249. }
  250. }
  251. func setCommandView() {
  252. var counter: CGFloat = 0
  253. if filesName.count == 0 {
  254. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  255. return
  256. } else {
  257. if filesName.count < 3 {
  258. counter = CGFloat(filesName.count)
  259. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  260. } else {
  261. counter = 3
  262. self.commandViewHeightConstraint.constant = heightCommandView + (self.heightRowTableView * counter)
  263. }
  264. if filesName.count <= 3 {
  265. self.tableView.isScrollEnabled = false
  266. }
  267. // Label upload button
  268. uploadLabel.text = NSLocalizedString("_upload_", comment: "") + " \(filesName.count) " + NSLocalizedString("_files_", comment: "")
  269. // Empty
  270. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50*counter, delegate: self)
  271. self.tableView.reloadData()
  272. }
  273. }
  274. // MARK: - Empty
  275. func emptyDataSetView(_ view: NCEmptyView) {
  276. if networkInProgress {
  277. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  278. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  279. view.emptyDescription.text = ""
  280. } else {
  281. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  282. view.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  283. view.emptyDescription.text = ""
  284. }
  285. }
  286. // MARK: ACTION
  287. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  288. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  289. }
  290. @objc func actionCreateFolder() {
  291. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  292. alertController.addTextField { (textField) in
  293. textField.autocapitalizationType = UITextAutocapitalizationType.words
  294. }
  295. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  296. if let fileName = alertController.textFields?.first?.text {
  297. self.createFolder(with: fileName)
  298. }
  299. }
  300. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  301. print("You've pressed cancel button")
  302. }
  303. alertController.addAction(actionSave)
  304. alertController.addAction(actionCancel)
  305. self.present(alertController, animated: true, completion:nil)
  306. }
  307. @objc func actionUpload() {
  308. if let fileName = filesName.first {
  309. filesName.removeFirst()
  310. let ocId = NSUUID().uuidString
  311. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  312. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: filePath) {
  313. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: true)
  314. 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)
  315. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  316. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  317. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  318. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  319. // E2EE
  320. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  321. metadata.e2eEncrypted = true
  322. }
  323. // CHUNCK
  324. if chunckSize != 0 && metadata.size > chunckSize {
  325. metadata.chunk = true
  326. }
  327. NCNetworking.shared.upload(metadata: metadata) {
  328. } completion: { (errorCode, errorDescription) in
  329. NCUtility.shared.stopActivityIndicator()
  330. if errorCode == 0 {
  331. self.actionUpload()
  332. } else {
  333. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  334. NCManageDatabase.shared.deleteChunks(account: self.activeAccount.account, ocId: ocId)
  335. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  336. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in
  337. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  338. return
  339. }))
  340. self.present(alertController, animated: true)
  341. }
  342. }
  343. }
  344. } else {
  345. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  346. return
  347. }
  348. }
  349. func rename(fileName: String, fileNameNew: String) {
  350. if let row = self.filesName.firstIndex(where: {$0 == fileName}) {
  351. if NCUtilityFileSystem.shared.moveFile(atPath: (NSTemporaryDirectory() + fileName), toPath: (NSTemporaryDirectory() + fileNameNew)) {
  352. filesName[row] = fileNameNew
  353. tableView.reloadData()
  354. }
  355. }
  356. }
  357. func accountRequestChangeAccount(account: String) {
  358. setAccount(account: account)
  359. }
  360. }
  361. // MARK: - Collection View
  362. extension NCShareExtension: UICollectionViewDelegate {
  363. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  364. if let metadata = dataSource.cellForItemAt(indexPath: indexPath) {
  365. if let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) {
  366. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: activeAccount.account) {
  367. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: NSLocalizedString("_e2e_goto_settings_for_enable_", comment: ""), preferredStyle: .alert)
  368. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  369. self.present(alertController, animated: true)
  370. return
  371. }
  372. self.serverUrl = serverUrl
  373. reloadDatasource(withLoadFolder: true)
  374. setNavigationBar(navigationTitle: metadata.fileNameView)
  375. }
  376. }
  377. }
  378. }
  379. extension NCShareExtension: UICollectionViewDataSource {
  380. func numberOfSections(in collectionView: UICollectionView) -> Int {
  381. return 1
  382. }
  383. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  384. let numberOfItems = dataSource.numberOfItems()
  385. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  386. return numberOfItems
  387. }
  388. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  389. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  390. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  391. }
  392. var tableShare: tableShare?
  393. var isShare = false
  394. var isMounted = false
  395. if let metadataFolder = metadataFolder {
  396. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  397. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  398. }
  399. if dataSource.metadataShare[metadata.ocId] != nil {
  400. tableShare = dataSource.metadataShare[metadata.ocId]
  401. }
  402. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  403. cell.delegate = self
  404. cell.fileObjectId = metadata.ocId
  405. cell.fileUser = metadata.ownerId
  406. cell.labelTitle.text = metadata.fileNameView
  407. cell.labelTitle.textColor = NCBrandColor.shared.label
  408. cell.imageSelect.image = nil
  409. cell.imageStatus.image = nil
  410. cell.imageLocal.image = nil
  411. cell.imageFavorite.image = nil
  412. cell.imageShared.image = nil
  413. cell.imageMore.image = nil
  414. cell.imageItem.image = nil
  415. cell.imageItem.backgroundColor = nil
  416. cell.progressView.progress = 0.0
  417. if metadata.directory {
  418. if metadata.e2eEncrypted {
  419. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  420. } else if isShare {
  421. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  422. } else if (tableShare != nil && tableShare?.shareType != 3) {
  423. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  424. } else if (tableShare != nil && tableShare?.shareType == 3) {
  425. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  426. } else if metadata.mountType == "group" {
  427. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  428. } else if isMounted {
  429. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  430. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  431. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  432. } else {
  433. cell.imageItem.image = NCBrandColor.cacheImages.folder
  434. }
  435. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  436. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  437. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  438. // Local image: offline
  439. if tableDirectory != nil && tableDirectory!.offline {
  440. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  441. }
  442. }
  443. // image Favorite
  444. if metadata.favorite {
  445. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  446. }
  447. cell.imageSelect.isHidden = true
  448. cell.backgroundView = nil
  449. cell.hideButtonMore(true)
  450. cell.hideButtonShare(true)
  451. cell.selectMode(false)
  452. // Live Photo
  453. if metadata.livePhoto {
  454. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  455. }
  456. // Remove last separator
  457. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  458. cell.separator.isHidden = true
  459. } else {
  460. cell.separator.isHidden = false
  461. }
  462. return cell
  463. }
  464. }
  465. // MARK: - Table View
  466. extension NCShareExtension: UITableViewDelegate {
  467. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  468. return heightRowTableView
  469. }
  470. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  471. }
  472. }
  473. extension NCShareExtension: UITableViewDataSource {
  474. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  475. filesName.count
  476. }
  477. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  478. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  479. cell.backgroundColor = NCBrandColor.shared.systemBackground
  480. let imageCell = cell.viewWithTag(10) as? UIImageView
  481. let fileNameCell = cell.viewWithTag(20) as? UILabel
  482. let moreButton = cell.viewWithTag(30) as? NCShareExtensionButtonWithIndexPath
  483. let sizeCell = cell.viewWithTag(40) as? UILabel
  484. imageCell?.layer.cornerRadius = 6
  485. imageCell?.layer.masksToBounds = true
  486. let fileName = filesName[indexPath.row]
  487. let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: "", directory: false)
  488. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  489. imageCell?.image = image.resizeImage(size: CGSize(width: 80, height: 80), isAspectRation: true)
  490. } else {
  491. if resultInternalType.iconName.count > 0 {
  492. imageCell?.image = UIImage.init(named: resultInternalType.iconName)
  493. } else {
  494. imageCell?.image = NCBrandColor.cacheImages.file
  495. }
  496. }
  497. fileNameCell?.text = fileName
  498. let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: (NSTemporaryDirectory() + fileName))
  499. sizeCell?.text = CCUtility.transformedSize(fileSize)
  500. moreButton?.setImage(NCUtility.shared.loadImage(named: "more").image(color: NCBrandColor.shared.label, size: 15), for: .normal)
  501. moreButton?.indexPath = indexPath
  502. moreButton?.fileName = fileName
  503. moreButton?.image = imageCell?.image
  504. moreButton?.action(for: .touchUpInside, { sender in
  505. if let fileName = (sender as! NCShareExtensionButtonWithIndexPath).fileName {
  506. let alertController = UIAlertController(title: "", message: fileName, preferredStyle: .alert)
  507. alertController.addAction(UIAlertAction(title: NSLocalizedString("_delete_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  508. if let index = self.filesName.firstIndex(of: fileName) {
  509. self.filesName.remove(at: index)
  510. if self.filesName.count == 0 {
  511. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  512. } else {
  513. self.setCommandView()
  514. }
  515. }
  516. })
  517. alertController.addAction(UIAlertAction(title: NSLocalizedString("_rename_file_", comment: ""), style: .default) { (action:UIAlertAction) in
  518. if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
  519. vcRename.delegate = self
  520. vcRename.fileName = fileName
  521. vcRename.imagePreview = (sender as! NCShareExtensionButtonWithIndexPath).image
  522. let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
  523. self.present(popup, animated: true)
  524. }
  525. })
  526. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in })
  527. self.present(alertController, animated: true, completion:nil)
  528. }
  529. })
  530. return cell
  531. }
  532. }
  533. // MARK: - NC API & Algorithm
  534. extension NCShareExtension {
  535. @objc func reloadDatasource(withLoadFolder: Bool) {
  536. layoutForView = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  537. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  538. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: layoutForView?.sort, ascending: layoutForView?.ascending, directoryOnTop: layoutForView?.directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  539. if withLoadFolder {
  540. loadFolder()
  541. } else {
  542. self.refreshControl.endRefreshing()
  543. }
  544. collectionView.reloadData()
  545. }
  546. func createFolder(with fileName: String) {
  547. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  548. if errorCode == 0 {
  549. self.serverUrl = self.serverUrl + "/" + fileName
  550. self.reloadDatasource(withLoadFolder: true)
  551. self.setNavigationBar(navigationTitle: fileName)
  552. } else {
  553. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  554. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  555. self.present(alertController, animated: true)
  556. }
  557. }
  558. }
  559. func loadFolder() {
  560. networkInProgress = true
  561. collectionView.reloadData()
  562. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, _, errorCode, errorDescription) in
  563. if errorCode != 0 {
  564. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: errorDescription, preferredStyle: .alert)
  565. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  566. self.present(alertController, animated: true)
  567. }
  568. self.networkInProgress = false
  569. self.metadataFolder = metadataFolder
  570. self.reloadDatasource(withLoadFolder: false)
  571. }
  572. }
  573. func getFilesExtensionContext(completion: @escaping (_ filesName: [String])->()) {
  574. var itemsProvider: [NSItemProvider] = []
  575. var filesName: [String] = []
  576. var conuter = 0
  577. let dateFormatter = DateFormatter()
  578. // ----------------------------------------------------------------------------------------
  579. // Image
  580. func getItem(image: UIImage, fileNameOriginal: String?) {
  581. var fileName: String = ""
  582. if let pngImageData = image.pngData() {
  583. if fileNameOriginal != nil {
  584. fileName = fileNameOriginal!
  585. } else {
  586. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  587. }
  588. let filenamePath = NSTemporaryDirectory() + fileName
  589. if (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil {
  590. filesName.append(fileName)
  591. }
  592. }
  593. }
  594. // URL
  595. func getItem(url: NSURL, fileNameOriginal: String?) {
  596. guard let path = url.path else { return }
  597. var fileName: String = ""
  598. if fileNameOriginal != nil {
  599. fileName = fileNameOriginal!
  600. } else {
  601. if let ext = url.pathExtension {
  602. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  603. }
  604. }
  605. let filenamePath = NSTemporaryDirectory() + fileName
  606. do {
  607. try FileManager.default.removeItem(atPath: filenamePath)
  608. }
  609. catch { }
  610. do {
  611. try FileManager.default.copyItem(atPath: path, toPath:filenamePath)
  612. do {
  613. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  614. if let _attr = attr {
  615. if _attr.fileSize() > 0 {
  616. filesName.append(fileName)
  617. }
  618. }
  619. } catch { }
  620. } catch { }
  621. }
  622. // Data
  623. func getItem(data: Data, fileNameOriginal: String?, description: String) {
  624. var fileName: String = ""
  625. if data.count > 0 {
  626. if fileNameOriginal != nil {
  627. fileName = fileNameOriginal!
  628. } else {
  629. let fullNameArr = description.components(separatedBy: "\"")
  630. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  631. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  632. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  633. }
  634. let filenamePath = NSTemporaryDirectory() + fileName
  635. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  636. filesName.append(fileName)
  637. }
  638. }
  639. // String
  640. func getItem(string: NSString, fileNameOriginal: String?) {
  641. var fileName: String = ""
  642. if string.length > 0 {
  643. fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  644. let filenamePath = NSTemporaryDirectory() + "\(dateFormatter.string(from: Date()))\(conuter).txt"
  645. FileManager.default.createFile(atPath: filenamePath, contents:string.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  646. filesName.append(fileName)
  647. }
  648. }
  649. // ----------------------------------------------------------------------------------------
  650. guard let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] else {
  651. return completion(filesName)
  652. }
  653. for item : NSExtensionItem in inputItems {
  654. if let attachments = item.attachments {
  655. if attachments.isEmpty { continue }
  656. for (_, itemProvider) in (attachments.enumerated()) {
  657. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || itemProvider.hasItemConformingToTypeIdentifier("public.url") {
  658. itemsProvider.append(itemProvider)
  659. }
  660. }
  661. }
  662. }
  663. CCUtility.emptyTemporaryDirectory()
  664. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  665. for itemProvider in itemsProvider {
  666. var typeIdentifier = ""
  667. if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  668. if itemProvider.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  669. itemProvider.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  670. if error == nil {
  671. var fileNameOriginal: String?
  672. if let url = item as? NSURL {
  673. if FileManager.default.fileExists(atPath: url.path ?? "") {
  674. fileNameOriginal = url.lastPathComponent!
  675. } else if url.scheme?.lowercased().contains("http") == true {
  676. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter).html"
  677. } else {
  678. fileNameOriginal = "\(dateFormatter.string(from: Date()))\(conuter)"
  679. }
  680. }
  681. if let image = item as? UIImage {
  682. getItem(image: image, fileNameOriginal: fileNameOriginal)
  683. }
  684. if let url = item as? URL {
  685. getItem(url: url as NSURL, fileNameOriginal: fileNameOriginal)
  686. }
  687. if let data = item as? Data {
  688. getItem(data: data, fileNameOriginal: fileNameOriginal, description: itemProvider.description)
  689. }
  690. if let string = item as? NSString {
  691. getItem(string: string, fileNameOriginal: fileNameOriginal)
  692. }
  693. }
  694. conuter += 1
  695. if conuter == itemsProvider.count {
  696. completion(filesName)
  697. }
  698. })
  699. }
  700. }
  701. }
  702. /*
  703. let task = URLSession.shared.downloadTask(with: urlitem) { localURL, urlResponse, error in
  704. if let localURL = localURL {
  705. if fileNameOriginal != nil {
  706. fileName = fileNameOriginal!
  707. } else {
  708. let ext = url.pathExtension
  709. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  710. }
  711. let filenamePath = NSTemporaryDirectory() + fileName
  712. do {
  713. try FileManager.default.removeItem(atPath: filenamePath)
  714. }
  715. catch { }
  716. do {
  717. try FileManager.default.copyItem(atPath: localURL.path, toPath:filenamePath)
  718. do {
  719. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  720. if let _attr = attr {
  721. if _attr.fileSize() > 0 {
  722. filesName.append(fileName)
  723. }
  724. }
  725. } catch let error {
  726. outError = error
  727. }
  728. } catch let error {
  729. outError = error
  730. }
  731. }
  732. if index + 1 == attachments.count {
  733. completion(filesName, outError)
  734. }
  735. }
  736. task.resume()
  737. */
  738. class NCShareExtensionButtonWithIndexPath: UIButton {
  739. var indexPath:IndexPath?
  740. var fileName: String?
  741. var image: UIImage?
  742. }