Skip to content
This repository has been archived by the owner on Sep 19, 2021. It is now read-only.

Commit

Permalink
release v1 api and refactor images into 3 types #3
Browse files Browse the repository at this point in the history
  • Loading branch information
mshd committed Sep 26, 2020
1 parent 1e5a69c commit b5e4a09
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 22 deletions.
8 changes: 7 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');

const upload = multer({ dest: path.join(__dirname, 'uploads') });
const upload = multer({ dest: path.join(__dirname, 'uploads/original') });

// var storage = multer.diskStorage({
// destination: function (req, file, cb) {
Expand Down Expand Up @@ -227,6 +227,12 @@ app.get('/api/getImageById/:id(\\d+)',imageController.showImageById);
app.get('/api/getImage/:id(\\d+)', imageController.showImageByWikidata);
app.get('/api/image/info/:id(\\d+)', imageController.imageInfo);

const v1ImageController = require('./controllers/api/v1image');

app.get('/api/v1/image/:type/id/:id(\\d+)', v1ImageController.showImageById);
app.get('/api/v1/image/:type/wikidata/:id(\\d+)' , v1ImageController.showImageByWikidata);
app.get('/api/v1/image/info/wikidata/:id(\\d+)' , v1ImageController.imageInfo);

// app.route('/images')
// .get(imageController.getBooks)
// .post(imageController.createBooks)
Expand Down
45 changes: 45 additions & 0 deletions controllers/api/v1image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* VERSION 1 of the API
* 2020 October
* do not make big changes
*/
const ImageModel = require('../../models/Image');
const path = require('path');

exports.showImageByWikidata = async (req, res) => {
const { id, type } = req.params;
// if (!Number.isInteger(id)) { //already checked at app.js
// res.json({ error: 'Only numbers allowed' });
// }
const allowedTypes = ['thumbnail','facecrop','original'];
if (allowedTypes.indexOf(type) === -1){
res.json({ error: true, errorMessage: 'Type not allowed' });
}
const image = await ImageModel.find({ wikidataEntity: id }, null, { sort: { name: 1 }, limit: 1 });
if (!image.length) {
res.sendStatus(404);
// res.json({ error: 404 });
}
if ( !image[0].mimetype) {
res.json({ error: true, errorMessage: 'mimetype', entry: image });
}

await ImageModel.updateOne( {_id:image[0]._id} , {viewCount:(image[0].viewCount+1)} );

res.setHeader('content-type', image[0].mimetype);
res.sendFile(path.resolve('uploads/'+type+'/' + image[0].id));
};

exports.showImageById = async (req, res) => {
const { id, type } = req.params;
res.setHeader('content-type', "image/jpeg");
res.sendFile(path.resolve('uploads/'+type+'/' + id));
};


exports.imageInfo = async (req, res) => {
const { id } = req.params;
const image = await ImageModel.find({ wikidataEntity: id }, null, { sort: { name: 1 }, limit: 1 });
res.setHeader('Access-Control-Allow-Origin', '*');
res.json({images:image});
};
16 changes: 9 additions & 7 deletions controllers/image.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/**
* GET /images
* List all images.
*/
const ImageModel = require('../models/Image');
const fs = require('fs');
const path = require('path');

