ChatViewController.swift 63 KB

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