ChatViewController.swift 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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, mediaUrls urls: [URL]) {
  655. let betterPreviewController = PreviewController(currentIndex: currentIndex, urls: urls)
  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 if let url = message.fileURL {
  1124. // find all other messages with same message type
  1125. let previousUrls: [URL] = message.previousMediaURLs()
  1126. let nextUrls: [URL] = message.nextMediaURLs()
  1127. // these are the files user will be able to swipe trough
  1128. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  1129. showMediaGallery(currentIndex: previousUrls.count, mediaUrls: mediaUrls)
  1130. }
  1131. }
  1132. }
  1133. private func didTapAsm(msg: DcMsg, orgText: String) {
  1134. let inputDlg = UIAlertController(
  1135. title: String.localized("autocrypt_continue_transfer_title"),
  1136. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1137. preferredStyle: .alert)
  1138. inputDlg.addTextField(configurationHandler: { (textField) in
  1139. textField.placeholder = msg.setupCodeBegin + ".."
  1140. textField.text = orgText
  1141. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1142. })
  1143. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1144. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1145. let textField = inputDlg.textFields![0]
  1146. let modText = textField.text ?? ""
  1147. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1148. let alert = UIAlertController(
  1149. title: String.localized("autocrypt_continue_transfer_title"),
  1150. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1151. preferredStyle: .alert)
  1152. if success {
  1153. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1154. } else {
  1155. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1156. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1157. self.didTapAsm(msg: msg, orgText: modText)
  1158. })
  1159. alert.addAction(retryAction)
  1160. alert.preferredAction = retryAction
  1161. }
  1162. self.navigationController?.present(alert, animated: true, completion: nil)
  1163. })
  1164. inputDlg.addAction(okAction)
  1165. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1166. navigationController?.present(inputDlg, animated: true, completion: nil)
  1167. }
  1168. @objc func didTapAvatar(in cell: MessageCollectionViewCell) {
  1169. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1170. let message = messageList[indexPath.section]
  1171. let chat = dcContext.getChat(chatId: chatId)
  1172. showContactDetail(of: message.fromContact.id, in: chat.chatType, chatId: chatId)
  1173. }
  1174. }
  1175. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  1176. logger.info("Top label tapped")
  1177. }
  1178. @objc(didTapCellBottomLabelIn:) func didTapCellBottomLabel(in _: MessageCollectionViewCell) {
  1179. print("Bottom label tapped")
  1180. }
  1181. func didTapPlayButton(in cell: AudioMessageCell) {
  1182. guard let indexPath = messagesCollectionView.indexPath(for: cell),
  1183. let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
  1184. print("Failed to identify message when audio cell receive tap gesture")
  1185. return
  1186. }
  1187. guard audioController.state != .stopped else {
  1188. // There is no audio sound playing - prepare to start playing for given audio message
  1189. audioController.playSound(for: message, in: cell)
  1190. return
  1191. }
  1192. if audioController.playingMessage?.messageId == message.messageId {
  1193. // tap occur in the current cell that is playing audio sound
  1194. if audioController.state == .playing {
  1195. audioController.pauseSound(for: message, in: cell)
  1196. } else {
  1197. audioController.resumeSound()
  1198. }
  1199. } else {
  1200. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  1201. audioController.stopAnyOngoingPlaying()
  1202. audioController.playSound(for: message, in: cell)
  1203. }
  1204. }
  1205. func didStartAudio(in cell: AudioMessageCell) {
  1206. print("audio started")
  1207. }
  1208. func didStopAudio(in cell: AudioMessageCell) {
  1209. print("audio stopped")
  1210. }
  1211. func didPauseAudio(in cell: AudioMessageCell) {
  1212. print("audio paused")
  1213. }
  1214. @objc func didTapBackground(in cell: MessageCollectionViewCell) {
  1215. print("background of message tapped")
  1216. }
  1217. }
  1218. // MARK: - MessageLabelDelegate
  1219. extension ChatViewController: MessageLabelDelegate {
  1220. func didSelectPhoneNumber(_ phoneNumber: String) {
  1221. logger.info("phone open", phoneNumber)
  1222. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1223. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  1224. UIApplication.shared.open(url as URL)
  1225. }
  1226. }
  1227. }
  1228. func didSelectURL(_ url: URL) {
  1229. if Utils.isEmail(url: url) {
  1230. print("tapped on contact")
  1231. let email = Utils.getEmailFrom(url)
  1232. self.askToChatWith(email: email)
  1233. ///TODO: implement handling
  1234. } else {
  1235. UIApplication.shared.open(url)
  1236. }
  1237. }
  1238. }
  1239. // MARK: - LocationMessageDisplayDelegate
  1240. /*
  1241. extension ChatViewController: LocationMessageDisplayDelegate {
  1242. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  1243. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  1244. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  1245. annotationView.image = pinImage
  1246. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  1247. return annotationView
  1248. }
  1249. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  1250. return { view in
  1251. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  1252. view.alpha = 0.0
  1253. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  1254. view.layer.transform = CATransform3DIdentity
  1255. view.alpha = 1.0
  1256. }, completion: nil)
  1257. }
  1258. }
  1259. }
  1260. */
  1261. // MARK: - MessageInputBarDelegate
  1262. extension ChatViewController: InputBarAccessoryViewDelegate {
  1263. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1264. if inputBar.inputTextView.images.isEmpty {
  1265. self.sendTextMessage(message: text.trimmingCharacters(in: .whitespacesAndNewlines))
  1266. } else {
  1267. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1268. .trimmingCharacters(in: .whitespacesAndNewlines)
  1269. // only 1 attachment allowed for now, thus it takes the first one
  1270. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1271. }
  1272. inputBar.inputTextView.text = String()
  1273. inputBar.inputTextView.attributedText = nil
  1274. }
  1275. }
  1276. /*
  1277. extension ChatViewController: MessageInputBarDelegate {
  1278. }
  1279. */
  1280. // MARK: - MessageCollectionViewCell
  1281. extension MessageCollectionViewCell {
  1282. @objc func messageForward(_ sender: Any?) {
  1283. // Get the collectionView
  1284. if let collectionView = self.superview as? UICollectionView {
  1285. // Get indexPath
  1286. if let indexPath = collectionView.indexPath(for: self) {
  1287. // Trigger action
  1288. collectionView.delegate?.collectionView?(collectionView,
  1289. performAction: #selector(MessageCollectionViewCell.messageForward(_:)),
  1290. forItemAt: indexPath, withSender: sender)
  1291. }
  1292. }
  1293. }
  1294. @objc func messageDelete(_ sender: Any?) {
  1295. // Get the collectionView
  1296. if let collectionView = self.superview as? UICollectionView {
  1297. // Get indexPath
  1298. if let indexPath = collectionView.indexPath(for: self) {
  1299. // Trigger action
  1300. collectionView.delegate?.collectionView?(collectionView,
  1301. performAction: #selector(MessageCollectionViewCell.messageDelete(_:)),
  1302. forItemAt: indexPath, withSender: sender)
  1303. }
  1304. }
  1305. }
  1306. @objc func messageInfo(_ sender: Any?) {
  1307. // Get the collectionView
  1308. if let collectionView = self.superview as? UICollectionView {
  1309. // Get indexPath
  1310. if let indexPath = collectionView.indexPath(for: self) {
  1311. // Trigger action
  1312. collectionView.delegate?.collectionView?(collectionView,
  1313. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  1314. forItemAt: indexPath, withSender: sender)
  1315. }
  1316. }
  1317. }
  1318. }