forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookController.js
More file actions
231 lines (199 loc) · 7.21 KB
/
Copy pathbookController.js
File metadata and controls
231 lines (199 loc) · 7.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import axios from "axios";
import Book from "../../models/Book.js";
import User from "../../models/User.js";
import cloudinary from "../../utils/cloudinary.js";
import logger from "../../config/logger.js";
import { validateMagicBytes } from "../../utils/fileValidation.js";
import { createNewBookNotification } from "../notificationController.js";
//cretae a book
export const createBook = async (req, res) => {
logger.info("Creating book with data:", req.body);
logger.info("Files received:", req.files);
try {
const { title, category, price, readCount, description } = req.body;
if (!req.files || !req.files.thumbnail || !req.files.file)
return res
.status(400)
.json({ error: "Thumbnail image and book file are required" });
if (!req.user || !req.user.name) {
return res.status(401).json({
success: false,
message: "Not authorized, user not found or missing name",
});
}
const isThumbnailValid = await validateMagicBytes(req.files.thumbnail[0].buffer, ["image/jpeg", "image/png", "image/webp"]);
const isFileValid = await validateMagicBytes(req.files.file[0].buffer, ["application/pdf", "application/epub+zip"]);
if (!isThumbnailValid || !isFileValid) {
return res.status(400).json({ success: false, message: "Invalid file content detected. Magic bytes do not match expected types.", data: null });
}
// Upload thumbnail to Cloudinary
const thumbnailUpload = await new Promise((resolve, reject) => {
const stream = cloudinary.uploader.upload_stream(
{ folder: "library-books/thumbnails" },
(error, result) => {
if (error) reject(error);
else resolve(result);
}
);
stream.end(req.files.thumbnail[0].buffer);
});
// Upload book file to Cloudinary (as raw file)
const fileUpload = await new Promise((resolve, reject) => {
const stream = cloudinary.uploader.upload_stream(
{ folder: "library-books/files", resource_type: "raw", type: "authenticated" },
(error, result) => {
if (error) reject(error);
else resolve(result);
}
);
stream.end(req.files.file[0].buffer);
});
// Debug: log Cloudinary upload results
logger.info("thumbnailUpload:", thumbnailUpload);
logger.info("fileUpload:", fileUpload);
const book = await Book.create({
title,
author: req.user._id,
thumbnail: thumbnailUpload.secure_url,
category,
price,
description,
readCount,
image: thumbnailUpload.secure_url,
fileUrl: fileUpload.secure_url,
filePublicId: fileUpload.public_id,
});
// Emit new book notification asynchronously to followers
createNewBookNotification(book._id, req.user._id, book.title).catch((err) =>
logger.error("Error creating book notification:", err)
);
res.status(201).json({ success: true, message: "Book created successfully", data: book });
} catch (err) {
logger.error("Book creation error:", err);
res.status(500).json({ success: false, error: err.message });
}
};
// get all books in the store
export const getBooks = async (req, res) => {
const books = await Book.find().populate("author", "name avatar bio").populate("reviews.user", "name avatar");
res.json({ success: true, books });
};
// get a particular book
export const getBook = async (req, res) => {
const book = await Book.findById(req.params.id)
.populate("author", "name avatar bio")
.populate("reviews.user", "name avatar");
if (!book) return res.status(404).json({ success: false, message: "Book not found" });
res.json({ success: true, book });
};
// get books created by the author
export const getBooksByAuthor = async (req, res) => {
try {
const { authorId } = req.params; // Get authorId from route params
if (!authorId) {
return res
.status(400)
.json({ success: false, message: "Missing author id" });
}
const books = await Book.find({ author: authorId }).populate("author", "name avatar bio");
if (!books || books.length === 0) {
return res
.status(200)
.json({ success: false, message: "No books found" });
}
res.status(200).json({ success: true, books });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// delete book by id
export const deleteBook = async (req, res) => {
try {
const book = await Book.findById(req.params.id);
if (!book) {
return res.status(404).json({ success: false, message: "Book not found" });
}
if (req.user.role !== "admin" && book.author.toString() !== req.user._id.toString()) {
return res.status(403).json({
success: false,
message: "Not authorized to delete this book",
});
}
await Book.findByIdAndDelete(req.params.id);
res.json({ success: true, message: "Book deleted" });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// review books
export {
addBookReview,
getBookReviews,
updateBookReview,
deleteBookReview,
} from "../reviewController.js";
// recommended books for user based on their profile interest
export const fetchRecommendedBooks = async (req, res) => {
try {
const { interests } = req.body;
const recommmended = await Book.find().$where(category === interests);
res.status(200).json({ success: true, recommmended });
} catch (e) {}
};
export const streamBookPreview = async (req, res) => {
try {
const { id } = req.params;
const userId = req.user?._id;
if (!id) {
return res
.status(400)
.json({ success: false, message: "Missing book id" });
}
const book = await Book.findById(id).populate("author", "_id");
if (!book || !book.fileUrl) {
return res
.status(404)
.json({ success: false, message: "Book file not found" });
}
let hasAccess = book.price === 0;
if (userId) {
if (book.author?._id?.toString() === userId.toString()) {
hasAccess = true;
} else {
const user = await User.findById(userId).select("purchasedBooks");
if (user?.purchasedBooks?.some((entry) => entry.bookId.toString() === id)) {
hasAccess = true;
}
}
}
if (!hasAccess) {
return res
.status(403)
.json({ success: false, message: "You do not have access to this book." });
}
if (book.filePublicId) {
const signedUrl = cloudinary.utils.private_download_url(book.filePublicId, "raw", {
expires_at: Math.floor(Date.now() / 1000) + 3600, // 1 hour
});
return res.redirect(302, signedUrl);
}
const fileResponse = await axios.get(book.fileUrl, {
responseType: "stream",
});
res.setHeader(
"Content-Type",
fileResponse.headers["content-type"] || "application/pdf"
);
res.setHeader(
"Content-Disposition",
`inline; filename="${encodeURIComponent(`${book.title}.pdf`)}"`
);
res.setHeader("Cache-Control", "private, max-age=0, no-cache");
fileResponse.data.pipe(res);
} catch (error) {
logger.error("Error streaming book preview:", error);
res
.status(500)
.json({ success: false, message: "Unable to stream book preview" });
}
};