images.controllers.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /** logic for image routes */
  2. import multer from 'multer';
  3. import Image from "../models/image.model.js";
  4. import { v2 as cloudinary } from 'cloudinary';
  5. import dotenv from 'dotenv';
  6. import path from 'path';
  7. import DatauriParser from 'datauri/parser.js';
  8. dotenv.config();
  9. const dUri = new DatauriParser();
  10. const dataUri = req => dUri.format(path.extname(req.file.originalname).toString(), req.file.buffer);
  11. cloudinary.config({
  12. cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  13. api_key: process.env.CLOUDINARY_API_KEY,
  14. api_secret: process.env.CLOUDINARY_API_SECRET,
  15. });
  16. const storage = multer.memoryStorage();
  17. /*
  18. const imageFileFilter = (req, file, cb) => {
  19. console.log("File in filter", file);
  20. if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
  21. cb(null, true);
  22. } else {
  23. cb(null, false);
  24. }
  25. }*/
  26. export const upload = multer({
  27. storage: storage,
  28. limits: {
  29. // Allow upload files under 10MB
  30. fileSize: 10485760,
  31. },
  32. // fileFilter: imageFileFilter,
  33. });
  34. export const uploadSingleImage = async (req, res) => {
  35. const image = dataUri(req).content;
  36. const { category, categoryId, tags, name } = req.body;
  37. const folderName = category && categoryId ? category + '/' + categoryId : req.params.folder;
  38. const uploadOptions = {
  39. folder: folderName,
  40. tags: tags || [],
  41. };
  42. if (category === 'userProfile') {
  43. uploadOptions.folder = category;
  44. uploadOptions.public_id = categoryId;
  45. uploadOptions.overwrite = true;
  46. uploadOptions.transformation = { aspect_ratio: 1, gravity: "faces", crop: "fill" };
  47. }
  48. cloudinary.uploader.upload(image, uploadOptions).then((cloudinaryImage) => {
  49. // console.log('upload successful');
  50. const { public_id, secure_url, url } = cloudinaryImage;
  51. const newImage = new Image({
  52. categoryName: category,
  53. categoryId,
  54. url: secure_url || url,
  55. cloudinaryPublicId: public_id,
  56. name,
  57. });
  58. try {
  59. // try to delete an already existing profile picture since it just gets replaced on cloudinary and then save the new one
  60. Image.findOneAndDelete({categoryName: 'userProfile', cloudinaryPublicId: public_id}).then((deletedImaged) => {
  61. // console.log('replaced', deletedImaged, 'with', newImage);
  62. newImage.save().then(() => {
  63. // console.log('added image to ' + folderName, public_id, name);
  64. res.status(201).json({ 'message': 'successfully added new Image', 'Image': newImage })
  65. });
  66. });
  67. } catch (error) {
  68. res.status(409).json({ message: error.message, errorDetails: 'upload successful, but database storage failed' });
  69. }
  70. }).catch((error) => {
  71. res.status(409).json({ message: error.message, errorDetails: 'upload failed', errorMessage: error.message });
  72. });
  73. }
  74. async function copySingleImage(image, category, newId) {
  75. let returnImage = null;
  76. const folder = category + '/' + newId;
  77. if (image.url) {
  78. await cloudinary.uploader.upload(image.url, { folder: folder }).then(async (cloudinaryImage) => {
  79. // console.log('upload successful');
  80. const { public_id, secure_url, url } = cloudinaryImage;
  81. const newImage = new Image({
  82. categoryName: category,
  83. categoryId: newId,
  84. url: secure_url || url,
  85. cloudinaryPublicId: public_id,
  86. name: image.name,
  87. });
  88. await newImage.save().then((savedImage) => {
  89. returnImage = savedImage;
  90. }).catch((error) => {
  91. console.log('upload of copied image successful, but database storage failed', 'error:', error.message);
  92. });
  93. }).catch((error) => {
  94. console.log('image upload failed because ', error);
  95. });
  96. }
  97. return returnImage;
  98. }
  99. export const copyImagesForCategory = async (req, res) => {
  100. let { category, oldId, newId } = req.params;
  101. let newImages = [];
  102. await Image.find({ categoryName: category, categoryId: oldId }, async function (err, foundImages) {
  103. if (err) {
  104. // console.log('error in find', err);
  105. } else {
  106. if (foundImages && foundImages.length > 0) {
  107. newImages = await Promise.all(foundImages.map(async (i) => {
  108. return await copySingleImage(i, 'mealImages', newId)
  109. }));
  110. if (newImages.length > 0) {
  111. res.status(201).json({ 'message': 'successfully copied Images', newImages });
  112. } else {
  113. res.status(400).json({ 'info': `copying images failed. Check log for more info` });
  114. }
  115. } else {
  116. res.status(200).json({ 'message': 'no images had to be copied' });
  117. }
  118. }
  119. });
  120. }
  121. export const deleteSingleImage = async (req, res) => {
  122. const image = req.body;
  123. Image.findByIdAndDelete(image._id, {}, function (err, deletionResult) {
  124. if (err) {
  125. res.status(400).json({ 'info': `Deletion of image ${image._id} failed`, 'message': err.message });
  126. } else {
  127. cloudinary.uploader.destroy(image.cloudinaryPublicId).then((result) => {
  128. res.status(201).json({ 'info': 'image deleted', deletionResult, cloudinaryResult: result });
  129. }).catch(error => {
  130. console.log('image deleted from database but not from cloudinary: ', image, 'reason', error);
  131. res.status(201).json({ 'info': 'image deleted from database but not from cloudinary', 'cloudinaryError': error });
  132. });
  133. }
  134. });
  135. }
  136. export const deleteAllImagesFromCategory = async (req, res) => {
  137. let category = req.params.category;
  138. let id = req.params.id;
  139. // console.log('delete all images from ', category, id);
  140. await Image.find({ categoryName: category, categoryId: id }, async function (err, foundImages) {
  141. if (err) {
  142. // console.log('error in find', err);
  143. } else {
  144. await Promise.all(foundImages.map(async (i) => {
  145. await cloudinary.uploader.destroy(i.cloudinaryPublicId).catch(error => {
  146. console.log('deletion of ' + i.name + ' from cloudinary failed because', error);
  147. });
  148. }));
  149. const folder = category + '/' + id;
  150. cloudinary.api.delete_folder(folder).catch(err => {
  151. console.log('error on delete folder', err);
  152. }).finally(() => {
  153. Image.deleteMany({ categoryName: category, categoryId: id }, {}, function (err, deletionResult) {
  154. if (err) {
  155. res.status(400).json({ 'info': `Deletion of images from ${category} ${id} failed`, 'message': err.message });
  156. } else {
  157. res.status(201).json({ 'info': `images from ${category} with ${id} deleted`, deletionResult });
  158. }
  159. });
  160. });
  161. }
  162. });
  163. }
  164. export const deleteAllImagesFromCategoryInternally = async (category, categoryId) => {
  165. await Image.find({ categoryName: category, categoryId: categoryId }, async function (err, foundImages) {
  166. if (err) {
  167. console.log('error in find', err);
  168. } else {
  169. await Promise.all(foundImages.map(async (i) => {
  170. await cloudinary.uploader.destroy(i.cloudinaryPublicId).catch(error => {
  171. console.log('deletion of ' + i.name + ' from cloudinary failed because', error);
  172. });
  173. }));
  174. const folder = category + '/' + categoryId;
  175. console.log('trying to delete folder ' + folder);
  176. cloudinary.api.delete_folder(folder).catch(err => {
  177. console.log('error on delete folder', err);
  178. }).finally(() => {
  179. Image.deleteMany({ categoryName: category, categoryId: categoryId }, {}, function (err, deletionResult) {
  180. if (err) {
  181. console.log(`Deletion of images from ${category} ${categoryId} failed`, err.message);
  182. } else {
  183. console.log(deletionResult.n + ` images from ${category} with ${categoryId} deleted`);
  184. }
  185. });
  186. });
  187. }
  188. });
  189. }