1310 lines
38 KiB
Go
1310 lines
38 KiB
Go
package webui
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"embed"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"io/fs"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"stream-bot/internal/ai"
|
|
"stream-bot/internal/commands"
|
|
"stream-bot/internal/db"
|
|
"stream-bot/internal/events"
|
|
"stream-bot/internal/hotkey"
|
|
"stream-bot/internal/logger"
|
|
"stream-bot/internal/notifications"
|
|
"stream-bot/internal/parser"
|
|
"stream-bot/internal/platforms"
|
|
"stream-bot/internal/webservices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
authStates sync.Map // map[string]string state -> "user" или "bot"
|
|
tokenUpdatedUser bool
|
|
tokenUpdatedBot bool
|
|
updateMutex sync.Mutex
|
|
)
|
|
|
|
type Server struct {
|
|
assets embed.FS
|
|
platformMgr *platforms.Manager
|
|
cmdProc *commands.Processor
|
|
eventProc *events.Processor
|
|
httpSrv *http.Server
|
|
twitchAuth *platforms.TwitchAuth
|
|
notifMgr *notifications.Manager
|
|
webSrvMgr *webservices.Manager
|
|
twitchClientID string
|
|
twitchClientSecret string
|
|
}
|
|
|
|
type UserActionRequest struct {
|
|
Username string `json:"username"`
|
|
Action string `json:"action"` // warn, timeout10sec, timeout10min, ban, unban, set_vip, unset_vip, set_mod, unset_mod, toggle_mark
|
|
Platform string `json:"platform"`
|
|
}
|
|
|
|
func NewServer(assets embed.FS, pm *platforms.Manager, cp *commands.Processor, ep *events.Processor, nm *notifications.Manager, wsm *webservices.Manager, twitchClientID, twitchClientSecret string) *Server {
|
|
return &Server{
|
|
assets: assets,
|
|
platformMgr: pm,
|
|
cmdProc: cp,
|
|
eventProc: ep,
|
|
notifMgr: nm,
|
|
webSrvMgr: wsm,
|
|
twitchAuth: platforms.NewTwitchAuth(twitchClientID, twitchClientSecret),
|
|
}
|
|
}
|
|
|
|
func (s *Server) Start(addr string) error {
|
|
mux := http.NewServeMux()
|
|
|
|
// Статика
|
|
staticFS, err := fs.Sub(s.assets, "internal/webui/static")
|
|
if err != nil {
|
|
logger.Error("Failed to create static sub FS: %v", err)
|
|
} else {
|
|
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
|
|
}
|
|
|
|
// Страницы
|
|
mux.HandleFunc("/", s.indexHandler)
|
|
mux.HandleFunc("/platforms", s.platformsHandler)
|
|
mux.HandleFunc("/commands", s.commandsHandler)
|
|
mux.HandleFunc("/events", s.eventsHandler)
|
|
mux.HandleFunc("/hotkeys", s.hotkeysHandler)
|
|
mux.HandleFunc("/webservices", s.webservicesHandler)
|
|
mux.HandleFunc("/logs", s.logsHandler)
|
|
|
|
// API (старые, но нужные)
|
|
mux.HandleFunc("/api/commands", s.apiCommandsHandler)
|
|
mux.HandleFunc("/api/events", s.apiEventsHandler)
|
|
mux.HandleFunc("/api/hotkeys", s.apiHotkeysHandler)
|
|
|
|
mux.HandleFunc("/api/platforms/twitch/auth", s.apiTwitchAuthHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/status", s.apiTwitchStatusHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/auth/user", s.apiTwitchAuthUserHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/auth/bot", s.apiTwitchAuthBotHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/auth/callback", s.apiTwitchAuthCallbackHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/token_check", s.apiTwitchTokenCheckHandler)
|
|
mux.HandleFunc("/api/platforms/twitch/token_expiry", s.apiTwitchTokenExpiryHandler)
|
|
|
|
mux.HandleFunc("/api/users", s.apiUsersHandler)
|
|
mux.HandleFunc("/api/users/action", s.apiUserActionHandler)
|
|
|
|
mux.HandleFunc("/ai", s.aiPageHandler)
|
|
mux.HandleFunc("/api/ai/config", s.apiAIConfigHandler)
|
|
mux.HandleFunc("/api/ai/test", s.apiAITestHandler)
|
|
|
|
mux.HandleFunc("/api/platforms/twitch/eventsub/status", s.apiTwitchEventSubStatusHandler)
|
|
mux.HandleFunc("/api/webservice/url", s.apiWebserviceURLHandler)
|
|
|
|
mux.HandleFunc("/api/commands/test", s.apiCommandsTestHandler)
|
|
|
|
mux.HandleFunc("/api/logs/stream", s.apiLogsStreamHandler)
|
|
|
|
mux.HandleFunc("/notifications", s.notificationsHandler)
|
|
mux.HandleFunc("/api/notifications", s.apiNotificationsHandler)
|
|
mux.HandleFunc("/api/notifications/test", s.apiNotificationTestHandler)
|
|
|
|
mux.HandleFunc("/api/sounds", s.apiSoundsHandler)
|
|
mux.HandleFunc("/api/sounds/upload", s.apiSoundsUploadHandler)
|
|
mux.HandleFunc("/api/obs/notify", s.apiObsNotifyHandler)
|
|
|
|
mux.HandleFunc("/api/webservices/media", s.apiWebServiceMediaHandler)
|
|
|
|
// НОВЫЕ API для управления множественными сервисами
|
|
mux.HandleFunc("/api/webservices", s.apiWebServicesList) // GET
|
|
mux.HandleFunc("/api/webservices/create", s.apiWebServicesCreate) // POST
|
|
mux.HandleFunc("/api/webservices/update", s.apiWebServicesUpdateConfig) // PUT (id в query)
|
|
mux.HandleFunc("/api/webservices/start", s.apiWebServicesStart) // POST?id=
|
|
mux.HandleFunc("/api/webservices/stop", s.apiWebServicesStop) // POST?id=
|
|
mux.HandleFunc("/api/webservices/delete", s.apiWebServicesDelete) // DELETE?id=
|
|
mux.HandleFunc("/api/webservices/test/chat", s.apiWebServicesTestChat) // POST?id=
|
|
mux.HandleFunc("/api/webservices/test/alert", s.apiWebServicesTestAlert) // POST?id=&event=
|
|
|
|
mux.HandleFunc("/api/settings/duplicate_sounds", s.apiDuplicateSoundsHandler)
|
|
mux.HandleFunc("/api/sounds/list", s.apiSoundsListHandler)
|
|
mux.HandleFunc("/api/images/list", s.apiImagesListHandler)
|
|
|
|
mux.HandleFunc("/api/webservices/alert/list", s.apiWebServicesAlertList)
|
|
|
|
mux.HandleFunc("/api/settings/hotkey", s.apiHotkeySettingHandler)
|
|
|
|
mux.HandleFunc("/api/logs/download", s.apiLogsDownloadHandler)
|
|
handler := corsMiddleware(mux)
|
|
s.httpSrv = &http.Server{Addr: addr, Handler: handler}
|
|
logger.Info("Web UI starting on http://%s", addr)
|
|
return s.httpSrv.ListenAndServe()
|
|
}
|
|
|
|
func (s *Server) Stop() error {
|
|
if s.httpSrv != nil {
|
|
return s.httpSrv.Close()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- Страницы (без изменений) ---
|
|
func (s *Server) indexHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t, err := template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/dashboard.html")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) platformsHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/platforms.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) commandsHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/commands.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) eventsHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t, err := template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/events.html")
|
|
if err != nil {
|
|
logger.Error("Failed to parse events template: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) hotkeysHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/hotkeys.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) webservicesHandler(w http.ResponseWriter, _ *http.Request) {
|
|
// Здесь должен быть новый шаблон для управления несколькими сервисами
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/webservices.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) logsHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/logs.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
// ApiEventsHandler обрабатывает GET (получение действий) и POST (сохранение)
|
|
func (s *Server) apiEventsHandler(w http.ResponseWriter, r *http.Request) {
|
|
platform := r.URL.Query().Get("platform")
|
|
eventName := r.URL.Query().Get("event")
|
|
if platform == "" || eventName == "" {
|
|
http.Error(w, "missing platform or event", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
actions, err := db.GetEventActions(platform, eventName)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(actions)
|
|
|
|
case http.MethodPost:
|
|
var actions []db.Action
|
|
if err := json.NewDecoder(r.Body).Decode(&actions); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := db.SaveEventActions(platform, eventName, actions); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
default:
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
func (s *Server) apiHotkeysHandler(w http.ResponseWriter, r *http.Request) {
|
|
platform := r.URL.Query().Get("platform")
|
|
if r.Method == http.MethodGet {
|
|
rules, _ := db.GetHotkeyRules(platform)
|
|
_ = json.NewEncoder(w).Encode(rules)
|
|
} else if r.Method == http.MethodPost {
|
|
var req struct {
|
|
MinAmount int `json:"min_amount"`
|
|
Comb string `json:"combination"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
_ = db.AddHotkeyRule(platform, req.MinAmount, req.Comb)
|
|
} else if r.Method == http.MethodDelete {
|
|
minAmt, _ := strconv.Atoi(r.URL.Query().Get("min_amount"))
|
|
_ = db.DeleteHotkeyRule(platform, minAmt)
|
|
}
|
|
}
|
|
|
|
func (s *Server) apiTwitchAuthHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
tokens, err := db.GetPlatformTokens("twitch")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
username := ""
|
|
hasToken := false
|
|
maskedToken := ""
|
|
if tokens != nil {
|
|
username = tokens.UserLogin
|
|
if tokens.BotToken != "" {
|
|
hasToken = true
|
|
if len(tokens.BotToken) > 8 {
|
|
maskedToken = tokens.BotToken[:4] + "****" + tokens.BotToken[len(tokens.BotToken)-4:]
|
|
}
|
|
}
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"username": username,
|
|
"hasToken": hasToken,
|
|
"maskedToken": maskedToken,
|
|
})
|
|
return
|
|
}
|
|
if r.Method == http.MethodPost {
|
|
token := r.FormValue("token")
|
|
username := r.FormValue("username")
|
|
if token == "" || username == "" {
|
|
http.Error(w, "token and username required", 400)
|
|
return
|
|
}
|
|
tokens, _ := db.GetPlatformTokens("twitch")
|
|
if tokens == nil {
|
|
tokens = &db.PlatformTokens{}
|
|
}
|
|
tokens.BotToken = token
|
|
tokens.BotLogin = username
|
|
if err := db.SetPlatformTokens("twitch", tokens); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
if p := s.platformMgr.GetPlatform("twitch"); p != nil {
|
|
p.Disconnect()
|
|
_ = p.Connect()
|
|
}
|
|
_, _ = w.Write([]byte("OK"))
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
|
|
func (s *Server) apiTwitchStatusHandler(w http.ResponseWriter, _ *http.Request) {
|
|
connected := s.platformMgr.IsConnected("twitch")
|
|
_ = json.NewEncoder(w).Encode(map[string]bool{"connected": connected})
|
|
}
|
|
|
|
func (s *Server) apiCommandsTestHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
var req struct {
|
|
Template string `json:"template"`
|
|
Username string `json:"username"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := parser.ValidateTemplate(req.Template); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
result, soundFiles, _, err := parser.ParseTemplate(req.Template, req.Username, "", "[AI заглушка]", func() string {
|
|
return "TestUser"
|
|
})
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"result": result,
|
|
"soundFiles": soundFiles,
|
|
})
|
|
}
|
|
|
|
func (s *Server) apiCommandsHandler(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
cmds, err := db.GetCommands()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(cmds)
|
|
case http.MethodPost:
|
|
var cmd db.Command
|
|
if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
if err := parser.ValidateTemplate(cmd.Template); err != nil {
|
|
http.Error(w, "Invalid template: "+err.Error(), 400)
|
|
return
|
|
}
|
|
err := db.AddCommand(cmd.Trigger, cmd.Template, cmd.Enabled, cmd.CooldownSec, cmd.Permission)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusCreated)
|
|
case http.MethodPut:
|
|
var cmd db.Command
|
|
if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
if err := parser.ValidateTemplate(cmd.Template); err != nil {
|
|
http.Error(w, "Invalid template: "+err.Error(), 400)
|
|
return
|
|
}
|
|
err := db.UpdateCommand(cmd.ID, cmd.Trigger, cmd.Template, cmd.Enabled, cmd.CooldownSec, cmd.Permission)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
case http.MethodDelete:
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", 400)
|
|
return
|
|
}
|
|
if err := db.DeleteCommand(id); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
default:
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
}
|
|
|
|
func (s *Server) apiLogsStreamHandler(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
flusher, ok := w.(http.Flusher)
|
|
if !ok {
|
|
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
recent := logger.GetRecent(50)
|
|
for _, entry := range recent {
|
|
data, _ := json.Marshal(entry)
|
|
_, _ = fmt.Fprintf(w, "data: %s\n\n", data)
|
|
flusher.Flush()
|
|
}
|
|
|
|
ch := logger.Subscribe()
|
|
defer logger.Unsubscribe(ch)
|
|
|
|
for {
|
|
select {
|
|
case entry := <-ch:
|
|
data, _ := json.Marshal(entry)
|
|
_, _ = fmt.Fprintf(w, "data: %s\n\n", data)
|
|
flusher.Flush()
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) apiTwitchAuthUserHandler(w http.ResponseWriter, _ *http.Request) {
|
|
scopes := []string{
|
|
"channel:manage:vips",
|
|
"moderator:read:followers",
|
|
"channel:manage:moderators",
|
|
"channel:manage:redemptions",
|
|
"channel:manage:broadcast",
|
|
"channel:read:subscriptions",
|
|
"channel:read:redemptions",
|
|
"user:read:email",
|
|
}
|
|
state := generateState()
|
|
authStates.Store(state, "user")
|
|
url := s.twitchAuth.GenerateAuthURL(scopes, state)
|
|
_ = s.twitchAuth.StartTempServer()
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"url": url})
|
|
}
|
|
|
|
func (s *Server) apiTwitchAuthBotHandler(w http.ResponseWriter, _ *http.Request) {
|
|
scopes := []string{
|
|
"moderator:manage:shoutouts",
|
|
"moderator:manage:announcements",
|
|
"moderator:manage:banned_users",
|
|
"moderator:manage:warnings",
|
|
"moderator:read:followers",
|
|
"channel:manage:raids",
|
|
"channel:manage:moderators",
|
|
"channel:read:redemptions",
|
|
"chat:read",
|
|
"chat:edit",
|
|
"user:read:emotes",
|
|
}
|
|
state := generateState()
|
|
authStates.Store(state, "bot")
|
|
url := s.twitchAuth.GenerateAuthURL(scopes, state) + "&force_verify=true"
|
|
_ = s.twitchAuth.StartTempServer()
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"url": url})
|
|
}
|
|
|
|
func (s *Server) apiTwitchAuthCallbackHandler(w http.ResponseWriter, r *http.Request) {
|
|
token := r.URL.Query().Get("token")
|
|
state := r.URL.Query().Get("state")
|
|
if token == "" || state == "" {
|
|
http.Error(w, "missing token or state", 400)
|
|
return
|
|
}
|
|
|
|
val, ok := authStates.Load(state)
|
|
if !ok {
|
|
http.Error(w, "invalid state", 400)
|
|
return
|
|
}
|
|
authType := val.(string)
|
|
authStates.Delete(state)
|
|
|
|
username, err := getUserFromToken(token)
|
|
if err != nil {
|
|
logger.Error("Failed to get username from token: %v", err)
|
|
http.Error(w, "failed to get user info", 500)
|
|
return
|
|
}
|
|
|
|
tokens, _ := db.GetPlatformTokens("twitch")
|
|
if tokens == nil {
|
|
tokens = &db.PlatformTokens{}
|
|
}
|
|
if authType == "user" {
|
|
tokens.UserToken = token
|
|
tokens.UserLogin = username
|
|
} else {
|
|
tokens.BotToken = token
|
|
tokens.BotLogin = username
|
|
}
|
|
if err := db.SetPlatformTokens("twitch", tokens); err != nil {
|
|
logger.Error("Failed to save tokens: %v", err)
|
|
http.Error(w, "db error", 500)
|
|
return
|
|
}
|
|
|
|
if p := s.platformMgr.GetPlatform("twitch"); p != nil {
|
|
p.Disconnect()
|
|
_ = p.Connect()
|
|
}
|
|
|
|
updateMutex.Lock()
|
|
if authType == "user" {
|
|
tokenUpdatedUser = true
|
|
} else {
|
|
tokenUpdatedBot = true
|
|
}
|
|
updateMutex.Unlock()
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
|
}
|
|
|
|
func generateState() string {
|
|
b := make([]byte, 16)
|
|
_, _ = rand.Read(b)
|
|
return base64.URLEncoding.EncodeToString(b)
|
|
}
|
|
|
|
func getUserFromToken(token string) (string, error) {
|
|
req, err := http.NewRequest("GET", "https://id.twitch.tv/oauth2/validate", nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func(Body io.ReadCloser) {
|
|
_ = Body.Close()
|
|
}(resp.Body)
|
|
if resp.StatusCode != 200 {
|
|
return "", fmt.Errorf("token invalid, status %d", resp.StatusCode)
|
|
}
|
|
var result struct {
|
|
Login string `json:"login"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
|
return "", err
|
|
}
|
|
return result.Login, nil
|
|
}
|
|
|
|
func (s *Server) apiTwitchTokenCheckHandler(w http.ResponseWriter, r *http.Request) {
|
|
authType := r.URL.Query().Get("type")
|
|
updated := false
|
|
if authType == "user" && tokenUpdatedUser {
|
|
updated = true
|
|
tokenUpdatedUser = false
|
|
} else if authType == "bot" && tokenUpdatedBot {
|
|
updated = true
|
|
tokenUpdatedBot = false
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]bool{"updated": updated})
|
|
}
|
|
|
|
func (s *Server) apiTwitchTokenExpiryHandler(w http.ResponseWriter, _ *http.Request) {
|
|
tokens, err := db.GetPlatformTokens("twitch")
|
|
if err != nil || tokens == nil {
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"user_expiry_days": nil,
|
|
"bot_expiry_days": nil,
|
|
})
|
|
return
|
|
}
|
|
|
|
userExpiry := getTokenExpiryDays(tokens.UserToken)
|
|
botExpiry := getTokenExpiryDays(tokens.BotToken)
|
|
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"user_expiry_days": userExpiry,
|
|
"bot_expiry_days": botExpiry,
|
|
})
|
|
}
|
|
|
|
func getTokenExpiryDays(token string) interface{} {
|
|
if token == "" {
|
|
return nil
|
|
}
|
|
req, err := http.NewRequest("GET", "https://id.twitch.tv/oauth2/validate", nil)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer func(Body io.ReadCloser) {
|
|
_ = Body.Close()
|
|
}(resp.Body)
|
|
if resp.StatusCode != 200 {
|
|
return nil
|
|
}
|
|
var result struct {
|
|
ExpiresIn int `json:"expires_in"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
|
return nil
|
|
}
|
|
days := result.ExpiresIn / 86400
|
|
if days < 0 {
|
|
days = 0
|
|
}
|
|
return days
|
|
}
|
|
|
|
func corsMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (s *Server) apiUsersHandler(w http.ResponseWriter, _ *http.Request) {
|
|
users := s.platformMgr.GetAllUsers()
|
|
_ = json.NewEncoder(w).Encode(users)
|
|
}
|
|
|
|
func (s *Server) apiUserActionHandler(w http.ResponseWriter, r *http.Request) {
|
|
var req UserActionRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
platform := s.platformMgr.GetPlatform(req.Platform)
|
|
if platform == nil {
|
|
http.Error(w, "platform not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
tw, ok := platform.(*platforms.TwitchPlatform)
|
|
if !ok {
|
|
http.Error(w, "only twitch supported", http.StatusBadRequest)
|
|
return
|
|
}
|
|
switch req.Action {
|
|
case "warn":
|
|
_ = tw.SendMessage("/warn " + req.Username)
|
|
case "timeout10sec":
|
|
if err := tw.TimeoutUserViaAPI(req.Username, 10); err != nil {
|
|
logger.Error("Timeout error: %v", err)
|
|
}
|
|
case "timeout10min":
|
|
if err := tw.TimeoutUserViaAPI(req.Username, 600); err != nil {
|
|
logger.Error("Timeout error: %v", err)
|
|
}
|
|
case "ban":
|
|
if err := tw.BanUserViaAPI(req.Username); err != nil {
|
|
logger.Error("Ban error: %v", err)
|
|
}
|
|
case "unban":
|
|
if err := tw.UnbanUserViaAPI(req.Username); err != nil {
|
|
logger.Error("Unban error: %v", err)
|
|
}
|
|
case "set_vip":
|
|
if err := tw.AddVipViaAPI(req.Username); err != nil {
|
|
logger.Error("Add VIP error: %v", err)
|
|
} else {
|
|
s.platformMgr.SetVip(req.Username, true)
|
|
}
|
|
case "unset_vip":
|
|
if err := tw.RemoveVipViaAPI(req.Username); err != nil {
|
|
logger.Error("Remove VIP error: %v", err)
|
|
} else {
|
|
s.platformMgr.SetVip(req.Username, false)
|
|
}
|
|
case "set_mod":
|
|
if err := tw.AddModViaAPI(req.Username); err != nil {
|
|
logger.Error("Add mod error: %v", err)
|
|
} else {
|
|
s.platformMgr.SetMod(req.Username, true)
|
|
}
|
|
case "unset_mod":
|
|
if err := tw.RemoveModViaAPI(req.Username); err != nil {
|
|
logger.Error("Remove mod error: %v", err)
|
|
} else {
|
|
s.platformMgr.SetMod(req.Username, false)
|
|
}
|
|
case "toggle_mark":
|
|
marked, _, _ := db.IsUserMarked(req.Username, req.Platform)
|
|
newMarked := !marked
|
|
_ = db.SetUserMarked(req.Username, req.Platform, newMarked)
|
|
s.platformMgr.SetMarked(req.Username, newMarked)
|
|
default:
|
|
http.Error(w, "unknown action", http.StatusBadRequest)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) aiPageHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/ai.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) apiAIConfigHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
cfg, err := db.GetAIConfig()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(cfg)
|
|
return
|
|
}
|
|
if r.Method == http.MethodPost {
|
|
bodyBytes, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
|
|
var cfg db.AIConfig
|
|
if err := json.Unmarshal(bodyBytes, &cfg); err != nil {
|
|
logger.Error("JSON decode error: %v", err)
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
|
|
if err := db.SaveAIConfig(&cfg); err != nil {
|
|
logger.Error("Save error: %v", err)
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
|
|
provider, err := ai.NewProvider(&cfg)
|
|
if err != nil {
|
|
logger.Warn("Failed to recreate AI provider: %v", err)
|
|
} else {
|
|
s.cmdProc.UpdateAIProvider(provider)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
|
|
func (s *Server) apiAITestHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", 405)
|
|
return
|
|
}
|
|
var req struct {
|
|
Prompt string `json:"prompt"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
cfg, err := db.GetAIConfig()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
provider, err := ai.NewProvider(cfg)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
answer, err := provider.Ask(context.Background(), req.Prompt)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"answer": answer})
|
|
}
|
|
|
|
func (s *Server) apiTwitchEventSubStatusHandler(w http.ResponseWriter, _ *http.Request) {
|
|
connected, subscriptions, err := s.platformMgr.GetTwitchEventSubStatus()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"connected": connected,
|
|
"subscriptions": subscriptions,
|
|
})
|
|
}
|
|
|
|
func (s *Server) apiWebserviceURLHandler(w http.ResponseWriter, _ *http.Request) {
|
|
url := "http://localhost:8080"
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"url": url})
|
|
}
|
|
|
|
func (s *Server) notificationsHandler(w http.ResponseWriter, _ *http.Request) {
|
|
t := template.Must(template.ParseFS(s.assets, "internal/webui/templates/base.html", "internal/webui/templates/notifications.html"))
|
|
_ = t.Execute(w, nil)
|
|
}
|
|
|
|
func (s *Server) apiNotificationsHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
settings := s.notifMgr.GetAll()
|
|
_ = json.NewEncoder(w).Encode(settings)
|
|
return
|
|
}
|
|
if r.Method == http.MethodPost {
|
|
var ns db.NotificationSetting
|
|
if err := json.NewDecoder(r.Body).Decode(&ns); err != nil {
|
|
logger.Error("Failed to decode notification setting: %v", err)
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
logger.Info("Saving notification setting: %+v", ns)
|
|
if err := s.notifMgr.UpdateSetting(&ns); err != nil {
|
|
logger.Error("UpdateSetting error: %v", err)
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
|
|
func (s *Server) apiNotificationTestHandler(w http.ResponseWriter, r *http.Request) {
|
|
eventName := r.URL.Query().Get("event")
|
|
if eventName == "" {
|
|
http.Error(w, "missing event", 400)
|
|
return
|
|
}
|
|
_ = s.notifMgr.PlayEvent(eventName)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiSoundsHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
files, _ := filepath.Glob("data/sounds/*.mp3")
|
|
wavs, _ := filepath.Glob("data/sounds/*.wav")
|
|
files = append(files, wavs...)
|
|
names := make([]string, len(files))
|
|
for i, f := range files {
|
|
names[i] = filepath.Base(f)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(names)
|
|
return
|
|
}
|
|
if r.Method == http.MethodDelete {
|
|
filename := r.URL.Query().Get("file")
|
|
if filename == "" {
|
|
http.Error(w, "missing file", 400)
|
|
return
|
|
}
|
|
path := filepath.Join("data/sounds", filepath.Base(filename))
|
|
if err := os.Remove(path); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
|
|
func (s *Server) apiSoundsUploadHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", 405)
|
|
return
|
|
}
|
|
file, header, err := r.FormFile("sound")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
defer func(file multipart.File) {
|
|
_ = file.Close()
|
|
}(file)
|
|
outPath := filepath.Join("data/sounds", filepath.Base(header.Filename))
|
|
out, err := os.Create(outPath)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
defer func(out *os.File) {
|
|
_ = out.Close()
|
|
}(out)
|
|
_, _ = io.Copy(out, file)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiObsNotifyHandler(w http.ResponseWriter, r *http.Request) {
|
|
event := r.URL.Query().Get("event")
|
|
if event == "" {
|
|
http.Error(w, "missing event", 400)
|
|
return
|
|
}
|
|
go func() {
|
|
_ = s.notifMgr.PlayEvent(event)
|
|
}()
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
// apiWebServiceMediaHandler управляет медиафайлами (изображения, звуки)
|
|
func (s *Server) apiWebServiceMediaHandler(w http.ResponseWriter, r *http.Request) {
|
|
mediaDir := "data/web"
|
|
if err := os.MkdirAll(mediaDir, 0755); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
files, err := os.ReadDir(mediaDir)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
var result []map[string]string
|
|
for _, f := range files {
|
|
if f.IsDir() {
|
|
continue
|
|
}
|
|
name := f.Name()
|
|
ext := strings.ToLower(filepath.Ext(name))
|
|
typ := "unknown"
|
|
if ext == ".png" || ext == ".gif" || ext == ".jpg" || ext == ".jpeg" {
|
|
typ = "image"
|
|
} else if ext == ".mp3" || ext == ".wav" {
|
|
typ = "sound"
|
|
}
|
|
result = append(result, map[string]string{"name": name, "type": typ})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(result)
|
|
|
|
case http.MethodPost:
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer func(file multipart.File) {
|
|
_ = file.Close()
|
|
}(file)
|
|
filename := filepath.Base(header.Filename)
|
|
outPath := filepath.Join(mediaDir, filename)
|
|
out, err := os.Create(outPath)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer func(out *os.File) {
|
|
_ = out.Close()
|
|
}(out)
|
|
if _, err := io.Copy(out, file); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
case http.MethodDelete:
|
|
filename := r.URL.Query().Get("file")
|
|
if filename == "" {
|
|
http.Error(w, "missing file parameter", http.StatusBadRequest)
|
|
return
|
|
}
|
|
filename = filepath.Base(filename)
|
|
path := filepath.Join(mediaDir, filename)
|
|
if err := os.Remove(path); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
default:
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
// --- НОВЫЕ API для множественных сервисов ---
|
|
func (s *Server) apiWebServicesList(w http.ResponseWriter, _ *http.Request) {
|
|
list, err := db.GetAllWebServices()
|
|
if err != nil {
|
|
logger.Error("GetAllWebServices error: %v", err)
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(list)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesCreate(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Type string `json:"type"`
|
|
Port int `json:"port"`
|
|
Config interface{} `json:"config"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
id, err := s.webSrvMgr.AddService(req.Type, req.Port, req.Config)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
// Автоматически запускаем созданный сервис
|
|
if err := s.webSrvMgr.StartService(id); err != nil {
|
|
logger.Error("Failed to start service %d: %v", id, err)
|
|
// Не возвращаем ошибку, сервис хотя бы создан
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]int{"id": id})
|
|
}
|
|
|
|
func (s *Server) apiWebServicesUpdateConfig(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPut {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var req struct {
|
|
Type string `json:"type"`
|
|
Port int `json:"port"`
|
|
Config interface{} `json:"config"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
if err := db.UpdateWebService(id, req.Port, req.Config, req.Enabled); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
// Если сервис запущен, перезапускаем его с новой конфигурацией
|
|
if srv := s.webSrvMgr.GetService(id); srv != nil && srv.IsRunning() {
|
|
_ = s.webSrvMgr.StopService(id)
|
|
_ = s.webSrvMgr.StartService(id)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesStart(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := s.webSrvMgr.StartService(id); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesStop(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := s.webSrvMgr.StopService(id); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesDelete(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodDelete {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
idStr := r.URL.Query().Get("id")
|
|
id, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := s.webSrvMgr.DeleteService(id); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesTestChat(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
idStr := r.URL.Query().Get("id")
|
|
_, err := strconv.Atoi(idStr)
|
|
if err != nil {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Message string `json:"message"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
if req.Username == "" {
|
|
req.Username = "TestUser"
|
|
}
|
|
s.webSrvMgr.SendChatMessage(webservices.ChatMessage{
|
|
Username: req.Username,
|
|
Message: req.Message,
|
|
Timestamp: time.Now().Unix(),
|
|
})
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) apiWebServicesTestAlert(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
var req struct {
|
|
ServiceID int `json:"serviceId"`
|
|
EventType string `json:"eventType"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
// Проверяем, существует ли сервис
|
|
srv := s.webSrvMgr.GetService(req.ServiceID)
|
|
if srv == nil || srv.GetType() != "alert" {
|
|
http.Error(w, "alert service not found", 404)
|
|
return
|
|
}
|
|
// Отправляем тестовое событие
|
|
data := map[string]interface{}{
|
|
"username": "TestUser",
|
|
"tier": "1000",
|
|
"viewers": 42,
|
|
"gifter": "Gifter",
|
|
"cumulative_total": 5,
|
|
"reward_title": "Test Reward",
|
|
}
|
|
s.webSrvMgr.SendAlertEvent(webservices.AlertEvent{Type: req.EventType, Data: data})
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
// apiDuplicateSoundsHandler управляет настройкой дублирования звуков из команд
|
|
func (s *Server) apiDuplicateSoundsHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
val, _ := db.GetSetting("duplicate_command_sounds")
|
|
enabled := val == "true"
|
|
_ = json.NewEncoder(w).Encode(map[string]bool{"enabled": enabled})
|
|
return
|
|
}
|
|
if r.Method == http.MethodPost {
|
|
var req struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
val := "false"
|
|
if req.Enabled {
|
|
val = "true"
|
|
}
|
|
if err := db.SetSetting("duplicate_command_sounds", val); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
|
|
// apiSoundsListHandler возвращает список звуковых файлов из data/sounds
|
|
func (s *Server) apiSoundsListHandler(w http.ResponseWriter, _ *http.Request) {
|
|
files, err := filepath.Glob("data/sounds/*.mp3")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
wavs, _ := filepath.Glob("data/sounds/*.wav")
|
|
files = append(files, wavs...)
|
|
names := make([]string, len(files))
|
|
for i, f := range files {
|
|
names[i] = filepath.Base(f)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(names)
|
|
}
|
|
|
|
// apiImagesListHandler возвращает список изображений из data/web
|
|
func (s *Server) apiImagesListHandler(w http.ResponseWriter, _ *http.Request) {
|
|
files, err := filepath.Glob("data/web/*.png")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
jpgs, _ := filepath.Glob("data/web/*.jpg")
|
|
files = append(files, jpgs...)
|
|
jpegs, _ := filepath.Glob("data/web/*.jpeg")
|
|
files = append(files, jpegs...)
|
|
gifs, _ := filepath.Glob("data/web/*.gif")
|
|
files = append(files, gifs...)
|
|
names := make([]string, len(files))
|
|
for i, f := range files {
|
|
names[i] = filepath.Base(f)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(names)
|
|
}
|
|
|
|
// apiWebServicesAlertList возвращает список ID и портов alert-сервисов для выпадающего списка
|
|
func (s *Server) apiWebServicesAlertList(w http.ResponseWriter, r *http.Request) {
|
|
services, err := db.GetAllWebServices()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
type AlertInfo struct {
|
|
ID int `json:"id"`
|
|
Port int `json:"port"`
|
|
Name string `json:"name"`
|
|
}
|
|
var result []AlertInfo
|
|
for _, svc := range services {
|
|
if svc.Type == "alert" {
|
|
result = append(result, AlertInfo{
|
|
ID: svc.ID,
|
|
Port: svc.Port,
|
|
Name: fmt.Sprintf("Alert на порту %d", svc.Port),
|
|
})
|
|
}
|
|
}
|
|
json.NewEncoder(w).Encode(result)
|
|
}
|
|
|
|
func (s *Server) apiHotkeySettingHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
val, _ := db.GetSetting("hotkey_enabled")
|
|
enabled := val == "true"
|
|
json.NewEncoder(w).Encode(map[string]bool{"enabled": enabled})
|
|
return
|
|
}
|
|
if r.Method == http.MethodPost {
|
|
var req struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
val := "false"
|
|
if req.Enabled {
|
|
val = "true"
|
|
}
|
|
if err := db.SetSetting("hotkey_enabled", val); err != nil {
|
|
http.Error(w, err.Error(), 500)
|
|
return
|
|
}
|
|
// Применяем настройку к пакету hotkey
|
|
hotkey.SetEnabled(req.Enabled)
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
http.Error(w, "method not allowed", 405)
|
|
}
|
|
|
|
func (s *Server) apiLogsDownloadHandler(w http.ResponseWriter, r *http.Request) {
|
|
entries := logger.GetAll()
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
w.Header().Set("Content-Disposition", "attachment; filename=\"bot_logs.txt\"")
|
|
for _, e := range entries {
|
|
line := fmt.Sprintf("[%s] [%s] %s\n", e.Time.Format("2006-01-02 15:04:05"), e.Level, e.Message)
|
|
_, _ = w.Write([]byte(line))
|
|
}
|
|
}
|