spee.ch/routes/sockets-routes.js

65 lines
2.7 KiB
JavaScript
Raw Normal View History

const logger = require('winston');
const publishController = require('../controllers/publishController.js');
2017-06-26 19:43:35 +02:00
const publishHelpers = require('../helpers/libraries/publishHelpers.js');
const errorHandlers = require('../helpers/libraries/errorHandlers.js');
2017-06-28 08:04:47 +02:00
const { postToAnalytics } = require('../helpers/libraries/analytics');
module.exports = (app, siofu, hostedContentPath) => {
const http = require('http').Server(app);
const io = require('socket.io')(http);
2017-05-25 07:50:02 +02:00
io.on('connection', socket => {
logger.silly('a user connected via sockets');
// attach upload listeners
const uploader = new siofu();
uploader.dir = hostedContentPath;
uploader.listen(socket);
// listener for when file upload starts
uploader.on('start', ({ file }) => {
2017-06-20 05:22:23 +02:00
logger.info('client started an upload:', file.name);
// server side test to make sure file is not a bad file type
if (/\.exe$/.test(file.name)) {
uploader.abort(file.id, socket);
}
});
// listener for when file upload encounters an error
uploader.on('error', ({ error }) => {
logger.error('an error occured while uploading', error);
2017-06-28 07:41:48 +02:00
postToAnalytics('publish', '/', null, error);
socket.emit('publish-status', error);
});
// listener for when file has been uploaded
uploader.on('saved', ({ file }) => {
if (file.success) {
2017-06-20 05:22:23 +02:00
logger.debug(`Client successfully uploaded ${file.name}`);
socket.emit('publish-status', 'file upload successfully completed. Your image is being published (this might take a second)...');
// prepare the publish parameters
const publishParams = publishHelpers.createPublishParams(file.meta.name, file.pathName, file.meta.license, file.meta.nsfw);
// publish the file
publishController
.publish(publishParams, file.name, file.meta.type)
.then(result => {
2017-06-28 07:41:48 +02:00
postToAnalytics('publish', '/', null, 'success');
socket.emit('publish-complete', { name: publishParams.name, result });
})
.catch(error => {
2017-06-28 06:32:05 +02:00
error = errorHandlers.handlePublishError(error);
2017-06-28 07:41:48 +02:00
postToAnalytics('publish', '/', null, error);
2017-06-28 06:32:05 +02:00
socket.emit('publish-failure', error);
});
} else {
logger.error(`An error occurred in uploading the client's file`);
socket.emit('publish-failure', 'file uploaded, but with errors');
2017-06-28 07:41:48 +02:00
postToAnalytics('publish', '/', null, 'file uploaded, but with errors');
// to-do: remove the file if not done automatically
}
});
// handle disconnect
socket.on('disconnect', () => {
logger.silly('a user disconnected via sockets');
});
});
return http;
};