ShareViewController.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. lazy var dbHelper: DatabaseHelper = {
  27. return DatabaseHelper(dcContext: dcContext)
  28. }()
  29. let logger = SimpleLogger()
  30. let dcContext: DcContext = DcContext()
  31. var selectedChatId: Int?
  32. var selectedChat: DcChat?
  33. var shareAttachment: ShareAttachment?
  34. var isAccountConfigured: Bool = true
  35. var isLoading: Bool = true
  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. if dbHelper.currentDatabaseLocation == dbHelper.sharedDbFile {
  67. dcContext.logger = self.logger
  68. dcContext.openDatabase(dbFile: dbHelper.sharedDbFile)
  69. isAccountConfigured = dcContext.isConfigured()
  70. if isAccountConfigured {
  71. if #available(iOSApplicationExtension 13.0, *) {
  72. if let intent = self.extensionContext?.intent as? INSendMessageIntent, let chatId = Int(intent.conversationIdentifier ?? "") {
  73. selectedChatId = chatId
  74. }
  75. }
  76. if selectedChatId == nil {
  77. selectedChatId = dcContext.getChatIdByContactId(contactId: Int(DC_CONTACT_ID_SELF))
  78. }
  79. if let chatId = selectedChatId {
  80. selectedChat = dcContext.getChat(chatId: chatId)
  81. }
  82. DispatchQueue.global(qos: .userInitiated).async {
  83. self.shareAttachment = ShareAttachment(dcContext: self.dcContext, inputItems: self.extensionContext?.inputItems, delegate: self)
  84. }
  85. }
  86. reloadConfigurationItems()
  87. validateContent()
  88. } else {
  89. cancel()
  90. }
  91. }
  92. override func loadPreviewView() -> UIView! {
  93. return preview
  94. }
  95. override func isContentValid() -> Bool {
  96. // Do validation of contentText and/or NSExtensionContext attachments here
  97. return isAccountConfigured && !isLoading && (!(contentText?.isEmpty ?? true) || !(self.shareAttachment?.isEmpty ?? true))
  98. }
  99. private func setupNavigationBar() {
  100. guard let item = navigationController?.navigationBar.items?.first else { return }
  101. let button = UIBarButtonItem(
  102. title: String.localized("menu_send"),
  103. style: .done,
  104. target: self,
  105. action: #selector(appendPostTapped))
  106. item.rightBarButtonItem? = button
  107. }
  108. /// Invoked when the user wants to post.
  109. @objc
  110. private func appendPostTapped() {
  111. if let chatId = self.selectedChatId {
  112. guard var messages = shareAttachment?.messages else { return }
  113. if !self.contentText.isEmpty {
  114. if messages.count == 1 {
  115. messages[0].text?.append(self.contentText)
  116. } else {
  117. let message = dcContext.newMessage(viewType: DC_MSG_TEXT)
  118. message.text = self.contentText
  119. messages.insert(message, at: 0)
  120. }
  121. }
  122. let chatListController = SendingController(chatId: chatId, dcMsgs: messages, dcContext: dcContext)
  123. chatListController.delegate = self
  124. self.pushConfigurationViewController(chatListController)
  125. }
  126. }
  127. func quit() {
  128. if dbHelper.currentDatabaseLocation == dbHelper.sharedDbFile {
  129. dcContext.closeDatabase()
  130. }
  131. // Inform the host that we're done, so it un-blocks its UI.
  132. self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
  133. }
  134. override func configurationItems() -> [Any]! {
  135. let item = SLComposeSheetConfigurationItem()
  136. if isAccountConfigured {
  137. logger.debug("configurationItems")
  138. // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
  139. item?.title = String.localized("forward_to")
  140. item?.value = selectedChat?.name
  141. logger.debug("configurationItems chat name: \(String(describing: selectedChat?.name))")
  142. item?.tapHandler = {
  143. let chatListController = ChatListController(dcContext: self.dcContext, chatListDelegate: self)
  144. self.pushConfigurationViewController(chatListController)
  145. }
  146. } else {
  147. item?.title = String.localized("share_account_not_configured")
  148. }
  149. return [item as Any]
  150. }
  151. override func didSelectCancel() {
  152. quit()
  153. }
  154. }
  155. extension ShareViewController: ChatListDelegate {
  156. func onChatSelected(chatId: Int) {
  157. selectedChatId = chatId
  158. selectedChat = dcContext.getChat(chatId: chatId)
  159. reloadConfigurationItems()
  160. popConfigurationViewController()
  161. }
  162. }
  163. extension ShareViewController: SendingControllerDelegate {
  164. func onSendingAttemptFinished() {
  165. DispatchQueue.main.async {
  166. self.popConfigurationViewController()
  167. UserDefaults.shared?.set(true, forKey: UserDefaults.hasExtensionAttemptedToSend)
  168. self.quit()
  169. }
  170. }
  171. }
  172. extension ShareViewController: ShareAttachmentDelegate {
  173. func onUrlShared(url: URL) {
  174. DispatchQueue.main.async {
  175. if var contentText = self.contentText, !contentText.isEmpty {
  176. contentText.append("\n\(url.absoluteString)")
  177. self.textView.text = contentText
  178. } else {
  179. self.textView.text = "\(url.absoluteString)"
  180. }
  181. self.validateContent()
  182. }
  183. }
  184. func onAttachmentChanged() {
  185. DispatchQueue.main.async {
  186. self.validateContent()
  187. }
  188. }
  189. func onThumbnailChanged() {
  190. DispatchQueue.main.async { [weak self] in
  191. guard let self = self else { return }
  192. if let preview = self.preview {
  193. preview.image = self.shareAttachment?.thumbnail ?? nil
  194. if let image = preview.image, image.sd_imageFormat == .webP {
  195. self.previewImageWidthConstraint?.isActive = false
  196. self.previewImageHeightConstraint?.isActive = false
  197. preview.centerInSuperview()
  198. self.textView.text = nil
  199. self.textView.attributedText = nil
  200. self.placeholder = nil
  201. self.textView.isHidden = true
  202. }
  203. }
  204. }
  205. }
  206. func onLoadingFinished() {
  207. isLoading = false
  208. }
  209. }