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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use wasm_bindgen::throw_str;

pub mod callbacks {
    use crate::{
        blob::Blob,
        file_reader::{FileReadError, ReadyState},
    };
    use gloo_events::EventListener;
    use std::{cell::RefCell, rc::Rc};
    use wasm_bindgen::{prelude::*, throw_str, JsCast, UnwrapThrowExt};

    /// A guard object that aborts the file read when dropped (if the read isn't already
    /// finished).
    #[derive(Debug)]
    pub struct FileReader {
        reader: web_sys::FileReader,
        _load_listener: EventListener,
        _error_listener: EventListener,
    }

    impl std::ops::Drop for FileReader {
        fn drop(&mut self) {
            if !ReadyState::from(self.reader.ready_state()).is_done() {
                self.reader.abort();
            }
        }
    }

    /// Asynchronously converts `blob` into a text string and then passes it to the `callback`.
    ///
    /// If the returned `FileReader` is dropped before the callback is called, the read will be
    /// cancelled.
    pub fn read_as_text<F>(blob: &Blob, callback: F) -> FileReader
    where
        F: FnOnce(Result<String, FileReadError>) + 'static,
    {
        read(
            blob,
            callback,
            |value| value.as_string().unwrap_throw(),
            |reader, blob| reader.read_as_text(blob).unwrap_throw(),
        )
    }

    /// Asynchronously converts the `blob` into a base64 encoded `data:` URL and then passes it to
    /// the `callback`.
    ///
    /// If the returned `FileReader` is dropped before the callback is called, the read will be
    /// cancelled.
    pub fn read_as_data_url<F>(blob: &Blob, callback: F) -> FileReader
    where
        F: FnOnce(Result<String, FileReadError>) + 'static,
    {
        read(
            blob,
            callback,
            |value| value.as_string().unwrap_throw(),
            |reader, blob| reader.read_as_data_url(blob).unwrap_throw(),
        )
    }

    /// Asynchronously converts the `blob` into an array buffer and then passes it to the `callback`.
    ///
    /// If the returned `FileReader` is dropped before the callback is called, the read will be
    /// cancelled.
    pub fn read_as_array_buffer<F>(blob: &Blob, callback: F) -> FileReader
    where
        F: FnOnce(Result<js_sys::ArrayBuffer, FileReadError>) + 'static,
    {
        read(
            blob,
            callback,
            |value| value.dyn_into::<js_sys::ArrayBuffer>().unwrap_throw(),
            |reader, blob| reader.read_as_array_buffer(blob).unwrap_throw(),
        )
    }

    /// Asynchronously converts the `blob` into a `Vec<u8>` and then passes it to the `callback`.
    ///
    /// If the returned `FileReader` is dropped before the callback is called, the read will be
    /// cancelled.
    pub fn read_as_bytes<F>(blob: &Blob, callback: F) -> FileReader
    where
        F: FnOnce(Result<Vec<u8>, FileReadError>) + 'static,
    {
        read_as_array_buffer(blob, move |result| {
            callback(result.map(|buffer| js_sys::Uint8Array::new(&buffer).to_vec()));
        })
    }

    /// Generic function to start the async read of the `FileReader`.
    ///
    /// `callback` is the user-supplied callback, `extract_fn` function converts between JsValue
    /// returned by the read and the type the callback expects, and `read_fn` is the method that
    /// runs the async read on the `FileReader`.
    fn read<T, CF, EF, RF>(blob: &Blob, callback: CF, extract_fn: EF, read_fn: RF) -> FileReader
    where
        CF: FnOnce(Result<T, FileReadError>) + 'static,
        EF: Fn(JsValue) -> T + 'static,
        RF: Fn(&web_sys::FileReader, &web_sys::Blob) + 'static,
    {
        // we need to be able to run the FnOnce, while proving to the compiler that it can only run
        // once. The easiest way is to `take` it out of an Option. The `Rc` and `RefCell` are
        // because we need shared ownership and mutability (for the `take`).
        let load_callback: Rc<RefCell<Option<CF>>> = Rc::new(RefCell::new(Some(callback)));
        let error_callback = load_callback.clone();

        let reader = web_sys::FileReader::new().unwrap_throw();

        let load_reader = reader.clone();
        let error_reader = reader.clone();
        // Either the load listener or the error listener will be called, never both (so FnOnce is
        // ok).
        let load_listener = EventListener::new(&reader, "load", move |_event| {
            let result = extract_fn(load_reader.result().unwrap_throw());
            let callback = load_callback.borrow_mut().take().unwrap_throw();
            callback(Ok(result));
        });

        let error_listener = EventListener::new(&reader, "error", move |_event| {
            let exception = error_reader.error().unwrap_throw();
            let error = match exception.name().as_str() {
                "NotFoundError" => FileReadError::NotFound(exception.message()),
                "NotReadableError" => FileReadError::NotReadable(exception.message()),
                "SecurityError" => FileReadError::Security(exception.message()),
                // This branch should never be hit, so returning a less helpful error message is
                // less of an issue than pulling in `format!` code.
                _ => throw_str("unrecognised error type"),
            };
            let callback = error_callback.borrow_mut().take().unwrap_throw();
            callback(Err(error));
        });

        read_fn(&reader, blob.as_ref());

        FileReader {
            reader,
            _load_listener: load_listener,
            _error_listener: error_listener,
        }
    }
}

