ChatViewController.swift 61 KB

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