NCShareExtension.swift 39 KB

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