/**
* GET /images
* List all images.
*/
exports.getImages = (req, res) => {
ImageModel
.find()
.find({uploadSite: req.hostname})
.populate('createdBy')
.exec((err, docs) => {
res.render('image/list', { images: docs });
Expand All @@ -25,9 +25,11 @@ exports.deleteImage = (req, res) => {
}else{
req.flash('success', { msg: 'Entry has been deleted.' });
try {
fs.unlinkSync('uploads/' + id);
fs.unlinkSync('uploads/thumbnails/' + id);
fs.unlinkSync('uploads/original/' + id);
fs.unlinkSync('uploads/thumbnail/' + id);
fs.unlinkSync('uploads/facecrop/' + id);
}catch (e) {
console.log(e);
req.flash('errors', { msg: 'Some images (Id:'+id+') couldn\'t be deleted' });
}
}
Expand Down
21 changes: 14 additions & 7 deletions controllers/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,18 @@ function applySmartCrop(src, dest, width, height) {



async function createThumbnail(filename){
//applySmartCrop('uploads/' + filename, 'uploads/thumbnails/' + filename, 200, 200);
await facecrop(`./uploads/${filename}`, `./uploads/thumbnails/${filename}`,"image/jpeg", 0.5);
async function createThumbnail(filename,filetype='image/jpeg'){

try {
applySmartCrop('uploads/original/' + filename, 'uploads/thumbnail/' + filename, 200, 200);

await facecrop(`./uploads/original/${filename}`, `./uploads/facecrop/${filename}`,filetype, 0.9);
}catch (e) {
req.flash('errors', { msg: 'Facecrop failed.' });
// console.log(e);
}
// console.log('Create thumb: uploads/' + filename);
// sharp('uploads/cropped/' + filename).resize(200).toFile('uploads/thumbnails/' + filename, (err, resizeImage) => {
// sharp('uploads/cropped/' + filename).resize(200).toFile('uploads/thumbnail/' + filename, (err, resizeImage) => {
// if (err) {
// console.log(err);
// } else {
Expand Down Expand Up @@ -210,7 +216,7 @@ exports.handleSourceUrl = async (req, res, next) => {
if (req.body.sourceUrl) {
try {
const file = getRandomFilename();
await download(req.body.sourceUrl, "uploads/" + file);
await download(req.body.sourceUrl, "uploads/original/" + file);
res.savedUrl = file;
next();
} catch (err){
Expand All @@ -233,6 +239,7 @@ function errorOnlyImages(){

exports.postFileUpload = async (req, res, next) => {
const wikidataId = req.body.wikidataEntityId;
// console.log(req.body);
if (!isEntityId(wikidataId)) {
req.flash('errors', { msg: 'The Entity ID ' + wikidataId + ' is invalid.' });
res.redirect('/image/single_upload');
Expand Down Expand Up @@ -265,12 +272,12 @@ exports.postFileUpload = async (req, res, next) => {

var savedImage = await image.save();

fs.rename('uploads/' + imageDetails.internalFileName, 'uploads/' +savedImage.id, function (err) {
fs.rename('uploads/original/' + imageDetails.internalFileName, 'uploads/original/' +savedImage.id, function (err) {
if (err) throw err;
console.log('Successfully renamed - AKA moved!')
});

createThumbnail(savedImage.id);
createThumbnail(savedImage.id,imageDetails.mimetype);

const wikidataLink = wdk.getSitelinkUrl({ site: 'wikidata', title: wikidataId });
req.flash('success', { msg: `File was uploaded successfully. Photo of ${label} was saved and entered into the Database.` });
Expand Down
File renamed without changes.
Empty file added uploads/original/empty.txt
Empty file.
Empty file added uploads/thumbnail/empty.txt
Empty file.
9 changes: 7 additions & 2 deletions views/image/list.pug
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ block content
table(style='width:100%')
tr
th Image
th Count
th Face
th Wikidata Id
th Wikidata Label
th Type
Expand All @@ -21,7 +21,12 @@ block content
tr
td
if image.wikidataEntity
img(src='/api/getImageById/' + image.id, style='max-height:30px' )
img(src='/api/v1/image/thumbnail/id/' + image.id, style='max-height:30px' )
else
span Image
td
if image.wikidataEntity
img(src='/api/v1/image/facecrop/id/' + image.id, style='max-height:30px' )
else
span Image
td=image.viewCount
Expand Down
13 changes: 8 additions & 5 deletions views/image/upload.pug
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@ block content
//h3 File Upload Form
.row
.col-md-6
p All files will be uploaded to "/uploads" directory and entered.
p All files will be uploaded to "/uploads" directory and entered. Please either Upload a file OR select the URL.
form(role='form', enctype='multipart/form-data', method='POST')
input(type='hidden', name='_csrf', value=_csrf)
.form-group
label.col-form-label.font-weight-bold Name
.col-md-6
input(type='text', name='name')
label.col-form-label.font-weight-bold Wikidata ID
.col-md-6
input(type='text', name='wikidataEntity', class='wikidata-searchbox', value=query.qLabel, required)
Expand All @@ -32,7 +29,13 @@ block content
label.col-form-label.font-weight-bold File Input (optional)
.col-md-6
input(type='file', name='myFile', accept='image/*')
label.col-form-label.font-weight-bold File URL
label.col-form-label.font-weight-bold File URL (optional)
.col-md-6
input(type='text', name='sourceUrl')
label.col-form-label.font-weight-bold Comment (optional)
.col-md-6
input(type='text', name='comment')
label.col-form-label.font-weight-bold Recorded date (optional)
.col-md-6
input(type='date', name='recordedDate')
button.btn.btn-primary(type='submit') Submit

0 comments on commit b5e4a09

Please sign in to comment.