emoji.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/owncast/owncast/config"
  11. "github.com/owncast/owncast/models"
  12. log "github.com/sirupsen/logrus"
  13. )
  14. var emojiCache = make([]models.CustomEmoji, 0)
  15. var emojiCacheTimestamp time.Time
  16. // getCustomEmojiList returns a list of custom emoji either from the cache or from the emoji directory.
  17. func getCustomEmojiList() []models.CustomEmoji {
  18. fullPath := filepath.Join(config.WebRoot, config.EmojiDir)
  19. emojiDirInfo, err := os.Stat(fullPath)
  20. if err != nil {
  21. log.Errorln(err)
  22. }
  23. if emojiDirInfo.ModTime() != emojiCacheTimestamp {
  24. log.Traceln("Emoji cache invalid")
  25. emojiCache = make([]models.CustomEmoji, 0)
  26. }
  27. if len(emojiCache) == 0 {
  28. files, err := os.ReadDir(fullPath)
  29. if err != nil {
  30. log.Errorln(err)
  31. return emojiCache
  32. }
  33. for _, f := range files {
  34. name := strings.TrimSuffix(f.Name(), path.Ext(f.Name()))
  35. emojiPath := filepath.Join(config.EmojiDir, f.Name())
  36. singleEmoji := models.CustomEmoji{Name: name, Emoji: emojiPath}
  37. emojiCache = append(emojiCache, singleEmoji)
  38. }
  39. emojiCacheTimestamp = emojiDirInfo.ModTime()
  40. }
  41. return emojiCache
  42. }
  43. // GetCustomEmoji returns a list of custom emoji via the API.
  44. func GetCustomEmoji(w http.ResponseWriter, r *http.Request) {
  45. emojiList := getCustomEmojiList()
  46. if err := json.NewEncoder(w).Encode(emojiList); err != nil {
  47. InternalErrorHandler(w, err)
  48. }
  49. }