-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsha-upload.coffee
48 lines (37 loc) · 1.14 KB
/
sha-upload.coffee
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
UI = require "ui"
require "./extensions"
{Modal, Progress} = UI
# Upload to firebase storage based on SHA256 of file
module.exports = (folder, file) ->
file.readAsArrayBuffer()
.then (buffer) ->
crypto.subtle.digest("SHA-256", buffer)
.then hex
.then (sha) ->
console.log sha
new Promise (resolve, reject) ->
# Upload to CDN
ref = folder.child(sha)
uploadTask = ref.put file
progressView = Progress
value: 0
max: 1
Modal.show progressView.element,
cancellable: false
uploadTask.on 'state_changed', (snapshot) ->
progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
progressView.value progress
, (error) ->
# Handle unsuccessful uploads
Modal.hide()
reject(error)
, () ->
# Handle successful uploads on complete
# For instance, get the download URL: https://firebasestorage.googleapis.com/...
Modal.hide()
resolve(uploadTask.snapshot.downloadURL)
hex = (buffer) ->
buffer = new Uint8Array(buffer)
Array::map.call buffer, (x) ->
('00' + x.toString(16)).slice(-2)
.join('')