113 Commits

Author SHA1 Message Date
Erno
c7aa844f49 feat(api): support prefixed IDs in routes and add unified mappers scaffolding
- Handlers parse IDs like kp_123 / tmdb_456 and set id_type accordingly
- Add KP->Unified and TMDB->Unified movie mappers (basic fields)
- Keep backward compatibility for numeric IDs
2025-10-19 08:30:16 +00:00
Erno
0fbf0f0f42 fix(search): force KP for ru language in multi search
- MultiSearch returns KP results when lang starts with ru
- No fallback to TMDB for ru; KP errors bubble up
2025-10-19 07:47:59 +00:00
Erno
f2f06485fd fix(api): respect explicit id_type and remove hidden TMDB fallback
- Movies/TV: if id_type=kp, fetch only from Kinopoisk (with TMDB->KP conversion)
- Movies/TV: if id_type=tmdb, fetch only from TMDB
- Default (no id_type): keep language-based behavior
- README: redact example tokens/keys with placeholders

Prevents wrong provider data when opened from search links with id_type.
2025-10-19 07:40:37 +00:00
f5a754ddf7 fix: Remove TMDB fallback and add ID conversion for strict id_type handling
ПРОБЛЕМА:
- При id_type='kp' код делал fallback на TMDB если фильм не найден
- Если передан TMDB ID с id_type='kp', возвращались данные из TMDB
- Нарушалась явная логика выбора источника

РЕШЕНИЕ:
1. Убран автоматический fallback на TMDB при id_type='kp'
2. Добавлена конвертация ID:
   - Если id_type='kp' и фильм не найден напрямую
   - Пробуем конвертировать TMDB ID → KP ID через TmdbIdToKPId
   - Запрашиваем данные по сконвертированному KP ID
3. Если конвертация не удалась → возвращаем ошибку

ЛОГИКА:
- id_type='kp' + ID=550 (TMDB):
  1. Поиск KP фильма с id=550 → не найдено
  2. Конвертация 550 (TMDB) → получаем KP ID (например 326)
  3. Поиск KP фильма с id=326 → успех
  4. Возврат данных из Kinopoisk 

- id_type='kp' + несуществующий ID:
  1. Поиск KP фильма → не найдено
  2. Конвертация → не удалась
  3. Возврат ошибки (НЕ fallback на TMDB) 

ИЗМЕНЕНИЯ:
- pkg/services/movie.go: добавлена конвертация и удален fallback
- pkg/services/tv.go: добавлена конвертация и удален fallback
- Добавлен import fmt для форматирования ошибок

РЕЗУЛЬТАТ:
 Строгое соблюдение id_type параметра
 Умная конвертация между TMDB и KP ID
 Нет неожиданного fallback на другой источник
2025-10-18 23:55:42 +00:00
be849fd103 feat: Add id_type parameter support for movies and TV shows 2025-10-18 23:41:53 +00:00
af625c7950 fix: Replace ioutil.ReadAll with io.ReadAll
- Fix undefined ioutil error
- Use io.ReadAll from io package (Go 1.16+)
2025-10-18 22:27:53 +00:00
7631e34f2d fix: HDVB player implementation
- Fetch iframe_url from HDVB API instead of direct embed
- Parse JSON response to extract iframe_url
- Use io.ReadAll instead of direct URL embed
- Fixes 'Не передан ни один параметр' error
- HDVB API returns JSON with iframe_url field
2025-10-18 22:18:35 +00:00
18421848c2 fix: Handle Kinopoisk IDs in GetExternalIDs
- Try to fetch from KP API first by KP ID
- If KP data found, return external IDs directly
- Falls back to TMDB if KP ID not found
- Fixes 500 error for Russian content external IDs
2025-10-18 22:05:51 +00:00
fd8e2cccfe fix: Generate OpenAPI spec inline instead of file reference
- Use SpecContent with marshaled JSON instead of SpecURL
- Prevents 'open /openapi.json: no such file or directory' error
- Documentation now loads properly on all domains
2025-10-18 21:35:34 +00:00
30c48fbc50 fix: Use relative URL for OpenAPI spec to bypass Cloudflare
- Change SpecURL from absolute to relative path
- Fixes documentation loading on api.neomovies.ru
- Browser will request openapi.json from same domain
2025-10-18 21:19:57 +00:00
36389f674f fix: Add additional cache headers for documentation
- Add Pragma: no-cache
- Add Expires: 0
- Ensure documentation never cached on api.neomovies.ru
2025-10-18 21:16:17 +00:00
35ceb00217 fix: Update api/index.go and README with new API format
- Fix NewSearchHandler call in api/index.go to include kpService
- Update README with Kinopoisk API integration details
- Document new player API format: /players/{player}/{id_type}/{id}
- Add all new environment variables (KPAPI_KEY, HDVB_TOKEN, etc)
- Add examples for both kp and imdb ID types
2025-10-18 21:04:46 +00:00
7b8d92af14 fix: Update api/index.go for Kinopoisk integration
- Add kpService initialization
- Pass kpService to movieService, tvService, searchHandler
- Update player routes to use id_type format
- Add HDVB player route
2025-10-18 20:50:31 +00:00
e5e70a635b fix: Correct field names ImdbID to IMDbID
- Fixed ImdbID to IMDbID in kinopoisk.go
- Fixed ImdbID to IMDbID in kp_mapper.go
- Removed Tagline field from TVShow mapping
- All builds now pass successfully
2025-10-18 20:30:37 +00:00
28555a83e1 feat: Update player API to use id_type in path
All Russian players now use format: /players/{player}/{id_type}/{id}
- id_type can be kp (Kinopoisk) or imdb
- Alloha, Lumex, Vibix, HDVB support both ID types
- Added validation for id_type parameter
- Updated handlers to parse id_type from path
2025-10-18 20:21:13 +00:00
Cursor Agent
567b287322 chore: add binary to gitignore 2025-10-05 15:46:44 +00:00
Cursor Agent
03091b0fc3 chore: remove accidentally committed binary 2025-10-05 15:46:26 +00:00
Cursor Agent
42d38ba0d1 fix: use GetLanguage helper in MultiSearch endpoint
Problem:
- MultiSearch endpoint was reading 'language' parameter only
- Frontend sends 'lang' parameter (from interceptor)
- Search results were always in Russian

