4 Commits

3 changed files with 109 additions and 28 deletions

View File

@@ -4,9 +4,11 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"neomovies-api/pkg/config" "neomovies-api/pkg/config"
@@ -26,7 +28,13 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
return return
} }
if imagePath == "placeholder.jpg" { // Попробуем декодировать путь заранее (на фронте абсолютные URL передаются как encodeURIComponent)
decodedPath := imagePath
if dp, err := url.QueryUnescape(imagePath); err == nil {
decodedPath = dp
}
if imagePath == "placeholder.jpg" || decodedPath == "placeholder.jpg" {
h.servePlaceholder(w, r) h.servePlaceholder(w, r)
return return
} }
@@ -37,15 +45,79 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
} }
var imageURL string var imageURL string
if strings.HasPrefix(imagePath, "http://") || strings.HasPrefix(imagePath, "https://") { // Нормализуем абсолютные ссылки вида "https:/..." → "https://...", а также "//..." → "https://..."
normalized := decodedPath
if strings.HasPrefix(normalized, "//") {
normalized = "https:" + normalized
}
if strings.HasPrefix(normalized, "http:/") && !strings.HasPrefix(normalized, "http://") {
normalized = strings.Replace(normalized, "http:/", "http://", 1)
}
if strings.HasPrefix(normalized, "https:/") && !strings.HasPrefix(normalized, "https://") {
normalized = strings.Replace(normalized, "https:/", "https://", 1)
}
if strings.HasPrefix(normalized, "http://") || strings.HasPrefix(normalized, "https://") {
// Проксируем внешний абсолютный URL (например, Kinopoisk) // Проксируем внешний абсолютный URL (например, Kinopoisk)
imageURL = imagePath imageURL = normalized
} else { } else {
// TMDB относительный путь // TMDB относительный путь
imageURL = fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath) imageURL = fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath)
} }
resp, err := http.Get(imageURL) client := &http.Client{Timeout: 12 * time.Second}
// Подготовим несколько вариантов заголовков для обхода ограничений источников
buildRequest := func(targetURL string, attempt int) (*http.Request, error) {
req, err := http.NewRequest("GET", targetURL, nil)
if err != nil {
return nil, err
}
// Универсальные заголовки как у браузера
req.Header.Set("Accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8")
req.Header.Set("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7")
if ua := r.Header.Get("User-Agent"); ua != "" {
req.Header.Set("User-Agent", ua)
} else {
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0 Safari/537.36")
}
// Настройка Referer: для Yandex/Kinopoisk ставим kinopoisk.ru, иначе — origin URL
parsed, _ := url.Parse(targetURL)
host := strings.ToLower(parsed.Host)
switch attempt {
case 0:
if strings.Contains(host, "kinopoisk") || strings.Contains(host, "yandex") {
req.Header.Set("Referer", "https://www.kinopoisk.ru/")
} else if parsed.Scheme != "" && parsed.Host != "" {
req.Header.Set("Referer", parsed.Scheme+"://"+parsed.Host+"/")
}
case 1:
// Без Referer
default:
// Оставляем как есть
}
return req, nil
}
// До 2-х попыток: с реферером источника и без реферера
var resp *http.Response
var err error
for attempt := 0; attempt < 2; attempt++ {
var req *http.Request
req, err = buildRequest(imageURL, attempt)
if err != nil {
continue
}
resp, err = client.Do(req)
if err == nil && resp != nil && resp.StatusCode == http.StatusOK {
break
}
if resp != nil {
resp.Body.Close()
}
}
if err != nil { if err != nil {
h.servePlaceholder(w, r) h.servePlaceholder(w, r)
return return

View File

@@ -152,6 +152,8 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
return return
} }
// Поддержка алиаса
if idType == "kinopoisk_id" { idType = "kp" }
if idType != "kp" && idType != "imdb" { if idType != "kp" && idType != "imdb" {
log.Printf("Error: invalid id_type: %s", idType) log.Printf("Error: invalid id_type: %s", idType)
http.Error(w, "id_type must be 'kp' or 'imdb'", http.StatusBadRequest) http.Error(w, "id_type must be 'kp' or 'imdb'", http.StatusBadRequest)
@@ -166,21 +168,20 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
return return
} }
// Формируем запрос вида: https://portal.lumex.host/api/short?api_token=...&kinopoisk_id=... // Встраивание напрямую через p.lumex.cloud: <iframe src="//p.lumex.cloud/<code>?kp_id=...">
// Ожидается, что LUMEX_URL уже содержит базовый URL и api_token, например: // Ожидается, что LUMEX_URL задаёт базу вида: https://p.lumex.cloud/<code>
// LUMEX_URL=https://portal.lumex.host/api/short?api_token=XXXX
var paramName string var paramName string
if idType == "kp" { if idType == "kp" {
paramName = "kinopoisk_id" paramName = "kp_id"
} else { } else {
paramName = "imdb_id" paramName = "imdb_id"
} }
separator := "&" separator := "?"
if !strings.Contains(h.config.LumexURL, "?") { if strings.Contains(h.config.LumexURL, "?") {
separator = "?" separator = "&"
} }
playerURL := fmt.Sprintf("%s% s%s=%s", h.config.LumexURL, separator, paramName, id) playerURL := fmt.Sprintf("%s%s%s=%s", h.config.LumexURL, separator, paramName, url.QueryEscape(id))
log.Printf("Lumex URL: %s", playerURL) log.Printf("Lumex URL: %s", playerURL)
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, playerURL) iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, playerURL)

