@openpeepshq/core 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/media/index.js +163 -24
  2. package/package.json +3 -3
@@ -110,7 +110,7 @@ export const transcodeIncomingMedia = async (type, inputPath, originalName, sour
110
110
  export const createPreview = async (inputPath, mimetype, originalName) => {
111
111
  switch (mimetype.split('/')[0]) {
112
112
  case 'image':
113
- return createImagePreview(inputPath);
113
+ return createImagePreview(inputPath, mimetype, originalName);
114
114
  case 'audio':
115
115
  return createAudioPreview(inputPath);
116
116
  case 'video':
@@ -122,10 +122,78 @@ export const createPreview = async (inputPath, mimetype, originalName) => {
122
122
  return createFilePreview(inputPath, mimetype, originalName);
123
123
  }
124
124
  };
125
- const createImagePreview = async (inputPath) => {
125
+ /**
126
+ * HEVC-coded HEIF variants. sharp's prebuilt libvips cannot decode these
127
+ * (AVIF, which shares the container, is handled natively).
128
+ */
129
+ const HEIF_MIMETYPES = new Set([
130
+ 'image/heic',
131
+ 'image/heif',
132
+ 'image/heic-sequence',
133
+ 'image/heif-sequence',
134
+ ]);
135
+ const isHeifFamily = (mimetype, originalName) => HEIF_MIMETYPES.has(mimetype) || /\.hei[cf]$/i.test(originalName);
136
+ /**
137
+ * Decode a HEIC/HEIF image to PNG with ImageMagick. Prefers the ImageMagick 7
138
+ * `magick` binary and falls back to the ImageMagick 6 `convert` (Debian/Ubuntu
139
+ * ship only the latter). `-auto-orient` bakes EXIF rotation into the PNG so
140
+ * the later sharp step cannot lose orientation with the pixel data.
141
+ */
142
+ const decodeWithImageMagick = async (inputPath) => {
143
+ const outputPath = tempPathFor('decode.png');
144
+ const args = [inputPath, '-auto-orient', outputPath];
145
+ await new Promise((resolve, reject) => {
146
+ const run = (bin) => {
147
+ const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });
148
+ let stderr = '';
149
+ proc.stderr?.setEncoding('utf8');
150
+ proc.stderr?.on('data', (chunk) => {
151
+ stderr += chunk;
152
+ });
153
+ proc.on('error', (err) => {
154
+ if (err.code === 'ENOENT' && bin === 'magick') {
155
+ run('convert');
156
+ return;
157
+ }
158
+ reject(err.code === 'ENOENT'
159
+ ? new Error('ImageMagick binary not found')
160
+ : err);
161
+ });
162
+ proc.on('close', (code) => {
163
+ if (code === 0) {
164
+ resolve();
165
+ }
166
+ else {
167
+ reject(new Error(`ImageMagick ${bin} failed (exit ${code}): ${stderr}`));
168
+ }
169
+ });
170
+ };
171
+ run('magick');
172
+ });
173
+ return outputPath;
174
+ };
175
+ /**
176
+ * Render an image to a WebP thumbnail via sharp. sharp's prebuilt libvips
177
+ * bundles libheif for AVIF but ships without the HEVC codecs iPhone photos
178
+ * use, so HEVC-coded HEIC inputs are first decoded with ImageMagick (when
179
+ * installed with its heic delegate; see decodeWithImageMagick). Without it the
180
+ * sharp call below rejects them with MediaContentError, preserving the
181
+ * reject-uploads-we-cannot-process behaviour.
182
+ */
183
+ const createImagePreview = async (inputPath, mimetype, originalName) => {
126
184
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
185
+ let decodePath = inputPath;
186
+ if (isHeifFamily(mimetype, originalName)) {
187
+ try {
188
+ decodePath = await decodeWithImageMagick(inputPath);
189
+ }
190
+ catch (error) {
191
+ const message = error instanceof Error ? error.message : String(error);
192
+ log.warn(`ImageMagick HEIC decode skipped for ${originalName}: ${message}`);
193
+ }
194
+ }
127
195
  try {
128
- await sharp(inputPath)
196
+ await sharp(decodePath)
129
197
  .rotate()
130
198
  .resize(previewMaxWidth)
131
199
  .webp({ quality: 80 })
@@ -134,6 +202,11 @@ const createImagePreview = async (inputPath) => {
134
202
  catch {
135
203
  throw new MediaContentError("This file isn't a supported image.");
136
204
  }
205
+ finally {
206
+ if (decodePath !== inputPath) {
207
+ await fs.rm(decodePath, { force: true }).catch(() => undefined);
208
+ }
209
+ }
137
210
  return { path: outputPath, mimetype: 'image/webp' };
138
211
  };
139
212
  const escapeXml = (value) => value
@@ -142,26 +215,82 @@ const escapeXml = (value) => value
142
215
  .replace(/>/g, '>')
143
216
  .replace(/"/g, '"');
144
217
  /**
145
- * Render the first page of a PDF to a WebP thumbnail via sharp. The prebuilt
146
- * sharp binary bundles poppler, so PDF decoding is available without any extra
147
- * system packages on Linux/musl (Alpine) and glibc.
218
+ * Rasterize page 1 of a PDF to PNG with poppler's pdftoppm. sharp's prebuilt
219
+ * binaries ship without a PDF loader, so this is the actual rendering engine;
220
+ * font selection goes through fontconfig (font-noto et al. in the image).
148
221
  */
149
- const createPdfPreview = async (inputPath) => {
222
+ const renderPdfWithPoppler = (inputPath, originalName) => new Promise((resolve, reject) => {
223
+ const prefix = join(tmpdir(), `pdf-${randomString(16)}`);
224
+ const proc = spawn('pdftoppm', [
225
+ '-png',
226
+ '-singlefile',
227
+ '-r',
228
+ '150',
229
+ '-f',
230
+ '1',
231
+ '-l',
232
+ '1',
233
+ inputPath,
234
+ prefix,
235
+ ], { stdio: ['ignore', 'ignore', 'pipe'] });
236
+ let stderr = '';
237
+ proc.stderr?.setEncoding('utf8');
238
+ proc.stderr?.on('data', (chunk) => {
239
+ stderr += chunk;
240
+ });
241
+ proc.on('error', (err) => {
242
+ reject(err.code === 'ENOENT' ? new Error('pdftoppm binary not found') : err);
243
+ });
244
+ proc.on('close', (code) => {
245
+ if (code === 0) {
246
+ resolve(`${prefix}.png`);
247
+ }
248
+ else {
249
+ reject(new Error(`pdftoppm failed for ${originalName} (exit ${code}): ${stderr}`));
250
+ }
251
+ });
252
+ });
253
+ /**
254
+ * Render the first page of a PDF to a WebP thumbnail: try sharp (in case a
255
+ * future build gains a PDF loader), then pdftoppm, then let the caller fall
256
+ * back to the document card preview.
257
+ */
258
+ const createPdfPreview = async (inputPath, originalName) => {
150
259
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
151
- await sharp(inputPath, { density: 150, pages: 1 })
152
- .resize(previewMaxWidth)
153
- .webp({ quality: 80 })
154
- .toFile(outputPath);
155
- // sharp/poppler may produce a blank or corrupt thumbnail without erroring
156
- // when fonts are missing (text renders as tofu rectangles) or the PDF page is
157
- // genuinely empty. Validate the output so callers fall back to the document
158
- // card preview, which shows the filename instead of garbled content.
159
- const { size } = await fs.stat(outputPath);
160
- if (size < 100) {
161
- throw new Error('PDF preview rendered to empty image');
260
+ let rendered = false;
261
+ try {
262
+ await sharp(inputPath, { density: 150, pages: 1 })
263
+ .resize(previewMaxWidth)
264
+ .webp({ quality: 80 })
265
+ .toFile(outputPath);
266
+ rendered = true;
267
+ }
268
+ catch {
269
+ // sharp has no PDF loader here; render the page with poppler instead.
162
270
  }
271
+ if (!rendered) {
272
+ const pngPath = await renderPdfWithPoppler(inputPath, originalName);
273
+ try {
274
+ await sharp(pngPath)
275
+ .resize(previewMaxWidth)
276
+ .webp({ quality: 80 })
277
+ .toFile(outputPath);
278
+ rendered = true;
279
+ }
280
+ finally {
281
+ await fs.rm(pngPath, { force: true }).catch(() => undefined);
282
+ }
283
+ }
284
+ if (!rendered) {
285
+ throw new Error(`PDF preview failed for ${originalName}`);
286
+ }
287
+ // A broken render may still produce a file: reject a blank (uniform,
288
+ // near-white) page so callers fall back to the document card preview.
289
+ // Solid-color pages are legitimate content and must pass.
163
290
  const stats = await sharp(outputPath).stats();
164
- if (stats.channels.every((c) => c.stdev < 2)) {
291
+ const uniform = stats.channels.every((c) => c.stdev < 2);
292
+ const nearWhite = stats.channels.every((c) => c.mean > 250);
293
+ if (uniform && nearWhite) {
165
294
  throw new Error('PDF preview rendered to blank image');
166
295
  }
167
296
  return { path: outputPath, mimetype: 'image/webp' };
@@ -244,17 +373,18 @@ const createFilePreview = async (inputPath, mimetype, originalName) => {
244
373
  originalName.toLowerCase().endsWith('.pdf');
245
374
  if (isPdf) {
246
375
  try {
247
- return await createPdfPreview(inputPath);
376
+ return await createPdfPreview(inputPath, originalName);
248
377
  }
249
- catch {
250
- // sharp PDF support may be missing; fall back to card preview below.
378
+ catch (error) {
379
+ const message = error instanceof Error ? error.message : String(error);
380
+ log.warn(`PDF preview failed for ${originalName}: ${message}`);
251
381
  }
252
382
  }
253
383
  if (isOfficeDocument(originalName)) {
254
384
  let pdfPath;
255
385
  try {
256
386
  pdfPath = await convertOfficeToPdf(inputPath, originalName);
257
- return await createPdfPreview(pdfPath);
387
+ return await createPdfPreview(pdfPath, originalName);
258
388
  }
259
389
  catch (error) {
260
390
  const message = error instanceof Error ? error.message : String(error);
@@ -325,7 +455,16 @@ const renderWaveform = (inputPath, outputPath, color) => new Promise((resolve, r
325
455
  });
326
456
  const createAudioPreview = async (inputPath) => {
327
457
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.png`);
328
- const color = waveformColor(getTheme(await communityConfig()).primaryHex);
458
+ // The waveform color is cosmetic: an unreadable community config must not
459
+ // block preview generation, so fall back to the default theme primary.
460
+ let primaryHex = '#15678a';
461
+ try {
462
+ primaryHex = getTheme(await communityConfig()).primaryHex;
463
+ }
464
+ catch {
465
+ // keep default
466
+ }
467
+ const color = waveformColor(primaryHex);
329
468
  try {
330
469
  await renderWaveform(inputPath, outputPath, color);
331
470
  return { path: outputPath, mimetype: 'image/png' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -38,9 +38,9 @@
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
40
  "@openpeepshq/common": "0.4.0",
41
+ "@openpeepshq/i18n": "^0.3.1",
41
42
  "@openpeepshq/geocoder": "^0.1.2",
42
- "@openpeepshq/fetch-client": "^0.2.1",
43
- "@openpeepshq/i18n": "^0.2.1"
43
+ "@openpeepshq/fetch-client": "^0.2.1"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",