mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-29 02:18:50 +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
|
```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"
|
||||||
|
|
||||||
# Детали фильма
|
# Детали по униф. ID
|
||||||
curl "https://api.neomovies.ru/api/v1/movies/550"
|
curl "https://api.neomovies.ru/api/v1/movie/tmdb_550"
|
||||||
|
curl "https://api.neomovies.ru/api/v1/tv/kp_61365"
|
||||||
# Добавить в избранное (с JWT токеном)
|
|
||||||
curl -X POST https://api.neomovies.ru/api/v1/favorites/550 \
|
|
||||||
-H "Authorization: Bearer YOUR_JWT_TOKEN"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Поиск торрентов
|
### Поиск торрентов
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
docsHandler := handlersPkg.NewDocsHandler()
|
docsHandler := handlersPkg.NewDocsHandler()
|
||||||
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
|
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
|
||||||
unifiedHandler := handlersPkg.NewUnifiedHandler(tmdbService, kpService)
|
unifiedHandler := handlersPkg.NewUnifiedHandler(tmdbService, kpService)
|
||||||
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
|
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
||||||
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
||||||
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
reactionsHandler := handlersPkg.NewReactionsHandler(reactionsService)
|
reactionsHandler := handlersPkg.NewReactionsHandler(reactionsService)
|
||||||
@@ -97,6 +97,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
api.HandleFunc("/categories/{id}/media", categoriesHandler.GetMediaByCategory).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/lumex/{id_type}/{id}", playersHandler.GetLumexPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/hdvb/{id_type}/{id}", playersHandler.GetHDVBPlayer).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()
|
docsHandler := appHandlers.NewDocsHandler()
|
||||||
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
|
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
|
||||||
unifiedHandler := appHandlers.NewUnifiedHandler(tmdbService, kpService)
|
unifiedHandler := appHandlers.NewUnifiedHandler(tmdbService, kpService)
|
||||||
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
|
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
||||||
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
||||||
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
reactionsHandler := appHandlers.NewReactionsHandler(reactionsService)
|
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()))
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -13,12 +13,17 @@ import (
|
|||||||
|
|
||||||
type CategoriesHandler struct {
|
type CategoriesHandler struct {
|
||||||
tmdbService *services.TMDBService
|
tmdbService *services.TMDBService
|
||||||
|
kpService *services.KinopoiskService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCategoriesHandler(tmdbService *services.TMDBService) *CategoriesHandler {
|
func NewCategoriesHandler(tmdbService *services.TMDBService) *CategoriesHandler {
|
||||||
return &CategoriesHandler{
|
// Для совместимости, kpService может быть добавлен позже через setter при инициализации в main.go/api/index.go
|
||||||
tmdbService: tmdbService,
|
return &CategoriesHandler{tmdbService: tmdbService}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *CategoriesHandler) WithKinopoisk(kp *services.KinopoiskService) *CategoriesHandler {
|
||||||
|
h.kpService = kp
|
||||||
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
type Category struct {
|
type Category struct {
|
||||||
@@ -35,7 +40,7 @@ func (h *CategoriesHandler) GetCategories(w http.ResponseWriter, r *http.Request
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Преобразуем жанры в категории
|
// Преобразуем жанры в категории (пока TMDB). Для KP — можно замаппить фиксированный список
|
||||||
var categories []Category
|
var categories []Category
|
||||||
for _, genre := range genresResponse.Genres {
|
for _, genre := range genresResponse.Genres {
|
||||||
slug := generateSlug(genre.Name)
|
slug := generateSlug(genre.Name)
|
||||||
@@ -77,16 +82,28 @@ func (h *CategoriesHandler) GetMediaByCategory(w http.ResponseWriter, r *http.Re
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
source := r.URL.Query().Get("source") // "kp" | "tmdb"
|
||||||
var data interface{}
|
var data interface{}
|
||||||
var err2 error
|
var err2 error
|
||||||
|
|
||||||
|
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" {
|
if mediaType == "movie" {
|
||||||
// Используем discover API для получения фильмов по жанру
|
|
||||||
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
||||||
} else {
|
} else {
|
||||||
// Используем discover API для получения сериалов по жанру
|
|
||||||
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err2 != nil {
|
if err2 != nil {
|
||||||
http.Error(w, err2.Error(), http.StatusInternalServerError)
|
http.Error(w, err2.Error(), http.StatusInternalServerError)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
@@ -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)
|
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to fetch from TMDB: %w", err)
|
return nil, fmt.Errorf("failed to fetch from TMDB: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"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)
|
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&%s", h.config.AllohaToken, idParam)
|
||||||
log.Printf("Calling Alloha API: %s", apiURL)
|
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 {
|
if err != nil {
|
||||||
log.Printf("Error calling Alloha API: %v", err)
|
log.Printf("Error calling Alloha API: %v", err)
|
||||||
http.Error(w, "Failed to fetch from Alloha API", http.StatusInternalServerError)
|
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)
|
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) {
|
func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
@@ -152,6 +268,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 +284,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)
|
||||||
@@ -600,7 +717,8 @@ func (h *PlayersHandler) GetHDVBPlayer(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
log.Printf("HDVB API URL: %s", apiURL)
|
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 {
|
if err != nil {
|
||||||
log.Printf("Error fetching HDVB data: %v", err)
|
log.Printf("Error fetching HDVB data: %v", err)
|
||||||
http.Error(w, "Failed to fetch player data", http.StatusInternalServerError)
|
http.Error(w, "Failed to fetch player data", http.StatusInternalServerError)
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ type UnifiedSearchItem struct {
|
|||||||
SourceID string `json:"sourceId"`
|
SourceID string `json:"sourceId"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
OriginalType string `json:"originalType,omitempty"`
|
||||||
ReleaseDate string `json:"releaseDate"`
|
ReleaseDate string `json:"releaseDate"`
|
||||||
PosterURL string `json:"posterUrl"`
|
PosterURL string `json:"posterUrl"`
|
||||||
Rating float64 `json:"rating"`
|
Rating float64 `json:"rating"`
|
||||||
|
|||||||
@@ -220,8 +220,8 @@ func MapKPToUnified(kpFilm *KPFilm) *models.UnifiedContent {
|
|||||||
Type: mapKPTypeToUnified(kpFilm),
|
Type: mapKPTypeToUnified(kpFilm),
|
||||||
Genres: genres,
|
Genres: genres,
|
||||||
Rating: kpFilm.RatingKinopoisk,
|
Rating: kpFilm.RatingKinopoisk,
|
||||||
PosterURL: poster,
|
PosterURL: BuildAPIImageProxyURL(poster, "w500"),
|
||||||
BackdropURL: kpFilm.CoverUrl,
|
BackdropURL: BuildAPIImageProxyURL(kpFilm.CoverUrl, "w1280"),
|
||||||
Director: "",
|
Director: "",
|
||||||
Cast: []models.UnifiedCastMember{},
|
Cast: []models.UnifiedCastMember{},
|
||||||
Duration: kpFilm.FilmLength,
|
Duration: kpFilm.FilmLength,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
)
|
)
|
||||||
@@ -17,10 +18,15 @@ type TMDBService struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewTMDBService(accessToken string) *TMDBService {
|
func NewTMDBService(accessToken string) *TMDBService {
|
||||||
|
transport := &http.Transport{
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
MaxIdleConnsPerHost: 10,
|
||||||
|
IdleConnTimeout: 60 * time.Second,
|
||||||
|
}
|
||||||
return &TMDBService{
|
return &TMDBService{
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
baseURL: "https://api.themoviedb.org/3",
|
baseURL: "https://api.themoviedb.org/3",
|
||||||
client: &http.Client{},
|
client: &http.Client{Timeout: 10 * time.Second, Transport: transport},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,6 +202,8 @@ func (s *TMDBService) FindTMDBIdByIMDB(imdbID string, media string, language str
|
|||||||
var resp struct {
|
var resp struct {
|
||||||
MovieResults []struct{ ID int `json:"id"` } `json:"movie_results"`
|
MovieResults []struct{ ID int `json:"id"` } `json:"movie_results"`
|
||||||
TVResults []struct{ ID int `json:"id"` } `json:"tv_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 {
|
if err := s.makeRequest(endpoint, &resp); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -217,6 +225,12 @@ func (s *TMDBService) FindTMDBIdByIMDB(imdbID string, media string, language str
|
|||||||
if len(resp.TVResults) > 0 {
|
if len(resp.TVResults) > 0 {
|
||||||
return resp.TVResults[0].ID, nil
|
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)
|
return 0, fmt.Errorf("tmdb id not found for imdb %s", imdbID)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -228,6 +236,7 @@ func MapKPSearchToUnifiedItems(kps *KPSearchResponse) []models.UnifiedSearchItem
|
|||||||
SourceID: "kp_" + strconv.Itoa(kpId),
|
SourceID: "kp_" + strconv.Itoa(kpId),
|
||||||
Title: title,
|
Title: title,
|
||||||
Type: mapKPTypeToUnifiedShort(f.Type),
|
Type: mapKPTypeToUnifiedShort(f.Type),
|
||||||
|
OriginalType: strings.ToUpper(strings.TrimSpace(f.Type)),
|
||||||
ReleaseDate: yearToDate(f.Year),
|
ReleaseDate: yearToDate(f.Year),
|
||||||
PosterURL: poster,
|
PosterURL: poster,
|
||||||
Rating: rating,
|
Rating: rating,
|
||||||
|
|||||||
Reference in New Issue
Block a user