about summary refs log tree commit diff
path: root/modules/expo-bluesky-swiss-army/ios/HLSDownload/HLSDownloadView.swift
blob: 591c09335b5a45cbf8802f6124bab7f8f34e5183 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import ExpoModulesCore
import WebKit

class HLSDownloadView: ExpoView, WKScriptMessageHandler, WKNavigationDelegate, WKDownloadDelegate {
  var webView: WKWebView!
  var downloaderUrl: URL?

  private var onStart = EventDispatcher()
  private var onError = EventDispatcher()
  private var onProgress = EventDispatcher()
  private var onSuccess = EventDispatcher()

  private var outputUrl: URL?

  public required init(appContext: AppContext? = nil) {
    super.init(appContext: appContext)

    // controller for post message api
    let contentController = WKUserContentController()
    contentController.add(self, name: "onMessage")
    let configuration = WKWebViewConfiguration()
    configuration.userContentController = contentController

    // create webview
    let webView = WKWebView(frame: .zero, configuration: configuration)

    // Use these for debugging, to see the webview itself
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    webView.layer.masksToBounds = false
    webView.backgroundColor = .clear
    webView.contentMode = .scaleToFill

    webView.navigationDelegate = self

    self.addSubview(webView)
    self.webView = webView
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  // MARK: - view functions

  func startDownload(sourceUrl: URL) {
    guard let downloaderUrl = self.downloaderUrl,
          let url = URL(string: "\(downloaderUrl.absoluteString)?videoUrl=\(sourceUrl.absoluteString)") else {
      self.onError([
        "message": "Downloader URL is not set."
      ])
      return
    }

    self.onStart()
    self.webView.load(URLRequest(url: url))
  }

  // webview message handling

  func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    guard let response = message.body as? String,
          let data = response.data(using: .utf8),
          let payload = try? JSONDecoder().decode(WebViewActionPayload.self, from: data) else {
      self.onError([
        "message": "Failed to decode JSON post message."
      ])
      return
    }

    switch payload.action {
    case .progress:
      guard let progress = payload.messageFloat else {
        self.onError([
          "message": "Failed to decode JSON post message."
        ])
        return
      }
      self.onProgress([
        "progress": progress
      ])
      case .error:
      guard let messageStr = payload.messageStr else {
        self.onError([
          "message": "Failed to decode JSON post message."
        ])
        return
      }
      self.onError([
        "message": messageStr
      ])
    }
  }

  func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy {
    guard #available(iOS 14.5, *) else {
      return .cancel
    }

    if navigationAction.shouldPerformDownload {
      return .download
    } else {
      return .allow
    }
  }

  // MARK: - wkdownloaddelegate

  @available(iOS 14.5, *)
  func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
    download.delegate = self
  }

  @available(iOS 14.5, *)
  func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
    download.delegate = self
  }

  @available(iOS 14.5, *)
  func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
    let directory = NSTemporaryDirectory()
    let fileName = "\(NSUUID().uuidString).mp4"
    let url = NSURL.fileURL(withPathComponents: [directory, fileName])

    self.outputUrl = url
    completionHandler(url)
  }

  @available(iOS 14.5, *)
  func downloadDidFinish(_ download: WKDownload) {
    guard let url = self.outputUrl else {
      return
    }
    self.onSuccess([
      "uri": url.absoluteString
    ])
    self.outputUrl = nil
  }
}

struct WebViewActionPayload: Decodable {
  enum Action: String, Decodable {
    case progress, error
  }

  let action: Action
  let messageStr: String?
  let messageFloat: Float?
}