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