gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

emojify.go (2079B)


      1 // GoToSocial
      2 // Copyright (C) GoToSocial Authors admin@gotosocial.org
      3 // SPDX-License-Identifier: AGPL-3.0-or-later
      4 //
      5 // This program is free software: you can redistribute it and/or modify
      6 // it under the terms of the GNU Affero General Public License as published by
      7 // the Free Software Foundation, either version 3 of the License, or
      8 // (at your option) any later version.
      9 //
     10 // This program is distributed in the hope that it will be useful,
     11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
     12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13 // GNU Affero General Public License for more details.
     14 //
     15 // You should have received a copy of the GNU Affero General Public License
     16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
     17 
     18 package text
     19 
     20 import (
     21 	"bytes"
     22 	"html"
     23 
     24 	apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
     25 	"github.com/superseriousbusiness/gotosocial/internal/regexes"
     26 )
     27 
     28 // Emojify replaces shortcodes in `inputText` with the emoji in `emojis`.
     29 //
     30 // Callers should ensure that inputText and resulting text are escaped
     31 // appropriately depending on what they're used for.
     32 func Emojify(emojis []apimodel.Emoji, inputText string) string {
     33 	emojisMap := make(map[string]apimodel.Emoji, len(emojis))
     34 
     35 	for _, emoji := range emojis {
     36 		shortcode := ":" + emoji.Shortcode + ":"
     37 		emojisMap[shortcode] = emoji
     38 	}
     39 
     40 	return regexes.ReplaceAllStringFunc(
     41 		regexes.EmojiFinder,
     42 		inputText,
     43 		func(shortcode string, buf *bytes.Buffer) string {
     44 			// Look for emoji according to this shortcode
     45 			emoji, ok := emojisMap[shortcode]
     46 			if !ok {
     47 				return shortcode
     48 			}
     49 
     50 			// Escape raw emoji content
     51 			safeURL := html.EscapeString(emoji.URL)
     52 			safeCode := html.EscapeString(emoji.Shortcode)
     53 
     54 			// Write HTML emoji repr to buffer
     55 			buf.WriteString(`<img src="`)
     56 			buf.WriteString(safeURL)
     57 			buf.WriteString(`" title=":`)
     58 			buf.WriteString(safeCode)
     59 			buf.WriteString(`:" alt=":`)
     60 			buf.WriteString(safeCode)
     61 			buf.WriteString(`:" class="emoji"/>`)
     62 
     63 			return buf.String()
     64 		},
     65 	)
     66 }