NCShareExtension.swift 42 KB

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