Debian Codegraph @

pkg/services/chat/signal/signal_payload.go

raw
1 package signal
2
3 import "strings"
4
5 // createPayload builds the JSON payload for POST /v2/send.
6 //
7 // Parameters:
8 // - message: the message text
9 // - config: the service configuration
10 //
11 // Returns:
12 // - sendMessagePayload: the payload struct to be sent
13 func createPayload(message string, config *Config) sendMessagePayload {
14 payload := sendMessagePayload{
15 Message: composeMessage(config.Title, message, config.TextMode == TextModeStyled),
16 Number: config.Source,
17 Recipients: apiRecipients(config.Recipients),
18 Base64Attachments: parseAttachments(config.Attachments),
19 TextMode: config.TextMode.payloadValue(),
20 }
21
22 if !config.NotifySelf {
23 payload.NotifySelf = new(false)
24 }
25
26 return payload
27 }
28
29 // composeMessage prepends an optional title to the message body.
30 //
31 // Parameters:
32 // - title: the optional title
33 // - message: the message body
34 // - styled: whether styled markup should wrap the title
35 //
36 // Returns:
37 // - string: the composed message
38 func composeMessage(title, message string, styled bool) string {
39 if title == "" {
40 return message
41 }
42
43 heading := title
44 if styled {
45 heading = "**" + title + "**"
46 }
47
48 if message == "" {
49 return heading
50 }
51
52 return heading + "\n" + message
53 }
54
55 // parseAttachments splits a config attachments value into API attachment strings.
56 //
57 // Parameters:
58 // - raw: comma-separated raw base64, or a single data URI
59 //
60 // Returns:
61 // - []string: attachment entries, or nil when empty
62 //
63 // apiRecipients maps URL recipients to REST API recipient strings.
64 // Username values keep the u: prefix for URL parsing and drop it in the payload.
65 //
66 // Parameters:
67 // - recipients: parsed URL recipients
68 //
69 // Returns:
70 // - []string: recipients suitable for POST /v2/send
71 func apiRecipients(recipients []string) []string {
72 out := make([]string, len(recipients))
73
74 for i, recipient := range recipients {
75 if rest, ok := strings.CutPrefix(recipient, usernamePrefix); ok && rest != "" {
76 out[i] = rest
77
78 continue
79 }
80
81 out[i] = recipient
82 }
83
84 return out
85 }
86
87 func parseAttachments(raw string) []string {
88 raw = strings.TrimSpace(raw)
89 if raw == "" {
90 return nil
91 }
92
93 if strings.Contains(raw, "data:") {
94 return []string{raw}
95 }
96
97 parts := strings.Split(raw, ",")
98 attachments := make([]string, 0, len(parts))
99
100 for _, part := range parts {
101 part = strings.TrimSpace(part)
102 if part != "" {
103 attachments = append(attachments, part)
104 }
105 }
106
107 if len(attachments) == 0 {
108 return nil
109 }
110
111 return attachments
112 }