Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async parallel image upload #1

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
csv-jsons/
node_modules/
.env
.env
launch.json
112 changes: 38 additions & 74 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const Sharinpix = require('sharinpix');
Sharinpix.configure(process.env.SHARINPIX_URL);
const sharinpixInstance = Sharinpix.get_instance();
const express = require('express');
const app = express();

if (app.settings.env === 'development') {
require('dotenv').config();
}
const bodyParser = require('body-parser');
const parseCsvImages = require('./lib/parse-csv-images');
const parseCsv = require('./lib/csv-upload');
const fileUpload = require('express-fileupload');
const Stream = require('stream');
const unirest = require('unirest');
Expand All @@ -14,14 +19,14 @@ const uuidV4 = require('uuid/v4');
const fs = require('fs');
const jsonfile = require('jsonfile');
const morgan = require('morgan');
const date = new Date();

app.set('json spaces', 3);

// For Content-Type: application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
// For Content-Type: application/json

app.use(bodyParser.json());
app.use(fileUpload());
app.use(morgan(':remote-addr | :method :url :status :res[content-length] bytes - :response-time ms'));
Expand All @@ -31,6 +36,7 @@ app.get('/', function(req, res) {
});

app.post('/webhook', function (req, res) {
return;
let payload = JSON.parse(req.body.p);
if (!payload.metadatas || !payload.metadatas.filepath || !payload.metadatas.externalId) {
return res.send({
Expand All @@ -50,10 +56,7 @@ app.post('/webhook', function (req, res) {
einstein_box: true
}
};
let token = jwt.sign({
abilities: abilities,
iss: process.env.SHARINPIX_SECRET_ID
}, process.env.SHARINPIX_SECRET);

jsonfile.readFile(filepath, function(err, images) {
let image = images[externalId];
let imageAttributesPair = _.pairs(image.otherAttributes);
Expand Down Expand Up @@ -83,7 +86,6 @@ app.post('/webhook', function (req, res) {
csvJson[externalId].webhookCompleted = true;
jsonfile.writeFileSync(filepath, csvJson);
}
console.log('done');
});
}
})(attribute)
Expand All @@ -100,85 +102,47 @@ app.post('/webhook', function (req, res) {
app.post('/upload-csv', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');

// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let csvFile = req.files.csvFile;
let albumId = req.body.albumId;

let bufferStream = new Stream.PassThrough();
bufferStream.end(csvFile.data);
let csvJsonId = uuidV4();
let outputFilePath = `${__dirname}/csv-jsons/${csvJsonId}.csv`;
let utcdate = ("0" + date.getUTCDate()).slice(-2);
let month = ("0" + date.getMonth()).slice(-2);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

espaces en plus

let csvJsonId = date.getFullYear()+'-'+month+'-'+utcdate+'-'+date.getHours()+date.getMinutes()+date.getSeconds();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

manque d'espaces

let outputFilePath = `${__dirname}/csv-jsons/${csvJsonId}.json`;
if (!fs.existsSync(`${__dirname}/csv-jsons`)) {
fs.mkdirSync(`${__dirname}/csv-jsons`);
}
parseCsvImages(bufferStream, outputFilePath, function(imagesHash) {
let images = _.map(imagesHash, function(image, externalId) {
image['externalId'] = externalId;
return image;
});
process.exit;
let abilities = {};
abilities[albumId] = {
Access: {
see: true,
image_upload: true
}
};
let token = jwt.sign({
abilities: abilities,
iss: process.env.SHARINPIX_SECRET_ID
}, process.env.SHARINPIX_SECRET);
images.forEach(function(image) {
unirest.post('https://' + process.env.ENDPOINT_DOMAIN + '/api/v1/imports').headers({
'Content-Type': 'application/json',
'Authorization': 'Token token="' + token + '"'
}).send({
album_id: albumId,
filename: image.name,
url: image.url,
import_type: 'url',
metadatas: {
externalId: image.externalId,
filepath: outputFilePath
}
}).end(function (response) {
let csvJson = jsonfile.readFileSync(outputFilePath);
csvJson[image.externalId].sentForUpload = true;
jsonfile.writeFileSync(outputFilePath, csvJson);
console.log('Image `' + image.name + '` sent for import.');
});
})
})
res.redirect(`/status/${csvJsonId}`);
parseCsv(albumId, bufferStream, outputFilePath, sharinpixInstance);
res.redirect(`/`);
});

app.get('/status/:csvJsonId', function(req, res) {
let csvJsonId = req.params.csvJsonId;
if (fs.existsSync(`${__dirname}/csv-jsons/${csvJsonId}.csv`)) {
let csvJson = jsonfile.readFileSync(`${__dirname}/csv-jsons/${csvJsonId}.csv`);
let csvJsonPairs = _.pairs(csvJson);
let response = {};
for (let csvJsonPair of csvJsonPairs) {
response[csvJsonPair[1].name] = {
sentForUpload: csvJsonPair[1].sentForUpload ? true : false,
webhookCompleted: csvJsonPair[1].webhookCompleted ? true : false
}
}
res.json(response);
} else {
res.json({
success: false,
message: 'File does not exists'
});
}
});
// app.get('/status/:csvJsonId', function(req, res) {
// let csvJsonId = req.params.csvJsonId;
// if (fs.existsSync(`${__dirname}/csv-jsons/${csvJsonId}.json`)) {
// let csvJson = jsonfile.readFileSync(`${__dirname}/csv-jsons/${csvJsonId}.json`);
// let csvJsonPairs = _.pairs(csvJson);
// let response = {};
// for (let csvJsonPair of csvJsonPairs) {
// response[csvJsonPair[1].name] = {
// sentForUpload: csvJsonPair[1].sentForUpload ? true : false,
// webhookCompleted: csvJsonPair[1].webhookCompleted ? true : false
// }
// }
// res.json(response);
// } else {
// res.json({
// success: false,
// message: 'File does not exists'
// });
// }
// });

app.use(function(req, res) {
res.status(404);
res.send('404 - Not found');
});

app.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}`);
});
app.listen(process.env.PORT, function () {

});
110 changes: 110 additions & 0 deletions lib/csv-upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const parseCsvImages = require('./parse-csv-images');
const _ = require('lodash');
const Sharinpix = require('sharinpix');
const async = require('async');

module.exports = function(albumId, bufferStream, outputFilePath, sharinpixInstance){
this.sharinpixInstance = sharinpixInstance;
parseCsvImages(bufferStream, outputFilePath, function(imagesHash) {
let imagesBoxHash = imagesHash;
let images = _.map(imagesHash, function(image, externalId) {
image['externalId'] = externalId;
image = (({ url, name, externalId }) => ({ url, name, externalId }))(image);
return image;
});
var imagesBox = _.map(imagesBoxHash, function(image, externalId){
externalId = externalId.toString();
image = (({ otherAttributes }) => ({ externalId, otherAttributes }))(image);
return image;
});
var imagesBoxObject = _.keyBy(imagesBox, 'externalId');
let abilities = {};
abilities[albumId] = {
Access: {
see: true,
image_upload: true
}
};
let claims = {
abilities: abilities
};
parallelTasks = [];
_.each(images,function(image) {
let body = {
album_id: albumId,
filename: image.name,
url: image.url,
import_type: 'url',
metadatas: {
externalId: image.externalId,
filepath: outputFilePath
}
};
parallelTasks.push(
function(){
async.waterfall(
[
function(callback){
sharinpixInstance.post('/imports', body, claims).then (
(res) => {
callback(null, { id: res.id, image_id: image.externalId });
},
(err) => {
callback(body, null);

});
},
function createBox(results, callback){
_.each(results, function(imageImport){
setTimeout(function() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setTimeout fires only once!!!

sharinpixInstance.get(`/imports/${imageImport.id}`, {admin: true}).then(
(res) => {
let imgId = res.id;
let extId = imageImport.image_id;
let einsteinBoxes = refineStruct(imagesBoxObject[extId]);
_.each(einsteinBoxes, (item) => {
sharinpixInstance.post(`/images/${imgId}/einstein_box`, item, {admin: true}).then(
(res) => {
},
(err) => {
}
);
});
if (res.id != null){
clearTimeout(this);
}
callback(null, 'done');
},
(err) => {
callback('err', null);
}
)
}, 5000);
});
}
], function(err, result){
}
)
}
);
});
async.parallelLimit(parallelTasks, 5, function(err, results){
if(results !== null && results.length > 0){
}
if(err !== null && err.size > 0){
writeErrorLog(err);
}
});
function writeErrorLog(err){
}
function refineStruct(element){
element = (({otherAttributes}) => ({otherAttributes}))(element);
let imagesBoxFlat = _.values(_.values(element));
let einsteinBoxes = _.map(imagesBoxFlat, (item) => {
item = _.values(item);
return item.splice(2, item.length);
});
return _.flatten(einsteinBoxes);
}
});
}
4 changes: 2 additions & 2 deletions lib/parse-csv-images.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module.exports = function(inputFile, outputFilePath, callback) {
}
}
if (externalIdColumnIndex === -1) {
csvRows.push(['external_id'].concat(data))
csvRows.push(data.concat(['external_id']));
} else {
csvRows.push(data)
}
Expand Down Expand Up @@ -67,7 +67,7 @@ module.exports = function(inputFile, outputFilePath, callback) {
otherAttributes[columnName] = otherAttribute;
}
if (externalIdColumnIndex === -1) {
csvRows.push([externalId].concat(data));
csvRows.push(data.concat([externalId]));
} else {
csvRows.push(data)
}
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.5.0",
"body-parser": "^1.17.2",
"dotenv": "^4.0.0",
"express": "^4.15.4",
"express-fileupload": "^0.1.4",
"fast-csv": "^2.4.0",
"jsonfile": "^3.0.1",
"jsonwebtoken": "^7.4.3",
"lodash": "^4.17.4",
"morgan": "^1.8.2",
"sharinpix": "0.0.6",
"underscore": "^1.8.3",
"unirest": "^0.5.1",
"uuid": "^3.1.0"
Expand Down
9 changes: 9 additions & 0 deletions performance.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Test#1
===================
OLD WAY
-------------------
1. Name: road.jpg
2. Size: 1101.kb
3. No. of boxes: 13
4. response time: 3s
4. No. image(s) : 1
2 changes: 1 addition & 1 deletion views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ <h1>Upload Einstein CSV</h1>
<fieldset>
<legend>Einstein CSV File Upload</legend>
<label for="albumId">Album ID</label><br />
<input type="text" id="albumId" name="albumId" /><br />
<input type="text" id="albumId" name="albumId" value="003240000046yLAWWW" /><br />
<label for="csvFile">CSV File</label><br />
<input name="csvFile" id="csvFile" type="file" />
</fieldset>
Expand Down