WebxdcViewController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import UIKit
  2. import WebKit
  3. import DcCore
  4. class WebxdcViewController: WebViewViewController {
  5. enum WebxdcHandler: String {
  6. case log = "log"
  7. case setUpdateListener = "setUpdateListener"
  8. case sendStatusUpdate = "sendStatusUpdateHandler"
  9. }
  10. let INTERNALSCHEMA = "webxdc"
  11. var messageId: Int
  12. var dcContext: DcContext
  13. var webxdcUpdateObserver: NSObjectProtocol?
  14. var webxdcName: String = ""
  15. var sourceCodeUrl: String?
  16. private var shortcutManager: ShortcutManager?
  17. private lazy var moreButton: UIBarButtonItem = {
  18. let image: UIImage?
  19. if #available(iOS 13.0, *) {
  20. image = UIImage(systemName: "ellipsis.circle")
  21. } else {
  22. image = UIImage(named: "ic_more")
  23. }
  24. return UIBarButtonItem(image: image,
  25. style: .plain,
  26. target: self,
  27. action: #selector(moreButtonPressed))
  28. }()
  29. // Block just everything, except of webxdc urls
  30. let blockRules = """
  31. [
  32. {
  33. "trigger": {
  34. "url-filter": ".*"
  35. },
  36. "action": {
  37. "type": "block"
  38. }
  39. },
  40. {
  41. "trigger": {
  42. "url-filter": "webxdc://*"
  43. },
  44. "action": {
  45. "type": "ignore-previous-rules"
  46. }
  47. }
  48. ]
  49. """
  50. lazy var webxdcbridge: String = {
  51. let addr = dcContext.addr?
  52. .addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
  53. let displayname = (dcContext.displayname ?? dcContext.addr)?
  54. .addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
  55. let script = """
  56. window.webxdc = (() => {
  57. var log = (s)=>webkit.messageHandlers.log.postMessage(s);
  58. var update_listener = () => {};
  59. let should_run_again = false;
  60. let running = false;
  61. let lastSerial = 0;
  62. window.__webxdcUpdate = async () => {
  63. if (running) {
  64. should_run_again = true
  65. return
  66. }
  67. should_run_again = false
  68. running = true;
  69. try {
  70. const updates = await fetch("webxdc-update.json?"+lastSerial).then((response) => response.json())
  71. updates.forEach((update) => {
  72. update_listener(update);
  73. if (lastSerial < update["max_serial"]){
  74. lastSerial = update["max_serial"]
  75. }
  76. });
  77. } catch (e) {
  78. log("json error: "+ e.message)
  79. } finally {
  80. running = false;
  81. if (should_run_again) {
  82. await window.__webxdcUpdate()
  83. }
  84. }
  85. }
  86. return {
  87. selfAddr: decodeURI("\((addr ?? "unknown"))"),
  88. selfName: decodeURI("\((displayname ?? "unknown"))"),
  89. setUpdateListener: (cb, serial) => {
  90. update_listener = cb
  91. return window.__webxdcUpdate()
  92. },
  93. getAllUpdates: () => {
  94. console.error("deprecated 2022-02-20 all updates are returned through the callback set by setUpdateListener");
  95. return Promise.resolve([]);
  96. },
  97. sendUpdate: (payload, descr) => {
  98. // only one parameter is allowed, we we create a new parameter object here
  99. var parameter = {
  100. payload: payload,
  101. descr: descr
  102. };
  103. webkit.messageHandlers.sendStatusUpdateHandler.postMessage(parameter);
  104. },
  105. };
  106. })();
  107. """
  108. return script
  109. }()
  110. override var configuration: WKWebViewConfiguration {
  111. let config = WKWebViewConfiguration()
  112. let preferences = WKPreferences()
  113. let contentController = WKUserContentController()
  114. contentController.add(self, name: WebxdcHandler.sendStatusUpdate.rawValue)
  115. contentController.add(self, name: WebxdcHandler.setUpdateListener.rawValue)
  116. contentController.add(self, name: WebxdcHandler.log.rawValue)
  117. config.userContentController = contentController
  118. config.setURLSchemeHandler(self, forURLScheme: INTERNALSCHEMA)
  119. config.mediaTypesRequiringUserActionForPlayback = []
  120. config.allowsInlineMediaPlayback = true
  121. if #available(iOS 13.0, *) {
  122. preferences.isFraudulentWebsiteWarningEnabled = true
  123. }
  124. if #available(iOS 14.0, *) {
  125. config.defaultWebpagePreferences.allowsContentJavaScript = true
  126. } else {
  127. preferences.javaScriptEnabled = true
  128. }
  129. preferences.javaScriptCanOpenWindowsAutomatically = false
  130. config.preferences = preferences
  131. return config
  132. }
  133. init(dcContext: DcContext, messageId: Int) {
  134. self.dcContext = dcContext
  135. self.messageId = messageId
  136. self.shortcutManager = ShortcutManager(dcContext: dcContext, messageId: messageId)
  137. super.init()
  138. }
  139. required init?(coder: NSCoder) {
  140. fatalError("init(coder:) has not been implemented")
  141. }
  142. override func viewDidLoad() {
  143. super.viewDidLoad()
  144. let msg = dcContext.getMessage(id: messageId)
  145. let dict = msg.getWebxdcInfoDict()
  146. let document = dict["document"] as? String ?? ""
  147. webxdcName = dict["name"] as? String ?? "ErrName" // name should not be empty
  148. let chatName = dcContext.getChat(chatId: msg.chatId).name
  149. self.title = document.isEmpty ? "\(webxdcName) – \(chatName)" : "\(document) – \(chatName)"
  150. navigationItem.rightBarButtonItem = moreButton
  151. if let sourceCode = dict["source_code_url"] as? String,
  152. !sourceCode.isEmpty {
  153. sourceCodeUrl = sourceCode
  154. }
  155. }
  156. override func willMove(toParent parent: UIViewController?) {
  157. super.willMove(toParent: parent)
  158. let willBeRemoved = parent == nil
  159. navigationController?.interactivePopGestureRecognizer?.isEnabled = willBeRemoved
  160. if willBeRemoved {
  161. // remove observer
  162. let nc = NotificationCenter.default
  163. if let webxdcUpdateObserver = webxdcUpdateObserver {
  164. nc.removeObserver(webxdcUpdateObserver)
  165. }
  166. shortcutManager = nil
  167. } else {
  168. addObserver()
  169. }
  170. }
  171. private func addObserver() {
  172. let nc = NotificationCenter.default
  173. webxdcUpdateObserver = nc.addObserver(
  174. forName: dcNotificationWebxdcUpdate,
  175. object: nil,
  176. queue: OperationQueue.main
  177. ) { [weak self] notification in
  178. guard let self = self else { return }
  179. guard let ui = notification.userInfo,
  180. let messageId = ui["message_id"] as? Int else {
  181. logger.error("failed to handle dcNotificationWebxdcUpdate")
  182. return
  183. }
  184. if messageId == self.messageId {
  185. self.updateWebxdc()
  186. }
  187. }
  188. }
  189. override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  190. // TODO: what about tel://
  191. if let url = navigationAction.request.url {
  192. if url.scheme == "mailto" {
  193. askToChatWith(url: url)
  194. decisionHandler(.cancel)
  195. return
  196. } else if url.scheme != INTERNALSCHEMA {
  197. logger.debug("cancel loading: \(url)")
  198. decisionHandler(.cancel)
  199. return
  200. }
  201. }
  202. logger.debug("loading: \(String(describing: navigationAction.request.url))")
  203. decisionHandler(.allow)
  204. }
  205. override func viewWillAppear(_ animated: Bool) {
  206. super.viewWillAppear(animated)
  207. loadRestrictedHtml()
  208. }
  209. override func viewDidDisappear(_ animated: Bool) {
  210. super.viewDidDisappear(animated)
  211. if #available(iOS 15.0, *) {
  212. webView.setAllMediaPlaybackSuspended(true)
  213. }
  214. }
  215. private func loadRestrictedHtml() {
  216. // TODO: compile only once
  217. WKContentRuleListStore.default().compileContentRuleList(
  218. forIdentifier: "WebxdcContentBlockingRules",
  219. encodedContentRuleList: blockRules) { (contentRuleList, error) in
  220. guard let contentRuleList = contentRuleList, error == nil else {
  221. return
  222. }
  223. let configuration = self.webView.configuration
  224. configuration.userContentController.add(contentRuleList)
  225. self.loadHtml()
  226. }
  227. }
  228. private func loadHtml() {
  229. DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  230. guard let self = self else { return }
  231. let url = URL(string: "\(self.INTERNALSCHEMA)://acc\(self.dcContext.id)-msg\(self.messageId).localhost/index.html")
  232. let urlRequest = URLRequest(url: url!)
  233. DispatchQueue.main.async {
  234. self.webView.load(urlRequest)
  235. }
  236. }
  237. }
  238. private func updateWebxdc() {
  239. webView.evaluateJavaScript("window.__webxdcUpdate()", completionHandler: nil)
  240. }
  241. @objc private func moreButtonPressed() {
  242. let alert = UIAlertController(title: webxdcName + " – " + String.localized("webxdc_app"),
  243. message: nil,
  244. preferredStyle: .safeActionSheet)
  245. let addToHomescreenAction = UIAlertAction(title: String.localized("add_to_home_screen"), style: .default, handler: addToHomeScreen(_:))
  246. alert.addAction(addToHomescreenAction)
  247. if sourceCodeUrl != nil {
  248. let sourceCodeAction = UIAlertAction(title: String.localized("source_code"), style: .default, handler: openUrl(_:))
  249. alert.addAction(sourceCodeAction)
  250. }
  251. let cancelAction = UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil)
  252. alert.addAction(cancelAction)
  253. self.present(alert, animated: true, completion: nil)
  254. }
  255. private func addToHomeScreen(_ action: UIAlertAction) {
  256. shortcutManager?.showShortcutLandingPage()
  257. }
  258. private func openUrl(_ action: UIAlertAction) {
  259. if let sourceCodeUrl = sourceCodeUrl,
  260. let url = URL(string: sourceCodeUrl) {
  261. UIApplication.shared.open(url)
  262. }
  263. }
  264. private func askToChatWith(url: URL) {
  265. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  266. let emailAddress = parseEmailAddress(from: url) else {
  267. return
  268. }
  269. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), emailAddress),
  270. message: nil,
  271. preferredStyle: .safeActionSheet)
  272. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { _ in
  273. RelayHelper.shared.askToChatWithMailto = false
  274. _ = appDelegate.application(UIApplication.shared, open: url)
  275. }))
  276. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  277. present(alert, animated: true, completion: nil)
  278. }
  279. private func parseEmailAddress(from url: URL) -> String? {
  280. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false),
  281. !urlComponents.path.isEmpty {
  282. return RelayHelper.shared.splitString(urlComponents.path)[0]
  283. }
  284. return nil
  285. }
  286. }
  287. extension WebxdcViewController: WKScriptMessageHandler {
  288. func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  289. let handler = WebxdcHandler(rawValue: message.name)
  290. switch handler {
  291. case .log:
  292. guard let msg = message.body as? String else {
  293. logger.error("could not convert param \(message.body) to string")
  294. return
  295. }
  296. logger.debug("webxdc log msg: "+msg)
  297. case .sendStatusUpdate:
  298. guard let dict = message.body as? [String: AnyObject],
  299. let payloadDict = dict["payload"] as? [String: AnyObject],
  300. let payloadJson = try? JSONSerialization.data(withJSONObject: payloadDict, options: []),
  301. let payloadString = String(data: payloadJson, encoding: .utf8),
  302. let description = dict["descr"] as? String else {
  303. logger.error("Failed to parse status update parameters \(message.body)")
  304. return
  305. }
  306. _ = dcContext.sendWebxdcStatusUpdate(msgId: messageId, payload: payloadString, description: description)
  307. default:
  308. logger.debug("another method was called")
  309. }
  310. }
  311. }
  312. extension WebxdcViewController: WKURLSchemeHandler {
  313. func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
  314. if let url = urlSchemeTask.request.url, let scheme = url.scheme, scheme == INTERNALSCHEMA {
  315. if url.path == "/webxdc-update.json" || url.path == "webxdc-update.json" {
  316. let lastKnownSerial = Int(url.query ?? "0") ?? 0
  317. let data = Data(
  318. dcContext.getWebxdcStatusUpdates(msgId: messageId, lastKnownSerial: lastKnownSerial).utf8)
  319. let response = URLResponse(url: url, mimeType: "application/json", expectedContentLength: data.count, textEncodingName: "utf-8")
  320. urlSchemeTask.didReceive(response)
  321. urlSchemeTask.didReceive(data)
  322. urlSchemeTask.didFinish()
  323. return
  324. }
  325. let file = url.path
  326. let dcMsg = dcContext.getMessage(id: messageId)
  327. var data: Data
  328. if url.lastPathComponent == "webxdc.js" {
  329. data = Data(webxdcbridge.utf8)
  330. } else {
  331. data = dcMsg.getWebxdcBlob(filename: file)
  332. }
  333. let mimeType = DcUtils.getMimeTypeForPath(path: file)
  334. let statusCode = (data.isEmpty ? 404 : 200)
  335. guard let response = HTTPURLResponse(
  336. url: url,
  337. statusCode: statusCode,
  338. httpVersion: "HTTP/1.1",
  339. headerFields: [
  340. "Content-Type": mimeType,
  341. "Content-Length": "\(data.count)"
  342. ]
  343. ) else {
  344. return
  345. }
  346. urlSchemeTask.didReceive(response)
  347. urlSchemeTask.didReceive(data)
  348. urlSchemeTask.didFinish()
  349. } else {
  350. logger.debug("not loading \(String(describing: urlSchemeTask.request.url))")
  351. }
  352. }
  353. func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
  354. }
  355. }