Solution:
- Replace manual language parameter reading with GetLanguage(r)
- GetLanguage checks both 'lang' and 'language' parameters
- Defaults to 'ru-RU' if not specified
- Converts 'en' to 'en-US' and 'ru' to 'ru-RU' for TMDB

Before:
language := r.URL.Query().Get("language")
if language == "" {
    language = "ru-RU"
}

After:
language := GetLanguage(r)

Result:
 Search results now respect ?lang=en parameter
 Movie/TV titles in search are localized
 Consistent with other endpoints (movies, tv, etc.)
2025-10-05 15:46:06 +00:00
Cursor Agent
859a7fd380 chore: remove binaries from repo and update .gitignore 2025-10-05 14:24:48 +00:00
Cursor Agent
303079740f feat: add ?lang=en support to API with default ru
Language Support:
- Create GetLanguage() helper function
- Support both 'lang' and 'language' query parameters
- Convert short codes (en/ru) to TMDB format (en-US/ru-RU)
- Default language: ru-RU

Changes:
- pkg/handlers/lang_helper.go: new helper for language detection
- pkg/handlers/movie.go: use GetLanguage() in all endpoints
- pkg/handlers/tv.go: use GetLanguage() in all endpoints

How to use:
- ?lang=en → returns English content
- ?lang=ru → returns Russian content (default)
- No param → defaults to Russian

All movie/TV endpoints now support multilingual content:
GET /api/v1/movies/{id}?lang=en
GET /api/v1/movies/popular?lang=en
GET /api/v1/tv/{id}?lang=en
etc.
2025-10-05 14:24:19 +00:00
Cursor Agent
39c8366ae1 feat: simplify player controls - remove hotkeys
- Remove all keyboard shortcuts (not working properly)
- Remove play/pause/volume visual controls
- Keep only Fullscreen button (actually works)
- Keep overlay for click-blocking (protects from ads)
- Simpler, cleaner UI
- Users should use browser's popup blocker + AdBlocker
2025-10-04 22:53:50 +00:00
Cursor Agent
d47b4fd0a8 feat: add custom controls overlay for English players
Remove sandbox completely and add custom solution:
- Transparent overlay blocks all clicks on iframe (ad protection)
- Custom controls UI with buttons: play/pause, mute, volume, rewind/forward, fullscreen
- Keyboard shortcuts (hotkeys):
  * Space - Play/Pause
  * M - Mute/Unmute
  * ← → - Rewind/Forward 10s
  * ↑ ↓ - Volume Up/Down
  * F - Fullscreen
  * ? - Show/Hide hotkeys help
- Auto-hide controls after 3s of inactivity
- Visual notifications for all actions
- Works without sandbox restrictions
- Better UX with keyboard control

Note: Controls are visual only (cannot actually control cross-origin iframe player)
but provide good UX and block unwanted clicks/ads
2025-10-04 22:40:58 +00:00
Cursor Agent
0d54aacc7d feat: add minimal sandbox restrictions for English players
Sandbox attributes for vidsrc and vidlink:
- allow-scripts: JavaScript работает (необходимо для плеера)
- allow-same-origin: Доступ к своему origin (необходимо для API)
- allow-forms: Работа с формами (если плеер использует)
- allow-presentation: Fullscreen режим
- allow-modals: Модальные окна (если плеер показывает)

Что блокируется:
- allow-popups (НЕТ) → всплывающие окна заблокированы
- allow-top-navigation (НЕТ) → редиректы родительской страницы заблокированы

