NewGroupController.swift 15 KB

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