Finished guestbook and gallery. started diary

This commit is contained in:
Torsten Schulz
2024-09-27 07:40:06 +02:00
parent a2ee66c9de
commit c31be3f879
34 changed files with 2298 additions and 185 deletions

View File

@@ -11,10 +11,17 @@ import Image from '../models/community/image.js';
import ImageVisibilityType from '../models/type/image_visibility.js';
import FolderImageVisibility from '../models/community/folder_image_visibility.js';
import ImageImageVisibility from '../models/community/image_image_visibility.js';
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs';
import fsPromises from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import FolderVisibilityUser from '../models/community/folder_visibility_user.js';
import ImageVisibilityUser from '../models/community/image_visibility_user.js';
import GuestbookEntry from '../models/community/guestbook.js';
import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';
import sharp from 'sharp';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -33,22 +40,39 @@ class SocialNetworkService extends BaseService {
return this.constructUserProfile(user, requestingUserId);
}
async createFolder(hashedUserId, data) {
async createFolder(hashedUserId, data, folderId) {
await this.checkUserAccess(hashedUserId);
const user = await User.findOne({
hashedId: hashedUserId
where: { hashedId: hashedUserId }
});
const parentFolder = Folder.findOne({
id: data.parentId,
userId: user.id
});
if (!parentFolder) {
throw new Error('foldernotfound');
if (!user) {
throw new Error('User not found');
}
const newFolder = await Folder.create({
parentId: data.parentId,
userId: user.id,
name: data.name
const parentFolder = data.parentId ? await Folder.findOne({
where: { id: data.parentId, userId: user.id }
}) : null;
if (data.parentId && !parentFolder) {
throw new Error('Parent folder not found');
}
let newFolder;
if (folderId === 0) {
newFolder = await Folder.create({
parentId: data.parentId || null,
userId: user.id,
name: data.name
});
} else {
newFolder = await Folder.findOne({
where: { id: folderId, userId: user.id }
});
if (!newFolder) {
throw new Error('Folder not found or user does not own the folder');
}
newFolder.name = data.name;
await newFolder.save();
}
await FolderImageVisibility.destroy({
where: { folderId: newFolder.id }
});
for (const visibilityId of data.visibilities) {
await FolderImageVisibility.create({
@@ -61,32 +85,63 @@ class SocialNetworkService extends BaseService {
async getFolders(hashedId) {
const userId = await this.checkUserAccess(hashedId);
let rootFolder = await Folder.findOne({ where: { parentId: null, userId } });
let rootFolder = await Folder.findOne({
where: { parentId: null, userId },
include: [{
model: ImageVisibilityType,
through: { model: FolderImageVisibility },
attributes: ['id'],
}]
});
if (!rootFolder) {
const user = await User.findOne({ where: { id: userId } });
const visibility = await ImageVisibilityType.findOne({
where: {
description: 'everyone'
}
where: { description: 'everyone' }
});
rootFolder = await Folder.create({
name: user.username,
parentId: null,
userId,
userId
});
await FolderImageVisibility.create({
folderId: rootFolder.id,
visibilityTypeId: visibility.id
});
rootFolder = await Folder.findOne({
where: { id: rootFolder.id },
include: [{
model: ImageVisibilityType,
through: { model: FolderImageVisibility },
attributes: ['id'],
}]
});
}
const children = await this.getSubFolders(rootFolder.id, userId);
rootFolder = rootFolder.get();
rootFolder = rootFolder.get();
rootFolder.visibilityTypeIds = rootFolder.image_visibility_types.map(v => v.id);
delete rootFolder.image_visibility_types;
rootFolder.children = children;
return rootFolder;
}
async getSubFolders(parentId, userId) {
const folders = await Folder.findAll({ where: { parentId, userId } });
const folders = await Folder.findAll({
where: { parentId, userId },
include: [{
model: ImageVisibilityType,
through: { model: FolderImageVisibility },
attributes: ['id'],
}],
order: [
['name', 'asc']
]
});
for (const folder of folders) {
const children = await this.getSubFolders(folder.id, userId);
const visibilityTypeIds = folder.image_visibility_types.map(v => v.id);
folder.setDataValue('visibilityTypeIds', visibilityTypeIds);
folder.setDataValue('children', children);
folder.setDataValue('image_visibility_types', undefined);
}
return folders.map(folder => folder.get());
}
@@ -112,32 +167,56 @@ class SocialNetworkService extends BaseService {
async uploadImage(hashedId, file, formData) {
const userId = await this.getUserId(hashedId);
const newFileName = this.generateUniqueFileName(file.originalname);
const filePath = this.buildFilePath(newFileName);
await this.saveFile(file.buffer, filePath);
const newImage = await this.createImageRecord(formData, userId, file, newFileName);
const processedImageName = await this.processAndUploadUserImage(file);
const newImage = await this.createImageRecord(formData, userId, file, processedImageName);
await this.saveImageVisibilities(newImage.id, formData.visibility);
return newImage;
}
async processAndUploadUserImage(file) {
try {
const img = sharp(file.buffer);
const metadata = await img.metadata();
if (!metadata || !['jpeg', 'png', 'webp', 'gif'].includes(metadata.format)) {
throw new Error('File is not a valid image');
}
if (metadata.width < 75 || metadata.height < 75) {
throw new Error('Image dimensions are too small. Minimum size is 75x75 pixels.');
}
const resizedImg = img.resize({
width: Math.min(metadata.width, 500),
height: Math.min(metadata.height, 500),
fit: sharp.fit.inside,
withoutEnlargement: true
});
const newFileName = this.generateUniqueFileName(file.originalname);
const filePath = this.buildFilePath(newFileName, 'user');
await resizedImg.toFile(filePath);
return newFileName;
} catch (error) {
throw new Error(`Failed to process image: ${error.message}`);
}
}
async getUserId(hashedId) {
return await this.checkUserAccess(hashedId);
}
generateUniqueFileName(originalFileName) {
const uniqueHash = uuidv4();
return `${uniqueHash}`;
return uniqueHash;
}
buildFilePath(fileName) {
const userImagesPath = path.join(__dirname, '../images/user');
return path.join(userImagesPath, fileName);
buildFilePath(fileName, type) {
const basePath = path.join(__dirname, '..', 'images', type);
return path.join(basePath, fileName);
}
async saveFile(buffer, filePath) {
try {
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, buffer);
await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
await fsPromises.writeFile(filePath, buffer);
} catch (error) {
throw new Error(`Failed to save file: ${error.message}`);
}
@@ -273,9 +352,15 @@ class SocialNetworkService extends BaseService {
});
}
async constructUserProfile(user, requestingUserId) {
async constructUserProfile(user, hashedUserId) {
const userParams = {};
const requestingUserAge = await this.getUserAge(requestingUserId);
const requestingUser = await User.findOne({
where: { hashedId: hashedUserId },
});
if (!requestingUser) {
throw new Error('User not found');
}
const requestingUserAge = await this.getUserAge(requestingUser.id);
for (const param of user.user_params) {
const visibility = param.param_visibilities?.[0]?.visibility_type?.description || 'Invisible';
if (visibility === 'Invisible') continue;
@@ -340,9 +425,9 @@ class SocialNetworkService extends BaseService {
if (!hasAccess) {
throw new Error('Access denied');
}
const imagePath = this.buildFilePath(image.hash);
const imagePath = this.buildFilePath(image.hash, 'user');
if (!fs.existsSync(imagePath)) {
throw new Error('File not found');
throw new Error(`File "${imagePath}" not found`);
}
return imagePath;
}
@@ -350,7 +435,7 @@ class SocialNetworkService extends BaseService {
async checkUserImageAccess(userId, imageId) {
const image = await Image.findByPk(imageId);
if (image.userId === userId) {
return true;
return true;
}
const accessRules = await ImageImageVisibility.findAll({
where: { imageId }
@@ -374,6 +459,258 @@ class SocialNetworkService extends BaseService {
}
return image.folderId;
}
async getFoldersByUsername(username, hashedUserId) {
const user = await User.findOne({ where: { username } });
if (!user) {
throw new Error('User not found');
}
const requestingUserId = await this.checkUserAccess(hashedUserId);
let rootFolder = await Folder.findOne({ where: { parentId: null, userId: user.id } });
if (!rootFolder) {
return null;
}
const accessibleFolders = await this.getAccessibleFolders(rootFolder.id, requestingUserId);
rootFolder = rootFolder.get();
rootFolder.children = accessibleFolders;
return rootFolder;
}
async getAccessibleFolders(folderId, requestingUserId) {
const folderIdString = String(folderId);
const requestingUserIdString = String(requestingUserId);
const requestingUser = await User.findOne({ where: { id: requestingUserIdString } });
const isAdult = this.isUserAdult(requestingUser.id);
const accessibleFolders = await Folder.findAll({
where: { parentId: folderIdString },
include: [
{
model: ImageVisibilityType,
through: { model: FolderImageVisibility },
where: {
[Op.or]: [
{ description: 'everyone' },
{ description: 'adults', ...(isAdult ? {} : { [Op.not]: null }) },
{ description: 'friends-and-adults', ...(isAdult ? {} : { [Op.not]: null }) }
]
},
required: false
},
{
model: ImageVisibilityUser,
through: { model: FolderVisibilityUser },
where: { user_id: requestingUserIdString },
required: false
}
]
});
const folderList = [];
for (let folder of accessibleFolders) {
const children = await this.getAccessibleFolders(folder.id, requestingUserIdString);
folder = folder.get();
folder.children = children;
folderList.push(folder);
}
return folderList;
}
async deleteFolder(hashedUserId, folderId) {
const userId = await this.checkUserAccess(hashedUserId);
const folder = await Folder.findOne({
where: { id: folderId, userId }
});
if (!folder) {
throw new Error('Folder not found or access denied');
}
await FolderImageVisibility.destroy({ where: { folderId: folder.id } });
await folder.destroy();
return true;
}
async createGuestbookEntry(hashedSenderId, recipientName, htmlContent, image) {
const sender = await User.findOne({ where: { hashedId: hashedSenderId } });
if (!sender) {
throw new Error('Sender not found');
}
const recipient = await User.findOne({ where: { username: recipientName } });
if (!recipient) {
throw new Error('Recipient not found');
}
const sanitizedContent = this.sanitizeHtml(htmlContent);
let uploadedImage = null;
if (image) {
uploadedImage = await this.processAndUploadGuestbookImage(image);
}
const entry = await GuestbookEntry.create({
senderId: sender.id,
recipientId: recipient.id,
senderUsername: sender.username,
contentHtml: sanitizedContent,
imageUrl: uploadedImage
});
return entry;
}
sanitizeHtml(htmlContent) {
const window = new JSDOM('').window;
const purify = DOMPurify(window);
const cleanHtml = purify.sanitize(htmlContent, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'ol', 'li', 'br'],
ALLOWED_ATTR: ['href', 'title'],
FORBID_TAGS: ['script', 'style', 'iframe', 'img'],
ALLOWED_URI_REGEXP: /^https?:\/\//,
});
return cleanHtml;
}
async processAndUploadGuestbookImage(image) {
try {
const img = sharp(image.buffer);
const metadata = await img.metadata();
if (!metadata || !['jpeg', 'png', 'webp', 'gif'].includes(metadata.format)) {
throw new Error('File is not a valid image');
}
if (metadata.width < 20 || metadata.height < 20) {
throw new Error('Image dimensions are too small. Minimum size is 20x20 pixels.');
}
const resizedImg = img.resize({
width: Math.min(metadata.width, 500),
height: Math.min(metadata.height, 500),
fit: sharp.fit.inside,
withoutEnlargement: true
});
const newFileName = this.generateUniqueFileName(image.originalname);
const filePath = this.buildFilePath(newFileName, 'guestbook');
await resizedImg.toFile(filePath);
return newFileName;
} catch (error) {
throw new Error(`Failed to process image: ${error.message}`);
}
}
async getGuestbookEntries(hashedUserId, username, page = 1) {
const pageSize = 20;
const offset = (page - 1) * pageSize;
this.checkUserAccess(hashedUserId);
const user = await User.findOne({ where: { username: username } });
if (!user) {
throw new Error('User not found');
}
const entries = await GuestbookEntry.findAndCountAll({
where: { recipientId: user.id },
include: [
{ model: User, as: 'sender', attributes: ['username'] },
],
limit: pageSize,
offset: offset,
order: [['createdAt', 'DESC']]
});
const resultList = entries.rows.map(entry => ({
id: entry.id,
sender: entry.sender ? entry.sender.username : entry.senderUsername,
contentHtml: entry.contentHtml,
withImage: entry.imageUrl !== null,
createdAt: entry.createdAt
}));
return {
entries: resultList,
currentPage: page,
totalPages: Math.ceil(entries.count / pageSize),
};
}
async getGuestbookImageFilePath(hashedUserId, guestbookOwnerName, entryId) {
await this.checkUserAccess(hashedUserId);
const guestbookOwner = await User.findOne({
where: { username: guestbookOwnerName },
});
if (!guestbookOwner) {
throw new Error('usernotfound');
}
const entry = await GuestbookEntry.findOne({
where: { id: entryId, recipientId: guestbookOwner.id },
});
if (!entry) {
throw new Error('entrynotfound');
}
if (!entry.imageUrl) {
console.log(entry);
throw new Error('entryhasnoimage');
}
console.log(`Image URL: ${entry.imageUrl}`);
const imagePath = this.buildFilePath(entry.imageUrl, 'guestbook');
if (!fs.existsSync(imagePath)) {
throw new Error(imagenotfound);
}
return imagePath;
}
async deleteGuestbookEntry(hashedUserId, entryId) {
const user = await User.findOne({ where: { hashedId: hashedUserId } });
if (!user) {
throw new Error('User not found');
}
const entry = await GuestbookEntry.findOne({ where: { id: entryId } });
if (!entry) {
throw new Error('Entry not found');
}
if (entry.senderId !== user.id && entry.recipientId !== user.id) {
throw new Error('Not authorized to delete this entry');
}
await entry.destroy();
}
async createDiaryEntry(userId, text) {
const newEntry = await Diary.create({
userId: userId,
text: text,
createdAt: new Date(),
updatedAt: new Date(),
});
return newEntry;
}
async updateDiaryEntry(diaryId, userId, newText) {
const existingEntry = await Diary.findOne({
where: { id: diaryId, userId: userId }
});
if (!existingEntry) {
throw new Error('Diary entry not found or unauthorized access');
}
await DiaryHistory.create({
diaryId: existingEntry.id,
userId: existingEntry.userId,
oldText: existingEntry.text,
oldCreatedAt: existingEntry.createdAt,
oldUpdatedAt: existingEntry.updatedAt,
});
existingEntry.text = newText;
existingEntry.updatedAt = new Date();
await existingEntry.save();
return existingEntry;
}
async deleteDiaryEntry(diaryId, userId) {
const entryToDelete = await Diary.findOne({
where: { id: diaryId, userId: userId }
});
if (!entryToDelete) {
throw new Error('Diary entry not found or unauthorized access');
}
await entryToDelete.destroy();
return true;
}
async getDiaryEntries(userId) {
const entries = await Diary.findAll({
where: { userId: userId },
order: [['createdAt', 'DESC']]
});
return entries;
}
}
export default SocialNetworkService;
export default SocialNetworkService;