ShareViewController.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 dcAccounts: DcAccounts = DcAccounts()
  28. lazy var dcContext: DcContext = {
  29. return dcAccounts.getSelected()
  30. }()
  31. var selectedChatId: Int?
  32. var selectedChat: DcChat?
  33. var shareAttachment: ShareAttachment?
  34. var isAccountConfigured: Bool = true
  35. var isLoading: Bool = false
  36. var previewImageHeightConstraint: NSLayoutConstraint?
  37. var previewImageWidthConstraint: NSLayoutConstraint?
  38. lazy var preview: SDAnimatedImageView? = {
  39. let imageView = SDAnimatedImageView(frame: .zero)
  40. imageView.clipsToBounds = true
  41. imageView.shouldGroupAccessibilityChildren = true
  42. imageView.isAccessibilityElement = false
  43. imageView.contentMode = .scaleAspectFit
  44. previewImageHeightConstraint = imageView.constraintHeightTo(96)
  45. previewImageWidthConstraint = imageView.constraintWidthTo(96)
  46. previewImageHeightConstraint?.isActive = true
  47. previewImageWidthConstraint?.isActive = true
  48. return imageView
  49. }()
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. setupNavigationBar()
  53. // workaround for iOS13 bug
  54. if #available(iOS 13.0, *) {
  55. _ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { (_) in
  56. if let layoutContainerView = self.view.subviews.last {
  57. layoutContainerView.frame.size.height += 10
  58. }
  59. }
  60. }
  61. placeholder = String.localized("chat_input_placeholder")
  62. let webPCoder = SDImageWebPCoder.shared
  63. SDImageCodersManager.shared.addCoder(webPCoder)
  64. }
  65. override func presentationAnimationDidFinish() {
  66. dcAccounts.logger = logger
  67. dcAccounts.openDatabase()
  68. isAccountConfigured = dcContext.isConfigured()
  69. if isAccountConfigured {
  70. if #available(iOSApplicationExtension 13.0, *) {
  71. if let intent = self.extensionContext?.intent as? INSendMessageIntent, let chatId = Int(intent.conversationIdentifier ?? "") {
  72. selectedChatId = chatId
  73. }
  74. }
  75. if selectedChatId == nil {
  76. selectedChatId = dcContext.getChatIdByContactId(contactId: Int(DC_CONTACT_ID_SELF))
  77. }
  78. if let chatId = selectedChatId {
  79. selectedChat = dcContext.getChat(chatId: chatId)
  80. }
  81. DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  82. guard let self = self else { return }
  83. self.shareAttachment = ShareAttachment(dcContext: self.dcContext, inputItems: self.extensionContext?.inputItems, delegate: self)
  84. }
  85. reloadConfigurationItems()
  86. validateContent()
  87. } else {
  88. cancel()
  89. }
  90. }
  91. override func loadPreviewView() -> UIView! {
  92. return preview
  93. }
  94. override func isContentValid() -> Bool {
  95. // Do validation of contentText and/or NSExtensionContext attachments here
  96. return isAccountConfigured && !isLoading && (!(contentText?.isEmpty ?? true) || !(self.shareAttachment?.isEmpty ?? true))
  97. }
  98. private func setupNavigationBar() {
  99. guard let item = navigationController?.navigationBar.items?.first else { return }
  100. let button = UIBarButtonItem(
  101. title: String.localized("menu_send"),
  102. style: .done,
  103. target: self,
  104. action: #selector(appendPostTapped))
  105. item.rightBarButtonItem? = button
  106. }
  107. /// Invoked when the user wants to post.
  108. @objc
  109. private func appendPostTapped() {
  110. if let chatId = self.selectedChatId {
  111. guard var messages = shareAttachment?.messages else { return }
  112. if !self.contentText.isEmpty {
  113. if messages.count == 1 {
  114. messages[0].text?.append(self.contentText)
  115. } else {
  116. let message = dcContext.newMessage(viewType: DC_MSG_TEXT)
  117. message.text = self.contentText
  118. messages.insert(message, at: 0)
  119. }
  120. }
  121. let chatListController = SendingController(chatId: chatId, dcMsgs: messages, dcContext: dcContext)
  122. chatListController.delegate = self
  123. self.pushConfigurationViewController(chatListController)
  124. }
  125. }
  126. func quit() {
  127. dcAccounts.closeDatabase()
  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. func onLoadingStarted() {
  204. isLoading = true
  205. }
  206. func onLoadingFinished() {
  207. isLoading = false
  208. self.validateContent()
  209. }
  210. }