#[cfg(feature = "futures")]
pub mod futures {
    use crate::{Blob, FileReadError};
    use std::future::Future;
    use wasm_bindgen::UnwrapThrowExt;

    /// Returns the contents of `blob` as a text string.
    ///
    /// Equivalent to `async fn read_as_text(blob: &Blob) -> Result<String, FileReadError>` but
    /// without borrowing the `Blob` fore the lifetime of the future.
    pub fn read_as_text(blob: &Blob) -> impl Future<Output = Result<String, FileReadError>> {
        let (sender, receiver) = futures_channel::oneshot::channel();
        let reader = super::callbacks::read_as_text(blob, |result| {
            sender.send(result).unwrap_throw();
        });

        async move {
            let output = receiver.await.unwrap_throw();
            drop(reader);
            output
        }
    }

    /// Returns the contents of `blob` as a base64 encoded `data:` URL.
    ///
    /// Equivalent to `async fn read_as_data_url(blob: &Blob) -> Result<String, FileReadError>` but
    /// without borrowing the `Blob` fore the lifetime of the future.
    pub fn read_as_data_url(blob: &Blob) -> impl Future<Output = Result<String, FileReadError>> {
        let (sender, receiver) = futures_channel::oneshot::channel();
        let reader = super::callbacks::read_as_data_url(blob, |result| {
            sender.send(result).unwrap_throw();
        });

        async move {
            let output = receiver.await.unwrap_throw();
            drop(reader);
            output
        }
    }

    /// Returns the contents of `blob` as an array buffer.
    ///
    /// Equivalent to
    /// `async fn read_as_array_buffer(blob: &Blob) -> Result<js_sys::ArrayBuffer, FileReadError>`
    /// but without borrowing the `Blob` fore the lifetime of the future.
    pub fn read_as_array_buffer(
        blob: &Blob,
    ) -> impl Future<Output = Result<js_sys::ArrayBuffer, FileReadError>> {
        let (sender, receiver) = futures_channel::oneshot::channel();
        let reader = super::callbacks::read_as_array_buffer(blob, |result| {
            sender.send(result).unwrap_throw();
        });

        async move {
            let output = receiver.await.unwrap_throw();
            drop(reader);
            output
        }
    }

    /// Returns the contents of `blob` as a `Vec<u8>`.
    ///
    /// Equivalent to
    /// `async fn read_as_bytes(blob: &Blob) -> Result<Vec<u8>, FileReadError>`
    /// but without borrowing the `Blob` fore the lifetime of the future.
    pub fn read_as_bytes(blob: &Blob) -> impl Future<Output = Result<Vec<u8>, FileReadError>> {
        let (sender, receiver) = futures_channel::oneshot::channel();
        let reader = super::callbacks::read_as_bytes(blob, |result| {
            sender.send(result).unwrap_throw();
        });

        async move {
            let output = receiver.await.unwrap_throw();
            drop(reader);
            output
        }
    }
}

enum ReadyState {
    Empty,
    Loading,
    Done,
}

impl ReadyState {
    fn is_done(&self) -> bool {
        matches!(self, ReadyState::Done)
    }
}

impl From<u16> for ReadyState {
    fn from(val: u16) -> Self {
        match val {
            0 => ReadyState::Empty,
            1 => ReadyState::Loading,
            2 => ReadyState::Done,
            _ => throw_str("got invalid value for FileReader.readyState"),
        }
    }
}

#[derive(Debug)]
pub enum FileReadError {
    AbortedEarly,
    NotFound(String),
    NotReadable(String),
    Security(String),
}

impl std::fmt::Display for FileReadError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            FileReadError::AbortedEarly => write!(f, "FileReader aborted early"),
            FileReadError::NotFound(msg) => write!(f, "FileReader cannot find blob: {}", msg),
            FileReadError::NotReadable(msg) => {
                write!(f, "FileReader cannot read contents of blob: {}", msg)
            }
            FileReadError::Security(msg) => {
                write!(f, "FileReader encountered a security exception: {}", msg)
            }
        }
    }
}

impl std::error::Error for FileReadError {}