ShareViewController.swift 8.8 KB

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