ShareViewController.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import UIKit
  2. import Social
  3. import DcCore
  4. import MobileCoreServices
  5. class ShareViewController: SLComposeServiceViewController {
  6. class SimpleLogger: Logger {
  7. func verbose(_ message: String) {
  8. print("ShareViewController", "verbose", message)
  9. }
  10. func debug(_ message: String) {
  11. print("ShareViewController", "debug", message)
  12. }
  13. func info(_ message: String) {
  14. print("ShareViewController", "info", message)
  15. }
  16. func warning(_ message: String) {
  17. print("ShareViewController", "warning", message)
  18. }
  19. func error(_ message: String) {
  20. print("ShareViewController", "error", message)
  21. }
  22. }
  23. let logger = SimpleLogger()
  24. let dcContext = DcContext.shared
  25. var selectedChatId: Int?
  26. var selectedChat: DcChat?
  27. let dbHelper = DatabaseHelper()
  28. var shareAttachment: ShareAttachment?
  29. lazy var preview: UIImageView? = {
  30. let imageView = UIImageView(frame: .zero)
  31. imageView.clipsToBounds = true
  32. imageView.shouldGroupAccessibilityChildren = true
  33. imageView.isAccessibilityElement = false
  34. return imageView
  35. }()
  36. override func viewDidLoad() {
  37. super.viewDidLoad()
  38. setupNavigationBar()
  39. // workaround for iOS13 bug
  40. if #available(iOS 13.0, *) {
  41. _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { (_) in
  42. if let layoutContainerView = self.view.subviews.last {
  43. layoutContainerView.frame.size.height += 10
  44. }
  45. }
  46. }
  47. placeholder = String.localized("chat_input_placeholder")
  48. DispatchQueue.global(qos: .background).async {
  49. self.shareAttachment = ShareAttachment(dcContext: self.dcContext, inputItems: self.extensionContext?.inputItems, delegate: self)
  50. }
  51. }
  52. override func presentationAnimationDidFinish() {
  53. if dbHelper.currentDatabaseLocation == dbHelper.sharedDbFile {
  54. dcContext.logger = self.logger
  55. dcContext.openDatabase(dbFile: dbHelper.sharedDbFile)
  56. selectedChatId = dcContext.getChatIdByContactId(contactId: Int(DC_CONTACT_ID_SELF))
  57. if let chatId = selectedChatId {
  58. selectedChat = dcContext.getChat(chatId: chatId)
  59. }
  60. reloadConfigurationItems()
  61. } else {
  62. cancel()
  63. }
  64. }
  65. override func loadPreviewView() -> UIView! {
  66. return preview
  67. }
  68. override func isContentValid() -> Bool {
  69. // Do validation of contentText and/or NSExtensionContext attachments here
  70. return !(contentText?.isEmpty ?? true) || !(self.shareAttachment?.isEmpty ?? true)
  71. }
  72. private func setupNavigationBar() {
  73. guard let item = navigationController?.navigationBar.items?.first else { return }
  74. let button = UIBarButtonItem(
  75. title: String.localized("menu_send"),
  76. style: .done,
  77. target: self,
  78. action: #selector(appendPostTapped))
  79. item.rightBarButtonItem? = button
  80. }
  81. /// Invoked when the user wants to post.
  82. @objc
  83. private func appendPostTapped() {
  84. if let chatId = self.selectedChatId {
  85. guard var messages = shareAttachment?.messages else { return }
  86. if !self.contentText.isEmpty {
  87. if messages.count == 1 {
  88. messages[0].text?.append(self.contentText)
  89. } else {
  90. let message = DcMsg(viewType: DC_MSG_TEXT)
  91. message.text = self.contentText
  92. messages.insert(message, at: 0)
  93. }
  94. }
  95. let chatListController = SendingController(chatId: chatId, dcMsgs: messages, dcContext: dcContext)
  96. chatListController.delegate = self
  97. self.pushConfigurationViewController(chatListController)
  98. }
  99. }
  100. func quit() {
  101. if dbHelper.currentDatabaseLocation == dbHelper.sharedDbFile {
  102. dcContext.closeDatabase()
  103. }
  104. // Inform the host that we're done, so it un-blocks its UI.
  105. self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
  106. }
  107. override func configurationItems() -> [Any]! {
  108. logger.debug("configurationItems")
  109. // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
  110. let item = SLComposeSheetConfigurationItem()
  111. item?.title = String.localized("forward_to")
  112. item?.value = selectedChat?.name
  113. logger.debug("configurationItems chat name: \(String(describing: selectedChat?.name))")
  114. item?.tapHandler = {
  115. let chatListController = ChatListController(dcContext: self.dcContext, chatListDelegate: self)
  116. self.pushConfigurationViewController(chatListController)
  117. }
  118. return [item as Any]
  119. }
  120. override func didSelectCancel() {
  121. quit()
  122. }
  123. }
  124. extension ShareViewController: ChatListDelegate {
  125. func onChatSelected(chatId: Int) {
  126. selectedChatId = chatId
  127. selectedChat = dcContext.getChat(chatId: chatId)
  128. reloadConfigurationItems()
  129. popConfigurationViewController()
  130. }
  131. }
  132. extension ShareViewController: SendingControllerDelegate {
  133. func onSendingAttemptFinished() {
  134. DispatchQueue.main.async {
  135. self.popConfigurationViewController()
  136. UserDefaults.shared?.set(true, forKey: UserDefaults.hasExtensionAttemptedToSend)
  137. self.quit()
  138. }
  139. }
  140. }
  141. extension ShareViewController: ShareAttachmentDelegate {
  142. func onUrlShared(url: URL) {
  143. DispatchQueue.main.async {
  144. if var contentText = self.contentText, !contentText.isEmpty {
  145. contentText.append("\n\(url.absoluteString)")
  146. self.textView.text = contentText
  147. } else {
  148. self.textView.text = "\(url.absoluteString)"
  149. }
  150. }
  151. }
  152. func onAttachmentChanged() {
  153. DispatchQueue.main.async {
  154. self.validateContent()
  155. }
  156. }
  157. func onThumbnailChanged() {
  158. DispatchQueue.main.async {
  159. if let preview = self.preview {
  160. preview.image = self.shareAttachment?.thumbnail ?? nil
  161. }
  162. }
  163. }
  164. }