]> git.giacomolli.uk - onechat/blob - telegram.go
Add local context to chat operation failures
[onechat] / telegram.go
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "log/slog"
11 "net/http"
12 "os"
13 "path/filepath"
14 "strings"
15 "sync"
16 "time"
17 "unicode/utf8"
18 )
19
20 const (
21 // telegramRetryDelay is the wait before the first retry of a failed
22 // call.
23 telegramRetryDelay = time.Second
24
25 // telegramRetryLimit is the longest wait between retries of a failed
26 // call.
27 telegramRetryLimit = time.Minute
28
29 // telegramAPIURL is the Telegram Bot API service.
30 telegramAPIURL = "https://api.telegram.org"
31
32 // telegramConfigFileName is the bot config in the data directory. The
33 // daemon runs the bot only when the file exists.
34 telegramConfigFileName = "telegram.json"
35
36 // telegramOffsetFileName is the update offset of the bot in the agent
37 // directory.
38 telegramOffsetFileName = "telegram-offset.json"
39
40 // telegramSource is the source of the user messages from Telegram.
41 telegramSource = "telegram"
42
43 // telegramMessageUnits is the most UTF-16 code units of one Telegram
44 // message.
45 telegramMessageUnits = 4096
46
47 // telegramRichBytes is the most bytes of the Markdown of one rich
48 // message. The Bot API allows 32768 characters of rendered text, and
49 // the Markdown of a text has at least as many bytes as the text has
50 // characters.
51 telegramRichBytes = 32768
52
53 // telegramTypingInterval is how often the bot shows the typing action
54 // while a turn runs. Telegram shows the action for about five seconds.
55 telegramTypingInterval = 4 * time.Second
56
57 // telegramTextOnly is the answer to a message that is not text.
58 telegramTextOnly = "Only text messages are supported."
59 )
60
61 // TelegramConfig holds the settings of telegram.json: the bot token and the
62 // user ID of the owner. The token is a secret, so the file must have mode 0600.
63 type TelegramConfig struct {
64 Token string `json:"token"`
65 Owner int64 `json:"owner"`
66 }
67
68 // TelegramBot connects the private chat of the owner with the agent. It polls
69 // the Bot API for new messages and sends owner text, images, and voice notes to
70 // the agent. It ignores every other update. Its sender sends the replies, the
71 // errors, the notices of the bot, and the user messages of the other clients to
72 // the chat, and shows the typing action while a turn runs. Only the replies
73 // have a format: their Markdown goes as rich messages, which Telegram renders
74 // itself, and as message entities only when Telegram refuses a rich message.
75 // The rest is plain text. Tool calls do not go to the chat.
76 //
77 // The offset file holds the ID of the next update. It moves past an update only
78 // after the message of the update is durable in the log, so a restart does not
79 // lose a message. A crash between the flush and the offset write makes Telegram
80 // send the update again, and the message repeats once.
81 //
82 // A failed Bot API call waits and tries again, from telegramRetryDelay up to
83 // telegramRetryLimit, or as long as the Bot API asks. It never stops the agent.
84 // A TelegramOutage logs the first failure and the end of each run of failures,
85 // and the retries between them log nothing.
86 type TelegramBot struct {
87 api *TelegramAPI
88 voice *VoiceTranscriber
89 owner int64
90 offsetPath string
91 logger *slog.Logger
92
93 mutex sync.Mutex
94 queue []Event
95 ready chan struct{}
96 }
97
98 // TelegramOutage is one run of failures of a kind of Bot API call. The first
99 // failure logs loss, its cause, and the wait of the next try. The retries log
100 // nothing. The next answer of Telegram logs back and the length of the outage.
101 // loss and back say what the user loses and gets again.
102 type TelegramOutage struct {
103 logger *slog.Logger
104 loss string
105 back string
106 start time.Time
107 }
108
109 // TelegramPart is the text of one message to the chat, at most
110 // telegramMessageUnits long, and its entities.
111 type TelegramPart struct {
112 text string
113 entities []TelegramEntity
114 }
115
116 // TelegramOffsetFile is the content of the offset file.
117 type TelegramOffsetFile struct {
118 Offset int64 `json:"offset"`
119 }
120
121 // loadTelegramConfig reads telegram.json in dir. It returns false when the file
122 // does not exist. An error never holds the token.
123 func loadTelegramConfig(dir string) (TelegramConfig, bool, error) {
124 path := filepath.Join(dir, telegramConfigFileName)
125 info, err := os.Stat(path)
126 if errors.Is(err, os.ErrNotExist) {
127 return TelegramConfig{}, false, nil
128 }
129
130 if err != nil {
131 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
132 }
133
134 if info.Mode().Perm()&0o077 != 0 {
135 return TelegramConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", telegramConfigFileName)
136 }
137
138 data, err := os.ReadFile(path)
139 if err != nil {
140 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
141 }
142
143 var config TelegramConfig
144
145 decoder := json.NewDecoder(bytes.NewReader(data))
146 decoder.DisallowUnknownFields()
147
148 err = decoder.Decode(&config)
149 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
150 err = errors.New("data after the JSON object")
151 }
152
153 if err != nil {
154 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
155 }
156
157 err = config.validate()
158 if err != nil {
159 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
160 }
161
162 return config, true, nil
163 }
164
165 // newTelegramBot returns the bot of owner on api. The offset file is at
166 // offsetPath, and logger gets the failures. No log line holds the text of a
167 // message.
168 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *slog.Logger) *TelegramBot {
169 return &TelegramBot{
170 api: api,
171 voice: &VoiceTranscriber{},
172 owner: owner,
173 offsetPath: offsetPath,
174 logger: logger,
175 ready: make(chan struct{}, 1),
176 }
177 }
178
179 // validate makes sure that the token has the form of a bot token and that the
180 // owner is a user ID. The token goes into a URL path, so it can only hold the
181 // characters of a bot token.
182 func (c TelegramConfig) validate() error {
183 id, secret, found := strings.Cut(c.Token, ":")
184 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
185 return errors.New("token does not have the form of a bot token from BotFather")
186 }
187
188 if c.Owner <= 0 {
189 return errors.New("owner must be the numeric Telegram user ID of the owner")
190 }
191
192 return nil
193 }
194
195 // Run polls for the messages of the owner and sends the queued events to the
196 // chat until ctx ends. It returns an error only when a message or the offset or
197 // image cannot be written, because then the bot would lose or repeat messages.
198 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
199 ctx, cancel := context.WithCancel(ctx)
200 defer cancel()
201
202 var sender sync.WaitGroup
203
204 sender.Add(1)
205
206 go func() {
207 defer sender.Done()
208
209 b.send(ctx)
210 }()
211
212 err := b.poll(ctx, l, whatsapp)
213
214 cancel()
215 sender.Wait()
216
217 return err
218 }
219
220 // send sends each queued event to the chat in order until ctx ends. While a
221 // turn runs, it shows the typing action every telegramTypingInterval and after
222 // each message, because a message ends the action.
223 func (b *TelegramBot) send(ctx context.Context) {
224 ticker := time.NewTicker(telegramTypingInterval)
225 defer ticker.Stop()
226
227 busy := false
228 for ctx.Err() == nil {
229 event, found := b.next()
230 if !found {
231 select {
232 case <-b.ready:
233 case <-ticker.C:
234 if busy {
235 b.typing(ctx)
236 }
237 case <-ctx.Done():
238 }
239
240 continue
241 }
242
243 switch event.Kind {
244 case "busy":
245 busy = true
246
247 b.typing(ctx)
248 ticker.Reset(telegramTypingInterval)
249 case "idle":
250 busy = false
251 default:
252 b.post(ctx, event)
253
254 if busy {
255 b.typing(ctx)
256 }
257 }
258 }
259 }
260
261 // poll gets updates from the stored offset and handles them until ctx ends. A
262 // failed image download retries from the same offset. A submitted message is
263 // flushed even if ctx ends, and only then can the offset advance.
264 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
265 offset, err := telegramLoadOffset(b.offsetPath)
266 if err != nil {
267 return fmt.Errorf("load Telegram offset: %w", err)
268 }
269
270 outage := &TelegramOutage{
271 logger: b.logger,
272 loss: "receive failed",
273 back: "receive back",
274 }
275
276 imageOutage := &TelegramOutage{
277 logger: b.logger,
278 loss: "image receive failed",
279 back: "image receive back",
280 }
281
282 imageWait := telegramRetryDelay
283 wait := telegramRetryDelay
284
285 poll:
286 for ctx.Err() == nil {
287 updates, err := b.api.GetUpdates(ctx, offset)
288 if ctx.Err() != nil {
289 return nil
290 }
291
292 if err != nil {
293 _, asked := telegramRetryable(err)
294 wait = b.pause(ctx, outage, err, wait, asked)
295
296 continue
297 }
298
299 outage.End()
300
301 wait = telegramRetryDelay
302
303 for _, update := range updates {
304 if ctx.Err() != nil {
305 return nil
306 }
307
308 err = b.handle(ctx, l, whatsapp, update)
309 if err != nil {
310 retry, asked := telegramRetryable(err)
311 if retry {
312 imageWait = b.pause(ctx, imageOutage, err, imageWait, asked)
313 continue poll
314 }
315
316 if err != nil {
317 return fmt.Errorf("handle Telegram update: %w", err)
318 }
319
320 return nil
321 }
322
323 imageOutage.End()
324
325 imageWait = telegramRetryDelay
326
327 offset = update.UpdateID + 1
328 err = telegramSaveOffset(b.offsetPath, offset)
329 if err != nil {
330 return fmt.Errorf("save Telegram offset: %w", err)
331 }
332 }
333 }
334
335 return nil
336 }
337
338 // next removes the first queued event and returns it.
339 func (b *TelegramBot) next() (Event, bool) {
340 b.mutex.Lock()
341 defer b.mutex.Unlock()
342
343 if len(b.queue) == 0 {
344 return Event{}, false
345 }
346
347 event := b.queue[0]
348 b.queue = b.queue[1:]
349
350 return event, true
351 }
352
353 // typing shows the typing action once. A failure is not logged, because the
354 // next message or poll logs the state of the network.
355 func (b *TelegramBot) typing(ctx context.Context) {
356 // The next message or poll reports a network failure.
357 b.api.SendTyping(ctx, b.owner) // nolint: errcheck
358 }
359
360 // post sends event to the chat. A reply goes as rich messages of its Markdown,
361 // with each < and & outside code escaped by telegramEscapeTags and then split
362 // with telegramSplitRich, so that the length limit counts the escaped text.
363 // Every other event goes as plain text, split with telegramSplitMessage.
364 func (b *TelegramBot) post(ctx context.Context, event Event) {
365 if event.Kind != "reply" {
366 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
367 b.deliver(ctx, TelegramPart{
368 text: text,
369 })
370 }
371
372 return
373 }
374
375 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
376 b.deliverRich(ctx, markdown)
377 }
378 }
379
380 // pause gives err to outage and waits the longer of wait and asked, or until
381 // ctx ends. It returns the wait of the next failure: twice wait, up to
382 // telegramRetryLimit.
383 func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
384 delay := max(wait, asked)
385 outage.Fail(err, delay)
386
387 timer := time.NewTimer(delay)
388 defer timer.Stop()
389
390 select {
391 case <-timer.C:
392 case <-ctx.Done():
393 }
394
395 return min(2*wait, telegramRetryLimit)
396 }
397
398 // handle runs one update. A text message of the owner in the private chat goes
399 // to the agent, and handle returns when it is durable in the log. The line
400 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
401 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
402 // answers go to the chat only. Photos and image documents enter the shared
403 // image store with their caption. Voice notes keep their audio and local
404 // transcript. Other media keep the text-only answer. Every other update is
405 // ignored, and its content is not logged.
406 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
407 message := update.Message
408 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
409 b.logger.Info("message ignored: not from the owner")
410
411 return nil
412 }
413
414 name, stop := stopSubagentName(message.Text)
415 args, isWhatsApp := whatsappCommandArgs(message.Text)
416 switch {
417 case message.Voice != nil:
418 text := telegramVoiceText(ctx, b.api, l.agent.Voices(), b.voice, message)
419 _, err := l.Submit(telegramSource, text)
420 if err != nil {
421 return fmt.Errorf("submit Telegram voice: %w", err)
422 }
423
424 err = l.Flush(context.WithoutCancel(ctx))
425 if err != nil {
426 return fmt.Errorf("flush Telegram voice: %w", err)
427 }
428 case len(message.Photo) > 0 || message.Document != nil:
429 text, err := telegramImageText(ctx, b.api, l.agent.Images(), message)
430 if err != nil {
431 retry, _ := telegramRetryable(err)
432 if retry {
433 return fmt.Errorf("receive image: %w", err)
434 }
435
436 switch {
437 case errors.Is(err, errTelegramOtherMedia):
438 b.notice(telegramTextOnly)
439 case errors.Is(err, errImageSize), errors.Is(err, errImageFormat), errors.Is(err, errTelegramPhotoSize):
440 b.notice(err.Error())
441 default:
442 var answer *TelegramError
443
444 if !errors.As(err, &answer) {
445 return fmt.Errorf("receive Telegram image: %w", err)
446 }
447
448 b.notice("Cannot download image.")
449 }
450
451 return nil
452 }
453
454 _, err = l.Submit(telegramSource, text)
455 if err != nil {
456 return fmt.Errorf("submit Telegram image: %w", err)
457 }
458
459 err = l.Flush(context.WithoutCancel(ctx))
460 if err != nil {
461 return fmt.Errorf("flush Telegram image: %w", err)
462 }
463 case message.Text == "":
464 b.notice(telegramTextOnly)
465 case strings.TrimSpace(message.Text) == stopCommand:
466 if !l.Interrupt() {
467 b.notice("No turn runs.")
468 }
469 case stop:
470 found, err := l.StopSubagent(name)
471 if err != nil {
472 return fmt.Errorf("stop subagent %s: %w", name, err)
473 }
474
475 if !found {
476 b.notice("No subagent " + name + " runs.")
477 }
478 case isWhatsApp:
479 whatsapp.Command(args, b.notice)
480 default:
481 _, err := l.Submit(telegramSource, message.Text)
482 if err != nil {
483 return fmt.Errorf("submit Telegram text: %w", err)
484 }
485
486 err = l.Flush(context.WithoutCancel(ctx))
487 if err != nil {
488 return fmt.Errorf("flush the message from Telegram: %w", err)
489 }
490 }
491
492 return nil
493 }
494
495 // deliver sends part to the chat. When Telegram refuses a part with entities
496 // (HTTP 400), it sends the text of the part again once with no entities, so a
497 // reply is not lost to a bad entity. It tries again after each failure that a
498 // later try can fix, until ctx ends. It drops the part after any other failure.
499 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
500 outage := b.sendOutage()
501 wait := telegramRetryDelay
502 for {
503 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
504 retry, asked := telegramRetryable(err)
505 if !retry {
506 outage.End()
507 }
508
509 if err == nil || ctx.Err() != nil {
510 return
511 }
512
513 var answer *TelegramError
514
515 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
516 b.logger.Warn("reply sent as plain text", "err", err)
517
518 part.entities = nil
519
520 continue
521 }
522
523 if !retry {
524 b.logger.Error("reply lost", "err", err)
525
526 return
527 }
528
529 wait = b.pause(ctx, outage, err, wait, asked)
530 }
531 }
532
533 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
534 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
535 // was not sent, so deliverRich sends the text of the part once with message
536 // entities, and the reply is not lost and does not repeat. Message entities
537 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
538 // the model wrote it. It tries again after each failure that a later try can
539 // fix, until ctx ends. It drops the message after any other failure.
540 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
541 outage := b.sendOutage()
542 wait := telegramRetryDelay
543 for {
544 err := b.api.SendRichMessage(ctx, b.owner, markdown)
545 retry, asked := telegramRetryable(err)
546 if !retry {
547 outage.End()
548 }
549
550 if err == nil || ctx.Err() != nil {
551 return
552 }
553
554 if telegramRejected(err) {
555 b.logger.Warn("reply sent with simple formatting", "err", err)
556
557 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
558 b.deliver(ctx, part)
559 }
560
561 return
562 }
563
564 if !retry {
565 b.logger.Error("reply lost", "err", err)
566
567 return
568 }
569
570 wait = b.pause(ctx, outage, err, wait, asked)
571 }
572 }
573
574 // notice queues a short answer of the bot for the chat.
575 func (b *TelegramBot) notice(text string) {
576 b.Notify(Event{
577 Kind: "notice",
578 Text: text,
579 })
580 }
581
582 // sendOutage returns a new outage of the messages to the chat.
583 func (b *TelegramBot) sendOutage() *TelegramOutage {
584 return &TelegramOutage{
585 logger: b.logger,
586 loss: "send failed",
587 back: "send back",
588 }
589 }
590
591 // Notify queues event for the chat. It never blocks, so a slow network does not
592 // stop the agent. The WhatsApp batches and the runs of the schedules do not go
593 // to the chat: the reply of the agent tells the user what needs the user.
594 func (b *TelegramBot) Notify(event Event) {
595 switch event.Kind {
596 case "busy", "idle", "reply", "error", "notice", "subagent":
597 case "work":
598 if event.Source == whatsappSource || event.Source == scheduleSource {
599 return
600 }
601 case "user":
602 if event.Source == telegramSource {
603 return
604 }
605 default:
606 return
607 }
608
609 b.mutex.Lock()
610
611 b.queue = append(b.queue, event)
612 b.mutex.Unlock()
613
614 select {
615 case b.ready <- struct{}{}:
616 default:
617 }
618 }
619
620 // End logs the end of the outage that runs, with its length.
621 func (o *TelegramOutage) End() {
622 if o.start.IsZero() {
623 return
624 }
625
626 o.logger.Info(o.back, "after", time.Since(o.start))
627
628 o.start = time.Time{}
629 }
630
631 // Fail logs the start of an outage with err and delay, unless an outage runs.
632 func (o *TelegramOutage) Fail(err error, delay time.Duration) {
633 if !o.start.IsZero() {
634 return
635 }
636
637 o.start = time.Now()
638 o.logger.Warn(o.loss, "err", err, "retry", delay)
639 }
640
641 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
642 // which asks for every update that Telegram keeps.
643 func telegramLoadOffset(path string) (int64, error) {
644 data, err := os.ReadFile(path)
645 if errors.Is(err, os.ErrNotExist) {
646 return 0, nil
647 }
648
649 if err != nil {
650 return 0, fmt.Errorf("read update offset: %w", err)
651 }
652
653 var file TelegramOffsetFile
654
655 err = json.Unmarshal(data, &file)
656 if err != nil {
657 return 0, fmt.Errorf("%s: %w", path, err)
658 }
659
660 return file.Offset, nil
661 }
662
663 // telegramSaveOffset replaces the update offset at path.
664 func telegramSaveOffset(path string, offset int64) error {
665 data, err := json.Marshal(TelegramOffsetFile{
666 Offset: offset,
667 })
668 if err != nil {
669 return fmt.Errorf("encode update offset: %w", err)
670 }
671
672 err = writeFileAtomic(path, append(data, '\n'))
673 if err != nil {
674 return fmt.Errorf("write update offset: %w", err)
675 }
676
677 return nil
678 }
679
680 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
681 // the unit of the Telegram message limit. It cuts after the last line break or
682 // space of a part when one is in its second half, and else at the limit. It
683 // never cuts a character.
684 func telegramSplitMessage(text string, limit int) []string {
685 var parts []string
686
687 for {
688 end := telegramPrefixEnd(text, limit)
689 if end == len(text) {
690 return append(parts, text)
691 }
692
693 cut := strings.LastIndexByte(text[:end], '\n') + 1
694 if cut <= end/2 {
695 cut = strings.LastIndexByte(text[:end], ' ') + 1
696 }
697
698 if cut <= end/2 {
699 cut = end
700 }
701
702 parts = append(parts, text[:cut])
703 text = text[cut:]
704 }
705 }
706
707 // telegramText returns the text of event for the chat. A user message of
708 // another client has its source as a mark. A subagent shows only its start and
709 // how its run ended, because the reply of the agent carries the content of the
710 // report.
711 func telegramText(event Event) string {
712 switch event.Kind {
713 case "user":
714 return "[" + event.Source + "] " + event.Text
715 case "subagent":
716 return "[" + event.Text + "] started"
717 case "work":
718 return "[" + event.Source + "] " + event.Status
719 case "error":
720 return "Error: " + event.Text
721 default:
722 return event.Text
723 }
724 }
725
726 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
727 // bytes. It cuts after a blank line outside a code block, so a table, a code
728 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
729 // after the last line break outside a code block, then after the last line
730 // break in a code block, which it closes at the end of the part and opens again
731 // in the next part with the same fence line. A line longer than limit is cut at
732 // the limit, or before an & in the four bytes before the limit, so that it does
733 // not cut an entity of telegramEscapeTags. It never cuts a character.
734 func telegramSplitRich(markdown string, limit int) []string {
735 var parts []string
736
737 for len(markdown) > limit {
738 cut, fence, opening := telegramRichCut(markdown, limit)
739 if fence == "" {
740 parts = append(parts, markdown[:cut])
741 markdown = markdown[cut:]
742
743 continue
744 }
745
746 parts = append(parts, markdown[:cut]+fence+"\n")
747 markdown = opening + "\n" + markdown[cut:]
748 }
749
750 return append(parts, markdown)
751 }
752
753 // telegramReplyParts returns the messages of the Markdown of a reply with
754 // message entities. A reply that has no text left after the conversion, such as
755 // an empty code block, goes as its Markdown.
756 func telegramReplyParts(markdown string) []TelegramPart {
757 text, entities := telegramMarkdownEntities(markdown)
758 if strings.TrimSpace(text) == "" {
759 text, entities = markdown, nil
760 }
761
762 return telegramSplitEntities(text, entities, telegramMessageUnits)
763 }
764
765 // telegramPrefixEnd returns the byte length of the longest prefix of text with
766 // at most limit UTF-16 code units.
767 func telegramPrefixEnd(text string, limit int) int {
768 units := 0
769 for index, char := range text {
770 size := 1
771 if char > 0xFFFF {
772 size = 2
773 }
774
775 if units+size > limit {
776 return index
777 }
778
779 units += size
780 }
781
782 return len(text)
783 }
784
785 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
786 // longer than limit. For a cut in a code block, it also returns the fence that
787 // closes the block and the line that opens it. Each part before a cut holds
788 // text other than space, and a cut in a code block leaves room for the fence,
789 // so each cut makes the rest shorter.
790 func telegramRichCut(markdown string, limit int) (int, string, string) {
791 blank, line, code := 0, 0, 0
792
793 var fence, opening, inFence, inOpening string
794
795 for start := 0; start < limit; {
796 end := strings.IndexByte(markdown[start:], '\n')
797 if end < 0 || start+end+1 > limit {
798 break
799 }
800
801 end += start + 1
802 text := strings.TrimRight(markdown[start:end], "\r\n")
803 _, opens := markdownCodeFence(text)
804 switch {
805 case fence != "":
806 if markdownClosesFence(text, fence) {
807 fence = ""
808 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
809 code, inFence, inOpening = end, fence, opening
810 }
811 case opens != "":
812 fence, opening = opens, text
813 case strings.TrimSpace(markdown[:end]) == "":
814 case strings.TrimSpace(text) == "":
815 blank = end
816 }
817
818 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
819 line = end
820 }
821
822 start = end
823 }
824
825 switch {
826 case blank > 0:
827 return blank, "", ""
828 case line > 0:
829 return line, "", ""
830 case code > 0:
831 return code, inFence, inOpening
832 }
833
834 cut := limit
835 for !utf8.RuneStart(markdown[cut]) {
836 cut--
837 }
838
839 start := max(cut-len("&amp;")+1, 0)
840 entity := strings.LastIndexByte(markdown[start:cut], '&')
841 if entity >= 0 && start+entity > 0 {
842 cut = start + entity
843 }
844
845 return cut, "", ""
846 }
847
848 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
849 // gives each part the entities in it, with offsets from the start of the part.
850 // An entity that crosses a cut becomes one entity in each part.
851 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
852 var parts []TelegramPart
853
854 start := 0
855 for _, part := range telegramSplitMessage(text, limit) {
856 end := start + telegramUTF16Units(part)
857
858 var kept []TelegramEntity
859
860 for _, entity := range entities {
861 from := max(entity.Offset, start)
862 to := min(entity.Offset+entity.Length, end)
863 if to <= from {
864 continue
865 }
866
867 entity.Offset = from - start
868 entity.Length = to - from
869 kept = append(kept, entity)
870 }
871
872 parts = append(parts, TelegramPart{
873 text: part,
874 entities: kept,
875 })
876
877 start = end
878 }
879
880 return parts
881 }