-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathmd5_file_hasher.ts
110 lines (92 loc) · 2.88 KB
/
md5_file_hasher.ts
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
import {Md5} from './md5';
declare let FileReaderSync: any;
export interface HashingResponse {
success: boolean;
result?: string | Int32Array;
}
// Hashes any blob
export class Md5FileHasher {
private _reader: any;
private _md5!: Md5;
private _part!: number;
// private _length!: number;
private _blob: any;
constructor(
private _callback: (r: HashingResponse) => void, // Callback to return the result
private _async: boolean = true, // Async version is not always available in a web worker
private _partSize: number = 1048576, // 1mb
) {
this._configureReader();
}
/**
* Hash a blob of data in the worker
* @param blob Data to hash
*/
public hash(blob: any) {
const self = this;
self._blob = blob;
// self._length = Math.ceil(blob.size / self._partSize);
self._part = 0;
self._md5 = new Md5();
self._processPart();
}
private _fail() {
this._callback({
success: false,
result: 'data read failed'
});
}
private _hashData(e: any) {
let self = this;
self._md5.appendByteArray(new Uint8Array(e.target.result));
if (self._part * self._partSize >= self._blob.size) {
self._callback({
success: true,
result: self._md5.end()
});
} else {
self._processPart();
}
}
private _processPart() {
const self = this;
let endbyte = 0;
let current_part: any;
self._part += 1;
if (self._blob.size > self._partSize) { // If blob bigger then part_size we will slice it up
endbyte = self._part * self._partSize;
if (endbyte > self._blob.size) {
endbyte = self._blob.size;
}
current_part = self._blob.slice((self._part - 1) * self._partSize, endbyte);
} else {
current_part = self._blob;
}
if (self._async) {
self._reader.readAsArrayBuffer(current_part);
} else {
setTimeout(() => {
try {
self._hashData({
target: {
result: self._reader.readAsArrayBuffer(current_part)
},
});
} catch (e) {
self._fail();
}
}, 0);
}
}
private _configureReader() {
const self = this;
if (self._async) {
self._reader = new FileReader();
self._reader.onload = self._hashData.bind(self);
self._reader.onerror = self._fail.bind(self);
self._reader.onabort = self._fail.bind(self);
} else {
self._reader = new FileReaderSync();
}
}
}