File size: 1,965 Bytes
e8c33fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const path = require('path');
const { ObjectId } = require('mongodb');
const { getMediaBucket } = require('../configs/gridfs');
const { asyncController } = require('../utils/asyncController');

const EXT_MIME = {
  '.webp': 'image/webp',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.png': 'image/png',
  '.gif': 'image/gif',
  '.avif': 'image/avif',
};

const resolveContentType = (file) => {
  if (file?.contentType && file.contentType !== 'application/octet-stream') return file.contentType;
  if (file?.metadata?.sourceMimeType) return file.metadata.sourceMimeType;
  const ext = path.extname(file?.filename || '').toLowerCase();
  return EXT_MIME[ext] || 'application/octet-stream';
};

const getMediaById = asyncController(async (req, res) => {
  const { id } = req.params;

  if (!ObjectId.isValid(id)) {
    return res.status(400).json({ message: 'Invalid media id' });
  }

  const bucket = getMediaBucket();
  if (!bucket) {
    return res.status(503).json({ message: 'Media storage is not ready. Please try again in a moment.' });
  }

  // Allow cross-origin embeds so <img> tags load correctly across LAN and different domains.
  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');

  const fileId = new ObjectId(id);
  const downloadStream = bucket.openDownloadStream(fileId);

  downloadStream.on('file', (file) => {
    res.setHeader('Content-Type', resolveContentType(file));
    res.setHeader('Content-Length', String(file.length));
    res.setHeader('Cache-Control', 'public, max-age=2592000, immutable');
    res.setHeader('ETag', `"${String(file._id)}-${file.length}"`);
    if (file.uploadDate) {
      res.setHeader('Last-Modified', new Date(file.uploadDate).toUTCString());
    }
  });

  downloadStream.on('error', () => {
    if (!res.headersSent) {
      return res.status(404).json({ message: 'Media not found' });
    }

    res.destroy();
  });

  downloadStream.pipe(res);
});

module.exports = {
  getMediaById,
};