Coverage for src/copytrading_engine/sources/source.py: 100%

61 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Translate Discord objects without involving persistence or publication.""" 

2 

3from urllib.parse import unquote, urlsplit 

4 

5import discord 

6from pydantic import JsonValue, ValidationError 

7 

8from copytrading_engine.shared.raw_message import RawMessage 

9from copytrading_engine.sources.application import AttachmentReference 

10from copytrading_engine.sources.attachments import discord_host 

11from copytrading_engine.sources.evidence import MAX_ATTACHMENTS_PER_MESSAGE 

12 

13 

14class InvalidSourceMessage(ValueError): 

15 def __init__(self, event: dict[str, JsonValue], reason: str) -> None: 

16 super().__init__(reason) 

17 self.event = event 

18 self.reason = reason 

19 

20 

21def envelope(message: discord.Message) -> RawMessage: 

22 parts = [message.content or ""] 

23 for embed in message.embeds: 

24 parts.extend([embed.title or "", embed.description or ""]) 

25 for field in embed.fields: 

26 parts.extend([field.name or "", field.value or ""]) 

27 event: dict[str, JsonValue] = { 

28 "schema_version": 1, 

29 "event_type": "raw_message", 

30 "source": "discord", 

31 "channel_id": str(message.channel.id), 

32 "author_id": str(message.author.id), 

33 "id": str(message.id), 

34 "timestamp": message.created_at.isoformat(), 

35 "text": "\n".join(part for part in parts if part), 

36 "image_count": len(message.attachments), 

37 } 

38 try: 

39 return RawMessage.model_validate(event) 

40 except ValidationError: 

41 reason = "text_too_long" if len(str(event["text"])) > 10_000 else "invalid_raw_message" 

42 raise InvalidSourceMessage(event, reason) from None 

43 

44 

45def attachment_references(message: discord.Message) -> tuple[AttachmentReference, ...]: 

46 """Return bounded source-adapter attachment references; callers never persist URLs.""" 

47 result = [] 

48 for attachment in message.attachments: 

49 size = getattr(attachment, "size", 0) 

50 result.append( 

51 AttachmentReference( 

52 attachment_id=str(getattr(attachment, "id", "")), 

53 filename=str(getattr(attachment, "filename", "")), 

54 content_type=( 

55 str(attachment.content_type) 

56 if getattr(attachment, "content_type", None) is not None 

57 else None 

58 ), 

59 declared_size=size if type(size) is int else -1, 

60 url=str(getattr(attachment, "url", "")), 

61 ) 

62 ) 

63 result.extend(_embed_pictures(message)) 

64 return tuple(result) 

65 

66 

67def _embed_pictures(message: discord.Message) -> list[AttachmentReference]: 

68 """A relay can post a picture inside an embed instead of attaching it; keep it as evidence too. 

69 A link preview's thumbnail is the linked site's, so only an image embed's thumbnail counts.""" 

70 result = [] 

71 for index, embed in enumerate(message.embeds, start=1): 

72 kinds = ("image", "thumbnail") if getattr(embed, "type", None) == "image" else ("image",) 

73 for kind in kinds: 

74 url = _picture_url(getattr(embed, kind, None)) 

75 if url is None: 

76 continue 

77 # Discord's proxy path ends in the whole original address, signed query and all; 

78 # keep only that address's file name. 

79 name = urlsplit(unquote(urlsplit(url).path)).path.rsplit("/", 1)[-1] 

80 result.append( 

81 AttachmentReference( 

82 attachment_id=f"embed-{index}-{kind}", 

83 filename=name or "picture", 

84 content_type=None, 

85 # Discord states no size for an embed picture; the download cap still holds. 

86 declared_size=0, 

87 url=url, 

88 ) 

89 ) 

90 return result 

91 

92 

93def _picture_url(picture: object) -> str | None: 

94 """The picture's Discord-hosted address: its own, else Discord's proxy copy. Any other address 

95 is kept so the capture records it as rejected rather than silently dropping the picture.""" 

96 url, proxy = getattr(picture, "url", None), getattr(picture, "proxy_url", None) 

97 for candidate in (url, proxy): 

98 if isinstance(candidate, str) and discord_host(urlsplit(candidate).hostname): 

99 return candidate 

100 return url if isinstance(url, str) and url else None 

101 

102 

103def adapter_event(message: discord.Message) -> dict[str, JsonValue]: 

104 """Capture the received Discord text/embed/attachment metadata before normalization.""" 

105 references = attachment_references(message) 

106 embeds: list[JsonValue] = [] 

107 for embed in message.embeds: 

108 fields: list[JsonValue] = [ 

109 { 

110 "name": str(field.name or ""), 

111 "value": str(field.value or ""), 

112 "inline": bool(getattr(field, "inline", False)), 

113 } 

114 for field in embed.fields 

115 ] 

116 pictures: list[JsonValue] = [ 

117 { 

118 "kind": kind, 

119 "width": getattr(picture, "width", None), 

120 "height": getattr(picture, "height", None), 

121 } 

122 for kind in ("image", "thumbnail", "video") 

123 if getattr(picture := getattr(embed, kind, None), "url", None) 

124 ] 

125 embeds.append( 

126 { 

127 "type": str(getattr(embed, "type", None) or "rich"), 

128 "title": str(embed.title) if embed.title is not None else None, 

129 "description": str(embed.description) if embed.description is not None else None, 

130 "fields": fields, 

131 "pictures": pictures, 

132 } 

133 ) 

134 attachments: list[JsonValue] = [ 

135 { 

136 "attachment_id": reference.attachment_id, 

137 "filename": reference.filename, 

138 "content_type": reference.content_type, 

139 "declared_size": reference.declared_size, 

140 } 

141 for reference in references[:MAX_ATTACHMENTS_PER_MESSAGE] 

142 ] 

143 return { 

144 "event_type": "discord_message", 

145 "message_id": str(message.id), 

146 "channel_id": str(message.channel.id), 

147 "author_id": str(message.author.id), 

148 "timestamp": message.created_at.isoformat(), 

149 "content": str(message.content or ""), 

150 "embeds": embeds, 

151 "attachments": attachments, 

152 "attachments_omitted": max(0, len(references) - MAX_ATTACHMENTS_PER_MESSAGE), 

153 } 

154 

155 

156def require_history_channel(channel: object) -> discord.abc.Messageable: 

157 if not isinstance(channel, discord.abc.Messageable): 

158 raise ValueError("Configured source channel does not support message history") 

159 return channel