ShareViewController.swift 8.2 KB

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