NCShareExtension.swift 40 KB

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