File size: 12,107 Bytes
6e13570
 
 
 
4c6b1e8
 
 
 
 
 
 
 
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db9f9f5
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e1247d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c6b1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e13570
 
 
 
 
 
 
 
 
 
4c6b1e8
6e13570
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
const fs = require("fs/promises");
const mongoose = require("mongoose");
const Course = require("../models/Course");
const AuditLog = require("../models/AuditLog");
const {
  uploadFromPath,
  deleteAsset,
  getSignedPlaybackUrl,
  resourceTypeForMimetype,
  uploadThumbnail: uploadThumbnailToCloudinary,
  deleteThumbnail,
} = require("../utils/cloudinaryUpload");
const logger = require("../utils/logger");

function userHasAccess(user, courseId) {
  if (!user) return false;
  if (user.role === "admin") return true;
  return user.hasAccessToCourse(courseId);
}

// ---------------------------------------------------------------------
// Learner-facing: view curriculum structure, and request a signed,
// time-limited playback URL for one lesson at a time.
// ---------------------------------------------------------------------

async function getCourseCurriculum(req, res, next) {
  try {
    const course = await Course.findById(req.params.id);
    if (!course || !course.isPublished) return res.status(404).json({ error: "Course not found." });

    const hasAccess = userHasAccess(req.user, course._id);
    res.json({
      courseId: course._id,
      title: course.title,
      hasAccess,
      curriculum: hasAccess ? course.toCurriculumJSON() : course.toLockedCurriculumJSON(),
    });
  } catch (err) {
    next(err);
  }
}

async function getLessonAccess(req, res, next) {
  try {
    const { id: courseId, sectionId, lessonId } = req.params;

    const course = await Course.findById(courseId);
    if (!course || !course.isPublished) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(sectionId);
    const lesson = section?.lessons.id(lessonId);
    if (!section || !lesson) return res.status(404).json({ error: "Lesson not found." });

    const hasAccess = userHasAccess(req.user, course._id);
    if (!hasAccess && !lesson.isPreview) {
      return res.status(403).json({ error: "Purchase this course to access this lesson." });
    }

    const { url, expiresAt } = getSignedPlaybackUrl(lesson.cloudinaryPublicId, lesson.cloudinaryResourceType, {
      format: lesson.format,
      viewer: { email: req.user.email },
    });

    await AuditLog.create({
      actor: req.user._id,
      actorEmail: req.user.email,
      action: "lesson.access_granted",
      targetType: "Lesson",
      targetId: lesson._id,
      ip: req.ip,
      userAgent: req.headers["user-agent"],
      metadata: { courseId: course._id.toString() },
    });

    res.json({
      url,
      expiresAt,
      type: lesson.type,
      title: lesson.title,
    });
  } catch (err) {
    next(err);
  }
}

// ---------------------------------------------------------------------
// Admin-only: manage curriculum structure and upload content to
// Cloudinary. No learner-facing route ever exposes an upload capability.
// ---------------------------------------------------------------------

