-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
234 lines (211 loc) · 9.63 KB
/
index.html
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
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<script>
// NOTE: This is a POC example implementation, not for production use. See README
// Constants for determining chunk size
const MEGABYTE = 1024 * 1024;
const CHUNK_SIZE = 20 * MEGABYTE;
// -----------------------------------
// Begin TrueVault API Call Wrappers
// -----------------------------------
// Create a JSON document in TrueVault
createDocument = function (authToken, vaultId, document) {
let formData = new FormData();
formData.append("document", btoa(JSON.stringify(document)));
let headers = new Headers();
headers.append("Authorization", `Basic ${btoa(authToken + ':')}`);
let request = new Request(`https://api.truevault.com/v1/vaults/${vaultId}/documents`, {
method: 'POST',
headers: headers,
body: formData
});
return fetch(request)
.then(response => response.json())
.then(json => {
if (json.result === 'error') {
let error = new Error(json.error.message);
error.error = json.error;
return Promise.reject(error);
} else {
return json.document_id;
}
})
};
// Read a JSON document from TrueVault
readDocument = function (authToken, vaultId, documentId) {
let headers = new Headers();
headers.append("Authorization", `Basic ${btoa(authToken + ':')}`);
let request = new Request(`https://api.truevault.com/v1/vaults/${vaultId}/documents/${documentId}`, {
method: 'GET',
headers: headers
});
return fetch(request)
.then(response => {
if (response.status === 200) {
return response.text();
} else {
return Promise.reject(`Request returned ${response.status}`)
}
}).then(responseText => JSON.parse(atob(responseText)));
};
// Read a BLOB from TrueVault
readBlob = function (authToken, vaultId, blobId) {
let headers = new Headers();
headers.append("Authorization", `Basic ${btoa(authToken + ':')}`);
let request = new Request(`https://api.truevault.com/v1/vaults/${vaultId}/blobs/${blobId}`, {
method: 'GET',
headers: headers
});
return fetch(request)
.then(response => {
if (response.status === 200) {
return response.blob();
} else {
return Promise.reject(`Request returned ${response.status}`)
}
});
};
// Write a BLOB to TrueVault
createBlob = function (authToken, vaultId, name, blobBody) {
let formData = new FormData();
formData.append("file", blobBody);
formData.append("name", name);
let headers = new Headers();
headers.append("Authorization", `Basic ${btoa(authToken + ':')}`);
let request = new Request(`https://api.truevault.com/v1/vaults/${vaultId}/blobs`, {
method: 'POST',
headers: headers,
body: formData
});
return fetch(request)
.then(response => response.json())
.then(json => {
if (json.result === 'error') {
let error = new Error(json.error.message);
error.error = json.error;
return Promise.reject(error);
} else {
return json.blob_id;
}
});
};
// -----------------------------------
// End TrueVault API Call Wrappers
// -----------------------------------
// ---------------------------------------------------------------------
// Below is sample code for grabbing the file, splitting it up, and
// sending each chunk to TrueVault.
// ---------------------------------------------------------------------
// This is just a throw away method to update a little status span for prototype
// to make the progress clear.
updateStatus = function (text) {
let statusEl = document.getElementById('status_val');
statusEl.innerHTML = text;
};
// After we've downloaded a BLOB we want to save it to the local file system.
// This method does that in a way that preserves the original name, effectively
// it creates a data url and clicks on the link.
saveBlobFile = function (blob, name) {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
// Download all the parts of a multi-part BLOB, using the ids stored
// in the metadataDocument
doCombinedDownload = function (token, vaultId, metadataDocumentId) {
readDocument(token, vaultId, metadataDocumentId).then(function (docjson) {
const blobIds = docjson.blob_ids;
const blobName = docjson.blob_name;
updateStatus(`Waiting to download all parts`);
const blobPromises = blobIds.map(bid => {
return readBlob(token, vaultId, bid).catch(function () {
alert("Failed to read blob, check inputs & console");
});
});
Promise.all(blobPromises).then(function (blobParts) {
var combinedBlob = new Blob(blobParts, {
type: 'application/octet-stream',
});
updateStatus(`Saving download to disk.`);
saveBlobFile(combinedBlob, blobName);
updateStatus(`Saved download to disk.`);
});
}).catch(function () {
alert("Failed to read metadata document, check inputs & console");
});
;
};
// Take a BLOB from the form and split it into many chunks to upload.
doSplitUpload = function (apiKey, vaultId) {
// Get the file that was chosen
const fileUploadEl = document.getElementById('fileuploadinput');
const file = fileUploadEl.files[0];
// Calculate the number of chunks
const chunkCount = Math.floor(file.size / CHUNK_SIZE) + 1;
// Keep track of each individual upload's promise so we can save the ids when it's all over.
let uploadPromises = [];
for (let currentChunk = 0; currentChunk < chunkCount; currentChunk += 1) {
const chunkValue = file.slice(currentChunk * CHUNK_SIZE, (currentChunk + 1) * CHUNK_SIZE);
const name = `${file.name}.part${currentChunk}`;
// Do the create blob, add the promise to the list
uploadPromises.push(
createBlob(apiKey, vaultId, name, chunkValue).catch(function () {
alert("Failed to create blobs, check inputs & console");
})
);
}
updateStatus(`Waiting for ${chunkCount} parts to upload`);
// When all promises are done, we will end up with an in-order array of resulting BLOB IDs
return Promise.all(uploadPromises).then(function (blobIds) {
updateStatus(`Creating metadata object.`);
return createDocument(apiKey, vaultId, {
blob_ids: blobIds,
blob_name: file.name
}).catch(function () {
alert("Failed to create metadata document, check inputs & console");
});
})
};
doDemoUploadThenDownload = function () {
const apiKey = document.getElementById('apikey').value;
const vaultId = document.getElementById('vaultid').value;
doSplitUpload(apiKey, vaultId).then(function (documentId) {
// Just for demo purposes, immediately re-download the blobs and merge them back together.
doCombinedDownload(apiKey, vaultId, documentId);
})
}
</script>
</head>
<body>
<p><strong>Status:</strong> <span id="status_val">Select File then Click Do Demo</span></p>
<hr/>
<form>
<div>
<p><label for="apikey">Vault ID (create a vault for testing)</label></p>
<input id='vaultid' type="text" name="vaultid">
</div>
<div>
<p><label for="apikey">API KEY (test only, a user who can create/read docs/blobs in vault) </label></p>
<input id='apikey' type="text" name="apikey">
</div>
<div>
<p><label for="fileuploadinput">Select a file (preferably 50-100MB)</label></p>
<input id='fileuploadinput' type="file" name="blobguy">
</div>
</form>
<div>
<p>Click this button to upload using multi-part, then immediately download again:</p>
<button onclick="doDemoUploadThenDownload()">Do Demo</button>
</div>
</body>
</html>