package handlers
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"neomovies-api/pkg/config"
"neomovies-api/pkg/players"
)
type PlayersHandler struct {
config *config.Config
}
func NewPlayersHandler(cfg *config.Config) *PlayersHandler {
return &PlayersHandler{
config: cfg,
}
}
func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request) {
log.Printf("GetAllohaPlayer called: %s %s", r.Method, r.URL.Path)
vars := mux.Vars(r)
idType := vars["id_type"]
id := vars["id"]
if idType == "" || id == "" {
log.Printf("Error: id_type or id is empty")
http.Error(w, "id_type and id are required", http.StatusBadRequest)
return
}
if idType == "kinopoisk_id" { idType = "kp" }
if idType != "kp" && idType != "imdb" {
log.Printf("Error: invalid id_type: %s", idType)
http.Error(w, "id_type must be 'kp' (kinopoisk_id) or 'imdb'", http.StatusBadRequest)
return
}
log.Printf("Processing %s ID: %s", idType, id)
if h.config.AllohaToken == "" {
log.Printf("Error: ALLOHA_TOKEN is missing")
http.Error(w, "Server misconfiguration: ALLOHA_TOKEN missing", http.StatusInternalServerError)
return
}
idParam := fmt.Sprintf("%s=%s", idType, url.QueryEscape(id))
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&%s", h.config.AllohaToken, idParam)
log.Printf("Calling Alloha API: %s", apiURL)
client := &http.Client{Timeout: 8 * time.Second}
resp, err := client.Get(apiURL)
if err != nil {
log.Printf("Error calling Alloha API: %v", err)
http.Error(w, "Failed to fetch from Alloha API", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
log.Printf("Alloha API response status: %d", resp.StatusCode)
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("Alloha API error: %d", resp.StatusCode), http.StatusBadGateway)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading Alloha response: %v", err)
http.Error(w, "Failed to read Alloha response", http.StatusInternalServerError)
return
}
log.Printf("Alloha API response body: %s", string(body))
var allohaResponse struct {
Status string `json:"status"`
Data struct {
Iframe string `json:"iframe"`
} `json:"data"`
}
if err := json.Unmarshal(body, &allohaResponse); err != nil {
log.Printf("Error unmarshaling JSON: %v", err)
http.Error(w, "Invalid JSON from Alloha", http.StatusBadGateway)
return
}
if allohaResponse.Status != "success" || allohaResponse.Data.Iframe == "" {
log.Printf("Video not found or empty iframe")
http.Error(w, "Video not found", http.StatusNotFound)
return
}
// Получаем параметры для сериалов
season := r.URL.Query().Get("season")
episode := r.URL.Query().Get("episode")
translation := r.URL.Query().Get("translation")
if translation == "" {
translation = "66" // дефолтная озвучка
}
// Используем iframe URL из API
iframeCode := allohaResponse.Data.Iframe
// Если это не HTML код, а просто URL
var playerURL string
if !strings.Contains(iframeCode, "<") {
playerURL = iframeCode
// Добавляем параметры для сериалов
if season != "" && episode != "" {
separator := "?"
if strings.Contains(playerURL, "?") {
separator = "&"
}
playerURL = fmt.Sprintf("%s%sseason=%s&episode=%s&translation=%s", playerURL, separator, season, episode, translation)
}
iframeCode = fmt.Sprintf(``, playerURL)
}
htmlDoc := fmt.Sprintf(`
Alloha Player%s`, iframeCode)
// Авто-исправление экранированных кавычек
htmlDoc = strings.ReplaceAll(htmlDoc, `\"`, `"`)
htmlDoc = strings.ReplaceAll(htmlDoc, `\'`, `'`)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(htmlDoc))
log.Printf("Successfully served Alloha player for %s: %s", idType, id)
}
// GetAllohaMetaByKP returns seasons/episodes meta for Alloha by kinopoisk_id
func (h *PlayersHandler) GetAllohaMetaByKP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
kpID := vars["kp_id"]
if strings.TrimSpace(kpID) == "" {
http.Error(w, "kp_id is required", http.StatusBadRequest)
return
}
if h.config.AllohaToken == "" {
http.Error(w, "Server misconfiguration: ALLOHA_TOKEN missing", http.StatusInternalServerError)
return
}
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&kp=%s", url.QueryEscape(h.config.AllohaToken), url.QueryEscape(kpID))
client := &http.Client{Timeout: 8 * time.Second}
resp, err := client.Get(apiURL)
if err != nil {
http.Error(w, "Failed to fetch from Alloha API", http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("Alloha API error: %d", resp.StatusCode), http.StatusBadGateway)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "Failed to read Alloha response", http.StatusBadGateway)
return
}
// Define only the parts we need
var raw struct {
Status string `json:"status"`
Data struct {
Seasons []struct {
Key string `json:"key"`
Value struct {
Episodes []struct {
Key string `json:"key"`
Value struct {
Translation []struct {
Value struct {
Translation string `json:"translation"`
} `json:"value"`
} `json:"translation"`
} `json:"value"`
} `json:"episodes"`
} `json:"value"`
} `json:"seasons"`
} `json:"data"`
}
if err := json.Unmarshal(body, &raw); err != nil {
http.Error(w, "Invalid JSON from Alloha", http.StatusBadGateway)
return
}
type episodeMeta struct {
Episode int `json:"episode"`
Translations []string `json:"translations"`
}
type seasonMeta struct {
Season int `json:"season"`
Episodes []episodeMeta `json:"episodes"`
}
out := struct {
Success bool `json:"success"`
Seasons []seasonMeta `json:"seasons"`
}{Success: true}
for _, s := range raw.Data.Seasons {
seasonNum, _ := strconv.Atoi(strings.TrimSpace(s.Key))
sm := seasonMeta{Season: seasonNum}
for _, e := range s.Value.Episodes {
epNum, _ := strconv.Atoi(strings.TrimSpace(e.Key))
em := episodeMeta{Episode: epNum}
for _, tr := range e.Value.Translation {
t := strings.TrimSpace(tr.Value.Translation)
if t != "" {
em.Translations = append(em.Translations, t)
}
}
sm.Episodes = append(sm.Episodes, em)
}
out.Seasons = append(out.Seasons, sm)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
}
func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request) {
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
vars := mux.Vars(r)
idType := vars["id_type"]
id := vars["id"]
if idType == "" || id == "" {
log.Printf("Error: id_type or id is empty")
http.Error(w, "id_type and id are required", http.StatusBadRequest)
return
}
// Поддержка алиаса
if idType == "kinopoisk_id" { idType = "kp" }
if idType != "kp" && idType != "imdb" {
log.Printf("Error: invalid id_type: %s", idType)
http.Error(w, "id_type must be 'kp' or 'imdb'", http.StatusBadRequest)
return
}
log.Printf("Processing %s ID: %s", idType, id)
if h.config.LumexURL == "" {
log.Printf("Error: LUMEX_URL is missing")
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
return
}
// Встраивание напрямую через p.lumex.cloud: