NCShareExtension.swift 41 KB

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