66from sqlalchemy .orm import Session
77from sqlalchemy .sql import func
88
9- from couchers .context import CouchersContext , make_background_user_context
9+ from couchers .context import CouchersContext , make_background_user_context , make_logged_out_context
1010from couchers .db import session_scope
11+ from couchers .i18n import LocalizationContext
1112from couchers .jobs .enqueue import queue_job
1213from couchers .models import (
1314 Comment ,
3132
3233logger = logging .getLogger (__name__ )
3334
34- # Since the API exposes a single ID space regardless of nesting level,
35- # we construct the API id by appending the nesting level to the
36- # database ID.
37-
3835
3936def pack_thread_id (database_id : int , depth : int ) -> int :
37+ """Pack (database_id, depth) into a single API thread id.
38+
39+ The API exposes a single ID space regardless of nesting level, so we append
40+ the nesting level (depth) as the trailing digit of the database id: depth 0
41+ = Thread, depth 1 = Comment, depth 2 = Reply.
42+ """
4043 return database_id * 10 + depth
4144
4245
4346def unpack_thread_id (thread_id : int ) -> tuple [int , int ]:
44- """Returns (database_id, depth) tuple ."""
47+ """Inverse of pack_thread_id; returns (database_id, depth)."""
4548 return divmod (thread_id , 10 )
4649
4750
48- def total_num_responses (session : Session , context : CouchersContext , database_id : int ) -> int :
51+ def _viewing_context (viewing_user_id : int | None ) -> CouchersContext :
52+ if viewing_user_id is not None :
53+ return make_background_user_context (user_id = viewing_user_id )
54+ return make_logged_out_context (LocalizationContext .en_utc ())
55+
56+
57+ def total_num_responses (session : Session , viewing_user_id : int | None , database_id : int ) -> int :
58+ context = _viewing_context (viewing_user_id )
4959 comments = where_moderated_content_visible (
5060 select (func .count ()).select_from (Comment ).where (Comment .thread_id == database_id ),
5161 context ,
@@ -64,10 +74,10 @@ def total_num_responses(session: Session, context: CouchersContext, database_id:
6474 return session .execute (comments ).scalar_one () + session .execute (replies ).scalar_one ()
6575
6676
67- def thread_to_pb (session : Session , context : CouchersContext , database_id : int ) -> threads_pb2 .Thread :
77+ def thread_to_pb (session : Session , viewing_user_id : int | None , database_id : int ) -> threads_pb2 .Thread :
6878 return threads_pb2 .Thread (
6979 thread_id = pack_thread_id (database_id , 0 ),
70- num_responses = total_num_responses (session , context , database_id ),
80+ num_responses = total_num_responses (session , viewing_user_id , database_id ),
7181 )
7282
7383
0 commit comments