Coverage for dao/moderation_dao.py: 27.59%

77 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 20:17 +0000

1"""Moderation DAO for live match chat (SB-1309). 

2 

3Three things App Store guideline 1.2 asks of user-generated content, beyond 

4the word filter in services/content_filter.py: 

5 

6- **Report** — content_reports, one row per (message, reporter). The message 

7 text, author and match are copied onto the row because chat messages are 

8 hard-deleted when they expire. 

9- **Block** — user_blocks. The read endpoints drop a blocked author's events 

10 for the blocker. 

11- **Eject** — user_profiles.chat_banned_at. A banned user cannot post. 

12 

13All three tables are service-key only (RLS on, no client grants), so every 

14access goes through here. 

15""" 

16 

17from __future__ import annotations 

18 

19from datetime import UTC, datetime 

20 

21import structlog 

22 

23from dao.base_dao import BaseDAO 

24 

25logger = structlog.get_logger() 

26 

27REPORTS = "content_reports" 

28BLOCKS = "user_blocks" 

29 

30# Postgres unique_violation: a repeated report or block is not an error. 

31_UNIQUE_VIOLATION = "23505" 

32# Postgres foreign_key_violation: the user being blocked does not exist. 

33_FOREIGN_KEY_VIOLATION = "23503" 

34 

35 

36class UnknownUserError(Exception): 

37 """The user being blocked has no profile.""" 

38 

39 

40def _is_pg_error(exc: Exception, code: str) -> bool: 

41 return getattr(exc, "code", None) == code or code in str(exc) 

42 

43 

44class ModerationDAO(BaseDAO): 

45 """Data access for chat reports, blocks and bans.""" 

46 

47 # ------------------------------------------------------------------ 

48 # Blocks 

49 # ------------------------------------------------------------------ 

50 

51 def block_user(self, blocker_id: str, blocked_id: str) -> None: 

52 """Block `blocked_id` for `blocker_id`. Idempotent. 

53 

54 Raises UnknownUserError when `blocked_id` has no profile. 

55 """ 

56 try: 

57 self.client.table(BLOCKS).insert({"blocker_id": blocker_id, "blocked_id": blocked_id}).execute() 

58 except Exception as exc: 

59 if _is_pg_error(exc, _UNIQUE_VIOLATION): 

60 return 

61 if _is_pg_error(exc, _FOREIGN_KEY_VIOLATION): 

62 raise UnknownUserError(blocked_id) from exc 

63 raise 

64 logger.info("user_blocked", blocker_id=blocker_id, blocked_id=blocked_id) 

65 

66 def unblock_user(self, blocker_id: str, blocked_id: str) -> None: 

67 """Remove a block. Idempotent: no row is not an error.""" 

68 self.client.table(BLOCKS).delete().eq("blocker_id", blocker_id).eq("blocked_id", blocked_id).execute() 

69 logger.info("user_unblocked", blocker_id=blocker_id, blocked_id=blocked_id) 

70 

71 def list_blocks(self, blocker_id: str) -> list[dict]: 

72 """The users `blocker_id` has blocked, newest first, with usernames. 

73 

74 A blocked user whose profile is gone keeps its row (the FK cascades, 

75 so in practice it cannot) and reports username None. 

76 """ 

77 rows = ( 

78 self.client.table(BLOCKS) 

79 .select("blocked_id, created_at") 

80 .eq("blocker_id", blocker_id) 

81 .order("created_at", desc=True) 

82 .execute() 

83 ).data or [] 

84 if not rows: 

85 return [] 

86 

87 ids = [r["blocked_id"] for r in rows] 

88 profiles = (self.client.table("user_profiles").select("id, username").in_("id", ids).execute()).data or [] 

89 usernames = {p["id"]: p.get("username") for p in profiles} 

90 return [ 

91 {"user_id": r["blocked_id"], "username": usernames.get(r["blocked_id"]), "created_at": r["created_at"]} 

92 for r in rows 

93 ] 

94 

95 def blocked_user_ids(self, blocker_id: str) -> list[str]: 

96 """Ids `blocker_id` has blocked. Empty on error: hiding is best effort, 

97 and a failed lookup must not take the live view down with it.""" 