Компромисс: плееры работают + базовая защита от редиректов
2025-10-04 22:28:02 +00:00
Cursor Agent
4e88529e0a fix: remove parser and fix docs syntax
- Fix OpenAPI documentation syntax error (extra indent before vidsrc)
- Remove server-side parser (chromedp) - not suitable for Vercel
- Client-side scraping not possible due to Same-Origin Policy
- Keep simple iframe players as current solution
2025-10-04 22:03:37 +00:00
Cursor Agent
0bd3a8860f fix: remove season/episode support from Lumex and Vibix
- Remove season/episode parameters from Lumex (not supported by API)
- Remove season/episode parameters from Vibix (not working properly)
- Improve redirect protection for English players:
  * Block window.close
  * Override window.location with getters/setters
  * Add mousedown event blocking
  * Add location change monitoring (100ms interval)
  * Prevent all forms of navigation
- Update API documentation to reflect changes
- Simplify player handlers code
2025-10-04 21:49:07 +00:00
Cursor Agent
5e761dbbc6 feat: add advanced popup and redirect protection
Multi-layered protection for English players:
- Block window.open with immutable override
- Prevent navigation when iframe is focused (beforeunload)
- Stop event propagation on iframe clicks
- Add overflow:hidden to prevent scrollbar exploits
- Keep players functional while reducing popups

Note: Some popups may still appear due to iframe cross-origin restrictions
2025-10-04 21:36:15 +00:00
Cursor Agent
5d422231ca fix: remove sandbox to allow English players to work
- Remove sandbox attribute that was blocking player functionality
- Add JavaScript popup blocker (limited effectiveness from parent frame)
- Add proper iframe permissions: autoplay, encrypted-media, fullscreen
- Players now work but may still show some popups
- Trade-off: functionality over strict popup blocking
2025-10-04 21:30:15 +00:00
Cursor Agent
b467b7ed1c fix: use query params for Lumex instead of path
- Change from /movie/{id} and /tv-series/{id} to ?imdb_id={id}
- Movie: {LUMEX_URL}?imdb_id={imdb_id}
- TV: {LUMEX_URL}?imdb_id={imdb_id}&season=1&episode=3
- Now matches actual Lumex API format
2025-10-04 21:28:00 +00:00
Cursor Agent
b76e8f685d feat: block popups and redirects for English players
- Add sandbox attribute to vidsrc and vidlink iframes
- Sandbox allows: scripts, same-origin, forms, presentation
- Sandbox blocks: popups, top navigation, unwanted redirects
- Add referrerpolicy=no-referrer for extra security
- Improves user experience by preventing annoying popups
2025-10-04 21:23:13 +00:00
Cursor Agent
3be73ad264 fix: implement Lumex API with correct URL format
- Use /movie/{id} for movies
- Use /tv-series/{id}?season=X&episode=Y for TV shows
- Keep route as /players/lumex/{imdb_id}
- Add autoplay=1 parameter
- Update API documentation with season/episode params
- Keep IMDb ID in route but format URL according to Lumex API
2025-10-04 21:20:39 +00:00
Cursor Agent
c170b2c7fa debug: add detailed logging for Lumex and Vibix players
- Log season/episode query parameters
- Log base URLs and final generated URLs
- Track query parameter separator logic
- Help diagnose why Lumex ignores params and Vibix only processes season
2025-10-04 21:17:37 +00:00
Cursor Agent
52d7e48bdb fix: restore original Alloha API method with season/episode support
- Use Data.Iframe from Alloha API response (original method)
- Add season, episode, translation query parameters to iframe URL
- Keep season/episode support for Lumex and Vibix
- All Russian players now work with episode selection
2025-10-04 21:12:29 +00:00
Cursor Agent
d4e29a8093 feat: add season/episode support for Russian players
- Alloha: now uses token_movie API with season/episode params
- Lumex: added season/episode query parameters
- Vibix: added season/episode to iframe URL
- All Russian players now support TV show episode selection
- Better control over playback for series
2025-10-04 20:56:19 +00:00
Cursor Agent
6ee4b8cc58 revert: remove server-side parsing (Vercel limits)
- Removed client_parser.go with heavy HTTP parsing
- Back to simple iframe players for vidsrc and vidlink
- Avoids Vercel function timeout limits
2025-10-04 20:39:07 +00:00
Cursor Agent
b20edae256 feat: add client-side parsing players with Video.js
- Added client-side parsing for Vidsrc and Vidlink
- Custom Video.js player with HLS support
- Auto-detection of m3u8/mp4 streams from iframe
- New routes: /players/vidsrc-parse, /players/vidlink-parse
- Performance API monitoring for stream detection
- Fallback to original iframe if parsing fails
- Updated API documentation
2025-10-04 20:21:55 +00:00
Cursor Agent
d29dce0afc fix: correct player routes and IDs, add API documentation
- Vidsrc: uses IMDb ID for both movies and TV shows
- Vidlink: uses IMDb ID for movies, TMDB ID for TV shows
- Updated routes: /players/vidsrc/{media_type}/{imdb_id}
- Updated routes: /players/vidlink/movie/{imdb_id}
- New route: /players/vidlink/tv/{tmdb_id}
- Added comprehensive OpenAPI documentation for new players
2025-10-04 19:52:39 +00:00
Cursor Agent
39eea67323 fix: remove dead players (twoembed, autoembed) and fix unused variable 2025-10-04 19:43:50 +00:00
Cursor Agent
bd853e7f89 add new players: vidsrc, twoembed, autoembed, vidlink 2025-10-04 19:18:44 +00:00
Cursor Agent
4e6e447e79 fix: remove AllowCredentials from CORS to support wildcard origin 2025-10-04 19:07:22 +00:00
e734e462c4 Merge branch 'feature/add-streaming-players-v2' into 'main'
feat: add RgShows and IframeVideo streaming players

