NewGroupController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import UIKit
  2. import DcCore
  3. class NewGroupController: UITableViewController, MediaPickerDelegate {
  4. weak var coordinator: NewGroupCoordinator?
  5. var groupName: String = ""
  6. var groupChatId: Int = 0
  7. var doneButton: UIBarButtonItem!
  8. var contactIdsForGroup: Set<Int> // TODO: check if array is sufficient
  9. var groupContactIds: [Int]
  10. var groupImage: UIImage?
  11. let isVerifiedGroup: Bool
  12. let dcContext: DcContext
  13. private var contactAddedObserver: NSObjectProtocol?
  14. ///TODO: remove the the line below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  15. private var workaroundObserver: NSObjectProtocol?
  16. private let sectionGroupDetails = 0
  17. private let sectionGroupDetailsRowAvatar = 0
  18. private let sectionGroupDetailsRowName = 1
  19. private let countSectionGroupDetails = 2
  20. private let sectionInvite = 1
  21. private let sectionInviteRowAddMembers = 0
  22. private let sectionInviteRowShowQrCode = 1
  23. private lazy var countSectionInvite: Int = 2
  24. private let sectionGroupMembers = 2
  25. lazy var groupNameCell: TextFieldCell = {
  26. let cell = TextFieldCell(description: String.localized("group_name"), placeholder: String.localized("group_name"))
  27. cell.onTextFieldChange = self.updateGroupName
  28. cell.textField.autocorrectionType = UITextAutocorrectionType.no
  29. return cell
  30. }()
  31. lazy var avatarSelectionCell: AvatarSelectionCell = {
  32. let cell = AvatarSelectionCell(context: nil)
  33. cell.hintLabel.text = String.localized("group_avatar")
  34. cell.onAvatarTapped = onAvatarTapped
  35. return cell
  36. }()
  37. var qrInviteCodeCell: ActionCell?
  38. init(dcContext: DcContext, isVerified: Bool) {
  39. self.contactIdsForGroup = [Int(DC_CONTACT_ID_SELF)]
  40. self.groupContactIds = Array(contactIdsForGroup)
  41. self.isVerifiedGroup = isVerified
  42. self.dcContext = dcContext
  43. super.init(style: .grouped)
  44. }
  45. required init?(coder _: NSCoder) {
  46. fatalError("init(coder:) has not been implemented")
  47. }
  48. override func viewDidLoad() {
  49. super.viewDidLoad()
  50. title = isVerifiedGroup ? String.localized("menu_new_verified_group") : String.localized("menu_new_group")
  51. doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed))
  52. navigationItem.rightBarButtonItem = doneButton
  53. doneButton.isEnabled = false
  54. tableView.register(ContactCell.self, forCellReuseIdentifier: "contactCell")
  55. tableView.register(ActionCell.self, forCellReuseIdentifier: "actionCell")
  56. self.hideKeyboardOnTap()
  57. }
  58. override func viewWillAppear(_ animated: Bool) {
  59. let nc = NotificationCenter.default
  60. contactAddedObserver = nc.addObserver(
  61. forName: dcNotificationChatModified,
  62. object: nil,
  63. queue: nil
  64. ) { notification in
  65. if let ui = notification.userInfo {
  66. if let chatId = ui["chat_id"] as? Int {
  67. if self.groupChatId == 0 || chatId != self.groupChatId {
  68. return
  69. }
  70. self.updateGroupContactIdsOnQRCodeInvite()
  71. }
  72. }
  73. }
  74. ///TODO: remove the the lines below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  75. workaroundObserver = nc.addObserver(
  76. forName: dcNotificationChanged,
  77. object: nil,
  78. queue: nil
  79. ) { notification in
  80. if let ui = notification.userInfo {
  81. if let chatId = ui["chat_id"] as? Int {
  82. if self.groupChatId == 0 || chatId != self.groupChatId {
  83. return
  84. }
  85. self.updateGroupContactIdsOnQRCodeInvite()
  86. }
  87. }
  88. }
  89. }
  90. override func viewWillDisappear(_ animated: Bool) {
  91. if let observer = self.contactAddedObserver {
  92. NotificationCenter.default.removeObserver(observer)
  93. }
  94. ///TODO: remove the the lines below as soon as deltachat-core 4b7b6d6cb3c26d817e3f3eeb6a20d8e8c66a4578 was released
  95. if let workaroundObserver = self.workaroundObserver {
  96. NotificationCenter.default.removeObserver(workaroundObserver)
  97. }
  98. }
  99. @objc func doneButtonPressed() {
  100. if groupChatId == 0 {
  101. groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  102. } else {
  103. _ = dcContext.setChatName(chatId: groupChatId, name: groupName)
  104. }
  105. for contactId in contactIdsForGroup {
  106. let success = dcContext.addContactToChat(chatId: groupChatId, contactId: contactId)
  107. if let groupImage = groupImage, let dcContext = coordinator?.dcContext {
  108. AvatarHelper.saveChatAvatar(dcContext: dcContext, image: groupImage, for: Int(groupChatId))
  109. }
  110. if success {
  111. logger.info("successfully added \(contactId) to group \(groupName)")
  112. } else {
  113. logger.error("failed to add \(contactId) to group \(groupName)")
  114. }
  115. }
  116. coordinator?.showGroupChat(chatId: Int(groupChatId))
  117. }
  118. override func didReceiveMemoryWarning() {
  119. super.didReceiveMemoryWarning()
  120. // Dispose of any resources that can be recreated.
  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. let row = indexPath.row
  180. switch section {
  181. case sectionGroupDetails:
  182. if row == sectionGroupDetailsRowAvatar {
  183. return AvatarSelectionCell.cellSize
  184. } else {
  185. return Constants.defaultCellHeight
  186. }
  187. case sectionInvite:
  188. return Constants.defaultCellHeight
  189. default:
  190. return ContactCell.cellHeight
  191. }
  192. }
  193. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  194. switch section {
  195. case sectionGroupDetails:
  196. return countSectionGroupDetails
  197. case sectionInvite:
  198. return countSectionInvite
  199. default:
  200. return contactIdsForGroup.count
  201. }
  202. }
  203. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  204. if section == sectionGroupMembers {
  205. return String.localized("in_this_group_desktop")
  206. } else {
  207. return nil
  208. }
  209. }
  210. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  211. let section = indexPath.section
  212. let row = indexPath.row
  213. if section == sectionInvite {
  214. if row == sectionInviteRowAddMembers {
  215. var contactsWithoutSelf = contactIdsForGroup
  216. contactsWithoutSelf.remove(Int(DC_CONTACT_ID_SELF))
  217. coordinator?.showAddMembers(preselectedMembers: contactsWithoutSelf, isVerified: self.isVerifiedGroup)
  218. } else {
  219. self.groupChatId = dcContext.createGroupChat(verified: isVerifiedGroup, name: groupName)
  220. coordinator?.showQrCodeInvite(chatId: Int(self.groupChatId))
  221. }
  222. }
  223. }
  224. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  225. let section = indexPath.section
  226. let row = indexPath.row
  227. //swipe by delete
  228. if section == sectionGroupMembers, groupContactIds[row] != DC_CONTACT_ID_SELF {
  229. let delete = UITableViewRowAction(style: .destructive, title: String.localized("remove_desktop")) { [unowned self] _, indexPath in
  230. if self.groupChatId != 0, self.dcContext.getChat(chatId: self.groupChatId).contactIds.contains(self.groupContactIds[row]) {
  231. let success = self.dcContext.removeContactFromChat(chatId: self.groupChatId, contactId: self.groupContactIds[row])
  232. if success {
  233. self.removeGroupContactFromList(at: indexPath)
  234. }
  235. } else {
  236. self.removeGroupContactFromList(at: indexPath)
  237. }
  238. }
  239. delete.backgroundColor = UIColor.red
  240. return [delete]
  241. } else {
  242. return nil
  243. }
  244. }
  245. private func updateGroupName(textView: UITextField) {
  246. let name = textView.text ?? ""
  247. groupName = name
  248. doneButton.isEnabled = name.containsCharacters()
  249. qrInviteCodeCell?.isUserInteractionEnabled = name.containsCharacters()
  250. qrInviteCodeCell?.actionColor = groupName.isEmpty ? DcColors.colorDisabled : UIColor.systemBlue
  251. }
  252. private func onAvatarTapped() {
  253. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  254. let photoAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  255. let videoAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  256. alert.addAction(photoAction)
  257. alert.addAction(videoAction)
  258. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  259. self.present(alert, animated: true, completion: nil)
  260. }
  261. private func galleryButtonPressed(_ action: UIAlertAction) {
  262. coordinator?.showPhotoPicker(delegate: self)
  263. }
  264. private func cameraButtonPressed(_ action: UIAlertAction) {
  265. coordinator?.showCamera(delegate: self)
  266. }
  267. func onImageSelected(image: UIImage) {
  268. groupImage = image
  269. avatarSelectionCell = AvatarSelectionCell(context: nil, with: groupImage)
  270. avatarSelectionCell.hintLabel.text = String.localized("group_avatar")
  271. avatarSelectionCell.onAvatarTapped = onAvatarTapped
  272. self.tableView.beginUpdates()
  273. let indexPath = IndexPath(row: sectionGroupDetailsRowAvatar, section: sectionGroupDetails)
  274. self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
  275. self.tableView.endUpdates()
  276. }
  277. func updateGroupContactIdsOnQRCodeInvite() {
  278. for contactId in dcContext.getChat(chatId: groupChatId).contactIds {
  279. contactIdsForGroup.insert(contactId)
  280. }
  281. groupContactIds = Array(contactIdsForGroup)
  282. self.tableView.reloadData()
  283. }
  284. func updateGroupContactIdsOnListSelection(_ members: Set<Int>) {
  285. if groupChatId != 0 {
  286. var members = members
  287. for contactId in dcContext.getChat(chatId: groupChatId).contactIds {
  288. members.insert(contactId)
  289. }
  290. }
  291. contactIdsForGroup = members
  292. groupContactIds = Array(members)
  293. self.tableView.reloadData()
  294. }
  295. func removeGroupContactFromList(at indexPath: IndexPath) {
  296. let row = indexPath.row
  297. self.contactIdsForGroup.remove(self.groupContactIds[row])
  298. self.groupContactIds.remove(at: row)
  299. tableView.deleteRows(at: [indexPath], with: .fade)
  300. }
  301. }