UNPKG

2.56 kBJavaScriptView Raw
1import work from 'webworkify-webpack';
2import crc32 from 'crc32';
3
4class Uploader {
5 constructor({onProgress, onError, complete, ...params}) {
6 this.state.workerManager = work(require.resolve('./workersManager.worker.js'));
7 this.state.workerManager.onmessage = this.onMessage;
8 this.postMessage({payload: params, event: 'setParams'});
9 this.onProgress = onProgress;
10 this.onError = onError;
11 this.complete = complete;
12 }
13
14 state = {
15 uploadedFiles: [],
16 workerManager: null
17 };
18
19 resume = (fileId) => {
20 const idIsCorrect = this.verifyId(fileId);
21
22 if (idIsCorrect) {
23 this.postMessage({payload: fileId, event: 'resumeUpload'});
24 }
25
26 return idIsCorrect;
27 }
28
29 pause = (fileId) => {
30 const idIsCorrect = this.verifyId(fileId);
31
32 if (idIsCorrect) {
33 this.postMessage({payload: fileId, event: 'pauseUpload'});
34 }
35
36 return idIsCorrect;
37 }
38
39 stop = (fileId) => {
40 const idIsCorrect = this.verifyId(fileId);
41
42 if (idIsCorrect) {
43 this.postMessage({payload: fileId, event: 'stopUpload'});
44 }
45
46 return idIsCorrect;
47 }
48
49 send = (files, url) => {
50 const post = [];
51
52 files.forEach((file) => {
53 const fileId = crc32(file.name + '-' + file.size + '-' + +file.lastModified);
54 const isContain = this.state.uploadedFiles.findIndex((identifier) => identifier === fileId);
55
56 if (isContain === -1) {
57 this.state.uploadedFiles.push(fileId);
58 post.push({id: fileId, data: file});
59 } else {
60 this.onError({
61 identifier: file.name,
62 error: {
63 message: file.name + ' file already is loading',
64 reason: ''
65 }
66 });
67 }
68 });
69
70 (post.length && this.postMessage({
71 payload: {
72 files: post,
73 url: url
74 },
75 event: 'setFiles'
76 }));
77 }
78
79 postMessage = (data) => {
80 this.state.workerManager.postMessage(data);
81 }
82
83 onMessage = (message) => {
84 if (typeof this[message.data.event] === 'function') {
85 this[message.data.event](message.data.payload);
86 }
87 }
88
89 refreshUploadedFiles = (hashArray) => {
90 this.state.uploadedFiles = [...new Set([...this.state.uploadedFiles, ...hashArray])];
91 }
92
93 verifyId = (id) => {
94 const idIsCorrect = this.state.uploadedFiles.some((fileId) => fileId === id);
95
96 if (!idIsCorrect) {
97 this.onError({
98 identifier: id,
99 error: {
100 message: 'invalid identifier, no such file',
101 reason: ''
102 }
103 });
104 }
105
106 return idIsCorrect;
107 }
108}
109
110export default Uploader;