File size: 2,306 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  Body,
  Controller,
  Post,
  UnprocessableEntityException,
  UseInterceptors,
} from '@nestjs/common';
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { SessionManager } from '@waha/core/abc/manager.abc';
import { WAMimeType } from '@waha/core/media/WAMimeType';
import { ApiFileAcceptHeader } from '@waha/nestjs/ApiFileAcceptHeader';
import {
  SessionApiParam,
  WorkingSessionParam,
} from '@waha/nestjs/params/SessionApiParam';
import {
  FileDTO,
  VideoFileDTO,
  VoiceFileDTO,
} from '@waha/structures/media.dto';

import { WhatsappSession } from '../core/abc/session.abc';
import { BufferResponseInterceptor } from '../nestjs/BufferResponseInterceptor';

@ApiSecurity('api_key')
@Controller('api/:session/media')
@ApiTags('🖼️ Media')
class MediaController {
  constructor(private manager: SessionManager) {}

  @Post('convert/voice')
  @ApiOperation({
    summary: 'Convert voice to WhatsApp format (opus)',
  })
  @SessionApiParam
  @UseInterceptors(
    new BufferResponseInterceptor(WAMimeType.VOICE, 'output.opus'),
  )
  @ApiFileAcceptHeader(WAMimeType.VOICE)
  async convertVoice(
    @WorkingSessionParam session: WhatsappSession,
    @Body() file: VoiceFileDTO,
  ): Promise<Buffer> {
    const data = await this.buffer(session, file);
    const content = await session.mediaConverter.voice(data);
    return content;
  }

  @Post('convert/video')
  @ApiOperation({
    summary: 'Convert video to WhatsApp format (mp4)',
  })
  @SessionApiParam
  @UseInterceptors(
    new BufferResponseInterceptor(WAMimeType.VIDEO, 'output.mp4'),
  )
  @ApiFileAcceptHeader(WAMimeType.VIDEO)
  async convertVideo(
    @WorkingSessionParam session: WhatsappSession,
    @Body() file: VideoFileDTO,
  ): Promise<Buffer> {
    const data = await this.buffer(session, file);
    const content = await session.mediaConverter.video(data);
    return content;
  }

  private async buffer(
    session: WhatsappSession,
    file: FileDTO,
  ): Promise<Buffer> {
    if ('url' in file) {
      return session.fetch(file.url);
    } else if ('data' in file) {
      return Buffer.from(file.data, 'base64');
    } else {
      throw new UnprocessableEntityException(
        'Either "url" or "data" must be specified.',
      );
    }
  }
}

export { MediaController };