Passed
Push — master ( d29cbb...0943a5 )
by Jochen
02:31
created

byceps.services.tourney.avatar.models.Avatar.url_path()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
"""
2
byceps.services.tourney.avatar.models
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from datetime import datetime
10
from pathlib import Path
11
from typing import NewType
12
from uuid import UUID
13
14
from flask import current_app
15
from sqlalchemy.ext.hybrid import hybrid_property
16
17
from ....database import db, generate_uuid
18
from ....typing import PartyID, UserID
19
from ....util.image.models import ImageType
20
from ....util.instances import ReprBuilder
21
22
23
AvatarID = NewType('AvatarID', UUID)
24
25
26
class Avatar(db.Model):
27
    """A tourney-related avatar image uploaded by a user."""
28
29
    __tablename__ = 'tourney_avatars'
30
31
    id = db.Column(db.Uuid, default=generate_uuid, primary_key=True)
32
    party_id = db.Column(db.UnicodeText, db.ForeignKey('parties.id'), index=True, nullable=False)
33
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
34
    creator_id = db.Column(db.Uuid, db.ForeignKey('users.id'), nullable=False)
35
    _image_type = db.Column('image_type', db.UnicodeText, nullable=False)
36
37
    def __init__(
38
        self, party_id: PartyID, creator_id: UserID, image_type: ImageType
39
    ) -> None:
40
        self.party_id = party_id
41
        self.creator_id = creator_id
42
        self.image_type = image_type
43
44
    @hybrid_property
45
    def image_type(self) -> ImageType:
46
        image_type_str = self._image_type
47
        if image_type_str is not None:
48
            return ImageType[image_type_str]
49
50
    @image_type.setter
51
    def image_type(self, image_type: ImageType) -> None:
52
        self._image_type = image_type.name if (image_type is not None) else None
53
54
    @property
55
    def filename(self) -> Path:
56
        name_without_suffix = str(self.id)
57
        suffix = '.' + self.image_type.name
58
        return Path(name_without_suffix).with_suffix(suffix)
59
60
    @property
61
    def path(self) -> Path:
62
        path = current_app.config['PATH_TOURNEY_AVATAR_IMAGES']
63
        return path / self.filename
64
65
    @property
66
    def url_path(self) -> str:
67
        return f'/party/tourney/avatars/{self.filename}'
68
69
    def __repr__(self) -> str:
70
        return ReprBuilder(self) \
71
            .add_with_lookup('id') \
72
            .add('party', self.party_id) \
73
            .add('image_type', self.image_type.name) \
74
            .build()
75