-
Notifications
You must be signed in to change notification settings - Fork 0
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
Closed
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b512efe
async parallel image upload
kherinwork 3c60bf5
async parallel image upload
kherinwork 2f9a942
pinging till image_id not null :in progress
kherinwork 1a3b439
minor refactoring
kherinwork fd32a28
refactoring: added function refineStruct
kherinwork b106a6f
refactoring: reduced function size
kherinwork 53f0a78
refactoring: reduced function size
kherinwork d48ac3b
refactoring: reduced function size
kherinwork 7fad741
Added async waterfall
kherinwork 752f55b
added setInterval
kherinwork File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
csv-jsons/ | ||
node_modules/ | ||
.env | ||
.env | ||
launch.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
|
@@ -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')); | ||
|
@@ -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({ | ||
|
@@ -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); | ||
|
@@ -83,7 +86,6 @@ app.post('/webhook', function (req, res) { | |
csvJson[externalId].webhookCompleted = true; | ||
jsonfile.writeFileSync(filepath, csvJson); | ||
} | ||
console.log('done'); | ||
}); | ||
} | ||
})(attribute) | ||
|
@@ -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); | ||
let csvJsonId = date.getFullYear()+'-'+month+'-'+utcdate+'-'+date.getHours()+date.getMinutes()+date.getSeconds(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 () { | ||
|
||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
espaces en plus