File size: 2,500 Bytes
d988ae4
 
 
 
 
 
 
 
56181a0
 
 
 
 
 
 
 
 
 
d988ae4
56181a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d988ae4
 
56181a0
 
 
 
d988ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Controller, Post, Body, Get, Param, HttpException, HttpStatus } from '@nestjs/common';
import { ClipboardService } from './clipboard.service';

@Controller('clipboard')
export class ClipboardController {
  constructor(private readonly clipboardService: ClipboardService) { }

  @Post('create')
  async createClipboard(@Body() body: { password?: string; roomCode?: string }) {
    const requestedRoomCode = body.roomCode?.trim().toUpperCase();

    if (requestedRoomCode && !/^[A-Z0-9]{4,6}$/.test(requestedRoomCode)) {
      throw new HttpException(
        'Invalid room code. Must be 4-6 alphanumeric characters.',
        HttpStatus.BAD_REQUEST,
      );
    }

    try {
      const roomCode = requestedRoomCode
        ? requestedRoomCode
        : await this.clipboardService.createClipboard(body.password);

      if (requestedRoomCode) {
        const created = await this.clipboardService.createClipboardWithCode(
          requestedRoomCode,
          body.password,
        );

        if (!created) {
          throw new HttpException('Room code already exists', HttpStatus.CONFLICT);
        }
      }

      return { roomCode };
    } catch (error) {
      if (error instanceof HttpException) {
        throw error;
      }

      throw new HttpException('Failed to create clipboard', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Get(':roomCode/exists')
  async clipboardExists(@Param('roomCode') roomCode: string) {
    const exists = await this.clipboardService.clipboardExists(roomCode);

    if (!exists) {
      return { exists: false, hasPassword: false };
    }

    // Get the clipboard to check if it has a password
    const clipboard = await this.clipboardService.getClipboard(roomCode);
    const hasPassword = clipboard?.password ? true : false;

    return { exists, hasPassword };
  }

  @Post(':roomCode/verify')
  async verifyPassword(
    @Param('roomCode') roomCode: string,
    @Body() body: { password: string },
  ) {
    const isValid = await this.clipboardService.verifyPassword(roomCode, body.password);

    if (!isValid) {
      throw new HttpException('Invalid password', HttpStatus.UNAUTHORIZED);
    }

    return { success: true };
  }

  @Post(':roomCode/refresh')
  async refreshExpiration(@Param('roomCode') roomCode: string) {
    const success = await this.clipboardService.refreshExpiration(roomCode);

    if (!success) {
      throw new HttpException('Clipboard not found', HttpStatus.NOT_FOUND);
    }

    return { success };
  }
}