NCShareExtension.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 Foundation
  24. import NCCommunication
  25. class NCShareExtension: UIViewController, NCListCellDelegate, NCEmptyDataSetDelegate {
  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 separatorHeightConstraint: NSLayoutConstraint!
  31. @IBOutlet weak var commandViewHeightConstraint: NSLayoutConstraint!
  32. @IBOutlet weak var createFolderButton: UIButton!
  33. @IBOutlet weak var createFolderLabel: UILabel!
  34. @IBOutlet weak var uploadButton: UIButton!
  35. // -------------------------------------------------------------
  36. var titleCurrentFolder = NCBrandOptions.shared.brand
  37. var serverUrl = ""
  38. var filesName: [String] = []
  39. // -------------------------------------------------------------
  40. private var emptyDataSet: NCEmptyDataSet?
  41. private let keyLayout = NCGlobal.shared.layoutViewShareExtension
  42. private var metadataFolder: tableMetadata?
  43. private var networkInProgress = false
  44. private var dataSource = NCDataSource()
  45. private var sort: String = ""
  46. private var ascending: Bool = true
  47. private var directoryOnTop: Bool = true
  48. private var layout = ""
  49. private var groupBy = ""
  50. private var titleButton = ""
  51. private var itemForLine = 0
  52. private var heightRowTableView: CGFloat = 50
  53. private var autoUploadFileName = ""
  54. private var autoUploadDirectory = ""
  55. private var shares: [tableShare]?
  56. private let refreshControl = UIRefreshControl()
  57. private var activeAccount: tableAccount!
  58. // COLOR
  59. var labelColor: UIColor {
  60. get {
  61. if #available(iOS 13, *) {
  62. return .label
  63. } else {
  64. return .black
  65. }
  66. }
  67. }
  68. var separatorColor: UIColor {
  69. get {
  70. if #available(iOS 13, *) {
  71. return .separator
  72. } else {
  73. return UIColor(hex: "#3C3C434A")!
  74. }
  75. }
  76. }
  77. // MARK: - Life Cycle
  78. override func viewDidLoad() {
  79. super.viewDidLoad()
  80. self.navigationController?.navigationBar.prefersLargeTitles = false
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.collectionViewLayout = NCListLayout()
  84. // Add Refresh Control
  85. collectionView.addSubview(refreshControl)
  86. refreshControl.tintColor = NCBrandColor.shared.brandText
  87. refreshControl.backgroundColor = NCBrandColor.shared.backgroundView
  88. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  89. // Empty
  90. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50, delegate: self)
  91. separatorView.backgroundColor = separatorColor
  92. tableView.separatorColor = separatorColor
  93. //tableView.layer.borderColor = separatorColor.cgColor
  94. tableView.layer.borderWidth = 0
  95. tableView.layer.cornerRadius = 10.0
  96. tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: 1)))
  97. createFolderLabel.text = NSLocalizedString("_create_folder_", comment: "")
  98. uploadButton.setTitle(NSLocalizedString("_save_files_", comment: ""), for: .normal)
  99. // LOG
  100. let levelLog = CCUtility.getLogLevel()
  101. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  102. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  103. NCCommunicationCommon.shared.levelLog = levelLog
  104. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  105. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  106. }
  107. if isSimulatorOrTestFlight {
  108. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  109. } else {
  110. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  111. }
  112. }
  113. override func viewWillAppear(_ animated: Bool) {
  114. super.viewWillAppear(animated)
  115. if serverUrl == "" {
  116. guard let account = NCManageDatabase.shared.getAccountActive() else {
  117. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  118. return
  119. }
  120. self.activeAccount = account
  121. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  122. // NETWORKING
  123. NCCommunicationCommon.shared.setup(account: account.account, user: account.user, userId: account.userId, password: CCUtility.getPassword(account.account), urlBase: account.urlBase, userAgent: CCUtility.getUserAgent(), webDav: NCUtilityFileSystem.shared.getWebDAV(account: account.account), dav: NCUtilityFileSystem.shared.getDAV(), nextcloudVersion: serverVersionMajor, delegate: NCNetworking.shared)
  124. // get auto upload folder
  125. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  126. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  127. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  128. // Load data source
  129. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account)
  130. getFilesExtensionContext { (filesName, error) in
  131. DispatchQueue.main.async {
  132. self.filesName = filesName
  133. if filesName.count == 0 {
  134. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  135. return
  136. } else {
  137. if filesName.count < 3 {
  138. self.commandViewHeightConstraint.constant = 140 + (self.heightRowTableView * CGFloat(filesName.count))
  139. } else {
  140. self.commandViewHeightConstraint.constant = 140 + (self.heightRowTableView * 3)
  141. }
  142. if filesName.count <= 3 {
  143. self.tableView.isScrollEnabled = false
  144. }
  145. self.tableView.reloadData()
  146. }
  147. }
  148. }
  149. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  150. reloadDatasource(withLoadFolder: true)
  151. setNavigationBar()
  152. }
  153. }
  154. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  155. super.viewWillTransition(to: size, with: coordinator)
  156. coordinator.animate(alongsideTransition: nil) { _ in
  157. self.collectionView?.collectionViewLayout.invalidateLayout()
  158. }
  159. }
  160. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  161. super.traitCollectionDidChange(previousTraitCollection)
  162. collectionView.reloadData()
  163. tableView.reloadData()
  164. }
  165. // MARK: -
  166. func setNavigationBar() {
  167. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  168. // BACK BUTTON
  169. let backButton = UIButton(type: .custom)
  170. backButton.setImage(UIImage(named: "back"), for: .normal)
  171. backButton.tintColor = .systemBlue
  172. backButton.semanticContentAttribute = .forceLeftToRight
  173. backButton.setTitle(" "+NSLocalizedString("_back_", comment: ""), for: .normal)
  174. backButton.setTitleColor(.systemBlue, for: .normal)
  175. backButton.addTarget(self, action: #selector(backButtonTapped(sender:)), for: .touchUpInside)
  176. // PROFILE BUTTON
  177. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  178. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + activeAccount.user + ".png"
  179. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  180. image = userImage
  181. }
  182. image = NCUtility.shared.createAvatar(image: image, size: 30)
  183. let profileButton = UIButton(type: .custom)
  184. profileButton.setImage(image, for: .normal)
  185. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  186. let account = NCManageDatabase.shared.getAccountActive()
  187. var title = " "
  188. if account?.alias == "" {
  189. title = title + (account?.user ?? "")
  190. } else {
  191. title = title + (account?.alias ?? "")
  192. }
  193. profileButton.setTitle(title, for: .normal)
  194. profileButton.setTitleColor(.systemBlue, for: .normal)
  195. }
  196. profileButton.semanticContentAttribute = .forceLeftToRight
  197. profileButton.sizeToFit()
  198. profileButton.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  199. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  200. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: profileButton)], animated: true)
  201. navigationItem.title = titleCurrentFolder
  202. } else {
  203. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  204. space.width = 20
  205. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: backButton), space, UIBarButtonItem(customView: profileButton)], animated: true)
  206. navigationItem.title = ""
  207. }
  208. }
  209. // MARK: - Empty
  210. func emptyDataSetView(_ view: NCEmptyView) {
  211. if networkInProgress {
  212. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  213. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  214. view.emptyDescription.text = ""
  215. } else {
  216. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  217. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  218. view.emptyDescription.text = ""
  219. }
  220. }
  221. // MARK: ACTION
  222. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  223. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  224. }
  225. @IBAction func actionCreateFolder(_ sender: UIButton) {
  226. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  227. alertController.addTextField { (textField) in
  228. textField.autocapitalizationType = UITextAutocapitalizationType.words
  229. }
  230. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  231. if let fileName = alertController.textFields?.first?.text {
  232. self.createFolder(with: fileName)
  233. }
  234. }
  235. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  236. print("You've pressed cancel button")
  237. }
  238. alertController.addAction(actionSave)
  239. alertController.addAction(actionCancel)
  240. self.present(alertController, animated: true, completion:nil)
  241. }
  242. @IBAction func actionUpload(_ sender: UIButton) {
  243. }
  244. @objc func backButtonTapped(sender: Any) {
  245. while serverUrl.last != "/" {
  246. serverUrl.removeLast()
  247. }
  248. serverUrl.removeLast()
  249. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  250. reloadDatasource(withLoadFolder: true)
  251. setNavigationBar()
  252. }
  253. @objc func renameButtonPressed(sender: NCShareExtensionButtonWithIndexPath) {
  254. }
  255. @objc func deleteButtonPressed(sender: NCShareExtensionButtonWithIndexPath) {
  256. }
  257. @objc func profileButtonTapped(sender: Any) {
  258. }
  259. func tapShareListItem(with objectId: String, sender: Any) {
  260. }
  261. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  262. }
  263. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  264. }
  265. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  266. }
  267. }
  268. // MARK: - Collection View
  269. extension NCShareExtension: UICollectionViewDelegate {
  270. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  271. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  272. guard let serverUrlTemp = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  273. serverUrl = serverUrlTemp
  274. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  275. reloadDatasource(withLoadFolder: true)
  276. setNavigationBar()
  277. }
  278. }
  279. extension NCShareExtension: UICollectionViewDataSource {
  280. func numberOfSections(in collectionView: UICollectionView) -> Int {
  281. return 1
  282. }
  283. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  284. let numberOfItems = dataSource.numberOfItems()
  285. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  286. return numberOfItems
  287. }
  288. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  289. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  290. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  291. }
  292. var tableShare: tableShare?
  293. var isShare = false
  294. var isMounted = false
  295. // Download preview
  296. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  297. if let metadataFolder = metadataFolder {
  298. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  299. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  300. }
  301. if dataSource.metadataShare[metadata.ocId] != nil {
  302. tableShare = dataSource.metadataShare[metadata.ocId]
  303. }
  304. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  305. cell.delegate = self
  306. cell.objectId = metadata.ocId
  307. cell.indexPath = indexPath
  308. cell.labelTitle.text = metadata.fileNameView
  309. cell.labelTitle.textColor = labelColor
  310. cell.separator.backgroundColor = separatorColor
  311. cell.separatorHeight(size: 0.5)
  312. cell.imageSelect.image = nil
  313. cell.imageStatus.image = nil
  314. cell.imageLocal.image = nil
  315. cell.imageFavorite.image = nil
  316. cell.imageShared.image = nil
  317. cell.imageMore.image = nil
  318. cell.imageItem.image = nil
  319. cell.imageItem.backgroundColor = nil
  320. cell.progressView.progress = 0.0
  321. if metadata.directory {
  322. if metadata.e2eEncrypted {
  323. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  324. } else if isShare {
  325. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  326. } else if (tableShare != nil && tableShare?.shareType != 3) {
  327. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  328. } else if (tableShare != nil && tableShare?.shareType == 3) {
  329. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  330. } else if metadata.mountType == "group" {
  331. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  332. } else if isMounted {
  333. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  334. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  335. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  336. } else {
  337. cell.imageItem.image = NCBrandColor.cacheImages.folder
  338. }
  339. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  340. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  341. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  342. // Local image: offline
  343. if tableDirectory != nil && tableDirectory!.offline {
  344. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  345. }
  346. } else {
  347. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  348. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  349. } else {
  350. if metadata.hasPreview {
  351. cell.imageItem.backgroundColor = .lightGray
  352. } else {
  353. if metadata.iconName.count > 0 {
  354. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  355. } else {
  356. cell.imageItem.image = NCBrandColor.cacheImages.file
  357. }
  358. }
  359. }
  360. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  361. // image local
  362. if dataSource.metadataOffLine.contains(metadata.ocId) {
  363. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  364. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  365. cell.imageLocal.image = NCBrandColor.cacheImages.local
  366. }
  367. }
  368. // image Favorite
  369. if metadata.favorite {
  370. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  371. }
  372. // Share image
  373. if (isShare) {
  374. cell.imageShared.image = NCBrandColor.cacheImages.shared
  375. } else if (tableShare != nil && tableShare?.shareType == 3) {
  376. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  377. } else if (tableShare != nil && tableShare?.shareType != 3) {
  378. cell.imageShared.image = NCBrandColor.cacheImages.shared
  379. } else {
  380. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  381. }
  382. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  383. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  384. if FileManager.default.fileExists(atPath: fileNameUser) {
  385. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  386. } else {
  387. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  388. if errorCode == 0 && account == self.activeAccount.account {
  389. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  390. }
  391. }
  392. }
  393. }
  394. cell.imageSelect.isHidden = true
  395. cell.backgroundView = nil
  396. cell.hideButtonMore(true)
  397. cell.hideButtonShare(true)
  398. cell.selectMode(false)
  399. // Live Photo
  400. if metadata.livePhoto {
  401. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  402. }
  403. // Remove last separator
  404. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  405. cell.separator.isHidden = true
  406. } else {
  407. cell.separator.isHidden = false
  408. }
  409. return cell
  410. }
  411. }
  412. extension NCShareExtension: UITableViewDelegate {
  413. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  414. return heightRowTableView
  415. }
  416. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  417. }
  418. }
  419. extension NCShareExtension: UITableViewDataSource {
  420. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  421. filesName.count
  422. }
  423. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  424. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  425. let imageCell = cell.viewWithTag(10) as? UIImageView
  426. let fileNameCell = cell.viewWithTag(20) as? UILabel
  427. let renameButton = cell.viewWithTag(30) as? NCShareExtensionButtonWithIndexPath
  428. let deleteButton = cell.viewWithTag(40) as? NCShareExtensionButtonWithIndexPath
  429. imageCell?.layer.cornerRadius = 6
  430. imageCell?.layer.masksToBounds = true
  431. let fileName = filesName[indexPath.row]
  432. imageCell?.image = NCUtility.shared.loadImage(named: "file")
  433. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  434. imageCell?.image = image
  435. }
  436. fileNameCell?.text = fileName
  437. renameButton?.setImage(NCUtility.shared.loadImage(named: "pencil").image(color: labelColor, size: 15), for: .normal)
  438. renameButton?.indexPath = indexPath
  439. renameButton?.addTarget(self, action:#selector(renameButtonPressed(sender:)), for: .touchUpInside)
  440. deleteButton?.setImage(NCUtility.shared.loadImage(named: "trash").image(color: .red, size: 15), for: .normal)
  441. deleteButton?.indexPath = indexPath
  442. deleteButton?.addTarget(self, action:#selector(deleteButtonPressed(sender:)), for: .touchUpInside)
  443. return cell
  444. }
  445. }
  446. // MARK: - NC API & Algorithm
  447. extension NCShareExtension {
  448. @objc func reloadDatasource(withLoadFolder: Bool) {
  449. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  450. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  451. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: sort, ascending: ascending, directoryOnTop: directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  452. if withLoadFolder {
  453. loadFolder()
  454. } else {
  455. self.refreshControl.endRefreshing()
  456. }
  457. collectionView.reloadData()
  458. }
  459. func createFolder(with fileName: String) {
  460. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  461. if errorCode == 0 {
  462. self.reloadDatasource(withLoadFolder: true)
  463. } else {
  464. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  465. }
  466. }
  467. }
  468. func loadFolder() {
  469. networkInProgress = true
  470. collectionView.reloadData()
  471. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, errorCode, errorDescription) in
  472. if errorCode != 0 {
  473. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  474. }
  475. self.networkInProgress = false
  476. self.metadataFolder = metadataFolder
  477. self.reloadDatasource(withLoadFolder: false)
  478. }
  479. }
  480. func getFilesExtensionContext(completion: @escaping (_ filesName: [String], _ error: Error?)->()) {
  481. var filesName: [String] = []
  482. var conuter = 0
  483. var outError: Error? = nil
  484. CCUtility.emptyTemporaryDirectory()
  485. if let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] {
  486. for item : NSExtensionItem in inputItems {
  487. if let attachments = item.attachments {
  488. if attachments.isEmpty {
  489. extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  490. completion(filesName, outError)
  491. return
  492. }
  493. for (index, current) in (attachments.enumerated()) {
  494. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || current.hasItemConformingToTypeIdentifier("public.url") {
  495. var typeIdentifier = ""
  496. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  497. if current.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  498. current.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  499. var fileNameOriginal: String?
  500. var fileName: String = ""
  501. let dateFormatter = DateFormatter()
  502. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  503. conuter += 1
  504. if let url = item as? NSURL {
  505. fileNameOriginal = url.lastPathComponent!
  506. }
  507. if error == nil {
  508. if let image = item as? UIImage {
  509. print("item as UIImage")
  510. if let pngImageData = image.pngData() {
  511. if fileNameOriginal != nil {
  512. fileName = fileNameOriginal!
  513. } else {
  514. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  515. }
  516. let filenamePath = NSTemporaryDirectory() + fileName
  517. let result = (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil
  518. if result {
  519. filesName.append(fileName)
  520. }
  521. } else {
  522. print("Error image nil")
  523. }
  524. }
  525. if let url = item as? URL {
  526. print("item as url: \(String(describing: item))")
  527. if fileNameOriginal != nil {
  528. fileName = fileNameOriginal!
  529. } else {
  530. let ext = url.pathExtension
  531. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  532. }
  533. let filenamePath = NSTemporaryDirectory() + fileName
  534. do {
  535. try FileManager.default.removeItem(atPath: filenamePath)
  536. }
  537. catch { }
  538. do {
  539. try FileManager.default.copyItem(atPath: url.path, toPath:filenamePath)
  540. do {
  541. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  542. if let _attr = attr {
  543. if _attr.fileSize() > 0 {
  544. filesName.append(fileName)
  545. }
  546. }
  547. } catch let error {
  548. outError = error
  549. }
  550. } catch let error {
  551. outError = error
  552. }
  553. }
  554. if let data = item as? Data {
  555. if data.count > 0 {
  556. print("item as NSdata")
  557. if fileNameOriginal != nil {
  558. fileName = fileNameOriginal!
  559. } else {
  560. let description = current.description
  561. let fullNameArr = description.components(separatedBy: "\"")
  562. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  563. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  564. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  565. }
  566. let filenamePath = NSTemporaryDirectory() + fileName
  567. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  568. filesName.append(fileName)
  569. }
  570. }
  571. if let data = item as? NSString {
  572. if data.length > 0 {
  573. print("item as NSString")
  574. let fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  575. let filenamePath = NSTemporaryDirectory() + fileName
  576. FileManager.default.createFile(atPath: filenamePath, contents:data.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  577. filesName.append(fileName)
  578. }
  579. }
  580. if index + 1 == attachments.count {
  581. completion(filesName, outError)
  582. }
  583. } else {
  584. completion( filesName, error)
  585. }
  586. })
  587. }
  588. } // end for
  589. } else {
  590. completion(filesName, outError)
  591. }
  592. }
  593. } else {
  594. completion(filesName, outError)
  595. }
  596. }
  597. }
  598. class NCShareExtensionButtonWithIndexPath: UIButton {
  599. var indexPath:IndexPath?
  600. }