0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-29 13:22:40 +00:00

Merge branch 'master' into addLocalLogin-#269

This commit is contained in:
G.Ambatte
2022-04-13 14:30:02 +12:00
committed by GitHub
20 changed files with 795 additions and 480 deletions

View File

@@ -291,6 +291,7 @@ app.use((req, res)=>{
};
const props = {
version : require('./../package.json').version,
publicUrl : config.get('publicUrl') ?? '',
url : req.originalUrl,
brew : req.brew,
brews : req.brews,

View File

@@ -126,7 +126,8 @@ const GoogleActions = {
views : parseInt(file.properties.views),
tags : '',
published : file.properties.published ? file.properties.published == 'true' : false,
systems : []
systems : [],
thumbnail : file.properties.thumbnail
};
});
return brews;
@@ -147,7 +148,8 @@ const GoogleActions = {
renderer : brew.renderer,
tags : brew.tags,
pageCount : brew.pageCount,
systems : brew.systems.join()
systems : brew.systems.join(),
thumbnail : brew.thumbnail
}
},
media : {
@@ -180,12 +182,13 @@ const GoogleActions = {
'description' : `${brew.description}`,
'parents' : [folderId],
'properties' : { //AppProperties is not accessible
'shareId' : nanoid(12),
'editId' : nanoid(12),
'shareId' : brew.shareId || nanoid(12),
'editId' : brew.editId || nanoid(12),
'title' : brew.title,
'views' : '0',
'pageCount' : brew.pageCount,
'renderer' : brew.renderer || 'legacy'
'renderer' : brew.renderer || 'legacy',
'thumbnail' : brew.thumbnail || ''
}
};
@@ -286,6 +289,7 @@ const GoogleActions = {
views : parseInt(obj.data.properties.views) || 0, //brews with no view parameter will return undefined
version : parseInt(obj.data.properties.version) || 0,
renderer : obj.data.properties.renderer ? obj.data.properties.renderer : 'legacy',
thumbnail : obj.data.properties.thumbnail || '',
gDrive : true,
googleId : id

View File

@@ -5,6 +5,7 @@ const zlib = require('zlib');
const GoogleActions = require('./googleActions.js');
const Markdown = require('../shared/naturalcrit/markdown.js');
const yaml = require('js-yaml');
const asyncHandler = require('express-async-handler');
// const getTopBrews = (cb) => {
// HomebrewModel.find().sort({ views: -1 }).limit(5).exec(function(err, brews) {
@@ -41,154 +42,195 @@ const excludePropsFromUpdate = (brew)=>{
const propsToExclude = ['views', 'lastViewed'];
for (const prop of propsToExclude) {
delete brew[prop];
};
}
return brew;
};
const newBrew = (req, res)=>{
const brew = req.body;
const beforeNewSave = (account, brew)=>{
if(!brew.title) {
brew.title = getGoodBrewTitle(brew.text);
}
brew.authors = (req.account) ? [req.account.username] : [];
brew.authors = (account) ? [account.username] : [];
brew.text = mergeBrewText(brew);
};
delete brew.editId;
delete brew.shareId;
delete brew.googleId;
const newLocalBrew = async (brew)=>{
const newHomebrew = new HomebrewModel(brew);
// Compress brew text to binary before saving
newHomebrew.textBin = zlib.deflateRawSync(newHomebrew.text);
// Delete the non-binary text field since it's not needed anymore
newHomebrew.text = undefined;
newHomebrew.save((err, obj)=>{
if(err) {
console.error(err, err.toString(), err.stack);
return res.status(500).send(`Error while creating new brew, ${err.toString()}`);
}
obj = obj.toObject();
obj.gDrive = false;
return res.status(200).send(obj);
});
};
const updateBrew = (req, res)=>{
HomebrewModel.get({ editId: req.params.id })
.then((brew)=>{
const updateBrew = excludePropsFromUpdate(req.body);
brew = _.merge(brew, updateBrew);
brew.text = mergeBrewText(brew);
// Compress brew text to binary before saving
brew.textBin = zlib.deflateRawSync(brew.text);
// Delete the non-binary text field since it's not needed anymore
brew.text = undefined;
brew.updatedAt = new Date();
if(req.account) {
brew.authors = _.uniq(_.concat(brew.authors, req.account.username));
}
brew.markModified('authors');
brew.markModified('systems');
brew.save((err, obj)=>{
if(err) throw err;
return res.status(200).send(obj);
});
})
let saved = await newHomebrew.save()
.catch((err)=>{
console.error(err);
return res.status(500).send('Error while saving');
console.error(err, err.toString(), err.stack);
throw `Error while creating new brew, ${err.toString()}`;
});
saved = saved.toObject();
saved.gDrive = false;
return saved;
};
const deleteBrew = (req, res)=>{
HomebrewModel.find({ editId: req.params.id }, (err, objs)=>{
if(!objs.length || err) {
return res.status(404).send('Can not find homebrew with that id');
}
const newGoogleBrew = async (account, brew, res)=>{
const oAuth2Client = GoogleActions.authCheck(account, res);
const brew = objs[0];
if(req.account) {
// Remove current user as author
brew.authors = _.pull(brew.authors, req.account.username);
brew.markModified('authors');
}
if(brew.authors.length === 0) {
// Delete brew if there are no authors left
brew.remove((err)=>{
if(err) return res.status(500).send('Error while removing');
return res.status(200).send();
});
} else {
// Otherwise, save the brew with updated author list
brew.save((err, savedBrew)=>{
if(err) throw err;
return res.status(200).send(savedBrew);
});
}
});
return await GoogleActions.newGoogleBrew(oAuth2Client, brew);
};
const newGoogleBrew = async (req, res, next)=>{
let oAuth2Client;
try { oAuth2Client = GoogleActions.authCheck(req.account, res); } catch (err) { return res.status(err.status).send(err.message); }
const newBrew = async (req, res)=>{
const brew = req.body;
if(!brew.title) {
brew.title = getGoodBrewTitle(brew.text);
}
brew.authors = (req.account) ? [req.account.username] : [];
brew.text = mergeBrewText(brew);
const { transferToGoogle } = req.query;
delete brew.editId;
delete brew.shareId;
delete brew.googleId;
req.body = brew;
beforeNewSave(req.account, brew);
try {
const newBrew = await GoogleActions.newGoogleBrew(oAuth2Client, brew);
return res.status(200).send(newBrew);
} catch (err) {
return res.status(err.response.status).send(err);
let saved;
if(transferToGoogle) {
saved = await newGoogleBrew(req.account, brew, res)
.catch((err)=>{
res.status(err.status || err.response.status).send(err.message || err);
});
} else {
saved = await newLocalBrew(brew)
.catch((err)=>{
res.status(500).send(err);
});
}
if(!saved) return;
return res.status(200).send(saved);
};
const updateBrew = async (req, res)=>{
let brew = excludePropsFromUpdate(req.body);
const { transferToGoogle, transferFromGoogle } = req.query;
let saved;
if(brew.googleId && transferFromGoogle) {
beforeNewSave(req.account, brew);
saved = await newLocalBrew(brew)
.catch((err)=>{
console.error(err);
res.status(500).send(err);
});
if(!saved) return;
await deleteGoogleBrew(req.account, `${brew.googleId}${brew.editId}`, res)
.catch((err)=>{
console.error(err);
res.status(err.status || err.response.status).send(err.message || err);
});
} else if(!brew.googleId && transferToGoogle) {
saved = await newGoogleBrew(req.account, brew, res)
.catch((err)=>{
console.error(err);
res.status(err.status || err.response.status).send(err.message || err);
});
if(!saved) return;
await deleteLocalBrew(req.account, brew.editId)
.catch((err)=>{
console.error(err);
res.status(err.status).send(err.message);
});
} else if(brew.googleId) {
brew.text = mergeBrewText(brew);
saved = await GoogleActions.updateGoogleBrew(brew)
.catch((err)=>{
console.error(err);
res.status(err.response?.status || 500).send(err);
});
} else {
const dbBrew = await HomebrewModel.get({ editId: req.params.id })
.catch((err)=>{
console.error(err);
return res.status(500).send('Error while saving');
});
brew = _.merge(dbBrew, brew);
brew.text = mergeBrewText(brew);
// Compress brew text to binary before saving
brew.textBin = zlib.deflateRawSync(brew.text);
// Delete the non-binary text field since it's not needed anymore
brew.text = undefined;
brew.updatedAt = new Date();
if(req.account) {
brew.authors = _.uniq(_.concat(brew.authors, req.account.username));
}
brew.markModified('authors');
brew.markModified('systems');
saved = await brew.save();
}
if(!saved) return;
if(!res.headersSent) return res.status(200).send(saved);
};
const deleteBrew = async (req, res)=>{
if(req.params.id.length > 12) {
const deleted = await deleteGoogleBrew(req.account, req.params.id, res)
.catch((err)=>{
res.status(500).send(err);
});
if(deleted) return res.status(200).send();
} else {
const deleted = await deleteLocalBrew(req.account, req.params.id)
.catch((err)=>{
res.status(err.status).send(err.message);
});
if(deleted) return res.status(200).send(deleted);
return res.status(200).send();
}
};
const updateGoogleBrew = async (req, res, next)=>{
const brew = excludePropsFromUpdate(req.body);
brew.text = mergeBrewText(brew);
const deleteLocalBrew = async (account, id)=>{
const brew = await HomebrewModel.findOne({ editId: id });
if(!brew) {
throw { status: 404, message: 'Can not find homebrew with that id' };
}
try {
const updatedBrew = await GoogleActions.updateGoogleBrew(brew);
return res.status(200).send(updatedBrew);
} catch (err) {
return res.status(err.response?.status || 500).send(err);
if(account) {
// Remove current user as author
brew.authors = _.pull(brew.authors, account.username);
brew.markModified('authors');
}
if(brew.authors.length === 0) {
// Delete brew if there are no authors left
await brew.remove()
.catch((err)=>{
console.error(err);
throw { status: 500, message: 'Error while removing' };
});
} else {
// Otherwise, save the brew with updated author list
return await brew.save()
.catch((err)=>{
throw { status: 500, message: err };
});
}
};
router.post('/api', newBrew);
router.post('/api/newGoogle/', newGoogleBrew);
router.put('/api/:id', updateBrew);
router.put('/api/update/:id', updateBrew);
router.put('/api/updateGoogle/:id', updateGoogleBrew);
router.delete('/api/:id', deleteBrew);
router.get('/api/remove/:id', deleteBrew);
router.get('/api/removeGoogle/:id', async (req, res)=>{
const auth = await GoogleActions.authCheck(req.account, res);
await GoogleActions.deleteGoogleBrew(auth, req.params.id);
return res.status(200).send();
});
const deleteGoogleBrew = async (account, id, res)=>{
const auth = await GoogleActions.authCheck(account, res);
await GoogleActions.deleteGoogleBrew(auth, id);
return true;
};
router.post('/api', asyncHandler(newBrew));
router.put('/api/:id', asyncHandler(updateBrew));
router.put('/api/update/:id', asyncHandler(updateBrew));
router.delete('/api/:id', asyncHandler(deleteBrew));
router.get('/api/remove/:id', asyncHandler(deleteBrew));
module.exports = router;

View File

@@ -17,6 +17,7 @@ const HomebrewSchema = mongoose.Schema({
renderer : { type: String, default: '' },
authors : [String],
published : { type: Boolean, default: false },
thumbnail : { type: String, default: '' },
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date, default: Date.now },