mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-28 01:48:51 +05:00
Compare commits
4 Commits
1f51746740
...
47bcc6589d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47bcc6589d | ||
|
|
95aae4c46d | ||
|
|
2237e27308 | ||
|
|
f8d54a2901 |
@@ -4,9 +4,11 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"neomovies-api/pkg/config"
|
||||
@@ -26,7 +28,13 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
return
|
||||
}
|
||||
@@ -37,15 +45,79 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
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)
|
||||
imageURL = imagePath
|
||||
imageURL = normalized
|
||||
} else {
|
||||
// TMDB относительный путь
|
||||
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 {
|
||||
h.servePlaceholder(w, r)
|
||||
return
|
||||
|
||||
@@ -152,6 +152,8 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
|
||||
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)
|
||||
@@ -166,21 +168,20 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
// Формируем запрос вида: https://portal.lumex.host/api/short?api_token=...&kinopoisk_id=...
|
||||
// Ожидается, что LUMEX_URL уже содержит базовый URL и api_token, например:
|
||||
// LUMEX_URL=https://portal.lumex.host/api/short?api_token=XXXX
|
||||
// Встраивание напрямую через p.lumex.cloud: <iframe src="//p.lumex.cloud/<code>?kp_id=...">
|
||||
// Ожидается, что LUMEX_URL задаёт базу вида: https://p.lumex.cloud/<code>
|
||||
var paramName string
|
||||
if idType == "kp" {
|
||||
paramName = "kinopoisk_id"
|
||||
paramName = "kp_id"
|
||||
} else {
|
||||
paramName = "imdb_id"
|
||||
}
|
||||
|
||||
separator := "&"
|
||||
if !strings.Contains(h.config.LumexURL, "?") {
|
||||
separator = "?"
|
||||
separator := "?"
|
||||
if strings.Contains(h.config.LumexURL, "?") {
|
||||
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)
|
||||
|
||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, playerURL)
|
||||
|
||||
@@ -2,6 +2,7 @@ package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -10,20 +11,26 @@ import (
|
||||
|
||||
const tmdbImageBase = "https://image.tmdb.org/t/p"
|
||||
|
||||
func BuildTMDBImageURL(path string, size string) string {
|
||||
if path == "" {
|
||||
// BuildAPIImageProxyURL строит относительный URL до нашего прокси-эндпоинта изображений.
|
||||
// Если передан абсолютный URL (KP и пр.) — он кодируется и передаётся как path параметр.
|
||||
// Если передан относительный TMDB-путь, он используется как есть (без ведущего '/').
|
||||
func BuildAPIImageProxyURL(pathOrURL string, size string) string {
|
||||
if strings.TrimSpace(pathOrURL) == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
|
||||
return path
|
||||
}
|
||||
if size == "" {
|
||||
size = "w500"
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
// Абсолютные ссылки (Kinopoisk и пр.) — кодируем целиком
|
||||
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 {
|
||||
@@ -74,8 +81,8 @@ func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *m
|
||||
Type: "movie",
|
||||
Genres: genres,
|
||||
Rating: movie.VoteAverage,
|
||||
PosterURL: BuildTMDBImageURL(movie.PosterPath, "w500"),
|
||||
BackdropURL: BuildTMDBImageURL(movie.BackdropPath, "w1280"),
|
||||
PosterURL: BuildAPIImageProxyURL(movie.PosterPath, "w500"),
|
||||
BackdropURL: BuildAPIImageProxyURL(movie.BackdropPath, "w1280"),
|
||||
Director: "",
|
||||
Cast: []models.UnifiedCastMember{},
|
||||
Duration: movie.Runtime,
|
||||
@@ -136,8 +143,8 @@ func MapTMDBTVToUnified(tv *models.TVShow, external *models.ExternalIDs) *models
|
||||
Type: "tv",
|
||||
Genres: genres,
|
||||
Rating: tv.VoteAverage,
|
||||
PosterURL: BuildTMDBImageURL(tv.PosterPath, "w500"),
|
||||
BackdropURL: BuildTMDBImageURL(tv.BackdropPath, "w1280"),
|
||||
PosterURL: BuildAPIImageProxyURL(tv.PosterPath, "w500"),
|
||||
BackdropURL: BuildAPIImageProxyURL(tv.BackdropPath, "w1280"),
|
||||
Director: "",
|
||||
Cast: []models.UnifiedCastMember{},
|
||||
Duration: duration,
|
||||
@@ -160,7 +167,7 @@ func MapTMDBTVToUnified(tv *models.TVShow, external *models.ExternalIDs) *models
|
||||
SeasonNumber: s.SeasonNumber,
|
||||
EpisodeCount: s.EpisodeCount,
|
||||
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" {
|
||||
release = r.FirstAirDate
|
||||
}
|
||||
poster := BuildTMDBImageURL(r.PosterPath, "w500")
|
||||
poster := BuildAPIImageProxyURL(r.PosterPath, "w500")
|
||||
tmdbId := r.ID
|
||||
items = append(items, models.UnifiedSearchItem{
|
||||
ID: strconv.Itoa(tmdbId),
|
||||
@@ -216,6 +223,7 @@ func MapKPSearchToUnifiedItems(kps *KPSearchResponse) []models.UnifiedSearchItem
|
||||
if poster == "" {
|
||||
poster = f.PosterUrl
|
||||
}
|
||||
poster = BuildAPIImageProxyURL(poster, "w500")
|
||||
rating := 0.0
|
||||
if strings.TrimSpace(f.Rating) != "" {
|
||||
if v, err := strconv.ParseFloat(f.Rating, 64); err == nil {
|
||||
|
||||
Reference in New Issue
Block a user