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