98 try: 

99 rows = self.client.table(BLOCKS).select("blocked_id").eq("blocker_id", blocker_id).execute().data or [] 

100 return [r["blocked_id"] for r in rows] 

101 except Exception: 

102 logger.exception("blocked_user_ids_failed", blocker_id=blocker_id) 

103 return [] 

104 

105 # ------------------------------------------------------------------ 

106 # Bans 

107 # ------------------------------------------------------------------ 

108 

109 def is_chat_banned(self, user_id: str) -> bool: 

110 """Whether an admin has removed this user from chat. 

111 

112 False on error, logged: a failed lookup (or the column not yet 

113 migrated) must not take chat down for everyone. The filter, reports 

114 and blocks still apply. 

115 """ 

116 try: 

117 rows = self.client.table("user_profiles").select("chat_banned_at").eq("id", user_id).limit(1).execute().data 

118 except Exception: 

119 logger.exception("is_chat_banned_failed", user_id=user_id) 

120 return False 

121 return bool(rows and rows[0].get("chat_banned_at")) 

122 

123 def ban_from_chat(self, user_id: str) -> None: 

124 """Set chat_banned_at, keeping the first ban's timestamp.""" 

125 ( 

126 self.client.table("user_profiles") 

127 .update({"chat_banned_at": datetime.now(UTC).isoformat()}) 

128 .eq("id", user_id) 

129 .is_("chat_banned_at", "null") 

130 .execute() 

131 ) 

132 logger.info("user_chat_banned", user_id=user_id) 

133 

134 # ------------------------------------------------------------------ 

135 # Reports 

136 # ------------------------------------------------------------------ 

137 

138 def create_report( 

139 self, 

140 *, 

141 event: dict, 

142 reporter_id: str, 

143 reason: str, 

144 details: str | None, 

145 ) -> dict | None: 

146 """Record a report of a chat message. 

147 

148 Returns the new row, or None when this reporter has already reported 

149 this message (the unique key makes a repeat a no-op). 

150 """ 

151 row = { 

152 "event_id": event["id"], 

153 "match_id": event["match_id"], 

154 "reporter_id": reporter_id, 

155 "reported_user_id": event.get("created_by"), 

156 "reported_username": event.get("created_by_username"), 

157 "message_text": event.get("message") or "", 

158 "reason": reason, 

159 "details": details, 

160 } 

161 try: 

162 response = self.client.table(REPORTS).insert(row).execute() 

163 except Exception as exc: 

164 if _is_pg_error(exc, _UNIQUE_VIOLATION): 

165 return None 

166 raise 

167 return response.data[0] if response.data else None 

168 

169 def list_reports(self, status: str | None = None, limit: int = 100) -> list[dict]: 

170 """Reports, newest first, optionally filtered by status.""" 

171 query = self.client.table(REPORTS).select("*").order("created_at", desc=True).limit(limit) 

172 if status: 

173 query = query.eq("status", status) 

174 return query.execute().data or [] 

175 

176 def get_report(self, report_id: int) -> dict | None: 

177 rows = self.client.table(REPORTS).select("*").eq("id", report_id).limit(1).execute().data 

178 return rows[0] if rows else None 

179 

180 def resolve_report(self, report_id: int, *, status: str, action: str, resolved_by: str) -> dict | None: 

181 response = ( 

182 self.client.table(REPORTS) 

183 .update( 

184 { 

185 "status": status, 

186 "action": action, 

187 "resolved_by": resolved_by, 

188 "resolved_at": datetime.now(UTC).isoformat(), 

189 } 

190 ) 

191 .eq("id", report_id) 

192 .execute() 

193 ) 

194 return response.data[0] if response.data else None 

195 

196 def count_pending_reports(self) -> int: 

197 response = self.client.table(REPORTS).select("id", count="exact").eq("status", "pending").execute() 

198 return response.count or 0 

199 

200 def count_reports_since(self, since_iso: str) -> int: 

201 """Reports created since `since_iso` — the alert cap's window.""" 

202 response = self.client.table(REPORTS).select("id", count="exact").gte("created_at", since_iso).execute() 

203 return response.count or 0