See merge request foxixus/neomovies-api!4
2025-09-29 10:12:28 +00:00
c183861491 Merge branch 'feature/remove-webtorrent-fix-issues' into 'main'
Remove WebTorrent player documentation from API docs

See merge request foxixus/neomovies-api!3
2025-09-29 09:29:52 +00:00
factory-droid[bot]
63b11eb2ad Remove WebTorrent player documentation from API docs 2025-09-29 08:12:54 +00:00
factory-droid[bot]
321694df9c feat: add RgShows and IframeVideo streaming players
🎬 New Streaming Players Added:
- RgShows player for movies and TV shows via TMDB ID
- IframeVideo player using Kinopoisk ID and IMDB ID
- Unified players manager for multiple streaming providers
- JSON API endpoints for programmatic access

📡 RgShows Player Features:
- Direct movie streaming: /api/v1/players/rgshows/{tmdb_id}
- TV show episodes: /api/v1/players/rgshows/{tmdb_id}/{season}/{episode}
- HTTP API integration with rgshows.com
- 40-second timeout for reliability
- Proper error handling and logging

🎯 IframeVideo Player Features:
- Two-step authentication process (search + token extraction)
- Support for both Kinopoisk and IMDB IDs
- HTML iframe parsing for token extraction
- Multipart form data for video URL requests
- Endpoint: /api/v1/players/iframevideo/{kinopoisk_id}/{imdb_id}

🔧 Technical Implementation:
- Clean Go architecture with pkg/players package
- StreamResult interface for consistent responses
- Proper HTTP headers mimicking browser requests
- Comprehensive error handling and logging
- RESTful API design following existing patterns

🌐 New API Endpoints:
- /api/v1/players/rgshows/{tmdb_id} - RgShows movie player
- /api/v1/players/rgshows/{tmdb_id}/{season}/{episode} - RgShows TV player
- /api/v1/players/iframevideo/{kinopoisk_id}/{imdb_id} - IframeVideo player
- /api/v1/stream/{provider}/{tmdb_id} - JSON API for stream info

 Quality Assurance:
- All code passes go vet without issues
- Proper Go formatting applied
- Modular design for easy extension
- Built from commit a31cdf0 'Merge branch feature/jwt-refresh-and-favorites-fix'

Ready for production deployment! 🚀
2025-09-28 16:11:09 +00:00
a31cdf0f75 Merge branch 'feature/jwt-refresh-and-favorites-fix' into 'main'
feat: implement JWT refresh token mechanism and improve auth

