NCShare.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. // Copyright © 2022 Henrik Storch. All rights reserved.
  8. //
  9. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  10. // Author Henrik Storch <henrik.storch@nextcloud.com>
  11. //
  12. // This program is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. import UIKit
  26. import Parchment
  27. import DropDown
  28. import NextcloudKit
  29. import MarqueeLabel
  30. import ContactsUI
  31. class NCShare: UIViewController, NCShareNetworkingDelegate, NCSharePagingContent {
  32. @IBOutlet weak var viewContainerConstraint: NSLayoutConstraint!
  33. @IBOutlet weak var sharedWithYouByView: UIView!
  34. @IBOutlet weak var sharedWithYouByImage: UIImageView!
  35. @IBOutlet weak var sharedWithYouByLabel: UILabel!
  36. @IBOutlet weak var sharedWithYouByNoteImage: UIImageView!
  37. @IBOutlet weak var sharedWithYouByNote: MarqueeLabel!
  38. @IBOutlet weak var searchFieldTopConstraint: NSLayoutConstraint!
  39. @IBOutlet weak var searchField: UITextField!
  40. var textField: UITextField? { searchField }
  41. @IBOutlet weak var tableView: UITableView!
  42. @IBOutlet weak var btnContact: UIButton!
  43. weak var appDelegate = UIApplication.shared.delegate as? AppDelegate
  44. public var metadata: tableMetadata?
  45. public var sharingEnabled = true
  46. public var height: CGFloat = 0
  47. let shareCommon = NCShareCommon()
  48. let utilityFileSystem = NCUtilityFileSystem()
  49. let utility = NCUtility()
  50. var canReshare: Bool {
  51. guard let metadata = metadata else { return true }
  52. return ((metadata.sharePermissionsCollaborationServices & NCPermissions().permissionShareShare) != 0)
  53. }
  54. var shares: (firstShareLink: tableShare?, share: [tableShare]?) = (nil, nil)
  55. private var dropDown = DropDown()
  56. var networking: NCShareNetworking?
  57. // MARK: - View Life Cycle
  58. override func viewDidLoad() {
  59. super.viewDidLoad()
  60. view.backgroundColor = .systemBackground
  61. viewContainerConstraint.constant = height
  62. searchFieldTopConstraint.constant = 10
  63. searchField.placeholder = NSLocalizedString("_shareLinksearch_placeholder_", comment: "")
  64. searchField.autocorrectionType = .no
  65. tableView.dataSource = self
  66. tableView.delegate = self
  67. tableView.allowsSelection = false
  68. tableView.backgroundColor = .systemBackground
  69. tableView.register(UINib(nibName: "NCShareLinkCell", bundle: nil), forCellReuseIdentifier: "cellLink")
  70. tableView.register(UINib(nibName: "NCShareUserCell", bundle: nil), forCellReuseIdentifier: "cellUser")
  71. NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataNCShare), object: nil)
  72. guard let metadata = metadata else { return }
  73. if metadata.e2eEncrypted {
  74. let direcrory = NCManageDatabase.shared.getTableDirectory(account: metadata.account, serverUrl: metadata.serverUrl)
  75. if NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV12 ||
  76. (NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV20 && direcrory?.e2eEncrypted ?? false) {
  77. // searchField.isEnabled = false
  78. searchFieldTopConstraint.constant = -50
  79. searchField.isHidden = true
  80. }
  81. } else {
  82. checkSharedWithYou()
  83. }
  84. reloadData()
  85. networking = NCShareNetworking(metadata: metadata, view: self.view, delegate: self)
  86. if sharingEnabled {
  87. let isVisible = (self.navigationController?.topViewController as? NCSharePaging)?.page == .sharing
  88. networking?.readShare(showLoadingIndicator: isVisible)
  89. }
  90. }
  91. func makeNewLinkShare() {
  92. guard
  93. let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
  94. let navigationController = self.navigationController,
  95. let metadata = self.metadata else { return }
  96. self.checkEnforcedPassword(shareType: shareCommon.SHARE_TYPE_LINK) { password in
  97. advancePermission.networking = self.networking
  98. advancePermission.share = NCTableShareOptions.shareLink(metadata: metadata, password: password)
  99. advancePermission.metadata = self.metadata
  100. navigationController.pushViewController(advancePermission, animated: true)
  101. }
  102. }
  103. // Shared with you by ...
  104. func checkSharedWithYou() {
  105. guard let appDelegate = self.appDelegate, let metadata = metadata, !metadata.ownerId.isEmpty, metadata.ownerId != appDelegate.userId else { return }
  106. if !canReshare {
  107. searchField.isEnabled = false
  108. searchField.placeholder = NSLocalizedString("_share_reshare_disabled_", comment: "")
  109. }
  110. searchFieldTopConstraint.constant = 65
  111. sharedWithYouByView.isHidden = false
  112. sharedWithYouByLabel.text = NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName
  113. sharedWithYouByImage.image = utility.loadUserImage(
  114. for: metadata.ownerId,
  115. displayName: metadata.ownerDisplayName,
  116. userBaseUrl: appDelegate)
  117. sharedWithYouByLabel.accessibilityHint = NSLocalizedString("_show_profile_", comment: "")
  118. let shareAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  119. sharedWithYouByImage.addGestureRecognizer(shareAction)
  120. let shareLabelAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  121. sharedWithYouByLabel.addGestureRecognizer(shareLabelAction)
  122. if !metadata.note.isEmpty {
  123. searchFieldTopConstraint.constant = 95
  124. sharedWithYouByNoteImage.isHidden = false
  125. sharedWithYouByNoteImage.image = utility.loadImage(named: "note.text", colors: [NCBrandColor.shared.iconImageColor])
  126. sharedWithYouByNote.isHidden = false
  127. sharedWithYouByNote.text = metadata.note
  128. sharedWithYouByNote.textColor = NCBrandColor.shared.textColor
  129. sharedWithYouByNote.trailingBuffer = sharedWithYouByNote.frame.width
  130. } else {
  131. sharedWithYouByNoteImage.isHidden = true
  132. sharedWithYouByNote.isHidden = true
  133. }
  134. let fileName = appDelegate.userBaseUrl + "-" + metadata.ownerId + ".png"
  135. if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil {
  136. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  137. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  138. NextcloudKit.shared.downloadAvatar(
  139. user: metadata.ownerId,
  140. fileNameLocalPath: fileNameLocalPath,
  141. sizeImage: NCGlobal.shared.avatarSize,
  142. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  143. etag: etag) { _, imageAvatar, _, etag, error in
  144. if error == .success, let etag = etag, let imageAvatar = imageAvatar {
  145. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  146. self.sharedWithYouByImage.image = imageAvatar
  147. } else if error.errorCode == NCGlobal.shared.errorNotModified, let imageAvatar = NCManageDatabase.shared.setAvatarLoaded(fileName: fileName) {
  148. self.sharedWithYouByImage.image = imageAvatar
  149. }
  150. }
  151. }
  152. }
  153. // MARK: - Notification Center
  154. @objc func openShareProfile() {
  155. guard let metadata = metadata else { return }
  156. self.showProfileMenu(userId: metadata.ownerId)
  157. }
  158. // MARK: -
  159. @objc func reloadData() {
  160. if let metadata = metadata {
  161. shares = NCManageDatabase.shared.getTableShares(metadata: metadata)
  162. }
  163. tableView.reloadData()
  164. }
  165. // MARK: - IBAction
  166. @IBAction func searchFieldDidEndOnExit(textField: UITextField) {
  167. // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
  168. func isValidEmail(_ email: String) -> Bool {
  169. let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  170. let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
  171. return emailPred.evaluate(with: email)
  172. }
  173. guard let searchString = textField.text, !searchString.isEmpty else { return }
  174. if searchString.contains("@"), !isValidEmail(searchString) { return }
  175. networking?.getSharees(searchString: searchString)
  176. }
  177. func checkEnforcedPassword(shareType: Int, completion: @escaping (String?) -> Void) {
  178. guard NCGlobal.shared.capabilityFileSharingPubPasswdEnforced,
  179. shareType == shareCommon.SHARE_TYPE_LINK || shareType == shareCommon.SHARE_TYPE_EMAIL
  180. else { return completion(nil) }
  181. self.present(UIAlertController.password(titleKey: "_enforce_password_protection_", completion: completion), animated: true)
  182. }
  183. @IBAction func selectContactClicked(_ sender: Any) {
  184. let cnPicker = CNContactPickerViewController()
  185. cnPicker.delegate = self
  186. cnPicker.displayedPropertyKeys = [CNContactEmailAddressesKey]
  187. cnPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
  188. cnPicker.predicateForSelectionOfProperty = NSPredicate(format: "emailAddresses.@count > 0")
  189. self.present(cnPicker, animated: true)
  190. }
  191. // MARK: - NCShareNetworkingDelegate
  192. func readShareCompleted() {
  193. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  194. }
  195. func shareCompleted() {
  196. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  197. }
  198. func unShareCompleted() {
  199. self.reloadData()
  200. }
  201. func updateShareWithError(idShare: Int) {
  202. self.reloadData()
  203. }
  204. func getSharees(sharees: [NKSharee]?) {
  205. guard let sharees = sharees, let appDelegate = appDelegate else { return }
  206. dropDown = DropDown()
  207. let appearance = DropDown.appearance()
  208. appearance.backgroundColor = .systemBackground
  209. appearance.cornerRadius = 10
  210. appearance.shadowColor = UIColor(white: 0.5, alpha: 1)
  211. appearance.shadowOpacity = 0.9
  212. appearance.shadowRadius = 25
  213. appearance.animationduration = 0.25
  214. appearance.textColor = .darkGray
  215. appearance.setupMaskedCorners([.layerMaxXMaxYCorner, .layerMinXMaxYCorner])
  216. for sharee in sharees {
  217. var label = sharee.label
  218. if sharee.shareType == shareCommon.SHARE_TYPE_CIRCLE {
  219. label += " (\(sharee.circleInfo), \(sharee.circleOwner))"
  220. }
  221. dropDown.dataSource.append(label)
  222. }
  223. dropDown.anchorView = searchField
  224. dropDown.bottomOffset = CGPoint(x: 0, y: searchField.bounds.height)
  225. dropDown.width = searchField.bounds.width
  226. dropDown.direction = .bottom
  227. dropDown.cellNib = UINib(nibName: "NCSearchUserDropDownCell", bundle: nil)
  228. dropDown.customCellConfiguration = { (index: Index, _, cell: DropDownCell) -> Void in
  229. guard let cell = cell as? NCSearchUserDropDownCell else { return }
  230. let sharee = sharees[index]
  231. cell.setupCell(sharee: sharee, baseUrl: appDelegate)
  232. }
  233. dropDown.selectionAction = { index, _ in
  234. let sharee = sharees[index]
  235. guard
  236. let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
  237. let navigationController = self.navigationController,
  238. let metadata = self.metadata else { return }
  239. self.checkEnforcedPassword(shareType: sharee.shareType) { password in
  240. let shareOptions = NCTableShareOptions(sharee: sharee, metadata: metadata, password: password)
  241. advancePermission.share = shareOptions
  242. advancePermission.networking = self.networking
  243. advancePermission.metadata = metadata
  244. navigationController.pushViewController(advancePermission, animated: true)
  245. }
  246. }
  247. dropDown.show()
  248. }
  249. }
  250. // MARK: - UITableViewDelegate
  251. extension NCShare: UITableViewDelegate {
  252. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  253. if indexPath.section == 0, indexPath.row == 0 {
  254. // internal cell has description
  255. return 90
  256. }
  257. return 70
  258. }
  259. }
  260. // MARK: - UITableViewDataSource
  261. extension NCShare: UITableViewDataSource {
  262. func numberOfSections(in tableView: UITableView) -> Int {
  263. return 2
  264. }
  265. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  266. guard let metadata = self.metadata else { return 0}
  267. var numRows = shares.share?.count ?? 0
  268. if section == 0 {
  269. if metadata.e2eEncrypted && NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV12 {
  270. numRows = 1
  271. } else {
  272. // don't allow link creation if reshare is disabled
  273. numRows = shares.firstShareLink != nil || canReshare ? 2 : 1
  274. }
  275. }
  276. return numRows
  277. }
  278. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  279. // Setup default share cells
  280. guard indexPath.section != 0 else {
  281. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell, let metadata = self.metadata
  282. else { return UITableViewCell() }
  283. cell.delegate = self
  284. if metadata.e2eEncrypted && NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV12 {
  285. cell.tableShare = shares.firstShareLink
  286. } else {
  287. if indexPath.row == 0 {
  288. cell.isInternalLink = true
  289. } else if shares.firstShareLink?.isInvalidated != true {
  290. cell.tableShare = shares.firstShareLink
  291. }
  292. }
  293. cell.setupCellUI()
  294. return cell
  295. }
  296. guard let appDelegate = appDelegate, let tableShare = shares.share?[indexPath.row] else { return UITableViewCell() }
  297. // LINK
  298. if tableShare.shareType == shareCommon.SHARE_TYPE_LINK {
  299. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell {
  300. cell.indexPath = indexPath
  301. cell.tableShare = tableShare
  302. cell.delegate = self
  303. cell.setupCellUI()
  304. return cell
  305. }
  306. } else {
  307. // USER / GROUP etc.
  308. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellUser", for: indexPath) as? NCShareUserCell {
  309. cell.indexPath = indexPath
  310. cell.tableShare = tableShare
  311. cell.delegate = self
  312. cell.setupCellUI(userId: appDelegate.userId)
  313. let fileName = appDelegate.userBaseUrl + "-" + tableShare.shareWith + ".png"
  314. NCNetworking.shared.downloadAvatar(user: tableShare.shareWith, dispalyName: tableShare.shareWithDisplayname, fileName: fileName, cell: cell, view: tableView)
  315. return cell
  316. }
  317. }
  318. return UITableViewCell()
  319. }
  320. }
  321. // MARK: CNContactPickerDelegate
  322. extension NCShare: CNContactPickerDelegate {
  323. func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
  324. if contact.emailAddresses.count > 1 {
  325. showEmailList(arrEmail: contact.emailAddresses.map({$0.value as String}))
  326. } else if let email = contact.emailAddresses.first?.value as? String {
  327. textField?.text = email
  328. networking?.getSharees(searchString: email)
  329. }
  330. }
  331. func showEmailList(arrEmail: [String]) {
  332. var actions = [NCMenuAction]()
  333. for email in arrEmail {
  334. actions.append(
  335. NCMenuAction(
  336. title: email,
  337. icon: utility.loadImage(named: "email", colors: [NCBrandColor.shared.iconImageColor]),
  338. selected: false,
  339. on: false,
  340. action: { _ in
  341. self.textField?.text = email
  342. self.networking?.getSharees(searchString: email)
  343. }
  344. )
  345. )
  346. }
  347. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  348. self.presentMenu(with: actions)
  349. }
  350. }
  351. }