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