NewGroupController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import UIKit
  2. import DcCore
  3. class NewGroupController: UITableViewController, MediaPickerDelegate {
  4. var groupName: String = ""
  5. var groupChatId: Int = 0
  6. var doneButton: UIBarButtonItem!
  7. var contactIdsForGroup: Set<Int> // TODO: check if array is sufficient
  8. var groupContactIds: [Int]
  9. private var changeGroupImage: UIImage?
  10. private var deleteGroupImage: Bool = false
  11. let isVerifiedGroup: Bool
  12. let createBroadcast: Bool
  13. let dcContext: DcContext
  14. private var contactAddedObserver: NSObjectProtocol?
  15. enum DetailsRows {
  16. case name
  17. case avatar
  18. }
  19. private let detailsRows: [DetailsRows]
  20. enum InviteRows {
  21. case addMembers
  22. case showQrCode
  23. }
  24. private let inviteRows: [InviteRows]
  25. enum NewGroupSections {
  26. case details
  27. case invite
  28. case members
  29. }
  30. private let sections: [NewGroupSections]
  31. private lazy var mediaPicker: MediaPicker? = {
  32. let mediaPicker = MediaPicker(navigationController: navigationController)
  33. mediaPicker.delegate = self
  34. return mediaPicker
  35. }()
  36. lazy var groupNameCell: TextFieldCell = {
  37. let cell = TextFieldCell(description: String.localized("group_name"), placeholder: String.localized("group_name"))
  38. cell.onTextFieldChange = self.updateGroupName
  39. cell.textField.autocorrectionType = UITextAutocorrectionType.no
  40. cell.textField.enablesReturnKeyAutomatically = true
  41. cell.textField.returnKeyType = .default
  42. cell.textFieldDelegate = self
  43. return cell
  44. }()
  45. lazy var avatarSelectionCell: AvatarSelectionCell = {
  46. let cell = AvatarSelectionCell(image: nil)
  47. cell.hintLabel.text = String.localized("group_avatar")
  48. cell.onAvatarTapped = onAvatarTapped
  49. return cell
  50. }()
  51. var qrInviteCodeCell: ActionCell?
  52. init(dcContext: DcContext, isVerified: Bool, createBroadcast: Bool) {
  53. self.isVerifiedGroup = isVerified
  54. self.createBroadcast = createBroadcast
  55. self.dcContext = dcContext
  56. if createBroadcast {
  57. self.sections = [.invite, .members]
  58. self.detailsRows = []
  59. self.inviteRows = [.addMembers]
  60. self.contactIdsForGroup = []
  61. } else {
  62. self.sections = [.details, .invite, .members]
  63. self.detailsRows = [.name, .avatar]
  64. self.inviteRows = [.addMembers, .showQrCode]
  65. self.contactIdsForGroup = [Int(DC_CONTACT_ID_SELF)]
  66. }
  67. self.groupContactIds = Array(contactIdsForGroup)
  68. super.init(style: .grouped)
  69. }
  70. required init?(coder _: NSCoder) {
  71. fatalError("init(coder:) has not been implemented")
  72. }
  73. override func viewDidLoad() {
  74. super.viewDidLoad()
  75. if isVerifiedGroup {
  76. title = String.localized("menu_new_verified_group")
  77. } else if createBroadcast {
  78. title = String.localized("new_broadcast_list")
  79. } else {
  80. title = String.localized("menu_new_group")
  81. }
  82. doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed))
  83. navigationItem.rightBarButtonItem = doneButton
  84. tableView.register(ContactCell.self, forCellReuseIdentifier: "contactCell")
  85. tableView.register(ActionCell.self, forCellReuseIdentifier: "actionCell")
  86. self.hideKeyboardOnTap()
  87. checkDoneButton()
  88. }
  89. override func viewWillAppear(_ animated: Bool) {
  90. let nc = NotificationCenter.default
  91. contactAddedObserver = nc.addObserver(
  92. forName: dcNotificationChatModified,
  93. object: nil,
  94. queue: nil
  95. ) { [weak self] notification in
  96. guard let self = self else { return }
  97. if let ui = notification.userInfo {
  98. if let chatId = ui["chat_id"] as? Int {
  99. if self.groupChatId == 0 || chatId != self.groupChatId {
  100. return
  101. }
  102. self.updateGroupContactIdsOnQRCodeInvite()
  103. }
  104. }
  105. }
  106. }
  107. override func viewWillDisappear(_ animated: Bool) {
  108. if let observer = self.contactAddedObserver {
  109. NotificationCenter.default.removeObserver(observer)
  110. }
  111. }
  112. private func checkDoneButton() {
  113. var nameOk = true
  114. if !createBroadcast {
  115. let name = groupNameCell.textField.text ?? ""
  116. nameOk = !name.isEmpty
  117. }
  118. doneButton.isEnabled = nameOk && contactIdsForGroup.count >= 1
  119. }
  120. @objc func doneButtonPressed() {
  121. if createBroadcast {
  122. groupChatId = dcContext.createBroadcastList()
  123. } else if groupChatId == 0 {
  124. groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  125. } else {
  126. _ = dcContext.setChatName(chatId: groupChatId, name: groupName)
  127. }
  128. for contactId in contactIdsForGroup {
  129. _ = dcContext.addContactToChat(chatId: groupChatId, contactId: contactId)
  130. }
  131. if let groupImage = changeGroupImage {
  132. AvatarHelper.saveChatAvatar(dcContext: dcContext, image: groupImage, for: groupChatId)
  133. } else if deleteGroupImage {
  134. AvatarHelper.saveChatAvatar(dcContext: dcContext, image: nil, for: groupChatId)
  135. }
  136. showGroupChat(chatId: Int(groupChatId))
  137. }
  138. override func numberOfSections(in _: UITableView) -> Int {
  139. return sections.count
  140. }
  141. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  142. let row = indexPath.row
  143. switch sections[indexPath.section] {
  144. case .details:
  145. if detailsRows[row] == .avatar {
  146. return avatarSelectionCell
  147. } else {
  148. return groupNameCell
  149. }
  150. case .invite:
  151. if inviteRows[row] == .addMembers {
  152. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  153. if let actionCell = cell as? ActionCell {
  154. actionCell.actionTitle = String.localized(createBroadcast ? "add_recipients" : "group_add_members")
  155. actionCell.actionColor = UIColor.systemBlue
  156. actionCell.isUserInteractionEnabled = true
  157. }
  158. return cell
  159. } else {
  160. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  161. if let actionCell = cell as? ActionCell {
  162. actionCell.actionTitle = String.localized("qrshow_join_group_title")
  163. actionCell.actionColor = groupName.isEmpty ? DcColors.colorDisabled : UIColor.systemBlue
  164. actionCell.isUserInteractionEnabled = !groupName.isEmpty
  165. qrInviteCodeCell = actionCell
  166. }
  167. return cell
  168. }
  169. case .members:
  170. let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
  171. if let contactCell = cell as? ContactCell {
  172. let contact = dcContext.getContact(id: groupContactIds[row])
  173. let displayName = contact.displayName
  174. contactCell.titleLabel.text = displayName
  175. contactCell.subtitleLabel.text = contact.email
  176. contactCell.avatar.setName(displayName)
  177. contactCell.avatar.setColor(contact.color)
  178. if let profileImage = contact.profileImage {
  179. contactCell.avatar.setImage(profileImage)
  180. }
  181. contactCell.setVerified(isVerified: contact.isVerified)
  182. contactCell.selectionStyle = .none
  183. }
  184. return cell
  185. }
  186. }
  187. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  188. if sections[section] == .details && isVerifiedGroup {
  189. return String.localized("verified_group_explain")
  190. } else if sections[section] == .invite && createBroadcast {
  191. return String.localized("chat_new_broadcast_hint")
  192. }
  193. return nil
  194. }
  195. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  196. switch sections[indexPath.section] {
  197. case .details, .invite:
  198. return UITableView.automaticDimension
  199. case .members:
  200. return ContactCell.cellHeight
  201. }
  202. }
  203. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  204. switch sections[section] {
  205. case .details:
  206. return detailsRows.count
  207. case .invite:
  208. return inviteRows.count
  209. case .members:
  210. return contactIdsForGroup.count
  211. }
  212. }
  213. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  214. if sections[section] == .members && !contactIdsForGroup.isEmpty {
  215. if createBroadcast {
  216. return String.localized(stringID: "n_recipients", count: contactIdsForGroup.count)
  217. } else {
  218. return String.localized(stringID: "n_members", count: contactIdsForGroup.count)
  219. }
  220. }
  221. return nil
  222. }
  223. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  224. if sections[indexPath.section] == .invite {
  225. tableView.deselectRow(at: indexPath, animated: false)
  226. if inviteRows[indexPath.row] == .addMembers {
  227. var contactsWithoutSelf = contactIdsForGroup
  228. contactsWithoutSelf.remove(Int(DC_CONTACT_ID_SELF))
  229. showAddMembers(preselectedMembers: contactsWithoutSelf, isVerified: self.isVerifiedGroup)
  230. } else {
  231. self.groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  232. showQrCodeInvite(chatId: Int(self.groupChatId))
  233. }
  234. }
  235. }
  236. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  237. let row = indexPath.row
  238. // swipe by delete
  239. if sections[indexPath.section] == .members, groupContactIds[indexPath.row] != DC_CONTACT_ID_SELF {
  240. let delete = UITableViewRowAction(style: .destructive, title: String.localized("remove_desktop")) { [weak self] _, indexPath in
  241. guard let self = self else { return }
  242. if self.groupChatId != 0,
  243. self.dcContext.getChat(chatId: self.groupChatId).getContactIds(self.dcContext).contains(self.groupContactIds[row]) {
  244. let success = self.dcContext.removeContactFromChat(chatId: self.groupChatId, contactId: self.groupContactIds[row])
  245. if success {
  246. self.removeGroupContactFromList(at: indexPath)
  247. }
  248. } else {
  249. self.removeGroupContactFromList(at: indexPath)
  250. }
  251. }
  252. delete.backgroundColor = UIColor.red
  253. return [delete]
  254. } else {
  255. return nil
  256. }
  257. }
  258. private func updateGroupName(textView: UITextField) {
  259. let name = textView.text ?? ""
  260. groupName = name
  261. qrInviteCodeCell?.isUserInteractionEnabled = name.containsCharacters()
  262. qrInviteCodeCell?.actionColor = groupName.isEmpty ? DcColors.colorDisabled : UIColor.systemBlue
  263. checkDoneButton()
  264. }
  265. private func onAvatarTapped() {
  266. let alert = UIAlertController(title: String.localized("group_avatar"), message: nil, preferredStyle: .safeActionSheet)
  267. alert.addAction(PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:)))
  268. alert.addAction(PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:)))
  269. if avatarSelectionCell.isAvatarSet() {
  270. alert.addAction(UIAlertAction(title: String.localized("delete"), style: .destructive, handler: deleteGroupAvatarPressed(_:)))
  271. }
  272. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  273. self.present(alert, animated: true, completion: nil)
  274. }
  275. private func galleryButtonPressed(_ action: UIAlertAction) {
  276. showPhotoPicker(delegate: self)
  277. }
  278. private func cameraButtonPressed(_ action: UIAlertAction) {
  279. showCamera(delegate: self)
  280. }
  281. private func deleteGroupAvatarPressed(_ action: UIAlertAction) {
  282. changeGroupImage = nil
  283. deleteGroupImage = true
  284. avatarSelectionCell.setAvatar(image: nil)
  285. }
  286. func onImageSelected(image: UIImage) {
  287. changeGroupImage = image
  288. deleteGroupImage = false
  289. avatarSelectionCell.setAvatar(image: changeGroupImage)
  290. }
  291. func updateGroupContactIdsOnQRCodeInvite() {
  292. for contactId in dcContext.getChat(chatId: groupChatId).getContactIds(dcContext) {
  293. contactIdsForGroup.insert(contactId)
  294. }
  295. groupContactIds = Array(contactIdsForGroup)
  296. self.tableView.reloadData()
  297. checkDoneButton()
  298. }
  299. func updateGroupContactIdsOnListSelection(_ members: Set<Int>) {
  300. if groupChatId != 0 {
  301. var members = members
  302. for contactId in dcContext.getChat(chatId: groupChatId).getContactIds(dcContext) {
  303. members.insert(contactId)
  304. }
  305. }
  306. contactIdsForGroup = members
  307. groupContactIds = Array(members)
  308. self.tableView.reloadData()
  309. checkDoneButton()
  310. }
  311. func removeGroupContactFromList(at indexPath: IndexPath) {
  312. let row = indexPath.row
  313. self.contactIdsForGroup.remove(self.groupContactIds[row])
  314. self.groupContactIds.remove(at: row)
  315. CATransaction.begin()
  316. CATransaction.setCompletionBlock {
  317. self.tableView.reloadData() // needed to update the "N members"-title, however do not interrupt the nice delete-animation
  318. self.checkDoneButton()
  319. }
  320. tableView.deleteRows(at: [indexPath], with: .fade)
  321. CATransaction.commit()
  322. }
  323. // MARK: - coordinator
  324. private func showGroupChat(chatId: Int) {
  325. if let chatlistViewController = navigationController?.viewControllers[0] {
  326. let chatViewController = ChatViewController(dcContext: dcContext, chatId: chatId)
  327. navigationController?.setViewControllers([chatlistViewController, chatViewController], animated: true)
  328. }
  329. }
  330. private func showPhotoPicker(delegate: MediaPickerDelegate) {
  331. mediaPicker?.showPhotoGallery()
  332. }
  333. private func showCamera(delegate: MediaPickerDelegate) {
  334. mediaPicker?.showCamera(allowCropping: true, supportedMediaTypes: .photo)
  335. }
  336. private func showQrCodeInvite(chatId: Int) {
  337. var hint = ""
  338. let dcChat = dcContext.getChat(chatId: chatId)
  339. if !dcChat.name.isEmpty {
  340. hint = String.localizedStringWithFormat(String.localized("qrshow_join_group_hint"), dcChat.name)
  341. }
  342. let qrInviteCodeController = QrViewController(dcContext: dcContext, chatId: chatId, qrCodeHint: hint)
  343. qrInviteCodeController.onDismissed = { [weak self] in
  344. self?.updateGroupContactIdsOnQRCodeInvite()
  345. }
  346. navigationController?.pushViewController(qrInviteCodeController, animated: true)
  347. }
  348. private func showAddMembers(preselectedMembers: Set<Int>, isVerified: Bool) {
  349. let newGroupController = AddGroupMembersViewController(dcContext: dcContext,
  350. preselected: preselectedMembers,
  351. isVerified: isVerified,
  352. isBroadcast: createBroadcast)
  353. newGroupController.onMembersSelected = { [weak self] (memberIds: Set<Int>) -> Void in
  354. guard let self = self else { return }
  355. var memberIds = memberIds
  356. if !self.createBroadcast {
  357. memberIds.insert(Int(DC_CONTACT_ID_SELF))
  358. }
  359. self.updateGroupContactIdsOnListSelection(memberIds)
  360. }
  361. navigationController?.pushViewController(newGroupController, animated: true)
  362. }
  363. }
  364. extension NewGroupController: UITextFieldDelegate {
  365. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  366. textField.resignFirstResponder()
  367. return true
  368. }
  369. }