NCShare.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 & NCGlobal.shared.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. btnContact.layer.cornerRadius = 5
  91. btnContact.layer.masksToBounds = true
  92. btnContact.layer.borderWidth = 1
  93. btnContact.layer.borderColor = UIColor.gray.cgColor
  94. btnContact.tintColor = .gray
  95. btnContact.setImage(utility.loadImage(named: "contact", color: .gray, size: 24), for: .normal)
  96. }
  97. func makeNewLinkShare() {
  98. guard
  99. let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
  100. let navigationController = self.navigationController,
  101. let metadata = self.metadata else { return }
  102. self.checkEnforcedPassword(shareType: shareCommon.SHARE_TYPE_LINK) { password in
  103. advancePermission.networking = self.networking
  104. advancePermission.share = NCTableShareOptions.shareLink(metadata: metadata, password: password)
  105. advancePermission.metadata = self.metadata
  106. navigationController.pushViewController(advancePermission, animated: true)
  107. }
  108. }
  109. // Shared with you by ...
  110. func checkSharedWithYou() {
  111. guard let appDelegate = self.appDelegate, let metadata = metadata, !metadata.ownerId.isEmpty, metadata.ownerId != appDelegate.userId else { return }
  112. if !canReshare {
  113. searchField.isEnabled = false
  114. searchField.placeholder = NSLocalizedString("_share_reshare_disabled_", comment: "")
  115. }
  116. searchFieldTopConstraint.constant = 65
  117. sharedWithYouByView.isHidden = false
  118. sharedWithYouByLabel.text = NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName
  119. sharedWithYouByImage.image = utility.loadUserImage(
  120. for: metadata.ownerId,
  121. displayName: metadata.ownerDisplayName,
  122. userBaseUrl: appDelegate)
  123. sharedWithYouByLabel.accessibilityHint = NSLocalizedString("_show_profile_", comment: "")
  124. let shareAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  125. sharedWithYouByImage.addGestureRecognizer(shareAction)
  126. let shareLabelAction = UITapGestureRecognizer(target: self, action: #selector(openShareProfile))
  127. sharedWithYouByLabel.addGestureRecognizer(shareLabelAction)
  128. if !metadata.note.isEmpty {
  129. searchFieldTopConstraint.constant = 95
  130. sharedWithYouByNoteImage.isHidden = false
  131. sharedWithYouByNoteImage.image = utility.loadImage(named: "note.text", color: .gray)
  132. sharedWithYouByNote.isHidden = false
  133. sharedWithYouByNote.text = metadata.note
  134. sharedWithYouByNote.textColor = .label
  135. sharedWithYouByNote.trailingBuffer = sharedWithYouByNote.frame.width
  136. } else {
  137. sharedWithYouByNoteImage.isHidden = true
  138. sharedWithYouByNote.isHidden = true
  139. }
  140. let fileName = appDelegate.userBaseUrl + "-" + metadata.ownerId + ".png"
  141. if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil {
  142. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  143. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  144. NextcloudKit.shared.downloadAvatar(
  145. user: metadata.ownerId,
  146. fileNameLocalPath: fileNameLocalPath,
  147. sizeImage: NCGlobal.shared.avatarSize,
  148. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  149. etag: etag) { _, imageAvatar, _, etag, error in
  150. if error == .success, let etag = etag, let imageAvatar = imageAvatar {
  151. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  152. self.sharedWithYouByImage.image = imageAvatar
  153. } else if error.errorCode == NCGlobal.shared.errorNotModified, let imageAvatar = NCManageDatabase.shared.setAvatarLoaded(fileName: fileName) {
  154. self.sharedWithYouByImage.image = imageAvatar
  155. }
  156. }
  157. }
  158. }
  159. // MARK: - Notification Center
  160. @objc func openShareProfile() {
  161. guard let metadata = metadata else { return }
  162. self.showProfileMenu(userId: metadata.ownerId)
  163. }
  164. // MARK: -
  165. @objc func reloadData() {
  166. if let metadata = metadata {
  167. shares = NCManageDatabase.shared.getTableShares(metadata: metadata)
  168. }
  169. tableView.reloadData()
  170. }
  171. // MARK: - IBAction
  172. @IBAction func searchFieldDidEndOnExit(textField: UITextField) {
  173. // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
  174. func isValidEmail(_ email: String) -> Bool {
  175. let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  176. let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
  177. return emailPred.evaluate(with: email)
  178. }
  179. guard let searchString = textField.text, !searchString.isEmpty else { return }
  180. if searchString.contains("@"), !isValidEmail(searchString) { return }
  181. networking?.getSharees(searchString: searchString)
  182. }
  183. func checkEnforcedPassword(shareType: Int, completion: @escaping (String?) -> Void) {
  184. guard NCGlobal.shared.capabilityFileSharingPubPasswdEnforced,
  185. shareType == shareCommon.SHARE_TYPE_LINK || shareType == shareCommon.SHARE_TYPE_EMAIL
  186. else { return completion(nil) }
  187. self.present(UIAlertController.password(titleKey: "_enforce_password_protection_", completion: completion), animated: true)
  188. }
  189. @IBAction func selectContactClicked(_ sender: Any) {
  190. let cnPicker = CNContactPickerViewController()
  191. cnPicker.delegate = self
  192. cnPicker.displayedPropertyKeys = [CNContactEmailAddressesKey]
  193. cnPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
  194. cnPicker.predicateForSelectionOfProperty = NSPredicate(format: "emailAddresses.@count > 0")
  195. self.present(cnPicker, animated: true)
  196. }
  197. // MARK: - NCShareNetworkingDelegate
  198. func readShareCompleted() {
  199. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  200. }
  201. func shareCompleted() {
  202. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataNCShare)
  203. }
  204. func unShareCompleted() {
  205. self.reloadData()
  206. }
  207. func updateShareWithError(idShare: Int) {
  208. self.reloadData()
  209. }
  210. func getSharees(sharees: [NKSharee]?) {
  211. guard let sharees = sharees, let appDelegate = appDelegate else { return }
  212. dropDown = DropDown()
  213. let appearance = DropDown.appearance()
  214. appearance.backgroundColor = .systemBackground
  215. appearance.cornerRadius = 10
  216. appearance.shadowColor = UIColor(white: 0.5, alpha: 1)
  217. appearance.shadowOpacity = 0.9
  218. appearance.shadowRadius = 25
  219. appearance.animationduration = 0.25
  220. appearance.textColor = .darkGray
  221. appearance.setupMaskedCorners([.layerMaxXMaxYCorner, .layerMinXMaxYCorner])
  222. for sharee in sharees {
  223. var label = sharee.label
  224. if sharee.shareType == shareCommon.SHARE_TYPE_CIRCLE {
  225. label += " (\(sharee.circleInfo), \(sharee.circleOwner))"
  226. }
  227. dropDown.dataSource.append(label)
  228. }
  229. dropDown.anchorView = searchField
  230. dropDown.bottomOffset = CGPoint(x: 0, y: searchField.bounds.height)
  231. dropDown.width = searchField.bounds.width
  232. dropDown.direction = .bottom
  233. dropDown.cellNib = UINib(nibName: "NCSearchUserDropDownCell", bundle: nil)
  234. dropDown.customCellConfiguration = { (index: Index, _, cell: DropDownCell) -> Void in
  235. guard let cell = cell as? NCSearchUserDropDownCell else { return }
  236. let sharee = sharees[index]
  237. cell.setupCell(sharee: sharee, baseUrl: appDelegate)
  238. }
  239. dropDown.selectionAction = { index, _ in
  240. let sharee = sharees[index]
  241. guard
  242. let advancePermission = UIStoryboard(name: "NCShare", bundle: nil).instantiateViewController(withIdentifier: "NCShareAdvancePermission") as? NCShareAdvancePermission,
  243. let navigationController = self.navigationController,
  244. let metadata = self.metadata else { return }
  245. self.checkEnforcedPassword(shareType: sharee.shareType) { password in
  246. let shareOptions = NCTableShareOptions(sharee: sharee, metadata: metadata, password: password)
  247. advancePermission.share = shareOptions
  248. advancePermission.networking = self.networking
  249. advancePermission.metadata = metadata
  250. navigationController.pushViewController(advancePermission, animated: true)
  251. }
  252. }
  253. dropDown.show()
  254. }
  255. }
  256. // MARK: - UITableViewDelegate
  257. extension NCShare: UITableViewDelegate {
  258. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  259. if indexPath.section == 0, indexPath.row == 0 {
  260. // internal cell has description
  261. return 90
  262. }
  263. return 70
  264. }
  265. }
  266. // MARK: - UITableViewDataSource
  267. extension NCShare: UITableViewDataSource {
  268. func numberOfSections(in tableView: UITableView) -> Int {
  269. return 2
  270. }
  271. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  272. guard let metadata = self.metadata else { return 0}
  273. var numRows = shares.share?.count ?? 0
  274. if section == 0 {
  275. if metadata.e2eEncrypted && NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV12 {
  276. numRows = 1
  277. } else {
  278. // don't allow link creation if reshare is disabled
  279. numRows = shares.firstShareLink != nil || canReshare ? 2 : 1
  280. }
  281. }
  282. return numRows
  283. }
  284. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  285. // Setup default share cells
  286. guard indexPath.section != 0 else {
  287. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell, let metadata = self.metadata
  288. else { return UITableViewCell() }
  289. cell.delegate = self
  290. if metadata.e2eEncrypted && NCGlobal.shared.capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV12 {
  291. cell.tableShare = shares.firstShareLink
  292. } else {
  293. if indexPath.row == 0 {
  294. cell.isInternalLink = true
  295. } else if shares.firstShareLink?.isInvalidated != true {
  296. cell.tableShare = shares.firstShareLink
  297. }
  298. }
  299. cell.setupCellUI()
  300. return cell
  301. }
  302. guard let appDelegate = appDelegate, let tableShare = shares.share?[indexPath.row] else { return UITableViewCell() }
  303. // LINK
  304. if tableShare.shareType == shareCommon.SHARE_TYPE_LINK {
  305. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell {
  306. cell.indexPath = indexPath
  307. cell.tableShare = tableShare
  308. cell.delegate = self
  309. cell.setupCellUI()
  310. return cell
  311. }
  312. } else {
  313. // USER / GROUP etc.
  314. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellUser", for: indexPath) as? NCShareUserCell {
  315. cell.indexPath = indexPath
  316. cell.tableShare = tableShare
  317. cell.delegate = self
  318. cell.setupCellUI(userId: appDelegate.userId)
  319. let fileName = appDelegate.userBaseUrl + "-" + tableShare.shareWith + ".png"
  320. NCNetworking.shared.downloadAvatar(user: tableShare.shareWith, dispalyName: tableShare.shareWithDisplayname, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  321. return cell
  322. }
  323. }
  324. return UITableViewCell()
  325. }
  326. }
  327. // MARK: CNContactPickerDelegate
  328. extension NCShare: CNContactPickerDelegate {
  329. func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
  330. if contact.emailAddresses.count > 1 {
  331. showEmailList(arrEmail: contact.emailAddresses.map({$0.value as String}))
  332. } else if let email = contact.emailAddresses.first?.value as? String {
  333. textField?.text = email
  334. networking?.getSharees(searchString: email)
  335. }
  336. }
  337. func showEmailList(arrEmail: [String]) {
  338. var actions = [NCMenuAction]()
  339. for email in arrEmail {
  340. actions.append(
  341. NCMenuAction(
  342. title: email,
  343. icon: utility.loadImage(named: "email"),
  344. selected: false,
  345. on: false,
  346. action: { _ in
  347. self.textField?.text = email
  348. self.networking?.getSharees(searchString: email)
  349. }
  350. )
  351. )
  352. }
  353. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  354. self.presentMenu(with: actions)
  355. }
  356. }
  357. }