See merge request foxixus/neomovies-api!1
2025-09-28 11:46:20 +00:00
dfcd9db295 feat: implement JWT refresh token mechanism and improve auth 2025-09-28 11:46:20 +00:00
59334da140 bug fixes 2025-08-28 21:25:21 +03:00
04583418a1 Edit README.md 2025-08-26 20:57:07 +00:00
42073ea7b4 Release 2.4.4 2025-08-17 11:58:43 +00:00
a2e015aa53 Bug fix 2025-08-14 15:19:20 +00:00
552e60440c Bug fix 2025-08-14 13:36:22 +00:00
fcb6caf1b9 Fix docs 2025-08-14 13:19:49 +00:00
bb64b2dde4 Fix docs 2025-08-14 13:19:19 +00:00
86034c8e12 Fix documentation 2025-08-14 12:47:52 +00:00
f3c1cab796 Add WebTorrent Player(Experimental) 2025-08-14 11:35:51 +00:00
d790eb7903 Add WebTorrent Player(Experimental) 2025-08-14 11:34:31 +00:00
d347c6003a Release 2.4.2 2025-08-13 18:02:03 +00:00
c8cf79d764 Edit docs.go 2025-08-11 19:11:52 +00:00
206aa770b6 Add player: Vibix 2025-08-11 18:36:02 +00:00
9db1ee3f50 Bug fix: favourites route 2025-08-11 11:36:23 +03:00
171a2bf3ed Add Google OAuth 2025-08-08 16:47:02 +00:00
486bbf5475 Bug Fix: Fix Delete profile route 2025-08-08 10:35:07 +00:00
12ed40f3d4 Bug fix 2025-08-07 19:23:10 +00:00
53d70c9262 Bug fix 2025-08-07 18:25:43 +00:00
7f6ff5f660 Rewrite api to Go 2025-08-07 13:47:42 +00:00
4a9a7febec fix 2025-07-19 21:45:57 +03:00
66cd0d3b21 add size torrent 2025-07-19 19:36:27 +03:00
92b936f057 fix seasons in JackRed 2025-07-17 21:00:58 +03:00
9cd3d45327 Add JackRed api 2025-07-17 20:35:20 +03:00
efcc5cd2b9 Delete useless code 2025-07-15 12:11:29 +00:00
a575b5c5bf improve db code 2025-07-10 22:22:57 +03:00
51af31a6d5 fix 2025-07-10 22:13:45 +03:00
0b2dc6b2f4 fix 2025-07-10 22:10:24 +03:00
cc463c4d7c new fix CORS 2025-07-10 22:02:41 +03:00
94968f3cd1 fix CORS for new subdomain 2025-07-10 21:56:47 +03:00
dff5e963ab impove db code 2025-07-08 16:56:03 +03:00
cf5dfc7e54 fix auth, reactions and etc 2025-07-08 16:43:41 +03:00
1005f30285 change reactions logic 2025-07-08 15:44:42 +03:00
ea3c208292 small fix 2025-07-08 15:39:58 +03:00
5ce5da39bb del useless file 2025-07-08 15:27:48 +03:00
58a32d8838 fix routes issue 2025-07-08 15:27:10 +03:00
770ecef6d5 change reactions logic 2025-07-08 14:55:20 +03:00
37040dd7ec add reactions 2025-07-08 14:51:41 +03:00
7aa0307e25 fix favourites issue 2025-07-08 13:26:58 +03:00
d961393562 small fixes and repair shit code 2025-07-08 00:12:12 +03:00
e1e2b4f92b fix db shit code 2025-07-07 20:43:22 +03:00
6b063f4c70 fix db close leak 2025-07-07 20:39:52 +03:00
95910e0710 ed readme 2025-07-07 18:23:34 +03:00
02dedbb8f7 Authorization, favorites and players have been moved to the API server 2025-07-07 18:08:42 +03:00
6bf00451fa Fix multisearch 2025-05-28 12:21:52 +00:00
600de04561 Fix search 2025-05-28 12:03:25 +00:00
7a83bf2e27 Add categories 2025-05-28 10:27:38 +00:00
1fd522872d Delete /movies/search route 2025-05-01 09:14:26 +00:00
0f751cced0 Update 2 files
- /src/routes/movies.js
- /src/index.js
2025-01-16 16:28:35 +00:00
4cb06cbde5 Update 2 files
- /src/routes/movies.js
- /src/config/tmdb.js
2025-01-16 16:21:32 +00:00
4f23e979d5 Update file movies.js 2025-01-16 16:12:42 +00:00
c25d4e5d87 Update 6 files
- /src/index.js
- /src/config/tmdb.js
- /src/routes/movies.js
- /src/routes/images.js
- /src/routes/tv.js
- /package-lock.json
2025-01-16 15:44:05 +00:00
5361894af1 Update 4 files
- /src/config/tmdb.js
- /src/routes/movies.js
- /LICENSE
- /package.json
2025-01-16 09:22:58 +00:00
a5eb03aea8 Update file movies.js 2025-01-04 14:17:20 +00:00
a04b4f7c12 Update file tmdb.js 2025-01-04 13:13:46 +00:00
3a86c14129 Update 4 files
- /src/index.js
- /src/routes/movies.js
- /src/config/tmdb.js
- /package.json
2025-01-04 12:54:12 +00:00
498bc41c1b Edit README.md 2025-01-04 08:21:15 +00:00
4d73fc9d8c Edit LICENSE 2025-01-04 08:14:48 +00:00
2d25162b1c Add LICENSE 2025-01-04 08:09:52 +00:00
af5957b4f9 Update file tmdb.js 2025-01-03 20:22:04 +00:00
a724bf0484 Update 3 files
- /api/index.js
- /src/index.js
- /vercel.json
2025-01-03 20:14:34 +00:00
8b11f89347 Update 4 files
- /src/index.js
- /src/routes/movies.js
- /src/config/tmdb.js
- /vercel.json
2025-01-03 20:08:13 +00:00
0c1cfb1ac5 Update 2 files
- /src/public/api-docs/index.html
- /src/index.js
2025-01-03 19:58:01 +00:00
868e71991c Update 10 files
- /package.json
- /package-lock.json
- /README.md
- /vercel.json
- /src/config/tmdb.js
- /src/public/api-docs/index.html
- /src/utils/date.js
- /src/utils/health.js
- /src/routes/movies.js
- /src/index.js
2025-01-03 19:46:10 +00:00
5f859eebb8 Update 25 files
- /docs/docs.go
- /docs/swagger.json
- /docs/swagger.yaml
- /internal/api/handlers.go
- /internal/api/init.go
- /internal/api/models.go
- /internal/api/utils.go
- /internal/tmdb/client.go
- /internal/tmdb/models.go
- /src/config/tmdb.js
- /src/routes/movies.js
- /src/utils/date.js
- /src/utils/health.js
- /src/index.js
- /build.sh
- /clean.sh
- /go.mod
- /go.sum
- /main.go
- /package-lock.json
- /package.json
- /README.md
- /render.yaml
- /run.sh
- /vercel.json
2025-01-03 19:36:22 +00:00
3a6ac8db4b Update file index.js 2025-01-03 19:28:39 +00:00
60c574849b Update 3 files
- /package-lock.json
- /vercel.json
- /src/index.js
2025-01-03 19:26:29 +00:00
037ab7a458 Update file package.json 2025-01-03 19:19:06 +00:00
9d60080116 Update 11 files
- /src/index.js
- /src/routes/movies.js
- /src/config/tmdb.js
- /src/utils/health.js
- /src/utils/date.js
- /clean.sh
- /package.json
- /package-lock.json
- /vercel.json
- /build.sh
- /README.md
2025-01-03 19:10:34 +00:00
17 changed files with 121 additions and 918 deletions

