NCShare.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. //
  2. // NCShare.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 17/07/2019.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import UIKit
  25. import Parchment
  26. import DropDown
  27. import NCCommunication
  28. import MarqueeLabel
  29. class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareNetworkingDelegate {
  30. @IBOutlet weak var viewContainerConstraint: NSLayoutConstraint!
  31. @IBOutlet weak var sharedWithYouByView: UIView!
  32. @IBOutlet weak var sharedWithYouByImage: UIImageView!
  33. @IBOutlet weak var sharedWithYouByLabel: UILabel!
  34. @IBOutlet weak var sharedWithYouByNoteImage: UIImageView!
  35. @IBOutlet weak var sharedWithYouByNote: MarqueeLabel!
  36. @IBOutlet weak var searchFieldTopConstraint: NSLayoutConstraint!
  37. @IBOutlet weak var searchField: UITextField!
  38. @IBOutlet weak var tableView: UITableView!
  39. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  40. public var metadata: tableMetadata?
  41. public var sharingEnabled = true
  42. public var height: CGFloat = 0
  43. var shares: (firstShareLink: tableShare?, share: [tableShare]?) = (nil, nil)
  44. private var shareLinkMenuView: NCShareLinkMenuView?
  45. private var shareUserMenuView: NCShareUserMenuView?
  46. private var shareMenuViewWindow: UIView?
  47. private var dropDown = DropDown()
  48. private var networking: NCShareNetworking?
  49. // MARK: - View Life Cycle
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. view.backgroundColor = NCBrandColor.shared.systemBackground
  53. viewContainerConstraint.constant = height
  54. searchFieldTopConstraint.constant = 10
  55. searchField.placeholder = NSLocalizedString("_shareLinksearch_placeholder_", comment: "")
  56. tableView.dataSource = self
  57. tableView.delegate = self
  58. tableView.allowsSelection = false
  59. tableView.backgroundColor = NCBrandColor.shared.systemBackground
  60. tableView.register(UINib(nibName: "NCShareLinkCell", bundle: nil), forCellReuseIdentifier: "cellLink")
  61. tableView.register(UINib(nibName: "NCShareUserCell", bundle: nil), forCellReuseIdentifier: "cellUser")
  62. NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataNCShare), object: nil)
  63. // Shared with you by ...
  64. if let metadata = metadata, !metadata.ownerId.isEmpty, metadata.ownerId != self.appDelegate.userId {
  65. searchFieldTopConstraint.constant = 65
  66. sharedWithYouByView.isHidden = false
  67. sharedWithYouByLabel.text = NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName
  68. sharedWithYouByImage.image = NCUtility.shared.loadUserImage(
  69. for: metadata.ownerId,
  70. displayName: metadata.ownerDisplayName,
  71. userBaseUrl: appDelegate)
  72. let shareAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  73. sharedWithYouByImage.addGestureRecognizer(shareAction)
  74. let shareLabelAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  75. sharedWithYouByLabel.addGestureRecognizer(shareLabelAction)
  76. if metadata.note.count > 0 {
  77. searchFieldTopConstraint.constant = 95
  78. sharedWithYouByNoteImage.isHidden = false
  79. sharedWithYouByNoteImage.image = NCUtility.shared.loadImage(named: "note.text", color: .gray)
  80. sharedWithYouByNote.isHidden = false
  81. sharedWithYouByNote.text = metadata.note
  82. sharedWithYouByNote.textColor = NCBrandColor.shared.label
  83. sharedWithYouByNote.trailingBuffer = sharedWithYouByNote.frame.width
  84. } else {
  85. sharedWithYouByNoteImage.isHidden = true
  86. sharedWithYouByNote.isHidden = true
  87. }
  88. let fileName = appDelegate.userBaseUrl + "-" + metadata.ownerId + ".png"
  89. if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil {
  90. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  91. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  92. NCCommunication.shared.downloadAvatar(user: metadata.ownerId, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag) { _, imageAvatar, _, etag, errorCode, _ in
  93. if errorCode == 0, let etag = etag, let imageAvatar = imageAvatar {
  94. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  95. self.sharedWithYouByImage.image = imageAvatar
  96. } else if errorCode == NCGlobal.shared.errorNotModified, let imageAvatar = NCManageDatabase.shared.setAvatarLoaded(fileName: fileName) {
  97. self.sharedWithYouByImage.image = imageAvatar
  98. }
  99. }
  100. }
  101. }
  102. reloadData()
  103. networking = NCShareNetworking(metadata: metadata!, urlBase: appDelegate.urlBase, view: self.view, delegate: self)
  104. if sharingEnabled {
  105. let isVisible = (self.navigationController?.topViewController as? NCSharePaging)?.indexPage == .sharing
  106. networking?.readShare(showLoadingIndicator: isVisible)
  107. }
  108. // changeTheming
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(changePermissions(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterShareChangePermissions), object: nil)
  111. changeTheming()
  112. }
  113. // MARK: - Notification Center
  114. @objc func openShareProfile() {
  115. guard let metadata = metadata else { return }
  116. self.showProfileMenu(userId: metadata.ownerId)
  117. }
  118. @objc func changeTheming() {
  119. tableView.reloadData()
  120. }
  121. @objc func changePermissions(_ notification: NSNotification) {
  122. if let userInfo = notification.userInfo as NSDictionary? {
  123. if let idShare = userInfo["idShare"] as? Int, let permissions = userInfo["permissions"] as? Int, let hideDownload = userInfo["hideDownload"] as? Bool {
  124. networking?.updateShare(idShare: idShare, password: nil, permissions: permissions, note: nil, label: nil, expirationDate: nil, hideDownload: hideDownload)
  125. }
  126. }
  127. }
  128. // MARK: -
  129. @objc func reloadData() {
  130. shares = NCManageDatabase.shared.getTableShares(metadata: metadata!)
  131. tableView.reloadData()
  132. }
  133. // MARK: - IBAction
  134. @IBAction func searchFieldDidEndOnExit(textField: UITextField) {
  135. guard let searchString = textField.text else { return }
  136. networking?.getSharees(searchString: searchString)
  137. }
  138. func checkEnforcedPassword(callback: @escaping (String?) -> Void) {
  139. guard let metadata = self.metadata,
  140. NCManageDatabase.shared.getCapabilitiesServerBool(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesFileSharingPubPasswdEnforced, exists: false)
  141. else { return callback(nil) }
  142. let alertController = UIAlertController(title: NSLocalizedString("_enforce_password_protection_", comment: ""), message: "", preferredStyle: .alert)
  143. alertController.addTextField { textField in
  144. textField.isSecureTextEntry = true
  145. }
  146. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { _ in })
  147. let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { _ in
  148. let password = alertController.textFields?.first?.text
  149. callback(password)
  150. }
  151. alertController.addAction(okAction)
  152. self.present(alertController, animated: true, completion:nil)
  153. }
  154. @objc func tapLinkMenuViewWindow(gesture: UITapGestureRecognizer) {
  155. shareLinkMenuView?.unLoad()
  156. shareLinkMenuView = nil
  157. shareUserMenuView?.unLoad()
  158. shareUserMenuView = nil
  159. }
  160. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
  161. return gestureRecognizer.view == touch.view
  162. }
  163. // MARK: - NCShareNetworkingDelegate
  164. func readShareCompleted() {
  165. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  166. }
  167. func shareCompleted() {
  168. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  169. }
  170. func unShareCompleted() { }
  171. func updateShareWithError(idShare: Int) {
  172. self.reloadData()
  173. }
  174. func getSharees(sharees: [NCCommunicationSharee]?) {
  175. guard let sharees = sharees else { return }
  176. dropDown = DropDown()
  177. let appearance = DropDown.appearance()
  178. appearance.backgroundColor = NCBrandColor.shared.systemBackground
  179. appearance.cornerRadius = 10
  180. appearance.shadowColor = UIColor(white: 0.5, alpha: 1)
  181. appearance.shadowOpacity = 0.9
  182. appearance.shadowRadius = 25
  183. appearance.animationduration = 0.25
  184. appearance.textColor = .darkGray
  185. appearance.setupMaskedCorners([.layerMaxXMaxYCorner, .layerMinXMaxYCorner])
  186. for sharee in sharees {
  187. var label = sharee.label
  188. if sharee.shareType == NCShareCommon.shared.SHARE_TYPE_CIRCLE {
  189. label += " (" + sharee.circleInfo + ", " + sharee.circleOwner + ")"
  190. }
  191. dropDown.dataSource.append(label)
  192. }
  193. dropDown.anchorView = searchField
  194. dropDown.bottomOffset = CGPoint(x: 0, y: searchField.bounds.height)
  195. dropDown.width = searchField.bounds.width
  196. dropDown.direction = .bottom
  197. dropDown.cellNib = UINib(nibName: "NCShareUserDropDownCell", bundle: nil)
  198. dropDown.customCellConfiguration = { (index: Index, _: String, cell: DropDownCell) -> Void in
  199. guard let cell = cell as? NCShareUserDropDownCell else { return }
  200. let sharee = sharees[index]
  201. cell.imageItem.image = NCShareCommon.shared.getImageShareType(shareType: sharee.shareType)
  202. cell.imageShareeType.image = NCShareCommon.shared.getImageShareType(shareType: sharee.shareType)
  203. let status = NCUtility.shared.getUserStatus(userIcon: sharee.userIcon, userStatus: sharee.userStatus, userMessage: sharee.userMessage)
  204. cell.imageStatus.image = status.onlineStatus
  205. cell.status.text = status.statusMessage
  206. if cell.status.text?.count ?? 0 > 0 {
  207. cell.centerTitle.constant = -5
  208. } else {
  209. cell.centerTitle.constant = 0
  210. }
  211. cell.imageItem.image = NCUtility.shared.loadUserImage(
  212. for: sharee.shareWith,
  213. displayName: nil,
  214. userBaseUrl: self.appDelegate)
  215. let fileName = self.appDelegate.userBaseUrl + "-" + sharee.shareWith + ".png"
  216. if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil {
  217. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  218. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  219. NCCommunication.shared.downloadAvatar(user: sharee.shareWith, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag) { _, imageAvatar, _, etag, errorCode, _ in
  220. if errorCode == 0, let etag = etag, let imageAvatar = imageAvatar {
  221. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  222. cell.imageItem.image = imageAvatar
  223. } else if errorCode == NCGlobal.shared.errorNotModified, let imageAvatar = NCManageDatabase.shared.setAvatarLoaded(fileName: fileName) {
  224. cell.imageItem.image = imageAvatar
  225. }
  226. }
  227. }
  228. }
  229. dropDown.selectionAction = { (index, item) in
  230. let sharee = sharees[index]
  231. self.checkEnforcedPassword { password in
  232. self.networking?.createShare(shareWith: sharee.shareWith, shareType: sharee.shareType, password: password, metadata: self.metadata!)
  233. }
  234. }
  235. dropDown.show()
  236. }
  237. }
  238. // MARK: - UITableViewDelegate
  239. extension NCShare: UITableViewDelegate {
  240. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  241. if indexPath.section == 0, indexPath.row == 0 {
  242. // internal cell has description
  243. return 90
  244. }
  245. return 70
  246. }
  247. }
  248. // MARK: - UITableViewDataSource
  249. extension NCShare: UITableViewDataSource {
  250. func numberOfSections(in tableView: UITableView) -> Int {
  251. return 2
  252. }
  253. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  254. guard section != 0 else { return 2 }
  255. return shares.share?.count ?? 0
  256. }
  257. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  258. // Setup default share cells
  259. guard indexPath.section != 0 else {
  260. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell
  261. else { return UITableViewCell() }
  262. cell.delegate = self
  263. if indexPath.row == 0 {
  264. cell.isInternalLink = true
  265. } else {
  266. cell.tableShare = shares.firstShareLink
  267. }
  268. cell.setupCellUI()
  269. return cell
  270. }
  271. let tableShare = shares.share![indexPath.row]
  272. // LINK
  273. if tableShare.shareType == 3 {
  274. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell {
  275. cell.tableShare = tableShare
  276. cell.delegate = self
  277. cell.setupCellUI()
  278. return cell
  279. }
  280. } else {
  281. // USER
  282. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellUser", for: indexPath) as? NCShareUserCell {
  283. cell.tableShare = tableShare
  284. cell.delegate = self
  285. cell.labelTitle.text = tableShare.shareWithDisplayname
  286. cell.labelTitle.textColor = NCBrandColor.shared.label
  287. cell.isUserInteractionEnabled = true
  288. cell.labelQuickStatus.isHidden = false
  289. cell.imageDownArrow.isHidden = false
  290. cell.buttonMenu.isHidden = false
  291. cell.imageItem.image = NCShareCommon.shared.getImageShareType(shareType: tableShare.shareType)
  292. let status = NCUtility.shared.getUserStatus(userIcon: tableShare.userIcon, userStatus: tableShare.userStatus, userMessage: tableShare.userMessage)
  293. cell.imageStatus.image = status.onlineStatus
  294. cell.status.text = status.statusMessage
  295. let fileName = appDelegate.userBaseUrl + "-" + tableShare.shareWith + ".png"
  296. NCOperationQueue.shared.downloadAvatar(user: tableShare.shareWith, dispalyName: tableShare.shareWithDisplayname, fileName: fileName, cell: cell, view: tableView)
  297. // If the initiator or the recipient is not the current user, show the list of sharees without any options to edit it.
  298. if tableShare.uidOwner != self.appDelegate.userId && tableShare.uidFileOwner != self.appDelegate.userId {
  299. cell.isUserInteractionEnabled = false
  300. cell.labelQuickStatus.isHidden = true
  301. cell.imageDownArrow.isHidden = true
  302. cell.buttonMenu.isHidden = true
  303. }
  304. cell.btnQuickStatus.setTitle("", for: .normal)
  305. cell.btnQuickStatus.contentHorizontalAlignment = .left
  306. if tableShare.permissions == NCGlobal.shared.permissionCreateShare {
  307. cell.labelQuickStatus.text = NSLocalizedString("_share_file_drop_", comment: "")
  308. } else {
  309. // Read Only
  310. if CCUtility.isAnyPermission(toEdit: tableShare.permissions) {
  311. cell.labelQuickStatus.text = NSLocalizedString("_share_editing_", comment: "")
  312. } else {
  313. cell.labelQuickStatus.text = NSLocalizedString("_share_read_only_", comment: "")
  314. }
  315. }
  316. return cell
  317. }
  318. }
  319. return UITableViewCell()
  320. }
  321. }
  322. // MARK: - NCCell Delegates
  323. extension NCShare: NCShareLinkCellDelegate, NCShareUserCellDelegate {
  324. func copyInternalLink(sender: Any) {
  325. guard let metadata = self.metadata else { return }
  326. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  327. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: metadata.account) { (account, metadata, errorCode, errorDescription) in
  328. if errorCode == 0 && metadata != nil {
  329. let internalLink = self.appDelegate.urlBase + "/index.php/f/" + metadata!.fileId
  330. NCShareCommon.shared.copyLink(link: internalLink, viewController: self, sender: sender)
  331. } else {
  332. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  333. }
  334. }
  335. }
  336. func tapCopy(with tableShare: tableShare?, sender: Any) {
  337. guard let tableShare = tableShare else {
  338. return copyInternalLink(sender: sender)
  339. }
  340. NCShareCommon.shared.copyLink(link: tableShare.url, viewController: self, sender: sender)
  341. }
  342. func tapMenu(with tableShare: tableShare?, sender: Any) {
  343. guard let metadata = self.metadata else { return }
  344. let isFilesSharingPublicPasswordEnforced = NCManageDatabase.shared.getCapabilitiesServerBool(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesFileSharingPubPasswdEnforced, exists: false)
  345. if let tableShare = tableShare {
  346. // open share menu
  347. if tableShare.shareType == 3 {
  348. let views = NCShareCommon.shared.openViewMenuShareLink(shareViewController: self, tableShare: tableShare, metadata: metadata)
  349. shareLinkMenuView = views.shareLinkMenuView
  350. shareMenuViewWindow = views.viewWindow
  351. let tap = UITapGestureRecognizer(target: self, action: #selector(tapLinkMenuViewWindow))
  352. tap.delegate = self
  353. shareMenuViewWindow?.addGestureRecognizer(tap)
  354. } else {
  355. let views = NCShareCommon.shared.openViewMenuUser(shareViewController: self, tableShare: tableShare, metadata: metadata)
  356. shareUserMenuView = views.shareUserMenuView
  357. shareMenuViewWindow = views.viewWindow
  358. let tap = UITapGestureRecognizer(target: self, action: #selector(tapLinkMenuViewWindow))
  359. tap.delegate = self
  360. shareMenuViewWindow?.addGestureRecognizer(tap)
  361. }
  362. } else if isFilesSharingPublicPasswordEnforced {
  363. // create share with pw
  364. let alertController = UIAlertController(title: NSLocalizedString("_enforce_password_protection_", comment: ""), message: "", preferredStyle: .alert)
  365. alertController.addTextField { (textField) in
  366. textField.isSecureTextEntry = true
  367. }
  368. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { (action:UIAlertAction) in })
  369. let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { (action:UIAlertAction) in
  370. let password = alertController.textFields?.first?.text
  371. self.networking?.createShareLink(password: password ?? "")
  372. }
  373. alertController.addAction(okAction)
  374. self.present(alertController, animated: true, completion: nil)
  375. } else {
  376. // create sahre without pw
  377. networking?.createShareLink(password: "")
  378. }
  379. }
  380. func showProfile(with tableShare: tableShare?, sender: Any) {
  381. guard let tableShare = tableShare else { return }
  382. showProfileMenu(userId: tableShare.shareWith)
  383. }
  384. func quickStatus(with tableShare: tableShare?, sender: Any) {
  385. guard let tableShare = tableShare else { return }
  386. if tableShare.shareType != NCGlobal.shared.permissionDefaultFileRemoteShareNoSupportShareOption {
  387. let quickStatusMenu = NCShareQuickStatusMenu()
  388. quickStatusMenu.toggleMenu(viewController: self, directory: metadata!.directory, tableShare: tableShare)
  389. }
  390. }
  391. }