async function createSection(req, res, next) {
  try {
    const { title } = req.body;
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const order = course.curriculum.length;
    course.curriculum.push({ title, order, lessons: [] });
    await course.save();

    res.status(201).json({ curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

async function updateSection(req, res, next) {
  try {
    const { title, order } = req.body;
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(req.params.sectionId);
    if (!section) return res.status(404).json({ error: "Section not found." });

    if (title !== undefined) section.title = title;
    if (order !== undefined) section.order = order;
    await course.save();

    res.json({ curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

async function deleteSection(req, res, next) {
  try {
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(req.params.sectionId);
    if (!section) return res.status(404).json({ error: "Section not found." });

    // Clean up every Cloudinary asset in this section before removing it.
    await Promise.all(
      section.lessons.map((lesson) =>
        deleteAsset(lesson.cloudinaryPublicId, lesson.cloudinaryResourceType).catch((err) =>
          logger.error("Failed to delete Cloudinary asset", { error: err.message, lessonId: lesson._id.toString() })
        )
      )
    );

    section.deleteOne();
    await course.save();

    res.json({ curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

async function uploadLesson(req, res, next) {
  const tempFilePath = req.file?.path;
  try {
    const { title, description, isPreview, order } = req.body;
    if (!req.file) return res.status(400).json({ error: "A file is required." });

    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(req.params.sectionId);
    if (!section) return res.status(404).json({ error: "Section not found." });

    const resourceType = resourceTypeForMimetype(req.file.mimetype);
    const lessonType = resourceType === "video" ? "video" : "document";

    const result = await uploadFromPath(tempFilePath, {
      resourceType,
      filenameHint: title,
    });

    // From here on, the asset exists in Cloudinary. If anything below
    // fails (DB validation, a save error, etc.), we must delete it —
    // otherwise a failed attempt leaves an orphaned file in storage
    // forever, since nothing in the database ever references it to
    // clean it up later.
    try {
      section.lessons.push({
        title,
        description: description || "",
        type: lessonType,
        order: order !== undefined ? Number(order) : section.lessons.length,
        isPreview: isPreview === "true" || isPreview === true,
        cloudinaryPublicId: result.public_id,
        cloudinaryResourceType: result.resource_type,
        format: result.format || "",
        bytes: result.bytes || 0,
        durationSeconds: result.duration ? Math.round(result.duration) : 0,
      });
      await course.save();

      await AuditLog.create({
        actor: req.user._id,
        actorEmail: req.user.email,
        action: "admin.lesson_uploaded",
        targetType: "Course",
        targetId: course._id,
        ip: req.ip,
        userAgent: req.headers["user-agent"],
        metadata: { sectionId: section._id.toString(), title },
      });

      res.status(201).json({ curriculum: course.toCurriculumJSON() });
    } catch (err) {
      await deleteAsset(result.public_id, result.resource_type).catch((cleanupErr) =>
        logger.error("Failed to clean up orphaned Cloudinary asset after failed save", {
          error: cleanupErr.message,
          publicId: result.public_id,
          resourceType: result.resource_type,
        })
      );
      throw err;
    }
  } catch (err) {
    next(err);
  } finally {
    // Always clean up the local temp file, whether the upload succeeded,
    // failed partway, or Cloudinary itself errored out.
    if (tempFilePath) {
      fs.unlink(tempFilePath).catch((err) =>
        logger.error("Failed to remove temp upload file", { error: err.message, tempFilePath })
      );
    }
  }
}

async function updateLesson(req, res, next) {
  try {
    const { title, description, isPreview, order } = req.body;
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(req.params.sectionId);
    const lesson = section?.lessons.id(req.params.lessonId);
    if (!section || !lesson) return res.status(404).json({ error: "Lesson not found." });

    if (title !== undefined) lesson.title = title;
    if (description !== undefined) lesson.description = description;
    if (isPreview !== undefined) lesson.isPreview = isPreview === "true" || isPreview === true;
    if (order !== undefined) lesson.order = Number(order);
    await course.save();

    res.json({ curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

async function deleteLesson(req, res, next) {
  try {
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });

    const section = course.curriculum.id(req.params.sectionId);
    const lesson = section?.lessons.id(req.params.lessonId);
    if (!section || !lesson) return res.status(404).json({ error: "Lesson not found." });

    await deleteAsset(lesson.cloudinaryPublicId, lesson.cloudinaryResourceType).catch((err) =>
      logger.error("Failed to delete Cloudinary asset", { error: err.message })
    );

    lesson.deleteOne();
    await course.save();

    await AuditLog.create({
      actor: req.user._id,
      actorEmail: req.user.email,
      action: "admin.lesson_deleted",
      targetType: "Course",
      targetId: course._id,
      ip: req.ip,
      userAgent: req.headers["user-agent"],
    });

    res.json({ curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

/** Admin editing view: full curriculum, same shape as the learner view (no raw Cloudinary IDs sent to the browser here either — uploads/deletes are the only mutating ops, playback still goes through the signed-URL endpoint). */
async function getCourseCurriculumForAdmin(req, res, next) {
  try {
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });
    res.json({ courseId: course._id, title: course.title, curriculum: course.toCurriculumJSON() });
  } catch (err) {
    next(err);
  }
}

/**

 * Admin uploads/replaces a course's marketing thumbnail (shown on the

 * homepage "Our Academy" preview and the Academy catalogue page). If

 * the course already had one, the old Cloudinary asset is deleted so

 * replacing a thumbnail doesn't leave the previous image as an

 * orphaned file in storage.

 */
async function uploadThumbnail(req, res, next) {
  try {
    const course = await Course.findById(req.params.id);
    if (!course) return res.status(404).json({ error: "Course not found." });
    if (!req.file) return res.status(400).json({ error: "No image file was uploaded." });

    const previousPublicId = course.thumbnailPublicId;

    const result = await uploadThumbnailToCloudinary(req.file.path, { filenameHint: course.slug });

    course.image = result.secure_url;
    course.thumbnailPublicId = result.public_id;
    await course.save();

    if (previousPublicId) {
      deleteThumbnail(previousPublicId).catch((err) =>
        logger.error("Failed to clean up replaced course thumbnail", { error: err.message, publicId: previousPublicId })
      );
    }

    await AuditLog.create({
      actor: req.user._id,
      actorEmail: req.user.email,
      action: "admin.course_thumbnail_uploaded",
      targetType: "Course",
      targetId: course._id,
      ip: req.ip,
      userAgent: req.headers["user-agent"],
    });

    res.json({ course });
  } catch (err) {
    next(err);
  } finally {
    if (req.file) {
      fs.unlink(req.file.path).catch(() => {});
    }
  }
}

module.exports = {
  getCourseCurriculum,
  getLessonAccess,
  getCourseCurriculumForAdmin,
  createSection,
  updateSection,
  deleteSection,
  uploadLesson,
  updateLesson,
  deleteLesson,
  uploadThumbnail,
};