# 미디어 저장

각 플랫폼의 `Save` 메서드는 받은 파일을 디렉터리에 다운로드하고 저장된 경로를 반환합니다.

## 시그니처

```go
// core/telegram — fileID는 Input.Photo[i].FileID 또는 Input.Document.FileID에서 가져옴
func (b *Bot) Save(ctx context.Context, fileID, dir string) (string, error)

// core/discord — Input.Attachments의 항목 하나
func (b *Bot) Save(ctx context.Context, att *discordgo.MessageAttachment, dir string) (string, error)

// core/line — image, video, audio, file 메시지의 Input.MessageID
func (b *Bot) Save(ctx context.Context, messageID, dir string) (string, error)
```

## 플랫폼별 동작

| | Telegram | Discord | LINE |
|---|---|---|---|
| 크기 상한 | 20 MiB(Bot API `getFile` 제한) | 25 MiB | 50 MiB(라이브러리 제한) |
| 다운로드 전 크기 확인 | `GetFile` → `FileSize` | `att.Size` | `ContentLength` |
| 다운로드 | `http.DefaultClient`로 `FileDownloadLink` | `http.DefaultClient`로 `att.URL` | `GetMessageContent` 스트림 |
| 확장자 | Telegram의 `file_path`에서 | `att.Filename`에서 | 응답의 `Content-Type`에서 |

## 공통 단계

1. 빈 인자(`fileID` / `att` / `att.URL` / `messageID`, 그리고 `dir`)를 거부합니다.
2. 보고된 크기가 상한을 넘으면 다운로드 전에 파일을 거부합니다.
3. HTTP 상태가 200이 아니면(Telegram, Discord) 본문을 최대 8 KiB 포함해 `http <code>: <body>`를 반환합니다.
4. `os.MkdirAll(dir, 0755)`로 `dir`을 만듭니다.
5. `dir` 안의 임시 파일 `<uuid>.*.tmp`로 스트리밍하며 최대 상한 + 1바이트까지 읽습니다. 상한보다 많은 데이터가 오면(보고된 크기가 없거나 틀린 경우) 임시 파일을 삭제하고 오류를 반환합니다. 상한을 넘는 파일을 잘라서 저장하는 일은 없습니다.
6. 임시 파일 이름을 `<uuid><ext>`로 바꾸고 전체 경로를 반환합니다.

파일 이름은 `go-pkg/utils`가 만든 v4 UUID입니다. UUID가 비어 있으면(난수 소스 실패) 오류로 반환됩니다. Telegram/Discord의 원래 파일 이름은 유지되지 않으며, LINE file 메시지의 원래 이름은 `Input.FileName`에 있습니다.

## LINE 확장자 매핑

`image/jpeg` → `.jpg`, `image/png` → `.png`, `image/gif` → `.gif`, `image/webp` → `.webp`, `video/mp4` → `.mp4`, `audio/mp4`와 `audio/x-m4a` → `.m4a`, `audio/aac` → `.aac`, `application/pdf` → `.pdf`. 그 밖의 타입은 `mime.ExtensionsByType`의 첫 번째 확장자를 사용하고, 알 수 없는 타입에는 확장자가 붙지 않습니다.

## 예시

```go
bot.Reply(func(ctx context.Context, in discord.Input) string {
    for _, att := range in.Attachments {
        path, err := bot.Save(ctx, att, "./uploads")
        if err != nil {
            return "save failed: " + err.Error()
        }
        log.Println("saved", path)
    }
    return ""
})
```

## 관련 페이지

- [Telegram 설정](/ko/telegram)(`Input.Photo`, `Input.Document`)
- [Discord 설정](/ko/discord)(`Input.Attachments`)
- [LINE 메시지](/ko/line-messages)(미디어 메시지 이벤트)
