UploadedFile should support a callback for upload progress
[WebKit.git] / Websites / perf.webkit.org / public / v3 / models / uploaded-file.js
1
2 class UploadedFile extends DataModelObject {
3
4     constructor(id, object)
5     {
6         super(id, object);
7         this._createdAt = new Date(object.createdAt);
8         this._filename = object.filename;
9         this._author = object.author;
10         this._size = object.size;
11         this._sha256 = object.sha256;
12         this.ensureNamedStaticMap('sha256')[object.sha256] = this;
13     }
14
15     static uploadFile(file, uploadProgressCallback = null)
16     {
17         return PrivilegedAPI.sendRequest('upload-file', {'newFile': file}, {useFormData: true, uploadProgressCallback}).then((rawData) => {
18             return UploadedFile.ensureSingleton(rawData['uploadedFile'].id, rawData['uploadedFile']);
19         });
20     }
21
22     static fetchUnloadedFileWithIdenticalHash(file)
23     {
24         return new Promise((resolve, reject) => {
25             const reader = new FileReader();
26             reader.onload = () => resolve(reader.result);
27             reader.onerror = () => reject();
28             reader.readAsArrayBuffer(file);
29         }).then((content) => {
30             return this._computeSHA256Hash(content);
31         }).then((sha256) => {
32             const map = this.namedStaticMap('sha256');
33             if (map && sha256 in map)
34                 return map[sha256];
35             return RemoteAPI.getJSONWithStatus(`../api/uploaded-file?sha256=${sha256}`).then((rawData) => {
36                 if (!rawData['uploadedFile'])
37                     return null;
38                 return UploadedFile.ensureSingleton(rawData['uploadedFile'].id, rawData['uploadedFile']);
39             });
40         });
41     }
42
43     static _computeSHA256Hash(content)
44     {
45         return crypto.subtle.digest('SHA-256', content).then((digest) => {
46             return Array.from(new Uint8Array(digest)).map((byte) => {
47                 if (byte < 0x10)
48                     return '0' + byte.toString(16);
49                 return byte.toString(16);
50             }).join('');
51         });
52     }
53
54 }