-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
326 lines (272 loc) · 8.59 KB
/
index.js
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"use strict";
const EventEmitter = require('events').EventEmitter;
const util = require('util');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const mkdirSyncRecursively = require('./utils').mkdirSyncRecursively;
const createDirectoryIfNotExists = require('./utils').createDirectoryIfNotExists;
function SocketIOFile(socket, options) {
if(!socket) {
throw new Error('SocketIOFile requires Socket.');
}
this.options = options || {};
this.maxFileSize = +options.maxFileSize || undefined;
this.accepts = options.accepts || [];
this.chunkSize = +options.chunkSize || 10240;
this.transmissionDelay = options.transmissionDelay || 0;
this.overwrite = !!options.overwrite || false;
this.rename = options.rename || null;
this.resume = !!options.resume || false;
if(!options.uploadDir) {
throw new Error('No upload directory specified.');
}
// check directory is exists
if(typeof options.uploadDir === 'string') {
createDirectoryIfNotExists(options.uploadDir);
}
else if(typeof options.uploadDir === 'object') {
for(var key in options.uploadDir) {
createDirectoryIfNotExists(options.uploadDir[key]);
}
}
else {
throw new Error('options.uploadDir must be string or object array.');
}
this.socket = socket;
socket.on('socket.io-file::reqSync', () => {
socket.emit('socket.io-file::recvSync', {
maxFileSize: this.maxFileSize,
accepts: this.accepts,
chunkSize: this.chunkSize,
transmissionDelay: this.transmissionDelay
});
this.emit('ready');
});
var self = this;
var uploadingFiles = {};
socket.on('socket.io-file::createFile', (fileInfo) => {
var id = fileInfo.id;
var uploadDir = null;
var uploadTo = fileInfo.uploadTo || '';
var data = fileInfo.data || {};
var filename = fileInfo.name;
var originalFileName = fileInfo.name;
function sendError(err) {
socket.emit(`socket.io-file::error::${id}`, {
message: err.message
});
self.emit('error', err, {
uploadId: id,
name: filename,
uploadTo: uploadTo,
data: data
});
}
if(this.rename) {
if(typeof this.rename === 'function') {
filename = this.rename(filename, fileInfo);
}
else {
filename = this.rename;
}
}
if(typeof options.uploadDir === 'string') {
uploadDir = path.join(options.uploadDir, filename);
}
else if(typeof options.uploadDir === 'object') {
if(!uploadTo) {
return sendError(new Error('Upload directory must be specified in multiple directories.'));
}
else if(options.uploadDir[uploadTo]) {
uploadDir = path.join(options.uploadDir[uploadTo], filename);
}
else {
return sendError(new Error('Upload directory ' + uploadTo + ' is not exists.'));
}
}
else if(fileInfo.size > this.maxFileSize) {
return sendError(new Error('Max Uploading File size must be under ' + this.maxFileSize + ' byte(s).'));
}
var startTime = new Date();
const emitObj = {
name: filename,
size: fileInfo.size,
uploadDir: uploadDir,
data: data
};
if(this.rename) {
// rename setting
// add origininalFileName to emitObj
emitObj.originalFileName = originalFileName;
}
this.emit('start', emitObj);
const uploadComplete = () => {
const ws = uploadingFiles[id].writeStream;
if(ws) {
ws.end();
}
const endTime = new Date();
const mimeType = mime.lookup(uploadDir);
const emitObj = {
name: filename,
size: uploadingFiles[id].size,
wrote: uploadingFiles[id].wrote,
uploadDir: uploadingFiles[id].uploadDir,
data: uploadingFiles[id].data,
mime: mimeType,
estimated: endTime - startTime,
uploadId: id
};
if(this.rename) {
// rename setting
// add originalFileName to emitObj
emitObj.originalFileName = originalFileName;
}
if(this.accepts && this.accepts.length > 0) {
let found = false;
for(var i = 0; i < this.accepts.length; i++) {
let accept = this.accepts[i];
if(mimeType === accept) {
found = true;
break;
}
}
// if mime is invalid, remove files and emit error
if(!found) {
fs.unlink(uploadDir, (err) => { console.log(err) }); // Node 10 onwards requires callback to be specified
let err = new Error('Not Acceptable file type ' + mimeType + ' of ' + filename + '. Type must be one of these: ' + this.accepts.join(', '));
return sendError(err);
}
else {
self.socket.emit(`socket.io-file::complete::${id}`, emitObj);
self.emit('complete', emitObj);
}
}
else {
self.socket.emit(`socket.io-file::complete::${id}`, emitObj);
self.emit('complete', emitObj);
}
// Release event handlers
socket.removeAllListeners(`socket.io-file::stream::${id}`);
socket.removeAllListeners(`socket.io-file::done::${id}`);
socket.removeAllListeners(`socket.io-file::complete::${id}`);
socket.removeAllListeners(`socket.io-file::abort::${id}`);
socket.removeAllListeners(`socket.io-file::error::${id}`);
delete uploadingFiles[id];
};
uploadingFiles[id] = {
writeStream: null,
name: fileInfo.name,
size: fileInfo.size,
wrote: 0,
uploadDir: uploadDir,
data: data,
resume: false,
};
// check if file exists
const isFileExists = fs.existsSync(uploadDir);
if (isFileExists) {
const uploadedFileStats = fs.statSync(uploadDir);
if (this.resume) {
if (uploadingFiles[id].size > 0) {
if (uploadingFiles[id].size > uploadedFileStats.size) {
uploadingFiles[id].wrote = uploadedFileStats.size;
uploadingFiles[id].resume = true;
socket.emit(`socket.io-file::resume::${id}`, uploadingFiles[id]);
} else {
if (!this.overwrite) return uploadComplete();
}
}
} else {
if (!this.overwrite) return uploadComplete();
}
}
if(!options.overwrite) {
let isFileExists = false;
try {
fs.accessSync(uploadDir, fs.F_OK);
isFileExists = true;
}
catch(e) {
// console.log('File is not exists, so create new one.');
}
if(isFileExists) return uploadComplete();
}
var writeStream = fs.createWriteStream(uploadDir);
uploadingFiles[id].writeStream = writeStream;
socket.emit(`socket.io-file::request::${id}`);
socket.on(`socket.io-file::stream::${id}`, (chunk) => {
if(uploadingFiles[id].abort) {
socket.removeAllListeners(`socket.io-file::stream::${id}`);
socket.removeAllListeners(`socket.io-file::done::${id}`);
socket.removeAllListeners(`socket.io-file::complete::${id}`);
socket.removeAllListeners(`socket.io-file::abort::${id}`);
socket.removeAllListeners(`socket.io-file::error::${id}`);
uploadingFiles[id].writeStream.end();
delete uploadingFiles[id];
return;
}
var writeStream = uploadingFiles[id].writeStream;
function write() {
let result = (uploadingFiles[id].wrote + chunk.length) > (self.maxFileSize);
if( (uploadingFiles[id].wrote + chunk.length) > (self.maxFileSize)) {
return sendError(new Error(`Uploading file size exceeded max file size ${self.maxFileSize} byte(s).`));
}
var writeDone = writeStream.write(chunk);
uploadingFiles[id].wrote += chunk.length;
self.emit('stream', {
name: uploadingFiles[id].name,
size: uploadingFiles[id].size,
wrote: uploadingFiles[id].wrote,
uploadDir: uploadingFiles[id].uploadDir,
data: uploadingFiles[id].data,
uploadId: id
});
if(!writeDone) {
writeStream.once('drain', () => socket.emit(`socket.io-file::request::${id}`));
}
else {
if(self.transmissionDelay) {
setTimeout(() => {
socket.emit(`socket.io-file::request::${id}`);
}, self.transmissionDelay);
}
else {
socket.emit(`socket.io-file::request::${id}`);
}
}
}
write();
});
socket.on(`socket.io-file::done::${id}`, () => {
uploadComplete();
});
socket.on(`socket.io-file::abort::${id}`, () => {
uploadingFiles[id].abort = true;
self.emit('abort', {
name: uploadingFiles[id].name,
size: uploadingFiles[id].size,
wrote: uploadingFiles[id].wrote,
uploadDir: uploadingFiles[id].uploadDir,
data: uploadingFiles[id].data,
uploadId: id
});
socket.emit(`socket.io-file::abort::${id}`, {
name: uploadingFiles[id].name,
size: uploadingFiles[id].size,
wrote: uploadingFiles[id].wrote,
uploadDir: uploadingFiles[id].uploadDir
});
});
});
}
SocketIOFile.prototype.destroy = function() {
this.emit('destroy');
this.socket.emit('socket.io-file::disconnectByServer');
// Clear the resources
this.removeAllListeners();
this.socket = null; // Remove reference of Socket.io
};
util.inherits(SocketIOFile, EventEmitter);
module.exports = SocketIOFile;