2017-06-19 18:37:35 +02:00
|
|
|
const publishController = require('../controllers/publishController.js');
|
2017-06-19 22:10:06 +02:00
|
|
|
const logger = require('winston');
|
2017-06-15 20:15:13 +02:00
|
|
|
|
2017-06-17 22:51:30 +02:00
|
|
|
module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => {
|
2017-06-19 18:37:35 +02:00
|
|
|
const http = require('http').Server(app);
|
|
|
|
const io = require('socket.io')(http);
|
2017-05-25 07:50:02 +02:00
|
|
|
|
2017-06-17 22:51:30 +02:00
|
|
|
io.on('connection', socket => {
|
2017-06-19 22:10:06 +02:00
|
|
|
logger.silly('a user connected via sockets');
|
2017-06-17 22:51:30 +02:00
|
|
|
// create visitor record
|
2017-06-19 18:37:35 +02:00
|
|
|
const visitor = ua(googleAnalyticsId, { https: true });
|
2017-06-17 22:51:30 +02:00
|
|
|
// attach upload listeners
|
2017-06-19 18:37:35 +02:00
|
|
|
const uploader = new siofu();
|
|
|
|
uploader.dir = hostedContentPath;
|
|
|
|
uploader.listen(socket);
|
2017-06-17 22:51:30 +02:00
|
|
|
uploader.on('start', ({ file }) => {
|
2017-06-20 05:22:23 +02:00
|
|
|
logger.info('client started an upload:', file.name);
|
2017-06-17 22:51:30 +02:00
|
|
|
// server side test to make sure file is not a bad file type
|
|
|
|
if (/\.exe$/.test(file.name)) {
|
2017-06-19 18:37:35 +02:00
|
|
|
uploader.abort(file.id, socket);
|
2017-06-17 22:51:30 +02:00
|
|
|
}
|
2017-06-19 18:37:35 +02:00
|
|
|
});
|
2017-06-17 22:51:30 +02:00
|
|
|
uploader.on('error', ({ error }) => {
|
2017-06-19 22:10:06 +02:00
|
|
|
logger.error('an error occured while uploading', error);
|
2017-06-19 18:37:35 +02:00
|
|
|
socket.emit('publish-status', error);
|
|
|
|
});
|
2017-06-17 22:51:30 +02:00
|
|
|
uploader.on('saved', ({ file }) => {
|
|
|
|
if (file.success) {
|
2017-06-20 05:22:23 +02:00
|
|
|
logger.debug(`Client successfully uploaded ${file.name}`);
|
2017-06-19 18:37:35 +02:00
|
|
|
socket.emit('publish-status', 'file upload successfully completed');
|
|
|
|
publishController.publish(file.meta.name, file.name, file.pathName, file.meta.type, file.meta.license, file.meta.nsfw, socket, visitor);
|
2017-06-17 22:51:30 +02:00
|
|
|
} else {
|
2017-06-19 22:10:06 +02:00
|
|
|
logger.error(`An error occurred in uploading the client's file`);
|
2017-06-19 18:37:35 +02:00
|
|
|
socket.emit('publish-failure', 'file uploaded, but with errors');
|
2017-06-19 22:10:06 +02:00
|
|
|
// to-do: remove the file if not done automatically
|
2017-06-17 22:51:30 +02:00
|
|
|
}
|
2017-06-19 18:37:35 +02:00
|
|
|
});
|
2017-06-17 22:51:30 +02:00
|
|
|
// handle disconnect
|
|
|
|
socket.on('disconnect', () => {
|
2017-06-19 22:10:06 +02:00
|
|
|
logger.silly('a user disconnected via sockets');
|
2017-06-19 18:37:35 +02:00
|
|
|
});
|
|
|
|
});
|
2017-06-17 22:51:30 +02:00
|
|
|
|
2017-06-19 18:37:35 +02:00
|
|
|
return http;
|
|
|
|
};
|