aboutsummaryrefslogtreecommitdiff
path: root/lib/elements/transfert.ml
blob: 878af2d689bbaf7a21892da5eaff122dfaa5c6b4 (plain)
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
open Brr

let send_raw : filename:Jstr.t -> Jstr.t -> unit =
 fun ~filename data ->
  (* Create the link to download the the element, and simulate a click on it *)
  let a =
    El.a
      ~at:
        At.[ href Jv.Id.(of_jv @@ to_jv data); v (Jstr.v "download") filename ]
      []
  in
  El.click a


(** Send a file to the user. *)
let send : mime_type:Jstr.t -> filename:Jstr.t -> Jstr.t -> unit =
 fun ~mime_type ~filename content ->
  let btoa = Jv.get Jv.global "btoa" in
  let base64data = Jv.apply btoa [| Jv.of_jstr content |] in

  let data =
    Jv.to_jstr
    @@ Jv.call
         (Jv.of_string "data:")
         "concat"
         [| Jv.of_jstr mime_type; Jv.of_jstr (Jstr.v ";base64,"); base64data |]
  in

  send_raw ~filename data


(** Load the content at the given URL and return it 
    The response body is only loaded if the result code is 200
 *)
let get_content_from_url :
    string -> (int * Jstr.t, Jv.Error.t) result Note.event =
 fun resource ->
  Brr_io.Fetch.Request.v (Jstr.v resource)
  |> Brr_io.Fetch.request
  |> fun f ->
  Fut.bind f (fun result ->
      match result with
      | Error e -> Fut.return (Error e)
      | Ok response ->
        (* Check the status before loading the response itself *)
        ( match Brr_io.Fetch.Response.status response with
        | 200 ->
            Brr_io.Fetch.Response.as_body response
            |> Brr_io.Fetch.Body.text
            |> Fut.map
                 (Result.map (fun v ->
                      (Brr_io.Fetch.Response.status response, v) ) )
        | other -> Fut.return (Ok (other, Jstr.empty)) ) )
  |> Brr_note.Futr.to_event