NCShareExtension.swift 39 KB

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