ChatViewController.swift 64 KB

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