ChatViewController.swift 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. protocol MediaSendHandler {
  9. func onSuccess()
  10. }
  11. extension ChatViewController: MediaSendHandler {
  12. func onSuccess() {
  13. refreshMessages()
  14. }
  15. }
  16. extension ChatViewController: MediaPickerDelegate {
  17. func onVideoSelected(url: NSURL) {
  18. sendVideo(url: url)
  19. }
  20. func onImageSelected(url: NSURL) {
  21. sendImage(url: url)
  22. }
  23. func onImageSelected(image: UIImage) {
  24. sendImage(image)
  25. }
  26. func onVoiceMessageRecorded(url: NSURL) {
  27. sendVoiceMessage(url: url)
  28. }
  29. func onDocumentSelected(url: NSURL) {
  30. sendDocumentMessage(url: url)
  31. }
  32. }
  33. class ChatViewController: MessagesViewController {
  34. var dcContext: DcContext
  35. let outgoingAvatarOverlap: CGFloat = 17.5
  36. let loadCount = 30
  37. let chatId: Int
  38. var messageList: [DcMsg] = []
  39. var msgChangedObserver: Any?
  40. var incomingMsgObserver: Any?
  41. private lazy var refreshControl: UIRefreshControl = {
  42. let refreshControl = UIRefreshControl()
  43. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  44. return UIRefreshControl()
  45. }()
  46. private weak var timer: Timer?
  47. lazy var navBarTap: UITapGestureRecognizer = {
  48. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  49. }()
  50. private var locationStreamingItem: UIBarButtonItem = {
  51. let indicator = LocationStreamingIndicator()
  52. return UIBarButtonItem(customView: indicator)
  53. }()
  54. private lazy var muteItem: UIBarButtonItem = {
  55. let imageView = UIImageView()
  56. imageView.tintColor = DcColors.defaultTextColor
  57. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  58. imageView.translatesAutoresizingMaskIntoConstraints = false
  59. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  60. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  61. return UIBarButtonItem(customView: imageView)
  62. }()
  63. private lazy var badgeItem: UIBarButtonItem = {
  64. let badge: InitialsBadge
  65. let chat = dcContext.getChat(chatId: chatId)
  66. if let image = chat.profileImage {
  67. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  68. } else {
  69. badge = InitialsBadge(
  70. name: chat.name,
  71. color: chat.color,
  72. size: 28,
  73. accessibilityLabel: String.localized("menu_view_profile")
  74. )
  75. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  76. }
  77. badge.setVerified(chat.isVerified)
  78. badge.accessibilityTraits = .button
  79. return UIBarButtonItem(customView: badge)
  80. }()
  81. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and udpate audio cell UI accordingly.
  82. open lazy var audioController = BasicAudioController(messageCollectionView: messagesCollectionView)
  83. private var disableWriting: Bool
  84. private var showNamesAboveMessage: Bool
  85. var showCustomNavBar = true
  86. private lazy var mediaPicker: MediaPicker? = {
  87. return MediaPicker(navigationController: navigationController)
  88. }()
  89. var emptyStateView: EmptyStateLabel = {
  90. let view = EmptyStateLabel()
  91. return view
  92. }()
  93. override var inputAccessoryView: UIView? {
  94. if disableWriting {
  95. return nil
  96. }
  97. return messageInputBar
  98. }
  99. init(dcContext: DcContext, chatId: Int) {
  100. let dcChat = dcContext.getChat(chatId: chatId)
  101. self.dcContext = dcContext
  102. self.chatId = chatId
  103. self.disableWriting = !dcChat.canSend
  104. self.showNamesAboveMessage = dcChat.isGroup
  105. super.init(nibName: nil, bundle: nil)
  106. hidesBottomBarWhenPushed = true
  107. }
  108. required init?(coder _: NSCoder) {
  109. fatalError("init(coder:) has not been implemented")
  110. }
  111. override func viewDidLoad() {
  112. messagesCollectionView.register(InfoMessageCell.self)
  113. super.viewDidLoad()
  114. if !dcContext.isConfigured() {
  115. // TODO: display message about nothing being configured
  116. return
  117. }
  118. configureMessageCollectionView()
  119. configureEmptyStateView()
  120. if !disableWriting {
  121. configureMessageInputBar()
  122. messageInputBar.inputTextView.text = textDraft
  123. messageInputBar.inputTextView.becomeFirstResponder()
  124. }
  125. let notificationCenter = NotificationCenter.default
  126. notificationCenter.addObserver(self,
  127. selector: #selector(setTextDraft),
  128. name: UIApplication.willResignActiveNotification,
  129. object: nil)
  130. }
  131. private func startTimer() {
  132. timer?.invalidate()
  133. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  134. //reload table
  135. DispatchQueue.main.async {
  136. guard let self = self else { return }
  137. self.messageList = self.getMessageIds(self.messageList.count)
  138. self.messagesCollectionView.reloadDataAndKeepOffset()
  139. self.refreshControl.endRefreshing()
  140. }
  141. }
  142. }
  143. private func stopTimer() {
  144. timer?.invalidate()
  145. }
  146. private func configureEmptyStateView() {
  147. view.addSubview(emptyStateView)
  148. emptyStateView.translatesAutoresizingMaskIntoConstraints = false
  149. emptyStateView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  150. emptyStateView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  151. emptyStateView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  152. }
  153. override func viewWillAppear(_ animated: Bool) {
  154. super.viewWillAppear(animated)
  155. // this will be removed in viewWillDisappear
  156. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  157. if showCustomNavBar {
  158. updateTitle(chat: dcContext.getChat(chatId: chatId))
  159. }
  160. configureMessageMenu()
  161. let nc = NotificationCenter.default
  162. msgChangedObserver = nc.addObserver(
  163. forName: dcNotificationChanged,
  164. object: nil,
  165. queue: OperationQueue.main
  166. ) { [weak self] notification in
  167. guard let self = self else { return }
  168. if let ui = notification.userInfo {
  169. if self.disableWriting {
  170. // always refresh, as we can't check currently
  171. self.refreshMessages()
  172. } else if let id = ui["message_id"] as? Int {
  173. if id > 0 {
  174. self.updateMessage(id)
  175. } else {
  176. // change might be a deletion
  177. self.refreshMessages()
  178. }
  179. }
  180. if self.showCustomNavBar {
  181. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  182. }
  183. }
  184. }
  185. incomingMsgObserver = nc.addObserver(
  186. forName: dcNotificationIncoming,
  187. object: nil, queue: OperationQueue.main
  188. ) {  [weak self] notification in
  189. guard let self = self else { return }
  190. if let ui = notification.userInfo {
  191. if self.chatId == ui["chat_id"] as? Int {
  192. if let id = ui["message_id"] as? Int {
  193. if id > 0 {
  194. self.insertMessage(DcMsg(id: id))
  195. }
  196. }
  197. }
  198. }
  199. }
  200. loadFirstMessages()
  201. if RelayHelper.sharedInstance.isForwarding() {
  202. askToForwardMessage()
  203. }
  204. }
  205. override func viewDidAppear(_ animated: Bool) {
  206. super.viewDidAppear(animated)
  207. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  208. // things that do not affect the chatview
  209. // and are delayed after the view is displayed
  210. dcContext.marknoticedChat(chatId: chatId)
  211. let array = dcContext.getFreshMessages()
  212. UIApplication.shared.applicationIconBadgeNumber = array.count
  213. startTimer()
  214. }
  215. override func viewWillDisappear(_ animated: Bool) {
  216. super.viewWillDisappear(animated)
  217. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  218. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  219. }
  220. override func viewDidDisappear(_ animated: Bool) {
  221. super.viewDidDisappear(animated)
  222. AppStateRestorer.shared.resetLastActiveChat()
  223. setTextDraft()
  224. let nc = NotificationCenter.default
  225. if let msgChangedObserver = self.msgChangedObserver {
  226. nc.removeObserver(msgChangedObserver)
  227. }
  228. if let incomingMsgObserver = self.incomingMsgObserver {
  229. nc.removeObserver(incomingMsgObserver)
  230. }
  231. audioController.stopAnyOngoingPlaying()
  232. stopTimer()
  233. }
  234. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  235. let lastSectionVisibleBeforeTransition = self.isLastSectionVisible()
  236. coordinator.animate(
  237. alongsideTransition: { [weak self] _ in
  238. guard let self = self else { return }
  239. if self.showCustomNavBar {
  240. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  241. }
  242. },
  243. completion: {[weak self] _ in
  244. guard let self = self else { return }
  245. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  246. self.messagesCollectionView.reloadDataAndKeepOffset()
  247. if lastSectionVisibleBeforeTransition {
  248. self.messagesCollectionView.scrollToBottom(animated: false)
  249. }
  250. }
  251. )
  252. super.viewWillTransition(to: size, with: coordinator)
  253. }
  254. private func updateTitle(chat: DcChat) {
  255. let titleView = ChatTitleView()
  256. var subtitle = "ErrSubtitle"
  257. let chatContactIds = chat.contactIds
  258. if chat.isGroup {
  259. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  260. } else if chatContactIds.count >= 1 {
  261. if chat.isDeviceTalk {
  262. subtitle = String.localized("device_talk_subtitle")
  263. } else if chat.isSelfTalk {
  264. subtitle = String.localized("chat_self_talk_subtitle")
  265. } else {
  266. subtitle = DcContact(id: chatContactIds[0]).email
  267. }
  268. }
  269. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  270. navigationItem.titleView = titleView
  271. var rightBarButtonItems = [badgeItem]
  272. if chat.isSendingLocations {
  273. rightBarButtonItems.append(locationStreamingItem)
  274. }
  275. if chat.isMuted {
  276. rightBarButtonItems.append(muteItem)
  277. }
  278. navigationItem.rightBarButtonItems = rightBarButtonItems
  279. }
  280. @objc
  281. private func loadMoreMessages() {
  282. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  283. DispatchQueue.main.async { [weak self] in
  284. guard let self = self else { return }
  285. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  286. self.messagesCollectionView.reloadDataAndKeepOffset()
  287. self.refreshControl.endRefreshing()
  288. }
  289. }
  290. }
  291. @objc
  292. private func refreshMessages() {
  293. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  294. DispatchQueue.main.async { [weak self] in
  295. guard let self = self else { return }
  296. self.messageList = self.getMessageIds(self.messageList.count)
  297. self.messagesCollectionView.reloadDataAndKeepOffset()
  298. self.refreshControl.endRefreshing()
  299. if self.isLastSectionVisible() {
  300. self.messagesCollectionView.scrollToBottom(animated: true)
  301. }
  302. self.showEmptyStateView(self.messageList.isEmpty)
  303. }
  304. }
  305. }
  306. private func loadFirstMessages() {
  307. DispatchQueue.global(qos: .userInitiated).async {
  308. DispatchQueue.main.async { [weak self] in
  309. guard let self = self else { return }
  310. self.messageList = self.getMessageIds(self.loadCount)
  311. self.messagesCollectionView.reloadData()
  312. self.refreshControl.endRefreshing()
  313. self.messagesCollectionView.scrollToBottom(animated: false)
  314. self.showEmptyStateView(self.messageList.isEmpty)
  315. }
  316. }
  317. }
  318. private func showEmptyStateView(_ show: Bool) {
  319. if show {
  320. let dcChat = dcContext.getChat(chatId: chatId)
  321. if chatId == DC_CHAT_ID_DEADDROP {
  322. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  323. emptyStateView.text = String.localized("chat_no_contact_requests")
  324. } else {
  325. emptyStateView.text = String.localized("chat_no_messages")
  326. }
  327. } else if dcChat.isGroup {
  328. if dcChat.isUnpromoted {
  329. emptyStateView.text = String.localized("chat_new_group_hint")
  330. } else {
  331. emptyStateView.text = String.localized("chat_no_messages")
  332. }
  333. } else if dcChat.isSelfTalk {
  334. emptyStateView.text = String.localized("saved_messages_explain")
  335. } else if dcChat.isDeviceTalk {
  336. emptyStateView.text = String.localized("device_talk_explain")
  337. } else {
  338. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  339. }
  340. emptyStateView.isHidden = false
  341. } else {
  342. emptyStateView.isHidden = true
  343. }
  344. }
  345. private var textDraft: String? {
  346. return dcContext.getDraft(chatId: chatId)
  347. }
  348. private func getMessageIds(_ count: Int, from: Int? = nil) -> [DcMsg] {
  349. let ids = dcContext.getMessageIds(chatId: chatId, count: count, from: from)
  350. let markIds: [UInt32] = ids.map { UInt32($0) }
  351. dcContext.markSeenMessages(messageIds: markIds, count: ids.count)
  352. return ids.map {
  353. DcMsg(id: $0)
  354. }
  355. }
  356. @objc private func setTextDraft() {
  357. if let text = self.messageInputBar.inputTextView.text {
  358. dcContext.setDraft(chatId: chatId, draftText: text)
  359. }
  360. }
  361. private func configureMessageMenu() {
  362. var menuItems: [UIMenuItem]
  363. menuItems = [
  364. UIMenuItem(title: String.localized("info"), action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  365. UIMenuItem(title: String.localized("delete"), action: #selector(MessageCollectionViewCell.messageDelete(_:))),
  366. UIMenuItem(title: String.localized("forward"), action: #selector(MessageCollectionViewCell.messageForward(_:)))
  367. ]
  368. UIMenuController.shared.menuItems = menuItems
  369. }
  370. private func configureMessageCollectionView() {
  371. messagesCollectionView.messagesDataSource = self
  372. messagesCollectionView.messageCellDelegate = self
  373. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  374. maintainPositionOnKeyboardFrameChanged = true // default false
  375. messagesCollectionView.backgroundColor = DcColors.chatBackgroundColor
  376. messagesCollectionView.addSubview(refreshControl)
  377. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  378. layout?.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 2, right: 8)
  379. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  380. layout?.setMessageOutgoingAvatarSize(.zero)
  381. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right,
  382. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  383. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right,
  384. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  385. // Set outgoing avatar to overlap with the message bubble
  386. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left,
  387. textInsets: UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 0)))
  388. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  389. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(
  390. top: 0, left: -18, bottom: 0, right: 0))
  391. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left,
  392. textInsets: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)))
  393. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  394. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  395. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  396. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  397. messagesCollectionView.messagesLayoutDelegate = self
  398. messagesCollectionView.messagesDisplayDelegate = self
  399. }
  400. private func configureMessageInputBar() {
  401. messageInputBar.delegate = self
  402. messageInputBar.inputTextView.tintColor = DcColors.primary
  403. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  404. messageInputBar.separatorLine.isHidden = true
  405. messageInputBar.inputTextView.tintColor = DcColors.primary
  406. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  407. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  408. scrollsToBottomOnKeyboardBeginsEditing = true
  409. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  410. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  411. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  412. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  413. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  414. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  415. messageInputBar.inputTextView.layer.borderWidth = 1.0
  416. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  417. messageInputBar.inputTextView.layer.masksToBounds = true
  418. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  419. configureInputBarItems()
  420. }
  421. private func configureInputBarItems() {
  422. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  423. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  424. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  425. messageInputBar.sendButton.image = sendButtonImage
  426. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  427. messageInputBar.sendButton.accessibilityTraits = .button
  428. messageInputBar.sendButton.title = nil
  429. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  430. messageInputBar.sendButton.layer.cornerRadius = 20
  431. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  432. // this adds a padding between textinputfield and send button
  433. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  434. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  435. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  436. let leftItems = [
  437. InputBarButtonItem()
  438. .configure {
  439. $0.spacing = .fixed(0)
  440. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  441. $0.image = clipperIcon
  442. $0.tintColor = DcColors.primary
  443. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  444. $0.accessibilityLabel = String.localized("menu_add_attachment")
  445. $0.accessibilityTraits = .button
  446. }.onSelected {
  447. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  448. }.onDeselected {
  449. $0.tintColor = DcColors.primary
  450. }.onTouchUpInside { [weak self] _ in
  451. self?.clipperButtonPressed()
  452. }
  453. ]
  454. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  455. // This just adds some more flare
  456. messageInputBar.sendButton
  457. .onEnabled { item in
  458. UIView.animate(withDuration: 0.3, animations: {
  459. item.backgroundColor = DcColors.primary
  460. })
  461. }.onDisabled { item in
  462. UIView.animate(withDuration: 0.3, animations: {
  463. item.backgroundColor = DcColors.colorDisabled
  464. })
  465. }
  466. }
  467. @objc private func chatProfilePressed() {
  468. if chatId != DC_CHAT_ID_DEADDROP {
  469. showChatDetail(chatId: chatId)
  470. }
  471. }
  472. // MARK: - UICollectionViewDataSource
  473. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  474. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  475. fatalError("notMessagesCollectionView")
  476. }
  477. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  478. fatalError("nilMessagesDataSource")
  479. }
  480. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  481. switch message.kind {
  482. case .text, .attributedText, .emoji:
  483. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  484. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  485. return cell
  486. case .info:
  487. let cell = messagesCollectionView.dequeueReusableCell(InfoMessageCell.self, for: indexPath)
  488. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  489. return cell
  490. case .photo, .video:
  491. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  492. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  493. return cell
  494. case .photoText, .videoText:
  495. let cell = messagesCollectionView.dequeueReusableCell(TextMediaMessageCell.self, for: indexPath)
  496. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  497. return cell
  498. case .animatedImageText:
  499. let cell = messagesCollectionView.dequeueReusableCell(AnimatedImageMessageCell.self, for: indexPath)
  500. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  501. return cell
  502. case .fileText:
  503. let cell = messagesCollectionView.dequeueReusableCell(FileMessageCell.self, for: indexPath)
  504. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  505. return cell
  506. case .location:
  507. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  508. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  509. return cell
  510. case .contact:
  511. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  512. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  513. return cell
  514. case .custom:
  515. let cell = messagesCollectionView.dequeueReusableCell(InfoMessageCell.self, for: indexPath)
  516. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  517. return cell
  518. case .audio:
  519. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  520. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  521. return cell
  522. }
  523. }
  524. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  525. if action == NSSelectorFromString("messageInfo:") ||
  526. action == NSSelectorFromString("messageDelete:") ||
  527. action == NSSelectorFromString("messageForward:") {
  528. return true
  529. } else {
  530. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  531. }
  532. }
  533. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  534. switch action {
  535. case NSSelectorFromString("messageInfo:"):
  536. let msg = messageList[indexPath.section]
  537. logger.info("message: View info \(msg.messageId)")
  538. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  539. if let ctrl = navigationController {
  540. ctrl.pushViewController(msgViewController, animated: true)
  541. }
  542. case NSSelectorFromString("messageDelete:"):
  543. let msg = messageList[indexPath.section]
  544. logger.info("message: delete \(msg.messageId)")
  545. askToDeleteMessage(id: msg.id)
  546. case NSSelectorFromString("messageForward:"):
  547. let msg = messageList[indexPath.section]
  548. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  549. navigationController?.popViewController(animated: true)
  550. default:
  551. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  552. }
  553. }
  554. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  555. let alert = UIAlertController(title: title,
  556. message: nil,
  557. preferredStyle: .safeActionSheet)
  558. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  559. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  560. self.dismiss(animated: true, completion: nil)
  561. }))
  562. present(alert, animated: true, completion: nil)
  563. }
  564. private func askToChatWith(email: String) {
  565. let contactId = self.dcContext.createContact(name: "", email: email)
  566. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  567. self.dismiss(animated: true, completion: nil)
  568. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  569. self.showChat(chatId: chatId)
  570. } else {
  571. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  572. actionTitle: String.localized("start_chat"),
  573. actionHandler: { _ in
  574. self.dismiss(animated: true, completion: nil)
  575. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  576. self.showChat(chatId: chatId)})
  577. }
  578. }
  579. private func askToDeleteMessage(id: Int) {
  580. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  581. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  582. actionHandler: { _ in
  583. self.dcContext.deleteMessage(msgId: id)
  584. self.dismiss(animated: true, completion: nil)})
  585. }
  586. private func askToForwardMessage() {
  587. let chat = dcContext.getChat(chatId: self.chatId)
  588. if chat.isSelfTalk {
  589. RelayHelper.sharedInstance.forward(to: self.chatId)
  590. } else {
  591. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  592. actionTitle: String.localized("menu_forward"),
  593. actionHandler: { _ in
  594. RelayHelper.sharedInstance.forward(to: self.chatId)
  595. self.dismiss(animated: true, completion: nil)},
  596. cancelHandler: { _ in
  597. self.dismiss(animated: false, completion: nil)
  598. self.navigationController?.popViewController(animated: true)})
  599. }
  600. }
  601. // MARK: - coordinator
  602. private func showChatDetail(chatId: Int) {
  603. let chat = dcContext.getChat(chatId: chatId)
  604. switch chat.chatType {
  605. case .SINGLE:
  606. if let contactId = chat.contactIds.first {
  607. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  608. navigationController?.pushViewController(contactDetailController, animated: true)
  609. }
  610. case .GROUP, .VERIFIEDGROUP:
  611. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  612. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  613. }
  614. }
  615. private func showContactDetail(of contactId: Int, in chatOfType: ChatType, chatId: Int?) {
  616. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  617. navigationController?.pushViewController(contactDetailController, animated: true)
  618. }
  619. func showChat(chatId: Int) {
  620. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  621. navigationController?.popToRootViewController(animated: false)
  622. appDelegate.appCoordinator.showChat(chatId: chatId)
  623. }
  624. }
  625. private func showDocumentLibrary(delegate: MediaPickerDelegate) {
  626. mediaPicker?.showDocumentLibrary(delegate: delegate)
  627. }
  628. private func showVoiceMessageRecorder(delegate: MediaPickerDelegate) {
  629. mediaPicker?.showVoiceRecorder(delegate: delegate)
  630. }
  631. private func showCameraViewController(delegate: MediaPickerDelegate) {
  632. mediaPicker?.showCamera(delegate: delegate, allowCropping: false)
  633. }
  634. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  635. mediaPicker?.showPhotoVideoLibrary(delegate: delegate)
  636. }
  637. private func showMediaGallery(currentIndex: Int, mediaUrls urls: [URL]) {
  638. let betterPreviewController = PreviewController(currentIndex: currentIndex, urls: urls)
  639. let nav = UINavigationController(rootViewController: betterPreviewController)
  640. nav.modalPresentationStyle = .fullScreen
  641. navigationController?.present(nav, animated: true)
  642. }
  643. }
  644. // MARK: - MessagesDataSource
  645. extension ChatViewController: MessagesDataSource {
  646. func numberOfSections(in _: MessagesCollectionView) -> Int {
  647. return messageList.count
  648. }
  649. func currentSender() -> SenderType {
  650. let currentSender = Sender(senderId: "1", displayName: "Alice")
  651. return currentSender
  652. }
  653. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  654. return messageList[indexPath.section]
  655. }
  656. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  657. let message = messageList[indexPath.section]
  658. let contact = message.fromContact
  659. return Avatar(image: contact.profileImage, initials: DcUtils.getInitials(inputName: contact.displayName))
  660. }
  661. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  662. if isInfoMessage(at: indexPath) {
  663. return nil
  664. }
  665. if isTimeLabelVisible(at: indexPath) {
  666. return NSAttributedString(
  667. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  668. attributes: [
  669. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  670. NSAttributedString.Key.foregroundColor: DcColors.grayTextColor,
  671. ]
  672. )
  673. }
  674. return nil
  675. }
  676. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  677. var attributedString: NSMutableAttributedString?
  678. if showNamesAboveMessage && !isPreviousMessageSameSender(at: indexPath) {
  679. let name = message.sender.displayName
  680. let m = messageList[indexPath.section]
  681. attributedString = NSMutableAttributedString(string: name, attributes: [
  682. .font: UIFont.systemFont(ofSize: 14),
  683. .foregroundColor: m.fromContact.color,
  684. ])
  685. }
  686. if isMessageForwarded(at: indexPath) {
  687. let forwardedString = NSMutableAttributedString(string: String.localized("forwarded_message"), attributes: [
  688. .font: UIFont.systemFont(ofSize: 14),
  689. .foregroundColor: DcColors.grayTextColor,
  690. ])
  691. if attributedString == nil {
  692. attributedString = forwardedString
  693. } else {
  694. attributedString?.append(NSAttributedString(string: "\n", attributes: nil))
  695. attributedString?.append(forwardedString)
  696. }
  697. }
  698. return attributedString
  699. }
  700. func isMessageForwarded(at indexPath: IndexPath) -> Bool {
  701. let m = messageList[indexPath.section]
  702. return m.isForwarded
  703. }
  704. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  705. guard indexPath.section + 1 < messageList.count else { return false }
  706. let messageA = messageList[indexPath.section]
  707. let messageB = messageList[indexPath.section + 1]
  708. if messageA.fromContactId == messageB.fromContactId {
  709. return false
  710. }
  711. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  712. let dateA = messageA.sentDate
  713. let dateB = messageB.sentDate
  714. let dayA = (calendar?.component(.day, from: dateA))
  715. let dayB = (calendar?.component(.day, from: dateB))
  716. return dayA != dayB
  717. }
  718. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  719. guard indexPath.section - 1 >= 0 else { return false }
  720. let messageA = messageList[indexPath.section - 1]
  721. let messageB = messageList[indexPath.section]
  722. if messageA.isInfo {
  723. return false
  724. }
  725. return messageA.fromContactId == messageB.fromContactId
  726. }
  727. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  728. return messageList[indexPath.section].isInfo
  729. }
  730. func isImmediateNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  731. guard indexPath.section + 1 < messageList.count else { return false }
  732. let messageA = messageList[indexPath.section]
  733. let messageB = messageList[indexPath.section + 1]
  734. if messageA.isInfo {
  735. return false
  736. }
  737. let dateA = messageA.sentDate
  738. let dateB = messageB.sentDate
  739. let timeinterval = dateB.timeIntervalSince(dateA)
  740. let minute = 60.0
  741. return messageA.fromContactId == messageB.fromContactId && timeinterval.isLessThanOrEqualTo(minute)
  742. }
  743. func isAvatarHidden(at indexPath: IndexPath) -> Bool {
  744. let message = messageList[indexPath.section]
  745. return isNextMessageSameSender(at: indexPath) || message.isInfo
  746. }
  747. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  748. guard indexPath.section + 1 < messageList.count else { return false }
  749. let messageA = messageList[indexPath.section]
  750. let messageB = messageList[indexPath.section + 1]
  751. if messageA.isInfo {
  752. return false
  753. }
  754. return messageA.fromContactId == messageB.fromContactId
  755. }
  756. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  757. guard indexPath.section < messageList.count else { return nil }
  758. let m = messageList[indexPath.section]
  759. if m.isInfo || isImmediateNextMessageSameSender(at: indexPath) {
  760. return nil
  761. }
  762. var timestampAttributes: [NSAttributedString.Key: Any] = [
  763. .font: UIFont.systemFont(ofSize: 12),
  764. .foregroundColor: DcColors.grayDateColor,
  765. .paragraphStyle: NSParagraphStyle()
  766. ]
  767. let text = NSMutableAttributedString()
  768. if isFromCurrentSender(message: message) {
  769. if let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle {
  770. style.alignment = .right
  771. timestampAttributes[.paragraphStyle] = style
  772. }
  773. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  774. if m.showPadlock() {
  775. attachPadlock(to: text)
  776. }
  777. attachSendingState(m.state, to: text)
  778. return text
  779. }
  780. if !isAvatarHidden(at: indexPath) {
  781. if let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle {
  782. style.firstLineHeadIndent = 22
  783. timestampAttributes[.paragraphStyle] = style
  784. }
  785. }
  786. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  787. if m.showPadlock() {
  788. attachPadlock(to: text)
  789. }
  790. return text
  791. }
  792. private func attachPadlock(to text: NSMutableAttributedString) {
  793. let imageAttachment = NSTextAttachment()
  794. imageAttachment.image = UIImage(named: "ic_lock")
  795. imageAttachment.image?.accessibilityIdentifier = String.localized("encrypted_message")
  796. let imageString = NSMutableAttributedString(attachment: imageAttachment)
  797. imageString.addAttributes([NSAttributedString.Key.baselineOffset: -1], range: NSRange(location: 0, length: 1))
  798. text.append(NSAttributedString(string: " "))
  799. text.append(imageString)
  800. }
  801. private func attachSendingState(_ state: Int, to text: NSMutableAttributedString) {
  802. let imageAttachment = NSTextAttachment()
  803. var offset = -4
  804. switch Int32(state) {
  805. case DC_STATE_OUT_PENDING, DC_STATE_OUT_PREPARING:
  806. imageAttachment.image = #imageLiteral(resourceName: "ic_hourglass_empty_white_36pt").scaleDownImage(toMax: 16)?.maskWithColor(color: DcColors.grayDateColor)
  807. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_sending")
  808. offset = -2
  809. case DC_STATE_OUT_DELIVERED:
  810. imageAttachment.image = #imageLiteral(resourceName: "ic_done_36pt").scaleDownImage(toMax: 18)
  811. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_delivered")
  812. case DC_STATE_OUT_MDN_RCVD:
  813. imageAttachment.image = #imageLiteral(resourceName: "ic_done_all_36pt").scaleDownImage(toMax: 18)
  814. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_read")
  815. text.append(NSAttributedString(string: " "))
  816. case DC_STATE_OUT_FAILED:
  817. imageAttachment.image = #imageLiteral(resourceName: "ic_error_36pt").scaleDownImage(toMax: 16)
  818. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_error")
  819. offset = -2
  820. default:
  821. imageAttachment.image = nil
  822. }
  823. let imageString = NSMutableAttributedString(attachment: imageAttachment)
  824. imageString.addAttributes([.baselineOffset: offset],
  825. range: NSRange(location: 0, length: 1))
  826. text.append(imageString)
  827. }
  828. func updateMessage(_ messageId: Int) {
  829. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  830. dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  831. messageList[index] = DcMsg(id: messageId)
  832. // Reload section to update header/footer labels
  833. messagesCollectionView.performBatchUpdates({ [weak self] in
  834. guard let self = self else { return }
  835. self.messagesCollectionView.reloadSections([index])
  836. if index > 0 {
  837. self.messagesCollectionView.reloadSections([index - 1])
  838. }
  839. if index < messageList.count - 1 {
  840. self.messagesCollectionView.reloadSections([index + 1])
  841. }
  842. }, completion: { [weak self] _ in
  843. if self?.isLastSectionVisible() == true {
  844. self?.messagesCollectionView.scrollToBottom(animated: true)
  845. }
  846. })
  847. } else {
  848. let msg = DcMsg(id: messageId)
  849. if msg.chatId == chatId {
  850. insertMessage(msg)
  851. }
  852. }
  853. }
  854. func insertMessage(_ message: DcMsg) {
  855. dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  856. messageList.append(message)
  857. emptyStateView.isHidden = true
  858. // Reload last section to update header/footer labels and insert a new one
  859. messagesCollectionView.performBatchUpdates({
  860. messagesCollectionView.insertSections([messageList.count - 1])
  861. if messageList.count >= 2 {
  862. messagesCollectionView.reloadSections([messageList.count - 2])
  863. }
  864. }, completion: { [weak self] _ in
  865. if self?.isLastSectionVisible() == true {
  866. self?.messagesCollectionView.scrollToBottom(animated: true)
  867. }
  868. })
  869. }
  870. private func sendTextMessage(message: String) {
  871. DispatchQueue.global().async {
  872. self.dcContext.sendTextInChat(id: self.chatId, message: message)
  873. }
  874. }
  875. private func sendImage(_ image: UIImage, message: String? = nil) {
  876. DispatchQueue.global().async {
  877. if let path = DcUtils.saveImage(image: image) {
  878. self.sendImageMessage(viewType: DC_MSG_IMAGE, image: image, filePath: path)
  879. }
  880. }
  881. }
  882. private func sendAnimatedImage(url: NSURL) {
  883. if let path = url.path {
  884. let result = SDAnimatedImage(contentsOfFile: path)
  885. if let result = result,
  886. let animatedImageData = result.animatedImageData,
  887. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  888. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  889. }
  890. }
  891. }
  892. private func sendImageMessage(viewType: Int32, image: UIImage, filePath: String, message: String? = nil) {
  893. let msg = DcMsg(viewType: viewType)
  894. msg.setFile(filepath: filePath)
  895. msg.text = (message ?? "").isEmpty ? nil : message
  896. msg.sendInChat(id: self.chatId)
  897. }
  898. private func sendDocumentMessage(url: NSURL) {
  899. DispatchQueue.global().async {
  900. let msg = DcMsg(viewType: DC_MSG_FILE)
  901. msg.setFile(filepath: url.relativePath, mimeType: nil)
  902. msg.sendInChat(id: self.chatId)
  903. }
  904. }
  905. private func sendVoiceMessage(url: NSURL) {
  906. DispatchQueue.global().async {
  907. let msg = DcMsg(viewType: DC_MSG_VOICE)
  908. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  909. msg.sendInChat(id: self.chatId)
  910. }
  911. }
  912. private func sendVideo(url: NSURL) {
  913. DispatchQueue.global().async {
  914. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  915. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  916. msg.sendInChat(id: self.chatId)
  917. }
  918. }
  919. private func sendImage(url: NSURL) {
  920. if url.pathExtension == "gif" {
  921. sendAnimatedImage(url: url)
  922. } else if let data = try? Data(contentsOf: url as URL),
  923. let image = UIImage(data: data) {
  924. sendImage(image)
  925. }
  926. }
  927. func isLastSectionVisible() -> Bool {
  928. guard !messageList.isEmpty else { return false }
  929. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  930. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  931. }
  932. }
  933. // MARK: - MessagesDisplayDelegate
  934. extension ChatViewController: MessagesDisplayDelegate {
  935. // MARK: - Text Messages
  936. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  937. return DcColors.defaultTextColor
  938. }
  939. // MARK: - All Messages
  940. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  941. return isFromCurrentSender(message: message) ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  942. }
  943. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  944. if isInfoMessage(at: indexPath) {
  945. //styling is hard-coded in info cell
  946. return .none
  947. }
  948. var corners: UIRectCorner = []
  949. if isFromCurrentSender(message: message) {
  950. corners.formUnion(.topLeft)
  951. corners.formUnion(.bottomLeft)
  952. if !isPreviousMessageSameSender(at: indexPath) {
  953. corners.formUnion(.topRight)
  954. }
  955. if !isNextMessageSameSender(at: indexPath) {
  956. corners.formUnion(.bottomRight)
  957. }
  958. } else {
  959. corners.formUnion(.topRight)
  960. corners.formUnion(.bottomRight)
  961. if !isPreviousMessageSameSender(at: indexPath) {
  962. corners.formUnion(.topLeft)
  963. }
  964. if !isNextMessageSameSender(at: indexPath) {
  965. corners.formUnion(.bottomLeft)
  966. }
  967. }
  968. return .custom { view in
  969. let radius: CGFloat = 16
  970. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  971. let mask = CAShapeLayer()
  972. mask.path = path.cgPath
  973. view.layer.mask = mask
  974. }
  975. }
  976. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  977. let message = messageList[indexPath.section]
  978. let contact = message.fromContact
  979. let avatar = Avatar(image: contact.profileImage, initials: DcUtils.getInitials(inputName: contact.displayName))
  980. avatarView.set(avatar: avatar)
  981. avatarView.isHidden = isAvatarHidden(at: indexPath)
  982. avatarView.backgroundColor = contact.color
  983. }
  984. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  985. return [.url, .phoneNumber]
  986. }
  987. func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] {
  988. return [ NSAttributedString.Key.foregroundColor: DcColors.defaultTextColor,
  989. NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
  990. NSAttributedString.Key.underlineColor: DcColors.defaultTextColor ]
  991. }
  992. }
  993. // MARK: - MessagesLayoutDelegate
  994. extension ChatViewController: MessagesLayoutDelegate {
  995. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  996. if isTimeLabelVisible(at: indexPath) {
  997. return 18
  998. }
  999. return 0
  1000. }
  1001. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1002. if isInfoMessage(at: indexPath) {
  1003. return 0
  1004. }
  1005. if !isPreviousMessageSameSender(at: indexPath) {
  1006. return 40
  1007. } else if isMessageForwarded(at: indexPath) {
  1008. return 20
  1009. }
  1010. return 0
  1011. }
  1012. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1013. if isInfoMessage(at: indexPath) {
  1014. return 0
  1015. }
  1016. if !isImmediateNextMessageSameSender(at: indexPath) {
  1017. return 16
  1018. }
  1019. return 0
  1020. }
  1021. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  1022. return 40
  1023. }
  1024. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  1025. return CGSize(width: messagesCollectionView.bounds.width, height: 20)
  1026. }
  1027. @objc private func clipperButtonPressed() {
  1028. showClipperOptions()
  1029. }
  1030. private func showClipperOptions() {
  1031. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  1032. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  1033. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  1034. let documentAction = UIAlertAction(title: String.localized("documents"), style: .default, handler: documentActionPressed(_:))
  1035. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  1036. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1037. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  1038. style: isLocationStreaming ? .destructive : .default,
  1039. handler: locationStreamingButtonPressed(_:))
  1040. alert.addAction(cameraAction)
  1041. alert.addAction(galleryAction)
  1042. alert.addAction(documentAction)
  1043. alert.addAction(voiceMessageAction)
  1044. if UserDefaults.standard.bool(forKey: "location_streaming") {
  1045. alert.addAction(locationStreamingAction)
  1046. }
  1047. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1048. self.present(alert, animated: true, completion: {
  1049. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  1050. // but this hack does the trick
  1051. if UIAccessibility.isVoiceOverRunning {
  1052. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  1053. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  1054. }
  1055. }
  1056. })
  1057. }
  1058. private func documentActionPressed(_ action: UIAlertAction) {
  1059. showDocumentLibrary(delegate: self)
  1060. }
  1061. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  1062. showVoiceMessageRecorder(delegate: self)
  1063. }
  1064. private func cameraButtonPressed(_ action: UIAlertAction) {
  1065. showCameraViewController(delegate: self)
  1066. }
  1067. private func galleryButtonPressed(_ action: UIAlertAction) {
  1068. showPhotoVideoLibrary(delegate: self)
  1069. }
  1070. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  1071. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1072. if isLocationStreaming {
  1073. locationStreamingFor(seconds: 0)
  1074. } else {
  1075. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  1076. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  1077. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  1078. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  1079. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  1080. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  1081. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1082. self.present(alert, animated: true, completion: nil)
  1083. }
  1084. }
  1085. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  1086. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  1087. self.locationStreamingFor(seconds: duration)
  1088. })
  1089. alert.addAction(action)
  1090. }
  1091. private func locationStreamingFor(seconds: Int) {
  1092. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  1093. return
  1094. }
  1095. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  1096. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  1097. }
  1098. }
  1099. // MARK: - MessageCellDelegate
  1100. extension ChatViewController: MessageCellDelegate {
  1101. @objc func didTapMessage(in cell: MessageCollectionViewCell) {
  1102. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1103. let message = messageList[indexPath.section]
  1104. if message.isSetupMessage {
  1105. didTapAsm(msg: message, orgText: "")
  1106. } else if let url = message.fileURL {
  1107. // find all other messages with same message type
  1108. let previousUrls: [URL] = message.previousMediaURLs()
  1109. let nextUrls: [URL] = message.nextMediaURLs()
  1110. // these are the files user will be able to swipe trough
  1111. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  1112. showMediaGallery(currentIndex: previousUrls.count, mediaUrls: mediaUrls)
  1113. }
  1114. }
  1115. }
  1116. private func didTapAsm(msg: DcMsg, orgText: String) {
  1117. let inputDlg = UIAlertController(
  1118. title: String.localized("autocrypt_continue_transfer_title"),
  1119. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1120. preferredStyle: .alert)
  1121. inputDlg.addTextField(configurationHandler: { (textField) in
  1122. textField.placeholder = msg.setupCodeBegin + ".."
  1123. textField.text = orgText
  1124. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1125. })
  1126. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1127. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1128. let textField = inputDlg.textFields![0]
  1129. let modText = textField.text ?? ""
  1130. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1131. let alert = UIAlertController(
  1132. title: String.localized("autocrypt_continue_transfer_title"),
  1133. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1134. preferredStyle: .alert)
  1135. if success {
  1136. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1137. } else {
  1138. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1139. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1140. self.didTapAsm(msg: msg, orgText: modText)
  1141. })
  1142. alert.addAction(retryAction)
  1143. alert.preferredAction = retryAction
  1144. }
  1145. self.navigationController?.present(alert, animated: true, completion: nil)
  1146. })
  1147. inputDlg.addAction(okAction)
  1148. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1149. navigationController?.present(inputDlg, animated: true, completion: nil)
  1150. }
  1151. @objc func didTapAvatar(in cell: MessageCollectionViewCell) {
  1152. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1153. let message = messageList[indexPath.section]
  1154. let chat = dcContext.getChat(chatId: chatId)
  1155. showContactDetail(of: message.fromContact.id, in: chat.chatType, chatId: chatId)
  1156. }
  1157. }
  1158. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  1159. logger.info("Top label tapped")
  1160. }
  1161. @objc(didTapCellBottomLabelIn:) func didTapCellBottomLabel(in _: MessageCollectionViewCell) {
  1162. print("Bottom label tapped")
  1163. }
  1164. func didTapPlayButton(in cell: AudioMessageCell) {
  1165. guard let indexPath = messagesCollectionView.indexPath(for: cell),
  1166. let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
  1167. print("Failed to identify message when audio cell receive tap gesture")
  1168. return
  1169. }
  1170. guard audioController.state != .stopped else {
  1171. // There is no audio sound playing - prepare to start playing for given audio message
  1172. audioController.playSound(for: message, in: cell)
  1173. return
  1174. }
  1175. if audioController.playingMessage?.messageId == message.messageId {
  1176. // tap occur in the current cell that is playing audio sound
  1177. if audioController.state == .playing {
  1178. audioController.pauseSound(for: message, in: cell)
  1179. } else {
  1180. audioController.resumeSound()
  1181. }
  1182. } else {
  1183. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  1184. audioController.stopAnyOngoingPlaying()
  1185. audioController.playSound(for: message, in: cell)
  1186. }
  1187. }
  1188. func didStartAudio(in cell: AudioMessageCell) {
  1189. print("audio started")
  1190. }
  1191. func didStopAudio(in cell: AudioMessageCell) {
  1192. print("audio stopped")
  1193. }
  1194. func didPauseAudio(in cell: AudioMessageCell) {
  1195. print("audio paused")
  1196. }
  1197. @objc func didTapBackground(in cell: MessageCollectionViewCell) {
  1198. print("background of message tapped")
  1199. }
  1200. }
  1201. // MARK: - MessageLabelDelegate
  1202. extension ChatViewController: MessageLabelDelegate {
  1203. func didSelectPhoneNumber(_ phoneNumber: String) {
  1204. logger.info("phone open", phoneNumber)
  1205. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1206. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  1207. UIApplication.shared.open(url as URL)
  1208. }
  1209. }
  1210. }
  1211. func didSelectURL(_ url: URL) {
  1212. if Utils.isEmail(url: url) {
  1213. print("tapped on contact")
  1214. let email = Utils.getEmailFrom(url)
  1215. self.askToChatWith(email: email)
  1216. ///TODO: implement handling
  1217. } else {
  1218. UIApplication.shared.open(url)
  1219. }
  1220. }
  1221. }
  1222. // MARK: - LocationMessageDisplayDelegate
  1223. /*
  1224. extension ChatViewController: LocationMessageDisplayDelegate {
  1225. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  1226. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  1227. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  1228. annotationView.image = pinImage
  1229. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  1230. return annotationView
  1231. }
  1232. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  1233. return { view in
  1234. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  1235. view.alpha = 0.0
  1236. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  1237. view.layer.transform = CATransform3DIdentity
  1238. view.alpha = 1.0
  1239. }, completion: nil)
  1240. }
  1241. }
  1242. }
  1243. */
  1244. // MARK: - MessageInputBarDelegate
  1245. extension ChatViewController: InputBarAccessoryViewDelegate {
  1246. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1247. if inputBar.inputTextView.images.isEmpty {
  1248. self.sendTextMessage(message: text.trimmingCharacters(in: .whitespacesAndNewlines))
  1249. } else {
  1250. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1251. .trimmingCharacters(in: .whitespacesAndNewlines)
  1252. // only 1 attachment allowed for now, thus it takes the first one
  1253. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1254. }
  1255. inputBar.inputTextView.text = String()
  1256. inputBar.inputTextView.attributedText = nil
  1257. }
  1258. }
  1259. /*
  1260. extension ChatViewController: MessageInputBarDelegate {
  1261. }
  1262. */
  1263. // MARK: - MessageCollectionViewCell
  1264. extension MessageCollectionViewCell {
  1265. @objc func messageForward(_ sender: Any?) {
  1266. // Get the collectionView
  1267. if let collectionView = self.superview as? UICollectionView {
  1268. // Get indexPath
  1269. if let indexPath = collectionView.indexPath(for: self) {
  1270. // Trigger action
  1271. collectionView.delegate?.collectionView?(collectionView,
  1272. performAction: #selector(MessageCollectionViewCell.messageForward(_:)),
  1273. forItemAt: indexPath, withSender: sender)
  1274. }
  1275. }
  1276. }
  1277. @objc func messageDelete(_ sender: Any?) {
  1278. // Get the collectionView
  1279. if let collectionView = self.superview as? UICollectionView {
  1280. // Get indexPath
  1281. if let indexPath = collectionView.indexPath(for: self) {
  1282. // Trigger action
  1283. collectionView.delegate?.collectionView?(collectionView,
  1284. performAction: #selector(MessageCollectionViewCell.messageDelete(_:)),
  1285. forItemAt: indexPath, withSender: sender)
  1286. }
  1287. }
  1288. }
  1289. @objc func messageInfo(_ sender: Any?) {
  1290. // Get the collectionView
  1291. if let collectionView = self.superview as? UICollectionView {
  1292. // Get indexPath
  1293. if let indexPath = collectionView.indexPath(for: self) {
  1294. // Trigger action
  1295. collectionView.delegate?.collectionView?(collectionView,
  1296. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  1297. forItemAt: indexPath, withSender: sender)
  1298. }
  1299. }
  1300. }
  1301. }