~homeworkprod/byceps

ref: a3214d27456b4060727966ca1ad520a92edaa6b2 byceps/byceps/services/tourney/avatar/models.py -rw-r--r-- 2.3 KiB
a3214d27 — Jochen Kupperschmidt Make tourney avatar path depend on party path, but non-configurable besides that 1 year, 11 months ago
                                                                                
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
"""
byceps.services.tourney.avatar.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from datetime import datetime
from pathlib import Path
from typing import NewType
from uuid import UUID

from flask import current_app
from sqlalchemy.ext.hybrid import hybrid_property

from ....database import db, generate_uuid
from ....typing import PartyID, UserID
from ....util.image.models import ImageType
from ....util.instances import ReprBuilder


AvatarID = NewType('AvatarID', UUID)


class Avatar(db.Model):
    """A tourney-related avatar image uploaded by a user."""

    __tablename__ = 'tourney_avatars'

    id = db.Column(db.Uuid, default=generate_uuid, primary_key=True)
    party_id = db.Column(db.UnicodeText, db.ForeignKey('parties.id'), index=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    creator_id = db.Column(db.Uuid, db.ForeignKey('users.id'), nullable=False)
    _image_type = db.Column('image_type', db.UnicodeText, nullable=False)

    def __init__(
        self, party_id: PartyID, creator_id: UserID, image_type: ImageType
    ) -> None:
        self.party_id = party_id
        self.creator_id = creator_id
        self.image_type = image_type

    @hybrid_property
    def image_type(self) -> ImageType:
        image_type_str = self._image_type
        if image_type_str is not None:
            return ImageType[image_type_str]

    @image_type.setter
    def image_type(self, image_type: ImageType) -> None:
        self._image_type = image_type.name if (image_type is not None) else None

    @property
    def filename(self) -> Path:
        name_without_suffix = str(self.id)
        suffix = '.' + self.image_type.name
        return Path(name_without_suffix).with_suffix(suffix)

    @property
    def path(self) -> Path:
        path = current_app.config['PATH_PARTY'] / 'tourney' / 'avatars'
        return path / self.filename

    @property
    def url_path(self) -> str:
        return f'/party/tourney/avatars/{self.filename}'

    def __repr__(self) -> str:
        return ReprBuilder(self) \
            .add_with_lookup('id') \
            .add('party', self.party_id) \
            .add('image_type', self.image_type.name) \
            .build()