NCShareExtension.swift 38 KB

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