View File

@@ -1,15 +1,15 @@
MONGO_URI=mongodb://localhost:27017/neomovies
MONGO_DB_NAME=neomovies
TMDB_ACCESS_TOKEN=your_tmdb_access_token
TMDB_ACCESS_TOKEN=your_tmdb_access_token_here
KPAPI_KEY=your_kp_api_key
KPAPI_KEY=920aaf6a-9f64-46f7-bda7-209fb1069440
KPAPI_BASE_URL=https://kinopoiskapiunofficial.tech/api
HDVB_TOKEN=your_hdvb_token
HDVB_TOKEN=b9ae5f8c4832244060916af4aa9d1939
VIBIX_HOST=https://vibix.org
VIBIX_TOKEN=your_vibix_token
VIBIX_TOKEN=18745|NzecUXT4gikPUtFkSEFlDLPmr9kWnQACTo1N0Ixq9240bcf1
LUMEX_URL=https://p.lumex.space
@@ -18,7 +18,7 @@ ALLOHA_TOKEN=your_alloha_token
REDAPI_BASE_URL=http://redapi.cfhttp.top
REDAPI_KEY=your_redapi_key
JWT_SECRET=your_jwt_secret_key
JWT_SECRET=your_jwt_secret_key_here
GMAIL_USER=your_gmail@gmail.com
GMAIL_APP_PASSWORD=your_gmail_app_password

View File

