@jrmc/adonis-attachment 2.1.1-1 → 2.3.0

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.
package/README.md CHANGED
@@ -7,6 +7,7 @@ Project sample : [adonis-starter-kit](https://github.com/batosai/adonis-starter-
7
7
  ## Links
8
8
 
9
9
  [View documentation](https://adonis-attachment.jrmc.dev/)
10
+ [Discord](https://discord.gg/89eMn2vB)
10
11
 
11
12
  [ChangeLog](https://adonis-attachment.jrmc.dev/changelog.html)
12
13
 
@@ -18,7 +19,7 @@ Project sample : [adonis-starter-kit](https://github.com/batosai/adonis-starter-
18
19
  - [x] save meta data
19
20
  - [x] variantes
20
21
  - [x] images
21
- - [ ] documents thumbnail
22
+ - [x] documents thumbnail
22
23
  - [x] videos thumbnail
23
24
  - [ ] command regenerate
24
25
  - [x] adonis-drive/flydrive
@@ -8,7 +8,7 @@ import fs from 'node:fs/promises';
8
8
  import ExifReader from 'exifreader';
9
9
  import logger from '@adonisjs/core/services/logger';
10
10
  import { fileTypeFromBuffer, fileTypeFromFile } from 'file-type';
11
- import { cleanObject, use } from '../utils/helpers.js';
11
+ import { bufferToTempFile, cleanObject, use } from '../utils/helpers.js';
12
12
  import { attachmentManager } from '../../index.js';
13
13
  export const exif = async (input) => {
14
14
  let fileType;
@@ -106,7 +106,11 @@ async function imageExif(buffer) {
106
106
  async function videoExif(input) {
107
107
  return new Promise(async (resolve) => {
108
108
  const ffmpeg = await use('fluent-ffmpeg');
109
- const ff = ffmpeg(input);
109
+ let file = input;
110
+ if (Buffer.isBuffer(input)) {
111
+ file = await bufferToTempFile(input);
112
+ }
113
+ const ff = ffmpeg(file);
110
114
  const config = attachmentManager.getConfig();
111
115
  if (config.bin) {
112
116
  if (config.bin.ffprobePath) {
@@ -5,7 +5,7 @@
5
5
  * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
6
  */
7
7
  import type { LoggerService } from '@adonisjs/core/types';
8
- import type { DriveService } from '@adonisjs/drive/types';
8
+ import type { DriveService, SignedURLOptions } from '@adonisjs/drive/types';
9
9
  import type { MultipartFile } from '@adonisjs/core/bodyparser';
10
10
  import type { AttachmentBase, Attachment as AttachmentType } from './types/attachment.js';
11
11
  import type { ResolvedAttachmentConfig } from './types/config.js';
@@ -18,8 +18,10 @@ export declare class AttachmentManager {
18
18
  createFromDbResponse(response: any): Attachment | null;
19
19
  createFromFile(file: MultipartFile): Promise<Attachment>;
20
20
  createFromBuffer(buffer: Buffer, name?: string): Promise<Attachment>;
21
+ createFromBase64(data: string, name?: string): Promise<Attachment>;
21
22
  getConverter(key: string): Promise<void | Converter>;
22
- computeUrl(attachment: AttachmentType): Promise<void>;
23
+ computeUrl(attachment: AttachmentType | AttachmentBase, signedUrlOptions?: SignedURLOptions): Promise<void>;
24
+ preComputeUrl(attachment: AttachmentType): Promise<void>;
23
25
  save(attachment: AttachmentBase): Promise<void>;
24
26
  delete(attachment: AttachmentBase): Promise<void>;
25
27
  }
@@ -49,6 +49,11 @@ export class AttachmentManager {
49
49
  const attributes = await createAttachmentAttributes(buffer, name);
50
50
  return new Attachment(this.#drive, attributes, buffer);
51
51
  }
52
+ async createFromBase64(data, name) {
53
+ const base64Data = data.replace(/^data:([A-Za-z-+\/]+);base64,/, '');
54
+ const buffer = Buffer.from(base64Data, 'base64');
55
+ return await this.createFromBuffer(buffer, name);
56
+ }
52
57
  async getConverter(key) {
53
58
  if (this.#config.converters) {
54
59
  for (const c of this.#config.converters) {
@@ -58,27 +63,25 @@ export class AttachmentManager {
58
63
  }
59
64
  }
60
65
  }
61
- async computeUrl(attachment) {
62
- if (attachment.options?.preComputeUrl === false) {
63
- return;
64
- }
66
+ async computeUrl(attachment, signedUrlOptions) {
65
67
  const disk = attachment.getDisk();
66
68
  const fileVisibility = await disk.getVisibility(attachment.path);
67
69
  if (fileVisibility === 'private') {
68
- attachment.url = await attachment.getSignedUrl();
70
+ attachment.url = await attachment.getSignedUrl(signedUrlOptions);
69
71
  }
70
72
  else {
71
73
  attachment.url = await attachment.getUrl();
72
74
  }
73
- if (attachment.variants) {
75
+ }
76
+ async preComputeUrl(attachment) {
77
+ if (attachment.options?.preComputeUrl === false) {
78
+ return;
79
+ }
80
+ await this.computeUrl(attachment);
81
+ if (attachment instanceof Attachment && attachment.variants) {
74
82
  for (const key in attachment.variants) {
75
83
  if (Object.prototype.hasOwnProperty.call(attachment.variants, key)) {
76
- if (fileVisibility === 'private') {
77
- attachment.variants[key].url = await attachment.getSignedUrl(attachment.variants[key].key);
78
- }
79
- else {
80
- attachment.variants[key].url = await attachment.getUrl(attachment.variants[key].key);
81
- }
84
+ await this.computeUrl(attachment.variants[key]);
82
85
  }
83
86
  }
84
87
  }
@@ -79,6 +79,14 @@ export class Attachment extends AttachmentBase {
79
79
  this.folder = this.options.folder;
80
80
  this.path = path.join(this.folder, this.name);
81
81
  }
82
+ if (this.variants) {
83
+ this.variants.forEach((v) => {
84
+ v.setOptions({
85
+ ...this.options,
86
+ variants: []
87
+ });
88
+ });
89
+ }
82
90
  return this;
83
91
  }
84
92
  toObject() {
@@ -98,15 +106,26 @@ export class Attachment extends AttachmentBase {
98
106
  mimetype: this.mimeType,
99
107
  meta: this.meta,
100
108
  };
109
+ if (this.variants) {
110
+ this.variants.map(async (v) => {
111
+ data[v.key] = {
112
+ name: v.name,
113
+ extname: v.extname,
114
+ mimetype: v.mimeType,
115
+ meta: v.meta,
116
+ size: v.size,
117
+ };
118
+ });
119
+ }
101
120
  if (this.url) {
102
121
  data.url = this.url;
103
- if (this.variants) {
104
- this.variants.map(async (v) => {
105
- data[v.key] = {
106
- url: v.url,
107
- };
108
- });
109
- }
122
+ }
123
+ if (this.variants) {
124
+ this.variants.map(async (v) => {
125
+ if (v.url) {
126
+ data[v.key].url = v.url;
127
+ }
128
+ });
110
129
  }
111
130
  return data;
112
131
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @jrmc/adonis-attachment
3
+ *
4
+ * @license MIT
5
+ * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
+ */
7
+ import type { ConverterAttributes } from '../types/converter.js';
8
+ import type { Input } from '../types/input.js';
9
+ import Converter from './converter.js';
10
+ export default class DocumentThumbnailConverter extends Converter {
11
+ handle({ input, options }: ConverterAttributes): Promise<any>;
12
+ documentToImage(LibreOfficeFileConverter: any, input: Input): Promise<any>;
13
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @jrmc/adonis-attachment
3
+ *
4
+ * @license MIT
5
+ * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
+ */
7
+ import Converter from './converter.js';
8
+ import ImageConverter from './image_converter.js';
9
+ import { use } from '../utils/helpers.js';
10
+ export default class DocumentThumbnailConverter extends Converter {
11
+ async handle({ input, options }) {
12
+ const lib = await use('libreoffice-file-converter');
13
+ if (lib) {
14
+ const LibreOfficeFileConverter = lib.LibreOfficeFileConverter;
15
+ const outputBuffer = await this.documentToImage(LibreOfficeFileConverter, input);
16
+ if (options && outputBuffer) {
17
+ const converter = new ImageConverter();
18
+ return await converter.handle({
19
+ input: outputBuffer,
20
+ options
21
+ });
22
+ }
23
+ return outputBuffer;
24
+ }
25
+ }
26
+ async documentToImage(LibreOfficeFileConverter, input) {
27
+ let binaryPaths = undefined;
28
+ if (this.binPaths && this.binPaths.libreofficePaths) {
29
+ binaryPaths = this.binPaths.libreofficePaths;
30
+ }
31
+ const libreOfficeFileConverter = new LibreOfficeFileConverter({
32
+ childProcessOptions: {
33
+ timeout: 60 * 1000,
34
+ },
35
+ binaryPaths
36
+ });
37
+ if (Buffer.isBuffer(input)) {
38
+ const output = await libreOfficeFileConverter.convert({
39
+ buffer: input,
40
+ input: 'buffer',
41
+ output: 'buffer',
42
+ format: 'jpeg',
43
+ });
44
+ return output;
45
+ }
46
+ else {
47
+ const output = await libreOfficeFileConverter.convert({
48
+ inputPath: input,
49
+ input: 'file',
50
+ output: 'buffer',
51
+ format: 'jpeg',
52
+ });
53
+ return output;
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @jrmc/adonis-attachment
3
+ *
4
+ * @license MIT
5
+ * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
+ */
7
+ import type { ConverterAttributes } from '../types/converter.js';
8
+ import type { Input } from '../types/input.js';
9
+ import Converter from './converter.js';
10
+ export default class PdfThumbnailConverter extends Converter {
11
+ handle({ input, options }: ConverterAttributes): Promise<any>;
12
+ pdfToImage(Poppler: any, input: Input): Promise<string>;
13
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @jrmc/adonis-attachment
3
+ *
4
+ * @license MIT
5
+ * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
+ */
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { cuid } from '@adonisjs/core/helpers';
10
+ import Converter from './converter.js';
11
+ import ImageConverter from './image_converter.js';
12
+ import { use } from '../utils/helpers.js';
13
+ export default class PdfThumbnailConverter extends Converter {
14
+ async handle({ input, options }) {
15
+ const nodePoppler = await use('node-poppler');
16
+ if (nodePoppler) {
17
+ const Poppler = nodePoppler.Poppler;
18
+ const filePath = await this.pdfToImage(Poppler, input);
19
+ if (options && filePath) {
20
+ const converter = new ImageConverter();
21
+ return await converter.handle({
22
+ input: filePath,
23
+ options
24
+ });
25
+ }
26
+ return filePath;
27
+ }
28
+ }
29
+ async pdfToImage(Poppler, input) {
30
+ let binPath = null;
31
+ if (this.binPaths && this.binPaths.pdftocairoBasePath) {
32
+ binPath = this.binPaths.pdftocairoBasePath;
33
+ }
34
+ const poppler = new Poppler(binPath);
35
+ const options = {
36
+ // firstPageToConvert: 1,
37
+ lastPageToConvert: 1,
38
+ jpegFile: true,
39
+ };
40
+ const filePath = path.join(os.tmpdir(), cuid());
41
+ await poppler.pdfToCairo(input, filePath, options);
42
+ return filePath + '-1.jpg';
43
+ }
44
+ }
@@ -5,8 +5,8 @@
5
5
  * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
6
  */
7
7
  import type { ConverterAttributes } from '../types/converter.js';
8
+ import type { Input } from '../types/input.js';
8
9
  import Converter from './converter.js';
9
- import { Input } from '../types/input.js';
10
10
  export default class VideoThumbnailConvert extends Converter {
11
11
  handle({ input, options }: ConverterAttributes): Promise<any>;
12
12
  videoToImage(ffmpeg: Function, input: Input): Promise<string | false>;
@@ -9,7 +9,7 @@ import path from 'node:path';
9
9
  import { cuid } from '@adonisjs/core/helpers';
10
10
  import Converter from './converter.js';
11
11
  import ImageConverter from './image_converter.js';
12
- import { use } from '../utils/helpers.js';
12
+ import { bufferToTempFile, use } from '../utils/helpers.js';
13
13
  export default class VideoThumbnailConvert extends Converter {
14
14
  async handle({ input, options }) {
15
15
  const ffmpeg = await use('fluent-ffmpeg');
@@ -28,10 +28,14 @@ export default class VideoThumbnailConvert extends Converter {
28
28
  }
29
29
  }
30
30
  async videoToImage(ffmpeg, input) {
31
+ let file = input;
32
+ if (Buffer.isBuffer(input)) {
33
+ file = await bufferToTempFile(input);
34
+ }
31
35
  return new Promise((resolve) => {
32
36
  const folder = os.tmpdir();
33
37
  const filename = `${cuid()}.png`;
34
- const ff = ffmpeg(input);
38
+ const ff = ffmpeg(file);
35
39
  if (this.binPaths) {
36
40
  if (this.binPaths.ffmpegPath) {
37
41
  ff.setFfmpegPath(this.binPaths.ffmpegPath);
@@ -16,6 +16,7 @@ export const attachment = (options) => {
16
16
  const defaultOptions = {
17
17
  meta: defaultConfig.meta !== undefined ? defaultConfig.meta : defaultOptionsDecorator.meta,
18
18
  rename: defaultConfig.rename !== undefined ? defaultConfig.rename : defaultOptionsDecorator.rename,
19
+ preComputeUrl: defaultConfig.preComputeUrl !== undefined ? defaultConfig.preComputeUrl : defaultOptionsDecorator.preComputeUrl,
19
20
  };
20
21
  if (!options || options?.meta === undefined) {
21
22
  options.meta = defaultOptions.meta;
@@ -23,6 +24,9 @@ export const attachment = (options) => {
23
24
  if (!options || options?.rename === undefined) {
24
25
  options.rename = defaultOptions.rename;
25
26
  }
27
+ if (!options || options?.preComputeUrl === undefined) {
28
+ options.preComputeUrl = defaultOptions.preComputeUrl;
29
+ }
26
30
  target[optionsSym][attributeName] = options;
27
31
  const Model = target.constructor;
28
32
  Model.boot();
@@ -11,7 +11,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
11
11
  return c > 3 && r && Object.defineProperty(target, key, r), r;
12
12
  };
13
13
  import { beforeSave, afterSave, beforeDelete, afterFind, afterFetch, afterPaginate } from '@adonisjs/lucid/orm';
14
- import { persistAttachment, commit, rollback, generateVariants, computeUrl } from '../utils/actions.js';
14
+ import { persistAttachment, commit, rollback, generateVariants, preComputeUrl } from '../utils/actions.js';
15
15
  import { clone, getAttachmentAttributeNames } from '../utils/helpers.js';
16
16
  import { defaultStateAttributeMixin } from '../utils/default_values.js';
17
17
  export const Attachmentable = (superclass) => {
@@ -20,7 +20,7 @@ export const Attachmentable = (superclass) => {
20
20
  static async afterFindHook(modelInstance) {
21
21
  const attachmentAttributeNames = getAttachmentAttributeNames(modelInstance);
22
22
  await Promise.all(attachmentAttributeNames.map((attributeName) => {
23
- return computeUrl(modelInstance, attributeName);
23
+ return preComputeUrl(modelInstance, attributeName);
24
24
  }));
25
25
  }
26
26
  static async afterFetchHook(modelInstances) {
@@ -16,11 +16,14 @@ type ConverterConfig = {
16
16
  export type BinPaths = {
17
17
  ffmpegPath?: string;
18
18
  ffprobePath?: string;
19
+ pdftocairoBasePath?: string;
20
+ libreofficePaths?: Array<string>;
19
21
  };
20
22
  export type AttachmentConfig = {
21
23
  bin?: BinPaths;
22
24
  meta?: boolean;
23
25
  rename?: boolean;
26
+ preComputeUrl?: boolean;
24
27
  converters?: ConverterConfig[];
25
28
  };
26
29
  export type ResolvedConverter = {
@@ -31,6 +34,7 @@ export type ResolvedAttachmentConfig = {
31
34
  bin?: BinPaths;
32
35
  meta?: boolean;
33
36
  rename?: boolean;
37
+ preComputeUrl?: boolean;
34
38
  converters?: ResolvedConverter[];
35
39
  };
36
40
  export {};
@@ -17,7 +17,7 @@ export declare function rollback(modelInstance: ModelWithAttachment): Promise<vo
17
17
  * Persist attachment for a given attachment attributeName
18
18
  */
19
19
  export declare function persistAttachment(modelInstance: ModelWithAttachment, attributeName: string): Promise<void>;
20
- export declare function computeUrl(modelInstance: ModelWithAttachment, attributeName: string): Promise<void>;
20
+ export declare function preComputeUrl(modelInstance: ModelWithAttachment, attributeName: string): Promise<void>;
21
21
  /**
22
22
  * Launch converter by variant option
23
23
  */
@@ -62,11 +62,11 @@ export async function persistAttachment(modelInstance, attributeName) {
62
62
  await attachmentManager.save(newFile);
63
63
  }
64
64
  }
65
- export async function computeUrl(modelInstance, attributeName) {
65
+ export async function preComputeUrl(modelInstance, attributeName) {
66
66
  const attachment = modelInstance.$attributes[attributeName];
67
67
  const options = getOptions(modelInstance, attributeName);
68
68
  attachment.setOptions(options);
69
- return attachmentManager.computeUrl(attachment);
69
+ return attachmentManager.preComputeUrl(attachment);
70
70
  }
71
71
  /**
72
72
  * Launch converter by variant option
@@ -9,8 +9,8 @@ export declare const defaultOptionsDecorator: {
9
9
  folder: string;
10
10
  preComputeUrl: boolean;
11
11
  variants: never[];
12
- rename: boolean;
13
12
  meta: boolean;
13
+ rename: boolean;
14
14
  };
15
15
  export declare const defaultStateAttributeMixin: {
16
16
  attached: never[];
@@ -9,8 +9,8 @@ export const defaultOptionsDecorator = {
9
9
  folder: 'uploads',
10
10
  preComputeUrl: false,
11
11
  variants: [],
12
- rename: true,
13
- meta: true
12
+ meta: true,
13
+ rename: true
14
14
  };
15
15
  export const defaultStateAttributeMixin = {
16
16
  attached: [],
@@ -18,3 +18,4 @@ export declare function createAttachmentAttributes(input: Input, name?: string):
18
18
  export declare function cleanObject(obj: any): any;
19
19
  export declare function clone(object: Object): any;
20
20
  export declare function use(module: string): Promise<any>;
21
+ export declare function bufferToTempFile(input: Buffer): Promise<string>;
@@ -4,6 +4,9 @@
4
4
  * @license MIT
5
5
  * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
6
6
  */
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import fs from 'fs/promises';
7
10
  import { cuid } from '@adonisjs/core/helpers';
8
11
  import string from '@adonisjs/core/helpers/string';
9
12
  import logger from '@adonisjs/core/services/logger';
@@ -61,9 +64,18 @@ export function clone(object) {
61
64
  export async function use(module) {
62
65
  try {
63
66
  const result = await import(module);
64
- return result.default;
67
+ if (result.default) {
68
+ return result.default;
69
+ }
70
+ return result;
65
71
  }
66
72
  catch (error) {
67
73
  logger.error({ err: error }, `Dependence missing, please install ${module}`);
68
74
  }
69
75
  }
76
+ export async function bufferToTempFile(input) {
77
+ const folder = os.tmpdir();
78
+ const tempFilePath = path.join(folder, `tempfile-${Date.now()}.tmp`);
79
+ await fs.writeFile(tempFilePath, input);
80
+ return tempFilePath;
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jrmc/adonis-attachment",
3
- "version": "2.1.1-1",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "Turn any field on your Lucid model to an attachment data type",
6
6
  "engines": {
@@ -82,7 +82,7 @@
82
82
  "prettier": "@adonisjs/prettier-config",
83
83
  "publishConfig": {
84
84
  "access": "public",
85
- "tag": "beta"
85
+ "tag": "latest"
86
86
  },
87
87
  "volta": {
88
88
  "node": "20.17.0"
@@ -1,7 +0,0 @@
1
- export {};
2
- /**
3
- * @jrmc/adonis-attachment
4
- *
5
- * @license MIT
6
- * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
7
- */
@@ -1,7 +0,0 @@
1
- export {};
2
- /**
3
- * @jrmc/adonis-attachment
4
- *
5
- * @license MIT
6
- * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
7
- */
@@ -1,7 +0,0 @@
1
- export {};
2
- /**
3
- * @jrmc/adonis-attachment
4
- *
5
- * @license MIT
6
- * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
7
- */
@@ -1,7 +0,0 @@
1
- export {};
2
- /**
3
- * @jrmc/adonis-attachment
4
- *
5
- * @license MIT
6
- * @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
7
- */