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