NCShareExtension.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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 {
  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 separatorHeightConstraint: NSLayoutConstraint!
  31. @IBOutlet weak var commandViewHeightConstraint: NSLayoutConstraint!
  32. @IBOutlet weak var createFolderButton: UIButton!
  33. @IBOutlet weak var createFolderLabel: UILabel!
  34. @IBOutlet weak var uploadButton: UIButton!
  35. // -------------------------------------------------------------
  36. var titleCurrentFolder = NCBrandOptions.shared.brand
  37. var serverUrl = ""
  38. var filesName: [String] = []
  39. // -------------------------------------------------------------
  40. private var emptyDataSet: NCEmptyDataSet?
  41. private let keyLayout = NCGlobal.shared.layoutViewShareExtension
  42. private var metadataFolder: tableMetadata?
  43. private var networkInProgress = false
  44. private var dataSource = NCDataSource()
  45. private var sort: String = ""
  46. private var ascending: Bool = true
  47. private var directoryOnTop: Bool = true
  48. private var layout = ""
  49. private var groupBy = ""
  50. private var titleButton = ""
  51. private var itemForLine = 0
  52. private var autoUploadFileName = ""
  53. private var autoUploadDirectory = ""
  54. private var shares: [tableShare]?
  55. private let refreshControl = UIRefreshControl()
  56. private var activeAccount: tableAccount!
  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.backgroundView
  67. refreshControl.addTarget(self, action: #selector(reloadDatasource), for: .valueChanged)
  68. // Empty
  69. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50, delegate: self)
  70. separatorView.backgroundColor = NCBrandColor.shared.separator
  71. createFolderButton.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  72. uploadButton.setTitle(NSLocalizedString("_save_files_", comment: ""), for: .normal)
  73. // LOG
  74. let levelLog = CCUtility.getLogLevel()
  75. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  76. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  77. NCCommunicationCommon.shared.levelLog = levelLog
  78. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  79. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  80. }
  81. if isSimulatorOrTestFlight {
  82. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  83. } else {
  84. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  85. }
  86. }
  87. override func viewWillAppear(_ animated: Bool) {
  88. super.viewWillAppear(animated)
  89. if serverUrl == "" {
  90. guard let account = NCManageDatabase.shared.getAccountActive() else {
  91. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  92. return
  93. }
  94. self.activeAccount = account
  95. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  96. // NETWORKING
  97. 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: serverVersionMajor, delegate: NCNetworking.shared)
  98. // get auto upload folder
  99. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  100. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  101. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  102. // Load data source
  103. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account)
  104. getFilesExtensionContext { (filesName, error) in
  105. DispatchQueue.main.async {
  106. self.filesName = filesName
  107. if filesName.count == 0 {
  108. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  109. return
  110. } else {
  111. self.tableView.reloadData()
  112. }
  113. }
  114. }
  115. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  116. reloadDatasource(withLoadFolder: true)
  117. setNavigationBar()
  118. }
  119. }
  120. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  121. super.viewWillTransition(to: size, with: coordinator)
  122. coordinator.animate(alongsideTransition: nil) { _ in
  123. self.collectionView?.collectionViewLayout.invalidateLayout()
  124. }
  125. }
  126. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  127. super.traitCollectionDidChange(previousTraitCollection)
  128. if traitCollection.userInterfaceStyle == .dark {
  129. } else {
  130. }
  131. }
  132. // MARK: -
  133. func setNavigationBar() {
  134. cancelButton.title = NSLocalizedString("_cancel_", comment: "")
  135. // BACK BUTTON
  136. let backButton = UIButton(type: .custom)
  137. backButton.setImage(UIImage(named: "back"), for: .normal)
  138. backButton.tintColor = .systemBlue
  139. backButton.semanticContentAttribute = .forceLeftToRight
  140. backButton.setTitle(" "+NSLocalizedString("_back_", comment: ""), for: .normal)
  141. backButton.setTitleColor(.systemBlue, for: .normal)
  142. backButton.addTarget(self, action: #selector(backButtonTapped(sender:)), for: .touchUpInside)
  143. // PROFILE BUTTON
  144. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  145. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + activeAccount.user + ".png"
  146. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  147. image = userImage
  148. }
  149. image = NCUtility.shared.createAvatar(image: image, size: 30)
  150. let profileButton = UIButton(type: .custom)
  151. profileButton.setImage(image, for: .normal)
  152. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  153. let account = NCManageDatabase.shared.getAccountActive()
  154. var title = " "
  155. if account?.alias == "" {
  156. title = title + (account?.user ?? "")
  157. } else {
  158. title = title + (account?.alias ?? "")
  159. }
  160. profileButton.setTitle(title, for: .normal)
  161. profileButton.setTitleColor(.systemBlue, for: .normal)
  162. }
  163. profileButton.semanticContentAttribute = .forceLeftToRight
  164. profileButton.sizeToFit()
  165. profileButton.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  166. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account) {
  167. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: profileButton)], animated: true)
  168. navigationItem.title = titleCurrentFolder
  169. } else {
  170. let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  171. space.width = 20
  172. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: backButton), space, UIBarButtonItem(customView: profileButton)], animated: true)
  173. navigationItem.title = ""
  174. }
  175. }
  176. // MARK: - Empty
  177. func emptyDataSetView(_ view: NCEmptyView) {
  178. if networkInProgress {
  179. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  180. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  181. view.emptyDescription.text = ""
  182. } else {
  183. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  184. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  185. view.emptyDescription.text = ""
  186. }
  187. }
  188. // MARK: ACTION
  189. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  190. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  191. }
  192. @IBAction func actionCreateFolder(_ sender: UIButton) {
  193. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  194. alertController.addTextField { (textField) in
  195. textField.autocapitalizationType = UITextAutocapitalizationType.words
  196. }
  197. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  198. if let fileName = alertController.textFields?.first?.text {
  199. self.createFolder(with: fileName)
  200. }
  201. }
  202. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  203. print("You've pressed cancel button")
  204. }
  205. alertController.addAction(actionSave)
  206. alertController.addAction(actionCancel)
  207. self.present(alertController, animated: true, completion:nil)
  208. }
  209. @IBAction func actionUpload(_ sender: UIButton) {
  210. }
  211. @objc func backButtonTapped(sender: Any) {
  212. while serverUrl.last != "/" {
  213. serverUrl.removeLast()
  214. }
  215. serverUrl.removeLast()
  216. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  217. reloadDatasource(withLoadFolder: true)
  218. setNavigationBar()
  219. }
  220. @objc func profileButtonTapped(sender: Any) {
  221. }
  222. func tapShareListItem(with objectId: String, sender: Any) {
  223. }
  224. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  225. }
  226. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  227. }
  228. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  229. }
  230. }
  231. // MARK: - Collection View
  232. extension NCShareExtension: UICollectionViewDelegate {
  233. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  234. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  235. guard let serverUrlTemp = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  236. serverUrl = serverUrlTemp
  237. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  238. reloadDatasource(withLoadFolder: true)
  239. setNavigationBar()
  240. }
  241. }
  242. extension NCShareExtension: UICollectionViewDataSource {
  243. func numberOfSections(in collectionView: UICollectionView) -> Int {
  244. return 1
  245. }
  246. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  247. let numberOfItems = dataSource.numberOfItems()
  248. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  249. return numberOfItems
  250. }
  251. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  252. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  253. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  254. }
  255. var tableShare: tableShare?
  256. var isShare = false
  257. var isMounted = false
  258. // Download preview
  259. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  260. if let metadataFolder = metadataFolder {
  261. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  262. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  263. }
  264. if dataSource.metadataShare[metadata.ocId] != nil {
  265. tableShare = dataSource.metadataShare[metadata.ocId]
  266. }
  267. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  268. cell.delegate = self
  269. cell.objectId = metadata.ocId
  270. cell.indexPath = indexPath
  271. cell.labelTitle.text = metadata.fileNameView
  272. cell.labelTitle.textColor = NCBrandColor.shared.textView
  273. cell.separator.backgroundColor = NCBrandColor.shared.separator
  274. cell.imageSelect.image = nil
  275. cell.imageStatus.image = nil
  276. cell.imageLocal.image = nil
  277. cell.imageFavorite.image = nil
  278. cell.imageShared.image = nil
  279. cell.imageMore.image = nil
  280. cell.imageItem.image = nil
  281. cell.imageItem.backgroundColor = nil
  282. cell.progressView.progress = 0.0
  283. if metadata.directory {
  284. if metadata.e2eEncrypted {
  285. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  286. } else if isShare {
  287. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  288. } else if (tableShare != nil && tableShare?.shareType != 3) {
  289. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  290. } else if (tableShare != nil && tableShare?.shareType == 3) {
  291. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  292. } else if metadata.mountType == "group" {
  293. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  294. } else if isMounted {
  295. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  296. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  297. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  298. } else {
  299. cell.imageItem.image = NCBrandColor.cacheImages.folder
  300. }
  301. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  302. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  303. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  304. // Local image: offline
  305. if tableDirectory != nil && tableDirectory!.offline {
  306. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  307. }
  308. } else {
  309. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  310. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  311. } else {
  312. if metadata.hasPreview {
  313. cell.imageItem.backgroundColor = .lightGray
  314. } else {
  315. if metadata.iconName.count > 0 {
  316. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  317. } else {
  318. cell.imageItem.image = NCBrandColor.cacheImages.file
  319. }
  320. }
  321. }
  322. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  323. // image local
  324. if dataSource.metadataOffLine.contains(metadata.ocId) {
  325. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  326. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  327. cell.imageLocal.image = NCBrandColor.cacheImages.local
  328. }
  329. }
  330. // image Favorite
  331. if metadata.favorite {
  332. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  333. }
  334. // Share image
  335. if (isShare) {
  336. cell.imageShared.image = NCBrandColor.cacheImages.shared
  337. } else if (tableShare != nil && tableShare?.shareType == 3) {
  338. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  339. } else if (tableShare != nil && tableShare?.shareType != 3) {
  340. cell.imageShared.image = NCBrandColor.cacheImages.shared
  341. } else {
  342. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  343. }
  344. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  345. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  346. if FileManager.default.fileExists(atPath: fileNameUser) {
  347. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  348. } else {
  349. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  350. if errorCode == 0 && account == self.activeAccount.account {
  351. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  352. }
  353. }
  354. }
  355. }
  356. cell.imageSelect.isHidden = true
  357. cell.backgroundView = nil
  358. cell.hideButtonMore(true)
  359. cell.hideButtonShare(true)
  360. cell.selectMode(false)
  361. // Live Photo
  362. if metadata.livePhoto {
  363. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  364. }
  365. // Remove last separator
  366. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  367. cell.separator.isHidden = true
  368. } else {
  369. cell.separator.isHidden = false
  370. }
  371. return cell
  372. }
  373. }
  374. extension NCShareExtension: UITableViewDelegate {
  375. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  376. return 50
  377. }
  378. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  379. }
  380. }
  381. extension NCShareExtension: UITableViewDataSource {
  382. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  383. filesName.count
  384. }
  385. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  386. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
  387. let imageCell = cell.viewWithTag(10) as? UIImageView
  388. let fileNameCell = cell.viewWithTag(20) as? UILabel
  389. let fileName = filesName[indexPath.row]
  390. imageCell?.image = NCUtility.shared.loadImage(named: "file")
  391. if let image = UIImage(contentsOfFile: (NSTemporaryDirectory() + fileName)) {
  392. imageCell?.image = image
  393. }
  394. fileNameCell?.text = fileName
  395. return cell
  396. }
  397. }
  398. // MARK: - NC API & Algorithm
  399. extension NCShareExtension {
  400. @objc func reloadDatasource(withLoadFolder: Bool) {
  401. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  402. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  403. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: sort, ascending: ascending, directoryOnTop: directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  404. if withLoadFolder {
  405. loadFolder()
  406. } else {
  407. self.refreshControl.endRefreshing()
  408. }
  409. collectionView.reloadData()
  410. }
  411. func createFolder(with fileName: String) {
  412. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  413. if errorCode == 0 {
  414. self.reloadDatasource(withLoadFolder: true)
  415. } else {
  416. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  417. }
  418. }
  419. }
  420. func loadFolder() {
  421. networkInProgress = true
  422. collectionView.reloadData()
  423. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, metadataFolder, _, _, _, errorCode, errorDescription) in
  424. if errorCode != 0 {
  425. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  426. }
  427. self.networkInProgress = false
  428. self.metadataFolder = metadataFolder
  429. self.reloadDatasource(withLoadFolder: false)
  430. }
  431. }
  432. func getFilesExtensionContext(completion: @escaping (_ filesName: [String], _ error: Error?)->()) {
  433. var filesName: [String] = []
  434. var conuter = 0
  435. var outError: Error? = nil
  436. CCUtility.emptyTemporaryDirectory()
  437. if let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] {
  438. for item : NSExtensionItem in inputItems {
  439. if let attachments = item.attachments {
  440. if attachments.isEmpty {
  441. extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  442. completion(filesName, outError)
  443. return
  444. }
  445. for (index, current) in (attachments.enumerated()) {
  446. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || current.hasItemConformingToTypeIdentifier("public.url") {
  447. var typeIdentifier = ""
  448. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  449. if current.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  450. current.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  451. var fileNameOriginal: String?
  452. var fileName: String = ""
  453. let dateFormatter = DateFormatter()
  454. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  455. conuter += 1
  456. if let url = item as? NSURL {
  457. fileNameOriginal = url.lastPathComponent!
  458. }
  459. if error == nil {
  460. if let image = item as? UIImage {
  461. print("item as UIImage")
  462. if let pngImageData = image.pngData() {
  463. if fileNameOriginal != nil {
  464. fileName = fileNameOriginal!
  465. } else {
  466. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  467. }
  468. let filenamePath = NSTemporaryDirectory() + fileName
  469. let result = (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil
  470. if result {
  471. filesName.append(fileName)
  472. }
  473. } else {
  474. print("Error image nil")
  475. }
  476. }
  477. if let url = item as? URL {
  478. print("item as url: \(String(describing: item))")
  479. if fileNameOriginal != nil {
  480. fileName = fileNameOriginal!
  481. } else {
  482. let ext = url.pathExtension
  483. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  484. }
  485. let filenamePath = NSTemporaryDirectory() + fileName
  486. do {
  487. try FileManager.default.removeItem(atPath: filenamePath)
  488. }
  489. catch { }
  490. do {
  491. try FileManager.default.copyItem(atPath: url.path, toPath:filenamePath)
  492. do {
  493. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  494. if let _attr = attr {
  495. if _attr.fileSize() > 0 {
  496. filesName.append(fileName)
  497. }
  498. }
  499. } catch let error {
  500. outError = error
  501. }
  502. } catch let error {
  503. outError = error
  504. }
  505. }
  506. if let data = item as? Data {
  507. if data.count > 0 {
  508. print("item as NSdata")
  509. if fileNameOriginal != nil {
  510. fileName = fileNameOriginal!
  511. } else {
  512. let description = current.description
  513. let fullNameArr = description.components(separatedBy: "\"")
  514. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  515. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  516. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  517. }
  518. let filenamePath = NSTemporaryDirectory() + fileName
  519. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  520. filesName.append(fileName)
  521. }
  522. }
  523. if let data = item as? NSString {
  524. if data.length > 0 {
  525. print("item as NSString")
  526. let fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  527. let filenamePath = NSTemporaryDirectory() + fileName
  528. FileManager.default.createFile(atPath: filenamePath, contents:data.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  529. filesName.append(fileName)
  530. }
  531. }
  532. if index + 1 == attachments.count {
  533. completion(filesName, outError)
  534. }
  535. } else {
  536. completion( filesName, error)
  537. }
  538. })
  539. }
  540. } // end for
  541. } else {
  542. completion(filesName, outError)
  543. }
  544. }
  545. } else {
  546. completion(filesName, outError)
  547. }
  548. }
  549. }