mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-12-18 13:36:09 +05:00
Add log
This commit is contained in:
1308
pkg/services/auth.go
1308
pkg/services/auth.go
File diff suppressed because it is too large
Load Diff
@@ -1,150 +1,150 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
)
|
||||
|
||||
type EmailService struct {
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
func NewEmailService(cfg *config.Config) *EmailService {
|
||||
return &EmailService{
|
||||
config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
type EmailOptions struct {
|
||||
To []string
|
||||
Subject string
|
||||
Body string
|
||||
IsHTML bool
|
||||
}
|
||||
|
||||
func (s *EmailService) SendEmail(options *EmailOptions) error {
|
||||
if s.config.GmailUser == "" || s.config.GmailPassword == "" {
|
||||
return fmt.Errorf("Gmail credentials not configured")
|
||||
}
|
||||
|
||||
// Gmail SMTP конфигурация
|
||||
smtpHost := "smtp.gmail.com"
|
||||
smtpPort := "587"
|
||||
auth := smtp.PlainAuth("", s.config.GmailUser, s.config.GmailPassword, smtpHost)
|
||||
|
||||
// Создаем заголовки email
|
||||
headers := make(map[string]string)
|
||||
headers["From"] = s.config.GmailUser
|
||||
headers["To"] = strings.Join(options.To, ",")
|
||||
headers["Subject"] = options.Subject
|
||||
|
||||
if options.IsHTML {
|
||||
headers["MIME-Version"] = "1.0"
|
||||
headers["Content-Type"] = "text/html; charset=UTF-8"
|
||||
}
|
||||
|
||||
// Формируем сообщение
|
||||
message := ""
|
||||
for key, value := range headers {
|
||||
message += fmt.Sprintf("%s: %s\r\n", key, value)
|
||||
}
|
||||
message += "\r\n" + options.Body
|
||||
|
||||
// Отправляем email
|
||||
err := smtp.SendMail(
|
||||
smtpHost+":"+smtpPort,
|
||||
auth,
|
||||
s.config.GmailUser,
|
||||
options.To,
|
||||
[]byte(message),
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Предустановленные шаблоны email
|
||||
func (s *EmailService) SendVerificationEmail(userEmail, code string) error {
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Подтверждение регистрации Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h1 style="color: #2196f3;">Neo Movies</h1>
|
||||
<p>Здравствуйте!</p>
|
||||
<p>Для завершения регистрации введите этот код:</p>
|
||||
<div style="
|
||||
background: #f5f5f5;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
font-size: 24px;
|
||||
letter-spacing: 4px;
|
||||
margin: 20px 0;
|
||||
">
|
||||
%s
|
||||
</div>
|
||||
<p>Код действителен в течение 10 минут.</p>
|
||||
<p>Если вы не регистрировались на нашем сайте, просто проигнорируйте это письмо.</p>
|
||||
</div>
|
||||
`, code),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
|
||||
func (s *EmailService) SendPasswordResetEmail(userEmail, resetToken string) error {
|
||||
resetURL := fmt.Sprintf("%s/reset-password?token=%s", s.config.BaseURL, resetToken)
|
||||
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Сброс пароля Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<html>
|
||||
<body>
|
||||
<h2>Сброс пароля</h2>
|
||||
<p>Вы запросили сброс пароля для вашего аккаунта Neo Movies.</p>
|
||||
<p>Нажмите на ссылку ниже, чтобы создать новый пароль:</p>
|
||||
<p><a href="%s">Сбросить пароль</a></p>
|
||||
<p>Ссылка действительна в течение 1 часа.</p>
|
||||
<p>Если вы не запрашивали сброс пароля, проигнорируйте это сообщение.</p>
|
||||
<br>
|
||||
<p>С уважением,<br>Команда Neo Movies</p>
|
||||
</body>
|
||||
</html>
|
||||
`, resetURL),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
|
||||
func (s *EmailService) SendMovieRecommendationEmail(userEmail, userName string, movies []string) error {
|
||||
moviesList := ""
|
||||
for _, movie := range movies {
|
||||
moviesList += fmt.Sprintf("<li>%s</li>", movie)
|
||||
}
|
||||
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Новые рекомендации фильмов от Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<html>
|
||||
<body>
|
||||
<h2>Привет, %s!</h2>
|
||||
<p>У нас есть новые рекомендации фильмов специально для вас:</p>
|
||||
<ul>%s</ul>
|
||||
<p>Заходите в приложение, чтобы узнать больше деталей!</p>
|
||||
<br>
|
||||
<p>С уважением,<br>Команда Neo Movies</p>
|
||||
</body>
|
||||
</html>
|
||||
`, userName, moviesList),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
)
|
||||
|
||||
type EmailService struct {
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
func NewEmailService(cfg *config.Config) *EmailService {
|
||||
return &EmailService{
|
||||
config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
type EmailOptions struct {
|
||||
To []string
|
||||
Subject string
|
||||
Body string
|
||||
IsHTML bool
|
||||
}
|
||||
|
||||
func (s *EmailService) SendEmail(options *EmailOptions) error {
|
||||
if s.config.GmailUser == "" || s.config.GmailPassword == "" {
|
||||
return fmt.Errorf("Gmail credentials not configured")
|
||||
}
|
||||
|
||||
// Gmail SMTP конфигурация
|
||||
smtpHost := "smtp.gmail.com"
|
||||
smtpPort := "587"
|
||||
auth := smtp.PlainAuth("", s.config.GmailUser, s.config.GmailPassword, smtpHost)
|
||||
|
||||
// Создаем заголовки email
|
||||
headers := make(map[string]string)
|
||||
headers["From"] = s.config.GmailUser
|
||||
headers["To"] = strings.Join(options.To, ",")
|
||||
headers["Subject"] = options.Subject
|
||||
|
||||
if options.IsHTML {
|
||||
headers["MIME-Version"] = "1.0"
|
||||
headers["Content-Type"] = "text/html; charset=UTF-8"
|
||||
}
|
||||
|
||||
// Формируем сообщение
|
||||
message := ""
|
||||
for key, value := range headers {
|
||||
message += fmt.Sprintf("%s: %s\r\n", key, value)
|
||||
}
|
||||
message += "\r\n" + options.Body
|
||||
|
||||
// Отправляем email
|
||||
err := smtp.SendMail(
|
||||
smtpHost+":"+smtpPort,
|
||||
auth,
|
||||
s.config.GmailUser,
|
||||
options.To,
|
||||
[]byte(message),
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Предустановленные шаблоны email
|
||||
func (s *EmailService) SendVerificationEmail(userEmail, code string) error {
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Подтверждение регистрации Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h1 style="color: #2196f3;">Neo Movies</h1>
|
||||
<p>Здравствуйте!</p>
|
||||
<p>Для завершения регистрации введите этот код:</p>
|
||||
<div style="
|
||||
background: #f5f5f5;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
font-size: 24px;
|
||||
letter-spacing: 4px;
|
||||
margin: 20px 0;
|
||||
">
|
||||
%s
|
||||
</div>
|
||||
<p>Код действителен в течение 10 минут.</p>
|
||||
<p>Если вы не регистрировались на нашем сайте, просто проигнорируйте это письмо.</p>
|
||||
</div>
|
||||
`, code),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
|
||||
func (s *EmailService) SendPasswordResetEmail(userEmail, resetToken string) error {
|
||||
resetURL := fmt.Sprintf("%s/reset-password?token=%s", s.config.BaseURL, resetToken)
|
||||
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Сброс пароля Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<html>
|
||||
<body>
|
||||
<h2>Сброс пароля</h2>
|
||||
<p>Вы запросили сброс пароля для вашего аккаунта Neo Movies.</p>
|
||||
<p>Нажмите на ссылку ниже, чтобы создать новый пароль:</p>
|
||||
<p><a href="%s">Сбросить пароль</a></p>
|
||||
<p>Ссылка действительна в течение 1 часа.</p>
|
||||
<p>Если вы не запрашивали сброс пароля, проигнорируйте это сообщение.</p>
|
||||
<br>
|
||||
<p>С уважением,<br>Команда Neo Movies</p>
|
||||
</body>
|
||||
</html>
|
||||
`, resetURL),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
|
||||
func (s *EmailService) SendMovieRecommendationEmail(userEmail, userName string, movies []string) error {
|
||||
moviesList := ""
|
||||
for _, movie := range movies {
|
||||
moviesList += fmt.Sprintf("<li>%s</li>", movie)
|
||||
}
|
||||
|
||||
options := &EmailOptions{
|
||||
To: []string{userEmail},
|
||||
Subject: "Новые рекомендации фильмов от Neo Movies",
|
||||
Body: fmt.Sprintf(`
|
||||
<html>
|
||||
<body>
|
||||
<h2>Привет, %s!</h2>
|
||||
<p>У нас есть новые рекомендации фильмов специально для вас:</p>
|
||||
<ul>%s</ul>
|
||||
<p>Заходите в приложение, чтобы узнать больше деталей!</p>
|
||||
<br>
|
||||
<p>С уважением,<br>Команда Neo Movies</p>
|
||||
</body>
|
||||
</html>
|
||||
`, userName, moviesList),
|
||||
IsHTML: true,
|
||||
}
|
||||
|
||||
return s.SendEmail(options)
|
||||
}
|
||||
|
||||
@@ -1,184 +1,184 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type FavoritesService struct {
|
||||
db *mongo.Database
|
||||
tmdb *TMDBService
|
||||
}
|
||||
|
||||
func NewFavoritesService(db *mongo.Database, tmdb *TMDBService) *FavoritesService {
|
||||
return &FavoritesService{
|
||||
db: db,
|
||||
tmdb: tmdb,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *FavoritesService) AddToFavorites(userID, mediaID, mediaType string) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
// Проверяем, не добавлен ли уже в избранное
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var existingFavorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&existingFavorite)
|
||||
if err == nil {
|
||||
// Уже в избранном
|
||||
return nil
|
||||
}
|
||||
|
||||
var title, posterPath string
|
||||
|
||||
// Получаем информацию из TMDB в зависимости от типа медиа
|
||||
mediaIDInt, err := strconv.Atoi(mediaID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid media ID: %s", mediaID)
|
||||
}
|
||||
|
||||
if mediaType == "movie" {
|
||||
movie, err := s.tmdb.GetMovie(mediaIDInt, "en-US")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title = movie.Title
|
||||
posterPath = movie.PosterPath
|
||||
} else if mediaType == "tv" {
|
||||
tv, err := s.tmdb.GetTVShow(mediaIDInt, "en-US")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title = tv.Name
|
||||
posterPath = tv.PosterPath
|
||||
} else {
|
||||
return fmt.Errorf("invalid media type: %s", mediaType)
|
||||
}
|
||||
|
||||
// Формируем полный URL для постера
|
||||
if posterPath != "" {
|
||||
posterPath = fmt.Sprintf("https://image.tmdb.org/t/p/w500%s", posterPath)
|
||||
}
|
||||
|
||||
favorite := models.Favorite{
|
||||
UserID: userID,
|
||||
MediaID: mediaID,
|
||||
MediaType: mediaType,
|
||||
Title: title,
|
||||
PosterPath: posterPath,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
_, err = collection.InsertOne(context.Background(), favorite)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddToFavoritesWithInfo adds media to favorites with provided media information
|
||||
func (s *FavoritesService) AddToFavoritesWithInfo(userID, mediaID, mediaType string, mediaInfo *models.MediaInfo) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
// Проверяем, не добавлен ли уже в избранное
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var existingFavorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&existingFavorite)
|
||||
if err == nil {
|
||||
// Уже в избранном
|
||||
return nil
|
||||
}
|
||||
|
||||
// Формируем полный URL для постера если он есть
|
||||
posterPath := mediaInfo.PosterPath
|
||||
if posterPath != "" && posterPath[0] == '/' {
|
||||
posterPath = fmt.Sprintf("https://image.tmdb.org/t/p/w500%s", posterPath)
|
||||
}
|
||||
|
||||
favorite := models.Favorite{
|
||||
UserID: userID,
|
||||
MediaID: mediaID,
|
||||
MediaType: mediaType,
|
||||
Title: mediaInfo.Title,
|
||||
PosterPath: posterPath,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
_, err = collection.InsertOne(context.Background(), favorite)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *FavoritesService) RemoveFromFavorites(userID, mediaID, mediaType string) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
_, err := collection.DeleteOne(context.Background(), filter)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *FavoritesService) GetFavorites(userID string) ([]models.Favorite, error) {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
}
|
||||
|
||||
cursor, err := collection.Find(context.Background(), filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
|
||||
var favorites []models.Favorite
|
||||
err = cursor.All(context.Background(), &favorites)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Возвращаем пустой массив вместо nil если нет избранных
|
||||
if favorites == nil {
|
||||
favorites = []models.Favorite{}
|
||||
}
|
||||
|
||||
return favorites, nil
|
||||
}
|
||||
|
||||
func (s *FavoritesService) IsFavorite(userID, mediaID, mediaType string) (bool, error) {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var favorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&favorite)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type FavoritesService struct {
|
||||
db *mongo.Database
|
||||
tmdb *TMDBService
|
||||
}
|
||||
|
||||
func NewFavoritesService(db *mongo.Database, tmdb *TMDBService) *FavoritesService {
|
||||
return &FavoritesService{
|
||||
db: db,
|
||||
tmdb: tmdb,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *FavoritesService) AddToFavorites(userID, mediaID, mediaType string) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
// Проверяем, не добавлен ли уже в избранное
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var existingFavorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&existingFavorite)
|
||||
if err == nil {
|
||||
// Уже в избранном
|
||||
return nil
|
||||
}
|
||||
|
||||
var title, posterPath string
|
||||
|
||||
// Получаем информацию из TMDB в зависимости от типа медиа
|
||||
mediaIDInt, err := strconv.Atoi(mediaID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid media ID: %s", mediaID)
|
||||
}
|
||||
|
||||
if mediaType == "movie" {
|
||||
movie, err := s.tmdb.GetMovie(mediaIDInt, "en-US")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title = movie.Title
|
||||
posterPath = movie.PosterPath
|
||||
} else if mediaType == "tv" {
|
||||
tv, err := s.tmdb.GetTVShow(mediaIDInt, "en-US")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title = tv.Name
|
||||
posterPath = tv.PosterPath
|
||||
} else {
|
||||
return fmt.Errorf("invalid media type: %s", mediaType)
|
||||
}
|
||||
|
||||
// Формируем полный URL для постера
|
||||
if posterPath != "" {
|
||||
posterPath = fmt.Sprintf("https://image.tmdb.org/t/p/w500%s", posterPath)
|
||||
}
|
||||
|
||||
favorite := models.Favorite{
|
||||
UserID: userID,
|
||||
MediaID: mediaID,
|
||||
MediaType: mediaType,
|
||||
Title: title,
|
||||
PosterPath: posterPath,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
_, err = collection.InsertOne(context.Background(), favorite)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddToFavoritesWithInfo adds media to favorites with provided media information
|
||||
func (s *FavoritesService) AddToFavoritesWithInfo(userID, mediaID, mediaType string, mediaInfo *models.MediaInfo) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
// Проверяем, не добавлен ли уже в избранное
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var existingFavorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&existingFavorite)
|
||||
if err == nil {
|
||||
// Уже в избранном
|
||||
return nil
|
||||
}
|
||||
|
||||
// Формируем полный URL для постера если он есть
|
||||
posterPath := mediaInfo.PosterPath
|
||||
if posterPath != "" && posterPath[0] == '/' {
|
||||
posterPath = fmt.Sprintf("https://image.tmdb.org/t/p/w500%s", posterPath)
|
||||
}
|
||||
|
||||
favorite := models.Favorite{
|
||||
UserID: userID,
|
||||
MediaID: mediaID,
|
||||
MediaType: mediaType,
|
||||
Title: mediaInfo.Title,
|
||||
PosterPath: posterPath,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
_, err = collection.InsertOne(context.Background(), favorite)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *FavoritesService) RemoveFromFavorites(userID, mediaID, mediaType string) error {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
_, err := collection.DeleteOne(context.Background(), filter)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *FavoritesService) GetFavorites(userID string) ([]models.Favorite, error) {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
}
|
||||
|
||||
cursor, err := collection.Find(context.Background(), filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
|
||||
var favorites []models.Favorite
|
||||
err = cursor.All(context.Background(), &favorites)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Возвращаем пустой массив вместо nil если нет избранных
|
||||
if favorites == nil {
|
||||
favorites = []models.Favorite{}
|
||||
}
|
||||
|
||||
return favorites, nil
|
||||
}
|
||||
|
||||
func (s *FavoritesService) IsFavorite(userID, mediaID, mediaType string) (bool, error) {
|
||||
collection := s.db.Collection("favorites")
|
||||
|
||||
filter := bson.M{
|
||||
"userId": userID,
|
||||
"mediaId": mediaID,
|
||||
"mediaType": mediaType,
|
||||
}
|
||||
|
||||
var favorite models.Favorite
|
||||
err := collection.FindOne(context.Background(), filter).Decode(&favorite)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -1,262 +1,262 @@
|
||||
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)
|
||||
}
|
||||
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 +1,425 @@
|
||||
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, "w300"),
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
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, "w300"),
|
||||
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)
|
||||
}
|
||||
|
||||
// Приоритет: PosterUrlPreview > PosterUrl
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
@@ -67,22 +68,42 @@ func (s *MovieService) GetByID(id int, language string, idType string) (*models.
|
||||
}
|
||||
|
||||
func (s *MovieService) GetPopular(page int, language, region string) (*models.TMDBResponse, error) {
|
||||
log.Printf("[GetPopular] language=%s, region=%s, page=%d", language, region, page)
|
||||
|
||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
||||
log.Printf("[GetPopular] Using Kinopoisk for language: %s", language)
|
||||
kpTop, err := s.kpService.GetTopFilms("TOP_100_POPULAR_FILMS", page)
|
||||
if err == nil {
|
||||
if err != nil {
|
||||
log.Printf("[GetPopular] Kinopoisk error: %v, falling back to TMDB", err)
|
||||
} else if kpTop != nil && len(kpTop.Films) > 0 {
|
||||
log.Printf("[GetPopular] Got %d films from Kinopoisk", len(kpTop.Films))
|
||||
return MapKPSearchToTMDBResponse(kpTop), nil
|
||||
} else {
|
||||
log.Printf("[GetPopular] Kinopoisk returned empty results, falling back to TMDB")
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[GetPopular] Using TMDB for language: %s", language)
|
||||
return s.tmdb.GetPopularMovies(page, language, region)
|
||||
}
|
||||
|
||||
func (s *MovieService) GetTopRated(page int, language, region string) (*models.TMDBResponse, error) {
|
||||
log.Printf("[GetTopRated] language=%s, region=%s, page=%d", language, region, page)
|
||||
|
||||
if ShouldUseKinopoisk(language) && s.kpService != nil {
|
||||
log.Printf("[GetTopRated] Using Kinopoisk for language: %s", language)
|
||||
kpTop, err := s.kpService.GetTopFilms("TOP_250_BEST_FILMS", page)
|
||||
if err == nil {
|
||||
if err != nil {
|
||||
log.Printf("[GetTopRated] Kinopoisk error: %v, falling back to TMDB", err)
|
||||
} else if kpTop != nil && len(kpTop.Films) > 0 {
|
||||
log.Printf("[GetTopRated] Got %d films from Kinopoisk", len(kpTop.Films))
|
||||
return MapKPSearchToTMDBResponse(kpTop), nil
|
||||
} else {
|
||||
log.Printf("[GetTopRated] Kinopoisk returned empty results, falling back to TMDB")
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[GetTopRated] Using TMDB for language: %s", language)
|
||||
return s.tmdb.GetTopRatedMovies(page, language, region)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,190 +1,190 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type ReactionsService struct {
|
||||
db *mongo.Database
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewReactionsService(db *mongo.Database) *ReactionsService {
|
||||
return &ReactionsService{
|
||||
db: db,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
var validReactions = []string{"fire", "nice", "think", "bore", "shit"}
|
||||
|
||||
// Получить счетчики реакций для медиа из внешнего API (cub.rip)
|
||||
func (s *ReactionsService) GetReactionCounts(mediaType, mediaID string) (*models.ReactionCounts, error) {
|
||||
cubID := fmt.Sprintf("%s_%s", mediaType, mediaID)
|
||||
|
||||
resp, err := s.client.Get(fmt.Sprintf("%s/reactions/get/%s", config.CubAPIBaseURL, cubID))
|
||||
if err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Result []struct {
|
||||
Type string `json:"type"`
|
||||
Counter int `json:"counter"`
|
||||
} `json:"result"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
counts := &models.ReactionCounts{}
|
||||
for _, reaction := range response.Result {
|
||||
switch reaction.Type {
|
||||
case "fire":
|
||||
counts.Fire = reaction.Counter
|
||||
case "nice":
|
||||
counts.Nice = reaction.Counter
|
||||
case "think":
|
||||
counts.Think = reaction.Counter
|
||||
case "bore":
|
||||
counts.Bore = reaction.Counter
|
||||
case "shit":
|
||||
counts.Shit = reaction.Counter
|
||||
}
|
||||
}
|
||||
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) GetMyReaction(userID, mediaType, mediaID string) (string, error) {
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
var result struct {
|
||||
Type string `bson:"type"`
|
||||
}
|
||||
err := collection.FindOne(ctx, bson.M{
|
||||
"userId": userID,
|
||||
"mediaType": mediaType,
|
||||
"mediaId": mediaID,
|
||||
}).Decode(&result)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return result.Type, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) SetReaction(userID, mediaType, mediaID, reactionType string) error {
|
||||
if !s.isValidReactionType(reactionType) {
|
||||
return fmt.Errorf("invalid reaction type")
|
||||
}
|
||||
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := collection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"userId": userID, "mediaType": mediaType, "mediaId": mediaID},
|
||||
bson.M{"$set": bson.M{"type": reactionType, "updatedAt": time.Now()}},
|
||||
options.Update().SetUpsert(true),
|
||||
)
|
||||
if err == nil {
|
||||
go s.sendReactionToCub(fmt.Sprintf("%s_%s", mediaType, mediaID), reactionType)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ReactionsService) RemoveReaction(userID, mediaType, mediaID string) error {
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := collection.DeleteOne(ctx, bson.M{
|
||||
"userId": userID,
|
||||
"mediaType": mediaType,
|
||||
"mediaId": mediaID,
|
||||
})
|
||||
|
||||
fullMediaID := fmt.Sprintf("%s_%s", mediaType, mediaID)
|
||||
go s.sendReactionToCub(fullMediaID, "remove")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Получить все реакции пользователя
|
||||
func (s *ReactionsService) GetUserReactions(userID string, limit int) ([]models.Reaction, error) {
|
||||
collection := s.db.Collection("reactions")
|
||||
|
||||
ctx := context.Background()
|
||||
cursor, err := collection.Find(ctx, bson.M{"userId": userID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
var reactions []models.Reaction
|
||||
if err := cursor.All(ctx, &reactions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reactions, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) isValidReactionType(reactionType string) bool {
|
||||
for _, valid := range validReactions {
|
||||
if valid == reactionType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Отправка реакции в cub.rip API (асинхронно)
|
||||
func (s *ReactionsService) sendReactionToCub(mediaID, reactionType string) {
|
||||
url := fmt.Sprintf("%s/reactions/set", config.CubAPIBaseURL)
|
||||
|
||||
data := map[string]string{
|
||||
"mediaId": mediaID,
|
||||
"type": reactionType,
|
||||
}
|
||||
|
||||
_, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.client.Get(fmt.Sprintf("%s?mediaId=%s&type=%s", url, mediaID, reactionType))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
fmt.Printf("Reaction sent to cub.rip: %s - %s\n", mediaID, reactionType)
|
||||
}
|
||||
}
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type ReactionsService struct {
|
||||
db *mongo.Database
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewReactionsService(db *mongo.Database) *ReactionsService {
|
||||
return &ReactionsService{
|
||||
db: db,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
var validReactions = []string{"fire", "nice", "think", "bore", "shit"}
|
||||
|
||||
// Получить счетчики реакций для медиа из внешнего API (cub.rip)
|
||||
func (s *ReactionsService) GetReactionCounts(mediaType, mediaID string) (*models.ReactionCounts, error) {
|
||||
cubID := fmt.Sprintf("%s_%s", mediaType, mediaID)
|
||||
|
||||
resp, err := s.client.Get(fmt.Sprintf("%s/reactions/get/%s", config.CubAPIBaseURL, cubID))
|
||||
if err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Result []struct {
|
||||
Type string `json:"type"`
|
||||
Counter int `json:"counter"`
|
||||
} `json:"result"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return &models.ReactionCounts{}, nil
|
||||
}
|
||||
|
||||
counts := &models.ReactionCounts{}
|
||||
for _, reaction := range response.Result {
|
||||
switch reaction.Type {
|
||||
case "fire":
|
||||
counts.Fire = reaction.Counter
|
||||
case "nice":
|
||||
counts.Nice = reaction.Counter
|
||||
case "think":
|
||||
counts.Think = reaction.Counter
|
||||
case "bore":
|
||||
counts.Bore = reaction.Counter
|
||||
case "shit":
|
||||
counts.Shit = reaction.Counter
|
||||
}
|
||||
}
|
||||
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) GetMyReaction(userID, mediaType, mediaID string) (string, error) {
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
var result struct {
|
||||
Type string `bson:"type"`
|
||||
}
|
||||
err := collection.FindOne(ctx, bson.M{
|
||||
"userId": userID,
|
||||
"mediaType": mediaType,
|
||||
"mediaId": mediaID,
|
||||
}).Decode(&result)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return result.Type, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) SetReaction(userID, mediaType, mediaID, reactionType string) error {
|
||||
if !s.isValidReactionType(reactionType) {
|
||||
return fmt.Errorf("invalid reaction type")
|
||||
}
|
||||
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := collection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"userId": userID, "mediaType": mediaType, "mediaId": mediaID},
|
||||
bson.M{"$set": bson.M{"type": reactionType, "updatedAt": time.Now()}},
|
||||
options.Update().SetUpsert(true),
|
||||
)
|
||||
if err == nil {
|
||||
go s.sendReactionToCub(fmt.Sprintf("%s_%s", mediaType, mediaID), reactionType)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ReactionsService) RemoveReaction(userID, mediaType, mediaID string) error {
|
||||
collection := s.db.Collection("reactions")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := collection.DeleteOne(ctx, bson.M{
|
||||
"userId": userID,
|
||||
"mediaType": mediaType,
|
||||
"mediaId": mediaID,
|
||||
})
|
||||
|
||||
fullMediaID := fmt.Sprintf("%s_%s", mediaType, mediaID)
|
||||
go s.sendReactionToCub(fullMediaID, "remove")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Получить все реакции пользователя
|
||||
func (s *ReactionsService) GetUserReactions(userID string, limit int) ([]models.Reaction, error) {
|
||||
collection := s.db.Collection("reactions")
|
||||
|
||||
ctx := context.Background()
|
||||
cursor, err := collection.Find(ctx, bson.M{"userId": userID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
var reactions []models.Reaction
|
||||
if err := cursor.All(ctx, &reactions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reactions, nil
|
||||
}
|
||||
|
||||
func (s *ReactionsService) isValidReactionType(reactionType string) bool {
|
||||
for _, valid := range validReactions {
|
||||
if valid == reactionType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Отправка реакции в cub.rip API (асинхронно)
|
||||
func (s *ReactionsService) sendReactionToCub(mediaID, reactionType string) {
|
||||
url := fmt.Sprintf("%s/reactions/set", config.CubAPIBaseURL)
|
||||
|
||||
data := map[string]string{
|
||||
"mediaId": mediaID,
|
||||
"type": reactionType,
|
||||
}
|
||||
|
||||
_, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := s.client.Get(fmt.Sprintf("%s?mediaId=%s&type=%s", url, mediaID, reactionType))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
fmt.Printf("Reaction sent to cub.rip: %s - %s\n", mediaID, reactionType)
|
||||
}
|
||||
}
|
||||
|
||||
1158
pkg/services/tmdb.go
1158
pkg/services/tmdb.go
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,134 +1,134 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type TVService struct {
|
||||
db *mongo.Database
|
||||
tmdb *TMDBService
|
||||
kpService *KinopoiskService
|
||||
}
|
||||
|
||||
func NewTVService(db *mongo.Database, tmdb *TMDBService, kpService *KinopoiskService) *TVService {
|
||||
return &TVService{
|
||||
db: db,
|
||||
tmdb: tmdb,
|
||||
kpService: kpService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TVService) Search(query string, page int, language string, year int) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.SearchTVShows(query, page, language, year)
|
||||
}
|
||||
|
||||
func (s *TVService) GetByID(id int, language string, idType string) (*models.TVShow, error) {
|
||||
// Строго уважаем явный id_type, без скрытого fallback на TMDB
|
||||
switch idType {
|
||||
case "kp":
|
||||
if s.kpService == nil {
|
||||
return nil, fmt.Errorf("kinopoisk service not configured")
|
||||
}
|
||||
|
||||
// Сначала пробуем как Kinopoisk ID
|
||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil && kpFilm != nil {
|
||||
// Попробуем обогатить 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) {
|
||||
return s.tmdb.GetPopularTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetTopRated(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetTopRatedTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetOnTheAir(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetOnTheAirTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetAiringToday(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetAiringTodayTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetRecommendations(id, page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetTVRecommendations(id, page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetSimilar(id, page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetSimilarTVShows(id, page, language)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
type TVService struct {
|
||||
db *mongo.Database
|
||||
tmdb *TMDBService
|
||||
kpService *KinopoiskService
|
||||
}
|
||||
|
||||
func NewTVService(db *mongo.Database, tmdb *TMDBService, kpService *KinopoiskService) *TVService {
|
||||
return &TVService{
|
||||
db: db,
|
||||
tmdb: tmdb,
|
||||
kpService: kpService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TVService) Search(query string, page int, language string, year int) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.SearchTVShows(query, page, language, year)
|
||||
}
|
||||
|
||||
func (s *TVService) GetByID(id int, language string, idType string) (*models.TVShow, error) {
|
||||
// Строго уважаем явный id_type, без скрытого fallback на TMDB
|
||||
switch idType {
|
||||
case "kp":
|
||||
if s.kpService == nil {
|
||||
return nil, fmt.Errorf("kinopoisk service not configured")
|
||||
}
|
||||
|
||||
// Сначала пробуем как Kinopoisk ID
|
||||
if kpFilm, err := s.kpService.GetFilmByKinopoiskId(id); err == nil && kpFilm != nil {
|
||||
// Попробуем обогатить 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) {
|
||||
return s.tmdb.GetPopularTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetTopRated(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetTopRatedTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetOnTheAir(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetOnTheAirTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetAiringToday(page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetAiringTodayTVShows(page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetRecommendations(id, page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetTVRecommendations(id, page, language)
|
||||
}
|
||||
|
||||
func (s *TVService) GetSimilar(id, page int, language string) (*models.TMDBTVResponse, error) {
|
||||
return s.tmdb.GetSimilarTVShows(id, page, language)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,291 +1,291 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
const tmdbImageBase = "https://image.tmdb.org/t/p"
|
||||
|
||||
func BuildAPIImageProxyURL(pathOrURL string, size string) string {
|
||||
if strings.TrimSpace(pathOrURL) == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Extract type and ID from Kinopoisk URL pattern
|
||||
// https://kinopoiskapiunofficial.tech/images/posters/{type}/{id}.jpg
|
||||
if strings.Contains(pathOrURL, "kinopoiskapiunofficial.tech") {
|
||||
parts := strings.Split(pathOrURL, "/")
|
||||
if len(parts) >= 2 {
|
||||
// Find "posters" index
|
||||
for i, part := range parts {
|
||||
if part == "posters" && i+2 < len(parts) {
|
||||
imageType := parts[i+1] // kp, kp_small, kp_big
|
||||
idWithExt := parts[i+2] // 326.jpg
|
||||
imageID := strings.TrimSuffix(idWithExt, ".jpg")
|
||||
|
||||
// Map size to type if needed
|
||||
if size == "w1280" || size == "original" {
|
||||
imageType = "kp_big"
|
||||
} else if size == "w300" || size == "w185" {
|
||||
imageType = "kp_small"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("/api/v1/images/%s/%s", imageType, imageID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Yandex/other absolute URLs - return empty for now
|
||||
if strings.HasPrefix(pathOrURL, "http://") || strings.HasPrefix(pathOrURL, "https://") {
|
||||
return ""
|
||||
}
|
||||
|
||||
// TMDB relative path - not supported in new format
|
||||
return ""
|
||||
}
|
||||
|
||||
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, "w300"),
|
||||
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, "w300"),
|
||||
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, "w300"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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, "w300")
|
||||
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, "w300")
|
||||
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
|
||||
}
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"neomovies-api/pkg/models"
|
||||
)
|
||||
|
||||
const tmdbImageBase = "https://image.tmdb.org/t/p"
|
||||
|
||||
func BuildAPIImageProxyURL(pathOrURL string, size string) string {
|
||||
if strings.TrimSpace(pathOrURL) == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Extract type and ID from Kinopoisk URL pattern
|
||||
// https://kinopoiskapiunofficial.tech/images/posters/{type}/{id}.jpg
|
||||
if strings.Contains(pathOrURL, "kinopoiskapiunofficial.tech") {
|
||||
parts := strings.Split(pathOrURL, "/")
|
||||
if len(parts) >= 2 {
|
||||
// Find "posters" index
|
||||
for i, part := range parts {
|
||||
if part == "posters" && i+2 < len(parts) {
|
||||
imageType := parts[i+1] // kp, kp_small, kp_big
|
||||
idWithExt := parts[i+2] // 326.jpg
|
||||
imageID := strings.TrimSuffix(idWithExt, ".jpg")
|
||||
|
||||
// Map size to type if needed
|
||||
if size == "w1280" || size == "original" {
|
||||
imageType = "kp_big"
|
||||
} else if size == "w300" || size == "w185" {
|
||||
imageType = "kp_small"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("/api/v1/images/%s/%s", imageType, imageID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Yandex/other absolute URLs - return empty for now
|
||||
if strings.HasPrefix(pathOrURL, "http://") || strings.HasPrefix(pathOrURL, "https://") {
|
||||
return ""
|
||||
}
|
||||
|
||||
// TMDB relative path - not supported in new format
|
||||
return ""
|
||||
}
|
||||
|
||||
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, "w300"),
|
||||
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, "w300"),
|
||||
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, "w300"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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, "w300")
|
||||
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, "w300")
|
||||
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