File size: 3,649 Bytes
2756f0f
 
 
 
 
 
 
fe40b87
2756f0f
fe40b87
2756f0f
 
 
 
 
 
 
 
 
fe40b87
 
e980186
2756f0f
e980186
 
fe40b87
e980186
fe40b87
 
2756f0f
 
 
 
fe40b87
 
e980186
 
fe40b87
 
 
 
 
 
 
2756f0f
 
 
 
fe40b87
2756f0f
 
 
 
 
 
 
fe40b87
 
 
 
 
 
 
 
2756f0f
fe40b87
 
 
2756f0f
fe40b87
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Presigned uploads (D1). The object is verified later, when POST /sessions references the upload."""

import uuid
from datetime import UTC, datetime, timedelta

from sqlalchemy.ext.asyncio import AsyncSession

from app.common.academy_access import staff_context
from app.core.config import get_settings
from app.core.errors import Forbidden, TooLarge, ValidationFailed
from app.integrations.storage import StorageClient
from app.modules.accounts.models import Account
from app.modules.uploads.repository import UploadRepository
from app.modules.uploads.schemas import UploadIn, UploadOut

# kind -> {content_type: file extension}
ALLOWED_TYPES = {
    "video": {"video/mp4": "mp4", "video/quicktime": "mov"},
    "thumbnail": {"image/jpeg": "jpg"},
    "audio": {"audio/mp4": "m4a", "audio/aac": "aac", "audio/mpeg": "mp3"},
    "drill_video": {"video/mp4": "mp4", "video/quicktime": "mov"},
    "image": {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp"},  # chat photos
}
FOLDERS = {"video": "videos", "thumbnail": "thumbnails", "audio": "audio", "drill_video": "drill-videos",
           "image": "images"}
MAX_AUDIO_BYTES = 5 * 1024 * 1024
MAX_IMAGE_BYTES = 10 * 1024 * 1024
MAX_AUDIO_SECONDS = 120.0
MAX_DRILL_VIDEO_SECONDS = 300.0


def max_bytes(kind: str) -> int:
    settings = get_settings()
    if kind == "audio":
        return MAX_AUDIO_BYTES
    if kind == "image":
        return MAX_IMAGE_BYTES
    return settings.max_video_bytes if kind in ("video", "drill_video") else settings.max_thumbnail_bytes


def max_seconds(kind: str) -> float | None:
    settings = get_settings()
    return {"video": settings.max_video_seconds, "audio": MAX_AUDIO_SECONDS,
            "drill_video": MAX_DRILL_VIDEO_SECONDS}.get(kind)


class UploadService:
    def __init__(self, db: AsyncSession, storage: StorageClient):
        self.db = db
        self.uploads = UploadRepository(db)
        self.storage = storage

    async def create(self, account: Account, body: UploadIn) -> UploadOut:
        ext = ALLOWED_TYPES[body.kind].get(body.content_type)
        if ext is None:
            raise ValidationFailed(fields={"content_type": f"Not an accepted {body.kind} type."})
        if body.kind == "drill_video":
            staff = await staff_context(self.db, account)
            if staff is None:
                raise Forbidden("Only coaches can do this.")
            staff.require("library")
        limit = max_seconds(body.kind)
        if limit is not None:
            label = {"video": "a video", "audio": "an audio note", "drill_video": "a drill video"}[body.kind]
            if body.duration_sec is None:
                raise ValidationFailed(fields={"duration_sec": f"Required for {label}."})
            if body.duration_sec > limit:
                subject = "Clips" if body.kind == "video" else "This"
                raise ValidationFailed("Clip too long.", fields={
                    "duration_sec": f"{subject} can be at most {limit:g} seconds."})
        if body.size_bytes > max_bytes(body.kind):
            raise TooLarge()

        upload_id = uuid.uuid4()
        key = f"{FOLDERS[body.kind]}/{account.id}/{upload_id}.{ext}"
        await self.uploads.create(id=upload_id, owner_id=account.id, kind=body.kind, object_key=key,
                                  content_type=body.content_type, size_bytes=body.size_bytes)
        return UploadOut(
            upload_id=upload_id,
            url=self.storage.presign_put(key, body.content_type),
            headers={"Content-Type": body.content_type},
            expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.upload_ttl),
        )