ChatViewController.swift 61 KB

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