ChatViewController.swift 64 KB

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