mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-28 01:48:51 +05:00
Compare commits
2 Commits
c7aa844f49
...
feature/jw
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdeb1e1d74 | ||
|
|
ea3159fb8e |
56
.env.example
56
.env.example
@@ -1,34 +1,28 @@
|
|||||||
MONGO_URI=mongodb://localhost:27017/neomovies
|
# Required
|
||||||
MONGO_DB_NAME=neomovies
|
MONGO_URI=
|
||||||
|
MONGO_DB_NAME=database
|
||||||
TMDB_ACCESS_TOKEN=your_tmdb_access_token_here
|
TMDB_ACCESS_TOKEN=
|
||||||
|
JWT_SECRET=
|
||||||
KPAPI_KEY=920aaf6a-9f64-46f7-bda7-209fb1069440
|
|
||||||
KPAPI_BASE_URL=https://kinopoiskapiunofficial.tech/api
|
|
||||||
|
|
||||||
HDVB_TOKEN=b9ae5f8c4832244060916af4aa9d1939
|
|
||||||
|
|
||||||
VIBIX_HOST=https://vibix.org
|
|
||||||
VIBIX_TOKEN=18745|NzecUXT4gikPUtFkSEFlDLPmr9kWnQACTo1N0Ixq9240bcf1
|
|
||||||
|
|
||||||
LUMEX_URL=https://p.lumex.space
|
|
||||||
|
|
||||||
ALLOHA_TOKEN=your_alloha_token
|
|
||||||
|
|
||||||
REDAPI_BASE_URL=http://redapi.cfhttp.top
|
|
||||||
REDAPI_KEY=your_redapi_key
|
|
||||||
|
|
||||||
JWT_SECRET=your_jwt_secret_key_here
|
|
||||||
|
|
||||||
GMAIL_USER=your_gmail@gmail.com
|
|
||||||
GMAIL_APP_PASSWORD=your_gmail_app_password
|
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID=your_google_client_id
|
|
||||||
GOOGLE_CLIENT_SECRET=your_google_client_secret
|
|
||||||
GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/callback
|
|
||||||
|
|
||||||
BASE_URL=http://localhost:3000
|
|
||||||
FRONTEND_URL=http://localhost:3001
|
|
||||||
|
|
||||||
|
# Service
|
||||||
PORT=3000
|
PORT=3000
|
||||||
|
BASE_URL=http://localhost:3000
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
|
|
||||||
|
# Email (Gmail)
|
||||||
|
GMAIL_USER=
|
||||||
|
GMAIL_APP_PASSWORD=
|
||||||
|
|
||||||
|
# Players
|
||||||
|
LUMEX_URL=
|
||||||
|
ALLOHA_TOKEN=
|
||||||
|
|
||||||
|
# Torrents (RedAPI)
|
||||||
|
REDAPI_BASE_URL=http://redapi.cfhttp.top
|
||||||
|
REDAPI_KEY=
|
||||||
|
|
||||||
|
# Google OAuth
|
||||||
|
GOOGLE_CLIENT_ID=
|
||||||
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/callback
|
||||||
|
FRONTEND_URL=http://localhost:3001
|
||||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -3,11 +3,3 @@
|
|||||||
node_modules
|
node_modules
|
||||||
package-lock.json
|
package-lock.json
|
||||||
yarn.lock
|
yarn.lock
|
||||||
# Binaries
|
|
||||||
bin/
|
|
||||||
main
|
|
||||||
*.exe
|
|
||||||
*.dll
|
|
||||||
*.so
|
|
||||||
*.dylib
|
|
||||||
neomovies-api
|
|
||||||
|
|||||||
90
README.md
90
README.md
@@ -4,14 +4,13 @@ REST API для поиска и получения информации о фи
|
|||||||
|
|
||||||
## Особенности
|
## Особенности
|
||||||
|
|
||||||
- Интеграция с Kinopoisk API для русского контента
|
- Поиск фильмов
|
||||||
- Автоматическое переключение между TMDB и Kinopoisk
|
|
||||||
- Поиск фильмов и сериалов
|
|
||||||
- Информация о фильмах
|
- Информация о фильмах
|
||||||
- Популярные, топ-рейтинговые, предстоящие фильмы
|
- Популярные фильмы
|
||||||
- Поддержка русских плееров (Alloha, Lumex, Vibix, HDVB)
|
- Топ рейтинговые фильмы
|
||||||
|
- Предстоящие фильмы
|
||||||
- Swagger документация
|
- Swagger документация
|
||||||
- Полная поддержка русского языка
|
- Поддержка русского языка
|
||||||
|
|
||||||
## 🛠 Быстрый старт
|
## 🛠 Быстрый старт
|
||||||
|
|
||||||
@@ -51,39 +50,32 @@ API будет доступен на `http://localhost:3000`
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Обязательные
|
# Обязательные
|
||||||
MONGO_URI=mongodb://localhost:27017/neomovies
|
MONGO_URI=
|
||||||
MONGO_DB_NAME=neomovies
|
MONGO_DB_NAME=database
|
||||||
TMDB_ACCESS_TOKEN=your_tmdb_access_token
|
TMDB_ACCESS_TOKEN=
|
||||||
JWT_SECRET=your_jwt_secret_key
|
JWT_SECRET=
|
||||||
|
|
||||||
# Kinopoisk API
|
|
||||||
KPAPI_KEY=your_kp_api_key
|
|
||||||
KPAPI_BASE_URL=https://kinopoiskapiunofficial.tech/api
|
|
||||||
|
|
||||||
# Сервис
|
# Сервис
|
||||||
PORT=3000
|
PORT=3000
|
||||||
BASE_URL=http://localhost:3000
|
BASE_URL=http://localhost:3000
|
||||||
FRONTEND_URL=http://localhost:3001
|
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
|
|
||||||
# Email (Gmail)
|
# Email (Gmail)
|
||||||
GMAIL_USER=your_gmail@gmail.com
|
GMAIL_USER=
|
||||||
GMAIL_APP_PASSWORD=your_gmail_app_password
|
GMAIL_APP_PASSWORD=
|
||||||
|
|
||||||
# Русские плееры
|
# Плееры
|
||||||
LUMEX_URL=https://p.lumex.space
|
LUMEX_URL=
|
||||||
ALLOHA_TOKEN=your_alloha_token
|
ALLOHA_TOKEN=
|
||||||
VIBIX_HOST=https://vibix.org
|
VIBIX_TOKEN=
|
||||||
VIBIX_TOKEN=your_vibix_token
|
|
||||||
HDVB_TOKEN=your_hdvb_token
|
|
||||||
|
|
||||||
# Торренты (RedAPI)
|
# Торренты (RedAPI)
|
||||||
REDAPI_BASE_URL=http://redapi.cfhttp.top
|
REDAPI_BASE_URL=http://redapi.cfhttp.top
|
||||||
REDAPI_KEY=your_redapi_key
|
REDAPI_KEY=
|
||||||
|
|
||||||
# Google OAuth
|
# Google OAuth
|
||||||
GOOGLE_CLIENT_ID=your_google_client_id
|
GOOGLE_CLIENT_ID=
|
||||||
GOOGLE_CLIENT_SECRET=your_google_client_secret
|
GOOGLE_CLIENT_SECRET=
|
||||||
GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/callback
|
GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/callback
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -128,14 +120,10 @@ GET /api/v1/tv/{id} # Детали сериала
|
|||||||
GET /api/v1/tv/{id}/recommendations # Рекомендации
|
GET /api/v1/tv/{id}/recommendations # Рекомендации
|
||||||
GET /api/v1/tv/{id}/similar # Похожие
|
GET /api/v1/tv/{id}/similar # Похожие
|
||||||
|
|
||||||
# Плееры (новый формат с типом ID)
|
# Плееры
|
||||||
GET /api/v1/players/alloha/{id_type}/{id} # Alloha плеер (kp/301 или imdb/tt0133093)
|
GET /api/v1/players/alloha/{imdb_id} # Alloha плеер по IMDb ID
|
||||||
GET /api/v1/players/lumex/{id_type}/{id} # Lumex плеер (kp/301 или imdb/tt0133093)
|
GET /api/v1/players/lumex/{imdb_id} # Lumex плеер по IMDb ID
|
||||||
GET /api/v1/players/vibix/{id_type}/{id} # Vibix плеер (kp/301 или imdb/tt0133093)
|
GET /api/v1/players/vibix/{imdb_id} # Vibix плеер по IMDb ID
|
||||||
GET /api/v1/players/hdvb/{id_type}/{id} # HDVB плеер (kp/301 или imdb/tt0133093)
|
|
||||||
GET /api/v1/players/vidsrc/{media_type}/{imdb_id} # Vidsrc (только IMDB)
|
|
||||||
GET /api/v1/players/vidlink/movie/{imdb_id} # Vidlink фильмы (только IMDB)
|
|
||||||
GET /api/v1/players/vidlink/tv/{tmdb_id} # Vidlink сериалы (только TMDB)
|
|
||||||
|
|
||||||
# Торренты
|
# Торренты
|
||||||
GET /api/v1/torrents/search/{imdbId} # Поиск торрентов
|
GET /api/v1/torrents/search/{imdbId} # Поиск торрентов
|
||||||
@@ -255,42 +243,10 @@ curl "https://api.neomovies.ru/api/v1/torrents/search/tt0111161?type=movie&quali
|
|||||||
- **Gorilla Mux** - HTTP роутер
|
- **Gorilla Mux** - HTTP роутер
|
||||||
- **MongoDB** - база данных
|
- **MongoDB** - база данных
|
||||||
- **JWT** - аутентификация
|
- **JWT** - аутентификация
|
||||||
- **TMDB API** - данные о фильмах (международный контент)
|
- **TMDB API** - данные о фильмах
|
||||||
- **Kinopoisk API Unofficial** - данные о русском контенте
|
|
||||||
- **Gmail SMTP** - email уведомления
|
- **Gmail SMTP** - email уведомления
|
||||||
- **Vercel** - деплой и хостинг
|
- **Vercel** - деплой и хостинг
|
||||||
|
|
||||||
## 🌍 Kinopoisk API интеграция
|
|
||||||
|
|
||||||
API автоматически переключается между TMDB и Kinopoisk в зависимости от языка запроса:
|
|
||||||
|
|
||||||
- **Русский язык (`lang=ru`)** → Kinopoisk API
|
|
||||||
- Русские названия фильмов
|
|
||||||
- Рейтинги Кинопоиска
|
|
||||||
- Поддержка Kinopoisk ID
|
|
||||||
|
|
||||||
- **Английский язык (`lang=en`)** → TMDB API
|
|
||||||
- Международные названия
|
|
||||||
- Рейтинги IMDB/TMDB
|
|
||||||
- Поддержка IMDB/TMDB ID
|
|
||||||
|
|
||||||
### Формат ID в плеерах
|
|
||||||
|
|
||||||
Все русские плееры поддерживают два типа идентификаторов:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# По Kinopoisk ID (приоритет для русского контента)
|
|
||||||
GET /api/v1/players/alloha/kp/301
|
|
||||||
|
|
||||||
# По IMDB ID (fallback)
|
|
||||||
GET /api/v1/players/alloha/imdb/tt0133093
|
|
||||||
|
|
||||||
# Примеры для других плееров
|
|
||||||
GET /api/v1/players/lumex/kp/301
|
|
||||||
GET /api/v1/players/vibix/kp/301
|
|
||||||
GET /api/v1/players/hdvb/kp/301
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 Производительность
|
## 🚀 Производительность
|
||||||
|
|
||||||
По сравнению с Node.js версией:
|
По сравнению с Node.js версией:
|
||||||
|
|||||||
45
api/index.go
45
api/index.go
@@ -52,12 +52,11 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tmdbService := services.NewTMDBService(globalCfg.TMDBAccessToken)
|
tmdbService := services.NewTMDBService(globalCfg.TMDBAccessToken)
|
||||||
kpService := services.NewKinopoiskService(globalCfg.KPAPIKey, globalCfg.KPAPIBaseURL)
|
|
||||||
emailService := services.NewEmailService(globalCfg)
|
emailService := services.NewEmailService(globalCfg)
|
||||||
authService := services.NewAuthService(globalDB, globalCfg.JWTSecret, emailService, globalCfg.BaseURL, globalCfg.GoogleClientID, globalCfg.GoogleClientSecret, globalCfg.GoogleRedirectURL, globalCfg.FrontendURL)
|
authService := services.NewAuthService(globalDB, globalCfg.JWTSecret, emailService, globalCfg.BaseURL, globalCfg.GoogleClientID, globalCfg.GoogleClientSecret, globalCfg.GoogleRedirectURL, globalCfg.FrontendURL)
|
||||||
|
|
||||||
movieService := services.NewMovieService(globalDB, tmdbService, kpService)
|
movieService := services.NewMovieService(globalDB, tmdbService)
|
||||||
tvService := services.NewTVService(globalDB, tmdbService, kpService)
|
tvService := services.NewTVService(globalDB, tmdbService)
|
||||||
favoritesService := services.NewFavoritesService(globalDB, tmdbService)
|
favoritesService := services.NewFavoritesService(globalDB, tmdbService)
|
||||||
torrentService := services.NewTorrentServiceWithConfig(globalCfg.RedAPIBaseURL, globalCfg.RedAPIKey)
|
torrentService := services.NewTorrentServiceWithConfig(globalCfg.RedAPIBaseURL, globalCfg.RedAPIKey)
|
||||||
reactionsService := services.NewReactionsService(globalDB)
|
reactionsService := services.NewReactionsService(globalDB)
|
||||||
@@ -67,7 +66,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
tvHandler := handlersPkg.NewTVHandler(tvService)
|
tvHandler := handlersPkg.NewTVHandler(tvService)
|
||||||
favoritesHandler := handlersPkg.NewFavoritesHandler(favoritesService, globalCfg)
|
favoritesHandler := handlersPkg.NewFavoritesHandler(favoritesService, globalCfg)
|
||||||
docsHandler := handlersPkg.NewDocsHandler()
|
docsHandler := handlersPkg.NewDocsHandler()
|
||||||
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
|
searchHandler := handlersPkg.NewSearchHandler(tmdbService)
|
||||||
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
|
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
|
||||||
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
||||||
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
@@ -95,13 +94,9 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
api.HandleFunc("/categories/{id}/movies", categoriesHandler.GetMoviesByCategory).Methods("GET")
|
api.HandleFunc("/categories/{id}/movies", categoriesHandler.GetMoviesByCategory).Methods("GET")
|
||||||
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/{imdb_id}", playersHandler.GetAllohaPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/lumex/{id_type}/{id}", playersHandler.GetLumexPlayer).Methods("GET")
|
api.HandleFunc("/players/lumex/{imdb_id}", playersHandler.GetLumexPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
api.HandleFunc("/players/vibix/{imdb_id}", playersHandler.GetVibixPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/hdvb/{id_type}/{id}", playersHandler.GetHDVBPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidsrc/{media_type}/{imdb_id}", playersHandler.GetVidsrcPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidlink/movie/{imdb_id}", playersHandler.GetVidlinkMoviePlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidlink/tv/{tmdb_id}", playersHandler.GetVidlinkTVPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/rgshows/{tmdb_id}", playersHandler.GetRgShowsPlayer).Methods("GET")
|
api.HandleFunc("/players/rgshows/{tmdb_id}", playersHandler.GetRgShowsPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/rgshows/{tmdb_id}/{season}/{episode}", playersHandler.GetRgShowsTVPlayer).Methods("GET")
|
api.HandleFunc("/players/rgshows/{tmdb_id}/{season}/{episode}", playersHandler.GetRgShowsTVPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/iframevideo/{kinopoisk_id}/{imdb_id}", playersHandler.GetIframeVideoPlayer).Methods("GET")
|
api.HandleFunc("/players/iframevideo/{kinopoisk_id}/{imdb_id}", playersHandler.GetIframeVideoPlayer).Methods("GET")
|
||||||
@@ -155,30 +150,12 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
protected.HandleFunc("/reactions/{mediaType}/{mediaId}", reactionsHandler.RemoveReaction).Methods("DELETE")
|
protected.HandleFunc("/reactions/{mediaType}/{mediaId}", reactionsHandler.RemoveReaction).Methods("DELETE")
|
||||||
protected.HandleFunc("/reactions/my", reactionsHandler.GetMyReactions).Methods("GET")
|
protected.HandleFunc("/reactions/my", reactionsHandler.GetMyReactions).Methods("GET")
|
||||||
|
|
||||||
// CORS configuration - allow all origins
|
|
||||||
corsHandler := handlers.CORS(
|
corsHandler := handlers.CORS(
|
||||||
handlers.AllowedOrigins([]string{
|
handlers.AllowedOrigins([]string{"*"}),
|
||||||
"*", // Allow all origins
|
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}),
|
||||||
}),
|
handlers.AllowedHeaders([]string{"Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With", "X-CSRF-Token"}),
|
||||||
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"}),
|
handlers.AllowCredentials(),
|
||||||
handlers.AllowedHeaders([]string{
|
handlers.ExposedHeaders([]string{"Authorization", "Content-Type"}),
|
||||||
"Authorization",
|
|
||||||
"Content-Type",
|
|
||||||
"Accept",
|
|
||||||
"Origin",
|
|
||||||
"X-Requested-With",
|
|
||||||
"X-CSRF-Token",
|
|
||||||
"Access-Control-Allow-Origin",
|
|
||||||
"Access-Control-Allow-Headers",
|
|
||||||
"Access-Control-Allow-Methods",
|
|
||||||
"Access-Control-Allow-Credentials",
|
|
||||||
}),
|
|
||||||
handlers.ExposedHeaders([]string{
|
|
||||||
"Authorization",
|
|
||||||
"Content-Type",
|
|
||||||
"X-Total-Count",
|
|
||||||
}),
|
|
||||||
handlers.MaxAge(3600),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
corsHandler(router).ServeHTTP(w, r)
|
corsHandler(router).ServeHTTP(w, r)
|
||||||
|
|||||||
45
main.go
45
main.go
@@ -32,12 +32,11 @@ func main() {
|
|||||||
defer database.Disconnect()
|
defer database.Disconnect()
|
||||||
|
|
||||||
tmdbService := services.NewTMDBService(cfg.TMDBAccessToken)
|
tmdbService := services.NewTMDBService(cfg.TMDBAccessToken)
|
||||||
kpService := services.NewKinopoiskService(cfg.KPAPIKey, cfg.KPAPIBaseURL)
|
|
||||||
emailService := services.NewEmailService(cfg)
|
emailService := services.NewEmailService(cfg)
|
||||||
authService := services.NewAuthService(db, cfg.JWTSecret, emailService, cfg.BaseURL, cfg.GoogleClientID, cfg.GoogleClientSecret, cfg.GoogleRedirectURL, cfg.FrontendURL)
|
authService := services.NewAuthService(db, cfg.JWTSecret, emailService, cfg.BaseURL, cfg.GoogleClientID, cfg.GoogleClientSecret, cfg.GoogleRedirectURL, cfg.FrontendURL)
|
||||||
|
|
||||||
movieService := services.NewMovieService(db, tmdbService, kpService)
|
movieService := services.NewMovieService(db, tmdbService)
|
||||||
tvService := services.NewTVService(db, tmdbService, kpService)
|
tvService := services.NewTVService(db, tmdbService)
|
||||||
favoritesService := services.NewFavoritesService(db, tmdbService)
|
favoritesService := services.NewFavoritesService(db, tmdbService)
|
||||||
torrentService := services.NewTorrentServiceWithConfig(cfg.RedAPIBaseURL, cfg.RedAPIKey)
|
torrentService := services.NewTorrentServiceWithConfig(cfg.RedAPIBaseURL, cfg.RedAPIKey)
|
||||||
reactionsService := services.NewReactionsService(db)
|
reactionsService := services.NewReactionsService(db)
|
||||||
@@ -47,7 +46,7 @@ func main() {
|
|||||||
tvHandler := appHandlers.NewTVHandler(tvService)
|
tvHandler := appHandlers.NewTVHandler(tvService)
|
||||||
favoritesHandler := appHandlers.NewFavoritesHandler(favoritesService, cfg)
|
favoritesHandler := appHandlers.NewFavoritesHandler(favoritesService, cfg)
|
||||||
docsHandler := appHandlers.NewDocsHandler()
|
docsHandler := appHandlers.NewDocsHandler()
|
||||||
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
|
searchHandler := appHandlers.NewSearchHandler(tmdbService)
|
||||||
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
|
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
|
||||||
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
||||||
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
@@ -76,13 +75,9 @@ func main() {
|
|||||||
api.HandleFunc("/categories/{id}/movies", categoriesHandler.GetMoviesByCategory).Methods("GET")
|
api.HandleFunc("/categories/{id}/movies", categoriesHandler.GetMoviesByCategory).Methods("GET")
|
||||||
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/{imdb_id}", playersHandler.GetAllohaPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/lumex/{id_type}/{id}", playersHandler.GetLumexPlayer).Methods("GET")
|
api.HandleFunc("/players/lumex/{imdb_id}", playersHandler.GetLumexPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
api.HandleFunc("/players/vibix/{imdb_id}", playersHandler.GetVibixPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vidsrc/{media_type}/{imdb_id}", playersHandler.GetVidsrcPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidlink/movie/{imdb_id}", playersHandler.GetVidlinkMoviePlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidlink/tv/{tmdb_id}", playersHandler.GetVidlinkTVPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/hdvb/{id_type}/{id}", playersHandler.GetHDVBPlayer).Methods("GET")
|
|
||||||
|
|
||||||
api.HandleFunc("/torrents/search/{imdbId}", torrentsHandler.SearchTorrents).Methods("GET")
|
api.HandleFunc("/torrents/search/{imdbId}", torrentsHandler.SearchTorrents).Methods("GET")
|
||||||
api.HandleFunc("/torrents/movies", torrentsHandler.SearchMovies).Methods("GET")
|
api.HandleFunc("/torrents/movies", torrentsHandler.SearchMovies).Methods("GET")
|
||||||
@@ -134,30 +129,12 @@ func main() {
|
|||||||
protected.HandleFunc("/reactions/{mediaType}/{mediaId}", reactionsHandler.RemoveReaction).Methods("DELETE")
|
protected.HandleFunc("/reactions/{mediaType}/{mediaId}", reactionsHandler.RemoveReaction).Methods("DELETE")
|
||||||
protected.HandleFunc("/reactions/my", reactionsHandler.GetMyReactions).Methods("GET")
|
protected.HandleFunc("/reactions/my", reactionsHandler.GetMyReactions).Methods("GET")
|
||||||
|
|
||||||
// CORS configuration - allow all origins
|
|
||||||
corsHandler := handlers.CORS(
|
corsHandler := handlers.CORS(
|
||||||
handlers.AllowedOrigins([]string{
|
handlers.AllowedOrigins([]string{"*"}),
|
||||||
"*", // Allow all origins
|
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}),
|
||||||
}),
|
handlers.AllowedHeaders([]string{"Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With", "X-CSRF-Token"}),
|
||||||
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"}),
|
handlers.AllowCredentials(),
|
||||||
handlers.AllowedHeaders([]string{
|
handlers.ExposedHeaders([]string{"Authorization", "Content-Type"}),
|
||||||
"Authorization",
|
|
||||||
"Content-Type",
|
|
||||||
"Accept",
|
|
||||||
"Origin",
|
|
||||||
"X-Requested-With",
|
|
||||||
"X-CSRF-Token",
|
|
||||||
"Access-Control-Allow-Origin",
|
|
||||||
"Access-Control-Allow-Headers",
|
|
||||||
"Access-Control-Allow-Methods",
|
|
||||||
"Access-Control-Allow-Credentials",
|
|
||||||
}),
|
|
||||||
handlers.ExposedHeaders([]string{
|
|
||||||
"Authorization",
|
|
||||||
"Content-Type",
|
|
||||||
"X-Total-Count",
|
|
||||||
}),
|
|
||||||
handlers.MaxAge(3600),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var finalHandler http.Handler
|
var finalHandler http.Handler
|
||||||
|
|||||||
@@ -25,9 +25,6 @@ type Config struct {
|
|||||||
FrontendURL string
|
FrontendURL string
|
||||||
VibixHost string
|
VibixHost string
|
||||||
VibixToken string
|
VibixToken string
|
||||||
KPAPIKey string
|
|
||||||
HDVBToken string
|
|
||||||
KPAPIBaseURL string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func New() *Config {
|
func New() *Config {
|
||||||
@@ -53,9 +50,6 @@ func New() *Config {
|
|||||||
FrontendURL: getEnv(EnvFrontendURL, ""),
|
FrontendURL: getEnv(EnvFrontendURL, ""),
|
||||||
VibixHost: getEnv(EnvVibixHost, DefaultVibixHost),
|
VibixHost: getEnv(EnvVibixHost, DefaultVibixHost),
|
||||||
VibixToken: getEnv(EnvVibixToken, ""),
|
VibixToken: getEnv(EnvVibixToken, ""),
|
||||||
KPAPIKey: getEnv(EnvKPAPIKey, ""),
|
|
||||||
HDVBToken: getEnv(EnvHDVBToken, ""),
|
|
||||||
KPAPIBaseURL: getEnv("KPAPI_BASE_URL", DefaultKPAPIBase),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,6 @@ const (
|
|||||||
EnvFrontendURL = "FRONTEND_URL"
|
EnvFrontendURL = "FRONTEND_URL"
|
||||||
EnvVibixHost = "VIBIX_HOST"
|
EnvVibixHost = "VIBIX_HOST"
|
||||||
EnvVibixToken = "VIBIX_TOKEN"
|
EnvVibixToken = "VIBIX_TOKEN"
|
||||||
EnvKPAPIKey = "KPAPI_KEY"
|
|
||||||
EnvHDVBToken = "HDVB_TOKEN"
|
|
||||||
|
|
||||||
// Default values
|
// Default values
|
||||||
DefaultJWTSecret = "your-secret-key"
|
DefaultJWTSecret = "your-secret-key"
|
||||||
@@ -31,7 +29,6 @@ const (
|
|||||||
DefaultRedAPIBase = "http://redapi.cfhttp.top"
|
DefaultRedAPIBase = "http://redapi.cfhttp.top"
|
||||||
DefaultMongoDBName = "database"
|
DefaultMongoDBName = "database"
|
||||||
DefaultVibixHost = "https://vibix.org"
|
DefaultVibixHost = "https://vibix.org"
|
||||||
DefaultKPAPIBase = "https://kinopoiskapiunofficial.tech/api"
|
|
||||||
|
|
||||||
// Static constants
|
// Static constants
|
||||||
TMDBImageBaseURL = "https://image.tmdb.org/t/p"
|
TMDBImageBaseURL = "https://image.tmdb.org/t/p"
|
||||||
|
|||||||
@@ -37,16 +37,11 @@ func (h *DocsHandler) GetOpenAPISpec(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *DocsHandler) ServeDocs(w http.ResponseWriter, r *http.Request) {
|
func (h *DocsHandler) ServeDocs(w http.ResponseWriter, r *http.Request) {
|
||||||
spec := getOpenAPISpecWithURL("/")
|
baseURL := determineBaseURL(r)
|
||||||
specJSON, err := json.Marshal(spec)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error marshaling OpenAPI spec: %v", err)
|
|
||||||
http.Error(w, fmt.Sprintf("Error marshaling spec: %v", err), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Use absolute SpecURL so the library does not try to read a local file path
|
||||||
htmlContent, err := scalar.ApiReferenceHTML(&scalar.Options{
|
htmlContent, err := scalar.ApiReferenceHTML(&scalar.Options{
|
||||||
SpecContent: string(specJSON),
|
SpecURL: fmt.Sprintf("%s/openapi.json", baseURL),
|
||||||
CustomOptions: scalar.CustomOptions{
|
CustomOptions: scalar.CustomOptions{
|
||||||
PageTitle: "Neo Movies API Documentation",
|
PageTitle: "Neo Movies API Documentation",
|
||||||
},
|
},
|
||||||
@@ -61,9 +56,6 @@ func (h *DocsHandler) ServeDocs(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
||||||
w.Header().Set("Pragma", "no-cache")
|
|
||||||
w.Header().Set("Expires", "0")
|
|
||||||
fmt.Fprintln(w, htmlContent)
|
fmt.Fprintln(w, htmlContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,7 +330,7 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
"/api/v1/players/lumex/{imdb_id}": map[string]interface{}{
|
"/api/v1/players/lumex/{imdb_id}": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Плеер Lumex",
|
"summary": "Плеер Lumex",
|
||||||
"description": "Получение плеера Lumex по IMDb ID. Не поддерживает выбор сезона/серии - плеер работает напрямую с IMDb ID",
|
"description": "Получение плеера Lumex по IMDb ID",
|
||||||
"tags": []string{"Players"},
|
"tags": []string{"Players"},
|
||||||
"parameters": []map[string]interface{}{
|
"parameters": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
@@ -346,15 +338,12 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
"in": "path",
|
"in": "path",
|
||||||
"required": true,
|
"required": true,
|
||||||
"schema": map[string]string{"type": "string"},
|
"schema": map[string]string{"type": "string"},
|
||||||
"description": "IMDb ID фильма или сериала (например, tt0133093)",
|
"description": "IMDb ID фильма",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"responses": map[string]interface{}{
|
"responses": map[string]interface{}{
|
||||||
"200": map[string]interface{}{
|
"200": map[string]interface{}{
|
||||||
"description": "HTML со встроенным Lumex плеером",
|
"description": "Данные плеера",
|
||||||
"content": map[string]interface{}{
|
|
||||||
"text/html": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -362,7 +351,7 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
"/api/v1/players/vibix/{imdb_id}": map[string]interface{}{
|
"/api/v1/players/vibix/{imdb_id}": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Vibix плеер по IMDb ID",
|
"summary": "Vibix плеер по IMDb ID",
|
||||||
"description": "Возвращает HTML-страницу с iframe Vibix для указанного IMDb ID. Не поддерживает выбор сезона/серии - плеер работает напрямую с IMDb ID",
|
"description": "Возвращает HTML-страницу с iframe Vibix для указанного IMDb ID",
|
||||||
"tags": []string{"Players"},
|
"tags": []string{"Players"},
|
||||||
"parameters": []map[string]interface{}{
|
"parameters": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
@@ -385,228 +374,76 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"/api/v1/players/vidsrc/{media_type}/{imdb_id}": map[string]interface{}{
|
"/api/v1/webtorrent/player": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Vidsrc плеер (английский)",
|
"summary": "WebTorrent плеер",
|
||||||
"description": "Возвращает HTML-страницу с iframe Vidsrc.to. Использует IMDb ID для фильмов и сериалов. Пример URL для фильма: https://vidsrc.to/embed/movie/tt1234567, для сериала: https://vidsrc.to/embed/tv/tt6385540/1/1",
|
"description": "Открытие WebTorrent плеера с магнет ссылкой. Плеер работает полностью на стороне клиента.",
|
||||||
"tags": []string{"Players"},
|
"tags": []string{"WebTorrent"},
|
||||||
"parameters": []map[string]interface{}{
|
"parameters": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
"name": "media_type",
|
"name": "magnet",
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]interface{}{"type": "string", "enum": []string{"movie", "tv"}},
|
|
||||||
"description": "Тип контента: movie (фильм) или tv (сериал)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "imdb_id",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "string"},
|
|
||||||
"description": "IMDb ID, например tt6385540 (с префиксом tt)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "season",
|
|
||||||
"in": "query",
|
"in": "query",
|
||||||
"required": false,
|
"required": false,
|
||||||
"schema": map[string]string{"type": "integer"},
|
"schema": map[string]string{"type": "string"},
|
||||||
"description": "Номер сезона (обязательно для TV)",
|
"description": "Магнет ссылка торрента",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "episode",
|
"name": "X-Magnet-Link",
|
||||||
"in": "query",
|
"in": "header",
|
||||||
"required": false,
|
"required": false,
|
||||||
"schema": map[string]string{"type": "integer"},
|
"schema": map[string]string{"type": "string"},
|
||||||
"description": "Номер серии (обязательно для TV)",
|
"description": "Магнет ссылка через заголовок (альтернативный способ)",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"responses": map[string]interface{}{
|
"responses": map[string]interface{}{
|
||||||
"200": map[string]interface{}{
|
"200": map[string]interface{}{
|
||||||
"description": "HTML со встроенным Vidsrc плеером",
|
"description": "HTML страница с WebTorrent плеером",
|
||||||
"content": map[string]interface{}{
|
"content": map[string]interface{}{
|
||||||
"text/html": map[string]interface{}{},
|
"text/html": map[string]interface{}{
|
||||||
},
|
"schema": map[string]string{"type": "string"},
|
||||||
},
|
|
||||||
"400": map[string]interface{}{"description": "Отсутствуют обязательные параметры"},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"/api/v1/players/vidlink/movie/{imdb_id}": map[string]interface{}{
|
"400": map[string]interface{}{
|
||||||
|
"description": "Отсутствует магнет ссылка",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"/api/v1/webtorrent/metadata": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Vidlink плеер для фильмов (английский)",
|
"summary": "Метаданные медиа",
|
||||||
"description": "Возвращает HTML-страницу с iframe Vidlink.pro для фильмов. Использует IMDb ID. Пример URL: https://vidlink.pro/movie/tt1234567",
|
"description": "Получение метаданных фильма или сериала по названию для WebTorrent плеера",
|
||||||
"tags": []string{"Players"},
|
"tags": []string{"WebTorrent"},
|
||||||
"parameters": []map[string]interface{}{
|
"parameters": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
"name": "imdb_id",
|
"name": "query",
|
||||||
"in": "path",
|
"in": "query",
|
||||||
"required": true,
|
"required": true,
|
||||||
"schema": map[string]string{"type": "string"},
|
"schema": map[string]string{"type": "string"},
|
||||||
"description": "IMDb ID фильма, например tt1234567 (с префиксом tt)",
|
"description": "Название для поиска (извлеченное из торрента)",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"responses": map[string]interface{}{
|
"responses": map[string]interface{}{
|
||||||
"200": map[string]interface{}{
|
"200": map[string]interface{}{
|
||||||
"description": "HTML со встроенным Vidlink плеером",
|
"description": "Метаданные найдены",
|
||||||
"content": map[string]interface{}{
|
"content": map[string]interface{}{
|
||||||
"text/html": map[string]interface{}{},
|
"application/json": map[string]interface{}{
|
||||||
},
|
"schema": map[string]interface{}{
|
||||||
},
|
"$ref": "#/components/schemas/WebTorrentMetadata",
|
||||||
"400": map[string]interface{}{"description": "IMDb ID не указан"},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"/api/v1/players/vidlink/tv/{tmdb_id}": map[string]interface{}{
|
|
||||||
"get": map[string]interface{}{
|
|
||||||
"summary": "Vidlink плеер для сериалов (английский)",
|
|
||||||
"description": "Возвращает HTML-страницу с iframe Vidlink.pro для сериалов. Использует TMDB ID (без префикса tt). Пример URL: https://vidlink.pro/tv/94997/1/1",
|
|
||||||
"tags": []string{"Players"},
|
|
||||||
"parameters": []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "tmdb_id",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "TMDB ID сериала, например 94997 (числовой идентификатор без префикса)",
|
|
||||||
},
|
},
|
||||||
{
|
"400": map[string]interface{}{
|
||||||
"name": "season",
|
"description": "Отсутствует параметр query",
|
||||||
"in": "query",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер сезона (обязательно)",
|
|
||||||
},
|
},
|
||||||
{
|
"404": map[string]interface{}{
|
||||||
"name": "episode",
|
"description": "Метаданные не найдены",
|
||||||
"in": "query",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер серии (обязательно)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"responses": map[string]interface{}{
|
|
||||||
"200": map[string]interface{}{
|
|
||||||
"description": "HTML со встроенным Vidlink плеером",
|
|
||||||
"content": map[string]interface{}{
|
|
||||||
"text/html": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"400": map[string]interface{}{"description": "Отсутствуют обязательные параметры (tmdb_id, season, episode)"},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"/api/v1/players/vidsrc-parse/{media_type}/{imdb_id}": map[string]interface{}{
|
|
||||||
"get": map[string]interface{}{
|
|
||||||
"summary": "Vidsrc плеер с парсингом (кастомный плеер)",
|
|
||||||
"description": "Возвращает HTML-страницу с кастомным Video.js плеером. Автоматически извлекает m3u8 ссылку из Vidsrc.to через клиентский парсинг в iframe. Использует IMDb ID для фильмов и сериалов.",
|
|
||||||
"tags": []string{"Players"},
|
|
||||||
"parameters": []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "media_type",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]interface{}{"type": "string", "enum": []string{"movie", "tv"}},
|
|
||||||
"description": "Тип контента: movie (фильм) или tv (сериал)",
|
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "imdb_id",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "string"},
|
|
||||||
"description": "IMDb ID, например tt6385540 (с префиксом tt)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "season",
|
|
||||||
"in": "query",
|
|
||||||
"required": false,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер сезона (обязательно для TV)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "episode",
|
|
||||||
"in": "query",
|
|
||||||
"required": false,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер серии (обязательно для TV)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"responses": map[string]interface{}{
|
|
||||||
"200": map[string]interface{}{
|
|
||||||
"description": "HTML с кастомным Video.js плеером и системой парсинга",
|
|
||||||
"content": map[string]interface{}{
|
|
||||||
"text/html": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"400": map[string]interface{}{"description": "Отсутствуют обязательные параметры"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"/api/v1/players/vidlink-parse/movie/{imdb_id}": map[string]interface{}{
|
|
||||||
"get": map[string]interface{}{
|
|
||||||
"summary": "Vidlink плеер с парсингом для фильмов (кастомный)",
|
|
||||||
"description": "Возвращает HTML-страницу с кастомным Video.js плеером. Автоматически извлекает m3u8/mp4 ссылку из Vidlink.pro через клиентский парсинг. Использует IMDb ID для фильмов.",
|
|
||||||
"tags": []string{"Players"},
|
|
||||||
"parameters": []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "imdb_id",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "string"},
|
|
||||||
"description": "IMDb ID фильма, например tt1234567 (с префиксом tt)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"responses": map[string]interface{}{
|
|
||||||
"200": map[string]interface{}{
|
|
||||||
"description": "HTML с кастомным Video.js плеером и системой парсинга",
|
|
||||||
"content": map[string]interface{}{
|
|
||||||
"text/html": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"400": map[string]interface{}{"description": "IMDb ID не указан"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"/api/v1/players/vidlink-parse/tv/{tmdb_id}": map[string]interface{}{
|
|
||||||
"get": map[string]interface{}{
|
|
||||||
"summary": "Vidlink плеер с парсингом для сериалов (кастомный)",
|
|
||||||
"description": "Возвращает HTML-страницу с кастомным Video.js плеером. Автоматически извлекает m3u8/mp4 ссылку из Vidlink.pro через клиентский парсинг. Использует TMDB ID для сериалов.",
|
|
||||||
"tags": []string{"Players"},
|
|
||||||
"parameters": []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "tmdb_id",
|
|
||||||
"in": "path",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "TMDB ID сериала, например 94997 (числовой идентификатор без префикса)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "season",
|
|
||||||
"in": "query",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер сезона (обязательно)",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "episode",
|
|
||||||
"in": "query",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]string{"type": "integer"},
|
|
||||||
"description": "Номер серии (обязательно)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"responses": map[string]interface{}{
|
|
||||||
"200": map[string]interface{}{
|
|
||||||
"description": "HTML с кастомным Video.js плеером и системой парсинга",
|
|
||||||
"content": map[string]interface{}{
|
|
||||||
"text/html": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"400": map[string]interface{}{"description": "Отсутствуют обязательные параметры (tmdb_id, season, episode)"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
"/api/v1/torrents/search/{imdbId}": map[string]interface{}{
|
"/api/v1/torrents/search/{imdbId}": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Поиск торрентов",
|
"summary": "Поиск торрентов",
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetLanguage extracts the lang parameter from request and returns it with default "ru"
|
|
||||||
// Supports both "lang" and "language" query parameters
|
|
||||||
// Valid values: "ru", "en"
|
|
||||||
// Default: "ru"
|
|
||||||
func GetLanguage(r *http.Request) string {
|
|
||||||
// Check "lang" parameter first (our new standard)
|
|
||||||
lang := r.URL.Query().Get("lang")
|
|
||||||
|
|
||||||
// Fall back to "language" for backward compatibility
|
|
||||||
if lang == "" {
|
|
||||||
lang = r.URL.Query().Get("language")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default to "ru" if not specified
|
|
||||||
if lang == "" {
|
|
||||||
return "ru-RU"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert short codes to TMDB format
|
|
||||||
switch lang {
|
|
||||||
case "en":
|
|
||||||
return "en-US"
|
|
||||||
case "ru":
|
|
||||||
return "ru-RU"
|
|
||||||
default:
|
|
||||||
// Return as-is if already in correct format
|
|
||||||
return lang
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
@@ -30,7 +29,7 @@ func (h *MovieHandler) Search(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
region := r.URL.Query().Get("region")
|
region := r.URL.Query().Get("region")
|
||||||
year := getIntQuery(r, "year", 0)
|
year := getIntQuery(r, "year", 0)
|
||||||
|
|
||||||
@@ -49,41 +48,15 @@ func (h *MovieHandler) Search(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *MovieHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
func (h *MovieHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
rawID := vars["id"]
|
id, err := strconv.Atoi(vars["id"])
|
||||||
|
|
||||||
// Support formats: "123" (old), "kp_123", "tmdb_123"
|
|
||||||
source := ""
|
|
||||||
var id int
|
|
||||||
if strings.Contains(rawID, "_") {
|
|
||||||
parts := strings.SplitN(rawID, "_", 2)
|
|
||||||
if len(parts) != 2 {
|
|
||||||
http.Error(w, "Invalid ID format", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
source = parts[0]
|
|
||||||
parsed, err := strconv.Atoi(parts[1])
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid numeric ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id = parsed
|
|
||||||
} else {
|
|
||||||
// Backward compatibility
|
|
||||||
parsed, err := strconv.Atoi(rawID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
|
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id = parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
idType := r.URL.Query().Get("id_type")
|
|
||||||
if source == "kp" || source == "tmdb" {
|
|
||||||
idType = source
|
|
||||||
}
|
|
||||||
|
|
||||||
movie, err := h.movieService.GetByID(id, language, idType)
|
movie, err := h.movieService.GetByID(id, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -98,7 +71,7 @@ func (h *MovieHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *MovieHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
func (h *MovieHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
region := r.URL.Query().Get("region")
|
region := r.URL.Query().Get("region")
|
||||||
|
|
||||||
movies, err := h.movieService.GetPopular(page, language, region)
|
movies, err := h.movieService.GetPopular(page, language, region)
|
||||||
@@ -116,7 +89,7 @@ func (h *MovieHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *MovieHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
func (h *MovieHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
region := r.URL.Query().Get("region")
|
region := r.URL.Query().Get("region")
|
||||||
|
|
||||||
movies, err := h.movieService.GetTopRated(page, language, region)
|
movies, err := h.movieService.GetTopRated(page, language, region)
|
||||||
@@ -134,7 +107,7 @@ func (h *MovieHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *MovieHandler) Upcoming(w http.ResponseWriter, r *http.Request) {
|
func (h *MovieHandler) Upcoming(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
region := r.URL.Query().Get("region")
|
region := r.URL.Query().Get("region")
|
||||||
|
|
||||||
movies, err := h.movieService.GetUpcoming(page, language, region)
|
movies, err := h.movieService.GetUpcoming(page, language, region)
|
||||||
@@ -152,7 +125,7 @@ func (h *MovieHandler) Upcoming(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *MovieHandler) NowPlaying(w http.ResponseWriter, r *http.Request) {
|
func (h *MovieHandler) NowPlaying(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
region := r.URL.Query().Get("region")
|
region := r.URL.Query().Get("region")
|
||||||
|
|
||||||
movies, err := h.movieService.GetNowPlaying(page, language, region)
|
movies, err := h.movieService.GetNowPlaying(page, language, region)
|
||||||
@@ -177,7 +150,7 @@ func (h *MovieHandler) GetRecommendations(w http.ResponseWriter, r *http.Request
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
movies, err := h.movieService.GetRecommendations(id, page, language)
|
movies, err := h.movieService.GetRecommendations(id, page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -201,7 +174,7 @@ func (h *MovieHandler) GetSimilar(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
movies, err := h.movieService.GetSimilar(id, page, language)
|
movies, err := h.movieService.GetSimilar(id, page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -30,22 +30,16 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
log.Printf("GetAllohaPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetAllohaPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
idType := vars["id_type"]
|
log.Printf("Route vars: %+v", vars)
|
||||||
id := vars["id"]
|
|
||||||
|
|
||||||
if idType == "" || id == "" {
|
imdbID := vars["imdb_id"]
|
||||||
log.Printf("Error: id_type or id is empty")
|
if imdbID == "" {
|
||||||
http.Error(w, "id_type and id are required", http.StatusBadRequest)
|
log.Printf("Error: imdb_id is empty")
|
||||||
|
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if idType != "kp" && idType != "imdb" {
|
log.Printf("Processing imdb_id: %s", imdbID)
|
||||||
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.AllohaToken == "" {
|
if h.config.AllohaToken == "" {
|
||||||
log.Printf("Error: ALLOHA_TOKEN is missing")
|
log.Printf("Error: ALLOHA_TOKEN is missing")
|
||||||
@@ -53,7 +47,7 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
idParam := fmt.Sprintf("%s=%s", idType, url.QueryEscape(id))
|
idParam := fmt.Sprintf("imdb=%s", url.QueryEscape(imdbID))
|
||||||
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)
|
||||||
|
|
||||||
@@ -100,30 +94,9 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
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
|
iframeCode := allohaResponse.Data.Iframe
|
||||||
|
|
||||||
// Если это не HTML код, а просто URL
|
|
||||||
var playerURL string
|
|
||||||
if !strings.Contains(iframeCode, "<") {
|
if !strings.Contains(iframeCode, "<") {
|
||||||
playerURL = iframeCode
|
iframeCode = fmt.Sprintf(`<iframe src="%s" allowfullscreen style="border:none;width:100%%;height:100%%"></iframe>`, 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(`<iframe src="%s" allowfullscreen style="border:none;width:100%%;height:100%%"></iframe>`, playerURL)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Alloha Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframeCode)
|
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Alloha Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframeCode)
|
||||||
@@ -135,29 +108,23 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
w.Write([]byte(htmlDoc))
|
w.Write([]byte(htmlDoc))
|
||||||
|
|
||||||
log.Printf("Successfully served Alloha player for %s: %s", idType, id)
|
log.Printf("Successfully served Alloha player for imdb_id: %s", imdbID)
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
idType := vars["id_type"]
|
log.Printf("Route vars: %+v", vars)
|
||||||
id := vars["id"]
|
|
||||||
|
|
||||||
if idType == "" || id == "" {
|
imdbID := vars["imdb_id"]
|
||||||
log.Printf("Error: id_type or id is empty")
|
if imdbID == "" {
|
||||||
http.Error(w, "id_type and id are required", http.StatusBadRequest)
|
log.Printf("Error: imdb_id is empty")
|
||||||
|
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if idType != "kp" && idType != "imdb" {
|
log.Printf("Processing imdb_id: %s", imdbID)
|
||||||
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 == "" {
|
if h.config.LumexURL == "" {
|
||||||
log.Printf("Error: LUMEX_URL is missing")
|
log.Printf("Error: LUMEX_URL is missing")
|
||||||
@@ -165,45 +132,32 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var paramName string
|
url := fmt.Sprintf("%s?imdb_id=%s", h.config.LumexURL, url.QueryEscape(imdbID))
|
||||||
if idType == "kp" {
|
log.Printf("Generated Lumex URL: %s", url)
|
||||||
paramName = "kinopoisk_id"
|
|
||||||
} else {
|
|
||||||
paramName = "imdb_id"
|
|
||||||
}
|
|
||||||
|
|
||||||
playerURL := fmt.Sprintf("%s?%s=%s", h.config.LumexURL, paramName, id)
|
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, url)
|
||||||
log.Printf("Lumex URL: %s", playerURL)
|
|
||||||
|
|
||||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, playerURL)
|
|
||||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Lumex Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Lumex Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
w.Write([]byte(htmlDoc))
|
w.Write([]byte(htmlDoc))
|
||||||
|
|
||||||
log.Printf("Successfully served Lumex player for %s: %s", idType, id)
|
log.Printf("Successfully served Lumex player for imdb_id: %s", imdbID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request) {
|
func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetVibixPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetVibixPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
idType := vars["id_type"]
|
log.Printf("Route vars: %+v", vars)
|
||||||
id := vars["id"]
|
|
||||||
|
|
||||||
if idType == "" || id == "" {
|
imdbID := vars["imdb_id"]
|
||||||
log.Printf("Error: id_type or id is empty")
|
if imdbID == "" {
|
||||||
http.Error(w, "id_type and id are required", http.StatusBadRequest)
|
log.Printf("Error: imdb_id is empty")
|
||||||
|
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if idType != "kp" && idType != "imdb" {
|
log.Printf("Processing imdb_id: %s", imdbID)
|
||||||
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.VibixToken == "" {
|
if h.config.VibixToken == "" {
|
||||||
log.Printf("Error: VIBIX_TOKEN is missing")
|
log.Printf("Error: VIBIX_TOKEN is missing")
|
||||||
@@ -216,14 +170,7 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
vibixHost = "https://vibix.org"
|
vibixHost = "https://vibix.org"
|
||||||
}
|
}
|
||||||
|
|
||||||
var endpoint string
|
apiURL := fmt.Sprintf("%s/api/v1/publisher/videos/imdb/%s", vibixHost, imdbID)
|
||||||
if idType == "kp" {
|
|
||||||
endpoint = "kinopoisk"
|
|
||||||
} else {
|
|
||||||
endpoint = "imdb"
|
|
||||||
}
|
|
||||||
|
|
||||||
apiURL := fmt.Sprintf("%s/api/v1/publisher/videos/%s/%s", vibixHost, endpoint, id)
|
|
||||||
log.Printf("Calling Vibix API: %s", apiURL)
|
log.Printf("Calling Vibix API: %s", apiURL)
|
||||||
|
|
||||||
req, err := http.NewRequest("GET", apiURL, nil)
|
req, err := http.NewRequest("GET", apiURL, nil)
|
||||||
@@ -234,7 +181,7 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
req.Header.Set("Authorization", h.config.VibixToken)
|
req.Header.Set("Authorization", "Bearer "+h.config.VibixToken)
|
||||||
req.Header.Set("X-CSRF-TOKEN", "")
|
req.Header.Set("X-CSRF-TOKEN", "")
|
||||||
|
|
||||||
client := &http.Client{Timeout: 8 * time.Second}
|
client := &http.Client{Timeout: 8 * time.Second}
|
||||||
@@ -280,17 +227,15 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vibix использует только iframe_url без season/episode
|
log.Printf("Generated Vibix iframe URL: %s", vibixResponse.IframeURL)
|
||||||
playerURL := vibixResponse.IframeURL
|
|
||||||
log.Printf("🔗 Vibix iframe 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>`, vibixResponse.IframeURL)
|
||||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Vibix Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Vibix Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
w.Write([]byte(htmlDoc))
|
w.Write([]byte(htmlDoc))
|
||||||
|
|
||||||
log.Printf("Successfully served Vibix player for %s: %s", idType, id)
|
log.Printf("Successfully served Vibix player for imdb_id: %s", imdbID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRgShowsPlayer handles RgShows streaming requests
|
// GetRgShowsPlayer handles RgShows streaming requests
|
||||||
@@ -490,228 +435,3 @@ func (h *PlayersHandler) GetStreamAPI(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
log.Printf("Successfully served stream API for provider: %s, tmdb_id: %s", provider, tmdbID)
|
log.Printf("Successfully served stream API for provider: %s, tmdb_id: %s", provider, tmdbID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetVidsrcPlayer handles Vidsrc.to player (uses IMDb ID for both movies and TV shows)
|
|
||||||
func (h *PlayersHandler) GetVidsrcPlayer(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("GetVidsrcPlayer called: %s %s", r.Method, r.URL.Path)
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
imdbId := vars["imdb_id"]
|
|
||||||
mediaType := vars["media_type"] // "movie" or "tv"
|
|
||||||
|
|
||||||
if imdbId == "" || mediaType == "" {
|
|
||||||
http.Error(w, "imdb_id and media_type are required", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var playerURL string
|
|
||||||
if mediaType == "movie" {
|
|
||||||
playerURL = fmt.Sprintf("https://vidsrc.to/embed/movie/%s", imdbId)
|
|
||||||
} else if mediaType == "tv" {
|
|
||||||
season := r.URL.Query().Get("season")
|
|
||||||
episode := r.URL.Query().Get("episode")
|
|
||||||
if season == "" || episode == "" {
|
|
||||||
http.Error(w, "season and episode are required for TV shows", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
playerURL = fmt.Sprintf("https://vidsrc.to/embed/tv/%s/%s/%s", imdbId, season, episode)
|
|
||||||
} else {
|
|
||||||
http.Error(w, "Invalid media_type. Use 'movie' or 'tv'", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("Generated Vidsrc URL: %s", playerURL)
|
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidsrc Player")
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
|
||||||
w.Write([]byte(htmlDoc))
|
|
||||||
|
|
||||||
log.Printf("Successfully served Vidsrc player for %s: %s", mediaType, imdbId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetVidlinkMoviePlayer handles vidlink.pro player for movies (uses IMDb ID)
|
|
||||||
func (h *PlayersHandler) GetVidlinkMoviePlayer(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("GetVidlinkMoviePlayer called: %s %s", r.Method, r.URL.Path)
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
imdbId := vars["imdb_id"]
|
|
||||||
|
|
||||||
if imdbId == "" {
|
|
||||||
http.Error(w, "imdb_id is required", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
playerURL := fmt.Sprintf("https://vidlink.pro/movie/%s", imdbId)
|
|
||||||
|
|
||||||
log.Printf("Generated Vidlink Movie URL: %s", playerURL)
|
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
|
||||||
w.Write([]byte(htmlDoc))
|
|
||||||
|
|
||||||
log.Printf("Successfully served Vidlink movie player: %s", imdbId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetVidlinkTVPlayer handles vidlink.pro player for TV shows (uses TMDB ID)
|
|
||||||
func (h *PlayersHandler) GetHDVBPlayer(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("GetHDVBPlayer 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 != "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.HDVBToken == "" {
|
|
||||||
log.Printf("Error: HDVB_TOKEN is missing")
|
|
||||||
http.Error(w, "Server misconfiguration: HDVB_TOKEN missing", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var apiURL string
|
|
||||||
if idType == "kp" {
|
|
||||||
apiURL = fmt.Sprintf("https://apivb.com/api/videos.json?id_kp=%s&token=%s", id, h.config.HDVBToken)
|
|
||||||
} else {
|
|
||||||
apiURL = fmt.Sprintf("https://apivb.com/api/videos.json?imdb_id=%s&token=%s", id, h.config.HDVBToken)
|
|
||||||
}
|
|
||||||
log.Printf("HDVB API URL: %s", apiURL)
|
|
||||||
|
|
||||||
resp, err := http.Get(apiURL)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error fetching HDVB data: %v", err)
|
|
||||||
http.Error(w, "Failed to fetch player data", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error reading HDVB response: %v", err)
|
|
||||||
http.Error(w, "Failed to read player data", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var hdvbData []map[string]interface{}
|
|
||||||
if err := json.Unmarshal(body, &hdvbData); err != nil {
|
|
||||||
log.Printf("Error parsing HDVB JSON: %v, body: %s", err, string(body))
|
|
||||||
http.Error(w, "Failed to parse player data", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(hdvbData) == 0 {
|
|
||||||
log.Printf("No HDVB data found for ID: %s", id)
|
|
||||||
http.Error(w, "No player data found", http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
iframeURL, ok := hdvbData[0]["iframe_url"].(string)
|
|
||||||
if !ok || iframeURL == "" {
|
|
||||||
log.Printf("No iframe_url in HDVB response for ID: %s", id)
|
|
||||||
http.Error(w, "No player URL found", http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("HDVB iframe URL: %s", iframeURL)
|
|
||||||
|
|
||||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, iframeURL)
|
|
||||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>HDVB Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
|
||||||
w.Write([]byte(htmlDoc))
|
|
||||||
|
|
||||||
log.Printf("Successfully served HDVB player for %s: %s", idType, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *PlayersHandler) GetVidlinkTVPlayer(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("GetVidlinkTVPlayer called: %s %s", r.Method, r.URL.Path)
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
tmdbId := vars["tmdb_id"]
|
|
||||||
|
|
||||||
if tmdbId == "" {
|
|
||||||
http.Error(w, "tmdb_id is required", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
season := r.URL.Query().Get("season")
|
|
||||||
episode := r.URL.Query().Get("episode")
|
|
||||||
if season == "" || episode == "" {
|
|
||||||
http.Error(w, "season and episode are required for TV shows", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
playerURL := fmt.Sprintf("https://vidlink.pro/tv/%s/%s/%s", tmdbId, season, episode)
|
|
||||||
|
|
||||||
log.Printf("Generated Vidlink TV URL: %s", playerURL)
|
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
|
||||||
w.Write([]byte(htmlDoc))
|
|
||||||
|
|
||||||
log.Printf("Successfully served Vidlink TV player: %s S%sE%s", tmdbId, season, episode)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getPlayerWithControlsHTML возвращает HTML с плеером и overlay для блокировки кликов
|
|
||||||
func getPlayerWithControlsHTML(playerURL, title string) string {
|
|
||||||
return fmt.Sprintf(`<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset='utf-8'/>
|
|
||||||
<title>%s</title>
|
|
||||||
<style>
|
|
||||||
html,body{margin:0;height:100%%;overflow:hidden;background:#000;font-family:Arial,sans-serif;}
|
|
||||||
#container{position:relative;width:100%%;height:100%%;}
|
|
||||||
#player-iframe{position:absolute;top:0;left:0;width:100%%;height:100%%;border:none;}
|
|
||||||
#overlay{position:absolute;top:0;left:0;width:100%%;height:100%%;z-index:10;pointer-events:none;}
|
|
||||||
#controls{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,0.8));padding:20px;opacity:0;transition:opacity 0.3s;pointer-events:auto;z-index:20;}
|
|
||||||
#container:hover #controls{opacity:1;}
|
|
||||||
.btn{background:rgba(255,255,255,0.2);border:none;color:#fff;padding:12px 20px;margin:0 5px;border-radius:5px;cursor:pointer;font-size:16px;transition:background 0.2s;}
|
|
||||||
.btn:hover{background:rgba(255,255,255,0.4);}
|
|
||||||
.btn:active{background:rgba(255,255,255,0.6);}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="container">
|
|
||||||
<iframe id="player-iframe" src="%s" allowfullscreen allow="autoplay; encrypted-media; fullscreen; picture-in-picture"></iframe>
|
|
||||||
<div id="overlay"></div>
|
|
||||||
<div id="controls">
|
|
||||||
<button class="btn" id="btn-fullscreen" title="Fullscreen">⛶ Fullscreen</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
const overlay=document.getElementById('overlay');
|
|
||||||
|
|
||||||
// Блокируем клики на iframe (защита от рекламы)
|
|
||||||
overlay.addEventListener('click',(e)=>{e.preventDefault();e.stopPropagation();});
|
|
||||||
overlay.addEventListener('mousedown',(e)=>{e.preventDefault();e.stopPropagation();});
|
|
||||||
|
|
||||||
// Fullscreen
|
|
||||||
document.getElementById('btn-fullscreen').addEventListener('click',()=>{
|
|
||||||
if(!document.fullscreenElement){
|
|
||||||
document.getElementById('container').requestFullscreen();
|
|
||||||
}else{
|
|
||||||
document.exitFullscreen();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>`, title, playerURL)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,13 +10,11 @@ import (
|
|||||||
|
|
||||||
type SearchHandler struct {
|
type SearchHandler struct {
|
||||||
tmdbService *services.TMDBService
|
tmdbService *services.TMDBService
|
||||||
kpService *services.KinopoiskService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSearchHandler(tmdbService *services.TMDBService, kpService *services.KinopoiskService) *SearchHandler {
|
func NewSearchHandler(tmdbService *services.TMDBService) *SearchHandler {
|
||||||
return &SearchHandler{
|
return &SearchHandler{
|
||||||
tmdbService: tmdbService,
|
tmdbService: tmdbService,
|
||||||
kpService: kpService,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,53 +26,11 @@ func (h *SearchHandler) MultiSearch(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
if language == "" {
|
||||||
if services.ShouldUseKinopoisk(language) {
|
language = "ru-RU"
|
||||||
if h.kpService == nil {
|
|
||||||
http.Error(w, "Kinopoisk service is not configured", http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
kpSearch, err := h.kpService.SearchFilms(query, page)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tmdbResp := services.MapKPSearchToTMDBResponse(kpSearch)
|
|
||||||
multiResults := make([]models.MultiSearchResult, 0)
|
|
||||||
for _, movie := range tmdbResp.Results {
|
|
||||||
multiResults = append(multiResults, models.MultiSearchResult{
|
|
||||||
ID: movie.ID,
|
|
||||||
MediaType: "movie",
|
|
||||||
Title: movie.Title,
|
|
||||||
OriginalTitle: movie.OriginalTitle,
|
|
||||||
Overview: movie.Overview,
|
|
||||||
PosterPath: movie.PosterPath,
|
|
||||||
BackdropPath: movie.BackdropPath,
|
|
||||||
ReleaseDate: movie.ReleaseDate,
|
|
||||||
VoteAverage: movie.VoteAverage,
|
|
||||||
VoteCount: movie.VoteCount,
|
|
||||||
Popularity: movie.Popularity,
|
|
||||||
Adult: movie.Adult,
|
|
||||||
OriginalLanguage: movie.OriginalLanguage,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(models.APIResponse{
|
|
||||||
Success: true,
|
|
||||||
Data: models.MultiSearchResponse{
|
|
||||||
Page: page,
|
|
||||||
Results: multiResults,
|
|
||||||
TotalPages: tmdbResp.TotalPages,
|
|
||||||
TotalResults: tmdbResp.TotalResults,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// EN/прочие языки — TMDB
|
|
||||||
results, err := h.tmdbService.SearchMulti(query, page, language)
|
results, err := h.tmdbService.SearchMulti(query, page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
@@ -30,7 +29,7 @@ func (h *TVHandler) Search(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
year := getIntQuery(r, "first_air_date_year", 0)
|
year := getIntQuery(r, "first_air_date_year", 0)
|
||||||
|
|
||||||
tvShows, err := h.tvService.Search(query, page, language, year)
|
tvShows, err := h.tvService.Search(query, page, language, year)
|
||||||
@@ -48,41 +47,15 @@ func (h *TVHandler) Search(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *TVHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
func (h *TVHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
rawID := vars["id"]
|
id, err := strconv.Atoi(vars["id"])
|
||||||
|
|
||||||
// Support formats: "123" (old), "kp_123", "tmdb_123"
|
|
||||||
source := ""
|
|
||||||
var id int
|
|
||||||
if strings.Contains(rawID, "_") {
|
|
||||||
parts := strings.SplitN(rawID, "_", 2)
|
|
||||||
if len(parts) != 2 {
|
|
||||||
http.Error(w, "Invalid ID format", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
source = parts[0]
|
|
||||||
parsed, err := strconv.Atoi(parts[1])
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid numeric ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id = parsed
|
|
||||||
} else {
|
|
||||||
// Backward compatibility
|
|
||||||
parsed, err := strconv.Atoi(rawID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Invalid TV show ID", http.StatusBadRequest)
|
http.Error(w, "Invalid TV show ID", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id = parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
idType := r.URL.Query().Get("id_type")
|
|
||||||
if source == "kp" || source == "tmdb" {
|
|
||||||
idType = source
|
|
||||||
}
|
|
||||||
|
|
||||||
tvShow, err := h.tvService.GetByID(id, language, idType)
|
tvShow, err := h.tvService.GetByID(id, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -97,7 +70,7 @@ func (h *TVHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *TVHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
func (h *TVHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetPopular(page, language)
|
tvShows, err := h.tvService.GetPopular(page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -114,7 +87,7 @@ func (h *TVHandler) Popular(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *TVHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
func (h *TVHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetTopRated(page, language)
|
tvShows, err := h.tvService.GetTopRated(page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -131,7 +104,7 @@ func (h *TVHandler) TopRated(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *TVHandler) OnTheAir(w http.ResponseWriter, r *http.Request) {
|
func (h *TVHandler) OnTheAir(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetOnTheAir(page, language)
|
tvShows, err := h.tvService.GetOnTheAir(page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -148,7 +121,7 @@ func (h *TVHandler) OnTheAir(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (h *TVHandler) AiringToday(w http.ResponseWriter, r *http.Request) {
|
func (h *TVHandler) AiringToday(w http.ResponseWriter, r *http.Request) {
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetAiringToday(page, language)
|
tvShows, err := h.tvService.GetAiringToday(page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -172,7 +145,7 @@ func (h *TVHandler) GetRecommendations(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetRecommendations(id, page, language)
|
tvShows, err := h.tvService.GetRecommendations(id, page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -196,7 +169,7 @@ func (h *TVHandler) GetSimilar(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := r.URL.Query().Get("language")
|
||||||
|
|
||||||
tvShows, err := h.tvService.GetSimilar(id, page, language)
|
tvShows, err := h.tvService.GetSimilar(id, page, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ type Movie struct {
|
|||||||
Tagline string `json:"tagline,omitempty"`
|
Tagline string `json:"tagline,omitempty"`
|
||||||
Homepage string `json:"homepage,omitempty"`
|
Homepage string `json:"homepage,omitempty"`
|
||||||
IMDbID string `json:"imdb_id,omitempty"`
|
IMDbID string `json:"imdb_id,omitempty"`
|
||||||
KinopoiskID int `json:"kinopoisk_id,omitempty"`
|
|
||||||
BelongsToCollection *Collection `json:"belongs_to_collection,omitempty"`
|
BelongsToCollection *Collection `json:"belongs_to_collection,omitempty"`
|
||||||
ProductionCompanies []ProductionCompany `json:"production_companies,omitempty"`
|
ProductionCompanies []ProductionCompany `json:"production_companies,omitempty"`
|
||||||
ProductionCountries []ProductionCountry `json:"production_countries,omitempty"`
|
ProductionCountries []ProductionCountry `json:"production_countries,omitempty"`
|
||||||
@@ -77,8 +76,6 @@ type TVShow struct {
|
|||||||
CreatedBy []Creator `json:"created_by,omitempty"`
|
CreatedBy []Creator `json:"created_by,omitempty"`
|
||||||
EpisodeRunTime []int `json:"episode_run_time,omitempty"`
|
EpisodeRunTime []int `json:"episode_run_time,omitempty"`
|
||||||
Seasons []Season `json:"seasons,omitempty"`
|
Seasons []Season `json:"seasons,omitempty"`
|
||||||
IMDbID string `json:"imdb_id,omitempty"`
|
|
||||||
KinopoiskID int `json:"kinopoisk_id,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MultiSearchResult для мультипоиска
|
// MultiSearchResult для мультипоиска
|
||||||
@@ -122,7 +119,6 @@ type GenresResponse struct {
|
|||||||
type ExternalIDs struct {
|
type ExternalIDs struct {
|
||||||
ID int `json:"id"`
|
ID int `json:"id"`
|
||||||
IMDbID string `json:"imdb_id"`
|
IMDbID string `json:"imdb_id"`
|
||||||
KinopoiskID int `json:"kinopoisk_id,omitempty"`
|
|
||||||
TVDBID int `json:"tvdb_id,omitempty"`
|
TVDBID int `json:"tvdb_id,omitempty"`
|
||||||
WikidataID string `json:"wikidata_id"`
|
WikidataID string `json:"wikidata_id"`
|
||||||
FacebookID string `json:"facebook_id"`
|
FacebookID string `json:"facebook_id"`
|
||||||
|
|||||||
@@ -1,261 +0,0 @@
|
|||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type KinopoiskService struct {
|
|
||||||
apiKey string
|
|
||||||
baseURL string
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPFilm struct {
|
|
||||||
KinopoiskId int `json:"kinopoiskId"`
|
|
||||||
ImdbId string `json:"imdbId"`
|
|
||||||
NameRu string `json:"nameRu"`
|
|
||||||
NameEn string `json:"nameEn"`
|
|
||||||
NameOriginal string `json:"nameOriginal"`
|
|
||||||
PosterUrl string `json:"posterUrl"`
|
|
||||||
PosterUrlPreview string `json:"posterUrlPreview"`
|
|
||||||
CoverUrl string `json:"coverUrl"`
|
|
||||||
LogoUrl string `json:"logoUrl"`
|
|
||||||
ReviewsCount int `json:"reviewsCount"`
|
|
||||||
RatingGoodReview float64 `json:"ratingGoodReview"`
|
|
||||||
RatingGoodReviewVoteCount int `json:"ratingGoodReviewVoteCount"`
|
|
||||||
RatingKinopoisk float64 `json:"ratingKinopoisk"`
|
|
||||||
RatingKinopoiskVoteCount int `json:"ratingKinopoiskVoteCount"`
|
|
||||||
RatingImdb float64 `json:"ratingImdb"`
|
|
||||||
RatingImdbVoteCount int `json:"ratingImdbVoteCount"`
|
|
||||||
RatingFilmCritics float64 `json:"ratingFilmCritics"`
|
|
||||||
RatingFilmCriticsVoteCount int `json:"ratingFilmCriticsVoteCount"`
|
|
||||||
RatingAwait float64 `json:"ratingAwait"`
|
|
||||||
RatingAwaitCount int `json:"ratingAwaitCount"`
|
|
||||||
RatingRfCritics float64 `json:"ratingRfCritics"`
|
|
||||||
RatingRfCriticsVoteCount int `json:"ratingRfCriticsVoteCount"`
|
|
||||||
WebUrl string `json:"webUrl"`
|
|
||||||
Year int `json:"year"`
|
|
||||||
FilmLength int `json:"filmLength"`
|
|
||||||
Slogan string `json:"slogan"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
ShortDescription string `json:"shortDescription"`
|
|
||||||
EditorAnnotation string `json:"editorAnnotation"`
|
|
||||||
IsTicketsAvailable bool `json:"isTicketsAvailable"`
|
|
||||||
ProductionStatus string `json:"productionStatus"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
RatingMpaa string `json:"ratingMpaa"`
|
|
||||||
RatingAgeLimits string `json:"ratingAgeLimits"`
|
|
||||||
HasImax bool `json:"hasImax"`
|
|
||||||
Has3D bool `json:"has3d"`
|
|
||||||
LastSync string `json:"lastSync"`
|
|
||||||
Countries []struct {
|
|
||||||
Country string `json:"country"`
|
|
||||||
} `json:"countries"`
|
|
||||||
Genres []struct {
|
|
||||||
Genre string `json:"genre"`
|
|
||||||
} `json:"genres"`
|
|
||||||
StartYear int `json:"startYear"`
|
|
||||||
EndYear int `json:"endYear"`
|
|
||||||
Serial bool `json:"serial"`
|
|
||||||
ShortFilm bool `json:"shortFilm"`
|
|
||||||
Completed bool `json:"completed"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPSearchResponse struct {
|
|
||||||
Keyword string `json:"keyword"`
|
|
||||||
PagesCount int `json:"pagesCount"`
|
|
||||||
Films []KPFilmShort `json:"films"`
|
|
||||||
SearchFilmsCountResult int `json:"searchFilmsCountResult"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPFilmShort struct {
|
|
||||||
FilmId int `json:"filmId"`
|
|
||||||
NameRu string `json:"nameRu"`
|
|
||||||
NameEn string `json:"nameEn"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Year string `json:"year"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
FilmLength string `json:"filmLength"`
|
|
||||||
Countries []KPCountry `json:"countries"`
|
|
||||||
Genres []KPGenre `json:"genres"`
|
|
||||||
Rating string `json:"rating"`
|
|
||||||
RatingVoteCount int `json:"ratingVoteCount"`
|
|
||||||
PosterUrl string `json:"posterUrl"`
|
|
||||||
PosterUrlPreview string `json:"posterUrlPreview"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPCountry struct {
|
|
||||||
Country string `json:"country"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPGenre struct {
|
|
||||||
Genre string `json:"genre"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type KPExternalSource struct {
|
|
||||||
Source string `json:"source"`
|
|
||||||
ID string `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewKinopoiskService(apiKey, baseURL string) *KinopoiskService {
|
|
||||||
return &KinopoiskService{
|
|
||||||
apiKey: apiKey,
|
|
||||||
baseURL: baseURL,
|
|
||||||
client: &http.Client{Timeout: 10 * time.Second},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) makeRequest(endpoint string, target interface{}) error {
|
|
||||||
req, err := http.NewRequest("GET", endpoint, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("X-API-KEY", s.apiKey)
|
|
||||||
req.Header.Set("Accept", "application/json")
|
|
||||||
|
|
||||||
resp, err := s.client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("Kinopoisk API error: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.NewDecoder(resp.Body).Decode(target)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) GetFilmByKinopoiskId(id int) (*KPFilm, error) {
|
|
||||||
endpoint := fmt.Sprintf("%s/v2.2/films/%d", s.baseURL, id)
|
|
||||||
var film KPFilm
|
|
||||||
err := s.makeRequest(endpoint, &film)
|
|
||||||
return &film, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) GetFilmByImdbId(imdbId string) (*KPFilm, error) {
|
|
||||||
endpoint := fmt.Sprintf("%s/v2.2/films?imdbId=%s", s.baseURL, imdbId)
|
|
||||||
|
|
||||||
var response struct {
|
|
||||||
Films []KPFilm `json:"items"`
|
|
||||||
}
|
|
||||||
|
|
||||||
err := s.makeRequest(endpoint, &response)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(response.Films) == 0 {
|
|
||||||
return nil, fmt.Errorf("film not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
return &response.Films[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) SearchFilms(keyword string, page int) (*KPSearchResponse, error) {
|
|
||||||
endpoint := fmt.Sprintf("%s/v2.1/films/search-by-keyword?keyword=%s&page=%d", s.baseURL, keyword, page)
|
|
||||||
var response KPSearchResponse
|
|
||||||
err := s.makeRequest(endpoint, &response)
|
|
||||||
return &response, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) GetExternalSources(kinopoiskId int) ([]KPExternalSource, error) {
|
|
||||||
endpoint := fmt.Sprintf("%s/v2.2/films/%d/external_sources", s.baseURL, kinopoiskId)
|
|
||||||
|
|
||||||
var response struct {
|
|
||||||
Items []KPExternalSource `json:"items"`
|
|
||||||
}
|
|
||||||
|
|
||||||
err := s.makeRequest(endpoint, &response)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.Items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *KinopoiskService) GetTopFilms(topType string, page int) (*KPSearchResponse, error) {
|
|
||||||
endpoint := fmt.Sprintf("%s/v2.2/films/top?type=%s&page=%d", s.baseURL, topType, page)
|
|
||||||
|
|
||||||
var response struct {
|
|
||||||
PagesCount int `json:"pagesCount"`
|
|
||||||
Films []KPFilmShort `json:"films"`
|
|
||||||
}
|
|
||||||
|
|
||||||
err := s.makeRequest(endpoint, &response)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &KPSearchResponse{
|
|
||||||
PagesCount: response.PagesCount,
|
|
||||||
Films: response.Films,
|
|
||||||
SearchFilmsCountResult: len(response.Films),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func KPIdToImdbId(kpService *KinopoiskService, kpId int) (string, error) {
|
|
||||||
film, err := kpService.GetFilmByKinopoiskId(kpId)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return film.ImdbId, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ImdbIdToKPId(kpService *KinopoiskService, imdbId string) (int, error) {
|
|
||||||
film, err := kpService.GetFilmByImdbId(imdbId)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return film.KinopoiskId, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TmdbIdToKPId(tmdbService *TMDBService, kpService *KinopoiskService, tmdbId int) (int, error) {
|
|
||||||
externalIds, err := tmdbService.GetMovieExternalIDs(tmdbId)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if externalIds.IMDbID == "" {
|
|
||||||
return 0, fmt.Errorf("no IMDb ID found for TMDB ID %d", tmdbId)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ImdbIdToKPId(kpService, externalIds.IMDbID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func KPIdToTmdbId(tmdbService *TMDBService, kpService *KinopoiskService, kpId int) (int, error) {
|
|
||||||
imdbId, err := KPIdToImdbId(kpService, kpId)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
movies, err := tmdbService.SearchMovies("", 1, "en-US", "", 0)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, movie := range movies.Results {
|
|
||||||
ids, err := tmdbService.GetMovieExternalIDs(movie.ID)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ids.IMDbID == imdbId {
|
|
||||||
return movie.ID, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0, fmt.Errorf("TMDB ID not found for KP ID %d", kpId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ConvertKPRating(rating float64) float64 {
|
|
||||||
return rating
|
|
||||||
}
|
|
||||||
|
|
||||||
func FormatKPYear(year int) string {
|
|
||||||
return strconv.Itoa(year)
|
|
||||||
}
|
|
||||||
@@ -1,390 +0,0 @@
|
|||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
func MapKPFilmToTMDBMovie(kpFilm *KPFilm) *models.Movie {
|
|
||||||
if kpFilm == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
releaseDate := ""
|
|
||||||
if kpFilm.Year > 0 {
|
|
||||||
releaseDate = fmt.Sprintf("%d-01-01", kpFilm.Year)
|
|
||||||
}
|
|
||||||
|
|
||||||
genres := make([]models.Genre, 0)
|
|
||||||
for _, g := range kpFilm.Genres {
|
|
||||||
genres = append(genres, models.Genre{
|
|
||||||
ID: 0,
|
|
||||||
Name: g.Genre,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
countries := make([]models.ProductionCountry, 0)
|
|
||||||
for _, c := range kpFilm.Countries {
|
|
||||||
countries = append(countries, models.ProductionCountry{
|
|
||||||
ISO31661: "",
|
|
||||||
Name: c.Country,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
posterPath := ""
|
|
||||||
if kpFilm.PosterUrlPreview != "" {
|
|
||||||
posterPath = kpFilm.PosterUrlPreview
|
|
||||||
} else if kpFilm.PosterUrl != "" {
|
|
||||||
posterPath = kpFilm.PosterUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
backdropPath := ""
|
|
||||||
if kpFilm.CoverUrl != "" {
|
|
||||||
backdropPath = kpFilm.CoverUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
overview := kpFilm.Description
|
|
||||||
if overview == "" {
|
|
||||||
overview = kpFilm.ShortDescription
|
|
||||||
}
|
|
||||||
|
|
||||||
title := kpFilm.NameRu
|
|
||||||
if title == "" {
|
|
||||||
title = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
if title == "" {
|
|
||||||
title = kpFilm.NameOriginal
|
|
||||||
}
|
|
||||||
|
|
||||||
originalTitle := kpFilm.NameOriginal
|
|
||||||
if originalTitle == "" {
|
|
||||||
originalTitle = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.Movie{
|
|
||||||
ID: kpFilm.KinopoiskId,
|
|
||||||
Title: title,
|
|
||||||
OriginalTitle: originalTitle,
|
|
||||||
Overview: overview,
|
|
||||||
PosterPath: posterPath,
|
|
||||||
BackdropPath: backdropPath,
|
|
||||||
ReleaseDate: releaseDate,
|
|
||||||
VoteAverage: kpFilm.RatingKinopoisk,
|
|
||||||
VoteCount: kpFilm.RatingKinopoiskVoteCount,
|
|
||||||
Popularity: float64(kpFilm.RatingKinopoisk * 100),
|
|
||||||
Adult: false,
|
|
||||||
OriginalLanguage: detectLanguage(kpFilm),
|
|
||||||
Runtime: kpFilm.FilmLength,
|
|
||||||
Genres: genres,
|
|
||||||
Tagline: kpFilm.Slogan,
|
|
||||||
ProductionCountries: countries,
|
|
||||||
IMDbID: kpFilm.ImdbId,
|
|
||||||
KinopoiskID: kpFilm.KinopoiskId,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapKPFilmToTVShow(kpFilm *KPFilm) *models.TVShow {
|
|
||||||
if kpFilm == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
firstAirDate := ""
|
|
||||||
if kpFilm.StartYear > 0 {
|
|
||||||
firstAirDate = fmt.Sprintf("%d-01-01", kpFilm.StartYear)
|
|
||||||
}
|
|
||||||
|
|
||||||
lastAirDate := ""
|
|
||||||
if kpFilm.EndYear > 0 {
|
|
||||||
lastAirDate = fmt.Sprintf("%d-01-01", kpFilm.EndYear)
|
|
||||||
}
|
|
||||||
|
|
||||||
genres := make([]models.Genre, 0)
|
|
||||||
for _, g := range kpFilm.Genres {
|
|
||||||
genres = append(genres, models.Genre{
|
|
||||||
ID: 0,
|
|
||||||
Name: g.Genre,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
posterPath := ""
|
|
||||||
if kpFilm.PosterUrlPreview != "" {
|
|
||||||
posterPath = kpFilm.PosterUrlPreview
|
|
||||||
} else if kpFilm.PosterUrl != "" {
|
|
||||||
posterPath = kpFilm.PosterUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
backdropPath := ""
|
|
||||||
if kpFilm.CoverUrl != "" {
|
|
||||||
backdropPath = kpFilm.CoverUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
overview := kpFilm.Description
|
|
||||||
if overview == "" {
|
|
||||||
overview = kpFilm.ShortDescription
|
|
||||||
}
|
|
||||||
|
|
||||||
name := kpFilm.NameRu
|
|
||||||
if name == "" {
|
|
||||||
name = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
if name == "" {
|
|
||||||
name = kpFilm.NameOriginal
|
|
||||||
}
|
|
||||||
|
|
||||||
originalName := kpFilm.NameOriginal
|
|
||||||
if originalName == "" {
|
|
||||||
originalName = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
|
|
||||||
status := "Ended"
|
|
||||||
if kpFilm.Completed {
|
|
||||||
status = "Ended"
|
|
||||||
} else {
|
|
||||||
status = "Returning Series"
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.TVShow{
|
|
||||||
ID: kpFilm.KinopoiskId,
|
|
||||||
Name: name,
|
|
||||||
OriginalName: originalName,
|
|
||||||
Overview: overview,
|
|
||||||
PosterPath: posterPath,
|
|
||||||
BackdropPath: backdropPath,
|
|
||||||
FirstAirDate: firstAirDate,
|
|
||||||
LastAirDate: lastAirDate,
|
|
||||||
VoteAverage: kpFilm.RatingKinopoisk,
|
|
||||||
VoteCount: kpFilm.RatingKinopoiskVoteCount,
|
|
||||||
Popularity: float64(kpFilm.RatingKinopoisk * 100),
|
|
||||||
OriginalLanguage: detectLanguage(kpFilm),
|
|
||||||
Genres: genres,
|
|
||||||
Status: status,
|
|
||||||
InProduction: !kpFilm.Completed,
|
|
||||||
KinopoiskID: kpFilm.KinopoiskId,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unified mappers with prefixed IDs
|
|
||||||
func MapKPToUnified(kpFilm *KPFilm) *models.UnifiedContent {
|
|
||||||
if kpFilm == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
releaseDate := FormatKPDate(kpFilm.Year)
|
|
||||||
endDate := (*string)(nil)
|
|
||||||
if kpFilm.EndYear > 0 {
|
|
||||||
v := FormatKPDate(kpFilm.EndYear)
|
|
||||||
endDate = &v
|
|
||||||
}
|
|
||||||
|
|
||||||
genres := make([]models.UnifiedGenre, 0)
|
|
||||||
for _, g := range kpFilm.Genres {
|
|
||||||
genres = append(genres, models.UnifiedGenre{ID: strings.ToLower(g.Genre), Name: g.Genre})
|
|
||||||
}
|
|
||||||
|
|
||||||
poster := kpFilm.PosterUrlPreview
|
|
||||||
if poster == "" {
|
|
||||||
poster = kpFilm.PosterUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
country := ""
|
|
||||||
if len(kpFilm.Countries) > 0 {
|
|
||||||
country = kpFilm.Countries[0].Country
|
|
||||||
}
|
|
||||||
|
|
||||||
title := kpFilm.NameRu
|
|
||||||
if title == "" {
|
|
||||||
title = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
originalTitle := kpFilm.NameOriginal
|
|
||||||
if originalTitle == "" {
|
|
||||||
originalTitle = kpFilm.NameEn
|
|
||||||
}
|
|
||||||
|
|
||||||
var budgetPtr *int64
|
|
||||||
var revenuePtr *int64
|
|
||||||
|
|
||||||
external := models.UnifiedExternalIDs{KP: &kpFilm.KinopoiskId, TMDB: nil, IMDb: kpFilm.ImdbId}
|
|
||||||
|
|
||||||
return &models.UnifiedContent{
|
|
||||||
ID: strconv.Itoa(kpFilm.KinopoiskId),
|
|
||||||
SourceID: "kp_" + strconv.Itoa(kpFilm.KinopoiskId),
|
|
||||||
Title: title,
|
|
||||||
OriginalTitle: originalTitle,
|
|
||||||
Description: firstNonEmpty(kpFilm.Description, kpFilm.ShortDescription),
|
|
||||||
ReleaseDate: releaseDate,
|
|
||||||
EndDate: endDate,
|
|
||||||
Type: mapKPTypeToUnified(kpFilm),
|
|
||||||
Genres: genres,
|
|
||||||
Rating: kpFilm.RatingKinopoisk,
|
|
||||||
PosterURL: poster,
|
|
||||||
BackdropURL: kpFilm.CoverUrl,
|
|
||||||
Director: "",
|
|
||||||
Cast: []models.UnifiedCastMember{},
|
|
||||||
Duration: kpFilm.FilmLength,
|
|
||||||
Country: country,
|
|
||||||
Language: detectLanguage(kpFilm),
|
|
||||||
Budget: budgetPtr,
|
|
||||||
Revenue: revenuePtr,
|
|
||||||
IMDbID: kpFilm.ImdbId,
|
|
||||||
ExternalIDs: external,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapKPTypeToUnified(kp *KPFilm) string {
|
|
||||||
if kp.Serial || kp.Type == "TV_SERIES" || kp.Type == "MINI_SERIES" {
|
|
||||||
return "tv"
|
|
||||||
}
|
|
||||||
return "movie"
|
|
||||||
}
|
|
||||||
|
|
||||||
func firstNonEmpty(values ...string) string {
|
|
||||||
for _, v := range values {
|
|
||||||
if strings.TrimSpace(v) != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapKPSearchToTMDBResponse(kpSearch *KPSearchResponse) *models.TMDBResponse {
|
|
||||||
if kpSearch == nil {
|
|
||||||
return &models.TMDBResponse{
|
|
||||||
Page: 1,
|
|
||||||
Results: []models.Movie{},
|
|
||||||
TotalPages: 0,
|
|
||||||
TotalResults: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
results := make([]models.Movie, 0)
|
|
||||||
for _, film := range kpSearch.Films {
|
|
||||||
movie := mapKPFilmShortToMovie(film)
|
|
||||||
if movie != nil {
|
|
||||||
results = append(results, *movie)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
totalPages := kpSearch.PagesCount
|
|
||||||
if totalPages == 0 && len(results) > 0 {
|
|
||||||
totalPages = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.TMDBResponse{
|
|
||||||
Page: 1,
|
|
||||||
Results: results,
|
|
||||||
TotalPages: totalPages,
|
|
||||||
TotalResults: kpSearch.SearchFilmsCountResult,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapKPFilmShortToMovie(film KPFilmShort) *models.Movie {
|
|
||||||
genres := make([]models.Genre, 0)
|
|
||||||
for _, g := range film.Genres {
|
|
||||||
genres = append(genres, models.Genre{
|
|
||||||
ID: 0,
|
|
||||||
Name: g.Genre,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
year := 0
|
|
||||||
if film.Year != "" {
|
|
||||||
year, _ = strconv.Atoi(film.Year)
|
|
||||||
}
|
|
||||||
|
|
||||||
releaseDate := ""
|
|
||||||
if year > 0 {
|
|
||||||
releaseDate = fmt.Sprintf("%d-01-01", year)
|
|
||||||
}
|
|
||||||
|
|
||||||
posterPath := film.PosterUrlPreview
|
|
||||||
if posterPath == "" {
|
|
||||||
posterPath = film.PosterUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
title := film.NameRu
|
|
||||||
if title == "" {
|
|
||||||
title = film.NameEn
|
|
||||||
}
|
|
||||||
|
|
||||||
originalTitle := film.NameEn
|
|
||||||
if originalTitle == "" {
|
|
||||||
originalTitle = film.NameRu
|
|
||||||
}
|
|
||||||
|
|
||||||
rating := 0.0
|
|
||||||
if film.Rating != "" {
|
|
||||||
rating, _ = strconv.ParseFloat(film.Rating, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.Movie{
|
|
||||||
ID: film.FilmId,
|
|
||||||
Title: title,
|
|
||||||
OriginalTitle: originalTitle,
|
|
||||||
Overview: film.Description,
|
|
||||||
PosterPath: posterPath,
|
|
||||||
ReleaseDate: releaseDate,
|
|
||||||
VoteAverage: rating,
|
|
||||||
VoteCount: film.RatingVoteCount,
|
|
||||||
Popularity: rating * 100,
|
|
||||||
Genres: genres,
|
|
||||||
KinopoiskID: film.FilmId,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func detectLanguage(film *KPFilm) string {
|
|
||||||
if film.NameRu != "" {
|
|
||||||
return "ru"
|
|
||||||
}
|
|
||||||
if film.NameEn != "" {
|
|
||||||
return "en"
|
|
||||||
}
|
|
||||||
return "ru"
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapKPExternalIDsToTMDB(kpFilm *KPFilm) *models.ExternalIDs {
|
|
||||||
if kpFilm == nil {
|
|
||||||
return &models.ExternalIDs{}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.ExternalIDs{
|
|
||||||
ID: kpFilm.KinopoiskId,
|
|
||||||
IMDbID: kpFilm.ImdbId,
|
|
||||||
KinopoiskID: kpFilm.KinopoiskId,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ShouldUseKinopoisk(language string) bool {
|
|
||||||
if language == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
lang := strings.ToLower(language)
|
|
||||||
return strings.HasPrefix(lang, "ru")
|
|
||||||
}
|
|
||||||
|
|
||||||
func NormalizeLanguage(language string) string {
|
|
||||||
if language == "" {
|
|
||||||
return "en-US"
|
|
||||||
}
|
|
||||||
|
|
||||||
lang := strings.ToLower(language)
|
|
||||||
if strings.HasPrefix(lang, "ru") {
|
|
||||||
return "ru-RU"
|
|
||||||
}
|
|
||||||
|
|
||||||
return "en-US"
|
|
||||||
}
|
|
||||||
|
|
||||||
func ConvertKPRatingToTMDB(kpRating float64) float64 {
|
|
||||||
return kpRating
|
|
||||||
}
|
|
||||||
|
|
||||||
func FormatKPDate(year int) string {
|
|
||||||
if year <= 0 {
|
|
||||||
return time.Now().Format("2006-01-02")
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%d-01-01", year)
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package services
|
package services
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
@@ -9,79 +8,27 @@ import (
|
|||||||
|
|
||||||
type MovieService struct {
|
type MovieService struct {
|
||||||
tmdb *TMDBService
|
tmdb *TMDBService
|
||||||
kpService *KinopoiskService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMovieService(db *mongo.Database, tmdb *TMDBService, kpService *KinopoiskService) *MovieService {
|
func NewMovieService(db *mongo.Database, tmdb *TMDBService) *MovieService {
|
||||||
return &MovieService{
|
return &MovieService{
|
||||||
tmdb: tmdb,
|
tmdb: tmdb,
|
||||||
kpService: kpService,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MovieService) Search(query string, page int, language, region string, year int) (*models.TMDBResponse, error) {
|
func (s *MovieService) Search(query string, page int, language, region string, year int) (*models.TMDBResponse, error) {
|
||||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
|
||||||
kpSearch, err := s.kpService.SearchFilms(query, page)
|
|
||||||
if err == nil {
|
|
||||||
return MapKPSearchToTMDBResponse(kpSearch), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.tmdb.SearchMovies(query, page, language, region, year)
|
return s.tmdb.SearchMovies(query, page, language, region, year)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MovieService) GetByID(id int, language string, idType string) (*models.Movie, error) {
|
func (s *MovieService) GetByID(id int, language string) (*models.Movie, error) {
|
||||||
// Строго уважаем явный id_type, без скрытого fallback на TMDB
|
|
||||||
switch idType {
|
|
||||||
case "kp":
|
|
||||||
if s.kpService == nil {
|
|
||||||
return nil, fmt.Errorf("kinopoisk service not configured")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Сначала пробуем как Kinopoisk ID
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil {
|
|
||||||
return MapKPFilmToTMDBMovie(kpFilm), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Возможно пришел TMDB ID — пробуем конвертировать TMDB -> KP
|
|
||||||
if kpId, convErr := TmdbIdToKPId(s.tmdb, s.kpService, id); convErr == nil {
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(kpId); err == nil {
|
|
||||||
return MapKPFilmToTMDBMovie(kpFilm), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Явно указан KP, но ничего не нашли — возвращаем ошибку
|
|
||||||
return nil, fmt.Errorf("film not found in Kinopoisk with id %d", id)
|
|
||||||
|
|
||||||
case "tmdb":
|
|
||||||
return s.tmdb.GetMovie(id, language)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Если id_type не указан — старая логика по языку
|
|
||||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil {
|
|
||||||
return MapKPFilmToTMDBMovie(kpFilm), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.tmdb.GetMovie(id, language)
|
return s.tmdb.GetMovie(id, language)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MovieService) GetPopular(page int, language, region string) (*models.TMDBResponse, error) {
|
func (s *MovieService) GetPopular(page int, language, region string) (*models.TMDBResponse, error) {
|
||||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
|
||||||
kpTop, err := s.kpService.GetTopFilms("TOP_100_POPULAR_FILMS", page)
|
|
||||||
if err == nil {
|
|
||||||
return MapKPSearchToTMDBResponse(kpTop), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.tmdb.GetPopularMovies(page, language, region)
|
return s.tmdb.GetPopularMovies(page, language, region)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MovieService) GetTopRated(page int, language, region string) (*models.TMDBResponse, error) {
|
func (s *MovieService) GetTopRated(page int, language, region string) (*models.TMDBResponse, error) {
|
||||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
|
||||||
kpTop, err := s.kpService.GetTopFilms("TOP_250_BEST_FILMS", page)
|
|
||||||
if err == nil {
|
|
||||||
return MapKPSearchToTMDBResponse(kpTop), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.tmdb.GetTopRatedMovies(page, language, region)
|
return s.tmdb.GetTopRatedMovies(page, language, region)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,26 +49,5 @@ func (s *MovieService) GetSimilar(id, page int, language string) (*models.TMDBRe
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *MovieService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
|
func (s *MovieService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
|
||||||
if s.kpService != nil {
|
return s.tmdb.GetMovieExternalIDs(id)
|
||||||
kpFilm, err := s.kpService.GetFilmByKinopoiskId(id)
|
|
||||||
if err == nil && kpFilm != nil {
|
|
||||||
externalIDs := MapKPExternalIDsToTMDB(kpFilm)
|
|
||||||
externalIDs.ID = id
|
|
||||||
return externalIDs, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tmdbIDs, err := s.tmdb.GetMovieExternalIDs(id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.kpService != nil && tmdbIDs.IMDbID != "" {
|
|
||||||
kpFilm, err := s.kpService.GetFilmByImdbId(tmdbIDs.IMDbID)
|
|
||||||
if err == nil && kpFilm != nil {
|
|
||||||
tmdbIDs.KinopoiskID = kpFilm.KinopoiskId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return tmdbIDs, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
)
|
)
|
||||||
@@ -180,80 +179,6 @@ func (s *TMDBService) GetTVShow(id int, language string) (*models.TVShow, error)
|
|||||||
return &tvShow, err
|
return &tvShow, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map TMDB movie to unified content with prefixed IDs. Requires optional external IDs for imdbId.
|
|
||||||
func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *models.UnifiedContent {
|
|
||||||
if movie == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
genres := make([]models.UnifiedGenre, 0, len(movie.Genres))
|
|
||||||
for _, g := range movie.Genres {
|
|
||||||
name := strings.TrimSpace(g.Name)
|
|
||||||
id := strings.ToLower(strings.ReplaceAll(name, " ", "-"))
|
|
||||||
if id == "" {
|
|
||||||
id = strconv.Itoa(g.ID)
|
|
||||||
}
|
|
||||||
genres = append(genres, models.UnifiedGenre{ID: id, Name: name})
|
|
||||||
}
|
|
||||||
|
|
||||||
var imdb string
|
|
||||||
if external != nil {
|
|
||||||
imdb = external.IMDbID
|
|
||||||
}
|
|
||||||
|
|
||||||
var budgetPtr *int64
|
|
||||||
if movie.Budget > 0 {
|
|
||||||
v := movie.Budget
|
|
||||||
budgetPtr = &v
|
|
||||||
}
|
|
||||||
|
|
||||||
var revenuePtr *int64
|
|
||||||
if movie.Revenue > 0 {
|
|
||||||
v := movie.Revenue
|
|
||||||
revenuePtr = &v
|
|
||||||
}
|
|
||||||
|
|
||||||
ext := models.UnifiedExternalIDs{
|
|
||||||
KP: nil,
|
|
||||||
TMDB: &movie.ID,
|
|
||||||
IMDb: imdb,
|
|
||||||
}
|
|
||||||
|
|
||||||
return &models.UnifiedContent{
|
|
||||||
ID: strconv.Itoa(movie.ID),
|
|
||||||
SourceID: "tmdb_" + strconv.Itoa(movie.ID),
|
|
||||||
Title: movie.Title,
|
|
||||||
OriginalTitle: movie.OriginalTitle,
|
|
||||||
Description: movie.Overview,
|
|
||||||
ReleaseDate: movie.ReleaseDate,
|
|
||||||
EndDate: nil,
|
|
||||||
Type: "movie",
|
|
||||||
Genres: genres,
|
|
||||||
Rating: movie.VoteAverage,
|
|
||||||
PosterURL: movie.PosterPath,
|
|
||||||
BackdropURL: movie.BackdropPath,
|
|
||||||
Director: "",
|
|
||||||
Cast: []models.UnifiedCastMember{},
|
|
||||||
Duration: movie.Runtime,
|
|
||||||
Country: firstCountry(movie.ProductionCountries),
|
|
||||||
Language: movie.OriginalLanguage,
|
|
||||||
Budget: budgetPtr,
|
|
||||||
Revenue: revenuePtr,
|
|
||||||
IMDbID: imdb,
|
|
||||||
ExternalIDs: ext,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func firstCountry(countries []models.ProductionCountry) string {
|
|
||||||
if len(countries) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(countries[0].Name) != "" {
|
|
||||||
return countries[0].Name
|
|
||||||
}
|
|
||||||
return countries[0].ISO31661
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TMDBService) GetGenres(mediaType string, language string) (*models.GenresResponse, error) {
|
func (s *TMDBService) GetGenres(mediaType string, language string) (*models.GenresResponse, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package services
|
package services
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
@@ -10,14 +9,12 @@ import (
|
|||||||
type TVService struct {
|
type TVService struct {
|
||||||
db *mongo.Database
|
db *mongo.Database
|
||||||
tmdb *TMDBService
|
tmdb *TMDBService
|
||||||
kpService *KinopoiskService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTVService(db *mongo.Database, tmdb *TMDBService, kpService *KinopoiskService) *TVService {
|
func NewTVService(db *mongo.Database, tmdb *TMDBService) *TVService {
|
||||||
return &TVService{
|
return &TVService{
|
||||||
db: db,
|
db: db,
|
||||||
tmdb: tmdb,
|
tmdb: tmdb,
|
||||||
kpService: kpService,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,39 +22,7 @@ func (s *TVService) Search(query string, page int, language string, year int) (*
|
|||||||
return s.tmdb.SearchTVShows(query, page, language, year)
|
return s.tmdb.SearchTVShows(query, page, language, year)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *TVService) GetByID(id int, language string, idType string) (*models.TVShow, error) {
|
func (s *TVService) GetByID(id int, language string) (*models.TVShow, error) {
|
||||||
// Строго уважаем явный id_type, без скрытого fallback на TMDB
|
|
||||||
switch idType {
|
|
||||||
case "kp":
|
|
||||||
if s.kpService == nil {
|
|
||||||
return nil, fmt.Errorf("kinopoisk service not configured")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Сначала пробуем как Kinopoisk ID
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil && kpFilm != nil {
|
|
||||||
return MapKPFilmToTVShow(kpFilm), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Возможно пришел TMDB ID — пробуем конвертировать TMDB -> KP
|
|
||||||
if kpId, convErr := TmdbIdToKPId(s.tmdb, s.kpService, id); convErr == nil {
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(kpId); err == nil && kpFilm != nil {
|
|
||||||
return MapKPFilmToTVShow(kpFilm), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Явно указан KP, но ничего не нашли — возвращаем ошибку
|
|
||||||
return nil, fmt.Errorf("TV show not found in Kinopoisk with id %d", id)
|
|
||||||
|
|
||||||
case "tmdb":
|
|
||||||
return s.tmdb.GetTVShow(id, language)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Если id_type не указан — старая логика по языку
|
|
||||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
|
||||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil && kpFilm != nil {
|
|
||||||
return MapKPFilmToTVShow(kpFilm), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.tmdb.GetTVShow(id, language)
|
return s.tmdb.GetTVShow(id, language)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user