@@ -1,4 +1,4 @@
# Neo Movies API (Unified)
# Neo Movies API
REST API для поиска и получения информации о фильмах, использующий TMDB API.
@@ -89,7 +89,7 @@ GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/callback
## 📋 API Endpoints
### 🔓 Публичные маршруты (старые)
### 🔓 Публичные маршруты
```http
# Система
@@ -114,7 +114,7 @@ GET /api/v1/movies/popular # Популярные
GET /api/v1/movies/top-rated # Топ-рейтинговые
GET /api/v1/movies/upcoming # Предстоящие
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}/similar # Похожие
@@ -124,86 +124,7 @@ GET /api/v1/tv/popular # Популярные
GET /api/v1/tv/top-rated # Топ-рейтинговые
GET /api/v1/tv/on-the-air # В эфире
GET /api/v1/tv/airing-today # Сегодня в эфире
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} # Детали сериала
GET /api/v1/tv/{id}/recommendations # Рекомендации
GET /api/v1/tv/{id}/similar # Похожие

View File

@@ -67,8 +67,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
tvHandler := handlersPkg.NewTVHandler(tvService)
favoritesHandler := handlersPkg.NewFavoritesHandler(favoritesService, globalCfg)
docsHandler := handlersPkg.NewDocsHandler()
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
unifiedHandler := handlersPkg.NewUnifiedHandler(tmdbService, kpService)
searchHandler := handlersPkg.NewSearchHandler(tmdbService, kpService)
categoriesHandler := handlersPkg.NewCategoriesHandler(tmdbService)
playersHandler := handlersPkg.NewPlayersHandler(globalCfg)
torrentsHandler := handlersPkg.NewTorrentsHandler(torrentService, tmdbService)
@@ -124,11 +123,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).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}", movieHandler.GetByID).Methods("GET")
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")

View File

@@ -47,8 +47,7 @@ func main() {
tvHandler := appHandlers.NewTVHandler(tvService)
favoritesHandler := appHandlers.NewFavoritesHandler(favoritesService, cfg)
docsHandler := appHandlers.NewDocsHandler()
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
unifiedHandler := appHandlers.NewUnifiedHandler(tmdbService, kpService)
searchHandler := appHandlers.NewSearchHandler(tmdbService, kpService)
categoriesHandler := appHandlers.NewCategoriesHandler(tmdbService)
playersHandler := appHandlers.NewPlayersHandler(cfg)
torrentsHandler := appHandlers.NewTorrentsHandler(torrentService, tmdbService)
@@ -101,11 +100,7 @@ func main() {
api.HandleFunc("/movies/top-rated", movieHandler.TopRated).Methods("GET")
api.HandleFunc("/movies/upcoming", movieHandler.Upcoming).Methods("GET")
api.HandleFunc("/movies/now-playing", movieHandler.NowPlaying).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}", movieHandler.GetByID).Methods("GET")
api.HandleFunc("/movies/{id}/recommendations", movieHandler.GetRecommendations).Methods("GET")
api.HandleFunc("/movies/{id}/similar", movieHandler.GetSimilar).Methods("GET")
api.HandleFunc("/movies/{id}/external-ids", movieHandler.GetExternalIDs).Methods("GET")

View File

@@ -161,8 +161,8 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
OpenAPI: "3.0.0",
Info: Info{
Title: "Neo Movies API",
Description: "Унифицированный API (TMDB/Kinopoisk) с префиксными ID (kp_*, tmdb_*) и единым форматом данных",
Version: "3.0.0",
Description: "Современный API для поиска фильмов и сериалов с интеграцией TMDB и поддержкой авторизации",
Version: "2.0.0",
Contact: Contact{
Name: "API Support",
URL: "https://github.com/your-username/neomovies-api-go",
@@ -194,10 +194,10 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
},
},
},
"/api/v1/search": map[string]interface{}{
"/api/v1/search/multi": map[string]interface{}{
"get": map[string]interface{}{
"summary": "Унифицированный поиск",
"description": "Поиск фильмов и сериалов в источниках TMDB или Kinopoisk",
"summary": "Мультипоиск",
"description": "Поиск фильмов, сериалов и актеров",
"tags": []string{"Search"},
"parameters": []map[string]interface{}{
{
@@ -207,13 +207,6 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
"schema": map[string]string{"type": "string"},
"description": "Поисковый запрос",
},
{
"name": "source",
"in": "query",
"required": true,
"schema": map[string]interface{}{"type": "string", "enum": []string{"kp", "tmdb"}},
"description": "Источник: kp или tmdb",
},
{
"name": "page",
"in": "query",
@@ -223,7 +216,7 @@ func getOpenAPISpecWithURL(baseURL string) *OpenAPISpec {
},
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "Результаты поиска (унифицированные)",
"description": "Результаты поиска",
},
},
},

View File

@@ -1,15 +1,15 @@
package handlers
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gorilla/mux"
"neomovies-api/pkg/config"
"github.com/gorilla/mux"
"neomovies-api/pkg/config"
)
type ImagesHandler struct{}
@@ -36,14 +36,7 @@ func (h *ImagesHandler) GetImage(w http.ResponseWriter, r *http.Request) {
size = "original"
}
var imageURL string
if strings.HasPrefix(imagePath, "http://") || strings.HasPrefix(imagePath, "https://") {
// Проксируем внешний абсолютный URL (например, Kinopoisk)
imageURL = imagePath
} else {
// TMDB относительный путь
imageURL = fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath)
}
imageURL := fmt.Sprintf("%s/%s/%s", config.TMDBImageBaseURL, size, imagePath)
resp, err := http.Get(imageURL)
if err != nil {

View File

@@ -30,7 +30,7 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
log.Printf("GetAllohaPlayer called: %s %s", r.Method, r.URL.Path)
vars := mux.Vars(r)
idType := vars["id_type"]
idType := vars["id_type"]
id := vars["id"]
if idType == "" || id == "" {
@@ -39,10 +39,9 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
return
}
if idType == "kinopoisk_id" { idType = "kp" }
if idType != "kp" && idType != "imdb" {
if idType != "kp" && idType != "imdb" {
log.Printf("Error: invalid id_type: %s", idType)
http.Error(w, "id_type must be 'kp' (kinopoisk_id) or 'imdb'", http.StatusBadRequest)
http.Error(w, "id_type must be 'kp' or 'imdb'", http.StatusBadRequest)
return
}
@@ -160,27 +159,20 @@ func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request)
log.Printf("Processing %s ID: %s", idType, id)
if h.config.LumexURL == "" {
log.Printf("Error: LUMEX_URL is missing")
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
return
}
if h.config.LumexURL == "" {
log.Printf("Error: LUMEX_URL is missing")
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
return
}
// Формируем запрос вида: https://portal.lumex.host/api/short?api_token=...&kinopoisk_id=...
// Ожидается, что LUMEX_URL уже содержит базовый URL и api_token, например:
// LUMEX_URL=https://portal.lumex.host/api/short?api_token=XXXX
var paramName string
if idType == "kp" {
paramName = "kinopoisk_id"
} else {
paramName = "imdb_id"
}
var paramName string
if idType == "kp" {
paramName = "kinopoisk_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, id)
playerURL := fmt.Sprintf("%s?%s=%s", h.config.LumexURL, paramName, 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)

View File

@@ -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)
}

View File

@@ -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"`
}

View File

@@ -123,7 +123,6 @@ type ExternalIDs struct {
ID int `json:"id"`
IMDbID string `json:"imdb_id"`
KinopoiskID int `json:"kinopoisk_id,omitempty"`
TMDBID int `json:"tmdb_id,omitempty"`
TVDBID int `json:"tvdb_id,omitempty"`
WikidataID string `json:"wikidata_id"`
FacebookID string `json:"facebook_id"`

View File

@@ -1,113 +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"`
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"`
}

View File

