mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-28 01:48:51 +05:00
Compare commits
98 Commits
main
...
567b287322
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
567b287322 | ||
|
|
03091b0fc3 | ||
|
|
42d38ba0d1 | ||
|
|
859a7fd380 | ||
|
|
303079740f | ||
|
|
39c8366ae1 | ||
|
|
d47b4fd0a8 | ||
|
|
0d54aacc7d | ||
|
|
4e88529e0a | ||
|
|
0bd3a8860f | ||
|
|
5e761dbbc6 | ||
|
|
5d422231ca | ||
|
|
b467b7ed1c | ||
|
|
b76e8f685d | ||
|
|
3be73ad264 | ||
|
|
c170b2c7fa | ||
|
|
52d7e48bdb | ||
|
|
d4e29a8093 | ||
|
|
6ee4b8cc58 | ||
|
|
b20edae256 | ||
|
|
d29dce0afc | ||
|
|
39eea67323 | ||
|
|
bd853e7f89 | ||
|
|
4e6e447e79 | ||
| e734e462c4 | |||
| c183861491 | |||
|
|
63b11eb2ad | ||
|
|
321694df9c | ||
| a31cdf0f75 | |||
| dfcd9db295 | |||
| 59334da140 | |||
| 04583418a1 | |||
| 42073ea7b4 | |||
| a2e015aa53 | |||
| 552e60440c | |||
| fcb6caf1b9 | |||
| bb64b2dde4 | |||
| 86034c8e12 | |||
| f3c1cab796 | |||
| d790eb7903 | |||
| d347c6003a | |||
| c8cf79d764 | |||
| 206aa770b6 | |||
| 9db1ee3f50 | |||
| 171a2bf3ed | |||
| 486bbf5475 | |||
| 12ed40f3d4 | |||
| 53d70c9262 | |||
| 7f6ff5f660 | |||
| 4a9a7febec | |||
| 66cd0d3b21 | |||
| 92b936f057 | |||
| 9cd3d45327 | |||
| efcc5cd2b9 | |||
| a575b5c5bf | |||
| 51af31a6d5 | |||
| 0b2dc6b2f4 | |||
| cc463c4d7c | |||
| 94968f3cd1 | |||
| dff5e963ab | |||
| cf5dfc7e54 | |||
| 1005f30285 | |||
| ea3c208292 | |||
| 5ce5da39bb | |||
| 58a32d8838 | |||
| 770ecef6d5 | |||
| 37040dd7ec | |||
| 7aa0307e25 | |||
| d961393562 | |||
| e1e2b4f92b | |||
| 6b063f4c70 | |||
| 95910e0710 | |||
| 02dedbb8f7 | |||
| 6bf00451fa | |||
| 600de04561 | |||
| 7a83bf2e27 | |||
| 1fd522872d | |||
| 0f751cced0 | |||
| 4cb06cbde5 | |||
| 4f23e979d5 | |||
| c25d4e5d87 | |||
| 5361894af1 | |||
| a5eb03aea8 | |||
| a04b4f7c12 | |||
| 3a86c14129 | |||
| 498bc41c1b | |||
| 4d73fc9d8c | |||
| 2d25162b1c | |||
| af5957b4f9 | |||
| a724bf0484 | |||
| 8b11f89347 | |||
| 0c1cfb1ac5 | |||
| 868e71991c | |||
| 5f859eebb8 | |||
| 3a6ac8db4b | |||
| 60c574849b | |||
| 037ab7a458 | |||
| 9d60080116 |
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
|
TMDB_ACCESS_TOKEN=
|
||||||
|
JWT_SECRET=
|
||||||
KPAPI_KEY=your_kp_api_key
|
|
||||||
KPAPI_BASE_URL=https://kinopoiskapiunofficial.tech/api
|
|
||||||
|
|
||||||
HDVB_TOKEN=your_hdvb_token
|
|
||||||
|
|
||||||
VIBIX_HOST=https://vibix.org
|
|
||||||
VIBIX_TOKEN=your_vibix_token
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
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
|
||||||
192
README.md
192
README.md
@@ -1,17 +1,16 @@
|
|||||||
# Neo Movies API (Unified)
|
# Neo Movies API
|
||||||
|
|
||||||
REST API для поиска и получения информации о фильмах, использующий TMDB API.
|
REST API для поиска и получения информации о фильмах, использующий TMDB API.
|
||||||
|
|
||||||
## Особенности
|
## Особенности
|
||||||
|
|
||||||
- Интеграция с Kinopoisk API для русского контента
|
- Поиск фильмов
|
||||||
- Автоматическое переключение между TMDB и Kinopoisk
|
|
||||||
- Поиск фильмов и сериалов
|
|
||||||
- Информация о фильмах
|
- Информация о фильмах
|
||||||
- Популярные, топ-рейтинговые, предстоящие фильмы
|
- Популярные фильмы
|
||||||
- Поддержка русских плееров (Alloha, Lumex, Vibix, HDVB)
|
- Топ рейтинговые фильмы
|
||||||
|
- Предстоящие фильмы
|
||||||
- Swagger документация
|
- Swagger документация
|
||||||
- Полная поддержка русского языка
|
- Поддержка русского языка
|
||||||
|
|
||||||
## 🛠 Быстрый старт
|
## 🛠 Быстрый старт
|
||||||
|
|
||||||
@@ -51,45 +50,38 @@ 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
|
||||||
```
|
```
|
||||||
|
|
||||||
## 📋 API Endpoints
|
## 📋 API Endpoints
|
||||||
|
|
||||||
### 🔓 Публичные маршруты (старые)
|
### 🔓 Публичные маршруты
|
||||||
|
|
||||||
```http
|
```http
|
||||||
# Система
|
# Система
|
||||||
@@ -114,7 +106,7 @@ GET /api/v1/movies/popular # Популярные
|
|||||||
GET /api/v1/movies/top-rated # Топ-рейтинговые
|
GET /api/v1/movies/top-rated # Топ-рейтинговые
|
||||||
GET /api/v1/movies/upcoming # Предстоящие
|
GET /api/v1/movies/upcoming # Предстоящие
|
||||||
GET /api/v1/movies/now-playing # В прокате
|
GET /api/v1/movies/now-playing # В прокате
|
||||||
GET /api/v1/movies/{id} # Детали фильма (устар.)
|
GET /api/v1/movies/{id} # Детали фильма
|
||||||
GET /api/v1/movies/{id}/recommendations # Рекомендации
|
GET /api/v1/movies/{id}/recommendations # Рекомендации
|
||||||
GET /api/v1/movies/{id}/similar # Похожие
|
GET /api/v1/movies/{id}/similar # Похожие
|
||||||
|
|
||||||
@@ -124,97 +116,14 @@ GET /api/v1/tv/popular # Популярные
|
|||||||
GET /api/v1/tv/top-rated # Топ-рейтинговые
|
GET /api/v1/tv/top-rated # Топ-рейтинговые
|
||||||
GET /api/v1/tv/on-the-air # В эфире
|
GET /api/v1/tv/on-the-air # В эфире
|
||||||
GET /api/v1/tv/airing-today # Сегодня в эфире
|
GET /api/v1/tv/airing-today # Сегодня в эфире
|
||||||
GET /api/v1/tv/{id} # Детали сериала (устар.)
|
GET /api/v1/tv/{id} # Детали сериала
|
||||||
### 🔓 Публичные маршруты (унифицированные)
|
|
||||||
|
|
||||||
```http
|
|
||||||
# Единый формат ID: SOURCE_ID = kp_123 | tmdb_456
|
|
||||||
GET /api/v1/movie/{SOURCE_ID} # Детали фильма (унифицированный ответ)
|
|
||||||
GET /api/v1/tv/{SOURCE_ID} # Детали сериала (унифицированный ответ, с seasons[])
|
|
||||||
GET /api/v1/search?query=...&source=kp|tmdb # Мультипоиск (унифицированные элементы)
|
|
||||||
```
|
|
||||||
|
|
||||||
Примеры:
|
|
||||||
|
|
||||||
```http
|
|
||||||
GET /api/v1/movie/tmdb_550
|
|
||||||
GET /api/v1/movie/kp_666
|
|
||||||
GET /api/v1/tv/tmdb_1399
|
|
||||||
GET /api/v1/search?query=matrix&source=tmdb
|
|
||||||
```
|
|
||||||
|
|
||||||
Схема ответа см. раздел «Unified responses» ниже.
|
|
||||||
|
|
||||||
## Unified responses
|
|
||||||
|
|
||||||
Пример карточки:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true,
|
|
||||||
"data": {
|
|
||||||
"id": "550",
|
|
||||||
"sourceId": "tmdb_550",
|
|
||||||
"title": "Fight Club",
|
|
||||||
"originalTitle": "Fight Club",
|
|
||||||
"description": "…",
|
|
||||||
"releaseDate": "1999-10-15",
|
|
||||||
"endDate": null,
|
|
||||||
"type": "movie",
|
|
||||||
"genres": [{ "id": "drama", "name": "Drama" }],
|
|
||||||
"rating": 8.8,
|
|
||||||
"posterUrl": "https://image.tmdb.org/t/p/w500/...jpg",
|
|
||||||
"backdropUrl": "https://image.tmdb.org/t/p/w1280/...jpg",
|
|
||||||
"director": "",
|
|
||||||
"cast": [],
|
|
||||||
"duration": 139,
|
|
||||||
"country": "US",
|
|
||||||
"language": "en",
|
|
||||||
"budget": 63000000,
|
|
||||||
"revenue": 100853753,
|
|
||||||
"imdbId": "0137523",
|
|
||||||
"externalIds": { "kp": null, "tmdb": 550, "imdb": "0137523" },
|
|
||||||
"seasons": []
|
|
||||||
},
|
|
||||||
"source": "tmdb",
|
|
||||||
"metadata": { "fetchedAt": "...", "apiVersion": "3.0", "responseTime": 12 }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Пример мультипоиска:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true,
|
|
||||||
"data": [
|
|
||||||
{
|
|
||||||
"id": "550",
|
|
||||||
"sourceId": "tmdb_550",
|
|
||||||
"title": "Fight Club",
|
|
||||||
"type": "movie",
|
|
||||||
"releaseDate": "1999-10-15",
|
|
||||||
"posterUrl": "https://image.tmdb.org/t/p/w500/...jpg",
|
|
||||||
"rating": 8.8,
|
|
||||||
"description": "…",
|
|
||||||
"externalIds": { "kp": null, "tmdb": 550, "imdb": "" }
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"source": "tmdb",
|
|
||||||
"pagination": { "page": 1, "totalPages": 5, "totalResults": 42, "pageSize": 20 },
|
|
||||||
"metadata": { "fetchedAt": "...", "apiVersion": "3.0", "responseTime": 20, "query": "fight" }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
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} # Поиск торрентов
|
||||||
@@ -278,15 +187,18 @@ curl -X POST https://api.neomovies.ru/api/v1/auth/login \
|
|||||||
}'
|
}'
|
||||||
```
|
```
|
||||||
|
|
||||||
### Поиск (унифицированный)
|
### Поиск фильмов
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Мультипоиск (источник обязателен)
|
# Поиск фильмов
|
||||||
curl "https://api.neomovies.ru/api/v1/search?query=matrix&source=tmdb&page=1"
|
curl "https://api.neomovies.ru/api/v1/movies/search?query=marvel&page=1"
|
||||||
|
|
||||||
# Детали по униф. ID
|
# Детали фильма
|
||||||
curl "https://api.neomovies.ru/api/v1/movie/tmdb_550"
|
curl "https://api.neomovies.ru/api/v1/movies/550"
|
||||||
curl "https://api.neomovies.ru/api/v1/tv/kp_61365"
|
|
||||||
|
# Добавить в избранное (с JWT токеном)
|
||||||
|
curl -X POST https://api.neomovies.ru/api/v1/favorites/550 \
|
||||||
|
-H "Authorization: Bearer YOUR_JWT_TOKEN"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Поиск торрентов
|
### Поиск торрентов
|
||||||
@@ -331,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 версией:
|
||||||
|
|||||||
24
api/index.go
24
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,9 +66,8 @@ 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)
|
||||||
unifiedHandler := handlersPkg.NewUnifiedHandler(tmdbService, kpService)
|
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
|
||||||
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
|
||||||
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
|
||||||
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
reactionsHandler := handlersPkg.NewReactionsHandler(reactionsService)
|
reactionsHandler := handlersPkg.NewReactionsHandler(reactionsService)
|
||||||
@@ -96,11 +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/alloha/meta/kp/{kp_id}", playersHandler.GetAllohaMetaByKP).Methods("GET")
|
api.HandleFunc("/players/lumex/{imdb_id}", playersHandler.GetLumexPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/lumex/{id_type}/{id}", playersHandler.GetLumexPlayer).Methods("GET")
|
api.HandleFunc("/players/vibix/{imdb_id}", playersHandler.GetVibixPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vibix/{id_type}/{id}", playersHandler.GetVibixPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/hdvb/{id_type}/{id}", playersHandler.GetHDVBPlayer).Methods("GET")
|
|
||||||
api.HandleFunc("/players/vidsrc/{media_type}/{imdb_id}", playersHandler.GetVidsrcPlayer).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/movie/{imdb_id}", playersHandler.GetVidlinkMoviePlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vidlink/tv/{tmdb_id}", playersHandler.GetVidlinkTVPlayer).Methods("GET")
|
api.HandleFunc("/players/vidlink/tv/{tmdb_id}", playersHandler.GetVidlinkTVPlayer).Methods("GET")
|
||||||
@@ -125,11 +121,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
|
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
|
||||||
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
|
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
|
||||||
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).Methods("GET")
|
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}", movieHandler.GetByID).Methods("GET")
|
api.HandleFunc("/movies/{id}", movieHandler.GetByID).Methods("GET")
|
||||||
// Unified prefixed routes
|
|
||||||
api.HandleFunc("/movie/{id}", unifiedHandler.GetMovie).Methods("GET")
|
|
||||||
api.HandleFunc("/tv/{id}", unifiedHandler.GetTV).Methods("GET")
|
|
||||||
api.HandleFunc("/search", unifiedHandler.Search).Methods("GET")
|
|
||||||
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
|
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
|
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")
|
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")
|
||||||
|
|||||||
23
main.go
23
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,9 +46,8 @@ 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)
|
||||||
unifiedHandler := appHandlers.NewUnifiedHandler(tmdbService, kpService)
|
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
|
||||||
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService).WithKinopoisk(kpService)
|
|
||||||
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
playersHandler := appHandlers.NewPlayersHandler(cfg)
|
||||||
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
|
||||||
reactionsHandler := appHandlers.NewReactionsHandler(reactionsService)
|
reactionsHandler := appHandlers.NewReactionsHandler(reactionsService)
|
||||||
@@ -77,13 +75,12 @@ 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/vidsrc/{media_type}/{imdb_id}", playersHandler.GetVidsrcPlayer).Methods("GET")
|
||||||
api.HandleFunc("/players/vidlink/movie/{imdb_id}", playersHandler.GetVidlinkMoviePlayer).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/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")
|
||||||
@@ -101,11 +98,7 @@ func main() {
|
|||||||
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
|
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
|
||||||
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
|
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
|
||||||
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).Methods("GET")
|
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}", movieHandler.GetByID).Methods("GET")
|
api.HandleFunc("/movies/{id}", movieHandler.GetByID).Methods("GET")
|
||||||
// Unified prefixed routes
|
|
||||||
api.HandleFunc("/movie/{id}", unifiedHandler.GetMovie).Methods("GET")
|
|
||||||
api.HandleFunc("/tv/{id}", unifiedHandler.GetTV).Methods("GET")
|
|
||||||
api.HandleFunc("/search", unifiedHandler.Search).Methods("GET")
|
|
||||||
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
|
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
|
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
|
||||||
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")
|
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")
|
||||||
|
|||||||
15
netlify.toml
15
netlify.toml
@@ -1,15 +0,0 @@
|
|||||||
[build]
|
|
||||||
functions = "netlify/functions"
|
|
||||||
|
|
||||||
[build.environment]
|
|
||||||
GO_VERSION = "1.22.6"
|
|
||||||
|
|
||||||
# Optional: include static assets used by handlers (placeholders, etc.)
|
|
||||||
[functions]
|
|
||||||
included_files = ["assets/**", "public/**", "static/**"]
|
|
||||||
|
|
||||||
# Route all API requests to the serverless function "api"
|
|
||||||
[[redirects]]
|
|
||||||
from = "/api/*"
|
|
||||||
to = "/.netlify/functions/api/:splat"
|
|
||||||
status = 200
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
bridge "github.com/vercel/go-bridge/go/bridge"
|
|
||||||
handler "neomovies-api/api"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
bridge.Start(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
handler.Handler(w, r.WithContext(context.Background()))
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
@@ -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"
|
||||||
|
|||||||
@@ -12,18 +12,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type CategoriesHandler struct {
|
type CategoriesHandler struct {
|
||||||
tmdbService *services.TMDBService
|
tmdbService *services.TMDBService
|
||||||
kpService *services.KinopoiskService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCategoriesHandler(tmdbService *services.TMDBService) *CategoriesHandler {
|
func NewCategoriesHandler(tmdbService *services.TMDBService) *CategoriesHandler {
|
||||||
// Для совместимости, kpService может быть добавлен позже через setter при инициализации в main.go/api/index.go
|
return &CategoriesHandler{
|
||||||
return &CategoriesHandler{tmdbService: tmdbService}
|
tmdbService: tmdbService,
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *CategoriesHandler) WithKinopoisk(kp *services.KinopoiskService) *CategoriesHandler {
|
|
||||||
h.kpService = kp
|
|
||||||
return h
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Category struct {
|
type Category struct {
|
||||||
@@ -33,14 +28,14 @@ type Category struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *CategoriesHandler) GetCategories(w http.ResponseWriter, r *http.Request) {
|
func (h *CategoriesHandler) GetCategories(w http.ResponseWriter, r *http.Request) {
|
||||||
// Получаем все жанры
|
// Получаем все жанры
|
||||||
genresResponse, err := h.tmdbService.GetAllGenres()
|
genresResponse, err := h.tmdbService.GetAllGenres()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Преобразуем жанры в категории (пока TMDB). Для KP — можно замаппить фиксированный список
|
// Преобразуем жанры в категории
|
||||||
var categories []Category
|
var categories []Category
|
||||||
for _, genre := range genresResponse.Genres {
|
for _, genre := range genresResponse.Genres {
|
||||||
slug := generateSlug(genre.Name)
|
slug := generateSlug(genre.Name)
|
||||||
@@ -72,7 +67,7 @@ func (h *CategoriesHandler) GetMediaByCategory(w http.ResponseWriter, r *http.Re
|
|||||||
language = "ru-RU"
|
language = "ru-RU"
|
||||||
}
|
}
|
||||||
|
|
||||||
mediaType := r.URL.Query().Get("type")
|
mediaType := r.URL.Query().Get("type")
|
||||||
if mediaType == "" {
|
if mediaType == "" {
|
||||||
mediaType = "movie" // По умолчанию фильмы для обратной совместимости
|
mediaType = "movie" // По умолчанию фильмы для обратной совместимости
|
||||||
}
|
}
|
||||||
@@ -82,28 +77,16 @@ func (h *CategoriesHandler) GetMediaByCategory(w http.ResponseWriter, r *http.Re
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
source := r.URL.Query().Get("source") // "kp" | "tmdb"
|
var data interface{}
|
||||||
var data interface{}
|
var err2 error
|
||||||
var err2 error
|
|
||||||
|
|
||||||
if source == "kp" && h.kpService != nil {
|
if mediaType == "movie" {
|
||||||
// KP не имеет прямого discover по genre id TMDB — здесь можно реализовать маппинг slug->поисковый запрос
|
// Используем discover API для получения фильмов по жанру
|
||||||
// Для простоты: используем keyword поиск по имени категории (slug как ключевое слово)
|
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
||||||
// Получим человекочитаемое имя жанра из TMDB как приближение
|
} else {
|
||||||
if mediaType == "movie" {
|
// Используем discover API для получения сериалов по жанру
|
||||||
// Поиском KP (keyword) эмулируем категорию
|
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
||||||
data, err2 = h.kpService.SearchFilms(r.URL.Query().Get("name"), page)
|
}
|
||||||
} else {
|
|
||||||
// Для сериалов у KP: используем тот же поиск (KP выдаёт и сериалы в некоторых случаях)
|
|
||||||
data, err2 = h.kpService.SearchFilms(r.URL.Query().Get("name"), page)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if mediaType == "movie" {
|
|
||||||
data, err2 = h.tmdbService.DiscoverMoviesByGenre(categoryID, page, language)
|
|
||||||
} else {
|
|
||||||
data, err2 = h.tmdbService.DiscoverTVByGenre(categoryID, page, language)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err2 != nil {
|
if err2 != nil {
|
||||||
http.Error(w, err2.Error(), http.StatusInternalServerError)
|
http.Error(w, err2.Error(), http.StatusInternalServerError)
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,8 +153,8 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
OpenAPI: "3.0.0",
|
OpenAPI: "3.0.0",
|
||||||
Info: Info{
|
Info: Info{
|
||||||
Title: "Neo Movies API",
|
Title: "Neo Movies API",
|
||||||
Description: "Унифицированный API (TMDB/Kinopoisk) с префиксными ID (kp_*, tmdb_*) и единым форматом данных",
|
Description: "Современный API для поиска фильмов и сериалов с интеграцией TMDB и поддержкой авторизации",
|
||||||
Version: "3.0.0",
|
Version: "2.0.0",
|
||||||
Contact: Contact{
|
Contact: Contact{
|
||||||
Name: "API Support",
|
Name: "API Support",
|
||||||
URL: "https://github.com/your-username/neomovies-api-go",
|
URL: "https://github.com/your-username/neomovies-api-go",
|
||||||
@@ -194,10 +186,10 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"/api/v1/search": map[string]interface{}{
|
"/api/v1/search/multi": map[string]interface{}{
|
||||||
"get": map[string]interface{}{
|
"get": map[string]interface{}{
|
||||||
"summary": "Унифицированный поиск",
|
"summary": "Мультипоиск",
|
||||||
"description": "Поиск фильмов и сериалов в источниках TMDB или Kinopoisk",
|
"description": "Поиск фильмов, сериалов и актеров",
|
||||||
"tags": []string{"Search"},
|
"tags": []string{"Search"},
|
||||||
"parameters": []map[string]interface{}{
|
"parameters": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
@@ -207,13 +199,6 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
"schema": map[string]string{"type": "string"},
|
"schema": map[string]string{"type": "string"},
|
||||||
"description": "Поисковый запрос",
|
"description": "Поисковый запрос",
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "source",
|
|
||||||
"in": "query",
|
|
||||||
"required": true,
|
|
||||||
"schema": map[string]interface{}{"type": "string", "enum": []string{"kp", "tmdb"}},
|
|
||||||
"description": "Источник: kp или tmdb",
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "page",
|
"name": "page",
|
||||||
"in": "query",
|
"in": "query",
|
||||||
@@ -223,7 +208,7 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
|
|||||||
},
|
},
|
||||||
"responses": map[string]interface{}{
|
"responses": map[string]interface{}{
|
||||||
"200": map[string]interface{}{
|
"200": map[string]interface{}{
|
||||||
"description": "Результаты поиска (унифицированные)",
|
"description": "Результаты поиска",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
"neomovies-api/pkg/config"
|
"neomovies-api/pkg/config"
|
||||||
"neomovies-api/pkg/middleware"
|
"neomovies-api/pkg/middleware"
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
"neomovies-api/pkg/services"
|
"neomovies-api/pkg/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
type FavoritesHandler struct {
|
type FavoritesHandler struct {
|
||||||
@@ -178,8 +177,7 @@ func (h *FavoritesHandler) fetchMediaInfoRussian(mediaID, mediaType string) (*mo
|
|||||||
url = fmt.Sprintf("https://api.themoviedb.org/3/tv/%s?api_key=%s&language=ru-RU", mediaID, h.config.TMDBAccessToken)
|
url = fmt.Sprintf("https://api.themoviedb.org/3/tv/%s?api_key=%s&language=ru-RU", mediaID, h.config.TMDBAccessToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
client := &http.Client{Timeout: 6 * time.Second}
|
resp, err := http.Get(url)
|
||||||
resp, err := client.Get(url)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to fetch from TMDB: %w", err)
|
return nil, fmt.Errorf("failed to fetch from TMDB: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"os"
|
||||||
"os"
|
"path/filepath"
|
||||||
"path/filepath"
|
"strings"
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"neomovies-api/pkg/config"
|
"neomovies-api/pkg/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ImagesHandler struct{}
|
type ImagesHandler struct{}
|
||||||
@@ -28,13 +26,7 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Попробуем декодировать путь заранее (на фронте абсолютные URL передаются как encodeURIComponent)
|
if imagePath == "placeholder.jpg" {
|
||||||
decodedPath := imagePath
|
|
||||||
if dp, err := url.QueryUnescape(imagePath); err == nil {
|
|
||||||
decodedPath = dp
|
|
||||||
}
|
|
||||||
|
|
||||||
if imagePath == "placeholder.jpg" || decodedPath == "placeholder.jpg" {
|
|
||||||
h.servePlaceholder(w, r)
|
h.servePlaceholder(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -44,85 +36,14 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
|
|||||||
size = "original"
|
size = "original"
|
||||||
}
|
}
|
||||||
|
|
||||||
var imageURL string
|
imageURL := fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath)
|
||||||
// Нормализуем абсолютные ссылки вида "https:/..." → "https://...", а также "//..." → "https://..."
|
|
||||||
normalized := decodedPath
|
|
||||||
if strings.HasPrefix(normalized, "//") {
|
|
||||||
normalized = "https:" + normalized
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(normalized, "http:/") && !strings.HasPrefix(normalized, "http://") {
|
|
||||||
normalized = strings.Replace(normalized, "http:/", "http://", 1)
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(normalized, "https:/") && !strings.HasPrefix(normalized, "https://") {
|
|
||||||
normalized = strings.Replace(normalized, "https:/", "https://", 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(normalized, "http://") || strings.HasPrefix(normalized, "https://") {
|
resp, err := http.Get(imageURL)
|
||||||
// Проксируем внешний абсолютный URL (например, Kinopoisk)
|
|
||||||
imageURL = normalized
|
|
||||||
} else {
|
|
||||||
// TMDB относительный путь
|
|
||||||
imageURL = fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
client := &http.Client{Timeout: 12 * time.Second}
|
|
||||||
|
|
||||||
// Подготовим несколько вариантов заголовков для обхода ограничений источников
|
|
||||||
buildRequest := func(targetURL string, attempt int) (*http.Request, error) {
|
|
||||||
req, err := http.NewRequest("GET", targetURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
// Универсальные заголовки как у браузера
|
|
||||||
req.Header.Set("Accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8")
|
|
||||||
req.Header.Set("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7")
|
|
||||||
if ua := r.Header.Get("User-Agent"); ua != "" {
|
|
||||||
req.Header.Set("User-Agent", ua)
|
|
||||||
} else {
|
|
||||||
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0 Safari/537.36")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Настройка Referer: для Yandex/Kinopoisk ставим kinopoisk.ru, иначе — origin URL
|
|
||||||
parsed, _ := url.Parse(targetURL)
|
|
||||||
host := strings.ToLower(parsed.Host)
|
|
||||||
switch attempt {
|
|
||||||
case 0:
|
|
||||||
if strings.Contains(host, "kinopoisk") || strings.Contains(host, "yandex") {
|
|
||||||
req.Header.Set("Referer", "https://www.kinopoisk.ru/")
|
|
||||||
} else if parsed.Scheme != "" && parsed.Host != "" {
|
|
||||||
req.Header.Set("Referer", parsed.Scheme+"://"+parsed.Host+"/")
|
|
||||||
}
|
|
||||||
case 1:
|
|
||||||
// Без Referer
|
|
||||||
default:
|
|
||||||
// Оставляем как есть
|
|
||||||
}
|
|
||||||
|
|
||||||
return req, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// До 2-х попыток: с реферером источника и без реферера
|
|
||||||
var resp *http.Response
|
|
||||||
var err error
|
|
||||||
for attempt := 0; attempt < 2; attempt++ {
|
|
||||||
var req *http.Request
|
|
||||||
req, err = buildRequest(imageURL, attempt)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
resp, err = client.Do(req)
|
|
||||||
if err == nil && resp != nil && resp.StatusCode == http.StatusOK {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if resp != nil {
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.servePlaceholder(w, r)
|
h.servePlaceholder(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
h.servePlaceholder(w, r)
|
h.servePlaceholder(w, r)
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
@@ -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"])
|
||||||
|
if err != nil {
|
||||||
// Support formats: "123" (old), "kp_123", "tmdb_123"
|
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
|
||||||
source := ""
|
return
|
||||||
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 {
|
|
||||||
http.Error(w, "Invalid movie ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id = parsed
|
|
||||||
}
|
}
|
||||||
|
|
||||||
language := GetLanguage(r)
|
language := GetLanguage(r)
|
||||||
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
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"sort"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -31,23 +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 == "kinopoisk_id" { idType = "kp" }
|
log.Printf("Processing imdb_id: %s", imdbID)
|
||||||
if idType != "kp" && idType != "imdb" {
|
|
||||||
log.Printf("Error: invalid id_type: %s", idType)
|
|
||||||
http.Error(w, "id_type must be 'kp' (kinopoisk_id) 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")
|
||||||
@@ -55,12 +47,11 @@ 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)
|
||||||
|
|
||||||
client := &http.Client{Timeout: 8 * time.Second}
|
resp, err := http.Get(apiURL)
|
||||||
resp, err := client.Get(apiURL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error calling Alloha API: %v", err)
|
log.Printf("Error calling Alloha API: %v", err)
|
||||||
http.Error(w, "Failed to fetch from Alloha API", http.StatusInternalServerError)
|
http.Error(w, "Failed to fetch from Alloha API", http.StatusInternalServerError)
|
||||||
@@ -113,7 +104,7 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
|
|
||||||
// Используем iframe URL из API
|
// Используем iframe URL из API
|
||||||
iframeCode := allohaResponse.Data.Iframe
|
iframeCode := allohaResponse.Data.Iframe
|
||||||
|
|
||||||
// Если это не HTML код, а просто URL
|
// Если это не HTML код, а просто URL
|
||||||
var playerURL string
|
var playerURL string
|
||||||
if !strings.Contains(iframeCode, "<") {
|
if !strings.Contains(iframeCode, "<") {
|
||||||
@@ -138,167 +129,33 @@ 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)
|
||||||
}
|
|
||||||
|
|
||||||
// GetAllohaMetaByKP returns seasons/episodes meta for Alloha by kinopoisk_id
|
|
||||||
func (h *PlayersHandler) GetAllohaMetaByKP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
kpID := vars["kp_id"]
|
|
||||||
if strings.TrimSpace(kpID) == "" {
|
|
||||||
http.Error(w, "kp_id is required", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if h.config.AllohaToken == "" {
|
|
||||||
http.Error(w, "Server misconfiguration: ALLOHA_TOKEN missing", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&kp=%s", url.QueryEscape(h.config.AllohaToken), url.QueryEscape(kpID))
|
|
||||||
client := &http.Client{Timeout: 8 * time.Second}
|
|
||||||
resp, err := client.Get(apiURL)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to fetch from Alloha API", http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
http.Error(w, fmt.Sprintf("Alloha API error: %d", resp.StatusCode), http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to read Alloha response", http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Define only the parts we need (map-based structure as в примере)
|
|
||||||
var raw struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Data struct {
|
|
||||||
SeasonsCount int `json:"seasons_count"`
|
|
||||||
Seasons map[string]struct {
|
|
||||||
Season int `json:"season"`
|
|
||||||
Episodes map[string]struct {
|
|
||||||
Episode int `json:"episode"`
|
|
||||||
Translation map[string]struct {
|
|
||||||
Translation string `json:"translation"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
} `json:"translation"`
|
|
||||||
} `json:"episodes"`
|
|
||||||
} `json:"seasons"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(body, &raw); err != nil {
|
|
||||||
http.Error(w, "Invalid JSON from Alloha", http.StatusBadGateway)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type episodeMeta struct {
|
|
||||||
Episode int `json:"episode"`
|
|
||||||
Translations []string `json:"translations"`
|
|
||||||
}
|
|
||||||
type seasonMeta struct {
|
|
||||||
Season int `json:"season"`
|
|
||||||
Episodes []episodeMeta `json:"episodes"`
|
|
||||||
}
|
|
||||||
out := struct {
|
|
||||||
Success bool `json:"success"`
|
|
||||||
Seasons []seasonMeta `json:"seasons"`
|
|
||||||
}{Success: true, Seasons: make([]seasonMeta, 0)}
|
|
||||||
|
|
||||||
if raw.Status == "success" && len(raw.Data.Seasons) > 0 {
|
|
||||||
// sort seasons by numeric key
|
|
||||||
seasonKeys := make([]int, 0, len(raw.Data.Seasons))
|
|
||||||
for k := range raw.Data.Seasons {
|
|
||||||
if n, err := strconv.Atoi(strings.TrimSpace(k)); err == nil {
|
|
||||||
seasonKeys = append(seasonKeys, n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Ints(seasonKeys)
|
|
||||||
|
|
||||||
for _, sn := range seasonKeys {
|
|
||||||
s := raw.Data.Seasons[strconv.Itoa(sn)]
|
|
||||||
sm := seasonMeta{Season: sn}
|
|
||||||
|
|
||||||
// sort episodes by numeric key
|
|
||||||
epKeys := make([]int, 0, len(s.Episodes))
|
|
||||||
for ek := range s.Episodes {
|
|
||||||
if en, err := strconv.Atoi(strings.TrimSpace(ek)); err == nil {
|
|
||||||
epKeys = append(epKeys, en)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Ints(epKeys)
|
|
||||||
|
|
||||||
for _, en := range epKeys {
|
|
||||||
e := s.Episodes[strconv.Itoa(en)]
|
|
||||||
em := episodeMeta{Episode: en}
|
|
||||||
// collect translations
|
|
||||||
for _, tr := range e.Translation {
|
|
||||||
t := strings.TrimSpace(tr.Translation)
|
|
||||||
if t == "" {
|
|
||||||
t = strings.TrimSpace(tr.Name)
|
|
||||||
}
|
|
||||||
if t != "" {
|
|
||||||
em.Translations = append(em.Translations, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sm.Episodes = append(sm.Episodes, em)
|
|
||||||
}
|
|
||||||
|
|
||||||
out.Seasons = append(out.Seasons, sm)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_ = json.NewEncoder(w).Encode(out)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request) {
|
func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// Поддержка алиаса
|
log.Printf("Processing imdb_id: %s", imdbID)
|
||||||
if idType == "kinopoisk_id" { idType = "kp" }
|
|
||||||
if idType != "kp" && idType != "imdb" {
|
if h.config.LumexURL == "" {
|
||||||
log.Printf("Error: invalid id_type: %s", idType)
|
log.Printf("Error: LUMEX_URL is missing")
|
||||||
http.Error(w, "id_type must be 'kp' or 'imdb'", http.StatusBadRequest)
|
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Processing %s ID: %s", idType, id)
|
// Lumex использует только IMDb ID без season/episode
|
||||||
|
playerURL := fmt.Sprintf("%s?imdb_id=%s", h.config.LumexURL, imdbID)
|
||||||
if h.config.LumexURL == "" {
|
log.Printf("🔗 Lumex URL: %s", playerURL)
|
||||||
log.Printf("Error: LUMEX_URL is missing")
|
|
||||||
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Встраивание напрямую через p.lumex.cloud: <iframe src="//p.lumex.cloud/<code>?kp_id=...">
|
|
||||||
// Ожидается, что LUMEX_URL задаёт базу вида: https://p.lumex.cloud/<code>
|
|
||||||
var paramName string
|
|
||||||
if idType == "kp" {
|
|
||||||
paramName = "kp_id"
|
|
||||||
} else {
|
|
||||||
paramName = "imdb_id"
|
|
||||||
}
|
|
||||||
|
|
||||||
separator := "?"
|
|
||||||
if strings.Contains(h.config.LumexURL, "?") {
|
|
||||||
separator = "&"
|
|
||||||
}
|
|
||||||
playerURL := fmt.Sprintf("%s%s%s=%s", h.config.LumexURL, separator, paramName, url.QueryEscape(id))
|
|
||||||
log.Printf("Lumex URL: %s", playerURL)
|
|
||||||
|
|
||||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, playerURL)
|
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)
|
||||||
@@ -306,29 +163,23 @@ func (h *PlayersHandler) GetLumexPlayer(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 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")
|
||||||
@@ -341,14 +192,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)
|
||||||
@@ -359,7 +203,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}
|
||||||
@@ -415,7 +259,7 @@ func (h *PlayersHandler) GetVibixPlayer(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 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
|
||||||
@@ -619,16 +463,16 @@ func (h *PlayersHandler) GetStreamAPI(w http.ResponseWriter, r *http.Request) {
|
|||||||
// GetVidsrcPlayer handles Vidsrc.to player (uses IMDb ID for both movies and TV shows)
|
// GetVidsrcPlayer handles Vidsrc.to player (uses IMDb ID for both movies and TV shows)
|
||||||
func (h *PlayersHandler) GetVidsrcPlayer(w http.ResponseWriter, r *http.Request) {
|
func (h *PlayersHandler) GetVidsrcPlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetVidsrcPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetVidsrcPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
imdbId := vars["imdb_id"]
|
imdbId := vars["imdb_id"]
|
||||||
mediaType := vars["media_type"] // "movie" or "tv"
|
mediaType := vars["media_type"] // "movie" or "tv"
|
||||||
|
|
||||||
if imdbId == "" || mediaType == "" {
|
if imdbId == "" || mediaType == "" {
|
||||||
http.Error(w, "imdb_id and media_type are required", http.StatusBadRequest)
|
http.Error(w, "imdb_id and media_type are required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var playerURL string
|
var playerURL string
|
||||||
if mediaType == "movie" {
|
if mediaType == "movie" {
|
||||||
playerURL = fmt.Sprintf("https://vidsrc.to/embed/movie/%s", imdbId)
|
playerURL = fmt.Sprintf("https://vidsrc.to/embed/movie/%s", imdbId)
|
||||||
@@ -644,154 +488,72 @@ func (h *PlayersHandler) GetVidsrcPlayer(w http.ResponseWriter, r *http.Request)
|
|||||||
http.Error(w, "Invalid media_type. Use 'movie' or 'tv'", http.StatusBadRequest)
|
http.Error(w, "Invalid media_type. Use 'movie' or 'tv'", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Generated Vidsrc URL: %s", playerURL)
|
log.Printf("Generated Vidsrc URL: %s", playerURL)
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
// Используем общий шаблон с кастомными контролами
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidsrc Player")
|
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidsrc Player")
|
||||||
|
|
||||||
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 Vidsrc player for %s: %s", mediaType, imdbId)
|
log.Printf("Successfully served Vidsrc player for %s: %s", mediaType, imdbId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetVidlinkMoviePlayer handles vidlink.pro player for movies (uses IMDb ID)
|
// GetVidlinkMoviePlayer handles vidlink.pro player for movies (uses IMDb ID)
|
||||||
func (h *PlayersHandler) GetVidlinkMoviePlayer(w http.ResponseWriter, r *http.Request) {
|
func (h *PlayersHandler) GetVidlinkMoviePlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetVidlinkMoviePlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetVidlinkMoviePlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
imdbId := vars["imdb_id"]
|
imdbId := vars["imdb_id"]
|
||||||
|
|
||||||
if imdbId == "" {
|
if imdbId == "" {
|
||||||
http.Error(w, "imdb_id is required", http.StatusBadRequest)
|
http.Error(w, "imdb_id is required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
playerURL := fmt.Sprintf("https://vidlink.pro/movie/%s", imdbId)
|
playerURL := fmt.Sprintf("https://vidlink.pro/movie/%s", imdbId)
|
||||||
|
|
||||||
log.Printf("Generated Vidlink Movie URL: %s", playerURL)
|
log.Printf("Generated Vidlink Movie URL: %s", playerURL)
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
// Используем общий шаблон с кастомными контролами
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
||||||
|
|
||||||
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 Vidlink movie player: %s", imdbId)
|
log.Printf("Successfully served Vidlink movie player: %s", imdbId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetVidlinkTVPlayer handles vidlink.pro player for TV shows (uses TMDB ID)
|
// 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)
|
|
||||||
|
|
||||||
client := &http.Client{Timeout: 8 * time.Second}
|
|
||||||
resp, err := client.Get(apiURL)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error fetching HDVB data: %v", err)
|
|
||||||
http.Error(w, "Failed to fetch player data", http.StatusInternalServerError)
|
|
||||||
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) {
|
func (h *PlayersHandler) GetVidlinkTVPlayer(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Printf("GetVidlinkTVPlayer called: %s %s", r.Method, r.URL.Path)
|
log.Printf("GetVidlinkTVPlayer called: %s %s", r.Method, r.URL.Path)
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
tmdbId := vars["tmdb_id"]
|
tmdbId := vars["tmdb_id"]
|
||||||
|
|
||||||
if tmdbId == "" {
|
if tmdbId == "" {
|
||||||
http.Error(w, "tmdb_id is required", http.StatusBadRequest)
|
http.Error(w, "tmdb_id is required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
season := r.URL.Query().Get("season")
|
season := r.URL.Query().Get("season")
|
||||||
episode := r.URL.Query().Get("episode")
|
episode := r.URL.Query().Get("episode")
|
||||||
if season == "" || episode == "" {
|
if season == "" || episode == "" {
|
||||||
http.Error(w, "season and episode are required for TV shows", http.StatusBadRequest)
|
http.Error(w, "season and episode are required for TV shows", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
playerURL := fmt.Sprintf("https://vidlink.pro/tv/%s/%s/%s", tmdbId, season, episode)
|
playerURL := fmt.Sprintf("https://vidlink.pro/tv/%s/%s/%s", tmdbId, season, episode)
|
||||||
|
|
||||||
log.Printf("Generated Vidlink TV URL: %s", playerURL)
|
log.Printf("Generated Vidlink TV URL: %s", playerURL)
|
||||||
|
|
||||||
// Используем общий шаблон с кастомными контролами
|
// Используем общий шаблон с кастомными контролами
|
||||||
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
htmlDoc := getPlayerWithControlsHTML(playerURL, "Vidlink Player")
|
||||||
|
|
||||||
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 Vidlink TV player: %s S%sE%s", tmdbId, season, episode)
|
log.Printf("Successfully served Vidlink TV player: %s S%sE%s", tmdbId, season, episode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,60 +28,15 @@ func (h *SearchHandler) MultiSearch(w http.ResponseWriter, r *http.Request) {
|
|||||||
page := getIntQuery(r, "page", 1)
|
page := getIntQuery(r, "page", 1)
|
||||||
language := GetLanguage(r)
|
language := GetLanguage(r)
|
||||||
|
|
||||||
if services.ShouldUseKinopoisk(language) {
|
results, err := h.tmdbService.SearchMulti(query, page, language)
|
||||||
if h.kpService == nil {
|
if err != nil {
|
||||||
http.Error(w, "Kinopoisk service is not configured", http.StatusBadGateway)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
kpSearch, err := h.kpService.SearchFilms(query, page)
|
w.Header().Set("Content-Type", "application/json")
|
||||||
if err != nil {
|
json.NewEncoder(w).Encode(models.APIResponse{
|
||||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
Success: true,
|
||||||
return
|
Data: results,
|
||||||
}
|
})
|
||||||
|
|
||||||
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)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(models.APIResponse{
|
|
||||||
Success: true,
|
|
||||||
Data: results,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
@@ -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"])
|
||||||
|
if err != nil {
|
||||||
// Support formats: "123" (old), "kp_123", "tmdb_123"
|
http.Error(w, "Invalid TV show ID", http.StatusBadRequest)
|
||||||
source := ""
|
return
|
||||||
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 {
|
|
||||||
http.Error(w, "Invalid TV show ID", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id = parsed
|
|
||||||
}
|
}
|
||||||
|
|
||||||
language := GetLanguage(r)
|
language := GetLanguage(r)
|
||||||
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
|
||||||
|
|||||||
@@ -1,228 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
|
||||||
"neomovies-api/pkg/services"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UnifiedHandler struct {
|
|
||||||
tmdb *services.TMDBService
|
|
||||||
kp *services.KinopoiskService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUnifiedHandler(tmdb *services.TMDBService, kp *services.KinopoiskService) *UnifiedHandler {
|
|
||||||
return &UnifiedHandler{tmdb: tmdb, kp: kp}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse source ID of form "kp_123" or "tmdb_456"
|
|
||||||
func parseSourceID(raw string) (source string, id int, err error) {
|
|
||||||
parts := strings.SplitN(raw, "_", 2)
|
|
||||||
if len(parts) != 2 {
|
|
||||||
return "", 0, strconv.ErrSyntax
|
|
||||||
}
|
|
||||||
src := strings.ToLower(parts[0])
|
|
||||||
if src != "kp" && src != "tmdb" {
|
|
||||||
return "", 0, strconv.ErrSyntax
|
|
||||||
}
|
|
||||||
num, err := strconv.Atoi(parts[1])
|
|
||||||
if err != nil {
|
|
||||||
return "", 0, err
|
|
||||||
}
|
|
||||||
return src, num, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *UnifiedHandler) GetMovie(w http.ResponseWriter, r *http.Request) {
|
|
||||||
start := time.Now()
|
|
||||||
vars := muxVars(r)
|
|
||||||
rawID := vars["id"]
|
|
||||||
|
|
||||||
source, id, err := parseSourceID(rawID)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadRequest, "invalid SOURCE_ID format", start, "")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
language := GetLanguage(r)
|
|
||||||
var data *models.UnifiedContent
|
|
||||||
if source == "kp" {
|
|
||||||
if h.kp == nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, "Kinopoisk service not configured", start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
kpFilm, err := h.kp.GetFilmByKinopoiskId(id)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data = services.MapKPToUnified(kpFilm)
|
|
||||||
// Обогащаем только externalIds.tmdb через /find (берем только поле id)
|
|
||||||
if kpFilm.ImdbId != "" {
|
|
||||||
if tmdbID, fErr := h.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "movie", GetLanguage(r)); fErr == nil {
|
|
||||||
data.ExternalIDs.TMDB = &tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// tmdb
|
|
||||||
movie, err := h.tmdb.GetMovie(id, language)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ext, _ := h.tmdb.GetMovieExternalIDs(id)
|
|
||||||
data = services.MapTMDBToUnifiedMovie(movie, ext)
|
|
||||||
}
|
|
||||||
|
|
||||||
writeUnifiedOK(w, data, start, source, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *UnifiedHandler) GetTV(w http.ResponseWriter, r *http.Request) {
|
|
||||||
start := time.Now()
|
|
||||||
vars := muxVars(r)
|
|
||||||
rawID := vars["id"]
|
|
||||||
|
|
||||||
source, id, err := parseSourceID(rawID)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadRequest, "invalid SOURCE_ID format", start, "")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
language := GetLanguage(r)
|
|
||||||
var data *models.UnifiedContent
|
|
||||||
if source == "kp" {
|
|
||||||
if h.kp == nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, "Kinopoisk service not configured", start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
kpFilm, err := h.kp.GetFilmByKinopoiskId(id)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data = services.MapKPToUnified(kpFilm)
|
|
||||||
if kpFilm.ImdbId != "" {
|
|
||||||
if tmdbID, fErr := h.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "tv", GetLanguage(r)); fErr == nil {
|
|
||||||
data.ExternalIDs.TMDB = &tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tv, err := h.tmdb.GetTVShow(id, language)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ext, _ := h.tmdb.GetTVExternalIDs(id)
|
|
||||||
data = services.MapTMDBTVToUnified(tv, ext)
|
|
||||||
}
|
|
||||||
|
|
||||||
writeUnifiedOK(w, data, start, source, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *UnifiedHandler) Search(w http.ResponseWriter, r *http.Request) {
|
|
||||||
start := time.Now()
|
|
||||||
query := r.URL.Query().Get("query")
|
|
||||||
if strings.TrimSpace(query) == "" {
|
|
||||||
writeUnifiedError(w, http.StatusBadRequest, "query is required", start, "")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
source := strings.ToLower(r.URL.Query().Get("source")) // kp|tmdb
|
|
||||||
page := getIntQuery(r, "page", 1)
|
|
||||||
language := GetLanguage(r)
|
|
||||||
|
|
||||||
if source != "kp" && source != "tmdb" {
|
|
||||||
writeUnifiedError(w, http.StatusBadRequest, "source must be 'kp' or 'tmdb'", start, "")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if source == "kp" {
|
|
||||||
if h.kp == nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, "Kinopoisk service not configured", start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
kpSearch, err := h.kp.SearchFilms(query, page)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
items := services.MapKPSearchToUnifiedItems(kpSearch)
|
|
||||||
// Обогащаем результаты поиска TMDB ID через получение полной информации о фильмах
|
|
||||||
if h.tmdb != nil {
|
|
||||||
for i := range items {
|
|
||||||
if kpID, err := strconv.Atoi(items[i].ID); err == nil {
|
|
||||||
if kpFilm, err := h.kp.GetFilmByKinopoiskId(kpID); err == nil && kpFilm.ImdbId != "" {
|
|
||||||
items[i].ExternalIDs.IMDb = kpFilm.ImdbId
|
|
||||||
mediaType := "movie"
|
|
||||||
if items[i].Type == "tv" {
|
|
||||||
mediaType = "tv"
|
|
||||||
}
|
|
||||||
if tmdbID, err := h.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, mediaType, "ru-RU"); err == nil {
|
|
||||||
items[i].ExternalIDs.TMDB = &tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resp := models.UnifiedSearchResponse{
|
|
||||||
Success: true,
|
|
||||||
Data: items,
|
|
||||||
Source: source,
|
|
||||||
Pagination: models.UnifiedPagination{Page: page, TotalPages: kpSearch.PagesCount, TotalResults: kpSearch.SearchFilmsCountResult, PageSize: len(items)},
|
|
||||||
Metadata: models.UnifiedMetadata{FetchedAt: time.Now(), APIVersion: "3.0", ResponseTime: time.Since(start).Milliseconds(), Query: query},
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, resp)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// TMDB multi search
|
|
||||||
multi, err := h.tmdb.SearchMulti(query, page, language)
|
|
||||||
if err != nil {
|
|
||||||
writeUnifiedError(w, http.StatusBadGateway, err.Error(), start, source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
items := services.MapTMDBMultiToUnifiedItems(multi)
|
|
||||||
resp := models.UnifiedSearchResponse{
|
|
||||||
Success: true,
|
|
||||||
Data: items,
|
|
||||||
Source: source,
|
|
||||||
Pagination: models.UnifiedPagination{Page: multi.Page, TotalPages: multi.TotalPages, TotalResults: multi.TotalResults, PageSize: len(items)},
|
|
||||||
Metadata: models.UnifiedMetadata{FetchedAt: time.Now(), APIVersion: "3.0", ResponseTime: time.Since(start).Milliseconds(), Query: query},
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, resp)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeUnifiedOK(w http.ResponseWriter, data *models.UnifiedContent, start time.Time, source string, query string) {
|
|
||||||
resp := models.UnifiedAPIResponse{
|
|
||||||
Success: true,
|
|
||||||
Data: data,
|
|
||||||
Source: source,
|
|
||||||
Metadata: models.UnifiedMetadata{
|
|
||||||
FetchedAt: time.Now(),
|
|
||||||
APIVersion: "3.0",
|
|
||||||
ResponseTime: time.Since(start).Milliseconds(),
|
|
||||||
Query: query,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(resp)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeUnifiedError(w http.ResponseWriter, code int, message string, start time.Time, source string) {
|
|
||||||
resp := models.UnifiedAPIResponse{
|
|
||||||
Success: false,
|
|
||||||
Error: message,
|
|
||||||
Source: source,
|
|
||||||
Metadata: models.UnifiedMetadata{
|
|
||||||
FetchedAt: time.Now(),
|
|
||||||
APIVersion: "3.0",
|
|
||||||
ResponseTime: time.Since(start).Milliseconds(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(code)
|
|
||||||
json.NewEncoder(w).Encode(resp)
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
|
||||||
)
|
|
||||||
|
|
||||||
func muxVars(r *http.Request) map[string]string { return mux.Vars(r) }
|
|
||||||
|
|
||||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(status)
|
|
||||||
_ = json.NewEncoder(w).Encode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
type metaEnvelope struct {
|
|
||||||
FetchedAt time.Time `json:"fetchedAt"`
|
|
||||||
APIVersion string `json:"apiVersion"`
|
|
||||||
ResponseTime int64 `json:"responseTime"`
|
|
||||||
}
|
|
||||||
@@ -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,8 +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"`
|
|
||||||
TMDBID int `json:"tmdb_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,114 +0,0 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
// Unified entities and response envelopes for prefixed-source API
|
|
||||||
|
|
||||||
type UnifiedGenre struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedCastMember struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Character string `json:"character,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedExternalIDs struct {
|
|
||||||
KP *int `json:"kp"`
|
|
||||||
TMDB *int `json:"tmdb"`
|
|
||||||
IMDb string `json:"imdb"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedContent struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SourceID string `json:"sourceId"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
OriginalTitle string `json:"originalTitle"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
ReleaseDate string `json:"releaseDate"`
|
|
||||||
EndDate *string `json:"endDate"`
|
|
||||||
Type string `json:"type"` // movie | tv
|
|
||||||
Genres []UnifiedGenre `json:"genres"`
|
|
||||||
Rating float64 `json:"rating"`
|
|
||||||
PosterURL string `json:"posterUrl"`
|
|
||||||
BackdropURL string `json:"backdropUrl"`
|
|
||||||
Director string `json:"director"`
|
|
||||||
Cast []UnifiedCastMember `json:"cast"`
|
|
||||||
Duration int `json:"duration"`
|
|
||||||
Country string `json:"country"`
|
|
||||||
Language string `json:"language"`
|
|
||||||
Budget *int64 `json:"budget"`
|
|
||||||
Revenue *int64 `json:"revenue"`
|
|
||||||
IMDbID string `json:"imdbId"`
|
|
||||||
ExternalIDs UnifiedExternalIDs `json:"externalIds"`
|
|
||||||
// For TV shows
|
|
||||||
Seasons []UnifiedSeason `json:"seasons,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedSeason struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SourceID string `json:"sourceId"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
SeasonNumber int `json:"seasonNumber"`
|
|
||||||
EpisodeCount int `json:"episodeCount"`
|
|
||||||
ReleaseDate string `json:"releaseDate"`
|
|
||||||
PosterURL string `json:"posterUrl"`
|
|
||||||
Episodes []UnifiedEpisode `json:"episodes,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedEpisode struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SourceID string `json:"sourceId"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
EpisodeNumber int `json:"episodeNumber"`
|
|
||||||
SeasonNumber int `json:"seasonNumber"`
|
|
||||||
AirDate string `json:"airDate"`
|
|
||||||
Duration int `json:"duration"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
StillURL string `json:"stillUrl"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedSearchItem struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SourceID string `json:"sourceId"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
OriginalType string `json:"originalType,omitempty"`
|
|
||||||
ReleaseDate string `json:"releaseDate"`
|
|
||||||
PosterURL string `json:"posterUrl"`
|
|
||||||
Rating float64 `json:"rating"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
ExternalIDs UnifiedExternalIDs `json:"externalIds"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedPagination struct {
|
|
||||||
Page int `json:"page"`
|
|
||||||
TotalPages int `json:"totalPages"`
|
|
||||||
TotalResults int `json:"totalResults"`
|
|
||||||
PageSize int `json:"pageSize"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedMetadata struct {
|
|
||||||
FetchedAt time.Time `json:"fetchedAt"`
|
|
||||||
APIVersion string `json:"apiVersion"`
|
|
||||||
ResponseTime int64 `json:"responseTime"`
|
|
||||||
Query string `json:"query,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedAPIResponse struct {
|
|
||||||
Success bool `json:"success"`
|
|
||||||
Data interface{} `json:"data,omitempty"`
|
|
||||||
Error string `json:"error,omitempty"`
|
|
||||||
Source string `json:"source,omitempty"`
|
|
||||||
Metadata UnifiedMetadata `json:"metadata"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UnifiedSearchResponse struct {
|
|
||||||
Success bool `json:"success"`
|
|
||||||
Data []UnifiedSearchItem `json:"data"`
|
|
||||||
Source string `json:"source"`
|
|
||||||
Pagination UnifiedPagination `json:"pagination"`
|
|
||||||
Metadata UnifiedMetadata `json:"metadata"`
|
|
||||||
}
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"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, url.QueryEscape(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, url.QueryEscape(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,424 +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: BuildAPIImageProxyURL(poster, "w500"),
|
|
||||||
BackdropURL: BuildAPIImageProxyURL(kpFilm.CoverUrl, "w1280"),
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnrichKPWithTMDBID обогащает KP контент TMDB ID через IMDB ID
|
|
||||||
func EnrichKPWithTMDBID(content *models.UnifiedContent, tmdbService *TMDBService) {
|
|
||||||
if content == nil || content.IMDbID == "" || content.ExternalIDs.TMDB != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
mediaType := "movie"
|
|
||||||
if content.Type == "tv" {
|
|
||||||
mediaType = "tv"
|
|
||||||
}
|
|
||||||
|
|
||||||
if tmdbID, err := tmdbService.FindTMDBIdByIMDB(content.IMDbID, mediaType, "ru-RU"); err == nil {
|
|
||||||
content.ExternalIDs.TMDB = &tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnrichKPSearchItemsWithTMDBID обогащает массив поисковых элементов TMDB ID
|
|
||||||
func EnrichKPSearchItemsWithTMDBID(items []models.UnifiedSearchItem, tmdbService *TMDBService) {
|
|
||||||
for i := range items {
|
|
||||||
if items[i].ExternalIDs.IMDb == "" || items[i].ExternalIDs.TMDB != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
mediaType := "movie"
|
|
||||||
if items[i].Type == "tv" {
|
|
||||||
mediaType = "tv"
|
|
||||||
}
|
|
||||||
|
|
||||||
if tmdbID, err := tmdbService.FindTMDBIdByIMDB(items[i].ExternalIDs.IMDb, mediaType, "ru-RU"); err == nil {
|
|
||||||
items[i].ExternalIDs.TMDB = &tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,88 +1,34 @@
|
|||||||
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
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
|
return s.tmdb.GetMovie(id, language)
|
||||||
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 {
|
|
||||||
// Возвращаем KP-модель в TMDB-формате без подмены на TMDB объект
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,34 +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
|
|
||||||
|
|
||||||
// Пытаемся получить TMDB ID через IMDB ID
|
|
||||||
if kpFilm.ImdbId != "" && s.tmdb != nil {
|
|
||||||
if tmdbID, tmdbErr := s.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "movie", "ru-RU"); tmdbErr == nil {
|
|
||||||
externalIDs.TMDBID = tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
package services
|
package services
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
"neomovies-api/pkg/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TMDBService struct {
|
type TMDBService struct {
|
||||||
@@ -18,16 +17,11 @@ type TMDBService struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewTMDBService(accessToken string) *TMDBService {
|
func NewTMDBService(accessToken string) *TMDBService {
|
||||||
transport := &http.Transport{
|
return &TMDBService{
|
||||||
MaxIdleConns: 100,
|
accessToken: accessToken,
|
||||||
MaxIdleConnsPerHost: 10,
|
baseURL: "https://api.themoviedb.org/3",
|
||||||
IdleConnTimeout: 60 * time.Second,
|
client: &http.Client{},
|
||||||
}
|
}
|
||||||
return &TMDBService{
|
|
||||||
accessToken: accessToken,
|
|
||||||
baseURL: "https://api.themoviedb.org/3",
|
|
||||||
client: &http.Client{Timeout: 10 * time.Second, Transport: transport},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *TMDBService) makeRequest(endpoint string, target interface{}) error {
|
func (s *TMDBService) makeRequest(endpoint string, target interface{}) error {
|
||||||
@@ -185,56 +179,6 @@ func (s *TMDBService) GetTVShow(id int, language string) (*models.TVShow, error)
|
|||||||
return &tvShow, err
|
return &tvShow, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// FindTMDBIdByIMDB finds TMDB IDs by external IMDb ID using /find/{external_id}
|
|
||||||
// media: "movie" | "tv" | "" (auto)
|
|
||||||
func (s *TMDBService) FindTMDBIdByIMDB(imdbID string, media string, language string) (int, error) {
|
|
||||||
if imdbID == "" {
|
|
||||||
return 0, fmt.Errorf("imdb id is empty")
|
|
||||||
}
|
|
||||||
if language == "" {
|
|
||||||
language = "ru-RU"
|
|
||||||
}
|
|
||||||
params := url.Values{}
|
|
||||||
params.Set("external_source", "imdb_id")
|
|
||||||
params.Set("language", language)
|
|
||||||
endpoint := fmt.Sprintf("%s/find/%s?%s", s.baseURL, url.PathEscape(imdbID), params.Encode())
|
|
||||||
|
|
||||||
var resp struct {
|
|
||||||
MovieResults []struct{ ID int `json:"id"` } `json:"movie_results"`
|
|
||||||
TVResults []struct{ ID int `json:"id"` } `json:"tv_results"`
|
|
||||||
TVEpisodeResults []struct{ ShowID int `json:"show_id"` } `json:"tv_episode_results"`
|
|
||||||
TVSeasonResults []struct{ ShowID int `json:"show_id"` } `json:"tv_season_results"`
|
|
||||||
}
|
|
||||||
if err := s.makeRequest(endpoint, &resp); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch media {
|
|
||||||
case "movie":
|
|
||||||
if len(resp.MovieResults) > 0 {
|
|
||||||
return resp.MovieResults[0].ID, nil
|
|
||||||
}
|
|
||||||
case "tv":
|
|
||||||
if len(resp.TVResults) > 0 {
|
|
||||||
return resp.TVResults[0].ID, nil
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if len(resp.MovieResults) > 0 {
|
|
||||||
return resp.MovieResults[0].ID, nil
|
|
||||||
}
|
|
||||||
if len(resp.TVResults) > 0 {
|
|
||||||
return resp.TVResults[0].ID, nil
|
|
||||||
}
|
|
||||||
if len(resp.TVSeasonResults) > 0 {
|
|
||||||
return resp.TVSeasonResults[0].ShowID, nil
|
|
||||||
}
|
|
||||||
if len(resp.TVEpisodeResults) > 0 {
|
|
||||||
return resp.TVEpisodeResults[0].ShowID, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0, fmt.Errorf("tmdb id not found for imdb %s", imdbID)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,23 +1,20 @@
|
|||||||
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
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,55 +22,8 @@ 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
|
return s.tmdb.GetTVShow(id, language)
|
||||||
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 {
|
|
||||||
// Попробуем обогатить TMDB сериал через IMDb -> TMDB find
|
|
||||||
if kpFilm.ImdbId != "" {
|
|
||||||
if tmdbID, fErr := s.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "tv", NormalizeLanguage(language)); fErr == nil {
|
|
||||||
if tmdbTV, mErr := s.tmdb.GetTVShow(tmdbID, NormalizeLanguage(language)); mErr == nil {
|
|
||||||
return tmdbTV, 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 {
|
|
||||||
if kpFilm.ImdbId != "" {
|
|
||||||
if tmdbID, fErr := s.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "tv", NormalizeLanguage(language)); fErr == nil {
|
|
||||||
if tmdbTV, mErr := s.tmdb.GetTVShow(tmdbID, NormalizeLanguage(language)); mErr == nil {
|
|
||||||
return tmdbTV, 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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *TVService) GetPopular(page int, language string) (*models.TMDBTVResponse, error) {
|
func (s *TVService) GetPopular(page int, language string) (*models.TMDBTVResponse, error) {
|
||||||
@@ -101,34 +51,5 @@ func (s *TVService) GetSimilar(id, page int, language string) (*models.TMDBTVRes
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *TVService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
|
func (s *TVService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
|
||||||
if s.kpService != nil {
|
return s.tmdb.GetTVExternalIDs(id)
|
||||||
kpFilm, err := s.kpService.GetFilmByKinopoiskId(id)
|
|
||||||
if err == nil && kpFilm != nil {
|
|
||||||
externalIDs := MapKPExternalIDsToTMDB(kpFilm)
|
|
||||||
externalIDs.ID = id
|
|
||||||
|
|
||||||
// Пытаемся получить TMDB ID через IMDB ID
|
|
||||||
if kpFilm.ImdbId != "" && s.tmdb != nil {
|
|
||||||
if tmdbID, tmdbErr := s.tmdb.FindTMDBIdByIMDB(kpFilm.ImdbId, "tv", "ru-RU"); tmdbErr == nil {
|
|
||||||
externalIDs.TMDBID = tmdbID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return externalIDs, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tmdbIDs, err := s.tmdb.GetTVExternalIDs(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
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,275 +0,0 @@
|
|||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"neomovies-api/pkg/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
const tmdbImageBase = "https://image.tmdb.org/t/p"
|
|
||||||
|
|
||||||
// BuildAPIImageProxyURL строит относительный URL до нашего прокси-эндпоинта изображений.
|
|
||||||
// Если передан абсолютный URL (KP и пр.) — он кодируется и передаётся как path параметр.
|
|
||||||
// Если передан относительный TMDB-путь, он используется как есть (без ведущего '/').
|
|
||||||
func BuildAPIImageProxyURL(pathOrURL string, size string) string {
|
|
||||||
if strings.TrimSpace(pathOrURL) == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if size == "" {
|
|
||||||
size = "w500"
|
|
||||||
}
|
|
||||||
// Абсолютные ссылки (Kinopoisk и пр.) — кодируем целиком
|
|
||||||
if strings.HasPrefix(pathOrURL, "http://") || strings.HasPrefix(pathOrURL, "https://") {
|
|
||||||
return fmt.Sprintf("/api/v1/images/%s/%s", size, url.QueryEscape(pathOrURL))
|
|
||||||
}
|
|
||||||
// TMDB относительный путь
|
|
||||||
clean := pathOrURL
|
|
||||||
if strings.HasPrefix(clean, "/") {
|
|
||||||
clean = clean[1:]
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("/api/v1/images/%s/%s", size, clean)
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *models.UnifiedContent {
|
|
||||||
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: BuildAPIImageProxyURL(movie.PosterPath, "w500"),
|
|
||||||
BackdropURL: BuildAPIImageProxyURL(movie.BackdropPath, "w1280"),
|
|
||||||
Director: "",
|
|
||||||
Cast: []models.UnifiedCastMember{},
|
|
||||||
Duration: movie.Runtime,
|
|
||||||
Country: firstCountry(movie.ProductionCountries),
|
|
||||||
Language: movie.OriginalLanguage,
|
|
||||||
Budget: budgetPtr,
|
|
||||||
Revenue: revenuePtr,
|
|
||||||
IMDbID: imdb,
|
|
||||||
ExternalIDs: ext,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapTMDBTVToUnified(tv *models.TVShow, external *models.ExternalIDs) *models.UnifiedContent {
|
|
||||||
if tv == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
genres := make([]models.UnifiedGenre, 0, len(tv.Genres))
|
|
||||||
for _, g := range tv.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
|
|
||||||
}
|
|
||||||
|
|
||||||
endDate := (*string)(nil)
|
|
||||||
if strings.TrimSpace(tv.LastAirDate) != "" {
|
|
||||||
v := tv.LastAirDate
|
|
||||||
endDate = &v
|
|
||||||
}
|
|
||||||
|
|
||||||
ext := models.UnifiedExternalIDs{
|
|
||||||
KP: nil,
|
|
||||||
TMDB: &tv.ID,
|
|
||||||
IMDb: imdb,
|
|
||||||
}
|
|
||||||
|
|
||||||
duration := 0
|
|
||||||
if len(tv.EpisodeRunTime) > 0 {
|
|
||||||
duration = tv.EpisodeRunTime[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
unified := &models.UnifiedContent{
|
|
||||||
ID: strconv.Itoa(tv.ID),
|
|
||||||
SourceID: "tmdb_" + strconv.Itoa(tv.ID),
|
|
||||||
Title: tv.Name,
|
|
||||||
OriginalTitle: tv.OriginalName,
|
|
||||||
Description: tv.Overview,
|
|
||||||
ReleaseDate: tv.FirstAirDate,
|
|
||||||
EndDate: endDate,
|
|
||||||
Type: "tv",
|
|
||||||
Genres: genres,
|
|
||||||
Rating: tv.VoteAverage,
|
|
||||||
PosterURL: BuildAPIImageProxyURL(tv.PosterPath, "w500"),
|
|
||||||
BackdropURL: BuildAPIImageProxyURL(tv.BackdropPath, "w1280"),
|
|
||||||
Director: "",
|
|
||||||
Cast: []models.UnifiedCastMember{},
|
|
||||||
Duration: duration,
|
|
||||||
Country: firstCountry(tv.ProductionCountries),
|
|
||||||
Language: tv.OriginalLanguage,
|
|
||||||
Budget: nil,
|
|
||||||
Revenue: nil,
|
|
||||||
IMDbID: imdb,
|
|
||||||
ExternalIDs: ext,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map seasons basic info
|
|
||||||
if len(tv.Seasons) > 0 {
|
|
||||||
unified.Seasons = make([]models.UnifiedSeason, 0, len(tv.Seasons))
|
|
||||||
for _, s := range tv.Seasons {
|
|
||||||
unified.Seasons = append(unified.Seasons, models.UnifiedSeason{
|
|
||||||
ID: strconv.Itoa(s.ID),
|
|
||||||
SourceID: "tmdb_" + strconv.Itoa(s.ID),
|
|
||||||
Name: s.Name,
|
|
||||||
SeasonNumber: s.SeasonNumber,
|
|
||||||
EpisodeCount: s.EpisodeCount,
|
|
||||||
ReleaseDate: s.AirDate,
|
|
||||||
PosterURL: BuildAPIImageProxyURL(s.PosterPath, "w500"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return unified
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapTMDBMultiToUnifiedItems(m *models.MultiSearchResponse) []models.UnifiedSearchItem {
|
|
||||||
if m == nil {
|
|
||||||
return []models.UnifiedSearchItem{}
|
|
||||||
}
|
|
||||||
items := make([]models.UnifiedSearchItem, 0, len(m.Results))
|
|
||||||
for _, r := range m.Results {
|
|
||||||
if r.MediaType != "movie" && r.MediaType != "tv" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
title := r.Title
|
|
||||||
if r.MediaType == "tv" {
|
|
||||||
title = r.Name
|
|
||||||
}
|
|
||||||
release := r.ReleaseDate
|
|
||||||
if r.MediaType == "tv" {
|
|
||||||
release = r.FirstAirDate
|
|
||||||
}
|
|
||||||
poster := BuildAPIImageProxyURL(r.PosterPath, "w500")
|
|
||||||
tmdbId := r.ID
|
|
||||||
items = append(items, models.UnifiedSearchItem{
|
|
||||||
ID: strconv.Itoa(tmdbId),
|
|
||||||
SourceID: "tmdb_" + strconv.Itoa(tmdbId),
|
|
||||||
Title: title,
|
|
||||||
Type: map[string]string{"movie":"movie","tv":"tv"}[r.MediaType],
|
|
||||||
ReleaseDate: release,
|
|
||||||
PosterURL: poster,
|
|
||||||
Rating: r.VoteAverage,
|
|
||||||
Description: r.Overview,
|
|
||||||
ExternalIDs: models.UnifiedExternalIDs{KP: nil, TMDB: &tmdbId, IMDb: ""},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return items
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapKPSearchToUnifiedItems(kps *KPSearchResponse) []models.UnifiedSearchItem {
|
|
||||||
if kps == nil {
|
|
||||||
return []models.UnifiedSearchItem{}
|
|
||||||
}
|
|
||||||
items := make([]models.UnifiedSearchItem, 0, len(kps.Films))
|
|
||||||
for _, f := range kps.Films {
|
|
||||||
title := f.NameRu
|
|
||||||
if strings.TrimSpace(title) == "" {
|
|
||||||
title = f.NameEn
|
|
||||||
}
|
|
||||||
poster := f.PosterUrlPreview
|
|
||||||
if poster == "" {
|
|
||||||
poster = f.PosterUrl
|
|
||||||
}
|
|
||||||
poster = BuildAPIImageProxyURL(poster, "w500")
|
|
||||||
rating := 0.0
|
|
||||||
if strings.TrimSpace(f.Rating) != "" {
|
|
||||||
if v, err := strconv.ParseFloat(f.Rating, 64); err == nil {
|
|
||||||
rating = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
kpId := f.FilmId
|
|
||||||
items = append(items, models.UnifiedSearchItem{
|
|
||||||
ID: strconv.Itoa(kpId),
|
|
||||||
SourceID: "kp_" + strconv.Itoa(kpId),
|
|
||||||
Title: title,
|
|
||||||
Type: mapKPTypeToUnifiedShort(f.Type),
|
|
||||||
OriginalType: strings.ToUpper(strings.TrimSpace(f.Type)),
|
|
||||||
ReleaseDate: yearToDate(f.Year),
|
|
||||||
PosterURL: poster,
|
|
||||||
Rating: rating,
|
|
||||||
Description: f.Description,
|
|
||||||
ExternalIDs: models.UnifiedExternalIDs{KP: &kpId, TMDB: nil, IMDb: ""},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return items
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapKPTypeToUnifiedShort(t string) string {
|
|
||||||
switch strings.ToUpper(strings.TrimSpace(t)) {
|
|
||||||
case "TV_SERIES", "MINI_SERIES":
|
|
||||||
return "tv"
|
|
||||||
default:
|
|
||||||
return "movie"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func yearToDate(y string) string {
|
|
||||||
y = strings.TrimSpace(y)
|
|
||||||
if y == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return y + "-01-01"
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user