mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-27 17:38:51 +05:00
Compare commits
9 Commits
1f51746740
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c988c762a9 | ||
|
|
f42d548105 | ||
|
|
04fe3f3925 | ||
|
|
53a405a743 | ||
|
|
71ea922528 | ||
|
|
47bcc6589d | ||
|
|
95aae4c46d | ||
|
|
2237e27308 | ||
|
|
f8d54a2901 |
15
README.md
15
README.md
@@ -278,18 +278,15 @@ curl -X POST https://api.neomovies.ru/api/v1/auth/login \
|
||||
}'
|
||||
```
|
||||
|
||||
### Поиск фильмов
|
||||
### Поиск (унифицированный)
|
||||
|
||||
```bash
|
||||
# Поиск фильмов
|
||||
curl "https://api.neomovies.ru/api/v1/movies/search?query=marvel&page=1"
|
||||
# Мультипоиск (источник обязателен)
|
||||
curl "https://api.neomovies.ru/api/v1/search?query=matrix&source=tmdb&page=1"
|
||||
|
||||
# Детали фильма
|
||||
curl "https://api.neomovies.ru/api/v1/movies/550"
|
||||
|
||||
# Добавить в избранное (с JWT токеном)
|
||||
curl -X POST https://api.neomovies.ru/api/v1/favorites/550 \
|
||||
-H "Authorization: Bearer YOUR_JWT_TOKEN"
|
||||
# Детали по униф. ID
|
||||
curl "https://api.neomovies.ru/api/v1/movie/tmdb_550"
|
||||
curl "https://api.neomovies.ru/api/v1/tv/kp_61365"
|
||||
```
|
||||
|
||||
### Поиск торрентов
|
||||
|
||||
@@ -69,7 +69,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
||||
docsHandler := handlersPkg.NewDocsHandler()
|
||||
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
|
||||
unifiedHandler := handlersPkg.NewUnifiedHandler(tmdbService, kpService)
|
||||
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
|
||||
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
||||
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
||||
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
||||
reactionsHandler := handlersPkg.NewReactionsHandler(reactionsService)
|
||||
@@ -96,7 +96,8 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
||||
api.HandleFunc("/categories/{id}/movies", categoriesHandler.GetMoviesByCategory).Methods("GET")
|
||||
api.HandleFunc("/categories/{id}/media", categoriesHandler.GetMediaByCategory).Methods("GET")
|
||||
|
||||
api.HandleFunc("/players/alloha/{id_type}/{id}", playersHandler.GetAllohaPlayer).Methods("GET")
|
||||
api.HandleFunc("/players/alloha/{id_type}/{id}", playersHandler.GetAllohaPlayer).Methods("GET")
|
||||
api.HandleFunc("/players/alloha/meta/kp/{kp_id}", playersHandler.GetAllohaMetaByKP).Methods("GET")
|
||||
api.HandleFunc("/players/lumex/{id_type}/{id}", playersHandler.GetLumexPlayer).Methods("GET")
|
||||
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
||||
api.HandleFunc("/players/hdvb/{id_type}/{id}", playersHandler.GetHDVBPlayer).Methods("GET")
|
||||
|
||||
2
main.go
2
main.go
@@ -49,7 +49,7 @@ func main() {
|
||||
docsHandler := appHandlers.NewDocsHandler()
|
||||
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
|
||||
unifiedHandler := appHandlers.NewUnifiedHandler(tmdbService, kpService)
|
||||
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
|
||||
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
||||
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
||||
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
||||
reactionsHandler := appHandlers.NewReactionsHandler(reactionsService)
|
||||
|
||||
15
netlify.toml
Normal file
15
netlify.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[build]
|
||||
functions = "netlify/functions"
|
||||
|
||||
[build.environment]
|
||||
GO_VERSION = "1.22.6"
|
||||
|
||||
# Optional: include static assets used by handlers (placeholders, etc.)
|
||||
[functions]
|
||||
included_files = ["assets/**", "public/**", "static/**"]
|
||||
|
||||
# Route all API requests to the serverless function "api"
|
||||
[[redirects]]
|
||||
from = "/api/*"
|
||||
to = "/.netlify/functions/api/:splat"
|
||||
status = 200
|
||||
15
netlify/functions/api.go
Normal file
15
netlify/functions/api.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
bridge "github.com/vercel/go-bridge/go/bridge"
|
||||
handler "neomovies-api/api"
|
||||
)
|
||||
|
||||
func main() {
|
||||
bridge.Start(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
handler.Handler(w, r.WithContext(context.Background()))
|
||||
}))
|
||||
}
|
||||
@@ -12,13 +12,18 @@ import (
|
||||
)
|
||||
|
||||
type CategoriesHandler struct {
|
||||
tmdbService *services.TMDBService
|
||||
tmdbService *services.TMDBService
|
||||
kpService *services.KinopoiskService
|
||||
}
|
||||
|
||||
func NewCategoriesHandler(tmdbService *services.TMDBService) *CategoriesHandler {
|
||||
return &CategoriesHandler{
|
||||
tmdbService: tmdbService,
|
||||
}
|
||||
// Для совместимости, kpService может быть добавлен позже через setter при инициализации в main.go/api/index.go
|
||||
return &CategoriesHandler{tmdbService: tmdbService}
|
||||
}
|
||||
|
||||
func (h *CategoriesHandler) WithKinopoisk(kp *services.KinopoiskService) *CategoriesHandler {
|
||||
h.kpService = kp
|
||||
return h
|
||||
}
|
||||
|
||||
type Category struct {
|
||||
@@ -28,14 +33,14 @@ type Category struct {
|
||||
}
|
||||
|
||||
func (h *CategoriesHandler) GetCategories(w http.ResponseWriter, r *http.Request) {
|
||||
// Получаем все жанры
|
||||
genresResponse, err := h.tmdbService.GetAllGenres()
|
||||
// Получаем все жанры
|
||||
genresResponse, err := h.tmdbService.GetAllGenres()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Преобразуем жанры в категории
|
||||
// Преобразуем жанры в категории (пока TMDB). Для KP — можно замаппить фиксированный список
|
||||
var categories []Category
|
||||
for _, genre := range genresResponse.Genres {
|
||||
slug := generateSlug(genre.Name)
|
||||
@@ -67,7 +72,7 @@ func (h *CategoriesHandler) GetMediaByCategory(w http.ResponseWriter, r *http.Re
|
||||
language = "ru-RU"
|
||||
}
|
||||
|
||||
mediaType := r.URL.Query().Get("type")
|
||||
mediaType := r.URL.Query().Get("type")
|
||||
if mediaType == "" {
|
||||
mediaType = "movie" // По умолчанию фильмы для обратной совместимости
|
||||
}
|
||||
@@ -77,16 +82,28 @@ func (h *CategoriesHandler) GetMediaByCategory(w http.ResponseWriter, r *http.Re
|
||||
return
|
||||
}
|
||||
|
||||
var data interface{}
|
||||
var err2 error
|
||||
source := r.URL.Query().Get("source") // "kp" | "tmdb"
|
||||
var data interface{}
|
||||
var err2 error
|
||||
|
||||
if mediaType == "movie" {
|
||||
// Используем discover API для получения фильмов по жанру
|
||||
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
||||
} else {
|
||||
// Используем discover API для получения сериалов по жанру
|
||||
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
||||
}
|
||||
if source == "kp" && h.kpService != nil {
|
||||
// KP не имеет прямого discover по genre id TMDB — здесь можно реализовать маппинг slug->поисковый запрос
|
||||
// Для простоты: используем keyword поиск по имени категории (slug как ключевое слово)
|
||||
// Получим человекочитаемое имя жанра из TMDB как приближение
|
||||
if mediaType == "movie" {
|
||||
// Поиском KP (keyword) эмулируем категорию
|
||||
data, err2 = h.kpService.SearchFilms(r.URL.Query().Get("name"), page)
|
||||
} else {
|
||||
// Для сериалов у KP: используем тот же поиск (KP выдаёт и сериалы в некоторых случаях)
|
||||
data, err2 = h.kpService.SearchFilms(r.URL.Query().Get("name"), page)
|
||||
}
|
||||
} else {
|
||||
if mediaType == "movie" {
|
||||
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
||||
} else {
|
||||
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
||||
}
|
||||
}
|
||||
|
||||
if err2 != nil {
|
||||
http.Error(w, err2.Error(), http.StatusInternalServerError)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
"neomovies-api/pkg/middleware"
|
||||
"neomovies-api/pkg/models"
|
||||
"neomovies-api/pkg/services"
|
||||
"neomovies-api/pkg/config"
|
||||
"neomovies-api/pkg/middleware"
|
||||
"neomovies-api/pkg/models"
|
||||
"neomovies-api/pkg/services"
|
||||
)
|
||||
|
||||
type FavoritesHandler struct {
|
||||
@@ -177,7 +178,8 @@ func (h *FavoritesHandler) fetchMediaInfoRussian(mediaID, mediaType string) (*mo
|
||||
url = fmt.Sprintf("https://api.themoviedb.org/3/tv/%s?api_key=%s&language=ru-RU", mediaID, h.config.TMDBAccessToken)
|
||||
}
|
||||
|
||||
resp, err := http.Get(url)
|
||||
client := &http.Client{Timeout: 6 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch from TMDB: %w", err)
|
||||
}
|
||||
|
||||
@@ -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,20 +45,84 @@ 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
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
h.servePlaceholder(w, r)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -58,7 +59,8 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
||||
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&%s", h.config.AllohaToken, idParam)
|
||||
log.Printf("Calling Alloha API: %s", apiURL)
|
||||
|
||||
resp, err := http.Get(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)
|
||||
@@ -139,6 +141,120 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
||||
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 (map-based structure as в примере)
|
||||
var raw struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
SeasonsCount int `json:"seasons_count"`
|
||||
Seasons map[string]struct {
|
||||
Season int `json:"season"`
|
||||
Episodes map[string]struct {
|
||||
Episode int `json:"episode"`
|
||||
Translation map[string]struct {
|
||||
Translation string `json:"translation"`
|
||||
Name string `json:"name"`
|
||||
} `json:"translation"`
|
||||
} `json:"episodes"`
|
||||
} `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, Seasons: make([]seasonMeta, 0)}
|
||||
|
||||
if raw.Status == "success" && len(raw.Data.Seasons) > 0 {
|
||||
// sort seasons by numeric key
|
||||
seasonKeys := make([]int, 0, len(raw.Data.Seasons))
|
||||
for k := range raw.Data.Seasons {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(k)); err == nil {
|
||||
seasonKeys = append(seasonKeys, n)
|
||||
}
|
||||
}
|
||||
sort.Ints(seasonKeys)
|
||||
|
||||
for _, sn := range seasonKeys {
|
||||
s := raw.Data.Seasons[strconv.Itoa(sn)]
|
||||
sm := seasonMeta{Season: sn}
|
||||
|
||||
// sort episodes by numeric key
|
||||
epKeys := make([]int, 0, len(s.Episodes))
|
||||
for ek := range s.Episodes {
|
||||
if en, err := strconv.Atoi(strings.TrimSpace(ek)); err == nil {
|
||||
epKeys = append(epKeys, en)
|
||||
}
|
||||
}
|
||||
sort.Ints(epKeys)
|
||||
|
||||
for _, en := range epKeys {
|
||||
e := s.Episodes[strconv.Itoa(en)]
|
||||
em := episodeMeta{Episode: en}
|
||||
// collect translations
|
||||
for _, tr := range e.Translation {
|
||||
t := strings.TrimSpace(tr.Translation)
|
||||
if t == "" {
|
||||
t = strings.TrimSpace(tr.Name)
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -152,7 +268,9 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
if idType != "kp" && idType != "imdb" {
|
||||
// Поддержка алиаса
|
||||
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
|
||||
@@ -166,21 +284,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)
|
||||
@@ -600,7 +717,8 @@ func (h *PlayersHandler) GetHDVBPlayer(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
log.Printf("HDVB API URL: %s", apiURL)
|
||||
|
||||
resp, err := http.Get(apiURL)
|
||||
client := &http.Client{Timeout: 8 * time.Second}
|
||||
resp, err := client.Get(apiURL)
|
||||
if err != nil {
|
||||
log.Printf("Error fetching HDVB data: %v", err)
|
||||
http.Error(w, "Failed to fetch player data", http.StatusInternalServerError)
|
||||
|
||||
@@ -75,6 +75,7 @@ type UnifiedSearchItem struct {
|
||||
SourceID string `json:"sourceId"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
OriginalType string `json:"originalType,omitempty"`
|
||||
ReleaseDate string `json:"releaseDate"`
|
||||
PosterURL string `json:"posterUrl"`
|
||||
Rating float64 `json:"rating"`
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
func MapKPFilmToTMDBMovie(kpFilm *KPFilm) *models.Movie {
|
||||
@@ -220,8 +220,8 @@ func MapKPToUnified(kpFilm *KPFilm) *models.UnifiedContent {
|
||||
Type: mapKPTypeToUnified(kpFilm),
|
||||
Genres: genres,
|
||||
Rating: kpFilm.RatingKinopoisk,
|
||||
PosterURL: poster,
|
||||
BackdropURL: kpFilm.CoverUrl,
|
||||
PosterURL: BuildAPIImageProxyURL(poster, "w500"),
|
||||
BackdropURL: BuildAPIImageProxyURL(kpFilm.CoverUrl, "w1280"),
|
||||
Director: "",
|
||||
Cast: []models.UnifiedCastMember{},
|
||||
Duration: kpFilm.FilmLength,
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
@@ -17,11 +18,16 @@ type TMDBService struct {
|
||||
}
|
||||
|
||||
func NewTMDBService(accessToken string) *TMDBService {
|
||||
return &TMDBService{
|
||||
accessToken: accessToken,
|
||||
baseURL: "https://api.themoviedb.org/3",
|
||||
client: &http.Client{},
|
||||
}
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
}
|
||||
return &TMDBService{
|
||||
accessToken: accessToken,
|
||||
baseURL: "https://api.themoviedb.org/3",
|
||||
client: &http.Client{Timeout: 10 * time.Second, Transport: transport},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TMDBService) makeRequest(endpoint string, target interface{}) error {
|
||||
@@ -194,8 +200,10 @@ func (s *TMDBService) FindTMDBIdByIMDB(imdbID string, media string, language str
|
||||
endpoint := fmt.Sprintf("%s/find/%s?%s", s.baseURL, url.PathEscape(imdbID), params.Encode())
|
||||
|
||||
var resp struct {
|
||||
MovieResults []struct{ ID int `json:"id"` } `json:"movie_results"`
|
||||
TVResults []struct{ ID int `json:"id"` } `json:"tv_results"`
|
||||
MovieResults []struct{ ID int `json:"id"` } `json:"movie_results"`
|
||||
TVResults []struct{ ID int `json:"id"` } `json:"tv_results"`
|
||||
TVEpisodeResults []struct{ ShowID int `json:"show_id"` } `json:"tv_episode_results"`
|
||||
TVSeasonResults []struct{ ShowID int `json:"show_id"` } `json:"tv_season_results"`
|
||||
}
|
||||
if err := s.makeRequest(endpoint, &resp); err != nil {
|
||||
return 0, err
|
||||
@@ -217,6 +225,12 @@ func (s *TMDBService) FindTMDBIdByIMDB(imdbID string, media string, language str
|
||||
if len(resp.TVResults) > 0 {
|
||||
return resp.TVResults[0].ID, nil
|
||||
}
|
||||
if len(resp.TVSeasonResults) > 0 {
|
||||
return resp.TVSeasonResults[0].ShowID, nil
|
||||
}
|
||||
if len(resp.TVEpisodeResults) > 0 {
|
||||
return resp.TVEpisodeResults[0].ShowID, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("tmdb id not found for imdb %s", imdbID)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -228,6 +236,7 @@ func MapKPSearchToUnifiedItems(kps *KPSearchResponse) []models.UnifiedSearchItem
|
||||
SourceID: "kp_" + strconv.Itoa(kpId),
|
||||
Title: title,
|
||||
Type: mapKPTypeToUnifiedShort(f.Type),
|
||||
OriginalType: strings.ToUpper(strings.TrimSpace(f.Type)),
|
||||
ReleaseDate: yearToDate(f.Year),
|
||||
PosterURL: poster,
|
||||
Rating: rating,
|
||||
|
||||
Reference in New Issue
Block a user