File size: 6,874 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Threads and messages, plus the reads the thread views need from accounts, sessions, reviews and uploads."""

from collections.abc import Sequence
from datetime import datetime
from uuid import UUID

from sqlalchemy import Select, and_, func, or_, select, tuple_, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import aliased

from app.common.base_repository import BaseRepository
from app.common.names import account_names
from app.modules.reviews.models import Review
from app.modules.sessions.models import SwingSession
from app.modules.threads.models import Message, Thread
from app.modules.uploads.models import Upload


class ThreadRepository(BaseRepository[Thread]):
    model = Thread

    async def locked(self, thread_id: UUID) -> Thread | None:
        return await self.session.scalar(select(Thread).where(Thread.id == thread_id).with_for_update())

    async def for_session(self, session_id: UUID) -> Thread | None:
        return await self.session.scalar(select(Thread).where(Thread.session_id == session_id))

    async def general(self, player_id: UUID, coach_id: UUID, mode: str) -> Thread | None:
        return await self.session.scalar(select(Thread).where(
            Thread.player_id == player_id, Thread.coach_id == coach_id, Thread.mode == mode,
            Thread.session_id.is_(None)))

    async def create_general(self, **values) -> Thread | None:
        """None when a concurrent request created it first (partial unique index)."""
        return await self.session.scalar(
            insert(Thread).values(session_id=None, **values).on_conflict_do_nothing().returning(Thread))

    def list_query(self, *, player_id: UUID, staff_id: UUID | None, team_id: UUID | None,
                   visible: Select | None, mode: str | None,
                   filter_player_id: UUID | None, unread: bool | None, cursor_at: datetime | None,
                   cursor_id: UUID | None, limit: int) -> Select:
        access = [Thread.player_id == player_id]
        if staff_id is not None:
            if visible is not None:
                access.append(and_(Thread.team_id == team_id, Thread.player_id.in_(visible)))
        query = select(Thread).where(or_(*access))
        if mode:
            query = query.where(Thread.mode == mode)
        if filter_player_id:
            query = query.where(Thread.player_id == filter_player_id)
        if unread is not None:
            has_unread = or_(and_(Thread.player_id == player_id, Thread.last_seq > Thread.player_read_seq),
                             and_(Thread.player_id != player_id, Thread.last_seq > Thread.coach_read_seq))
            query = query.where(has_unread if unread else ~has_unread)
        if cursor_at is not None and cursor_id is not None:
            query = query.where(tuple_(Thread.updated_at, Thread.id) < tuple_(cursor_at, cursor_id))
        return query.order_by(Thread.updated_at.desc(), Thread.id.desc()).limit(limit)

    async def run(self, query: Select) -> Sequence[Thread]:
        return (await self.session.scalars(query)).all()

    async def latest_messages(self, thread_ids: list[UUID], per_thread: int,
                              before_seq: int | None = None) -> dict[UUID, list[Message]]:
        """Newest `per_thread` messages of each thread, returned oldest first."""
        rank = func.row_number().over(partition_by=Message.thread_id, order_by=Message.seq.desc()).label("rank")
        inner = select(Message.id, rank).where(Message.thread_id.in_(thread_ids))
        if before_seq is not None:
            inner = inner.where(Message.seq < before_seq)
        ranked = inner.subquery()
        rows = (await self.session.scalars(
            select(Message).join(ranked, ranked.c.id == Message.id).where(ranked.c.rank <= per_thread)
            .order_by(Message.thread_id, Message.seq))).all()
        grouped: dict[UUID, list[Message]] = {t: [] for t in thread_ids}
        for message in rows:
            grouped[message.thread_id].append(message)
        return grouped

    async def message(self, message_id: UUID) -> Message | None:
        return await self.session.get(Message, message_id)

    async def add_message(self, **values) -> Message:
        message = Message(**values)
        self.session.add(message)
        await self.session.flush()
        await self.session.refresh(message)
        return message

    async def advance_read(self, thread_id: UUID, side: str, seq: int) -> None:
        column = Thread.player_read_seq if side == "player" else Thread.coach_read_seq
        await self.session.execute(
            update(Thread).where(Thread.id == thread_id).values({column.key: func.greatest(column, seq)}))

    async def names(self, ids: set[UUID]) -> dict[UUID, str]:
        return {i: n or "" for i, n in (await account_names(self.session, ids)).items()}

    async def session_row(self, session_id: UUID) -> SwingSession | None:
        return await self.session.get(SwingSession, session_id)

    async def session_infos(self, session_ids: set[UUID]) -> dict[UUID, tuple[SwingSession, int]]:
        """Each live session with its 1-based ordinal among the owner's analysed reps of the same mode and athlete."""
        if not session_ids:
            return {}
        earlier = aliased(SwingSession)
        ordinal = (select(func.count()).select_from(earlier).where(
            earlier.owner_id == SwingSession.owner_id, earlier.mode == SwingSession.mode,
            earlier.athlete["name"].astext == SwingSession.athlete["name"].astext, earlier.deleted_at.is_(None),
            earlier.analyzed_at.is_not(None), earlier.created_at <= SwingSession.created_at,
            earlier.id != SwingSession.id).correlate(SwingSession).scalar_subquery())
        rows = await self.session.execute(select(SwingSession, ordinal + 1).where(
            SwingSession.id.in_(session_ids), SwingSession.deleted_at.is_(None)))
        return {s.id: (s, n) for s, n in rows.all()}

    async def reviews(self, session_ids: set[UUID]) -> dict[UUID, Review]:
        if not session_ids:
            return {}
        rows = await self.session.scalars(select(Review).where(Review.session_id.in_(session_ids)))
        return {r.session_id: r for r in rows}

    async def uploads(self, ids: set[UUID]) -> dict[UUID, Upload]:
        if not ids:
            return {}
        return {u.id: u for u in await self.session.scalars(select(Upload).where(Upload.id.in_(ids)))}

    async def upload_in_use(self, upload_id: UUID) -> bool:
        """Backstop for rows attached before attached_at was reliably set."""
        used = await self.session.scalar(select(Message.id).where(Message.upload_id == upload_id).limit(1))
        if used is None:
            used = await self.session.scalar(select(Review.session_id).where(Review.voice_upload_id == upload_id))
        return used is not None