View File

@@ -2,6 +2,7 @@ package services
import ( import (
"fmt" "fmt"
"net/url"
"strconv" "strconv"
"strings" "strings"
@@ -10,20 +11,26 @@ import (
const tmdbImageBase = "https://image.tmdb.org/t/p" const tmdbImageBase = "https://image.tmdb.org/t/p"
func BuildTMDBImageURL(path string, size string) string { // BuildAPIImageProxyURL строит относительный URL до нашего прокси-эндпоинта изображений.
if path == "" { // Если передан абсолютный URL (KP и пр.) — он кодируется и передаётся как path параметр.
// Если передан относительный TMDB-путь, он используется как есть (без ведущего '/').
func BuildAPIImageProxyURL(pathOrURL string, size string) string {
if strings.TrimSpace(pathOrURL) == "" {
return "" return ""
} }
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return path
}
if size == "" { if size == "" {
size = "w500" size = "w500"
} }
if !strings.HasPrefix(path, "/") { // Абсолютные ссылки (Kinopoisk и пр.) — кодируем целиком
path = "/" + path if strings.HasPrefix(pathOrURL, "http://") || strings.HasPrefix(pathOrURL, "https://") {
return fmt.Sprintf("/api/v1/images/%s/%s", size, url.QueryEscape(pathOrURL))
} }
return fmt.Sprintf("%s/%s%s", tmdbImageBase, size, path) // TMDB относительный путь
clean := pathOrURL
if strings.HasPrefix(clean, "/") {
clean = clean[1:]
}
return fmt.Sprintf("/api/v1/images/%s/%s", size, clean)
} }
func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *models.UnifiedContent { func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *models.UnifiedContent {
@@ -74,8 +81,8 @@ func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *m
Type: "movie", Type: "movie",
Genres: genres, Genres: genres,
Rating: movie.VoteAverage, Rating: movie.VoteAverage,
PosterURL: BuildTMDBImageURL(movie.PosterPath, "w500"), PosterURL: BuildAPIImageProxyURL(movie.PosterPath, "w500"),
BackdropURL: BuildTMDBImageURL(movie.BackdropPath, "w1280"), BackdropURL: BuildAPIImageProxyURL(movie.BackdropPath, "w1280"),
Director: "", Director: "",
Cast: []models.UnifiedCastMember{}, Cast: []models.UnifiedCastMember{},
Duration: movie.Runtime, Duration: movie.Runtime,
@@ -136,8 +143,8 @@ func MapTMDBTVToUnified(tv *models.TVShow, external *models.ExternalIDs) *models
Type: "tv", Type: "tv",
Genres: genres, Genres: genres,
Rating: tv.VoteAverage, Rating: tv.VoteAverage,
PosterURL: BuildTMDBImageURL(tv.PosterPath, "w500"), PosterURL: BuildAPIImageProxyURL(tv.PosterPath, "w500"),
BackdropURL: BuildTMDBImageURL(tv.BackdropPath, "w1280"), BackdropURL: BuildAPIImageProxyURL(tv.BackdropPath, "w1280"),
Director: "", Director: "",
Cast: []models.UnifiedCastMember{}, Cast: []models.UnifiedCastMember{},
Duration: duration, Duration: duration,
@@ -160,7 +167,7 @@ func MapTMDBTVToUnified(tv *models.TVShow, external *models.ExternalIDs) *models
SeasonNumber: s.SeasonNumber, SeasonNumber: s.SeasonNumber,
EpisodeCount: s.EpisodeCount, EpisodeCount: s.EpisodeCount,
ReleaseDate: s.AirDate, ReleaseDate: s.AirDate,
PosterURL: BuildTMDBImageURL(s.PosterPath, "w500"), PosterURL: BuildAPIImageProxyURL(s.PosterPath, "w500"),
}) })
} }
} }
@@ -185,7 +192,7 @@ func MapTMDBMultiToUnifiedItems(m *models.MultiSearchResponse) []models.UnifiedS
if r.MediaType == "tv" { if r.MediaType == "tv" {
release = r.FirstAirDate release = r.FirstAirDate
} }
poster := BuildTMDBImageURL(r.PosterPath, "w500") poster := BuildAPIImageProxyURL(r.PosterPath, "w500")
tmdbId := r.ID tmdbId := r.ID
items = append(items, models.UnifiedSearchItem{ items = append(items, models.UnifiedSearchItem{
ID: strconv.Itoa(tmdbId), ID: strconv.Itoa(tmdbId),
@@ -216,6 +223,7 @@ func MapKPSearchToUnifiedItems(kps *KPSearchResponse) []models.UnifiedSearchItem
if poster == "" { if poster == "" {
poster = f.PosterUrl poster = f.PosterUrl
} }
poster = BuildAPIImageProxyURL(poster, "w500")
rating := 0.0 rating := 0.0
if strings.TrimSpace(f.Rating) != "" { if strings.TrimSpace(f.Rating) != "" {
if v, err := strconv.ParseFloat(f.Rating, 64); err == nil { if v, err := strconv.ParseFloat(f.Rating, 64); err == nil {