15 // whatsappStateFileName is the state file in the WhatsApp directory:
16 // the batches that are not in the log yet and the records of the sends.
17 whatsappStateFileName = "state.json"
19 // whatsappBatchQuiet is how long a chat is quiet before its batch
21 whatsappBatchQuiet = 20 * time.Second
23 // whatsappBatchWindow is the longest time of a batch.
24 whatsappBatchWindow = 2 * time.Minute
26 // whatsappBatchMessages is the most messages of a batch.
27 whatsappBatchMessages = 50
29 // whatsappSendRecords is the most send records that the state file
31 whatsappSendRecords = 1000
34 // openWhatsAppState reads the batches and the send records of the state file at
35 // path. A missing file holds none. A batch closes after quiet with no message,
36 // or after window at the latest.
37 func openWhatsAppState(path string, quiet, window time.Duration) (*WhatsAppState, error) {
44 data, err := os.ReadFile(path)
45 if errors.Is(err, os.ErrNotExist) {
50 return nil, fmt.Errorf("read WhatsApp state: %w", err)
53 err = json.Unmarshal(data, &s.file)
55 return nil, fmt.Errorf("%s: %w", path, err)
61 // WhatsAppState holds the state file: the send records, and the batches of the
62 // WhatsApp messages that are not in the log yet, open and closed, in the order
63 // of their first message. The messages of one chat form one batch while the
64 // times of the messages are at most quiet apart, at most window after the
65 // first, and the batch has fewer than whatsappBatchMessages messages. The times
66 // are the WhatsApp times, so a catch-up after a stop gives the same batches as
67 // live messages. A batch also closes when quiet passes after the arrival of its
68 // last message, or window after the arrival of its first message, in real time.
70 // A send record keeps the result of a send by its ID, so that a repeated call
71 // of the send tool does not send again. The state file keeps the last
72 // whatsappSendRecords records.
74 // Each change writes the state file whole, so the batches and the records
75 // survive a restart. The mutex protects them, because the event handler of the
76 // library adds messages while Run closes and removes batches, and the turns
78 type WhatsAppState struct {
84 file WhatsAppStateFile
87 // Add puts message of chat into the open batch of chat, or into a new batch,
88 // with arrival as its time of arrival. A message that the batch holds already,
89 // which the servers sent again, changes nothing. It returns true when a batch
91 func (s *WhatsAppState) Add(chat WhatsAppChat, message WhatsAppMessage, arrival time.Time) (bool, error) {
93 defer s.mutex.Unlock()
96 index := s.open(chat.ID)
98 batch := &s.file.Batches[index]
99 if slices.ContainsFunc(batch.Messages, func(held WhatsAppMessage) bool {
100 return held.ID == message.ID
105 if message.Time.Sub(batch.Messages[len(batch.Messages)-1].Time) > s.quiet || message.Time.Sub(batch.Messages[0].Time) > s.window {
114 s.file.Batches = append(s.file.Batches, WhatsAppBatch{
119 index = len(s.file.Batches) - 1
122 batch := &s.file.Batches[index]
123 batch.Messages = append(batch.Messages, message)
125 if len(batch.Messages) >= whatsappBatchMessages {
130 return closed, s.save()
133 // CloseDue closes each open batch whose time is up at now and tells if one
135 func (s *WhatsAppState) CloseDue(now time.Time) (bool, error) {
137 defer s.mutex.Unlock()
140 for index := range s.file.Batches {
141 batch := &s.file.Batches[index]
142 if !batch.Closed && !now.Before(s.deadline(*batch)) {
152 return true, s.save()
155 // CloseAll closes every open batch.
156 func (s *WhatsAppState) CloseAll() error {
158 defer s.mutex.Unlock()
160 for index := range s.file.Batches {
161 s.file.Batches[index].Closed = true
167 // Closed returns the closed batches in order.
168 func (s *WhatsAppState) Closed() []WhatsAppBatch {
170 defer s.mutex.Unlock()
172 var closed []WhatsAppBatch
174 for _, batch := range s.file.Batches {
176 closed = append(closed, batch)
183 // Remove removes the batch with number, which is in the log.
184 func (s *WhatsAppState) Remove(number int) error {
186 defer s.mutex.Unlock()
188 s.file.Batches = slices.DeleteFunc(s.file.Batches, func(batch WhatsAppBatch) bool {
189 return batch.Number == number
195 // Wait returns how long after now the first open batch closes, or false when no
197 func (s *WhatsAppState) Wait(now time.Time) (time.Duration, bool) {
199 defer s.mutex.Unlock()
203 for _, batch := range s.file.Batches {
204 deadline := s.deadline(batch)
205 if !batch.Closed && (first.IsZero() || deadline.Before(first)) {
214 return max(first.Sub(now), 0), true
217 // Send returns the send record id, or false when there is none.
218 func (s *WhatsAppState) Send(id string) (WhatsAppSend, bool) {
220 defer s.mutex.Unlock()
222 index := slices.IndexFunc(s.file.Sends, func(record WhatsAppSend) bool {
223 return record.ID == id
227 return WhatsAppSend{}, false
230 return s.file.Sends[index], true
233 // PutSend writes record in the place of the record with its ID, or after the
234 // last record, and drops the oldest records past whatsappSendRecords.
235 func (s *WhatsAppState) PutSend(record WhatsAppSend) error {
237 defer s.mutex.Unlock()
239 index := slices.IndexFunc(s.file.Sends, func(held WhatsAppSend) bool {
240 return held.ID == record.ID
244 s.file.Sends[index] = record
246 s.file.Sends = append(s.file.Sends, record)
249 s.file.Sends = s.file.Sends[max(len(s.file.Sends)-whatsappSendRecords, 0):]
254 // open returns the index of the open batch of chat, or -1. The caller holds the
256 func (s *WhatsAppState) open(chat string) int {
257 return slices.IndexFunc(s.file.Batches, func(batch WhatsAppBatch) bool {
258 return !batch.Closed && batch.Chat.ID == chat
262 // deadline returns when batch closes in real time.
263 func (s *WhatsAppState) deadline(batch WhatsAppBatch) time.Time {
264 quiet := batch.Last.Add(s.quiet)
265 window := batch.First.Add(s.window)
266 if window.Before(quiet) {
273 // save writes the state file whole. The caller holds the mutex.
274 func (s *WhatsAppState) save() error {
275 data, err := json.Marshal(s.file)
277 return fmt.Errorf("encode WhatsApp state: %w", err)
280 err = os.MkdirAll(filepath.Dir(s.path), 0o700)
282 err = writeFileAtomic(s.path, append(data, '\n'))
286 return fmt.Errorf("save WhatsApp state: %w", err)
292 // WhatsAppStateFile is the content of the state file: the number of the last
293 // batch, the batches that are not in the log yet, and the send records, oldest
295 type WhatsAppStateFile struct {
296 Next int `json:"next"`
297 Batches []WhatsAppBatch `json:"batches"`
298 Sends []WhatsAppSend `json:"sends"`
301 // WhatsAppSend is the record of one send: the ID that the agent gave, the chat,
302 // the SHA-256 of the text, the WhatsApp message ID, the state, which is
303 // sending, sent, or failed, the answer of the tool, and the time of its start.
304 type WhatsAppSend struct {
305 ID string `json:"id"`
306 Chat string `json:"chat"`
307 Digest string `json:"digest"`
308 MessageID string `json:"message_id"`
309 State string `json:"state"`
310 Answer string `json:"answer,omitempty"`
311 Time time.Time `json:"time"`