NCShareExtension.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. @IBOutlet weak var buttonCancel: UIBarButtonItem!
  28. // -------------------------------------------------------------
  29. var titleCurrentFolder = NCBrandOptions.shared.brand
  30. var serverUrl = ""
  31. var filesName: [String] = []
  32. // -------------------------------------------------------------
  33. private var emptyDataSet: NCEmptyDataSet?
  34. private let keyLayout = NCGlobal.shared.layoutViewShareExtension
  35. private var serverUrlPush = ""
  36. private var metadataTouch: tableMetadata?
  37. private var metadataFolder = tableMetadata()
  38. private var networkInProgress = false
  39. private var dataSource = NCDataSource()
  40. internal var richWorkspaceText: String?
  41. private var sort: String = ""
  42. private var ascending: Bool = true
  43. private var directoryOnTop: Bool = true
  44. private var layout = ""
  45. private var groupBy = ""
  46. private var titleButton = ""
  47. private var itemForLine = 0
  48. private var autoUploadFileName = ""
  49. private var autoUploadDirectory = ""
  50. private var listLayout: NCListLayout!
  51. private var gridLayout: NCGridLayout!
  52. private let headerHeight: CGFloat = 50
  53. private var headerRichWorkspaceHeight: CGFloat = 0
  54. private let footerHeight: CGFloat = 100
  55. private var shares: [tableShare]?
  56. private let refreshControl = UIRefreshControl()
  57. private var activeAccount: tableAccount!
  58. override func viewDidLoad() {
  59. super.viewDidLoad()
  60. self.navigationController?.navigationBar.prefersLargeTitles = true
  61. // Cell
  62. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  63. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  64. // Header
  65. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  66. // Footer
  67. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  68. collectionView.alwaysBounceVertical = true
  69. listLayout = NCListLayout()
  70. gridLayout = NCGridLayout()
  71. // Add Refresh Control
  72. collectionView.addSubview(refreshControl)
  73. refreshControl.tintColor = NCBrandColor.shared.brandText
  74. refreshControl.backgroundColor = NCBrandColor.shared.backgroundView
  75. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  76. // Empty
  77. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  78. }
  79. override func viewWillAppear(_ animated: Bool) {
  80. super.viewWillAppear(animated)
  81. guard let account = NCManageDatabase.shared.getAccountActive() else {
  82. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  83. return
  84. }
  85. self.activeAccount = account
  86. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  87. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  88. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  89. // LOG
  90. let levelLog = CCUtility.getLogLevel()
  91. NCCommunicationCommon.shared.levelLog = levelLog
  92. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  93. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  94. }
  95. if isSimulatorOrTestFlight {
  96. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  97. } else {
  98. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  99. }
  100. // NETWORKING
  101. 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)
  102. self.navigationItem.title = titleCurrentFolder
  103. // get auto upload folder
  104. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  105. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  106. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  107. gridLayout.itemForLine = CGFloat(itemForLine)
  108. if layout == NCGlobal.shared.layoutList {
  109. collectionView.collectionViewLayout = listLayout
  110. } else {
  111. collectionView.collectionViewLayout = gridLayout
  112. }
  113. // Load data source
  114. if serverUrl == "" {
  115. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account)
  116. // ROOT load files
  117. loadFiles(NSTemporaryDirectory()) { (filesName, error) in
  118. self.filesName = filesName
  119. if filesName.count == 0 {
  120. self.extensionContext?.completeRequest(returningItems: self.extensionContext?.inputItems, completionHandler: nil)
  121. return
  122. } else {
  123. self.loadDatasource(withLoadFolder: true)
  124. }
  125. }
  126. } else {
  127. loadDatasource(withLoadFolder: true)
  128. }
  129. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  130. }
  131. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  132. super.viewWillTransition(to: size, with: coordinator)
  133. coordinator.animate(alongsideTransition: nil) { _ in
  134. self.collectionView?.collectionViewLayout.invalidateLayout()
  135. }
  136. }
  137. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  138. super.traitCollectionDidChange(previousTraitCollection)
  139. if traitCollection.userInterfaceStyle == .dark {
  140. } else {
  141. }
  142. }
  143. // MARK: - Empty
  144. func emptyDataSetView(_ view: NCEmptyView) {
  145. if networkInProgress {
  146. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  147. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  148. view.emptyDescription.text = ""
  149. } else {
  150. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  151. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  152. view.emptyDescription.text = ""
  153. }
  154. }
  155. // MARK: ACTION
  156. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  157. extensionContext?.completeRequest(returningItems: extensionContext?.inputItems, completionHandler: nil)
  158. }
  159. func createFolderButtonPressed(_ sender: UIButton) {
  160. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  161. alertController.addTextField { (textField) in
  162. textField.autocapitalizationType = UITextAutocapitalizationType.words
  163. }
  164. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  165. if let fileName = alertController.textFields?.first?.text {
  166. self.createFolder(with: fileName)
  167. }
  168. }
  169. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  170. print("You've pressed cancel button")
  171. }
  172. alertController.addAction(actionSave)
  173. alertController.addAction(actionCancel)
  174. self.present(alertController, animated: true, completion:nil)
  175. }
  176. // MARK: TAP EVENT
  177. func tapSwitchHeader(sender: Any) {
  178. if collectionView.collectionViewLayout == gridLayout {
  179. // list layout
  180. UIView.animate(withDuration: 0.0, animations: {
  181. self.collectionView.collectionViewLayout.invalidateLayout()
  182. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  183. self.collectionView.reloadData()
  184. })
  185. })
  186. layout = NCGlobal.shared.layoutList
  187. } else {
  188. // grid layout
  189. UIView.animate(withDuration: 0.0, animations: {
  190. self.collectionView.collectionViewLayout.invalidateLayout()
  191. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  192. self.collectionView.reloadData()
  193. })
  194. })
  195. layout = NCGlobal.shared.layoutGrid
  196. }
  197. }
  198. func tapOrderHeader(sender: Any) {
  199. let sortMenu = NCSortMenu()
  200. sortMenu.toggleMenu(viewController: self, key: keyLayout, sortButton: sender as? UIButton, serverUrl: serverUrl)
  201. }
  202. func tapMoreHeader(sender: Any) {
  203. }
  204. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  205. }
  206. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  207. }
  208. func tapShareListItem(with objectId: String, sender: Any) {
  209. }
  210. func tapRichWorkspace(sender: Any) {
  211. }
  212. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  213. }
  214. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  215. }
  216. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  217. }
  218. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  219. }
  220. }
  221. // MARK: - Collection View
  222. extension NCShareExtension: UICollectionViewDelegate {
  223. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  224. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  225. if metadata.directory {
  226. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  227. guard let viewController = UIStoryboard(name: "MainInterface", bundle: nil).instantiateViewController(withIdentifier: "NCShareExtension.storyboard") as? NCShareExtension else { return }
  228. self.serverUrlPush = serverUrlPush
  229. self.metadataTouch = metadata
  230. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  231. viewController.serverUrl = serverUrlPush
  232. viewController.filesName = filesName
  233. self.navigationController?.pushViewController(viewController, animated: true)
  234. }
  235. }
  236. }
  237. extension NCShareExtension: UICollectionViewDataSource {
  238. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  239. if kind == UICollectionView.elementKindSectionHeader {
  240. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  241. if collectionView.collectionViewLayout == gridLayout {
  242. header.buttonSwitch.setImage(UIImage.init(named: "switchList")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  243. } else {
  244. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  245. }
  246. header.delegate = self
  247. header.setStatusButton(count: dataSource.metadatas.count)
  248. header.setTitleSorted(datasourceTitleButton: titleButton)
  249. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  250. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  251. return header
  252. } else {
  253. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  254. let info = dataSource.getFilesInformation()
  255. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  256. return footer
  257. }
  258. }
  259. func numberOfSections(in collectionView: UICollectionView) -> Int {
  260. return 1
  261. }
  262. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  263. let numberOfItems = dataSource.numberOfItems()
  264. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  265. return numberOfItems
  266. }
  267. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  268. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  269. if layout == NCGlobal.shared.layoutList {
  270. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  271. } else {
  272. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  273. }
  274. }
  275. var tableShare: tableShare?
  276. var isShare = false
  277. var isMounted = false
  278. // Download preview
  279. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  280. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  281. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  282. if dataSource.metadataShare[metadata.ocId] != nil {
  283. tableShare = dataSource.metadataShare[metadata.ocId]
  284. }
  285. // LAYOUT LIST
  286. if layout == NCGlobal.shared.layoutList {
  287. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  288. cell.delegate = self
  289. cell.objectId = metadata.ocId
  290. cell.indexPath = indexPath
  291. cell.labelTitle.text = metadata.fileNameView
  292. cell.labelTitle.textColor = NCBrandColor.shared.textView
  293. cell.separator.backgroundColor = NCBrandColor.shared.separator
  294. cell.imageSelect.image = nil
  295. cell.imageStatus.image = nil
  296. cell.imageLocal.image = nil
  297. cell.imageFavorite.image = nil
  298. cell.imageShared.image = nil
  299. cell.imageMore.image = nil
  300. cell.imageItem.image = nil
  301. cell.imageItem.backgroundColor = nil
  302. cell.progressView.progress = 0.0
  303. if metadata.directory {
  304. if metadata.e2eEncrypted {
  305. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  306. } else if isShare {
  307. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  308. } else if (tableShare != nil && tableShare?.shareType != 3) {
  309. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  310. } else if (tableShare != nil && tableShare?.shareType == 3) {
  311. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  312. } else if metadata.mountType == "group" {
  313. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  314. } else if isMounted {
  315. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  316. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  317. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  318. } else {
  319. cell.imageItem.image = NCBrandColor.cacheImages.folder
  320. }
  321. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  322. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  323. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  324. // Local image: offline
  325. if tableDirectory != nil && tableDirectory!.offline {
  326. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  327. }
  328. } else {
  329. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  330. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  331. } else {
  332. if metadata.hasPreview {
  333. cell.imageItem.backgroundColor = .lightGray
  334. } else {
  335. if metadata.iconName.count > 0 {
  336. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  337. } else {
  338. cell.imageItem.image = NCBrandColor.cacheImages.file
  339. }
  340. }
  341. }
  342. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  343. // image local
  344. if dataSource.metadataOffLine.contains(metadata.ocId) {
  345. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  346. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  347. cell.imageLocal.image = NCBrandColor.cacheImages.local
  348. }
  349. }
  350. // image Favorite
  351. if metadata.favorite {
  352. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  353. }
  354. // Share image
  355. if (isShare) {
  356. cell.imageShared.image = NCBrandColor.cacheImages.shared
  357. } else if (tableShare != nil && tableShare?.shareType == 3) {
  358. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  359. } else if (tableShare != nil && tableShare?.shareType != 3) {
  360. cell.imageShared.image = NCBrandColor.cacheImages.shared
  361. } else {
  362. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  363. }
  364. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  365. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  366. if FileManager.default.fileExists(atPath: fileNameUser) {
  367. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  368. } else {
  369. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  370. if errorCode == 0 && account == self.activeAccount.account {
  371. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  372. }
  373. }
  374. }
  375. }
  376. cell.imageSelect.isHidden = true
  377. cell.backgroundView = nil
  378. cell.hideButtonMore(true)
  379. cell.hideButtonShare(true)
  380. cell.selectMode(false)
  381. // Live Photo
  382. if metadata.livePhoto {
  383. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  384. }
  385. // Remove last separator
  386. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  387. cell.separator.isHidden = true
  388. } else {
  389. cell.separator.isHidden = false
  390. }
  391. return cell
  392. }
  393. // LAYOUT GRID
  394. if layout == NCGlobal.shared.layoutGrid {
  395. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  396. cell.delegate = self
  397. cell.objectId = metadata.ocId
  398. cell.indexPath = indexPath
  399. cell.labelTitle.text = metadata.fileNameView
  400. cell.labelTitle.textColor = NCBrandColor.shared.textView
  401. cell.imageSelect.image = nil
  402. cell.imageStatus.image = nil
  403. cell.imageLocal.image = nil
  404. cell.imageFavorite.image = nil
  405. cell.imageItem.image = nil
  406. cell.imageItem.backgroundColor = nil
  407. cell.progressView.progress = 0.0
  408. if metadata.directory {
  409. if metadata.e2eEncrypted {
  410. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  411. } else if isShare {
  412. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  413. } else if (tableShare != nil && tableShare!.shareType != 3) {
  414. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  415. } else if (tableShare != nil && tableShare!.shareType == 3) {
  416. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  417. } else if metadata.mountType == "group" {
  418. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  419. } else if isMounted {
  420. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  421. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  422. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  423. } else {
  424. cell.imageItem.image = NCBrandColor.cacheImages.folder
  425. }
  426. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  427. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  428. // Local image: offline
  429. if tableDirectory != nil && tableDirectory!.offline {
  430. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  431. }
  432. } else {
  433. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  434. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  435. } else {
  436. if metadata.hasPreview {
  437. cell.imageItem.backgroundColor = .lightGray
  438. } else {
  439. if metadata.iconName.count > 0 {
  440. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  441. } else {
  442. cell.imageItem.image = NCBrandColor.cacheImages.file
  443. }
  444. }
  445. }
  446. // image Local
  447. if dataSource.metadataOffLine.contains(metadata.ocId) {
  448. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  449. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  450. cell.imageLocal.image = NCBrandColor.cacheImages.local
  451. }
  452. }
  453. // image Favorite
  454. if metadata.favorite {
  455. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  456. }
  457. cell.imageSelect.isHidden = true
  458. cell.backgroundView = nil
  459. cell.hideButtonMore(true)
  460. // Live Photo
  461. if metadata.livePhoto {
  462. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  463. }
  464. return cell
  465. }
  466. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  467. }
  468. }
  469. extension NCShareExtension: UICollectionViewDelegateFlowLayout {
  470. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  471. headerRichWorkspaceHeight = 0
  472. if let richWorkspaceText = richWorkspaceText {
  473. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  474. if trimmed.count > 0 {
  475. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  476. }
  477. }
  478. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  479. }
  480. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  481. return CGSize(width: collectionView.frame.width, height: footerHeight)
  482. }
  483. }
  484. // MARK: - NC API & Algorithm
  485. extension NCShareExtension {
  486. @objc func reloadDataSource() {
  487. loadDatasource(withLoadFolder: false)
  488. }
  489. @objc func loadDatasource(withLoadFolder: Bool) {
  490. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  491. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl))
  492. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: sort, ascending: ascending, directoryOnTop: directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  493. if withLoadFolder {
  494. loadFolder()
  495. } else {
  496. self.refreshControl.endRefreshing()
  497. }
  498. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account,serverUrl))
  499. richWorkspaceText = directory?.richWorkspace
  500. collectionView.reloadData()
  501. }
  502. func createFolder(with fileName: String) {
  503. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  504. if errorCode == 0 {
  505. self.loadDatasource(withLoadFolder: true)
  506. } else {
  507. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  508. }
  509. }
  510. }
  511. func loadFolder() {
  512. networkInProgress = true
  513. collectionView.reloadData()
  514. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, _, _, _, _, errorCode, errorDescription) in
  515. if errorCode != 0 {
  516. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  517. }
  518. self.networkInProgress = false
  519. self.loadDatasource(withLoadFolder: false)
  520. }
  521. }
  522. func loadFiles(_ directory: String, completion: @escaping (_ filesName: [String], _ error: Error?)->()) {
  523. var filesName: [String] = []
  524. var conuter = 0
  525. var outError: Error? = nil
  526. CCUtility.emptyTemporaryDirectory()
  527. if let inputItems : [NSExtensionItem] = extensionContext?.inputItems as? [NSExtensionItem] {
  528. for item : NSExtensionItem in inputItems {
  529. if let attachments = item.attachments {
  530. if attachments.isEmpty {
  531. extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  532. completion(filesName, outError)
  533. return
  534. }
  535. for (index, current) in (attachments.enumerated()) {
  536. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) || current.hasItemConformingToTypeIdentifier("public.url") {
  537. var typeIdentifier = ""
  538. if current.hasItemConformingToTypeIdentifier(kUTTypeItem as String) { typeIdentifier = kUTTypeItem as String }
  539. if current.hasItemConformingToTypeIdentifier("public.url") { typeIdentifier = "public.url" }
  540. current.loadItem(forTypeIdentifier: typeIdentifier, options: nil, completionHandler: {(item, error) -> Void in
  541. var fileNameOriginal: String?
  542. var fileName: String = ""
  543. let dateFormatter = DateFormatter()
  544. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss-"
  545. conuter += 1
  546. if let url = item as? NSURL {
  547. fileNameOriginal = url.lastPathComponent!
  548. }
  549. if error == nil {
  550. if let image = item as? UIImage {
  551. print("item as UIImage")
  552. if let pngImageData = image.pngData() {
  553. if fileNameOriginal != nil {
  554. fileName = fileNameOriginal!
  555. } else {
  556. fileName = "\(dateFormatter.string(from: Date()))\(conuter).png"
  557. }
  558. let filenamePath = directory + fileName
  559. let result = (try? pngImageData.write(to: URL(fileURLWithPath: filenamePath), options: [.atomic])) != nil
  560. if result {
  561. filesName.append(fileName)
  562. }
  563. } else {
  564. print("Error image nil")
  565. }
  566. }
  567. if let url = item as? URL {
  568. print("item as url: \(String(describing: item))")
  569. if fileNameOriginal != nil {
  570. fileName = fileNameOriginal!
  571. } else {
  572. let ext = url.pathExtension
  573. fileName = "\(dateFormatter.string(from: Date()))\(conuter)." + ext
  574. }
  575. let filenamePath = directory + fileName
  576. do {
  577. try FileManager.default.removeItem(atPath: filenamePath)
  578. }
  579. catch { }
  580. do {
  581. try FileManager.default.copyItem(atPath: url.path, toPath:filenamePath)
  582. do {
  583. let attr : NSDictionary? = try FileManager.default.attributesOfItem(atPath: filenamePath) as NSDictionary?
  584. if let _attr = attr {
  585. if _attr.fileSize() > 0 {
  586. filesName.append(fileName)
  587. }
  588. }
  589. } catch let error {
  590. outError = error
  591. }
  592. } catch let error {
  593. outError = error
  594. }
  595. }
  596. if let data = item as? Data {
  597. if data.count > 0 {
  598. print("item as NSdata")
  599. if fileNameOriginal != nil {
  600. fileName = fileNameOriginal!
  601. } else {
  602. let description = current.description
  603. let fullNameArr = description.components(separatedBy: "\"")
  604. let fileExtArr = fullNameArr[1].components(separatedBy: ".")
  605. let pathExtention = (fileExtArr[fileExtArr.count-1]).uppercased()
  606. fileName = "\(dateFormatter.string(from: Date()))\(conuter).\(pathExtention)"
  607. }
  608. let filenamePath = directory + fileName
  609. FileManager.default.createFile(atPath: filenamePath, contents:data, attributes:nil)
  610. filesName.append(fileName)
  611. }
  612. }
  613. if let data = item as? NSString {
  614. if data.length > 0 {
  615. print("item as NSString")
  616. let fileName = "\(dateFormatter.string(from: Date()))\(conuter).txt"
  617. let filenamePath = directory + fileName
  618. FileManager.default.createFile(atPath: filenamePath, contents:data.data(using: String.Encoding.utf8.rawValue), attributes:nil)
  619. filesName.append(fileName)
  620. }
  621. }
  622. if index + 1 == attachments.count {
  623. completion(filesName, outError)
  624. }
  625. } else {
  626. completion( filesName, error)
  627. }
  628. })
  629. }
  630. } // end for
  631. } else {
  632. completion(filesName, outError)
  633. }
  634. }
  635. } else {
  636. completion(filesName, outError)
  637. }
  638. }
  639. }