@@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
@@ -140,7 +139,7 @@ func (s *KinopoiskService) GetFilmByKinopoiskId(id int) (*KPFilm, error) {
}
func (s *KinopoiskService) GetFilmByImdbId(imdbId string) (*KPFilm, error) {
endpoint := fmt.Sprintf("%s/v2.2/films?imdbId=%s", s.baseURL, url.QueryEscape(imdbId))
endpoint := fmt.Sprintf("%s/v2.2/films?imdbId=%s", s.baseURL, imdbId)
var response struct {
Films []KPFilm `json:"items"`
@@ -159,7 +158,7 @@ func (s *KinopoiskService) GetFilmByImdbId(imdbId string) (*KPFilm, error) {
}
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)
endpoint := fmt.Sprintf("%s/v2.1/films/search-by-keyword?keyword=%s&page=%d", s.baseURL, keyword, page)
var response KPSearchResponse
err := s.makeRequest(endpoint, &response)
return &response, err

View File

@@ -388,37 +388,3 @@ func FormatKPDate(year int) string {
}
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
}
}
}

View File

@@ -39,7 +39,6 @@ func (s *MovieService) GetByID(id int, language string, idType string) (*models.
// Сначала пробуем как Kinopoisk ID
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil {
// Возвращаем KP-модель в TMDB-формате без подмены на TMDB объект
return MapKPFilmToTMDBMovie(kpFilm), nil
}
@@ -108,14 +107,6 @@ func (s *MovieService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
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
}
}

View File

@@ -1,13 +1,14 @@
package services
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"neomovies-api/pkg/models"
"neomovies-api/pkg/models"
)
type TMDBService struct {
@@ -179,46 +180,78 @@ func (s *TMDBService) GetTVShow(id int, language string) (*models.TVShow, error)
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"`
}
if err := s.makeRequest(endpoint, &resp); err != nil {
return 0, err
// Map TMDB movie to unified content with prefixed IDs. Requires optional external IDs for imdbId.
func MapTMDBToUnifiedMovie(movie *models.Movie, external *models.ExternalIDs) *models.UnifiedContent {
if movie == nil {
return nil
}
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
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})
}
return 0, fmt.Errorf("tmdb id not found for imdb %s", imdbID)
var imdb string
if external != nil {
imdb = external.IMDbID
}
var budgetPtr *int64
if movie.Budget > 0 {
v := movie.Budget
budgetPtr = &v
}
var revenuePtr *int64
if movie.Revenue > 0 {
v := movie.Revenue
revenuePtr = &v
}
ext := models.UnifiedExternalIDs{
KP: nil,
TMDB: &movie.ID,
IMDb: imdb,
}
return &models.UnifiedContent{
ID: strconv.Itoa(movie.ID),
SourceID: "tmdb_" + strconv.Itoa(movie.ID),
Title: movie.Title,
OriginalTitle: movie.OriginalTitle,
Description: movie.Overview,
ReleaseDate: movie.ReleaseDate,
EndDate: nil,
Type: "movie",
Genres: genres,
Rating: movie.VoteAverage,
PosterURL: movie.PosterPath,
BackdropURL: movie.BackdropPath,
Director: "",
Cast: []models.UnifiedCastMember{},
Duration: movie.Runtime,
Country: firstCountry(movie.ProductionCountries),
Language: movie.OriginalLanguage,
Budget: budgetPtr,
Revenue: revenuePtr,
IMDbID: imdb,
ExternalIDs: ext,
}
}
func firstCountry(countries []models.ProductionCountry) string {
if len(countries) == 0 {
return ""
}
if strings.TrimSpace(countries[0].Name) != "" {
return countries[0].Name
}
return countries[0].ISO31661
}
func (s *TMDBService) GetGenres(mediaType string, language string) (*models.GenresResponse, error) {

View File

@@ -35,27 +35,12 @@ func (s *TVService) GetByID(id int, language string, idType string) (*models.TVS
// Сначала пробуем как 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
}
}
@@ -101,34 +86,5 @@ func (s *TVService) GetSimilar(id, page int, language string) (*models.TMDBTVRes
}
func (s *TVService) GetExternalIDs(id int) (*models.ExternalIDs, error) {
if s.kpService != nil {
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
return s.tmdb.GetTVExternalIDs(id)
}

View File

@@ -1,266 +0,0 @@
package services
import (
"fmt"
"strconv"
"strings"
"neomovies-api/pkg/models"
)
const tmdbImageBase = "https://image.tmdb.org/t/p"
func BuildTMDBImageURL(path string, size string) string {
if path == "" {
return ""
}
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return path
}
if size == "" {
size = "w500"
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return fmt.Sprintf("%s/%s%s", tmdbImageBase, size, path)
}
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: BuildTMDBImageURL(movie.PosterPath, "w500"),
BackdropURL: BuildTMDBImageURL(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: BuildTMDBImageURL(tv.PosterPath, "w500"),
BackdropURL: BuildTMDBImageURL(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: BuildTMDBImageURL(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 := BuildTMDBImageURL(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
}
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),
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
}