ShareViewController.swift 9.4 KB

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