Add metadata management for shows: implement metadata retrieval, application, and updates in the API and UI. Enhance Show and ShowDto models to include metadata fields, and update the database schema accordingly. Introduce new endpoints for metadata operations and integrate metadata display in the ShowDetail component.

This commit is contained in:
Leonid Pershin
2026-07-25 09:07:55 +03:00
parent ba023bc416
commit 0d2dee815e
42 changed files with 2271 additions and 4 deletions
+7
View File
@@ -63,6 +63,13 @@ Media__LoudnessTargetLufs=-16
# Меняй при правке ЛОГИКИ рендера, чтобы пересобрать уже отрендеренные заставки.
# Bumpers__TemplateVersion=1
# ── Метаданные шоу/серий (TMDb / OMDb) ─────────────────────────────────────
# Ключи бесплатные: TMDb — themoviedb.org (Settings → API, v3 key), OMDb — omdbapi.com.
# Без ключа источник просто не показывается в админке (ручной режим работает всегда).
Metadata__Language=ru-RU
Metadata__Tmdb__ApiKey=
Metadata__Omdb__ApiKey=
# ── ASP.NET Core ──────────────────────────────────────────────────────────
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_HTTP_PORTS=8080
+1
View File
@@ -26,6 +26,7 @@
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.10" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.21.0" />
<PackageVersion Include="LiteCqrs.Net" Version="1.0.1" />
@@ -0,0 +1,161 @@
using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Api.Common;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Metadata;
using TeleWave.Application.Metadata.ApplyShowMetadata;
using TeleWave.Application.Metadata.ClearShowMetadata;
using TeleWave.Application.Metadata.GetProviders;
using TeleWave.Application.Metadata.SearchShows;
using TeleWave.Application.Metadata.SetShowPoster;
using TeleWave.Application.Metadata.UpdateShowMetadata;
using TeleWave.Infrastructure.Identity;
namespace TeleWave.Api.Endpoints;
public static class MetadataEndpoints
{
private const long MaxPosterBytes = 10L * 1024 * 1024; // 10 МБ
private static readonly IReadOnlySet<string> PosterExtensions = new HashSet<string>(
StringComparer.OrdinalIgnoreCase
)
{
".jpg",
".jpeg",
".png",
".webp",
};
public static IEndpointRouteBuilder MapMetadataEndpoints(this IEndpointRouteBuilder app)
{
var admin = app.MapGroup("/api/admin/metadata")
.WithTags("Admin.Metadata")
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
admin.MapGet("/providers", GetProviders).Produces<IReadOnlyList<string>>();
admin.MapGet("/search", Search).Produces<IReadOnlyList<MetadataCandidate>>();
admin.MapPost("/shows/{showId:guid}/apply", Apply).Produces(StatusCodes.Status204NoContent);
admin.MapPut("/shows/{showId:guid}", Update).Produces(StatusCodes.Status204NoContent);
admin.MapDelete("/shows/{showId:guid}", Clear).Produces(StatusCodes.Status204NoContent);
admin.MapPut("/shows/{showId:guid}/poster", UploadPoster).Produces(StatusCodes.Status204NoContent);
// Постеры отдаём публично (просто картинки, id не угадать) — чтобы работал <img src>.
app.MapGet("/api/metadata/shows/{showId:guid}/poster", ServePoster)
.WithTags("Metadata")
.Produces(StatusCodes.Status200OK);
return app;
}
private static async Task<IResult> GetProviders(ISender sender, CancellationToken cancellationToken)
{
var providers = await sender.Send(new GetMetadataProvidersQuery(), cancellationToken);
return Results.Ok(providers);
}
private static async Task<IResult> Search(
string provider,
string query,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new SearchShowMetadataQuery(provider, query), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> Apply(
Guid showId,
ApplyMetadataBody body,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(
new ApplyShowMetadataCommand(showId, body.Provider, body.ExternalId),
cancellationToken
);
return result.ToHttpResult();
}
private static async Task<IResult> Update(
Guid showId,
UpdateMetadataBody body,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(
new UpdateShowMetadataCommand(showId, body.Description, body.Year),
cancellationToken
);
return result.ToHttpResult();
}
private static async Task<IResult> Clear(
Guid showId,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new ClearShowMetadataCommand(showId), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> UploadPoster(
Guid showId,
string fileName,
HttpRequest request,
IMetadataImageStore imageStore,
ISender sender,
CancellationToken cancellationToken
)
{
var ext = Path.GetExtension(fileName).ToLowerInvariant();
if (
request.ContentLength is > MaxPosterBytes or 0 or null
|| !PosterExtensions.Contains(ext)
)
return MetadataErrors.InvalidPoster.ToProblem();
var relative = await imageStore.SaveShowPosterAsync(showId, ext, request.Body, cancellationToken);
var result = await sender.Send(new SetShowPosterCommand(showId, relative), cancellationToken);
if (!result.IsSuccess)
imageStore.DeleteShowImages(showId);
return result.ToHttpResult();
}
private static async Task<IResult> ServePoster(
Guid showId,
IAppDbContext dbContext,
IMetadataImageStore imageStore,
CancellationToken cancellationToken
)
{
var path = await dbContext.Shows.AsNoTracking()
.Where(s => s.Id == showId)
.Select(s => s.PosterPath)
.FirstOrDefaultAsync(cancellationToken);
if (string.IsNullOrEmpty(path))
return Results.NotFound();
var abs = imageStore.ResolveAbsolutePath(path);
if (abs is null)
return Results.NotFound();
return Results.File(abs, ContentTypeFor(Path.GetExtension(abs)));
}
private static string ContentTypeFor(string extension) =>
extension.ToLowerInvariant() switch
{
".png" => "image/png",
".webp" => "image/webp",
_ => "image/jpeg",
};
}
public sealed record ApplyMetadataBody(string Provider, string ExternalId);
public sealed record UpdateMetadataBody(string? Description, int? Year);
+1
View File
@@ -118,6 +118,7 @@ app.MapChannelEndpoints();
app.MapStreamingEndpoints();
app.MapMaintenanceEndpoints();
app.MapSettingsEndpoints();
app.MapMetadataEndpoints();
// Раздача статики SPA из wwwroot + fallback на index.html для клиентских маршрутов.
app.UseDefaultFiles();
+14
View File
@@ -41,6 +41,20 @@
"FontFileSerif": "/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf",
"TemplateVersion": 1
},
"Metadata": {
"Language": "ru-RU",
"Tmdb": {
"ApiKey": "",
"BaseUrl": "https://api.themoviedb.org/3",
"ImageBaseUrl": "https://image.tmdb.org/t/p",
"PosterSize": "w500",
"StillSize": "w300"
},
"Omdb": {
"ApiKey": "",
"BaseUrl": "https://www.omdbapi.com"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
@@ -0,0 +1,28 @@
namespace TeleWave.Application.Common.Interfaces;
/// <summary>
/// Локальное хранилище картинок метаданных (постеры/кадры) под metadata/ в корне хранилища. Скачивает
/// изображения к себе, чтобы не зависеть от внешнего CDN на этапе показа.
/// </summary>
public interface IMetadataImageStore
{
/// <summary>Скачивает постер по URL и сохраняет для шоу. Возвращает относительный путь или null при ошибке.</summary>
Task<string?> DownloadShowPosterAsync(
Guid showId,
string url,
CancellationToken cancellationToken
);
/// <summary>Сохраняет загруженный вручную постер шоу. Возвращает относительный путь.</summary>
Task<string> SaveShowPosterAsync(
Guid showId,
string extension,
Stream content,
CancellationToken cancellationToken
);
void DeleteShowImages(Guid showId);
/// <summary>Абсолютный путь к файлу по относительному (с защитой от traversal) или null, если вне корня.</summary>
string? ResolveAbsolutePath(string relativePath);
}
@@ -0,0 +1,33 @@
using TeleWave.Application.Metadata;
namespace TeleWave.Application.Common.Interfaces;
/// <summary>Источник метаданных о шоу/сериях (TMDb, OMDb). Реализация ходит во внешний API.</summary>
public interface IMetadataProvider
{
/// <summary>Ключ источника: «tmdb», «omdb».</summary>
string Key { get; }
Task<IReadOnlyList<MetadataCandidate>> SearchShowsAsync(
string query,
CancellationToken cancellationToken
);
Task<ShowMetadata?> GetShowAsync(string externalId, CancellationToken cancellationToken);
Task<EpisodeMetadata?> GetEpisodeAsync(
string externalId,
int season,
int episode,
CancellationToken cancellationToken
);
}
/// <summary>Резолвит провайдер по ключу и перечисляет реально настроенные (с API-ключом) источники.</summary>
public interface IMetadataProviderResolver
{
IMetadataProvider? Resolve(string key);
/// <summary>Ключи источников, у которых задан API-ключ (доступны в UI).</summary>
IReadOnlyList<string> AvailableKeys { get; }
}
@@ -45,7 +45,17 @@ public sealed class GetShowQueryHandler(IAppDbContext dbContext)
.ToList();
return Result.Success(
new ShowDto(show.Id, show.Name, show.Kind, show.Description, episodeDtos)
new ShowDto(
show.Id,
show.Name,
show.Kind,
show.Description,
show.MetadataProvider,
show.MetadataExternalId,
show.Year,
show.PosterPath is not null,
episodeDtos
)
);
}
}
@@ -32,7 +32,16 @@ public sealed class ListShowsQueryHandler(IAppDbContext dbContext)
.Where(season => season is not null)
.Distinct()
.Count();
return new ShowSummaryDto(s.Id, s.Name, s.Kind, s.Episodes.Count, seasons, s.CreatedAt);
return new ShowSummaryDto(
s.Id,
s.Name,
s.Kind,
s.Episodes.Count,
seasons,
s.Year,
s.PosterPath is not null,
s.CreatedAt
);
})
.ToList();
}
@@ -9,6 +9,8 @@ public sealed record ShowSummaryDto(
ShowKind Kind,
int EpisodeCount,
int SeasonCount,
int? Year,
bool HasPoster,
DateTimeOffset CreatedAt
);
@@ -26,5 +28,9 @@ public sealed record ShowDto(
string Name,
ShowKind Kind,
string? Description,
string? MetadataProvider,
string? MetadataExternalId,
int? Year,
bool HasPoster,
IReadOnlyList<EpisodeDto> Episodes
);
@@ -0,0 +1,8 @@
using LiteCqrs;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.ApplyShowMetadata;
/// <summary>Применить к шоу выбранный результат из источника метаданных (с загрузкой постера).</summary>
public sealed record ApplyShowMetadataCommand(Guid ShowId, string Provider, string ExternalId)
: ICommand<Result>;
@@ -0,0 +1,46 @@
using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Application.Library;
namespace TeleWave.Application.Metadata.ApplyShowMetadata;
public sealed class ApplyShowMetadataCommandHandler(
IAppDbContext dbContext,
IMetadataProviderResolver resolver,
IMetadataImageStore imageStore
) : ICommandHandler<ApplyShowMetadataCommand, Result>
{
public async Task<Result> Handle(
ApplyShowMetadataCommand command,
CancellationToken cancellationToken
)
{
var show = await dbContext.Shows.FirstOrDefaultAsync(
s => s.Id == command.ShowId,
cancellationToken
);
if (show is null)
return Result.Failure(ShowErrors.NotFound);
var provider = resolver.Resolve(command.Provider);
if (provider is null)
return Result.Failure(MetadataErrors.ProviderNotAvailable);
var meta = await provider.GetShowAsync(command.ExternalId, cancellationToken);
if (meta is null)
return Result.Failure(MetadataErrors.NotFound);
string? posterPath = null;
if (!string.IsNullOrEmpty(meta.PosterUrl))
posterPath = await imageStore.DownloadShowPosterAsync(
show.Id,
meta.PosterUrl,
cancellationToken
);
show.ApplyMetadata(command.Provider, meta.ExternalId, meta.Overview, meta.Year, posterPath);
return Result.Success();
}
}
@@ -0,0 +1,6 @@
using LiteCqrs;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.ClearShowMetadata;
public sealed record ClearShowMetadataCommand(Guid ShowId) : ICommand<Result>;
@@ -0,0 +1,30 @@
using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Application.Library;
namespace TeleWave.Application.Metadata.ClearShowMetadata;
public sealed class ClearShowMetadataCommandHandler(
IAppDbContext dbContext,
IMetadataImageStore imageStore
) : ICommandHandler<ClearShowMetadataCommand, Result>
{
public async Task<Result> Handle(
ClearShowMetadataCommand command,
CancellationToken cancellationToken
)
{
var show = await dbContext.Shows.FirstOrDefaultAsync(
s => s.Id == command.ShowId,
cancellationToken
);
if (show is null)
return Result.Failure(ShowErrors.NotFound);
imageStore.DeleteShowImages(show.Id);
show.ClearMetadata();
return Result.Success();
}
}
@@ -0,0 +1,6 @@
using LiteCqrs;
namespace TeleWave.Application.Metadata.GetProviders;
/// <summary>Список доступных источников метаданных (у которых задан API-ключ).</summary>
public sealed record GetMetadataProvidersQuery : IQuery<IReadOnlyList<string>>;
@@ -0,0 +1,13 @@
using LiteCqrs;
using TeleWave.Application.Common.Interfaces;
namespace TeleWave.Application.Metadata.GetProviders;
public sealed class GetMetadataProvidersQueryHandler(IMetadataProviderResolver resolver)
: IQueryHandler<GetMetadataProvidersQuery, IReadOnlyList<string>>
{
public Task<IReadOnlyList<string>> Handle(
GetMetadataProvidersQuery query,
CancellationToken cancellationToken
) => Task.FromResult(resolver.AvailableKeys);
}
@@ -0,0 +1,21 @@
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata;
public static class MetadataErrors
{
public static readonly Error ProviderNotAvailable = Error.Validation(
"Metadata.ProviderNotAvailable",
"Источник метаданных недоступен — не задан API-ключ."
);
public static readonly Error NotFound = Error.NotFound(
"Metadata.NotFound",
"Метаданные по этому источнику не найдены."
);
public static readonly Error InvalidPoster = Error.Validation(
"Metadata.InvalidPoster",
"Недопустимый файл постера (формат или размер)."
);
}
@@ -0,0 +1,27 @@
namespace TeleWave.Application.Metadata;
/// <summary>Кандидат из поиска по названию в источнике метаданных.</summary>
public sealed record MetadataCandidate(
string ExternalId,
string Title,
int? Year,
string? Overview,
string? PosterUrl
);
/// <summary>Метаданные шоу из источника (PosterUrl — полный URL, скачивается локально при применении).</summary>
public sealed record ShowMetadata(
string ExternalId,
string Title,
int? Year,
string? Overview,
string? PosterUrl
);
/// <summary>Метаданные серии (для этапа 2).</summary>
public sealed record EpisodeMetadata(
string Title,
string? Overview,
string? StillUrl,
DateOnly? AirDate
);
@@ -0,0 +1,7 @@
using LiteCqrs;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.SearchShows;
public sealed record SearchShowMetadataQuery(string Provider, string Query)
: IQuery<Result<IReadOnlyList<MetadataCandidate>>>;
@@ -0,0 +1,25 @@
using LiteCqrs;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.SearchShows;
public sealed class SearchShowMetadataQueryHandler(IMetadataProviderResolver resolver)
: IQueryHandler<SearchShowMetadataQuery, Result<IReadOnlyList<MetadataCandidate>>>
{
public async Task<Result<IReadOnlyList<MetadataCandidate>>> Handle(
SearchShowMetadataQuery query,
CancellationToken cancellationToken
)
{
var provider = resolver.Resolve(query.Provider);
if (provider is null)
return Result.Failure<IReadOnlyList<MetadataCandidate>>(MetadataErrors.ProviderNotAvailable);
if (string.IsNullOrWhiteSpace(query.Query))
return Result.Success<IReadOnlyList<MetadataCandidate>>([]);
var results = await provider.SearchShowsAsync(query.Query, cancellationToken);
return Result.Success(results);
}
}
@@ -0,0 +1,7 @@
using LiteCqrs;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.SetShowPoster;
/// <summary>Привязать к шоу загруженный вручную постер (файл уже сохранён хранилищем).</summary>
public sealed record SetShowPosterCommand(Guid ShowId, string PosterPath) : ICommand<Result>;
@@ -0,0 +1,27 @@
using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Application.Library;
namespace TeleWave.Application.Metadata.SetShowPoster;
public sealed class SetShowPosterCommandHandler(IAppDbContext dbContext)
: ICommandHandler<SetShowPosterCommand, Result>
{
public async Task<Result> Handle(
SetShowPosterCommand command,
CancellationToken cancellationToken
)
{
var show = await dbContext.Shows.FirstOrDefaultAsync(
s => s.Id == command.ShowId,
cancellationToken
);
if (show is null)
return Result.Failure(ShowErrors.NotFound);
show.SetPosterPath(command.PosterPath);
return Result.Success();
}
}
@@ -0,0 +1,8 @@
using LiteCqrs;
using TeleWave.Application.Common.Models;
namespace TeleWave.Application.Metadata.UpdateShowMetadata;
/// <summary>Ручная правка метаданных шоу (описание/год) без внешнего источника.</summary>
public sealed record UpdateShowMetadataCommand(Guid ShowId, string? Description, int? Year)
: ICommand<Result>;
@@ -0,0 +1,27 @@
using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Application.Library;
namespace TeleWave.Application.Metadata.UpdateShowMetadata;
public sealed class UpdateShowMetadataCommandHandler(IAppDbContext dbContext)
: ICommandHandler<UpdateShowMetadataCommand, Result>
{
public async Task<Result> Handle(
UpdateShowMetadataCommand command,
CancellationToken cancellationToken
)
{
var show = await dbContext.Shows.FirstOrDefaultAsync(
s => s.Id == command.ShowId,
cancellationToken
);
if (show is null)
return Result.Failure(ShowErrors.NotFound);
show.UpdateMetadataManual(command.Description, command.Year);
return Result.Success();
}
}
@@ -15,6 +15,18 @@ public class Show
public ShowKind Kind { get; private set; }
public DateTimeOffset CreatedAt { get; private set; }
// ── Метаданные (TMDb/OMDb/вручную) ──
/// <summary>Источник метаданных: «tmdb»/«omdb»/«manual» или null, если не заданы.</summary>
public string? MetadataProvider { get; private set; }
/// <summary>Идентификатор шоу во внешнем источнике (для довыгрузки серий).</summary>
public string? MetadataExternalId { get; private set; }
public int? Year { get; private set; }
/// <summary>Относительный путь локального постера от корня хранилища или null.</summary>
public string? PosterPath { get; private set; }
/// <summary>Серии шоу (backing-field для EF). Порядок показа — по <see cref="ShowEpisode.Position"/>;
/// потребители сортируют явно (см. загрузчик планировщика).</summary>
public IReadOnlyList<ShowEpisode> Episodes => _episodes;
@@ -56,4 +68,44 @@ public class Show
}
public bool CanAddEpisode => Kind != ShowKind.Single || _episodes.Count == 0;
/// <summary>Применить метаданные из внешнего источника. Постер (уже скачанный локально) может быть null.</summary>
public void ApplyMetadata(
string provider,
string externalId,
string? description,
int? year,
string? posterPath
)
{
MetadataProvider = provider;
MetadataExternalId = externalId;
if (!string.IsNullOrWhiteSpace(description))
Description = description;
Year = year;
if (posterPath is not null)
PosterPath = posterPath;
}
/// <summary>Ручная правка метаданных (без внешнего источника).</summary>
public void UpdateMetadataManual(string? description, int? year)
{
MetadataProvider = "manual";
MetadataExternalId = null;
Description = description;
Year = year;
}
/// <summary>Задать/снять локальный постер (после скачивания/загрузки/удаления файла).</summary>
public void SetPosterPath(string? path) => PosterPath = path;
/// <summary>Сбросить все метаданные и постер (файл удаляет вызывающий по старому PosterPath).</summary>
public void ClearMetadata()
{
MetadataProvider = null;
MetadataExternalId = null;
Year = null;
PosterPath = null;
Description = null;
}
}
@@ -13,6 +13,7 @@ using TeleWave.Domain.Broadcast.Scheduling;
using TeleWave.Infrastructure.Broadcast;
using TeleWave.Infrastructure.Identity;
using TeleWave.Infrastructure.Media;
using TeleWave.Infrastructure.Metadata;
using TeleWave.Infrastructure.Persistence;
using TeleWave.Infrastructure.Settings;
using TeleWave.Infrastructure.Streaming;
@@ -96,10 +97,22 @@ public static class DependencyInjection
AddMedia(services, configuration);
AddBroadcast(services, configuration);
AddMetadata(services, configuration);
return services;
}
/// <summary>Метаданные шоу/серий: провайдеры TMDb/OMDb, резолвер, локальное хранилище картинок.</summary>
private static void AddMetadata(IServiceCollection services, IConfiguration configuration)
{
services.Configure<MetadataOptions>(configuration.GetSection(MetadataOptions.SectionName));
services.AddHttpClient("metadata", client => client.Timeout = TimeSpan.FromSeconds(15));
services.AddSingleton<IMetadataProvider, TmdbMetadataProvider>();
services.AddSingleton<IMetadataProvider, OmdbMetadataProvider>();
services.AddSingleton<IMetadataProviderResolver, MetadataProviderResolver>();
services.AddSingleton<IMetadataImageStore, MetadataImageStore>();
}
/// <summary>Планировщик расписания: генератор, источник случайности и фоновый сервис горизонта.</summary>
private static void AddBroadcast(IServiceCollection services, IConfiguration configuration)
{
@@ -18,6 +18,7 @@ public sealed class MediaPathResolver
OriginalsDir = Path.Combine(_root, "originals");
AssetsDir = Path.Combine(_root, "assets");
BumpersDir = Path.Combine(_root, "bumpers");
MetadataDir = Path.Combine(_root, "metadata");
}
public string InboxDir { get; }
@@ -28,6 +29,9 @@ public sealed class MediaPathResolver
/// <summary>Сырые файлы шаблонов заставок (фон/музыка) по каналам — не режутся на HLS.</summary>
public string BumpersDir { get; }
/// <summary>Картинки метаданных (постеры/кадры), скачанные локально.</summary>
public string MetadataDir { get; }
public void EnsureDirectories()
{
Directory.CreateDirectory(InboxDir);
@@ -35,6 +39,33 @@ public sealed class MediaPathResolver
Directory.CreateDirectory(OriginalsDir);
Directory.CreateDirectory(AssetsDir);
Directory.CreateDirectory(BumpersDir);
Directory.CreateDirectory(MetadataDir);
}
public string MetadataShowDir(Guid showId) =>
EnsureWithinRoot(Path.Combine(MetadataDir, "shows", showId.ToString("N")));
/// <summary>Абсолютный путь к файлу постера шоу (extension — с точкой).</summary>
public string MetadataShowPosterPath(Guid showId, string extension) =>
EnsureWithinRoot(
Path.Combine(MetadataDir, "shows", showId.ToString("N"), "poster" + extension)
);
/// <summary>Относительный путь постера от корня (для хранения в БД и отдачи).</summary>
public string MetadataShowPosterRelative(Guid showId, string extension) =>
$"metadata/shows/{showId:N}/poster{extension}";
/// <summary>Абсолютный путь по относительному (с защитой от traversal) или null, если вне корня.</summary>
public string? ResolveRelative(string relativePath)
{
try
{
return EnsureWithinRoot(Path.Combine(_root, relativePath));
}
catch (UnauthorizedAccessException)
{
return null;
}
}
public string BumperChannelDir(Guid channelId) =>
@@ -0,0 +1,88 @@
using TeleWave.Application.Common.Interfaces;
using TeleWave.Infrastructure.Media;
namespace TeleWave.Infrastructure.Metadata;
/// <summary>Скачивает и хранит картинки метаданных локально под metadata/shows/{id}.</summary>
public sealed class MetadataImageStore(MediaPathResolver paths, IHttpClientFactory httpFactory)
: IMetadataImageStore
{
public async Task<string?> DownloadShowPosterAsync(
Guid showId,
string url,
CancellationToken cancellationToken
)
{
try
{
var client = httpFactory.CreateClient("metadata");
using var response = await client.GetAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode)
return null;
var ext = ExtensionFor(url, response.Content.Headers.ContentType?.MediaType);
await using var content = await response.Content.ReadAsStreamAsync(cancellationToken);
return await WritePosterAsync(showId, ext, content, cancellationToken);
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException)
{
return null;
}
}
public Task<string> SaveShowPosterAsync(
Guid showId,
string extension,
Stream content,
CancellationToken cancellationToken
) => WritePosterAsync(showId, NormalizeExtension(extension), content, cancellationToken);
public void DeleteShowImages(Guid showId)
{
var dir = paths.MetadataShowDir(showId);
if (Directory.Exists(dir))
Directory.Delete(dir, recursive: true);
}
public string? ResolveAbsolutePath(string relativePath)
{
var abs = paths.ResolveRelative(relativePath);
return abs is not null && File.Exists(abs) ? abs : null;
}
private async Task<string> WritePosterAsync(
Guid showId,
string ext,
Stream content,
CancellationToken cancellationToken
)
{
var dir = paths.MetadataShowDir(showId);
Directory.CreateDirectory(dir);
RemoveExisting(dir, "poster");
var abs = paths.MetadataShowPosterPath(showId, ext);
await using (var fs = File.Create(abs))
await content.CopyToAsync(fs, cancellationToken);
return paths.MetadataShowPosterRelative(showId, ext);
}
private static void RemoveExisting(string dir, string baseName)
{
foreach (var file in Directory.EnumerateFiles(dir, baseName + ".*"))
File.Delete(file);
}
private static string ExtensionFor(string url, string? mediaType) =>
mediaType switch
{
"image/png" => ".png",
"image/webp" => ".webp",
"image/jpeg" => ".jpg",
_ => Path.GetExtension(new Uri(url).AbsolutePath) is { Length: > 1 } e ? e.ToLowerInvariant() : ".jpg",
};
private static string NormalizeExtension(string extension) =>
extension.StartsWith('.') ? extension.ToLowerInvariant() : "." + extension.ToLowerInvariant();
}
@@ -0,0 +1,27 @@
namespace TeleWave.Infrastructure.Metadata;
public sealed class MetadataOptions
{
public const string SectionName = "Metadata";
/// <summary>Язык метаданных (ISO, например «ru-RU»).</summary>
public string Language { get; init; } = "ru-RU";
public TmdbOptions Tmdb { get; init; } = new();
public OmdbOptions Omdb { get; init; } = new();
}
public sealed class TmdbOptions
{
public string ApiKey { get; init; } = string.Empty;
public string BaseUrl { get; init; } = "https://api.themoviedb.org/3";
public string ImageBaseUrl { get; init; } = "https://image.tmdb.org/t/p";
public string PosterSize { get; init; } = "w500";
public string StillSize { get; init; } = "w300";
}
public sealed class OmdbOptions
{
public string ApiKey { get; init; } = string.Empty;
public string BaseUrl { get; init; } = "https://www.omdbapi.com";
}
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Options;
using TeleWave.Application.Common.Interfaces;
namespace TeleWave.Infrastructure.Metadata;
/// <summary>Резолвит провайдеры по ключу; доступными считает только те, у кого задан API-ключ.</summary>
public sealed class MetadataProviderResolver : IMetadataProviderResolver
{
private readonly Dictionary<string, IMetadataProvider> _byKey;
private readonly List<string> _available = new();
public MetadataProviderResolver(
IEnumerable<IMetadataProvider> providers,
IOptions<MetadataOptions> options
)
{
_byKey = providers.ToDictionary(p => p.Key, StringComparer.OrdinalIgnoreCase);
var opt = options.Value;
if (_byKey.ContainsKey("tmdb") && !string.IsNullOrWhiteSpace(opt.Tmdb.ApiKey))
_available.Add("tmdb");
if (_byKey.ContainsKey("omdb") && !string.IsNullOrWhiteSpace(opt.Omdb.ApiKey))
_available.Add("omdb");
}
public IMetadataProvider? Resolve(string key) =>
_available.Contains(key, StringComparer.OrdinalIgnoreCase)
&& _byKey.TryGetValue(key, out var provider)
? provider
: null;
public IReadOnlyList<string> AvailableKeys => _available;
}
@@ -0,0 +1,122 @@
using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Options;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Metadata;
namespace TeleWave.Infrastructure.Metadata;
/// <summary>Провайдер метаданных OMDb (omdbapi.com, данные IMDb). Требует API-ключ.</summary>
public sealed class OmdbMetadataProvider(IHttpClientFactory httpFactory, IOptions<MetadataOptions> options)
: IMetadataProvider
{
private readonly OmdbOptions _omdb = options.Value.Omdb;
public string Key => "omdb";
public async Task<IReadOnlyList<MetadataCandidate>> SearchShowsAsync(
string query,
CancellationToken cancellationToken
)
{
var url = $"{_omdb.BaseUrl}/?apikey={_omdb.ApiKey}&type=series&s={Uri.EscapeDataString(query)}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null || !doc.RootElement.TryGetProperty("Search", out var search))
return [];
var list = new List<MetadataCandidate>();
foreach (var item in search.EnumerateArray())
{
var id = Clean(GetString(item, "imdbID"));
if (id is null)
continue;
list.Add(
new MetadataCandidate(
id,
Clean(GetString(item, "Title")) ?? "—",
YearFrom(GetString(item, "Year")),
null,
Clean(GetString(item, "Poster"))
)
);
}
return list;
}
public async Task<ShowMetadata?> GetShowAsync(string externalId, CancellationToken cancellationToken)
{
var url = $"{_omdb.BaseUrl}/?apikey={_omdb.ApiKey}&i={Uri.EscapeDataString(externalId)}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null || !IsResponseTrue(doc.RootElement))
return null;
var root = doc.RootElement;
return new ShowMetadata(
externalId,
Clean(GetString(root, "Title")) ?? "—",
YearFrom(GetString(root, "Year")),
Clean(GetString(root, "Plot")),
Clean(GetString(root, "Poster"))
);
}
public async Task<EpisodeMetadata?> GetEpisodeAsync(
string externalId,
int season,
int episode,
CancellationToken cancellationToken
)
{
var url =
$"{_omdb.BaseUrl}/?apikey={_omdb.ApiKey}&i={Uri.EscapeDataString(externalId)}"
+ $"&Season={season}&Episode={episode}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null || !IsResponseTrue(doc.RootElement))
return null;
var root = doc.RootElement;
return new EpisodeMetadata(
Clean(GetString(root, "Title")) ?? "—",
Clean(GetString(root, "Plot")),
Clean(GetString(root, "Poster")),
DateFrom(GetString(root, "Released"))
);
}
private async Task<JsonDocument?> GetJsonAsync(string url, CancellationToken cancellationToken)
{
var client = httpFactory.CreateClient("metadata");
try
{
using var response = await client.GetAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode)
return null;
var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
}
catch (Exception ex) when (ex is HttpRequestException or JsonException or TaskCanceledException)
{
return null;
}
}
private static bool IsResponseTrue(JsonElement root) =>
GetString(root, "Response") is { } r && r.Equals("True", StringComparison.OrdinalIgnoreCase);
private static string? GetString(JsonElement el, string name) =>
el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
/// <summary>OMDb отдаёт «N/A» вместо отсутствующих значений — приводим к null.</summary>
private static string? Clean(string? value) =>
string.IsNullOrWhiteSpace(value) || value == "N/A" ? null : value;
private static int? YearFrom(string? year)
{
if (year is { Length: >= 4 } && int.TryParse(year.AsSpan(0, 4), out var y))
return y;
return null;
}
private static DateOnly? DateFrom(string? released) =>
DateTime.TryParse(released, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt)
? DateOnly.FromDateTime(dt)
: null;
}
@@ -0,0 +1,122 @@
using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Options;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Metadata;
namespace TeleWave.Infrastructure.Metadata;
/// <summary>Провайдер метаданных TMDb (themoviedb.org). Требует API-ключ (v3).</summary>
public sealed class TmdbMetadataProvider(IHttpClientFactory httpFactory, IOptions<MetadataOptions> options)
: IMetadataProvider
{
private readonly MetadataOptions _options = options.Value;
public string Key => "tmdb";
private TmdbOptions Tmdb => _options.Tmdb;
public async Task<IReadOnlyList<MetadataCandidate>> SearchShowsAsync(
string query,
CancellationToken cancellationToken
)
{
var url =
$"{Tmdb.BaseUrl}/search/tv?api_key={Tmdb.ApiKey}&language={_options.Language}"
+ $"&include_adult=false&query={Uri.EscapeDataString(query)}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null || !doc.RootElement.TryGetProperty("results", out var results))
return [];
var list = new List<MetadataCandidate>();
foreach (var item in results.EnumerateArray())
{
var id = GetInt(item, "id");
if (id is null)
continue;
list.Add(
new MetadataCandidate(
id.Value.ToString(CultureInfo.InvariantCulture),
GetString(item, "name") ?? "—",
YearFrom(GetString(item, "first_air_date")),
GetString(item, "overview"),
PosterUrl(GetString(item, "poster_path"))
)
);
}
return list;
}
public async Task<ShowMetadata?> GetShowAsync(string externalId, CancellationToken cancellationToken)
{
var url = $"{Tmdb.BaseUrl}/tv/{externalId}?api_key={Tmdb.ApiKey}&language={_options.Language}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null)
return null;
var root = doc.RootElement;
return new ShowMetadata(
externalId,
GetString(root, "name") ?? "—",
YearFrom(GetString(root, "first_air_date")),
GetString(root, "overview"),
PosterUrl(GetString(root, "poster_path"))
);
}
public async Task<EpisodeMetadata?> GetEpisodeAsync(
string externalId,
int season,
int episode,
CancellationToken cancellationToken
)
{
var url =
$"{Tmdb.BaseUrl}/tv/{externalId}/season/{season}/episode/{episode}"
+ $"?api_key={Tmdb.ApiKey}&language={_options.Language}";
using var doc = await GetJsonAsync(url, cancellationToken);
if (doc is null)
return null;
var root = doc.RootElement;
return new EpisodeMetadata(
GetString(root, "name") ?? "—",
GetString(root, "overview"),
StillUrl(GetString(root, "still_path")),
DateFrom(GetString(root, "air_date"))
);
}
private string? PosterUrl(string? path) =>
string.IsNullOrEmpty(path) ? null : $"{Tmdb.ImageBaseUrl}/{Tmdb.PosterSize}{path}";
private string? StillUrl(string? path) =>
string.IsNullOrEmpty(path) ? null : $"{Tmdb.ImageBaseUrl}/{Tmdb.StillSize}{path}";
private async Task<JsonDocument?> GetJsonAsync(string url, CancellationToken cancellationToken)
{
var client = httpFactory.CreateClient("metadata");
try
{
using var response = await client.GetAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode)
return null;
var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
}
catch (Exception ex) when (ex is HttpRequestException or JsonException or TaskCanceledException)
{
return null;
}
}
private static string? GetString(JsonElement el, string name) =>
el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
private static int? GetInt(JsonElement el, string name) =>
el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetInt32() : null;
private static int? YearFrom(string? date) =>
date is { Length: >= 4 } && int.TryParse(date.AsSpan(0, 4), out var y) ? y : null;
private static DateOnly? DateFrom(string? date) =>
DateOnly.TryParse(date, CultureInfo.InvariantCulture, out var d) ? d : null;
}
@@ -0,0 +1,827 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TeleWave.Infrastructure.Persistence;
#nullable disable
namespace TeleWave.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260725055823_ShowMetadata")]
partial class ShowMetadata
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("TeleWave.Domain.Auth.RefreshToken", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ReplacedByTokenHash")
.HasColumnType("text");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.BumperAsset", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FromShowId")
.HasColumnType("uuid");
b.Property<Guid>("MediaAssetId")
.HasColumnType("uuid");
b.Property<string>("Signature")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<Guid>("ToShowId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("FromShowId", "ToShowId", "Signature");
b.ToTable("BumperAssets");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.Channel", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int>("AdInsertion")
.HasColumnType("integer");
b.Property<int>("AdsPerBreak")
.HasColumnType("integer");
b.Property<string>("BumperAccentColor")
.IsRequired()
.HasColumnType("text");
b.Property<string>("BumperBackgroundColor")
.IsRequired()
.HasColumnType("text");
b.Property<string>("BumperBackgroundColor2")
.IsRequired()
.HasColumnType("text");
b.Property<string>("BumperBackgroundExtension")
.HasColumnType("text");
b.Property<int>("BumperDurationSeconds")
.HasColumnType("integer");
b.Property<int>("BumperFont")
.HasColumnType("integer");
b.Property<int>("BumperMinIntervalMinutes")
.HasColumnType("integer");
b.Property<int>("BumperMode")
.HasColumnType("integer");
b.Property<string>("BumperMusicExtension")
.HasColumnType("text");
b.Property<string>("BumperNextLabel")
.IsRequired()
.HasColumnType("text");
b.Property<string>("BumperNowLabel")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("BumperOnlyBetweenDifferentShows")
.HasColumnType("boolean");
b.Property<int>("BumperRevision")
.HasColumnType("integer");
b.Property<string>("BumperTextColor")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("BumpersEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("EpochUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("FillerAssetId")
.HasColumnType("uuid");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int>("NextAdIndex")
.HasColumnType("integer");
b.Property<int>("NextJingleIndex")
.HasColumnType("integer");
b.Property<string>("Slug")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.HasKey("Id");
b.HasIndex("Slug")
.IsUnique();
b.ToTable("Channels");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelAd", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<Guid>("MediaAssetId")
.HasColumnType("uuid");
b.Property<int>("Position")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ChannelId", "Position");
b.ToTable("ChannelAd");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelJingle", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<Guid>("MediaAssetId")
.HasColumnType("uuid");
b.Property<int>("Position")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ChannelId", "Position");
b.ToTable("ChannelJingle");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelShow", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<int>("BlockMode")
.HasColumnType("integer");
b.Property<int>("BlockValue")
.HasColumnType("integer");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<int>("NextEpisodeIndex")
.HasColumnType("integer");
b.Property<Guid>("ShowId")
.HasColumnType("uuid");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ChannelId", "ShowId");
b.ToTable("ChannelShow");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.OverrideShow", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("ProgrammingOverrideId")
.HasColumnType("uuid");
b.Property<Guid>("ShowId")
.HasColumnType("uuid");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProgrammingOverrideId");
b.ToTable("OverrideShow");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ProgrammingOverride", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("EndsAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<int>("Mode")
.HasColumnType("integer");
b.Property<DateTimeOffset>("StartsAtUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ChannelId", "StartsAtUtc", "EndsAtUtc");
b.ToTable("ProgrammingOverride");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ScheduleEntry", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("EndsAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("EpisodeIndex")
.HasColumnType("integer");
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<Guid>("MediaAssetId")
.HasColumnType("uuid");
b.Property<Guid?>("ShowId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("StartsAtUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ChannelId", "EndsAtUtc");
b.HasIndex("ChannelId", "ShowId");
b.HasIndex("ChannelId", "StartsAtUtc");
b.ToTable("ScheduleEntries");
});
modelBuilder.Entity("TeleWave.Domain.Library.Show", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<string>("MetadataExternalId")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("MetadataProvider")
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PosterPath")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int?>("Year")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Shows");
});
modelBuilder.Entity("TeleWave.Domain.Library.ShowEpisode", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("MediaAssetId")
.HasColumnType("uuid");
b.Property<int>("Position")
.HasColumnType("integer");
b.Property<Guid>("ShowId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("MediaAssetId");
b.HasIndex("ShowId", "Position");
b.ToTable("ShowEpisode");
});
modelBuilder.Entity("TeleWave.Domain.Media.MediaAsset", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("AudioCodec")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<TimeSpan?>("Duration")
.HasColumnType("interval");
b.Property<string>("ErrorMessage")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<int?>("Height")
.HasColumnType("integer");
b.Property<string>("OriginalExtension")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.Property<string>("OriginalFileName")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("RelativePath")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int?>("SegmentCount")
.HasColumnType("integer");
b.Property<int?>("SegmentSeconds")
.HasColumnType("integer");
b.Property<int>("Source")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("VideoCodec")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<int?>("Width")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("Status");
b.ToTable("MediaAssets");
});
modelBuilder.Entity("TeleWave.Domain.Settings.AppSetting", b =>
{
b.Property<string>("Key")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.HasKey("Key");
b.ToTable("AppSettings");
});
modelBuilder.Entity("TeleWave.Infrastructure.Identity.AppRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<bool>("IsSystem")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("TeleWave.Infrastructure.Identity.AppUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("IsBlocked")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("TeleWave.Infrastructure.Identity.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("TeleWave.Infrastructure.Identity.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("TeleWave.Infrastructure.Identity.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("TeleWave.Infrastructure.Identity.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TeleWave.Infrastructure.Identity.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("TeleWave.Infrastructure.Identity.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelAd", b =>
{
b.HasOne("TeleWave.Domain.Broadcast.Channel", null)
.WithMany("Ads")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelJingle", b =>
{
b.HasOne("TeleWave.Domain.Broadcast.Channel", null)
.WithMany("Jingles")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ChannelShow", b =>
{
b.HasOne("TeleWave.Domain.Broadcast.Channel", null)
.WithMany("Shows")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.OverrideShow", b =>
{
b.HasOne("TeleWave.Domain.Broadcast.ProgrammingOverride", null)
.WithMany("Shows")
.HasForeignKey("ProgrammingOverrideId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ProgrammingOverride", b =>
{
b.HasOne("TeleWave.Domain.Broadcast.Channel", null)
.WithMany("Overrides")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Library.ShowEpisode", b =>
{
b.HasOne("TeleWave.Domain.Library.Show", null)
.WithMany("Episodes")
.HasForeignKey("ShowId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.Channel", b =>
{
b.Navigation("Ads");
b.Navigation("Jingles");
b.Navigation("Overrides");
b.Navigation("Shows");
});
modelBuilder.Entity("TeleWave.Domain.Broadcast.ProgrammingOverride", b =>
{
b.Navigation("Shows");
});
modelBuilder.Entity("TeleWave.Domain.Library.Show", b =>
{
b.Navigation("Episodes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,61 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace TeleWave.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class ShowMetadata : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "MetadataExternalId",
table: "Shows",
type: "character varying(64)",
maxLength: 64,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "MetadataProvider",
table: "Shows",
type: "character varying(16)",
maxLength: 16,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "PosterPath",
table: "Shows",
type: "character varying(256)",
maxLength: 256,
nullable: true);
migrationBuilder.AddColumn<int>(
name: "Year",
table: "Shows",
type: "integer",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "MetadataExternalId",
table: "Shows");
migrationBuilder.DropColumn(
name: "MetadataProvider",
table: "Shows");
migrationBuilder.DropColumn(
name: "PosterPath",
table: "Shows");
migrationBuilder.DropColumn(
name: "Year",
table: "Shows");
}
}
}
@@ -458,11 +458,26 @@ namespace TeleWave.Infrastructure.Migrations
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<string>("MetadataExternalId")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("MetadataProvider")
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PosterPath")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int?>("Year")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Shows");
@@ -11,6 +11,9 @@ public class ShowConfiguration : IEntityTypeConfiguration<Show>
{
builder.Property(x => x.Name).IsRequired().HasMaxLength(256);
builder.Property(x => x.Description).HasMaxLength(2048);
builder.Property(x => x.MetadataProvider).HasMaxLength(16);
builder.Property(x => x.MetadataExternalId).HasMaxLength(64);
builder.Property(x => x.PosterPath).HasMaxLength(256);
builder
.HasMany(x => x.Episodes)
@@ -11,6 +11,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Options" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
@@ -17,6 +17,7 @@ import {
parseEpisodeName,
} from '@/features/admin/media/episode-parse'
import { formatDuration } from '@/features/admin/media/MediaPanel'
import { ShowMetadataCard } from './ShowMetadataCard'
import { addEpisode, getShow, removeEpisode } from './api'
type Candidate = { asset: MediaAssetDto; parsed: ParsedEpisode }
@@ -140,6 +141,8 @@ export function ShowDetail({ showId }: { showId: string }) {
)}
</div>
<ShowMetadataCard show={show} onChanged={invalidate} />
{canAdd && (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
@@ -0,0 +1,237 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { HttpError } from '@/shared/api/client'
import type { MetadataCandidate, ShowDto } from '@/shared/api/types'
import { Button } from '@/shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { toast } from '@/shared/ui/toast-store'
import {
applyMetadata,
clearMetadata,
getMetadataProviders,
searchMetadata,
showPosterUrl,
updateMetadata,
uploadPoster,
} from './api'
export function ShowMetadataCard({ show, onChanged }: { show: ShowDto; onChanged: () => void }) {
const { t } = useTranslation()
const posterInput = useRef<HTMLInputElement>(null)
const [bust, setBust] = useState(0)
const [provider, setProvider] = useState('')
const [query, setQuery] = useState(show.name)
const [results, setResults] = useState<MetadataCandidate[]>([])
const [description, setDescription] = useState(show.description ?? '')
const [year, setYear] = useState(show.year != null ? String(show.year) : '')
const { data: providers } = useQuery({
queryKey: ['admin', 'metadata', 'providers'],
queryFn: getMetadataProviders,
})
const onError = (error: unknown) =>
toast.error(error instanceof HttpError ? error.detail : t('common.error'))
const changed = () => {
setBust(Date.now())
onChanged()
}
const effectiveProvider = provider || providers?.[0] || ''
const search = useMutation({
mutationFn: () => searchMetadata(effectiveProvider, query.trim()),
onSuccess: setResults,
onError,
})
const apply = useMutation({
mutationFn: (externalId: string) => applyMetadata(show.id, effectiveProvider, externalId),
onSuccess: () => {
setResults([])
toast.success(t('admin.metadata.applied'))
changed()
},
onError,
})
const saveManual = useMutation({
mutationFn: () =>
updateMetadata(show.id, {
description: description.trim() || null,
year: year.trim() ? Number(year) : null,
}),
onSuccess: () => {
toast.success(t('settings.saved'))
changed()
},
onError,
})
const clear = useMutation({
mutationFn: () => clearMetadata(show.id),
onSuccess: () => {
setDescription('')
setYear('')
changed()
},
onError,
})
const posterUpload = useMutation({
mutationFn: (file: File) => uploadPoster(show.id, file),
onSuccess: changed,
onError,
})
return (
<Card>
<CardHeader>
<CardTitle>{t('admin.metadata.title')}</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4 sm:flex-row">
{/* Постер */}
<div className="flex w-40 shrink-0 flex-col gap-2">
<div className="flex aspect-[2/3] items-center justify-center overflow-hidden rounded-md border border-border bg-muted/30">
{show.hasPoster ? (
<img
src={showPosterUrl(show.id, String(bust))}
alt=""
className="h-full w-full object-cover"
/>
) : (
<span className="text-xs text-muted-foreground">{t('admin.metadata.noPoster')}</span>
)}
</div>
<input
ref={posterInput}
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0]
if (file) posterUpload.mutate(file)
e.target.value = ''
}}
/>
<Button
size="sm"
variant="outline"
disabled={posterUpload.isPending}
onClick={() => posterInput.current?.click()}
>
{t('admin.metadata.uploadPoster')}
</Button>
</div>
{/* Поиск + ручная правка */}
<div className="flex min-w-0 flex-1 flex-col gap-4">
{providers && providers.length > 0 && (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-end gap-2">
<div className="flex flex-col gap-1.5">
<Label>{t('admin.metadata.source')}</Label>
<Select value={effectiveProvider} onValueChange={setProvider}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{providers.map((p) => (
<SelectItem key={p} value={p}>
{p.toUpperCase()}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Input
className="min-w-40 flex-1"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('admin.metadata.searchPlaceholder')}
/>
<Button size="sm" disabled={search.isPending || !query.trim()} onClick={() => search.mutate()}>
{t('admin.metadata.searchBtn')}
</Button>
</div>
{results.length > 0 && (
<ul className="crt-panel max-h-72 divide-y divide-border overflow-y-auto rounded-md">
{results.map((r) => (
<li key={r.externalId} className="flex items-start gap-3 p-2">
{r.posterUrl ? (
<img src={r.posterUrl} alt="" className="h-16 w-11 shrink-0 rounded object-cover" />
) : (
<div className="h-16 w-11 shrink-0 rounded bg-muted/40" />
)}
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">
{r.title}
{r.year != null && (
<span className="text-muted-foreground"> ({r.year})</span>
)}
</div>
{r.overview && (
<p className="line-clamp-2 text-xs text-muted-foreground">{r.overview}</p>
)}
</div>
<Button
size="sm"
variant="outline"
disabled={apply.isPending}
onClick={() => apply.mutate(r.externalId)}
>
{t('admin.metadata.apply')}
</Button>
</li>
))}
</ul>
)}
</div>
)}
<div className="flex flex-col gap-2">
<div className="flex items-end gap-2">
<div className="flex flex-1 flex-col gap-1.5">
<Label>{t('admin.metadata.overview')}</Label>
<textarea
className="min-h-20 w-full rounded-sm border border-border bg-transparent px-3 py-2 text-sm"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="flex w-24 flex-col gap-1.5">
<Label>{t('admin.metadata.year')}</Label>
<Input
type="number"
value={year}
onChange={(e) => setYear(e.target.value)}
/>
</div>
</div>
<div className="flex items-center gap-2">
<Button size="sm" disabled={saveManual.isPending} onClick={() => saveManual.mutate()}>
{t('common.save')}
</Button>
{(show.metadataProvider || show.hasPoster) && (
<Button
size="sm"
variant="ghost"
disabled={clear.isPending}
onClick={() => clear.mutate()}
>
{t('admin.metadata.clear')}
</Button>
)}
{show.metadataProvider && (
<span className="text-xs text-muted-foreground">
{t('admin.metadata.sourceLabel')}: {show.metadataProvider}
</span>
)}
</div>
</div>
</div>
</CardContent>
</Card>
)
}
+65 -2
View File
@@ -1,5 +1,11 @@
import { apiRequest } from '@/shared/api/client'
import type { CreatedIdResponse, ShowDto, ShowKind, ShowSummaryDto } from '@/shared/api/types'
import { apiRequest, getAccessToken, HttpError } from '@/shared/api/client'
import type {
CreatedIdResponse,
MetadataCandidate,
ShowDto,
ShowKind,
ShowSummaryDto,
} from '@/shared/api/types'
export function listShows() {
return apiRequest<ShowSummaryDto[]>('/admin/shows')
@@ -27,3 +33,60 @@ export function addEpisode(showId: string, mediaAssetId: string) {
export function removeEpisode(showId: string, episodeId: string) {
return apiRequest<void>(`/admin/shows/${showId}/episodes/${episodeId}`, { method: 'DELETE' })
}
// ── Метаданные ────────────────────────────────────────────────────────────
export function getMetadataProviders() {
return apiRequest<string[]>('/admin/metadata/providers')
}
export function searchMetadata(provider: string, query: string) {
const q = new URLSearchParams({ provider, query })
return apiRequest<MetadataCandidate[]>(`/admin/metadata/search?${q.toString()}`)
}
export function applyMetadata(showId: string, provider: string, externalId: string) {
return apiRequest<void>(`/admin/metadata/shows/${showId}/apply`, {
method: 'POST',
body: { provider, externalId },
})
}
export function updateMetadata(showId: string, body: { description: string | null; year: number | null }) {
return apiRequest<void>(`/admin/metadata/shows/${showId}`, { method: 'PUT', body })
}
export function clearMetadata(showId: string) {
return apiRequest<void>(`/admin/metadata/shows/${showId}`, { method: 'DELETE' })
}
/** Ссылка на локальный постер шоу (публичный эндпоинт; cache-buster — по флагу наличия). */
export function showPosterUrl(showId: string, bust?: string) {
return `/api/metadata/shows/${showId}/poster${bust ? `?v=${encodeURIComponent(bust)}` : ''}`
}
/** Загрузка постера вручную (сырое тело, имя в query — как uploadMedia). */
export function uploadPoster(showId: string, file: File): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
const q = new URLSearchParams({ fileName: file.name })
xhr.open('PUT', `/api/admin/metadata/shows/${showId}/poster?${q.toString()}`)
const token = getAccessToken()
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`)
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) resolve()
else {
let detail = `HTTP ${xhr.status}`
try {
const p = JSON.parse(xhr.responseText) as { detail?: string; title?: string }
detail = p.detail ?? p.title ?? detail
} catch {
/* пусто */
}
reject(new HttpError({ detail }, xhr.status))
}
}
xhr.onerror = () => reject(new HttpError({ title: 'Network error' }, 0))
xhr.send(file)
})
}
+14
View File
@@ -71,9 +71,19 @@ export type ShowSummaryDto = {
kind: ShowKind
episodeCount: number
seasonCount: number
year: number | null
hasPoster: boolean
createdAt: string
}
export type MetadataCandidate = {
externalId: string
title: string
year: number | null
overview: string | null
posterUrl: string | null
}
export type EpisodeDto = {
id: string
mediaAssetId: string
@@ -88,6 +98,10 @@ export type ShowDto = {
name: string
kind: ShowKind
description: string | null
metadataProvider: string | null
metadataExternalId: string | null
year: number | null
hasPoster: boolean
episodes: EpisodeDto[]
}
+28
View File
@@ -260,6 +260,20 @@ const resources = {
'Когда выключено — новые пользователи не могут регистрироваться сами, учётки заводит только администратор.',
registrationLabel: 'Разрешить регистрацию на сайте',
},
metadata: {
title: 'Метаданные',
source: 'Источник',
sourceLabel: 'Источник',
searchPlaceholder: 'Название для поиска',
searchBtn: 'Искать',
apply: 'Применить',
applied: 'Метаданные применены',
overview: 'Описание',
year: 'Год',
clear: 'Очистить',
uploadPoster: 'Загрузить постер',
noPoster: 'Нет постера',
},
},
},
},
@@ -521,6 +535,20 @@ const resources = {
'When off, new users cannot sign up themselves — only an administrator can create accounts.',
registrationLabel: 'Allow public registration',
},
metadata: {
title: 'Metadata',
source: 'Source',
sourceLabel: 'Source',
searchPlaceholder: 'Title to search',
searchBtn: 'Search',
apply: 'Apply',
applied: 'Metadata applied',
overview: 'Overview',
year: 'Year',
clear: 'Clear',
uploadPoster: 'Upload poster',
noPoster: 'No poster',
},
},
},
},