NCShareExtension.swift 40 KB

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