NewGroupController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. var groupImage: UIImage?
  10. let isVerifiedGroup: Bool
  11. let dcContext: DcContext
  12. private var contactAddedObserver: NSObjectProtocol?
  13. ///TODO: remove the the line below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  14. private var workaroundObserver: NSObjectProtocol?
  15. private let sectionGroupDetails = 0
  16. private let sectionGroupDetailsRowAvatar = 0
  17. private let sectionGroupDetailsRowName = 1
  18. private let countSectionGroupDetails = 2
  19. private let sectionInvite = 1
  20. private let sectionInviteRowAddMembers = 0
  21. private let sectionInviteRowShowQrCode = 1
  22. private lazy var countSectionInvite: Int = 2
  23. private let sectionGroupMembers = 2
  24. private lazy var mediaPicker: MediaPicker? = {
  25. return MediaPicker(navigationController: navigationController)
  26. }()
  27. lazy var groupNameCell: TextFieldCell = {
  28. let cell = TextFieldCell(description: String.localized("group_name"), placeholder: String.localized("group_name"))
  29. cell.onTextFieldChange = self.updateGroupName
  30. cell.textField.autocorrectionType = UITextAutocorrectionType.no
  31. return cell
  32. }()
  33. lazy var avatarSelectionCell: AvatarSelectionCell = {
  34. let cell = AvatarSelectionCell(context: nil)
  35. cell.hintLabel.text = String.localized("group_avatar")
  36. cell.onAvatarTapped = onAvatarTapped
  37. return cell
  38. }()
  39. var qrInviteCodeCell: ActionCell?
  40. init(dcContext: DcContext, isVerified: Bool) {
  41. self.contactIdsForGroup = [Int(DC_CONTACT_ID_SELF)]
  42. self.groupContactIds = Array(contactIdsForGroup)
  43. self.isVerifiedGroup = isVerified
  44. self.dcContext = dcContext
  45. super.init(style: .grouped)
  46. }
  47. required init?(coder _: NSCoder) {
  48. fatalError("init(coder:) has not been implemented")
  49. }
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. title = isVerifiedGroup ? String.localized("menu_new_verified_group") : String.localized("menu_new_group")
  53. doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed))
  54. navigationItem.rightBarButtonItem = doneButton
  55. doneButton.isEnabled = false
  56. tableView.register(ContactCell.self, forCellReuseIdentifier: "contactCell")
  57. tableView.register(ActionCell.self, forCellReuseIdentifier: "actionCell")
  58. self.hideKeyboardOnTap()
  59. }
  60. override func viewWillAppear(_ animated: Bool) {
  61. let nc = NotificationCenter.default
  62. contactAddedObserver = nc.addObserver(
  63. forName: dcNotificationChatModified,
  64. object: nil,
  65. queue: nil
  66. ) { [weak self] notification in
  67. guard let self = self else { return }
  68. if let ui = notification.userInfo {
  69. if let chatId = ui["chat_id"] as? Int {
  70. if self.groupChatId == 0 || chatId != self.groupChatId {
  71. return
  72. }
  73. self.updateGroupContactIdsOnQRCodeInvite()
  74. }
  75. }
  76. }
  77. ///TODO: remove the the lines below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  78. workaroundObserver = nc.addObserver(
  79. forName: dcNotificationChanged,
  80. object: nil,
  81. queue: nil
  82. ) { [weak self] notification in
  83. guard let self = self else { return }
  84. if let ui = notification.userInfo {
  85. if let chatId = ui["chat_id"] as? Int {
  86. if self.groupChatId == 0 || chatId != self.groupChatId {
  87. return
  88. }
  89. self.updateGroupContactIdsOnQRCodeInvite()
  90. }
  91. }
  92. }
  93. }
  94. override func viewWillDisappear(_ animated: Bool) {
  95. if let observer = self.contactAddedObserver {
  96. NotificationCenter.default.removeObserver(observer)
  97. }
  98. ///TODO: remove the the lines below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  99. if let workaroundObserver = self.workaroundObserver {
  100. NotificationCenter.default.removeObserver(workaroundObserver)
  101. }
  102. }
  103. @objc func doneButtonPressed() {
  104. if groupChatId == 0 {
  105. groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  106. } else {
  107. _ = dcContext.setChatName(chatId: groupChatId, name: groupName)
  108. }
  109. for contactId in contactIdsForGroup {
  110. let success = dcContext.addContactToChat(chatId: groupChatId, contactId: contactId)
  111. if let groupImage = groupImage {
  112. AvatarHelper.saveChatAvatar(dcContext: dcContext, image: groupImage, for: Int(groupChatId))
  113. }
  114. if success {
  115. logger.info("successfully added \(contactId) to group \(groupName)")
  116. } else {
  117. logger.error("failed to add \(contactId) to group \(groupName)")
  118. }
  119. }
  120. showGroupChat(chatId: Int(groupChatId))
  121. }
  122. override func numberOfSections(in _: UITableView) -> Int {
  123. return 3
  124. }
  125. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  126. let section = indexPath.section
  127. let row = indexPath.row
  128. switch section {
  129. case sectionGroupDetails:
  130. if row == sectionGroupDetailsRowAvatar {
  131. return avatarSelectionCell
  132. } else {
  133. return groupNameCell
  134. }
  135. case sectionInvite:
  136. if row == sectionInviteRowAddMembers {
  137. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  138. if let actionCell = cell as? ActionCell {
  139. actionCell.actionTitle = String.localized("group_add_members")
  140. actionCell.actionColor = UIColor.systemBlue
  141. actionCell.isUserInteractionEnabled = true
  142. }
  143. return cell
  144. } else {
  145. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  146. if let actionCell = cell as? ActionCell {
  147. actionCell.actionTitle = String.localized("qrshow_join_group_title")
  148. actionCell.actionColor = groupName.isEmpty ? DcColors.colorDisabled : UIColor.systemBlue
  149. actionCell.isUserInteractionEnabled = !groupName.isEmpty
  150. qrInviteCodeCell = actionCell
  151. }
  152. return cell
  153. }
  154. default:
  155. let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
  156. if let contactCell = cell as? ContactCell {
  157. let contact = DcContact(id: groupContactIds[row])
  158. let displayName = contact.displayName
  159. contactCell.titleLabel.text = displayName
  160. contactCell.subtitleLabel.text = contact.email
  161. contactCell.avatar.setName(displayName)
  162. contactCell.avatar.setColor(contact.color)
  163. if let profileImage = contact.profileImage {
  164. contactCell.avatar.setImage(profileImage)
  165. }
  166. contactCell.setVerified(isVerified: contact.isVerified)
  167. }
  168. return cell
  169. }
  170. }
  171. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  172. if section == sectionGroupDetails && isVerifiedGroup {
  173. return String.localized("verified_group_explain")
  174. }
  175. return nil
  176. }
  177. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  178. let section = indexPath.section
  179. switch section {
  180. case sectionGroupDetails, sectionInvite:
  181. return UITableView.automaticDimension
  182. default:
  183. return ContactCell.cellHeight
  184. }
  185. }
  186. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  187. switch section {
  188. case sectionGroupDetails:
  189. return countSectionGroupDetails
  190. case sectionInvite:
  191. return countSectionInvite
  192. default:
  193. return contactIdsForGroup.count
  194. }
  195. }
  196. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  197. if section == sectionGroupMembers {
  198. return String.localized("in_this_group_desktop")
  199. } else {
  200. return nil
  201. }
  202. }
  203. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  204. let section = indexPath.section
  205. let row = indexPath.row
  206. if section == sectionInvite {
  207. if row == sectionInviteRowAddMembers {
  208. var contactsWithoutSelf = contactIdsForGroup
  209. contactsWithoutSelf.remove(Int(DC_CONTACT_ID_SELF))
  210. showAddMembers(preselectedMembers: contactsWithoutSelf, isVerified: self.isVerifiedGroup)
  211. } else {
  212. self.groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  213. showQrCodeInvite(chatId: Int(self.groupChatId))
  214. }
  215. }
  216. }
  217. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  218. let section = indexPath.section
  219. let row = indexPath.row
  220. //swipe by delete
  221. if section == sectionGroupMembers, groupContactIds[row] != DC_CONTACT_ID_SELF {
  222. let delete = UITableViewRowAction(style: .destructive, title: String.localized("remove_desktop")) { [weak self] _, indexPath in
  223. guard let self = self else { return }
  224. if self.groupChatId != 0,
  225. self.dcContext.getChat(chatId: self.groupChatId).contactIds.contains(self.groupContactIds[row]) {
  226. let success = self.dcContext.removeContactFromChat(chatId: self.groupChatId, contactId: self.groupContactIds[row])
  227. if success {
  228. self.removeGroupContactFromList(at: indexPath)
  229. }
  230. } else {
  231. self.removeGroupContactFromList(at: indexPath)
  232. }
  233. }
  234. delete.backgroundColor = UIColor.red
  235. return [delete]
  236. } else {
  237. return nil
  238. }
  239. }
  240. private func updateGroupName(textView: UITextField) {
  241. let name = textView.text ?? ""
  242. groupName = name
  243. doneButton.isEnabled = name.containsCharacters()
  244. qrInviteCodeCell?.isUserInteractionEnabled = name.containsCharacters()
  245. qrInviteCodeCell?.actionColor = groupName.isEmpty ? DcColors.colorDisabled : UIColor.systemBlue
  246. }
  247. private func onAvatarTapped() {
  248. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  249. let photoAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  250. let videoAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  251. alert.addAction(photoAction)
  252. alert.addAction(videoAction)
  253. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  254. self.present(alert, animated: true, completion: nil)
  255. }
  256. private func galleryButtonPressed(_ action: UIAlertAction) {
  257. showPhotoPicker(delegate: self)
  258. }
  259. private func cameraButtonPressed(_ action: UIAlertAction) {
  260. showCamera(delegate: self)
  261. }
  262. func onImageSelected(image: UIImage) {
  263. groupImage = image
  264. avatarSelectionCell = AvatarSelectionCell(context: nil, with: groupImage)
  265. avatarSelectionCell.hintLabel.text = String.localized("group_avatar")
  266. avatarSelectionCell.onAvatarTapped = onAvatarTapped
  267. self.tableView.beginUpdates()
  268. let indexPath = IndexPath(row: sectionGroupDetailsRowAvatar, section: sectionGroupDetails)
  269. self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
  270. self.tableView.endUpdates()
  271. }
  272. func updateGroupContactIdsOnQRCodeInvite() {
  273. for contactId in dcContext.getChat(chatId: groupChatId).contactIds {
  274. contactIdsForGroup.insert(contactId)
  275. }
  276. groupContactIds = Array(contactIdsForGroup)
  277. self.tableView.reloadData()
  278. }
  279. func updateGroupContactIdsOnListSelection(_ members: Set<Int>) {
  280. if groupChatId != 0 {
  281. var members = members
  282. for contactId in dcContext.getChat(chatId: groupChatId).contactIds {
  283. members.insert(contactId)
  284. }
  285. }
  286. contactIdsForGroup = members
  287. groupContactIds = Array(members)
  288. self.tableView.reloadData()
  289. }
  290. func removeGroupContactFromList(at indexPath: IndexPath) {
  291. let row = indexPath.row
  292. self.contactIdsForGroup.remove(self.groupContactIds[row])
  293. self.groupContactIds.remove(at: row)
  294. tableView.deleteRows(at: [indexPath], with: .fade)
  295. }
  296. // MARK: - coordinator
  297. private func showGroupChat(chatId: Int) {
  298. if let chatlistViewController = navigationController?.viewControllers[0] {
  299. let chatViewController = ChatViewController(dcContext: dcContext, chatId: chatId)
  300. navigationController?.setViewControllers([chatlistViewController, chatViewController], animated: true)
  301. }
  302. }
  303. private func showPhotoPicker(delegate: MediaPickerDelegate) {
  304. mediaPicker?.showPhotoGallery(delegate: delegate)
  305. }
  306. private func showCamera(delegate: MediaPickerDelegate) {
  307. mediaPicker?.showCamera(delegate: delegate)
  308. }
  309. private func showQrCodeInvite(chatId: Int) {
  310. var hint = ""
  311. let dcChat = dcContext.getChat(chatId: chatId)
  312. if !dcChat.name.isEmpty {
  313. hint = String.localizedStringWithFormat(String.localized("qrshow_join_group_hint"), dcChat.name)
  314. }
  315. let qrInviteCodeController = QrViewController(dcContext: dcContext, chatId: chatId, qrCodeHint: hint)
  316. qrInviteCodeController.onDismissed = { [weak self] in
  317. self?.updateGroupContactIdsOnQRCodeInvite()
  318. }
  319. navigationController?.pushViewController(qrInviteCodeController, animated: true)
  320. }
  321. private func showAddMembers(preselectedMembers: Set<Int>, isVerified: Bool) {
  322. let newGroupController = NewGroupAddMembersViewController(preselected: preselectedMembers,
  323. isVerified: isVerified)
  324. newGroupController.onMembersSelected = { [weak self] (memberIds: Set<Int>) -> Void in
  325. guard let self = self else { return }
  326. self.updateGroupContactIdsOnListSelection(memberIds)
  327. self.navigationController?.popViewController(animated: true)
  328. }
  329. navigationController?.pushViewController(newGroupController, animated: true)
  330. }
  331. }