ChatViewController.swift 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. class ChatViewController: UITableViewController {
  9. var dcContext: DcContext
  10. private var draftMessage: DcMsg?
  11. let outgoingAvatarOverlap: CGFloat = 17.5
  12. let loadCount = 30
  13. let chatId: Int
  14. var messageIds: [Int] = []
  15. var msgChangedObserver: Any?
  16. var incomingMsgObserver: Any?
  17. var ephemeralTimerModifiedObserver: Any?
  18. lazy var isGroupChat: Bool = {
  19. return dcContext.getChat(chatId: chatId).isGroup
  20. }()
  21. lazy var draft: DraftModel = {
  22. let draft = DraftModel(chatId: chatId)
  23. return draft
  24. }()
  25. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  26. open var messageInputBar = InputBarAccessoryView()
  27. lazy var quotePreview: QuotePreview = {
  28. let view = QuotePreview()
  29. view.delegate = self
  30. view.translatesAutoresizingMaskIntoConstraints = false
  31. return view
  32. }()
  33. lazy var mediaPreview: MediaPreview = {
  34. let view = MediaPreview()
  35. view.delegate = self
  36. view.translatesAutoresizingMaskIntoConstraints = false
  37. return view
  38. }()
  39. lazy var documentPreview: DocumentPreview = {
  40. let view = DocumentPreview()
  41. view.delegate = self
  42. view.translatesAutoresizingMaskIntoConstraints = false
  43. return view
  44. }()
  45. open override var shouldAutorotate: Bool {
  46. return false
  47. }
  48. private weak var timer: Timer?
  49. lazy var navBarTap: UITapGestureRecognizer = {
  50. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  51. }()
  52. private var locationStreamingItem: UIBarButtonItem = {
  53. let indicator = LocationStreamingIndicator()
  54. return UIBarButtonItem(customView: indicator)
  55. }()
  56. private lazy var muteItem: UIBarButtonItem = {
  57. let imageView = UIImageView()
  58. imageView.tintColor = DcColors.defaultTextColor
  59. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  60. imageView.translatesAutoresizingMaskIntoConstraints = false
  61. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  62. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  63. return UIBarButtonItem(customView: imageView)
  64. }()
  65. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  66. let imageView = UIImageView()
  67. imageView.tintColor = DcColors.defaultTextColor
  68. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  69. imageView.translatesAutoresizingMaskIntoConstraints = false
  70. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  71. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  72. return UIBarButtonItem(customView: imageView)
  73. }()
  74. private lazy var badgeItem: UIBarButtonItem = {
  75. let badge: InitialsBadge
  76. let chat = dcContext.getChat(chatId: chatId)
  77. if let image = chat.profileImage {
  78. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  79. } else {
  80. badge = InitialsBadge(
  81. name: chat.name,
  82. color: chat.color,
  83. size: 28,
  84. accessibilityLabel: String.localized("menu_view_profile")
  85. )
  86. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  87. }
  88. badge.setVerified(chat.isProtected)
  89. badge.accessibilityTraits = .button
  90. return UIBarButtonItem(customView: badge)
  91. }()
  92. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  93. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId)
  94. private var disableWriting: Bool
  95. private var showNamesAboveMessage: Bool
  96. var showCustomNavBar = true
  97. var highlightedMsg: Int?
  98. private lazy var mediaPicker: MediaPicker? = {
  99. let mediaPicker = MediaPicker(navigationController: navigationController)
  100. mediaPicker.delegate = self
  101. return mediaPicker
  102. }()
  103. var emptyStateView: EmptyStateLabel = {
  104. let view = EmptyStateLabel()
  105. return view
  106. }()
  107. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  108. let dcChat = dcContext.getChat(chatId: chatId)
  109. self.dcContext = dcContext
  110. self.chatId = chatId
  111. self.disableWriting = !dcChat.canSend
  112. self.showNamesAboveMessage = dcChat.isGroup
  113. self.highlightedMsg = highlightedMsg
  114. super.init(nibName: nil, bundle: nil)
  115. hidesBottomBarWhenPushed = true
  116. }
  117. required init?(coder _: NSCoder) {
  118. fatalError("init(coder:) has not been implemented")
  119. }
  120. override func loadView() {
  121. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  122. self.tableView.delegate = self
  123. self.tableView.dataSource = self
  124. self.view = self.tableView
  125. }
  126. override func viewDidLoad() {
  127. super.viewDidLoad()
  128. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  129. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  130. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  131. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  132. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  133. tableView.rowHeight = UITableView.automaticDimension
  134. tableView.separatorStyle = .none
  135. tableView.keyboardDismissMode = .interactive
  136. if !dcContext.isConfigured() {
  137. // TODO: display message about nothing being configured
  138. return
  139. }
  140. configureEmptyStateView()
  141. if !disableWriting {
  142. configureMessageInputBar()
  143. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  144. messageInputBar.inputTextView.text = draft.draftText
  145. configureDraftArea(draft: draft)
  146. }
  147. let notificationCenter = NotificationCenter.default
  148. notificationCenter.addObserver(self,
  149. selector: #selector(saveDraft),
  150. name: UIApplication.willResignActiveNotification,
  151. object: nil)
  152. notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  153. prepareContextMenu()
  154. }
  155. @objc func keyboardWillShow(_ notification: Notification) {
  156. if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
  157. if keyboardSize.height > tableView.inputAccessoryView?.frame.height ?? 0 {
  158. if self.isLastRowVisible() {
  159. DispatchQueue.main.async { [weak self] in
  160. self?.scrollToBottom(animated: true)
  161. }
  162. }
  163. }
  164. }
  165. }
  166. private func startTimer() {
  167. timer?.invalidate()
  168. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  169. //reload table
  170. DispatchQueue.main.async {
  171. guard let self = self else { return }
  172. self.messageIds = self.getMessageIds()
  173. self.tableView.reloadData()
  174. }
  175. }
  176. }
  177. private func stopTimer() {
  178. timer?.invalidate()
  179. }
  180. private func configureEmptyStateView() {
  181. view.addSubview(emptyStateView)
  182. emptyStateView.translatesAutoresizingMaskIntoConstraints = false
  183. emptyStateView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  184. emptyStateView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  185. emptyStateView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  186. emptyStateView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  187. }
  188. override func viewWillAppear(_ animated: Bool) {
  189. super.viewWillAppear(animated)
  190. self.tableView.becomeFirstResponder()
  191. // this will be removed in viewWillDisappear
  192. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  193. if showCustomNavBar {
  194. updateTitle(chat: dcContext.getChat(chatId: chatId))
  195. }
  196. let nc = NotificationCenter.default
  197. msgChangedObserver = nc.addObserver(
  198. forName: dcNotificationChanged,
  199. object: nil,
  200. queue: OperationQueue.main
  201. ) { [weak self] notification in
  202. guard let self = self else { return }
  203. if let ui = notification.userInfo {
  204. if self.disableWriting {
  205. // always refresh, as we can't check currently
  206. self.refreshMessages()
  207. } else if let id = ui["message_id"] as? Int {
  208. if id > 0 {
  209. self.updateMessage(id)
  210. } else {
  211. // change might be a deletion
  212. self.refreshMessages()
  213. }
  214. }
  215. if self.showCustomNavBar {
  216. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  217. }
  218. }
  219. }
  220. incomingMsgObserver = nc.addObserver(
  221. forName: dcNotificationIncoming,
  222. object: nil, queue: OperationQueue.main
  223. ) { [weak self] notification in
  224. guard let self = self else { return }
  225. if let ui = notification.userInfo {
  226. if self.chatId == ui["chat_id"] as? Int {
  227. if let id = ui["message_id"] as? Int {
  228. if id > 0 {
  229. self.insertMessage(DcMsg(id: id))
  230. }
  231. }
  232. }
  233. }
  234. }
  235. ephemeralTimerModifiedObserver = nc.addObserver(
  236. forName: dcEphemeralTimerModified,
  237. object: nil, queue: OperationQueue.main
  238. ) { [weak self] _ in
  239. guard let self = self else { return }
  240. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  241. }
  242. loadMessages()
  243. if RelayHelper.sharedInstance.isForwarding() {
  244. askToForwardMessage()
  245. }
  246. }
  247. override func viewDidAppear(_ animated: Bool) {
  248. super.viewDidAppear(animated)
  249. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  250. // things that do not affect the chatview
  251. // and are delayed after the view is displayed
  252. DispatchQueue.global(qos: .background).async { [weak self] in
  253. guard let self = self else { return }
  254. self.dcContext.marknoticedChat(chatId: self.chatId)
  255. }
  256. startTimer()
  257. }
  258. override func viewWillDisappear(_ animated: Bool) {
  259. super.viewWillDisappear(animated)
  260. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  261. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  262. }
  263. override func viewDidDisappear(_ animated: Bool) {
  264. super.viewDidDisappear(animated)
  265. AppStateRestorer.shared.resetLastActiveChat()
  266. saveDraft()
  267. let nc = NotificationCenter.default
  268. if let msgChangedObserver = self.msgChangedObserver {
  269. nc.removeObserver(msgChangedObserver)
  270. }
  271. if let incomingMsgObserver = self.incomingMsgObserver {
  272. nc.removeObserver(incomingMsgObserver)
  273. }
  274. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  275. nc.removeObserver(ephemeralTimerModifiedObserver)
  276. }
  277. audioController.stopAnyOngoingPlaying()
  278. stopTimer()
  279. }
  280. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  281. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  282. coordinator.animate(
  283. alongsideTransition: { [weak self] _ in
  284. guard let self = self else { return }
  285. if self.showCustomNavBar {
  286. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  287. }
  288. if lastSectionVisibleBeforeTransition {
  289. self.scrollToBottom(animated: false)
  290. }
  291. },
  292. completion: {[weak self] _ in
  293. guard let self = self else { return }
  294. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  295. if lastSectionVisibleBeforeTransition {
  296. DispatchQueue.main.async { [weak self] in
  297. self?.tableView.reloadData()
  298. self?.scrollToBottom(animated: false)
  299. }
  300. }
  301. }
  302. )
  303. super.viewWillTransition(to: size, with: coordinator)
  304. }
  305. /// UITableView methods
  306. override func numberOfSections(in tableView: UITableView) -> Int {
  307. return 1
  308. }
  309. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  310. return messageIds.count //viewModel.numberOfRowsIn(section: section)
  311. }
  312. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  313. _ = handleUIMenu()
  314. let id = messageIds[indexPath.row]
  315. let message = DcMsg(id: id)
  316. if message.isInfo {
  317. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  318. cell.update(msg: message)
  319. return cell
  320. }
  321. let cell: BaseMessageCell
  322. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  323. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  324. } else if message.type == DC_MSG_FILE {
  325. if message.isSetupMessage {
  326. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  327. message.text = String.localized("autocrypt_asm_click_body")
  328. } else {
  329. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  330. }
  331. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  332. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  333. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  334. audioController.update(audioMessageCell, with: message.id)
  335. cell = audioMessageCell
  336. } else {
  337. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  338. }
  339. cell.baseDelegate = self
  340. cell.update(msg: message,
  341. messageStyle: configureMessageStyle(for: message, at: indexPath),
  342. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  343. isGroup: isGroupChat)
  344. return cell
  345. }
  346. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  347. if !decelerate {
  348. markSeenMessagesInVisibleArea()
  349. }
  350. }
  351. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  352. markSeenMessagesInVisibleArea()
  353. }
  354. private func configureDraftArea(draft: DraftModel) {
  355. quotePreview.configure(draft: draft)
  356. mediaPreview.configure(draft: draft)
  357. documentPreview.configure(draft: draft)
  358. // setStackViewItems recalculates the proper messageInputBar height
  359. messageInputBar.setStackViewItems([quotePreview, mediaPreview, documentPreview], forStack: .top, animated: true)
  360. }
  361. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  362. if disableWriting {
  363. return nil
  364. }
  365. let action = UIContextualAction(style: .normal, title: nil,
  366. handler: { (_, _, completionHandler) in
  367. let message = DcMsg(id: self.messageIds[indexPath.row])
  368. self.draft.setQuote(quotedMsg: message)
  369. self.configureDraftArea(draft: self.draft)
  370. self.messageInputBar.inputTextView.becomeFirstResponder()
  371. completionHandler(true)
  372. })
  373. if #available(iOS 12.0, *) {
  374. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  375. } else {
  376. action.image = UIImage(named: "ic_reply_black")
  377. }
  378. action.image?.accessibilityTraits = .button
  379. action.image?.accessibilityLabel = String.localized("menu_reply")
  380. action.backgroundColor = DcColors.chatBackgroundColor
  381. let configuration = UISwipeActionsConfiguration(actions: [action])
  382. return configuration
  383. }
  384. func markSeenMessagesInVisibleArea() {
  385. if let indexPaths = tableView.indexPathsForVisibleRows {
  386. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  387. if !visibleMessagesIds.isEmpty {
  388. DispatchQueue.global(qos: .background).async { [weak self] in
  389. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  390. }
  391. }
  392. }
  393. }
  394. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  395. let messageId = messageIds[indexPath.row]
  396. let message = DcMsg(id: messageId)
  397. if message.isSetupMessage {
  398. didTapAsm(msg: message, orgText: "")
  399. } else if message.type == DC_MSG_FILE ||
  400. message.type == DC_MSG_AUDIO ||
  401. message.type == DC_MSG_VOICE {
  402. showMediaGalleryFor(message: message)
  403. }
  404. _ = handleUIMenu()
  405. }
  406. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  407. return isGroupChat && !message.isFromCurrentSender
  408. }
  409. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  410. var corners: UIRectCorner = []
  411. if message.isFromCurrentSender {
  412. corners.formUnion(.topLeft)
  413. corners.formUnion(.bottomLeft)
  414. corners.formUnion(.topRight)
  415. } else {
  416. corners.formUnion(.topRight)
  417. corners.formUnion(.bottomRight)
  418. corners.formUnion(.topLeft)
  419. }
  420. return corners
  421. }
  422. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  423. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  424. }
  425. private func updateTitle(chat: DcChat) {
  426. let titleView = ChatTitleView()
  427. var subtitle = "ErrSubtitle"
  428. let chatContactIds = chat.contactIds
  429. if chat.isGroup {
  430. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  431. } else if chatContactIds.count >= 1 {
  432. if chat.isDeviceTalk {
  433. subtitle = String.localized("device_talk_subtitle")
  434. } else if chat.isSelfTalk {
  435. subtitle = String.localized("chat_self_talk_subtitle")
  436. } else {
  437. subtitle = DcContact(id: chatContactIds[0]).email
  438. }
  439. }
  440. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  441. navigationItem.titleView = titleView
  442. var rightBarButtonItems = [badgeItem]
  443. if chat.isSendingLocations {
  444. rightBarButtonItems.append(locationStreamingItem)
  445. }
  446. if chat.isMuted {
  447. rightBarButtonItems.append(muteItem)
  448. }
  449. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  450. rightBarButtonItems.append(ephemeralMessageItem)
  451. }
  452. navigationItem.rightBarButtonItems = rightBarButtonItems
  453. }
  454. // TODO: is the delay of one second needed?
  455. @objc
  456. private func refreshMessages() {
  457. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  458. DispatchQueue.main.async { [weak self] in
  459. guard let self = self else { return }
  460. self.messageIds = self.getMessageIds()
  461. self.tableView.reloadData()
  462. if self.isLastRowVisible() {
  463. self.scrollToBottom(animated: true)
  464. }
  465. self.showEmptyStateView(self.messageIds.isEmpty)
  466. }
  467. }
  468. }
  469. private func loadMessages() {
  470. DispatchQueue.global(qos: .userInitiated).async {
  471. DispatchQueue.main.async { [weak self] in
  472. guard let self = self else { return }
  473. let wasLastRowVisible = self.isLastRowVisible()
  474. let wasMessageIdsEmpty = self.messageIds.isEmpty
  475. // update message ids
  476. self.messageIds = self.getMessageIds()
  477. self.tableView.reloadData()
  478. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  479. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  480. self.highlightedMsg = nil
  481. } else if wasMessageIdsEmpty ||
  482. wasLastRowVisible {
  483. self.scrollToBottom(animated: false)
  484. }
  485. self.showEmptyStateView(self.messageIds.isEmpty)
  486. }
  487. }
  488. }
  489. func isLastRowVisible() -> Bool {
  490. guard !messageIds.isEmpty else { return false }
  491. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  492. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  493. }
  494. func scrollToBottom(animated: Bool) {
  495. if !messageIds.isEmpty {
  496. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  497. }
  498. }
  499. private func showEmptyStateView(_ show: Bool) {
  500. if show {
  501. let dcChat = dcContext.getChat(chatId: chatId)
  502. if chatId == DC_CHAT_ID_DEADDROP {
  503. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  504. emptyStateView.text = String.localized("chat_no_contact_requests")
  505. } else {
  506. emptyStateView.text = String.localized("chat_no_messages")
  507. }
  508. } else if dcChat.isGroup {
  509. if dcChat.isUnpromoted {
  510. emptyStateView.text = String.localized("chat_new_group_hint")
  511. } else {
  512. emptyStateView.text = String.localized("chat_no_messages")
  513. }
  514. } else if dcChat.isSelfTalk {
  515. emptyStateView.text = String.localized("saved_messages_explain")
  516. } else if dcChat.isDeviceTalk {
  517. emptyStateView.text = String.localized("device_talk_explain")
  518. } else {
  519. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  520. }
  521. emptyStateView.isHidden = false
  522. } else {
  523. emptyStateView.isHidden = true
  524. }
  525. }
  526. private func getMessageIds() -> [Int] {
  527. return dcContext.getMessageIds(chatId: chatId)
  528. }
  529. @objc private func saveDraft() {
  530. draft.save(context: dcContext)
  531. }
  532. private func configureMessageInputBar() {
  533. messageInputBar.delegate = self
  534. messageInputBar.inputTextView.tintColor = DcColors.primary
  535. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  536. messageInputBar.separatorLine.isHidden = true
  537. messageInputBar.inputTextView.tintColor = DcColors.primary
  538. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  539. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  540. //scrollsToBottomOnKeyboardBeginsEditing = true
  541. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  542. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  543. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  544. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  545. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  546. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  547. messageInputBar.inputTextView.layer.borderWidth = 1.0
  548. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  549. messageInputBar.inputTextView.layer.masksToBounds = true
  550. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  551. configureInputBarItems()
  552. }
  553. func evaluateInputBar(draft: DraftModel) {
  554. let isEnabled = !(draft.draftText?.isEmpty ?? true) || draft.draftAttachment != nil
  555. messageInputBar.sendButton.isEnabled = isEnabled
  556. }
  557. private func configureInputBarItems() {
  558. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  559. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  560. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  561. messageInputBar.sendButton.image = sendButtonImage
  562. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  563. messageInputBar.sendButton.accessibilityTraits = .button
  564. messageInputBar.sendButton.title = nil
  565. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  566. messageInputBar.sendButton.layer.cornerRadius = 20
  567. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  568. // this adds a padding between textinputfield and send button
  569. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  570. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  571. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  572. messageInputBar.shouldManageSendButtonEnabledState = false
  573. let leftItems = [
  574. InputBarButtonItem()
  575. .configure {
  576. $0.spacing = .fixed(0)
  577. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  578. $0.image = clipperIcon
  579. $0.tintColor = DcColors.primary
  580. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  581. $0.accessibilityLabel = String.localized("menu_add_attachment")
  582. $0.accessibilityTraits = .button
  583. }.onSelected {
  584. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  585. }.onDeselected {
  586. $0.tintColor = DcColors.primary
  587. }.onTouchUpInside { [weak self] _ in
  588. self?.clipperButtonPressed()
  589. }
  590. ]
  591. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  592. // This just adds some more flare
  593. messageInputBar.sendButton
  594. .onEnabled { item in
  595. UIView.animate(withDuration: 0.3, animations: {
  596. item.backgroundColor = DcColors.primary
  597. })
  598. }.onDisabled { item in
  599. UIView.animate(withDuration: 0.3, animations: {
  600. item.backgroundColor = DcColors.colorDisabled
  601. })
  602. }
  603. }
  604. @objc private func chatProfilePressed() {
  605. if chatId != DC_CHAT_ID_DEADDROP {
  606. showChatDetail(chatId: chatId)
  607. }
  608. }
  609. @objc private func clipperButtonPressed() {
  610. showClipperOptions()
  611. }
  612. private func showClipperOptions() {
  613. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  614. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  615. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  616. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  617. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  618. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  619. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  620. style: isLocationStreaming ? .destructive : .default,
  621. handler: locationStreamingButtonPressed(_:))
  622. alert.addAction(cameraAction)
  623. alert.addAction(galleryAction)
  624. alert.addAction(documentAction)
  625. alert.addAction(voiceMessageAction)
  626. if UserDefaults.standard.bool(forKey: "location_streaming") {
  627. alert.addAction(locationStreamingAction)
  628. }
  629. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  630. self.present(alert, animated: true, completion: {
  631. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  632. // but this hack does the trick
  633. if UIAccessibility.isVoiceOverRunning {
  634. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  635. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  636. }
  637. }
  638. })
  639. }
  640. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  641. let alert = UIAlertController(title: title,
  642. message: nil,
  643. preferredStyle: .safeActionSheet)
  644. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  645. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  646. self.dismiss(animated: true, completion: nil)
  647. }))
  648. present(alert, animated: true, completion: nil)
  649. }
  650. private func askToChatWith(email: String) {
  651. let contactId = self.dcContext.createContact(name: "", email: email)
  652. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  653. self.dismiss(animated: true, completion: nil)
  654. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  655. self.showChat(chatId: chatId)
  656. } else {
  657. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  658. actionTitle: String.localized("start_chat"),
  659. actionHandler: { _ in
  660. self.dismiss(animated: true, completion: nil)
  661. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  662. self.showChat(chatId: chatId)})
  663. }
  664. }
  665. private func askToDeleteMessage(id: Int) {
  666. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  667. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  668. actionHandler: { _ in
  669. self.dcContext.deleteMessage(msgId: id)
  670. self.dismiss(animated: true, completion: nil)})
  671. }
  672. private func askToForwardMessage() {
  673. let chat = dcContext.getChat(chatId: self.chatId)
  674. if chat.isSelfTalk {
  675. RelayHelper.sharedInstance.forward(to: self.chatId)
  676. } else {
  677. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  678. actionTitle: String.localized("menu_forward"),
  679. actionHandler: { _ in
  680. RelayHelper.sharedInstance.forward(to: self.chatId)
  681. self.dismiss(animated: true, completion: nil)},
  682. cancelHandler: { _ in
  683. self.dismiss(animated: false, completion: nil)
  684. self.navigationController?.popViewController(animated: true)})
  685. }
  686. }
  687. // MARK: - coordinator
  688. private func showChatDetail(chatId: Int) {
  689. let chat = dcContext.getChat(chatId: chatId)
  690. switch chat.chatType {
  691. case .SINGLE:
  692. if let contactId = chat.contactIds.first {
  693. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  694. navigationController?.pushViewController(contactDetailController, animated: true)
  695. }
  696. case .GROUP, .VERIFIEDGROUP:
  697. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  698. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  699. }
  700. }
  701. func showChat(chatId: Int) {
  702. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  703. navigationController?.popToRootViewController(animated: false)
  704. appDelegate.appCoordinator.showChat(chatId: chatId)
  705. }
  706. }
  707. private func showDocumentLibrary() {
  708. mediaPicker?.showDocumentLibrary()
  709. }
  710. private func showVoiceMessageRecorder() {
  711. mediaPicker?.showVoiceRecorder()
  712. }
  713. private func showCameraViewController() {
  714. mediaPicker?.showCamera()
  715. }
  716. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  717. mediaPicker?.showPhotoVideoLibrary()
  718. }
  719. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  720. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  721. let nav = UINavigationController(rootViewController: betterPreviewController)
  722. nav.modalPresentationStyle = .fullScreen
  723. navigationController?.present(nav, animated: true)
  724. }
  725. private func documentActionPressed(_ action: UIAlertAction) {
  726. showDocumentLibrary()
  727. }
  728. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  729. showVoiceMessageRecorder()
  730. }
  731. private func cameraButtonPressed(_ action: UIAlertAction) {
  732. showCameraViewController()
  733. }
  734. private func galleryButtonPressed(_ action: UIAlertAction) {
  735. showPhotoVideoLibrary(delegate: self)
  736. }
  737. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  738. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  739. if isLocationStreaming {
  740. locationStreamingFor(seconds: 0)
  741. } else {
  742. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  743. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  744. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  745. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  746. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  747. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  748. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  749. self.present(alert, animated: true, completion: nil)
  750. }
  751. }
  752. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  753. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  754. self.locationStreamingFor(seconds: duration)
  755. })
  756. alert.addAction(action)
  757. }
  758. private func locationStreamingFor(seconds: Int) {
  759. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  760. return
  761. }
  762. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  763. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  764. }
  765. func updateMessage(_ messageId: Int) {
  766. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  767. DispatchQueue.global(qos: .background).async { [weak self] in
  768. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  769. }
  770. let wasLastSectionVisible = self.isLastRowVisible()
  771. tableView.reloadData()
  772. if wasLastSectionVisible {
  773. self.scrollToBottom(animated: true)
  774. }
  775. } else {
  776. let msg = DcMsg(id: messageId)
  777. if msg.chatId == chatId {
  778. insertMessage(msg)
  779. }
  780. }
  781. }
  782. func insertMessage(_ message: DcMsg) {
  783. DispatchQueue.global(qos: .background).async { [weak self] in
  784. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  785. }
  786. let wasLastSectionVisible = isLastRowVisible()
  787. messageIds.append(message.id)
  788. emptyStateView.isHidden = true
  789. tableView.reloadData()
  790. if wasLastSectionVisible || message.isFromCurrentSender {
  791. scrollToBottom(animated: true)
  792. }
  793. }
  794. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  795. DispatchQueue.global().async {
  796. let message = DcMsg(viewType: DC_MSG_TEXT)
  797. message.text = text
  798. if let quoteMessage = quoteMessage {
  799. message.quoteMessage = quoteMessage
  800. }
  801. message.sendInChat(id: self.chatId)
  802. }
  803. }
  804. private func stageDocument(url: NSURL) {
  805. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  806. self.configureDraftArea(draft: self.draft)
  807. self.messageInputBar.inputTextView.becomeFirstResponder()
  808. }
  809. private func stageImage(url: NSURL) {
  810. if url.pathExtension == "gif" {
  811. stageAnimatedImage(url: url)
  812. } else if let data = try? Data(contentsOf: url as URL),
  813. let image = UIImage(data: data) {
  814. stageImage(image)
  815. }
  816. }
  817. private func stageAnimatedImage(url: NSURL) {
  818. DispatchQueue.global().async {
  819. if let path = url.path,
  820. let result = SDAnimatedImage(contentsOfFile: path),
  821. let animatedImageData = result.animatedImageData,
  822. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  823. DispatchQueue.main.async {
  824. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  825. self.configureDraftArea(draft: self.draft)
  826. self.messageInputBar.inputTextView.becomeFirstResponder()
  827. }
  828. }
  829. }
  830. }
  831. private func stageImage(_ image: UIImage) {
  832. DispatchQueue.global().async {
  833. if let pathInDocDir = DcUtils.saveImage(image: image) {
  834. DispatchQueue.main.async {
  835. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  836. self.configureDraftArea(draft: self.draft)
  837. self.messageInputBar.inputTextView.becomeFirstResponder()
  838. }
  839. }
  840. }
  841. }
  842. private func sendImage(_ image: UIImage, message: String? = nil) {
  843. DispatchQueue.global().async {
  844. if let path = DcUtils.saveImage(image: image) {
  845. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path)
  846. }
  847. }
  848. }
  849. /*private func sendAnimatedImage(url: NSURL) {
  850. if let path = url.path {
  851. let result = SDAnimatedImage(contentsOfFile: path)
  852. if let result = result,
  853. let animatedImageData = result.animatedImageData,
  854. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  855. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  856. }
  857. }
  858. }*/
  859. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  860. let msg = DcMsg(viewType: viewType)
  861. msg.setFile(filepath: filePath)
  862. msg.text = (message ?? "").isEmpty ? nil : message
  863. if quoteMessage != nil {
  864. msg.quoteMessage = quoteMessage
  865. }
  866. msg.sendInChat(id: self.chatId)
  867. }
  868. private func sendVoiceMessage(url: NSURL) {
  869. DispatchQueue.global().async {
  870. let msg = DcMsg(viewType: DC_MSG_VOICE)
  871. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  872. msg.sendInChat(id: self.chatId)
  873. }
  874. }
  875. private func sendVideo(url: NSURL) {
  876. DispatchQueue.global().async {
  877. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  878. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  879. msg.sendInChat(id: self.chatId)
  880. }
  881. }
  882. /*private func sendImage(url: NSURL) {
  883. if url.pathExtension == "gif" {
  884. sendAnimatedImage(url: url)
  885. } else if let data = try? Data(contentsOf: url as URL),
  886. let image = UIImage(data: data) {
  887. sendImage(image)
  888. }
  889. }*/
  890. // MARK: - Context menu
  891. private func prepareContextMenu() {
  892. UIMenuController.shared.menuItems = [
  893. UIMenuItem(title: String.localized("info"), action: #selector(BaseMessageCell.messageInfo)),
  894. UIMenuItem(title: String.localized("delete"), action: #selector(BaseMessageCell.messageDelete)),
  895. UIMenuItem(title: String.localized("forward"), action: #selector(BaseMessageCell.messageForward))
  896. ]
  897. UIMenuController.shared.update()
  898. }
  899. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  900. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  901. }
  902. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  903. return action == #selector(UIResponderStandardEditActions.copy(_:))
  904. || action == #selector(BaseMessageCell.messageInfo)
  905. || action == #selector(BaseMessageCell.messageDelete)
  906. || action == #selector(BaseMessageCell.messageForward)
  907. }
  908. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  909. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  910. switch action {
  911. case #selector(copy(_:)):
  912. let id = messageIds[indexPath.row]
  913. let msg = DcMsg(id: id)
  914. let pasteboard = UIPasteboard.general
  915. if msg.type == DC_MSG_TEXT {
  916. pasteboard.string = msg.text
  917. } else {
  918. pasteboard.string = msg.summary(chars: 10000000)
  919. }
  920. case #selector(BaseMessageCell.messageInfo(_:)):
  921. let msg = DcMsg(id: messageIds[indexPath.row])
  922. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  923. if let ctrl = navigationController {
  924. ctrl.pushViewController(msgViewController, animated: true)
  925. }
  926. case #selector(BaseMessageCell.messageDelete(_:)):
  927. let msg = DcMsg(id: messageIds[indexPath.row])
  928. askToDeleteMessage(id: msg.id)
  929. case #selector(BaseMessageCell.messageForward(_:)):
  930. let msg = DcMsg(id: messageIds[indexPath.row])
  931. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  932. navigationController?.popViewController(animated: true)
  933. default:
  934. break
  935. }
  936. }
  937. func showMediaGalleryFor(indexPath: IndexPath) {
  938. let messageId = messageIds[indexPath.row]
  939. let message = DcMsg(id: messageId)
  940. showMediaGalleryFor(message: message)
  941. }
  942. func showMediaGalleryFor(message: DcMsg) {
  943. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  944. let index = msgIds.firstIndex(of: message.id) ?? 0
  945. showMediaGallery(currentIndex: index, msgIds: msgIds)
  946. }
  947. private func didTapAsm(msg: DcMsg, orgText: String) {
  948. let inputDlg = UIAlertController(
  949. title: String.localized("autocrypt_continue_transfer_title"),
  950. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  951. preferredStyle: .alert)
  952. inputDlg.addTextField(configurationHandler: { (textField) in
  953. textField.placeholder = msg.setupCodeBegin + ".."
  954. textField.text = orgText
  955. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  956. })
  957. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  958. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  959. let textField = inputDlg.textFields![0]
  960. let modText = textField.text ?? ""
  961. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  962. let alert = UIAlertController(
  963. title: String.localized("autocrypt_continue_transfer_title"),
  964. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  965. preferredStyle: .alert)
  966. if success {
  967. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  968. } else {
  969. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  970. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  971. self.didTapAsm(msg: msg, orgText: modText)
  972. })
  973. alert.addAction(retryAction)
  974. alert.preferredAction = retryAction
  975. }
  976. self.navigationController?.present(alert, animated: true, completion: nil)
  977. })
  978. inputDlg.addAction(okAction)
  979. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  980. navigationController?.present(inputDlg, animated: true, completion: nil)
  981. }
  982. func handleUIMenu() -> Bool {
  983. if UIMenuController.shared.isMenuVisible {
  984. UIMenuController.shared.setMenuVisible(false, animated: true)
  985. return true
  986. }
  987. return false
  988. }
  989. }
  990. // MARK: - BaseMessageCellDelegate
  991. extension ChatViewController: BaseMessageCellDelegate {
  992. @objc func quoteTapped(indexPath: IndexPath) {
  993. _ = handleUIMenu()
  994. let msg = DcMsg(id: messageIds[indexPath.row])
  995. if let quoteMsg = msg.quoteMessage,
  996. let index = messageIds.firstIndex(of: quoteMsg.id) {
  997. let indexPath = IndexPath(row: index, section: 0)
  998. tableView.scrollToRow(at: indexPath, at: .top, animated: true)
  999. }
  1000. }
  1001. @objc func textTapped(indexPath: IndexPath) {
  1002. if handleUIMenu() { return }
  1003. let message = DcMsg(id: messageIds[indexPath.row])
  1004. if message.isSetupMessage {
  1005. didTapAsm(msg: message, orgText: "")
  1006. }
  1007. }
  1008. @objc func phoneNumberTapped(number: String) {
  1009. if handleUIMenu() { return }
  1010. logger.debug("phone number tapped \(number)")
  1011. }
  1012. @objc func commandTapped(command: String) {
  1013. if handleUIMenu() { return }
  1014. logger.debug("command tapped \(command)")
  1015. }
  1016. @objc func urlTapped(url: URL) {
  1017. if handleUIMenu() { return }
  1018. if Utils.isEmail(url: url) {
  1019. logger.debug("tapped on contact")
  1020. let email = Utils.getEmailFrom(url)
  1021. self.askToChatWith(email: email)
  1022. ///TODO: implement handling
  1023. } else {
  1024. UIApplication.shared.open(url)
  1025. }
  1026. }
  1027. @objc func imageTapped(indexPath: IndexPath) {
  1028. if handleUIMenu() { return }
  1029. showMediaGalleryFor(indexPath: indexPath)
  1030. }
  1031. @objc func avatarTapped(indexPath: IndexPath) {
  1032. let message = DcMsg(id: messageIds[indexPath.row])
  1033. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1034. navigationController?.pushViewController(contactDetailController, animated: true)
  1035. }
  1036. }
  1037. // MARK: - MediaPickerDelegate
  1038. extension ChatViewController: MediaPickerDelegate {
  1039. func onVideoSelected(url: NSURL) {
  1040. sendVideo(url: url)
  1041. }
  1042. func onImageSelected(url: NSURL) {
  1043. stageImage(url: url)
  1044. }
  1045. func onImageSelected(image: UIImage) {
  1046. stageImage(image)
  1047. }
  1048. func onVoiceMessageRecorded(url: NSURL) {
  1049. sendVoiceMessage(url: url)
  1050. }
  1051. func onDocumentSelected(url: NSURL) {
  1052. stageDocument(url: url)
  1053. }
  1054. }
  1055. // MARK: - MessageInputBarDelegate
  1056. extension ChatViewController: InputBarAccessoryViewDelegate {
  1057. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1058. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1059. .trimmingCharacters(in: .whitespacesAndNewlines)
  1060. if let filePath = draft.draftAttachment, let viewType = draft.draftViewType {
  1061. switch viewType {
  1062. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE:
  1063. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1064. default:
  1065. logger.warning("Unsupported viewType for drafted messages.")
  1066. }
  1067. } else if inputBar.inputTextView.images.isEmpty {
  1068. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1069. } else {
  1070. // only 1 attachment allowed for now, thus it takes the first one
  1071. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1072. }
  1073. inputBar.inputTextView.text = String()
  1074. inputBar.inputTextView.attributedText = nil
  1075. self.quotePreview.cancel()
  1076. self.mediaPreview.cancel()
  1077. self.documentPreview.cancel()
  1078. }
  1079. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1080. draft.draftText = text
  1081. evaluateInputBar(draft: draft)
  1082. }
  1083. }
  1084. extension ChatViewController: DraftPreviewDelegate {
  1085. func onCancelQuote() {
  1086. draft.setQuote(quotedMsg: nil)
  1087. configureDraftArea(draft: draft)
  1088. }
  1089. func onCancelAttachment() {
  1090. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1091. configureDraftArea(draft: draft)
  1092. evaluateInputBar(draft: draft)
  1093. }
  1094. func onAttachmentAdded() {
  1095. evaluateInputBar(draft: draft)
  1096. }
  1097. }