NCShare.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. //
  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 Parchment
  25. import DropDown
  26. class NCShare: UIViewController, UIGestureRecognizerDelegate, NCShareLinkCellDelegate, NCShareUserCellDelegate, NCShareNetworkingDelegate {
  27. @IBOutlet weak var viewContainerConstraint: NSLayoutConstraint!
  28. @IBOutlet weak var sharedWithYouByView: UIView!
  29. @IBOutlet weak var sharedWithYouByImage: UIImageView!
  30. @IBOutlet weak var sharedWithYouByLabel: UILabel!
  31. @IBOutlet weak var searchFieldTopConstraint: NSLayoutConstraint!
  32. @IBOutlet weak var searchField: UITextField!
  33. @IBOutlet weak var shareLinkImage: UIImageView!
  34. @IBOutlet weak var shareLinkLabel: UILabel!
  35. @IBOutlet weak var buttonCopy: UIButton!
  36. @IBOutlet weak var buttonMenu: UIButton!
  37. @IBOutlet weak var tableView: UITableView!
  38. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  39. var metadata: tableMetadata?
  40. public var height: CGFloat = 0
  41. private var shareLinkMenuView: NCShareLinkMenuView?
  42. private var shareUserMenuView: NCShareUserMenuView?
  43. private var shareMenuViewWindow: UIView?
  44. private var dropDown = DropDown()
  45. private var networking: NCShareNetworking?
  46. override func viewDidLoad() {
  47. super.viewDidLoad()
  48. viewContainerConstraint.constant = height
  49. searchFieldTopConstraint.constant = 10
  50. searchField.placeholder = NSLocalizedString("_shareLinksearch_placeholder_", comment: "")
  51. shareLinkLabel.text = NSLocalizedString("_share_link_", comment: "")
  52. shareLinkLabel.textColor = NCBrandColor.sharedInstance.textView
  53. shareLinkImage.image = NCShareCommon.sharedInstance.createLinkAvatar()
  54. buttonCopy.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareCopy"), width: 100, height: 100, color: UIColor.gray), for: .normal)
  55. tableView.dataSource = self
  56. tableView.delegate = self
  57. tableView.allowsSelection = false
  58. tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm
  59. tableView.register(UINib.init(nibName: "NCShareLinkCell", bundle: nil), forCellReuseIdentifier: "cellLink")
  60. tableView.register(UINib.init(nibName: "NCShareUserCell", bundle: nil), forCellReuseIdentifier: "cellUser")
  61. NotificationCenter.default.addObserver(self, selector: #selector(self.reloadData), name: NSNotification.Name(rawValue: "reloadDataNCShare"), object: nil)
  62. // Shared with you by ...
  63. if metadata!.ownerId != self.appDelegate.activeUserID {
  64. searchFieldTopConstraint.constant = 65
  65. sharedWithYouByView.isHidden = false
  66. sharedWithYouByLabel.text = NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata!.ownerDisplayName
  67. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata!.ownerId + ".png"
  68. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  69. if let image = UIImage(contentsOfFile: fileNameLocalPath) { sharedWithYouByImage.image = image }
  70. } else {
  71. let url = appDelegate.activeUrl + k_avatar + metadata!.ownerId + "/" + k_avatar_size
  72. let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
  73. OCNetworking.sharedManager()?.downloadContents(ofUrl: encodedString, completion: { (data, message, errorCode) in
  74. if errorCode == 0 && UIImage(data: data!) != nil {
  75. do {
  76. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  77. if let image = UIImage(contentsOfFile: fileNameLocalPath) { self.sharedWithYouByImage.image = image }
  78. } catch { return }
  79. } else {
  80. self.sharedWithYouByImage.image = UIImage(named: "avatar")
  81. }
  82. })
  83. }
  84. }
  85. reloadData()
  86. networking = NCShareNetworking.init(metadata: metadata!, activeUrl: appDelegate.activeUrl, view: self.view, delegate: self)
  87. networking?.readShare()
  88. }
  89. @objc func reloadData() {
  90. let shares = NCManageDatabase.sharedInstance.getTableShares(metadata: metadata!)
  91. if shares.firstShareLink == nil {
  92. buttonMenu.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareAdd"), width: 100, height: 100, color: UIColor.gray), for: .normal)
  93. buttonCopy.isHidden = true
  94. } else {
  95. buttonMenu.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMenu"), width: 100, height: 100, color: UIColor.gray), for: .normal)
  96. buttonCopy.isHidden = false
  97. }
  98. tableView.reloadData()
  99. }
  100. // MARK: - IBAction
  101. @IBAction func searchFieldDidEndOnExit(textField: UITextField) {
  102. guard let searchString = textField.text else { return }
  103. networking?.getUserAndGroup(searchString: searchString)
  104. }
  105. @IBAction func touchUpInsideButtonCopy(_ sender: Any) {
  106. guard let metadata = self.metadata else { return }
  107. let shares = NCManageDatabase.sharedInstance.getTableShares(metadata: metadata)
  108. tapCopy(with: shares.firstShareLink, sender: sender)
  109. }
  110. @IBAction func touchUpInsideButtonMenu(_ sender: Any) {
  111. guard let metadata = self.metadata else { return }
  112. guard let capabilities = NCManageDatabase.sharedInstance.getCapabilites(account: metadata.account) else { return }
  113. let shares = NCManageDatabase.sharedInstance.getTableShares(metadata: metadata)
  114. if capabilities.isFilesSharingPublicPasswordEnforced && shares.firstShareLink == nil {
  115. let alertController = UIAlertController(title: NSLocalizedString("_enforce_password_protection_", comment: ""), message: "", preferredStyle: .alert)
  116. alertController.addTextField { (textField) in
  117. textField.isSecureTextEntry = true
  118. textField.addTarget(self, action: #selector(self.minCharTextFieldDidChange(sender:)), for: UIControl.Event.editingChanged)
  119. }
  120. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { (action:UIAlertAction) in })
  121. let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { (action:UIAlertAction) in
  122. let password = alertController.textFields?.first?.text
  123. self.networking?.share(password: password ?? "", permission: 1, hideDownload: false)
  124. }
  125. okAction.isEnabled = false
  126. alertController.addAction(okAction)
  127. self.present(alertController, animated: true, completion:nil)
  128. } else if shares.firstShareLink == nil {
  129. networking?.share(password: "", permission: 1, hideDownload: false)
  130. } else {
  131. tapMenu(with: shares.firstShareLink!, sender: sender)
  132. }
  133. }
  134. @objc func minCharTextFieldDidChange(sender: UITextField) {
  135. guard let alertController = self.presentedViewController as? UIAlertController else { return }
  136. guard let password = alertController.textFields?.first else { return }
  137. guard let ok = alertController.actions.last else { return }
  138. ok.isEnabled = password.text?.count ?? 0 >= 8
  139. }
  140. @objc func tapLinkMenuViewWindow(gesture: UITapGestureRecognizer) {
  141. shareLinkMenuView?.unLoad()
  142. shareLinkMenuView = nil
  143. shareUserMenuView?.unLoad()
  144. shareUserMenuView = nil
  145. }
  146. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
  147. return gestureRecognizer.view == touch.view
  148. }
  149. func tapCopy(with tableShare: tableShare?, sender: Any) {
  150. NCShareCommon.sharedInstance.copyLink(tableShare: tableShare, viewController: self)
  151. }
  152. func switchCanEdit(with tableShare: tableShare?, switch: Bool, sender: UISwitch) {
  153. guard let tableShare = tableShare else { return }
  154. guard let metadata = self.metadata else { return }
  155. let canShare = UtilsFramework.isPermission(toCanShare: tableShare.permissions)
  156. var permission: Int = 0
  157. if sender.isOn {
  158. permission = UtilsFramework.getPermissionsValue(byCanEdit: true, andCanCreate: true, andCanChange: true, andCanDelete: true, andCanShare: canShare, andIsFolder: metadata.directory)
  159. } else {
  160. permission = UtilsFramework.getPermissionsValue(byCanEdit: false, andCanCreate: false, andCanChange: false, andCanDelete: false, andCanShare: canShare, andIsFolder: metadata.directory)
  161. }
  162. networking?.updateShare(idRemoteShared: tableShare.idRemoteShared, password: nil, permission: permission, note: nil, expirationTime: nil, hideDownload: tableShare.hideDownload)
  163. }
  164. func tapMenu(with tableShare: tableShare?, sender: Any) {
  165. guard let tableShare = tableShare else { return }
  166. if tableShare.shareType == Int(shareTypeLink.rawValue) {
  167. let views = NCShareCommon.sharedInstance.openViewMenuShareLink(shareViewController: self, tableShare: tableShare, metadata: metadata!)
  168. shareLinkMenuView = views.shareLinkMenuView
  169. shareMenuViewWindow = views.viewWindow
  170. let tap = UITapGestureRecognizer(target: self, action: #selector(tapLinkMenuViewWindow))
  171. tap.delegate = self
  172. shareMenuViewWindow?.addGestureRecognizer(tap)
  173. } else {
  174. let views = NCShareCommon.sharedInstance.openViewMenuUser(shareViewController: self, tableShare: tableShare, metadata: metadata!)
  175. shareUserMenuView = views.shareUserMenuView
  176. shareMenuViewWindow = views.viewWindow
  177. let tap = UITapGestureRecognizer(target: self, action: #selector(tapLinkMenuViewWindow))
  178. tap.delegate = self
  179. shareMenuViewWindow?.addGestureRecognizer(tap)
  180. }
  181. }
  182. /// MARK: - NCShareNetworkingDelegate
  183. func readShareCompleted() {
  184. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadDataNCShare"), object: nil, userInfo: nil)
  185. }
  186. func shareCompleted() {
  187. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadDataNCShare"), object: nil, userInfo: nil)
  188. }
  189. func unShareCompleted() { }
  190. func updateShareWithError(idRemoteShared: Int) { }
  191. func getUserAndGroup(items: [OCShareUser]?) {
  192. guard let items = items else { return }
  193. dropDown = DropDown()
  194. let appearance = DropDown.appearance()
  195. appearance.backgroundColor = .white
  196. appearance.cornerRadius = 10
  197. appearance.shadowColor = UIColor(white: 0.5, alpha: 1)
  198. appearance.shadowOpacity = 0.9
  199. appearance.shadowRadius = 25
  200. appearance.animationduration = 0.25
  201. appearance.textColor = .darkGray
  202. if #available(iOS 11.0, *) {
  203. appearance.setupMaskedCorners([.layerMaxXMaxYCorner, .layerMinXMaxYCorner])
  204. }
  205. for item in items {
  206. if item.displayName != nil && item.displayName != "" {
  207. dropDown.dataSource.append(item.displayName)
  208. } else {
  209. dropDown.dataSource.append(item.name)
  210. }
  211. }
  212. dropDown.anchorView = searchField
  213. dropDown.bottomOffset = CGPoint(x: 0, y: searchField.bounds.height)
  214. dropDown.width = searchField.bounds.width
  215. dropDown.direction = .bottom
  216. dropDown.cellNib = UINib(nibName: "NCShareUserDropDownCell", bundle: nil)
  217. dropDown.customCellConfiguration = { (index: Index, item: String, cell: DropDownCell) -> Void in
  218. guard let cell = cell as? NCShareUserDropDownCell else { return }
  219. cell.imageItem.image = UIImage(named: "avatar")
  220. let item = items[index]
  221. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-" + item.name + ".png"
  222. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  223. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.imageItem.image = image }
  224. } else {
  225. DispatchQueue.global().async {
  226. let url = self.appDelegate.activeUrl + k_avatar + item.name + "/" + k_avatar_size
  227. let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
  228. OCNetworking.sharedManager()?.downloadContents(ofUrl: encodedString, completion: { (data, message, errorCode) in
  229. if errorCode == 0 && UIImage(data: data!) != nil {
  230. do {
  231. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  232. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.imageItem.image = image }
  233. } catch { return }
  234. } else {
  235. cell.imageItem.image = UIImage(named: "avatar")
  236. }
  237. })
  238. }
  239. }
  240. if item.shareeType == 0 { cell.imageShareeType.image = UIImage(named: "shareTypeUser")} // shareTypeUser
  241. if item.shareeType == 1 { cell.imageShareeType.image = UIImage(named: "shareTypeGroup")} // shareTypeGroup
  242. if item.shareeType == 3 { cell.imageShareeType.image = UIImage(named: "shareTypeLink")} // shareTypeLink
  243. if item.shareeType == 4 { cell.imageShareeType.image = UIImage(named: "shareTypeEmail")} // shareTypeEmail
  244. if item.shareeType == 5 { cell.imageShareeType.image = UIImage(named: "shareTypeUser")} // shareTypeContact
  245. if item.shareeType == 6 { cell.imageShareeType.image = UIImage(named: "shareTypeLink")} // shareTypeRemote
  246. }
  247. dropDown.selectionAction = { [weak self] (index, item) in
  248. let item = items[index]
  249. self!.networking?.shareUserAndGroup(name: item.name, shareeType: item.shareeType, metadata: self!.metadata!)
  250. }
  251. dropDown.show()
  252. }
  253. }
  254. // MARK: - UITableViewDelegate
  255. extension NCShare: UITableViewDelegate {
  256. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  257. return 60
  258. }
  259. }
  260. // MARK: - UITableViewDataSource
  261. extension NCShare: UITableViewDataSource {
  262. func numberOfSections(in tableView: UITableView) -> Int {
  263. return 1
  264. }
  265. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  266. var numOfRows = 0
  267. let shares = NCManageDatabase.sharedInstance.getTableShares(metadata: metadata!)
  268. if shares.share != nil {
  269. numOfRows = shares.share!.count
  270. }
  271. return numOfRows
  272. }
  273. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  274. let shares = NCManageDatabase.sharedInstance.getTableShares(metadata: metadata!)
  275. let tableShare = shares.share![indexPath.row]
  276. // LINK
  277. if tableShare.shareType == Int(shareTypeLink.rawValue) {
  278. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellLink", for: indexPath) as? NCShareLinkCell {
  279. cell.tableShare = tableShare
  280. cell.delegate = self
  281. cell.labelTitle.text = NSLocalizedString("_share_link_", comment: "")
  282. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  283. return cell
  284. }
  285. } else {
  286. // USER
  287. if let cell = tableView.dequeueReusableCell(withIdentifier: "cellUser", for: indexPath) as? NCShareUserCell {
  288. cell.tableShare = tableShare
  289. cell.delegate = self
  290. cell.labelTitle.text = tableShare.shareWithDisplayName
  291. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  292. cell.labelCanEdit.text = NSLocalizedString("_share_permission_edit_", comment: "")
  293. cell.labelCanEdit.textColor = NCBrandColor.sharedInstance.textView
  294. cell.isUserInteractionEnabled = true
  295. cell.switchCanEdit.isHidden = false
  296. cell.labelCanEdit.isHidden = false
  297. cell.buttonMenu.isHidden = false
  298. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + tableShare.shareWith + ".png"
  299. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  300. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.imageItem.image = image }
  301. } else {
  302. DispatchQueue.global().async {
  303. let url = self.appDelegate.activeUrl + k_avatar + tableShare.shareWith + "/" + k_avatar_size
  304. let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
  305. OCNetworking.sharedManager()?.downloadContents(ofUrl: encodedString, completion: { (data, message, errorCode) in
  306. if errorCode == 0 && UIImage(data: data!) != nil {
  307. do {
  308. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  309. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.imageItem.image = image }
  310. } catch { return }
  311. } else {
  312. cell.imageItem.image = UIImage(named: "avatar")
  313. }
  314. })
  315. }
  316. }
  317. if UtilsFramework.isAnyPermission(toEdit: tableShare.permissions) {
  318. cell.switchCanEdit.setOn(true, animated: false)
  319. } else {
  320. cell.switchCanEdit.setOn(false, animated: false)
  321. }
  322. // If the initiator or the recipient is not the current user, show the list of sharees without any options to edit it.
  323. if tableShare.uidOwner != self.appDelegate.activeUserID && tableShare.uidFileOwner != self.appDelegate.activeUserID {
  324. cell.isUserInteractionEnabled = false
  325. cell.switchCanEdit.isHidden = true
  326. cell.labelCanEdit.isHidden = true
  327. cell.buttonMenu.isHidden = true
  328. }
  329. return cell
  330. }
  331. }
  332. return UITableViewCell()
  333. }
  334. }
  335. // MARK: - NCShareLinkCell
  336. class NCShareLinkCell: UITableViewCell {
  337. @IBOutlet weak var imageItem: UIImageView!
  338. @IBOutlet weak var labelTitle: UILabel!
  339. @IBOutlet weak var buttonCopy: UIButton!
  340. @IBOutlet weak var buttonMenu: UIButton!
  341. private let iconShare: CGFloat = 200
  342. var tableShare: tableShare?
  343. var delegate: NCShareLinkCellDelegate?
  344. override func awakeFromNib() {
  345. super.awakeFromNib()
  346. imageItem.image = NCShareCommon.sharedInstance.createLinkAvatar()
  347. buttonCopy.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareCopy"), width:100, height: 100, color: UIColor.gray), for: .normal)
  348. buttonMenu.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMenu"), width:100, height: 100, color: UIColor.gray), for: .normal)
  349. }
  350. @IBAction func touchUpInsideCopy(_ sender: Any) {
  351. delegate?.tapCopy(with: tableShare, sender: sender)
  352. }
  353. @IBAction func touchUpInsideMenu(_ sender: Any) {
  354. delegate?.tapMenu(with: tableShare, sender: sender)
  355. }
  356. }
  357. protocol NCShareLinkCellDelegate {
  358. func tapCopy(with tableShare: tableShare?, sender: Any)
  359. func tapMenu(with tableShare: tableShare?, sender: Any)
  360. }
  361. // MARK: - NCShareUserCell
  362. class NCShareUserCell: UITableViewCell {
  363. @IBOutlet weak var imageItem: UIImageView!
  364. @IBOutlet weak var labelTitle: UILabel!
  365. @IBOutlet weak var labelCanEdit: UILabel!
  366. @IBOutlet weak var switchCanEdit: UISwitch!
  367. @IBOutlet weak var buttonMenu: UIButton!
  368. var tableShare: tableShare?
  369. var delegate: NCShareUserCellDelegate?
  370. override func awakeFromNib() {
  371. super.awakeFromNib()
  372. switchCanEdit.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
  373. switchCanEdit.onTintColor = NCBrandColor.sharedInstance.brand
  374. buttonMenu.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMenu"), width:100, height: 100, color: UIColor.gray), for: .normal)
  375. }
  376. @IBAction func switchCanEditChanged(sender: UISwitch) {
  377. delegate?.switchCanEdit(with: tableShare, switch: sender.isOn, sender: sender)
  378. }
  379. @IBAction func touchUpInsideMenu(_ sender: Any) {
  380. delegate?.tapMenu(with: tableShare, sender: sender)
  381. }
  382. }
  383. protocol NCShareUserCellDelegate {
  384. func switchCanEdit(with tableShare: tableShare?, switch: Bool, sender: UISwitch)
  385. func tapMenu(with tableShare: tableShare?, sender: Any)
  386. }
  387. // MARK: - NCShareUserDropDownCell
  388. class NCShareUserDropDownCell: DropDownCell {
  389. @IBOutlet weak var imageItem: UIImageView!
  390. @IBOutlet weak var imageShareeType: UIImageView!
  391. }