NCShareExtension.swift 42 KB

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