ShareViewController.swift 8.3 KB

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