diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..03ae297d5b8bb6c7ceb9d4321f29f4fefe912c6e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +**/.git +**/.vs +**/bin +**/obj +**/output +**/.env +**/node_modules +*.md +.dockerignore +docker-compose*.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e68ae0d0cc0d2b90f311a8ca8aef0e4ceac0bc48 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base +WORKDIR /app +EXPOSE 7860 + +RUN apt-get update && apt-get install -y ffmpeg python3 curl && curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp && chmod a+rx /usr/local/bin/yt-dlp && rm -rf /var/lib/apt/lists/* + +FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build +WORKDIR /src +COPY src/ClipForge.Api/ClipForge.Api.csproj ClipForge.Api/ +COPY src/ClipForge.Core/ClipForge.Core.csproj ClipForge.Core/ +COPY src/ClipForge.Infrastructure/ClipForge.Infrastructure.csproj ClipForge.Infrastructure/ +COPY src/ClipForge.Workers/ClipForge.Workers.csproj ClipForge.Workers/ +COPY src/ClipForge.Contracts/ClipForge.Contracts.csproj ClipForge.Contracts/ +RUN dotnet restore ClipForge.Api/ClipForge.Api.csproj +COPY src/ . +RUN dotnet publish ClipForge.Api/ClipForge.Api.csproj -c Release -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +RUN mkdir -p /app/output/audio /app/output/videos /app/output/thumbnails /app/output/subtitles /app/output/temp +ENV ASPNETCORE_URLS=http://+:7860 +ENV ASPNETCORE_ENVIRONMENT=Production +ENTRYPOINT ["dotnet", "ClipForge.Api.dll"] diff --git a/src/ClipForge.Api/ClipForge.Api.csproj b/src/ClipForge.Api/ClipForge.Api.csproj new file mode 100644 index 0000000000000000000000000000000000000000..5d6882cd5e1e4ec4290cc5422bcd78bc2435ace2 --- /dev/null +++ b/src/ClipForge.Api/ClipForge.Api.csproj @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + net9.0 + enable + enable + + + diff --git a/src/ClipForge.Api/Endpoints/IdeaEndpoints.cs b/src/ClipForge.Api/Endpoints/IdeaEndpoints.cs new file mode 100644 index 0000000000000000000000000000000000000000..efcd27e8a0f2e350c0d4a3a5a6de41c48af6672a --- /dev/null +++ b/src/ClipForge.Api/Endpoints/IdeaEndpoints.cs @@ -0,0 +1,54 @@ +using ClipForge.Contracts.Requests; +using ClipForge.Contracts.Responses; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; + +namespace ClipForge.Api.Endpoints; + +public static class IdeaEndpoints +{ + public static void MapIdeaEndpoints(this WebApplication app) + { + var group = app.MapGroup("/api/ideas").WithTags("Ideas"); + + group.MapPost("/generate", async (GenerateIdeaRequest request, IIdeaGenerationService service) => + { + if (request.Count > 1) + { + var ideas = await service.GenerateBatchIdeasAsync(request.Niche, request.Count, request.Platform); + return Results.Ok(ideas.Select(MapToResponse)); + } + + var idea = await service.GenerateIdeaAsync(request.Niche, request.Platform); + return Results.Ok(MapToResponse(idea)); + }); + + group.MapGet("/", async (IVideoIdeaRepository repository) => + { + var ideas = await repository.GetAllAsync(); + return Results.Ok(ideas.Select(MapToResponse)); + }); + + group.MapGet("/{id:guid}", async (Guid id, IVideoIdeaRepository repository) => + { + var idea = await repository.GetByIdAsync(id); + return idea is null ? Results.NotFound() : Results.Ok(MapToResponse(idea)); + }); + + group.MapGet("/status/{status}", async (string status, IVideoIdeaRepository repository) => + { + var ideas = await repository.GetByStatusAsync(status); + return Results.Ok(ideas.Select(MapToResponse)); + }); + + group.MapGet("/niche/{niche}", async (string niche, IVideoIdeaRepository repository) => + { + var ideas = await repository.GetByNicheAsync(niche); + return Results.Ok(ideas.Select(MapToResponse)); + }); + } + + private static VideoIdeaResponse MapToResponse(ClipForge.Core.Entities.VideoIdea idea) => new( + idea.Id, idea.Topic, idea.Title, idea.Hook, idea.TargetAudience, + idea.Platform, idea.Status, idea.Niche, idea.Tags, idea.CreatedAt); +} diff --git a/src/ClipForge.Api/Endpoints/PipelineEndpoints.cs b/src/ClipForge.Api/Endpoints/PipelineEndpoints.cs new file mode 100644 index 0000000000000000000000000000000000000000..cafa68cbb10008e24df8403b06e9c19a21263aea --- /dev/null +++ b/src/ClipForge.Api/Endpoints/PipelineEndpoints.cs @@ -0,0 +1,45 @@ +using ClipForge.Contracts.Requests; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Workers.Jobs; +using Hangfire; + +namespace ClipForge.Api.Endpoints; + +public static class PipelineEndpoints +{ + public static void MapPipelineEndpoints(this WebApplication app) + { + var group = app.MapGroup("/api/pipeline").WithTags("Pipeline"); + + // Run full pipeline immediately (background job) + group.MapPost("/run", async (FullPipelineRequest request, ISchedulerService scheduler) => + { + await scheduler.ScheduleFullPipelineAsync(request.Niche, request.Platform); + return Results.Accepted(value: new { Message = "Pipeline scheduled", Niche = request.Niche, Platform = request.Platform }); + }); + + // Schedule recurring pipeline + group.MapPost("/schedule", async (SchedulePipelineRequest request, ISchedulerService scheduler) => + { + if (string.IsNullOrEmpty(request.CronExpression)) + return Results.BadRequest(new { Error = "CronExpression is required for scheduling" }); + + await scheduler.ScheduleRecurringGenerationAsync(request.Niche, request.CronExpression, request.Platform); + return Results.Ok(new { Message = "Recurring pipeline scheduled", Niche = request.Niche, Cron = request.CronExpression }); + }); + + // Cancel recurring job + group.MapDelete("/schedule/{jobId}", async (string jobId, ISchedulerService scheduler) => + { + await scheduler.CancelRecurringJobAsync(jobId); + return Results.Ok(new { Message = $"Job '{jobId}' cancelled" }); + }); + + // Run full pipeline synchronously (for testing) + group.MapPost("/run-sync", async (FullPipelineRequest request, FullPipelineJob job) => + { + await job.ExecuteAsync(request.Niche, request.Platform, request.VoiceId); + return Results.Ok(new { Message = "Pipeline completed", Niche = request.Niche }); + }); + } +} diff --git a/src/ClipForge.Api/Endpoints/ScriptEndpoints.cs b/src/ClipForge.Api/Endpoints/ScriptEndpoints.cs new file mode 100644 index 0000000000000000000000000000000000000000..3190f5c51a939eed5c5cfd8f64d8154a6e75f9cf --- /dev/null +++ b/src/ClipForge.Api/Endpoints/ScriptEndpoints.cs @@ -0,0 +1,42 @@ +using ClipForge.Contracts.Requests; +using ClipForge.Contracts.Responses; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; + +namespace ClipForge.Api.Endpoints; + +public static class ScriptEndpoints +{ + public static void MapScriptEndpoints(this WebApplication app) + { + var group = app.MapGroup("/api/scripts").WithTags("Scripts"); + + group.MapPost("/generate", async (GenerateScriptRequest request, IScriptGenerationService service) => + { + var script = await service.GenerateScriptAsync(request.IdeaId); + return Results.Ok(MapToResponse(script)); + }); + + group.MapGet("/", async (IVideoScriptRepository repository) => + { + var scripts = await repository.GetAllAsync(); + return Results.Ok(scripts.Select(MapToResponse)); + }); + + group.MapGet("/{id:guid}", async (Guid id, IVideoScriptRepository repository) => + { + var script = await repository.GetByIdAsync(id); + return script is null ? Results.NotFound() : Results.Ok(MapToResponse(script)); + }); + + group.MapGet("/idea/{ideaId:guid}", async (Guid ideaId, IVideoScriptRepository repository) => + { + var script = await repository.GetByIdeaIdAsync(ideaId); + return script is null ? Results.NotFound() : Results.Ok(MapToResponse(script)); + }); + } + + private static VideoScriptResponse MapToResponse(ClipForge.Core.Entities.VideoScript script) => new( + script.Id, script.VideoIdeaId, script.ScriptText, script.Scenes, + script.EstimatedDurationSeconds, script.Tone, script.Language, script.CreatedAt); +} diff --git a/src/ClipForge.Api/Endpoints/VideoEndpoints.cs b/src/ClipForge.Api/Endpoints/VideoEndpoints.cs new file mode 100644 index 0000000000000000000000000000000000000000..7a223d0141a1fea08ffca740fa3bc1609e489d5c --- /dev/null +++ b/src/ClipForge.Api/Endpoints/VideoEndpoints.cs @@ -0,0 +1,60 @@ +using ClipForge.Contracts.Requests; +using ClipForge.Contracts.Responses; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using Microsoft.AspNetCore.Hosting; + +namespace ClipForge.Api.Endpoints; + +public static class VideoEndpoints +{ + public static void MapVideoEndpoints(this WebApplication app) + { + var group = app.MapGroup("/api/videos").WithTags("Videos"); + + group.MapPost("/assemble", async (AssembleVideoRequest request, IVideoAssemblyService service) => + { + var video = await service.AssembleVideoAsync(request.ScriptId); + return Results.Ok(MapToResponse(video)); + }); + + group.MapGet("/", async (IVideoAssetRepository repository) => + { + var videos = await repository.GetAllAsync(); + return Results.Ok(videos.Select(MapToResponse)); + }); + + group.MapGet("/{id:guid}", async (Guid id, IVideoAssetRepository repository) => + { + var video = await repository.GetByIdAsync(id); + return video is null ? Results.NotFound() : Results.Ok(MapToResponse(video)); + }); + + group.MapGet("/status/{status}", async (string status, IVideoAssetRepository repository) => + { + var videos = await repository.GetByStatusAsync(status); + return Results.Ok(videos.Select(MapToResponse)); + }); + + group.MapGet("/{id:guid}/download", async (Guid id, IVideoAssetRepository repository, IWebHostEnvironment env) => + { + var video = await repository.GetByIdAsync(id); + if (video is null) return Results.NotFound(); + + // Resolve path relative to content root + var filePath = video.FilePath; + if (filePath.StartsWith("./")) + filePath = Path.Combine(env.ContentRootPath, filePath[2..]); + + filePath = Path.GetFullPath(filePath); + if (!File.Exists(filePath)) return Results.NotFound($"File not found: {filePath}"); + + return Results.File(filePath, "video/mp4", $"clipforge_{id}.mp4"); + }); + } + + private static VideoAssetResponse MapToResponse(ClipForge.Core.Entities.VideoAsset video) => new( + video.Id, video.VideoScriptId, video.FilePath, video.ThumbnailPath, + video.Width, video.Height, video.DurationSeconds, video.FileSizeBytes, + video.Format, video.Status, video.CreatedAt); +} diff --git a/src/ClipForge.Api/Endpoints/VoiceEndpoints.cs b/src/ClipForge.Api/Endpoints/VoiceEndpoints.cs new file mode 100644 index 0000000000000000000000000000000000000000..7fb1d4d08efe134396d4a8906aa605ec8752b3a7 --- /dev/null +++ b/src/ClipForge.Api/Endpoints/VoiceEndpoints.cs @@ -0,0 +1,28 @@ +using ClipForge.Contracts.Requests; +using ClipForge.Core.Interfaces.Services; + +namespace ClipForge.Api.Endpoints; + +public static class VoiceEndpoints +{ + public static void MapVoiceEndpoints(this WebApplication app) + { + var group = app.MapGroup("/api/voice").WithTags("Voice"); + + group.MapPost("/generate", async (GenerateVoiceRequest request, IVoiceGenerationService service) => + { + var voice = await service.GenerateVoiceAsync(request.ScriptId, request.VoiceId); + return Results.Ok(new + { + voice.Id, + voice.VideoScriptId, + voice.FilePath, + voice.VoiceProvider, + voice.VoiceId, + voice.DurationSeconds, + voice.FileSizeBytes, + voice.CreatedAt + }); + }); + } +} diff --git a/src/ClipForge.Api/Program.cs b/src/ClipForge.Api/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..b81a11ac6ca76ef1cf85f398d140735a39dc9918 --- /dev/null +++ b/src/ClipForge.Api/Program.cs @@ -0,0 +1,68 @@ +using ClipForge.Api.Endpoints; +using ClipForge.Infrastructure; +using ClipForge.Infrastructure.Data; +using ClipForge.Workers.Jobs; +using Hangfire; +using Hangfire.PostgreSql; +using Microsoft.EntityFrameworkCore; + +var builder = WebApplication.CreateBuilder(args); + +// Add Infrastructure (DI, DbContext, Services) +builder.Services.AddInfrastructure(builder.Configuration); + +// Workers +builder.Services.AddScoped(); + +// Hangfire +builder.Services.AddHangfire(config => + config.UsePostgreSqlStorage(options => + options.UseNpgsqlConnection(builder.Configuration.GetConnectionString("DefaultConnection")))); +builder.Services.AddHangfireServer(); + +var app = builder.Build(); + +// Apply migrations on startup +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.MigrateAsync(); +} + +// Hangfire Dashboard +app.UseHangfireDashboard("/hangfire"); + +// Serve static files (frontend) +app.UseDefaultFiles(); +app.UseStaticFiles(); + +// Map API endpoints +app.MapIdeaEndpoints(); +app.MapScriptEndpoints(); +app.MapVoiceEndpoints(); +app.MapVideoEndpoints(); +app.MapPipelineEndpoints(); + +app.MapGet("/api/status", () => Results.Ok(new +{ + Name = "ClipForge API", + Version = "1.0.0", + Status = "Running" +})); + +// Temporary cleanup endpoint +app.MapDelete("/api/admin/cleanup/{keepVideoId}", async (Guid keepVideoId, ClipForge.Infrastructure.Data.AppDbContext db) => +{ + var sql = $@" + DELETE FROM ""PublishJobs"" WHERE ""VideoAssetId"" != '{keepVideoId}'; + DELETE FROM ""CaptionAssets"" WHERE ""VideoAssetId"" != '{keepVideoId}'; + DELETE FROM ""VideoAssets"" WHERE ""Id"" != '{keepVideoId}'; + DELETE FROM ""VoiceAssets"" WHERE ""VideoScriptId"" NOT IN (SELECT ""VideoScriptId"" FROM ""VideoAssets"" WHERE ""Id"" = '{keepVideoId}'); + DELETE FROM ""VideoScripts"" WHERE ""Id"" NOT IN (SELECT ""VideoScriptId"" FROM ""VideoAssets"" WHERE ""Id"" = '{keepVideoId}'); + DELETE FROM ""VideoIdeas"" WHERE ""Id"" NOT IN (SELECT ""VideoIdeaId"" FROM ""VideoScripts"" WHERE ""Id"" IN (SELECT ""VideoScriptId"" FROM ""VideoAssets"" WHERE ""Id"" = '{keepVideoId}')); + "; + var rows = await db.Database.ExecuteSqlRawAsync(sql); + return Results.Ok(new { Message = "Cleanup done", RowsDeleted = rows }); +}); + +app.Run(); diff --git a/src/ClipForge.Api/Properties/launchSettings.json b/src/ClipForge.Api/Properties/launchSettings.json new file mode 100644 index 0000000000000000000000000000000000000000..897e073d58bc7165053cbf16264da0a9b3b69448 --- /dev/null +++ b/src/ClipForge.Api/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://0.0.0.0:5011", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7024;http://0.0.0.0:5011", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/ClipForge.Api/appsettings.Production.json b/src/ClipForge.Api/appsettings.Production.json new file mode 100644 index 0000000000000000000000000000000000000000..564a7939ad49ea0d1bdb7ce1433e425b3ea715b4 --- /dev/null +++ b/src/ClipForge.Api/appsettings.Production.json @@ -0,0 +1,25 @@ +{ + "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, + "AllowedHosts": "*", + "ConnectionStrings": { + "DefaultConnection": "Host=ep-restless-surf-ap1x9yyn-pooler.c-7.us-east-1.aws.neon.tech;Database=neondb;Username=neondb_owner;Password=npg_pT3JVYi2MOAj;SSL Mode=Require;Trust Server Certificate=true" + }, + "OpenAi": { + "ApiKey": "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", + "Model": "google/gemini-2.0-flash-001", + "TtsModel": "", + "BaseUrl": "https://openrouter.ai/api/v1" + }, + "Pexels": { + "ApiKey": "Q5nTHwnhC5qKv1J3iEkbFUbp3it4RjHIUfuGZ75A5f53kSq7eHoZYSgB", + "BaseUrl": "https://api.pexels.com" + }, + "Storage": { + "BasePath": "/app/output", + "AudioFolder": "audio", + "VideoFolder": "videos", + "ThumbnailFolder": "thumbnails", + "SubtitleFolder": "subtitles", + "TempFolder": "temp" + } +} diff --git a/src/ClipForge.Api/appsettings.json b/src/ClipForge.Api/appsettings.json new file mode 100644 index 0000000000000000000000000000000000000000..564a7939ad49ea0d1bdb7ce1433e425b3ea715b4 --- /dev/null +++ b/src/ClipForge.Api/appsettings.json @@ -0,0 +1,25 @@ +{ + "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, + "AllowedHosts": "*", + "ConnectionStrings": { + "DefaultConnection": "Host=ep-restless-surf-ap1x9yyn-pooler.c-7.us-east-1.aws.neon.tech;Database=neondb;Username=neondb_owner;Password=npg_pT3JVYi2MOAj;SSL Mode=Require;Trust Server Certificate=true" + }, + "OpenAi": { + "ApiKey": "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", + "Model": "google/gemini-2.0-flash-001", + "TtsModel": "", + "BaseUrl": "https://openrouter.ai/api/v1" + }, + "Pexels": { + "ApiKey": "Q5nTHwnhC5qKv1J3iEkbFUbp3it4RjHIUfuGZ75A5f53kSq7eHoZYSgB", + "BaseUrl": "https://api.pexels.com" + }, + "Storage": { + "BasePath": "/app/output", + "AudioFolder": "audio", + "VideoFolder": "videos", + "ThumbnailFolder": "thumbnails", + "SubtitleFolder": "subtitles", + "TempFolder": "temp" + } +} diff --git a/src/ClipForge.Api/wwwroot/index.html b/src/ClipForge.Api/wwwroot/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9e7440d594234586dc419738c8a9fc285bda30bd --- /dev/null +++ b/src/ClipForge.Api/wwwroot/index.html @@ -0,0 +1,216 @@ + + + + + + ClipForge - Gerador de Vídeos + + + +
+

🎬 ClipForge

+

Gerador automático de vídeos virais com IA

+ +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+ +
+

📁 Vídeos Gerados

+
Carregando...
+
+
+ + + + diff --git a/src/ClipForge.Contracts/ClipForge.Contracts.csproj b/src/ClipForge.Contracts/ClipForge.Contracts.csproj new file mode 100644 index 0000000000000000000000000000000000000000..125f4c93bc98c2ee5a8520de3a0017a6c86f5047 --- /dev/null +++ b/src/ClipForge.Contracts/ClipForge.Contracts.csproj @@ -0,0 +1,9 @@ + + + + net9.0 + enable + enable + + + diff --git a/src/ClipForge.Contracts/Requests/AssembleVideoRequest.cs b/src/ClipForge.Contracts/Requests/AssembleVideoRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..97b6a887dd68e9b9a7f6da06db2366c68e03a24d --- /dev/null +++ b/src/ClipForge.Contracts/Requests/AssembleVideoRequest.cs @@ -0,0 +1,5 @@ +namespace ClipForge.Contracts.Requests; + +public record AssembleVideoRequest( + Guid ScriptId +); diff --git a/src/ClipForge.Contracts/Requests/FullPipelineRequest.cs b/src/ClipForge.Contracts/Requests/FullPipelineRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..4bf20726ebda117bb051883d02e1e202270d186e --- /dev/null +++ b/src/ClipForge.Contracts/Requests/FullPipelineRequest.cs @@ -0,0 +1,9 @@ +namespace ClipForge.Contracts.Requests; + +public record FullPipelineRequest( + string Niche, + string Platform = "tiktok", + string Tone = "engaging", + string Language = "pt-BR", + string VoiceId = "alloy" +); diff --git a/src/ClipForge.Contracts/Requests/GenerateIdeaRequest.cs b/src/ClipForge.Contracts/Requests/GenerateIdeaRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..313b7f4ac6a2a573c5e33544c592509884ff3386 --- /dev/null +++ b/src/ClipForge.Contracts/Requests/GenerateIdeaRequest.cs @@ -0,0 +1,7 @@ +namespace ClipForge.Contracts.Requests; + +public record GenerateIdeaRequest( + string Niche, + string Platform = "tiktok", + int Count = 1 +); diff --git a/src/ClipForge.Contracts/Requests/GenerateScriptRequest.cs b/src/ClipForge.Contracts/Requests/GenerateScriptRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..3788dfda6a9083b38f7e1d996da0ccdc38145b8a --- /dev/null +++ b/src/ClipForge.Contracts/Requests/GenerateScriptRequest.cs @@ -0,0 +1,7 @@ +namespace ClipForge.Contracts.Requests; + +public record GenerateScriptRequest( + Guid IdeaId, + string Tone = "engaging", + string Language = "pt-BR" +); diff --git a/src/ClipForge.Contracts/Requests/GenerateVoiceRequest.cs b/src/ClipForge.Contracts/Requests/GenerateVoiceRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..4300d0c7cbac67fa521117d043a20c15c1068043 --- /dev/null +++ b/src/ClipForge.Contracts/Requests/GenerateVoiceRequest.cs @@ -0,0 +1,6 @@ +namespace ClipForge.Contracts.Requests; + +public record GenerateVoiceRequest( + Guid ScriptId, + string VoiceId = "alloy" +); diff --git a/src/ClipForge.Contracts/Requests/SchedulePipelineRequest.cs b/src/ClipForge.Contracts/Requests/SchedulePipelineRequest.cs new file mode 100644 index 0000000000000000000000000000000000000000..7f5f42c29346b3d604e82ccea4bd9eaa4c9d2b98 --- /dev/null +++ b/src/ClipForge.Contracts/Requests/SchedulePipelineRequest.cs @@ -0,0 +1,7 @@ +namespace ClipForge.Contracts.Requests; + +public record SchedulePipelineRequest( + string Niche, + string Platform = "tiktok", + string? CronExpression = null +); diff --git a/src/ClipForge.Contracts/Responses/PipelineStatusResponse.cs b/src/ClipForge.Contracts/Responses/PipelineStatusResponse.cs new file mode 100644 index 0000000000000000000000000000000000000000..af84e73954e2bfb3fb645a99b8ff89c3bf7c0bba --- /dev/null +++ b/src/ClipForge.Contracts/Responses/PipelineStatusResponse.cs @@ -0,0 +1,10 @@ +namespace ClipForge.Contracts.Responses; + +public record PipelineStatusResponse( + Guid IdeaId, + Guid? ScriptId, + Guid? VideoAssetId, + string CurrentStep, + string Status, + string? ErrorMessage +); diff --git a/src/ClipForge.Contracts/Responses/VideoAssetResponse.cs b/src/ClipForge.Contracts/Responses/VideoAssetResponse.cs new file mode 100644 index 0000000000000000000000000000000000000000..29d144d84409927ad36cca4bf6af1134095e268b --- /dev/null +++ b/src/ClipForge.Contracts/Responses/VideoAssetResponse.cs @@ -0,0 +1,15 @@ +namespace ClipForge.Contracts.Responses; + +public record VideoAssetResponse( + Guid Id, + Guid VideoScriptId, + string FilePath, + string ThumbnailPath, + int Width, + int Height, + double DurationSeconds, + long FileSizeBytes, + string Format, + string Status, + DateTime CreatedAt +); diff --git a/src/ClipForge.Contracts/Responses/VideoIdeaResponse.cs b/src/ClipForge.Contracts/Responses/VideoIdeaResponse.cs new file mode 100644 index 0000000000000000000000000000000000000000..1de4b3d77d863c7403f5d739c9211ad0807d52ae --- /dev/null +++ b/src/ClipForge.Contracts/Responses/VideoIdeaResponse.cs @@ -0,0 +1,14 @@ +namespace ClipForge.Contracts.Responses; + +public record VideoIdeaResponse( + Guid Id, + string Topic, + string Title, + string Hook, + string TargetAudience, + string Platform, + string Status, + string? Niche, + string? Tags, + DateTime CreatedAt +); diff --git a/src/ClipForge.Contracts/Responses/VideoScriptResponse.cs b/src/ClipForge.Contracts/Responses/VideoScriptResponse.cs new file mode 100644 index 0000000000000000000000000000000000000000..8970541a59d7461b34f358ea2764a67e8ee26f34 --- /dev/null +++ b/src/ClipForge.Contracts/Responses/VideoScriptResponse.cs @@ -0,0 +1,12 @@ +namespace ClipForge.Contracts.Responses; + +public record VideoScriptResponse( + Guid Id, + Guid VideoIdeaId, + string ScriptText, + string Scenes, + int EstimatedDurationSeconds, + string Tone, + string Language, + DateTime CreatedAt +); diff --git a/src/ClipForge.Core/ClipForge.Core.csproj b/src/ClipForge.Core/ClipForge.Core.csproj new file mode 100644 index 0000000000000000000000000000000000000000..125f4c93bc98c2ee5a8520de3a0017a6c86f5047 --- /dev/null +++ b/src/ClipForge.Core/ClipForge.Core.csproj @@ -0,0 +1,9 @@ + + + + net9.0 + enable + enable + + + diff --git a/src/ClipForge.Core/Entities/BaseEntity.cs b/src/ClipForge.Core/Entities/BaseEntity.cs new file mode 100644 index 0000000000000000000000000000000000000000..e4c02b341ec143169077e5023f0b26f77dc3abc3 --- /dev/null +++ b/src/ClipForge.Core/Entities/BaseEntity.cs @@ -0,0 +1,8 @@ +namespace ClipForge.Core.Entities; + +public abstract class BaseEntity +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime? UpdatedAt { get; set; } +} diff --git a/src/ClipForge.Core/Entities/CaptionAsset.cs b/src/ClipForge.Core/Entities/CaptionAsset.cs new file mode 100644 index 0000000000000000000000000000000000000000..b0eae5dac184db01463612cf8418928929dbbea0 --- /dev/null +++ b/src/ClipForge.Core/Entities/CaptionAsset.cs @@ -0,0 +1,16 @@ +namespace ClipForge.Core.Entities; + +public class CaptionAsset : BaseEntity +{ + public Guid VideoAssetId { get; set; } + public string SrtFilePath { get; set; } = string.Empty; + public string CaptionStyle { get; set; } = "dynamic"; // dynamic, static, karaoke + public string FontFamily { get; set; } = "Montserrat"; + public int FontSize { get; set; } = 48; + public string FontColor { get; set; } = "#FFFFFF"; + public string StrokeColor { get; set; } = "#000000"; + public int StrokeWidth { get; set; } = 2; + + // Navigation + public VideoAsset? VideoAsset { get; set; } +} diff --git a/src/ClipForge.Core/Entities/PublishJob.cs b/src/ClipForge.Core/Entities/PublishJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..84ea2e8ae634859de321a5bf2f1d3215faccfbe7 --- /dev/null +++ b/src/ClipForge.Core/Entities/PublishJob.cs @@ -0,0 +1,19 @@ +namespace ClipForge.Core.Entities; + +public class PublishJob : BaseEntity +{ + public Guid VideoAssetId { get; set; } + public Guid? SocialAccountId { get; set; } + public string Platform { get; set; } = "tiktok"; // tiktok, youtube_shorts, kwai + public string Status { get; set; } = "pending"; // pending, scheduled, publishing, published, failed + public DateTime? ScheduledAt { get; set; } + public DateTime? PublishedAt { get; set; } + public string? ExternalId { get; set; } + public string? ErrorMessage { get; set; } + public string? Caption { get; set; } + public string? Hashtags { get; set; } + + // Navigation + public VideoAsset? VideoAsset { get; set; } + public SocialAccount? SocialAccount { get; set; } +} diff --git a/src/ClipForge.Core/Entities/SocialAccount.cs b/src/ClipForge.Core/Entities/SocialAccount.cs new file mode 100644 index 0000000000000000000000000000000000000000..2c875d3ca4df7f08c2aee48873f7c006d2010ce7 --- /dev/null +++ b/src/ClipForge.Core/Entities/SocialAccount.cs @@ -0,0 +1,14 @@ +namespace ClipForge.Core.Entities; + +public class SocialAccount : BaseEntity +{ + public string Platform { get; set; } = "tiktok"; + public string AccountName { get; set; } = string.Empty; + public string? AccessToken { get; set; } + public string? RefreshToken { get; set; } + public DateTime? TokenExpiresAt { get; set; } + public bool IsActive { get; set; } = true; + + // Navigation + public List PublishJobs { get; set; } = []; +} diff --git a/src/ClipForge.Core/Entities/VideoAsset.cs b/src/ClipForge.Core/Entities/VideoAsset.cs new file mode 100644 index 0000000000000000000000000000000000000000..79ec72ccb08e62f910349e66b639bb17bb4e8def --- /dev/null +++ b/src/ClipForge.Core/Entities/VideoAsset.cs @@ -0,0 +1,19 @@ +namespace ClipForge.Core.Entities; + +public class VideoAsset : BaseEntity +{ + public Guid VideoScriptId { get; set; } + public string FilePath { get; set; } = string.Empty; + public string ThumbnailPath { get; set; } = string.Empty; + public int Width { get; set; } = 1080; + public int Height { get; set; } = 1920; + public double DurationSeconds { get; set; } + public long FileSizeBytes { get; set; } + public string Format { get; set; } = "mp4"; + public string Status { get; set; } = "processing"; // processing, completed, failed + + // Navigation + public VideoScript? VideoScript { get; set; } + public CaptionAsset? CaptionAsset { get; set; } + public List PublishJobs { get; set; } = []; +} diff --git a/src/ClipForge.Core/Entities/VideoIdea.cs b/src/ClipForge.Core/Entities/VideoIdea.cs new file mode 100644 index 0000000000000000000000000000000000000000..8fba9fcf4369d5258ce2b113a2218fd04782494f --- /dev/null +++ b/src/ClipForge.Core/Entities/VideoIdea.cs @@ -0,0 +1,16 @@ +namespace ClipForge.Core.Entities; + +public class VideoIdea : BaseEntity +{ + public string Topic { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Hook { get; set; } = string.Empty; + public string TargetAudience { get; set; } = string.Empty; + public string Platform { get; set; } = "tiktok"; // tiktok, youtube_shorts, kwai + public string Status { get; set; } = "pending"; // pending, scripted, completed, failed + public string? Niche { get; set; } + public string? Tags { get; set; } + + // Navigation + public VideoScript? Script { get; set; } +} diff --git a/src/ClipForge.Core/Entities/VideoScript.cs b/src/ClipForge.Core/Entities/VideoScript.cs new file mode 100644 index 0000000000000000000000000000000000000000..63d878780a6d650357b8de3156675962d0a822af --- /dev/null +++ b/src/ClipForge.Core/Entities/VideoScript.cs @@ -0,0 +1,16 @@ +namespace ClipForge.Core.Entities; + +public class VideoScript : BaseEntity +{ + public Guid VideoIdeaId { get; set; } + public string ScriptText { get; set; } = string.Empty; + public string Scenes { get; set; } = string.Empty; // JSON array of scene descriptions + public int EstimatedDurationSeconds { get; set; } + public string Tone { get; set; } = "engaging"; // engaging, funny, dramatic, informative + public string Language { get; set; } = "pt-BR"; + + // Navigation + public VideoIdea? VideoIdea { get; set; } + public VoiceAsset? VoiceAsset { get; set; } + public VideoAsset? VideoAsset { get; set; } +} diff --git a/src/ClipForge.Core/Entities/VoiceAsset.cs b/src/ClipForge.Core/Entities/VoiceAsset.cs new file mode 100644 index 0000000000000000000000000000000000000000..3b101b6048f04901e388cabf64c5c1dcccee8d8a --- /dev/null +++ b/src/ClipForge.Core/Entities/VoiceAsset.cs @@ -0,0 +1,14 @@ +namespace ClipForge.Core.Entities; + +public class VoiceAsset : BaseEntity +{ + public Guid VideoScriptId { get; set; } + public string FilePath { get; set; } = string.Empty; + public string VoiceProvider { get; set; } = "openai"; // openai, elevenlabs + public string VoiceId { get; set; } = "alloy"; + public double DurationSeconds { get; set; } + public long FileSizeBytes { get; set; } + + // Navigation + public VideoScript? VideoScript { get; set; } +} diff --git a/src/ClipForge.Core/Interfaces/IRepository.cs b/src/ClipForge.Core/Interfaces/IRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..30ef96cb590a9a597268115bd9a78ee2352c2f57 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/IRepository.cs @@ -0,0 +1,12 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces; + +public interface IRepository where T : BaseEntity +{ + Task GetByIdAsync(Guid id, CancellationToken ct = default); + Task> GetAllAsync(CancellationToken ct = default); + Task AddAsync(T entity, CancellationToken ct = default); + Task UpdateAsync(T entity, CancellationToken ct = default); + Task DeleteAsync(Guid id, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/IVideoAssetRepository.cs b/src/ClipForge.Core/Interfaces/IVideoAssetRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..f211ad55fb76647bdf0de57aff76761f9f1a7de8 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/IVideoAssetRepository.cs @@ -0,0 +1,9 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces; + +public interface IVideoAssetRepository : IRepository +{ + Task> GetByStatusAsync(string status, CancellationToken ct = default); + Task GetByScriptIdAsync(Guid scriptId, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/IVideoIdeaRepository.cs b/src/ClipForge.Core/Interfaces/IVideoIdeaRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..04a2454f1c48cdd21e448cb40e4172342e8c24fd --- /dev/null +++ b/src/ClipForge.Core/Interfaces/IVideoIdeaRepository.cs @@ -0,0 +1,9 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces; + +public interface IVideoIdeaRepository : IRepository +{ + Task> GetByStatusAsync(string status, CancellationToken ct = default); + Task> GetByNicheAsync(string niche, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/IVideoScriptRepository.cs b/src/ClipForge.Core/Interfaces/IVideoScriptRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..37ddac910f123a0c75513c577c15b128880cf579 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/IVideoScriptRepository.cs @@ -0,0 +1,8 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces; + +public interface IVideoScriptRepository : IRepository +{ + Task GetByIdeaIdAsync(Guid ideaId, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IFfmpegService.cs b/src/ClipForge.Core/Interfaces/Services/IFfmpegService.cs new file mode 100644 index 0000000000000000000000000000000000000000..1f2fa28da5d9502ade2cbb3d1691fe41fb3afe4a --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IFfmpegService.cs @@ -0,0 +1,9 @@ +namespace ClipForge.Core.Interfaces.Services; + +public interface IFfmpegService +{ + Task AssembleVerticalVideoAsync(string audioPath, IReadOnlyList backgroundClips, string outputPath, CancellationToken ct = default); + Task AddSubtitlesToVideoAsync(string videoPath, string srtPath, string outputPath, CancellationToken ct = default); + Task GetMediaDurationAsync(string filePath, CancellationToken ct = default); + Task GenerateThumbnailAsync(string videoPath, string outputPath, double atSecond = 1.0, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IIdeaGenerationService.cs b/src/ClipForge.Core/Interfaces/Services/IIdeaGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..4d643ef22b0cae0150b99d46379d325d0100c987 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IIdeaGenerationService.cs @@ -0,0 +1,9 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces.Services; + +public interface IIdeaGenerationService +{ + Task GenerateIdeaAsync(string niche, string platform = "tiktok", CancellationToken ct = default); + Task> GenerateBatchIdeasAsync(string niche, int count = 5, string platform = "tiktok", CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IOpenAiClient.cs b/src/ClipForge.Core/Interfaces/Services/IOpenAiClient.cs new file mode 100644 index 0000000000000000000000000000000000000000..9e0945f4ae9026d109073b57c7f81a83b4900fc1 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IOpenAiClient.cs @@ -0,0 +1,7 @@ +namespace ClipForge.Core.Interfaces.Services; + +public interface IOpenAiClient +{ + Task GenerateChatCompletionAsync(string systemPrompt, string userPrompt, CancellationToken ct = default); + Task GenerateSpeechAsync(string text, string voice = "alloy", CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/ISchedulerService.cs b/src/ClipForge.Core/Interfaces/Services/ISchedulerService.cs new file mode 100644 index 0000000000000000000000000000000000000000..7c183dae68ec37d54d60b1265e8f9056894dbcce --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/ISchedulerService.cs @@ -0,0 +1,8 @@ +namespace ClipForge.Core.Interfaces.Services; + +public interface ISchedulerService +{ + Task ScheduleFullPipelineAsync(string niche, string platform = "tiktok", CancellationToken ct = default); + Task ScheduleRecurringGenerationAsync(string niche, string cronExpression, string platform = "tiktok", CancellationToken ct = default); + Task CancelRecurringJobAsync(string jobId, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IScriptGenerationService.cs b/src/ClipForge.Core/Interfaces/Services/IScriptGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..d5097ad18f4a2981f5792af8ef4c000d5560f964 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IScriptGenerationService.cs @@ -0,0 +1,9 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces.Services; + +public interface IScriptGenerationService +{ + Task GenerateScriptAsync(Guid ideaId, CancellationToken ct = default); + Task GenerateScriptFromTopicAsync(string topic, string tone = "engaging", string language = "pt-BR", CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IStockMediaService.cs b/src/ClipForge.Core/Interfaces/Services/IStockMediaService.cs new file mode 100644 index 0000000000000000000000000000000000000000..bcaad14683d94e830bce0099679c7504b9ac809a --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IStockMediaService.cs @@ -0,0 +1,7 @@ +namespace ClipForge.Core.Interfaces.Services; + +public interface IStockMediaService +{ + Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default); + Task> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/ISubtitleService.cs b/src/ClipForge.Core/Interfaces/Services/ISubtitleService.cs new file mode 100644 index 0000000000000000000000000000000000000000..3b202d1df1a640d140bcea4b60cfaaa7b22aadbe --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/ISubtitleService.cs @@ -0,0 +1,9 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces.Services; + +public interface ISubtitleService +{ + Task GenerateSubtitlesAsync(Guid videoAssetId, CancellationToken ct = default); + Task GenerateSrtFromTextAsync(string text, double totalDuration, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IVideoAssemblyService.cs b/src/ClipForge.Core/Interfaces/Services/IVideoAssemblyService.cs new file mode 100644 index 0000000000000000000000000000000000000000..5682988edba94fb68e204390d71a21c805c2c687 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IVideoAssemblyService.cs @@ -0,0 +1,8 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces.Services; + +public interface IVideoAssemblyService +{ + Task AssembleVideoAsync(Guid scriptId, CancellationToken ct = default); +} diff --git a/src/ClipForge.Core/Interfaces/Services/IVoiceGenerationService.cs b/src/ClipForge.Core/Interfaces/Services/IVoiceGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..9cab68f457f5c0040aa749c220660c997255a4a6 --- /dev/null +++ b/src/ClipForge.Core/Interfaces/Services/IVoiceGenerationService.cs @@ -0,0 +1,8 @@ +using ClipForge.Core.Entities; + +namespace ClipForge.Core.Interfaces.Services; + +public interface IVoiceGenerationService +{ + Task GenerateVoiceAsync(Guid scriptId, string voiceId = "alloy", CancellationToken ct = default); +} diff --git a/src/ClipForge.Infrastructure/ClipForge.Infrastructure.csproj b/src/ClipForge.Infrastructure/ClipForge.Infrastructure.csproj new file mode 100644 index 0000000000000000000000000000000000000000..83a78337518ef09f030ee3d9e5040daecffe7eea --- /dev/null +++ b/src/ClipForge.Infrastructure/ClipForge.Infrastructure.csproj @@ -0,0 +1,25 @@ + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + net9.0 + enable + enable + + + diff --git a/src/ClipForge.Infrastructure/Configuration/OpenAiSettings.cs b/src/ClipForge.Infrastructure/Configuration/OpenAiSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..b8608a02479166f3b324a98b63138963d1397a34 --- /dev/null +++ b/src/ClipForge.Infrastructure/Configuration/OpenAiSettings.cs @@ -0,0 +1,10 @@ +namespace ClipForge.Infrastructure.Configuration; + +public class OpenAiSettings +{ + public const string SectionName = "OpenAi"; + public string ApiKey { get; set; } = string.Empty; + public string Model { get; set; } = "llama-3.3-70b-versatile"; + public string TtsModel { get; set; } = "tts-1"; + public string BaseUrl { get; set; } = "https://api.groq.com/openai/v1"; +} diff --git a/src/ClipForge.Infrastructure/Configuration/PexelsSettings.cs b/src/ClipForge.Infrastructure/Configuration/PexelsSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..4e81c14da3e65d78f1f5379b6c45a28608a4fb9b --- /dev/null +++ b/src/ClipForge.Infrastructure/Configuration/PexelsSettings.cs @@ -0,0 +1,8 @@ +namespace ClipForge.Infrastructure.Configuration; + +public class PexelsSettings +{ + public const string SectionName = "Pexels"; + public string ApiKey { get; set; } = string.Empty; + public string BaseUrl { get; set; } = "https://api.pexels.com"; +} diff --git a/src/ClipForge.Infrastructure/Configuration/StorageSettings.cs b/src/ClipForge.Infrastructure/Configuration/StorageSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..19f9e7c0cf0e625cc303d09ea7b9f36e60b69ceb --- /dev/null +++ b/src/ClipForge.Infrastructure/Configuration/StorageSettings.cs @@ -0,0 +1,12 @@ +namespace ClipForge.Infrastructure.Configuration; + +public class StorageSettings +{ + public const string SectionName = "Storage"; + public string BasePath { get; set; } = "./output"; + public string AudioFolder { get; set; } = "audio"; + public string VideoFolder { get; set; } = "videos"; + public string ThumbnailFolder { get; set; } = "thumbnails"; + public string SubtitleFolder { get; set; } = "subtitles"; + public string TempFolder { get; set; } = "temp"; +} diff --git a/src/ClipForge.Infrastructure/Data/AppDbContext.cs b/src/ClipForge.Infrastructure/Data/AppDbContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..090ea1405fe304002b3d11a429d214054d3b3335 --- /dev/null +++ b/src/ClipForge.Infrastructure/Data/AppDbContext.cs @@ -0,0 +1,107 @@ +using ClipForge.Core.Entities; +using Microsoft.EntityFrameworkCore; + +namespace ClipForge.Infrastructure.Data; + +public class AppDbContext : DbContext +{ + public AppDbContext(DbContextOptions options) : base(options) { } + + public DbSet VideoIdeas => Set(); + public DbSet VideoScripts => Set(); + public DbSet VoiceAssets => Set(); + public DbSet VideoAssets => Set(); + public DbSet CaptionAssets => Set(); + public DbSet PublishJobs => Set(); + public DbSet SocialAccounts => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Topic).HasMaxLength(500).IsRequired(); + entity.Property(e => e.Title).HasMaxLength(500).IsRequired(); + entity.Property(e => e.Hook).HasMaxLength(1000).IsRequired(); + entity.Property(e => e.TargetAudience).HasMaxLength(200); + entity.Property(e => e.Platform).HasMaxLength(50); + entity.Property(e => e.Status).HasMaxLength(50); + entity.Property(e => e.Niche).HasMaxLength(200); + entity.Property(e => e.Tags).HasMaxLength(1000); + entity.HasOne(e => e.Script).WithOne(s => s.VideoIdea).HasForeignKey(s => s.VideoIdeaId); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.ScriptText).IsRequired(); + entity.Property(e => e.Scenes).IsRequired(); + entity.Property(e => e.Tone).HasMaxLength(50); + entity.Property(e => e.Language).HasMaxLength(10); + entity.HasOne(e => e.VoiceAsset).WithOne(v => v.VideoScript).HasForeignKey(v => v.VideoScriptId); + entity.HasOne(e => e.VideoAsset).WithOne(v => v.VideoScript).HasForeignKey(v => v.VideoScriptId); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.FilePath).HasMaxLength(1000).IsRequired(); + entity.Property(e => e.VoiceProvider).HasMaxLength(50); + entity.Property(e => e.VoiceId).HasMaxLength(100); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.FilePath).HasMaxLength(1000).IsRequired(); + entity.Property(e => e.ThumbnailPath).HasMaxLength(1000); + entity.Property(e => e.Format).HasMaxLength(10); + entity.Property(e => e.Status).HasMaxLength(50); + entity.HasOne(e => e.CaptionAsset).WithOne(c => c.VideoAsset).HasForeignKey(c => c.VideoAssetId); + entity.HasMany(e => e.PublishJobs).WithOne(p => p.VideoAsset).HasForeignKey(p => p.VideoAssetId); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.SrtFilePath).HasMaxLength(1000).IsRequired(); + entity.Property(e => e.CaptionStyle).HasMaxLength(50); + entity.Property(e => e.FontFamily).HasMaxLength(100); + entity.Property(e => e.FontColor).HasMaxLength(20); + entity.Property(e => e.StrokeColor).HasMaxLength(20); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Platform).HasMaxLength(50).IsRequired(); + entity.Property(e => e.Status).HasMaxLength(50); + entity.Property(e => e.ExternalId).HasMaxLength(500); + entity.Property(e => e.ErrorMessage).HasMaxLength(2000); + entity.Property(e => e.Caption).HasMaxLength(2000); + entity.Property(e => e.Hashtags).HasMaxLength(1000); + entity.HasOne(e => e.SocialAccount).WithMany(s => s.PublishJobs).HasForeignKey(e => e.SocialAccountId); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Platform).HasMaxLength(50).IsRequired(); + entity.Property(e => e.AccountName).HasMaxLength(200).IsRequired(); + entity.Property(e => e.AccessToken).HasMaxLength(2000); + entity.Property(e => e.RefreshToken).HasMaxLength(2000); + }); + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State == EntityState.Modified) + entry.Entity.UpdatedAt = DateTime.UtcNow; + } + return base.SaveChangesAsync(cancellationToken); + } +} diff --git a/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.Designer.cs b/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..253e3785d2c37d3c001db6ee1b842298324e9e27 --- /dev/null +++ b/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.Designer.cs @@ -0,0 +1,467 @@ +// +using System; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace ClipForge.Infrastructure.Data.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260517232254_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ClipForge.Core.Entities.CaptionAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CaptionStyle") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FontColor") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("FontFamily") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("FontSize") + .HasColumnType("integer"); + + b.Property("SrtFilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("StrokeColor") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StrokeWidth") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoAssetId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VideoAssetId") + .IsUnique(); + + b.ToTable("CaptionAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.PublishJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Caption") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ExternalId") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Hashtags") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SocialAccountId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoAssetId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SocialAccountId"); + + b.HasIndex("VideoAssetId"); + + b.ToTable("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.SocialAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessToken") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("AccountName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("RefreshToken") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("SocialAccounts"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationSeconds") + .HasColumnType("double precision"); + + b.Property("FilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FileSizeBytes") + .HasColumnType("bigint"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ThumbnailPath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoScriptId") + .HasColumnType("uuid"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VideoScriptId") + .IsUnique(); + + b.ToTable("VideoAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoIdea", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Hook") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Niche") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Tags") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TargetAudience") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("VideoIdeas"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EstimatedDurationSeconds") + .HasColumnType("integer"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Scenes") + .IsRequired() + .HasColumnType("text"); + + b.Property("ScriptText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Tone") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoIdeaId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VideoIdeaId") + .IsUnique(); + + b.ToTable("VideoScripts"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VoiceAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationSeconds") + .HasColumnType("double precision"); + + b.Property("FilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FileSizeBytes") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoScriptId") + .HasColumnType("uuid"); + + b.Property("VoiceId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("VoiceProvider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("VideoScriptId") + .IsUnique(); + + b.ToTable("VoiceAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.CaptionAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoAsset", "VideoAsset") + .WithOne("CaptionAsset") + .HasForeignKey("ClipForge.Core.Entities.CaptionAsset", "VideoAssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoAsset"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.PublishJob", b => + { + b.HasOne("ClipForge.Core.Entities.SocialAccount", "SocialAccount") + .WithMany("PublishJobs") + .HasForeignKey("SocialAccountId"); + + b.HasOne("ClipForge.Core.Entities.VideoAsset", "VideoAsset") + .WithMany("PublishJobs") + .HasForeignKey("VideoAssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SocialAccount"); + + b.Navigation("VideoAsset"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoScript", "VideoScript") + .WithOne("VideoAsset") + .HasForeignKey("ClipForge.Core.Entities.VideoAsset", "VideoScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoScript"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.HasOne("ClipForge.Core.Entities.VideoIdea", "VideoIdea") + .WithOne("Script") + .HasForeignKey("ClipForge.Core.Entities.VideoScript", "VideoIdeaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoIdea"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VoiceAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoScript", "VideoScript") + .WithOne("VoiceAsset") + .HasForeignKey("ClipForge.Core.Entities.VoiceAsset", "VideoScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoScript"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.SocialAccount", b => + { + b.Navigation("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.Navigation("CaptionAsset"); + + b.Navigation("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoIdea", b => + { + b.Navigation("Script"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.Navigation("VideoAsset"); + + b.Navigation("VoiceAsset"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.cs b/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.cs new file mode 100644 index 0000000000000000000000000000000000000000..3e59592c726019740dc5cfbdd8510fc9933def02 --- /dev/null +++ b/src/ClipForge.Infrastructure/Data/Migrations/20260517232254_InitialCreate.cs @@ -0,0 +1,253 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ClipForge.Infrastructure.Data.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "SocialAccounts", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Platform = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + AccountName = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + AccessToken = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + RefreshToken = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + TokenExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + IsActive = table.Column(type: "boolean", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SocialAccounts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "VideoIdeas", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Topic = table.Column(type: "character varying(500)", maxLength: 500, nullable: false), + Title = table.Column(type: "character varying(500)", maxLength: 500, nullable: false), + Hook = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + TargetAudience = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Platform = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Status = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Niche = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + Tags = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_VideoIdeas", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "VideoScripts", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + VideoIdeaId = table.Column(type: "uuid", nullable: false), + ScriptText = table.Column(type: "text", nullable: false), + Scenes = table.Column(type: "text", nullable: false), + EstimatedDurationSeconds = table.Column(type: "integer", nullable: false), + Tone = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Language = table.Column(type: "character varying(10)", maxLength: 10, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_VideoScripts", x => x.Id); + table.ForeignKey( + name: "FK_VideoScripts_VideoIdeas_VideoIdeaId", + column: x => x.VideoIdeaId, + principalTable: "VideoIdeas", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "VideoAssets", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + VideoScriptId = table.Column(type: "uuid", nullable: false), + FilePath = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + ThumbnailPath = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + Width = table.Column(type: "integer", nullable: false), + Height = table.Column(type: "integer", nullable: false), + DurationSeconds = table.Column(type: "double precision", nullable: false), + FileSizeBytes = table.Column(type: "bigint", nullable: false), + Format = table.Column(type: "character varying(10)", maxLength: 10, nullable: false), + Status = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_VideoAssets", x => x.Id); + table.ForeignKey( + name: "FK_VideoAssets_VideoScripts_VideoScriptId", + column: x => x.VideoScriptId, + principalTable: "VideoScripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "VoiceAssets", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + VideoScriptId = table.Column(type: "uuid", nullable: false), + FilePath = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + VoiceProvider = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + VoiceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + DurationSeconds = table.Column(type: "double precision", nullable: false), + FileSizeBytes = table.Column(type: "bigint", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_VoiceAssets", x => x.Id); + table.ForeignKey( + name: "FK_VoiceAssets_VideoScripts_VideoScriptId", + column: x => x.VideoScriptId, + principalTable: "VideoScripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "CaptionAssets", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + VideoAssetId = table.Column(type: "uuid", nullable: false), + SrtFilePath = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + CaptionStyle = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + FontFamily = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + FontSize = table.Column(type: "integer", nullable: false), + FontColor = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + StrokeColor = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + StrokeWidth = table.Column(type: "integer", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_CaptionAssets", x => x.Id); + table.ForeignKey( + name: "FK_CaptionAssets_VideoAssets_VideoAssetId", + column: x => x.VideoAssetId, + principalTable: "VideoAssets", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PublishJobs", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + VideoAssetId = table.Column(type: "uuid", nullable: false), + SocialAccountId = table.Column(type: "uuid", nullable: true), + Platform = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Status = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + ScheduledAt = table.Column(type: "timestamp with time zone", nullable: true), + PublishedAt = table.Column(type: "timestamp with time zone", nullable: true), + ExternalId = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + ErrorMessage = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + Caption = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + Hashtags = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PublishJobs", x => x.Id); + table.ForeignKey( + name: "FK_PublishJobs_SocialAccounts_SocialAccountId", + column: x => x.SocialAccountId, + principalTable: "SocialAccounts", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_PublishJobs_VideoAssets_VideoAssetId", + column: x => x.VideoAssetId, + principalTable: "VideoAssets", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_CaptionAssets_VideoAssetId", + table: "CaptionAssets", + column: "VideoAssetId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PublishJobs_SocialAccountId", + table: "PublishJobs", + column: "SocialAccountId"); + + migrationBuilder.CreateIndex( + name: "IX_PublishJobs_VideoAssetId", + table: "PublishJobs", + column: "VideoAssetId"); + + migrationBuilder.CreateIndex( + name: "IX_VideoAssets_VideoScriptId", + table: "VideoAssets", + column: "VideoScriptId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_VideoScripts_VideoIdeaId", + table: "VideoScripts", + column: "VideoIdeaId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_VoiceAssets_VideoScriptId", + table: "VoiceAssets", + column: "VideoScriptId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CaptionAssets"); + + migrationBuilder.DropTable( + name: "PublishJobs"); + + migrationBuilder.DropTable( + name: "VoiceAssets"); + + migrationBuilder.DropTable( + name: "SocialAccounts"); + + migrationBuilder.DropTable( + name: "VideoAssets"); + + migrationBuilder.DropTable( + name: "VideoScripts"); + + migrationBuilder.DropTable( + name: "VideoIdeas"); + } + } +} diff --git a/src/ClipForge.Infrastructure/Data/Migrations/AppDbContextModelSnapshot.cs b/src/ClipForge.Infrastructure/Data/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000000000000000000000000000000000000..651e70b7d0562e234110d7df804ab9f403940a1e --- /dev/null +++ b/src/ClipForge.Infrastructure/Data/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,464 @@ +// +using System; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace ClipForge.Infrastructure.Data.Migrations +{ + [DbContext(typeof(AppDbContext))] + partial class AppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ClipForge.Core.Entities.CaptionAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CaptionStyle") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FontColor") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("FontFamily") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("FontSize") + .HasColumnType("integer"); + + b.Property("SrtFilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("StrokeColor") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StrokeWidth") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoAssetId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VideoAssetId") + .IsUnique(); + + b.ToTable("CaptionAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.PublishJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Caption") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ExternalId") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Hashtags") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SocialAccountId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoAssetId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SocialAccountId"); + + b.HasIndex("VideoAssetId"); + + b.ToTable("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.SocialAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessToken") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("AccountName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("RefreshToken") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("SocialAccounts"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationSeconds") + .HasColumnType("double precision"); + + b.Property("FilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FileSizeBytes") + .HasColumnType("bigint"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ThumbnailPath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoScriptId") + .HasColumnType("uuid"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VideoScriptId") + .IsUnique(); + + b.ToTable("VideoAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoIdea", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Hook") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Niche") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Tags") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TargetAudience") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("VideoIdeas"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EstimatedDurationSeconds") + .HasColumnType("integer"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Scenes") + .IsRequired() + .HasColumnType("text"); + + b.Property("ScriptText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Tone") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoIdeaId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VideoIdeaId") + .IsUnique(); + + b.ToTable("VideoScripts"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VoiceAsset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationSeconds") + .HasColumnType("double precision"); + + b.Property("FilePath") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FileSizeBytes") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VideoScriptId") + .HasColumnType("uuid"); + + b.Property("VoiceId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("VoiceProvider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("VideoScriptId") + .IsUnique(); + + b.ToTable("VoiceAssets"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.CaptionAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoAsset", "VideoAsset") + .WithOne("CaptionAsset") + .HasForeignKey("ClipForge.Core.Entities.CaptionAsset", "VideoAssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoAsset"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.PublishJob", b => + { + b.HasOne("ClipForge.Core.Entities.SocialAccount", "SocialAccount") + .WithMany("PublishJobs") + .HasForeignKey("SocialAccountId"); + + b.HasOne("ClipForge.Core.Entities.VideoAsset", "VideoAsset") + .WithMany("PublishJobs") + .HasForeignKey("VideoAssetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SocialAccount"); + + b.Navigation("VideoAsset"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoScript", "VideoScript") + .WithOne("VideoAsset") + .HasForeignKey("ClipForge.Core.Entities.VideoAsset", "VideoScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoScript"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.HasOne("ClipForge.Core.Entities.VideoIdea", "VideoIdea") + .WithOne("Script") + .HasForeignKey("ClipForge.Core.Entities.VideoScript", "VideoIdeaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoIdea"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VoiceAsset", b => + { + b.HasOne("ClipForge.Core.Entities.VideoScript", "VideoScript") + .WithOne("VoiceAsset") + .HasForeignKey("ClipForge.Core.Entities.VoiceAsset", "VideoScriptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VideoScript"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.SocialAccount", b => + { + b.Navigation("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoAsset", b => + { + b.Navigation("CaptionAsset"); + + b.Navigation("PublishJobs"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoIdea", b => + { + b.Navigation("Script"); + }); + + modelBuilder.Entity("ClipForge.Core.Entities.VideoScript", b => + { + b.Navigation("VideoAsset"); + + b.Navigation("VoiceAsset"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ClipForge.Infrastructure/DependencyInjection.cs b/src/ClipForge.Infrastructure/DependencyInjection.cs new file mode 100644 index 0000000000000000000000000000000000000000..ecf2436e106f6d90b1587909fe9abb2c29a71a5a --- /dev/null +++ b/src/ClipForge.Infrastructure/DependencyInjection.cs @@ -0,0 +1,50 @@ +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using ClipForge.Infrastructure.Data; +using ClipForge.Infrastructure.Repositories; +using ClipForge.Infrastructure.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace ClipForge.Infrastructure; + +public static class DependencyInjection +{ + public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) + { + // Configuration + services.Configure(configuration.GetSection(OpenAiSettings.SectionName)); + services.Configure(configuration.GetSection(PexelsSettings.SectionName)); + services.Configure(configuration.GetSection(StorageSettings.SectionName)); + + // Database + services.AddDbContext(options => + options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))); + + // Repositories + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>)); + + // HTTP Clients + services.AddHttpClient(); + + // Media service (YouTube via yt-dlp) + services.AddScoped(); + + // Services + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + return services; + } +} diff --git a/src/ClipForge.Infrastructure/Repositories/BaseRepository.cs b/src/ClipForge.Infrastructure/Repositories/BaseRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..a742cb26c808ffcf0f9e5e796c0087b454a14b16 --- /dev/null +++ b/src/ClipForge.Infrastructure/Repositories/BaseRepository.cs @@ -0,0 +1,47 @@ +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace ClipForge.Infrastructure.Repositories; + +public class BaseRepository : IRepository where T : BaseEntity +{ + protected readonly AppDbContext _context; + protected readonly DbSet _dbSet; + + public BaseRepository(AppDbContext context) + { + _context = context; + _dbSet = context.Set(); + } + + public async Task GetByIdAsync(Guid id, CancellationToken ct = default) + => await _dbSet.FindAsync([id], ct); + + public async Task> GetAllAsync(CancellationToken ct = default) + => await _dbSet.OrderByDescending(e => e.CreatedAt).ToListAsync(ct); + + public async Task AddAsync(T entity, CancellationToken ct = default) + { + await _dbSet.AddAsync(entity, ct); + await _context.SaveChangesAsync(ct); + return entity; + } + + public async Task UpdateAsync(T entity, CancellationToken ct = default) + { + _dbSet.Update(entity); + await _context.SaveChangesAsync(ct); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var entity = await GetByIdAsync(id, ct); + if (entity is not null) + { + _dbSet.Remove(entity); + await _context.SaveChangesAsync(ct); + } + } +} diff --git a/src/ClipForge.Infrastructure/Repositories/VideoAssetRepository.cs b/src/ClipForge.Infrastructure/Repositories/VideoAssetRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..69cbdcf30670b8a43267d0d9b6d97e9a47f50e1e --- /dev/null +++ b/src/ClipForge.Infrastructure/Repositories/VideoAssetRepository.cs @@ -0,0 +1,17 @@ +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace ClipForge.Infrastructure.Repositories; + +public class VideoAssetRepository : BaseRepository, IVideoAssetRepository +{ + public VideoAssetRepository(AppDbContext context) : base(context) { } + + public async Task> GetByStatusAsync(string status, CancellationToken ct = default) + => await _dbSet.Where(v => v.Status == status).OrderByDescending(v => v.CreatedAt).ToListAsync(ct); + + public async Task GetByScriptIdAsync(Guid scriptId, CancellationToken ct = default) + => await _dbSet.FirstOrDefaultAsync(v => v.VideoScriptId == scriptId, ct); +} diff --git a/src/ClipForge.Infrastructure/Repositories/VideoIdeaRepository.cs b/src/ClipForge.Infrastructure/Repositories/VideoIdeaRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..a49d2f2c4e6bb1637404aec814cc487dec5c9691 --- /dev/null +++ b/src/ClipForge.Infrastructure/Repositories/VideoIdeaRepository.cs @@ -0,0 +1,17 @@ +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace ClipForge.Infrastructure.Repositories; + +public class VideoIdeaRepository : BaseRepository, IVideoIdeaRepository +{ + public VideoIdeaRepository(AppDbContext context) : base(context) { } + + public async Task> GetByStatusAsync(string status, CancellationToken ct = default) + => await _dbSet.Where(i => i.Status == status).OrderByDescending(i => i.CreatedAt).ToListAsync(ct); + + public async Task> GetByNicheAsync(string niche, CancellationToken ct = default) + => await _dbSet.Where(i => i.Niche == niche).OrderByDescending(i => i.CreatedAt).ToListAsync(ct); +} diff --git a/src/ClipForge.Infrastructure/Repositories/VideoScriptRepository.cs b/src/ClipForge.Infrastructure/Repositories/VideoScriptRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..b5d822f69ac70bbb71e85e9538f867a16f1e351f --- /dev/null +++ b/src/ClipForge.Infrastructure/Repositories/VideoScriptRepository.cs @@ -0,0 +1,14 @@ +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace ClipForge.Infrastructure.Repositories; + +public class VideoScriptRepository : BaseRepository, IVideoScriptRepository +{ + public VideoScriptRepository(AppDbContext context) : base(context) { } + + public async Task GetByIdeaIdAsync(Guid ideaId, CancellationToken ct = default) + => await _dbSet.FirstOrDefaultAsync(s => s.VideoIdeaId == ideaId, ct); +} diff --git a/src/ClipForge.Infrastructure/Services/EdgeTtsService.cs b/src/ClipForge.Infrastructure/Services/EdgeTtsService.cs new file mode 100644 index 0000000000000000000000000000000000000000..aabf00e94c3e20f26edcfc7e71175b3526c4bca5 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/EdgeTtsService.cs @@ -0,0 +1,197 @@ +using System.Net.WebSockets; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +/// +/// Edge TTS implementation using Microsoft Edge's speech synthesis WebSocket API. +/// Free, no API key required, high quality voices in multiple languages. +/// Based on https://github.com/rany2/edge-tts +/// +public class EdgeTtsService +{ + private const string TrustedClientToken = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"; + private const string ChromiumFullVersion = "143.0.3650.75"; + private const string ChromiumMajor = "143"; + private const long WinEpoch = 11644473600; + private const double SToNs = 1e9; + + private static string WssUrl => + $"wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken={TrustedClientToken}&Sec-MS-GEC={GenerateSecMsGec()}&Sec-MS-GEC-Version=1-{ChromiumFullVersion}"; + + private readonly ILogger _logger; + + public static class Voices + { + public const string FranciscaPtBr = "pt-BR-FranciscaNeural"; + public const string AntonioNeural = "pt-BR-AntonioNeural"; + public const string ThalitaNeural = "pt-BR-ThalitaNeural"; + } + + public EdgeTtsService(ILogger logger) + { + _logger = logger; + } + + public async Task SynthesizeSpeechAsync(string text, string voice = "pt-BR-FranciscaNeural", CancellationToken ct = default) + { + _logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length); + + // Retry up to 3 times + for (int attempt = 1; attempt <= 3; attempt++) + { + try + { + var result = await TrySynthesizeAsync(text, voice, ct); + if (result.Length > 0) + return result; + } + catch (Exception ex) when (attempt < 3) + { + _logger.LogWarning(ex, "Edge TTS attempt {Attempt} failed, retrying...", attempt); + await Task.Delay(1000 * attempt, ct); + } + } + + // Final attempt - let it throw + return await TrySynthesizeAsync(text, voice, ct); + } + + private async Task TrySynthesizeAsync(string text, string voice, CancellationToken ct) + { + _logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length); + + using var ws = new ClientWebSocket(); + + // Headers matching edge-tts Python library + ws.Options.SetRequestHeader("Pragma", "no-cache"); + ws.Options.SetRequestHeader("Cache-Control", "no-cache"); + ws.Options.SetRequestHeader("Origin", "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold"); + ws.Options.SetRequestHeader("User-Agent", + $"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromiumMajor}.0.0.0 Safari/537.36 Edg/{ChromiumMajor}.0.0.0"); + ws.Options.SetRequestHeader("Accept-Encoding", "gzip, deflate, br, zstd"); + ws.Options.SetRequestHeader("Accept-Language", "en-US,en;q=0.9"); + + // MUID cookie + var muid = GenerateMuid(); + ws.Options.SetRequestHeader("Cookie", $"muid={muid};"); + + var url = WssUrl; + _logger.LogDebug("Connecting to Edge TTS WebSocket"); + + await ws.ConnectAsync(new Uri(url), ct); + + var requestId = Guid.NewGuid().ToString("N"); + + // Send configuration + var configMessage = + $"X-Timestamp:{GetTimestamp()}\r\n" + + "Content-Type:application/json; charset=utf-8\r\n" + + "Path:speech.config\r\n\r\n" + + "{\"context\":{\"synthesis\":{\"audio\":{\"metadataoptions\":{\"sentenceBoundaryEnabled\":\"false\",\"wordBoundaryEnabled\":\"false\"},\"outputFormat\":\"audio-24khz-48kbitrate-mono-mp3\"}}}}"; + + await SendTextAsync(ws, configMessage, ct); + + // Send SSML + var ssml = $"" + + $"{EscapeXml(text)}"; + + var ssmlMessage = + $"X-RequestId:{requestId}\r\n" + + "Content-Type:application/ssml+xml\r\n" + + $"X-Timestamp:{GetTimestamp()}\r\n" + + "Path:ssml\r\n\r\n" + + ssml; + + await SendTextAsync(ws, ssmlMessage, ct); + + // Receive audio data + var audioData = new List(); + var buffer = new byte[32768]; + + while (ws.State == WebSocketState.Open) + { + var result = await ws.ReceiveAsync(buffer, ct); + + if (result.MessageType == WebSocketMessageType.Close) + break; + + if (result.MessageType == WebSocketMessageType.Binary) + { + // Binary messages: first 2 bytes are header length (big-endian) + if (result.Count > 2) + { + int headerLen = (buffer[0] << 8) | buffer[1]; + int audioStart = 2 + headerLen; + if (audioStart < result.Count) + { + var audioChunk = new byte[result.Count - audioStart]; + Array.Copy(buffer, audioStart, audioChunk, 0, audioChunk.Length); + audioData.AddRange(audioChunk); + } + } + } + else if (result.MessageType == WebSocketMessageType.Text) + { + var msg = Encoding.UTF8.GetString(buffer, 0, result.Count); + if (msg.Contains("Path:turn.end")) + break; + } + } + + if (ws.State == WebSocketState.Open) + { + try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "done", ct); } + catch { /* ignore close errors */ } + } + + _logger.LogInformation("Edge TTS generated {Bytes} bytes of audio", audioData.Count); + return audioData.ToArray(); + } + + /// + /// Generates the Sec-MS-GEC token value (SHA256 hash of rounded timestamp + token). + /// Matches the Python edge-tts DRM implementation. + /// + private static string GenerateSecMsGec() + { + // Get current Unix timestamp + var ticks = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + + // Convert to Windows file time epoch + ticks += WinEpoch; + + // Round down to nearest 5 minutes (300 seconds) + ticks -= ticks % 300; + + // Convert to 100-nanosecond intervals (Windows file time format) + var nsValue = (long)(ticks * SToNs / 100); + + // Hash: "{ticks}{TrustedClientToken}" + var strToHash = $"{nsValue}{TrustedClientToken}"; + var hashBytes = SHA256.HashData(Encoding.ASCII.GetBytes(strToHash)); + + return Convert.ToHexString(hashBytes); + } + + private static string GenerateMuid() + { + var bytes = new byte[16]; + RandomNumberGenerator.Fill(bytes); + return Convert.ToHexString(bytes); + } + + private static async Task SendTextAsync(ClientWebSocket ws, string message, CancellationToken ct) + { + var bytes = Encoding.UTF8.GetBytes(message); + await ws.SendAsync(bytes, WebSocketMessageType.Text, true, ct); + } + + private static string GetTimestamp() + => DateTime.UtcNow.ToString("ddd MMM dd yyyy HH:mm:ss") + " GMT+0000 (Coordinated Universal Time)"; + + private static string EscapeXml(string text) + => text.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'"); +} diff --git a/src/ClipForge.Infrastructure/Services/FfmpegService.cs b/src/ClipForge.Infrastructure/Services/FfmpegService.cs new file mode 100644 index 0000000000000000000000000000000000000000..78d75b7a2e01ff09eff7dcc251d9d80ccd09dae7 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/FfmpegService.cs @@ -0,0 +1,214 @@ +using System.Diagnostics; +using System.Globalization; +using ClipForge.Core.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +public class FfmpegService : IFfmpegService +{ + private readonly ILogger _logger; + + public FfmpegService(ILogger logger) + { + _logger = logger; + } + + public async Task AssembleVerticalVideoAsync(string audioPath, IReadOnlyList backgroundClips, string outputPath, CancellationToken ct = default) + { + _logger.LogInformation("Assembling vertical video with {ClipCount} background items", backgroundClips.Count); + + // Detect if inputs are images or videos + var isImages = backgroundClips.All(f => + f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || + f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || + f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + f.EndsWith(".webp", StringComparison.OrdinalIgnoreCase)); + + if (isImages && backgroundClips.Count > 0) + { + await AssembleFromImagesAsync(audioPath, backgroundClips, outputPath, ct); + } + else + { + await AssembleFromVideosAsync(audioPath, backgroundClips, outputPath, ct); + } + + _logger.LogInformation("Video assembled successfully: {OutputPath}", outputPath); + return outputPath; + } + + private async Task AssembleFromImagesAsync(string audioPath, IReadOnlyList images, string outputPath, CancellationToken ct) + { + _logger.LogInformation("Using Ken Burns effect with {Count} images", images.Count); + + // Get audio duration to calculate time per image + var audioDuration = await GetMediaDurationAsync(audioPath, ct); + if (audioDuration <= 0) audioDuration = 45; + var timePerImage = audioDuration / images.Count; + + // Build FFmpeg command with Ken Burns effect (zoom + pan) on each image + var inputArgs = new List(); + var filterParts = new List(); + + for (int i = 0; i < images.Count; i++) + { + inputArgs.Add($"-loop 1 -t {timePerImage.ToString("F2", CultureInfo.InvariantCulture)} -i \"{images[i]}\""); + + var frames = (int)(timePerImage * 25); + + // Ken Burns: alternate between zoom-in and zoom-out for variety + string zoomEffect; + if (i % 3 == 0) + { + // Zoom in from center + zoomEffect = $"zoompan=z='min(zoom+0.002,1.4)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s=1080x1920:fps=25"; + } + else if (i % 3 == 1) + { + // Zoom out + pan down + zoomEffect = $"zoompan=z='if(lte(zoom,1.0),1.4,max(1.001,zoom-0.002))':x='iw/2-(iw/zoom/2)':y='ih/4-(ih/zoom/4)':d={frames}:s=1080x1920:fps=25"; + } + else + { + // Slow pan right + zoomEffect = $"zoompan=z='1.2':x='iw/4+((iw/2-iw/4)*on/{frames})':y='ih/2-(ih/zoom/2)':d={frames}:s=1080x1920:fps=25"; + } + + filterParts.Add($"[{i}:v]scale=1920:1920:force_original_aspect_ratio=increase,crop=1080:1920,{zoomEffect},setsar=1[v{i}]"); + } + + // Concatenate all image clips + var concatInputs = string.Join("", Enumerable.Range(0, images.Count).Select(i => $"[v{i}]")); + filterParts.Add($"{concatInputs}concat=n={images.Count}:v=1:a=0[outv]"); + + var filterComplex = string.Join(";", filterParts); + + // Add audio + inputArgs.Add($"-i \"{audioPath}\""); + var audioIndex = images.Count; + + var args = $"{string.Join(" ", inputArgs)} -filter_complex \"{filterComplex}\" -map \"[outv]\" -map {audioIndex}:a -c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 -c:a aac -b:a 192k -shortest -y \"{outputPath}\""; + + await RunFfmpegAsync(args, ct); + } + + private async Task AssembleFromVideosAsync(string audioPath, IReadOnlyList backgroundClips, string outputPath, CancellationToken ct) + { + // Simple approach: scale + concat all clips, then merge with audio using -shortest + var inputArgs = new List(); + var filterParts = new List(); + + for (int i = 0; i < backgroundClips.Count; i++) + { + inputArgs.Add($"-i \"{backgroundClips[i]}\""); + } + + inputArgs.Add($"-i \"{audioPath}\""); + int audioIndex = backgroundClips.Count; + + // Scale each clip to vertical 1080x1920 + for (int i = 0; i < backgroundClips.Count; i++) + { + filterParts.Add($"[{i}:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1,fps=25[v{i}]"); + } + + // Concat all clips + var concatInputs = string.Join("", Enumerable.Range(0, backgroundClips.Count).Select(i => $"[v{i}]")); + filterParts.Add($"{concatInputs}concat=n={backgroundClips.Count}:v=1:a=0[outv]"); + + var filterComplex = string.Join(";", filterParts); + + var args = $"{string.Join(" ", inputArgs)} " + + $"-filter_complex \"{filterComplex}\" " + + $"-map \"[outv]\" -map {audioIndex}:a " + + $"-c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 " + + $"-c:a aac -b:a 192k -shortest -y \"{outputPath}\""; + + await RunFfmpegAsync(args, ct); + } + + public async Task AddSubtitlesToVideoAsync(string videoPath, string srtPath, string outputPath, CancellationToken ct = default) + { + _logger.LogInformation("Adding subtitles to video: {VideoPath}", videoPath); + + var escapedSrtPath = srtPath.Replace("\\", "/").Replace(":", "\\:"); + + var args = $"-i \"{videoPath}\" -vf \"subtitles='{escapedSrtPath}':force_style='FontName=Arial,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,Outline=3,Alignment=2,MarginV=40'\" -c:v libx264 -profile:v baseline -level 3.1 -pix_fmt yuv420p -preset fast -crf 23 -c:a copy -y \"{outputPath}\""; + + await RunFfmpegAsync(args, ct); + + _logger.LogInformation("Subtitles added successfully: {OutputPath}", outputPath); + return outputPath; + } + + public async Task GetMediaDurationAsync(string filePath, CancellationToken ct = default) + { + var args = $"-i \"{filePath}\" -show_entries format=duration -v quiet -of csv=\"p=0\""; + + var output = await RunFfprobeAsync(args, ct); + if (double.TryParse(output.Trim(), CultureInfo.InvariantCulture, out var duration)) + return duration; + + return 0; + } + + public async Task GenerateThumbnailAsync(string videoPath, string outputPath, double atSecond = 1.0, CancellationToken ct = default) + { + var timeStr = TimeSpan.FromSeconds(atSecond).ToString(@"hh\:mm\:ss\.fff"); + var args = $"-i \"{videoPath}\" -ss {timeStr} -vframes 1 -y \"{outputPath}\""; + + await RunFfmpegAsync(args, ct); + return outputPath; + } + + private async Task RunFfmpegAsync(string arguments, CancellationToken ct) + { + _logger.LogDebug("FFmpeg args: {Args}", arguments); + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = arguments, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + var stderr = await process.StandardError.ReadToEndAsync(ct); + await process.WaitForExitAsync(ct); + + if (process.ExitCode != 0) + { + _logger.LogError("FFmpeg failed with exit code {ExitCode}: {Error}", process.ExitCode, stderr[..Math.Min(stderr.Length, 500)]); + throw new InvalidOperationException($"FFmpeg failed (exit code {process.ExitCode}): {stderr[..Math.Min(stderr.Length, 300)]}"); + } + } + + private async Task RunFfprobeAsync(string arguments, CancellationToken ct) + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "ffprobe", + Arguments = arguments, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + var output = await process.StandardOutput.ReadToEndAsync(ct); + await process.WaitForExitAsync(ct); + + return output; + } +} diff --git a/src/ClipForge.Infrastructure/Services/GeminiClient.cs b/src/ClipForge.Infrastructure/Services/GeminiClient.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad369c8e62dcef5e8c91ccf72ef15730d7136d76 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/GeminiClient.cs @@ -0,0 +1,76 @@ +using System.Text; +using System.Text.Json; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class GeminiClient : IOpenAiClient +{ + private readonly HttpClient _httpClient; + private readonly OpenAiSettings _settings; + private readonly ILogger _logger; + + public GeminiClient(HttpClient httpClient, IOptions settings, ILogger logger) + { + _httpClient = httpClient; + _settings = settings.Value; + _logger = logger; + } + + public async Task GenerateChatCompletionAsync(string systemPrompt, string userPrompt, CancellationToken ct = default) + { + var url = $"https://generativelanguage.googleapis.com/v1beta/models/{_settings.Model}:generateContent?key={_settings.ApiKey}"; + + var requestBody = new + { + contents = new[] + { + new + { + parts = new[] + { + new { text = $"{systemPrompt}\n\n{userPrompt}" } + } + } + }, + generationConfig = new + { + temperature = 0.9, + maxOutputTokens = 4000 + } + }; + + var json = JsonSerializer.Serialize(requestBody); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + _logger.LogInformation("Sending request to Gemini model {Model}", _settings.Model); + + var response = await _httpClient.PostAsync(url, content, ct); + var responseBody = await response.Content.ReadAsStringAsync(ct); + + if (!response.IsSuccessStatusCode) + { + _logger.LogError("Gemini API error {Status}: {Body}", response.StatusCode, responseBody[..Math.Min(responseBody.Length, 300)]); + throw new HttpRequestException($"Gemini API error: {response.StatusCode}"); + } + + using var doc = JsonDocument.Parse(responseBody); + var text = doc.RootElement + .GetProperty("candidates")[0] + .GetProperty("content") + .GetProperty("parts")[0] + .GetProperty("text") + .GetString(); + + return text ?? string.Empty; + } + + public Task GenerateSpeechAsync(string text, string voice = "alloy", CancellationToken ct = default) + { + // Not used - Edge TTS handles speech + throw new NotImplementedException("Use Edge TTS for speech generation"); + } +} diff --git a/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs b/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs new file mode 100644 index 0000000000000000000000000000000000000000..1c0ffdacf2c1c9e3199cb363382e1d13149e1835 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs @@ -0,0 +1,108 @@ +using System.Text.Json; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +/// +/// Downloads photos from Pexels API (free, reliable, high quality). +/// Used as background for videos with Ken Burns effect. +/// +public class GoogleImageSearchService : IStockMediaService +{ + private readonly HttpClient _httpClient; + private readonly PexelsSettings _settings; + private readonly ILogger _logger; + + public GoogleImageSearchService(HttpClient httpClient, IOptions settings, ILogger logger) + { + _httpClient = httpClient; + _settings = settings.Value; + _logger = logger; + + _httpClient.DefaultRequestHeaders.Add("Authorization", _settings.ApiKey); + } + + public async Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) + { + var images = await DownloadImagesAsync(query, 1, outputDir, ct); + return images.FirstOrDefault() ?? string.Empty; + } + + public async Task> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default) + { + return await DownloadImagesAsync(query, count, outputDir, ct); + } + + private async Task> DownloadImagesAsync(string query, int count, string outputDir, CancellationToken ct) + { + _logger.LogInformation("Searching Pexels photos for '{Query}', count: {Count}", query, count); + Directory.CreateDirectory(outputDir); + + var downloadedFiles = new List(); + + try + { + // Use Pexels photo search API - orientation=portrait for vertical images + var searchUrl = $"https://api.pexels.com/v1/search?query={Uri.EscapeDataString(query)}&per_page={count}&orientation=portrait&size=large"; + + var response = await _httpClient.GetAsync(searchUrl, ct); + + if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("Pexels photo search returned {Status} for '{Query}'", response.StatusCode, query); + return downloadedFiles; + } + + var json = await response.Content.ReadAsStringAsync(ct); + using var doc = JsonDocument.Parse(json); + + if (!doc.RootElement.TryGetProperty("photos", out var photos)) + return downloadedFiles; + + foreach (var photo in photos.EnumerateArray()) + { + if (downloadedFiles.Count >= count) break; + + try + { + // Get the "large2x" or "portrait" size for best quality + var src = photo.GetProperty("src"); + var imageUrl = src.TryGetProperty("portrait", out var portrait) + ? portrait.GetString() + : src.TryGetProperty("large2x", out var large2x) + ? large2x.GetString() + : src.GetProperty("large").GetString(); + + if (string.IsNullOrEmpty(imageUrl)) continue; + + var imageResponse = await _httpClient.GetAsync(imageUrl, ct); + if (!imageResponse.IsSuccessStatusCode) continue; + + var bytes = await imageResponse.Content.ReadAsByteArrayAsync(ct); + if (bytes.Length < 5000) continue; + + var fileName = $"{Guid.NewGuid()}.jpg"; + var filePath = Path.Combine(outputDir, fileName); + await File.WriteAllBytesAsync(filePath, bytes, ct); + + downloadedFiles.Add(filePath); + _logger.LogInformation("Downloaded Pexels photo ({Size}KB) for '{Query}'", bytes.Length / 1024, query); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Failed to download photo"); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Pexels photo search failed for '{Query}'", query); + } + + _logger.LogInformation("Downloaded {Count} photos for '{Query}'", downloadedFiles.Count, query); + return downloadedFiles; + } +} diff --git a/src/ClipForge.Infrastructure/Services/IdeaGenerationService.cs b/src/ClipForge.Infrastructure/Services/IdeaGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..265f5022301cb30e4383a2cfc48834443991e670 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/IdeaGenerationService.cs @@ -0,0 +1,95 @@ +using System.Text.Json; +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +public class IdeaGenerationService : IIdeaGenerationService +{ + private readonly IOpenAiClient _openAi; + private readonly IVideoIdeaRepository _ideaRepository; + private readonly ILogger _logger; + + public IdeaGenerationService(IOpenAiClient openAi, IVideoIdeaRepository ideaRepository, ILogger logger) + { + _openAi = openAi; + _ideaRepository = ideaRepository; + _logger = logger; + } + + public async Task GenerateIdeaAsync(string niche, string platform = "tiktok", CancellationToken ct = default) + { + var ideas = await GenerateBatchIdeasAsync(niche, 1, platform, ct); + return ideas.First(); + } + + public async Task> GenerateBatchIdeasAsync(string niche, int count = 5, string platform = "tiktok", CancellationToken ct = default) + { + _logger.LogInformation("Generating {Count} video ideas for niche '{Niche}' on {Platform}", count, niche, platform); + + var systemPrompt = @"Você é um estrategista de conteúdo viral especializado em TikTok/Reels/Shorts no Brasil. + +REGRAS: +1. Cada ideia DEVE ser baseada em um FATO REAL, ESPECÍFICO e SURPREENDENTE +2. O título deve ser curto, impactante e gerar curiosidade IMEDIATA (estilo clickbait mas verdadeiro) +3. O hook deve ser uma frase que CHOCA nos primeiros 2 segundos - um fato que a pessoa não sabia +4. Use linguagem brasileira informal + +Responda APENAS com um JSON array: +[{""topic"": ""tema específico e detalhado"", ""title"": ""título viral em português (max 50 chars)"", ""hook"": ""frase de abertura chocante em português"", ""targetAudience"": ""público alvo"", ""tags"": ""hashtags separadas por vírgula""}]"; + + var userPrompt = $@"Gere {count} ideias de vídeo VIRAL sobre: '{niche}' +Plataforma: {platform} + +IMPORTANTE: Cada ideia deve revelar algo que 99% das pessoas NÃO sabem sobre o tema. Fatos de bastidores, polêmicas, números absurdos, coincidências malucas. Seja ESPECÍFICO."; + + var response = await _openAi.GenerateChatCompletionAsync(systemPrompt, userPrompt, ct); + + var jsonContent = ExtractJson(response); + var ideasData = JsonSerializer.Deserialize>(jsonContent, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }) ?? []; + + var ideas = new List(); + foreach (var dto in ideasData) + { + var idea = new VideoIdea + { + Topic = dto.Topic ?? niche, + Title = dto.Title ?? "Untitled", + Hook = dto.Hook ?? "", + TargetAudience = dto.TargetAudience ?? "general", + Platform = platform, + Niche = niche, + Tags = dto.Tags, + Status = "pending" + }; + + await _ideaRepository.AddAsync(idea, ct); + ideas.Add(idea); + } + + _logger.LogInformation("Generated {Count} ideas successfully", ideas.Count); + return ideas; + } + + private static string ExtractJson(string response) + { + var trimmed = response.Trim(); + if (trimmed.StartsWith("```")) + { + var firstNewline = trimmed.IndexOf('\n'); + var lastBackticks = trimmed.LastIndexOf("```"); + if (firstNewline > 0 && lastBackticks > firstNewline) + { + trimmed = trimmed[(firstNewline + 1)..lastBackticks].Trim(); + } + } + return trimmed; + } + + private record IdeaDto(string? Topic, string? Title, string? Hook, string? TargetAudience, string? Tags); +} diff --git a/src/ClipForge.Infrastructure/Services/OpenAiClient.cs b/src/ClipForge.Infrastructure/Services/OpenAiClient.cs new file mode 100644 index 0000000000000000000000000000000000000000..3de7ae334a4d519b76a94f35424c66081ee8afdc --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/OpenAiClient.cs @@ -0,0 +1,81 @@ +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class OpenAiClient : IOpenAiClient +{ + private readonly HttpClient _httpClient; + private readonly OpenAiSettings _settings; + private readonly ILogger _logger; + + public OpenAiClient(HttpClient httpClient, IOptions settings, ILogger logger) + { + _httpClient = httpClient; + _settings = settings.Value; + _logger = logger; + + _httpClient.BaseAddress = new Uri(_settings.BaseUrl.TrimEnd('/') + "/"); + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _settings.ApiKey); + } + + public async Task GenerateChatCompletionAsync(string systemPrompt, string userPrompt, CancellationToken ct = default) + { + var requestBody = new + { + model = _settings.Model, + messages = new[] + { + new { role = "system", content = systemPrompt }, + new { role = "user", content = userPrompt } + }, + temperature = 0.8, + max_tokens = 4000 + }; + + var json = JsonSerializer.Serialize(requestBody); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + _logger.LogInformation("Sending chat completion request to model {Model}", _settings.Model); + + var response = await _httpClient.PostAsync("chat/completions", content, ct); + response.EnsureSuccessStatusCode(); + + var responseJson = await response.Content.ReadAsStringAsync(ct); + using var doc = JsonDocument.Parse(responseJson); + + var message = doc.RootElement + .GetProperty("choices")[0] + .GetProperty("message") + .GetProperty("content") + .GetString(); + + return message ?? string.Empty; + } + + public async Task GenerateSpeechAsync(string text, string voice = "alloy", CancellationToken ct = default) + { + var requestBody = new + { + model = _settings.TtsModel, + input = text, + voice, + response_format = "mp3" + }; + + var json = JsonSerializer.Serialize(requestBody); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + _logger.LogInformation("Generating TTS with voice {Voice}, text length: {Length}", voice, text.Length); + + var response = await _httpClient.PostAsync("audio/speech", content, ct); + response.EnsureSuccessStatusCode(); + + return await response.Content.ReadAsByteArrayAsync(ct); + } +} diff --git a/src/ClipForge.Infrastructure/Services/PexelsStockMediaService.cs b/src/ClipForge.Infrastructure/Services/PexelsStockMediaService.cs new file mode 100644 index 0000000000000000000000000000000000000000..cd7a060dcb3b7faa37fb12b7b9a038739a56fa6d --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/PexelsStockMediaService.cs @@ -0,0 +1,90 @@ +using System.Net.Http.Headers; +using System.Text.Json; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class PexelsStockMediaService : IStockMediaService +{ + private readonly HttpClient _httpClient; + private readonly PexelsSettings _settings; + private readonly ILogger _logger; + + public PexelsStockMediaService(HttpClient httpClient, IOptions settings, ILogger logger) + { + _httpClient = httpClient; + _settings = settings.Value; + _logger = logger; + + _httpClient.BaseAddress = new Uri(_settings.BaseUrl); + _httpClient.DefaultRequestHeaders.Add("Authorization", _settings.ApiKey); + } + + public async Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) + { + var videos = await DownloadMultipleVideosAsync(query, 1, outputDir, ct); + return videos.FirstOrDefault() ?? string.Empty; + } + + public async Task> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default) + { + _logger.LogInformation("Searching Pexels for '{Query}', count: {Count}", query, count); + + Directory.CreateDirectory(outputDir); + + var response = await _httpClient.GetAsync($"/videos/search?query={Uri.EscapeDataString(query)}&per_page={count}&orientation=portrait", ct); + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(ct); + using var doc = JsonDocument.Parse(json); + + var downloadedFiles = new List(); + var videos = doc.RootElement.GetProperty("videos"); + + foreach (var video in videos.EnumerateArray()) + { + var videoFiles = video.GetProperty("video_files"); + // Prefer HD quality vertical video + string? downloadUrl = null; + + foreach (var file in videoFiles.EnumerateArray()) + { + var width = file.TryGetProperty("width", out var w) ? w.GetInt32() : 0; + var height = file.TryGetProperty("height", out var h) ? h.GetInt32() : 0; + + // Prefer vertical or square videos with decent quality + if (height >= width && height >= 720) + { + downloadUrl = file.GetProperty("link").GetString(); + break; + } + } + + // Fallback to first available file + if (downloadUrl is null && videoFiles.GetArrayLength() > 0) + { + downloadUrl = videoFiles[0].GetProperty("link").GetString(); + } + + if (downloadUrl is not null) + { + var fileName = $"{Guid.NewGuid()}.mp4"; + var filePath = Path.Combine(outputDir, fileName); + + using var videoResponse = await _httpClient.GetAsync(downloadUrl, ct); + videoResponse.EnsureSuccessStatusCode(); + + var bytes = await videoResponse.Content.ReadAsByteArrayAsync(ct); + await File.WriteAllBytesAsync(filePath, bytes, ct); + + downloadedFiles.Add(filePath); + _logger.LogInformation("Downloaded stock video: {FilePath}", filePath); + } + } + + return downloadedFiles; + } +} diff --git a/src/ClipForge.Infrastructure/Services/SchedulerService.cs b/src/ClipForge.Infrastructure/Services/SchedulerService.cs new file mode 100644 index 0000000000000000000000000000000000000000..91d3fc389d41bd4dfd21e07c630f84a2ab2c2637 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/SchedulerService.cs @@ -0,0 +1,53 @@ +using ClipForge.Core.Interfaces.Services; +using Hangfire; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +public class SchedulerService : ISchedulerService +{ + private readonly IBackgroundJobClient _backgroundJobs; + private readonly IRecurringJobManager _recurringJobs; + private readonly ILogger _logger; + + public SchedulerService( + IBackgroundJobClient backgroundJobs, + IRecurringJobManager recurringJobs, + ILogger logger) + { + _backgroundJobs = backgroundJobs; + _recurringJobs = recurringJobs; + _logger = logger; + } + + public Task ScheduleFullPipelineAsync(string niche, string platform = "tiktok", CancellationToken ct = default) + { + _logger.LogInformation("Scheduling full pipeline for niche '{Niche}' on {Platform}", niche, platform); + + // Enqueue using IIdeaGenerationService as entry point - the pipeline endpoint handles orchestration + _backgroundJobs.Enqueue(svc => svc.GenerateIdeaAsync(niche, platform, CancellationToken.None)); + + return Task.CompletedTask; + } + + public Task ScheduleRecurringGenerationAsync(string niche, string cronExpression, string platform = "tiktok", CancellationToken ct = default) + { + var jobId = $"pipeline-{niche}-{platform}".ToLowerInvariant().Replace(" ", "-"); + + _logger.LogInformation("Scheduling recurring pipeline '{JobId}' with cron '{Cron}'", jobId, cronExpression); + + _recurringJobs.AddOrUpdate( + jobId, + svc => svc.GenerateIdeaAsync(niche, platform, CancellationToken.None), + cronExpression); + + return Task.CompletedTask; + } + + public Task CancelRecurringJobAsync(string jobId, CancellationToken ct = default) + { + _logger.LogInformation("Cancelling recurring job '{JobId}'", jobId); + _recurringJobs.RemoveIfExists(jobId); + return Task.CompletedTask; + } +} diff --git a/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs b/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..efbc54ff26fdcab66446fafba1737287fce57b87 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/ScriptGenerationService.cs @@ -0,0 +1,132 @@ +using System.Text.Json; +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +public class ScriptGenerationService : IScriptGenerationService +{ + private readonly IOpenAiClient _openAi; + private readonly IVideoIdeaRepository _ideaRepository; + private readonly IVideoScriptRepository _scriptRepository; + private readonly ILogger _logger; + + public ScriptGenerationService( + IOpenAiClient openAi, + IVideoIdeaRepository ideaRepository, + IVideoScriptRepository scriptRepository, + ILogger logger) + { + _openAi = openAi; + _ideaRepository = ideaRepository; + _scriptRepository = scriptRepository; + _logger = logger; + } + + public async Task GenerateScriptAsync(Guid ideaId, CancellationToken ct = default) + { + var idea = await _ideaRepository.GetByIdAsync(ideaId, ct) + ?? throw new InvalidOperationException($"Video idea {ideaId} not found"); + + _logger.LogInformation("Generating script for idea: {Title}", idea.Title); + + var systemPrompt = @"Você é um roteirista de elite. Seus roteiros são usados em vídeos que viralizam com MILHÕES de views no TikTok. + +Seu estilo é: IMPACTANTE, RÁPIDO, CHEIO DE INFORMAÇÃO BOMBÁSTICA, como se fosse um documentário da Netflix condensado em 60 segundos. + +REGRAS INEGOCIÁVEIS: +1. O roteiro DEVE ter entre 200-300 palavras (50-70 segundos de narração) +2. PRIMEIRA FRASE: Uma bomba. Um fato tão absurdo que a pessoa PARA de rolar o feed. Exemplos: 'O sobrinho do Michael Jackson gastou 3 anos aprendendo a andar EXATAMENTE como o tio pra esse filme.' ou 'Hollywood gastou 150 MILHÕES de dólares pra recontar a vida do maior artista de todos os tempos.' +3. CADA FRASE deve conter um fato novo, um número, um nome, uma revelação. ZERO enrolação. +4. Use CONTRASTE e TENSÃO: 'Mas nem tudo foi fácil...', 'O que ninguém esperava era que...', 'E aqui vem a parte mais insana...' +5. Linguagem: como um narrador de documentário brasileiro falando com um amigo. Informal mas PODEROSO. +6. TERMINE com uma frase que OBRIGA a pessoa a comentar ou compartilhar. +7. NÃO use: 'é muito interessante', 'vale a pena', 'fique ligado', 'se inscreva'. Isso é LIXO. +8. CADA informação deve ser REAL e VERIFICÁVEL. + +Para as cenas: gere termos de busca pro YouTube que retornem vídeos VISUAIS do tema (performances, trailers, entrevistas, clipes musicais). NÃO use termos que retornem vídeos de texto/podcast/reaction. + +Responda APENAS com JSON: +{ + ""scriptText"": ""narração completa em português brasileiro"", + ""scenes"": [{""description"": ""termo de busca YouTube"", ""duration"": 8}], + ""estimatedDurationSeconds"": 55 +}"; + + var userPrompt = $@"Crie um roteiro NÍVEL HOLLYWOOD sobre: +Tema: {idea.Topic} +Título: {idea.Title} +Gancho: {idea.Hook} +Público: {idea.TargetAudience} +Plataforma: {idea.Platform} + +EXIGÊNCIAS ABSOLUTAS: +- Mínimo 8 fatos REAIS e ESPECÍFICOS (nomes completos, datas, valores em dólares, bastidores) +- Primeira frase TÃO impactante que é impossível não assistir +- Ritmo de metralhadora: fato-fato-fato-fato sem pausa +- Linguagem de documentário Netflix narrado por brasileiro +- Cenas: use termos como 'Michael Jackson Thriller performance', 'Michael Jackson moonwalk live', 'Jaafar Jackson dancing' — termos que retornem VÍDEOS VISUAIS no YouTube, não podcasts ou textos +- Mínimo 7 cenas diferentes"; + + var response = await _openAi.GenerateChatCompletionAsync(systemPrompt, userPrompt, ct); + var jsonContent = ExtractJson(response); + + var scriptData = JsonSerializer.Deserialize(jsonContent, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }) ?? throw new InvalidOperationException("Failed to parse script response"); + + var script = new VideoScript + { + VideoIdeaId = ideaId, + ScriptText = scriptData.ScriptText ?? "", + Scenes = scriptData.Scenes is not null ? JsonSerializer.Serialize(scriptData.Scenes) : "[]", + EstimatedDurationSeconds = scriptData.EstimatedDurationSeconds > 0 ? scriptData.EstimatedDurationSeconds : 50, + Tone = "engaging", + Language = "pt-BR" + }; + + await _scriptRepository.AddAsync(script, ct); + + idea.Status = "scripted"; + await _ideaRepository.UpdateAsync(idea, ct); + + _logger.LogInformation("Script generated for idea {IdeaId}, duration: {Duration}s", ideaId, script.EstimatedDurationSeconds); + return script; + } + + public async Task GenerateScriptFromTopicAsync(string topic, string tone = "engaging", string language = "pt-BR", CancellationToken ct = default) + { + var idea = new VideoIdea + { + Topic = topic, + Title = topic, + Hook = $"Você sabia que {topic}?", + TargetAudience = "general", + Platform = "tiktok", + Status = "pending" + }; + + await _ideaRepository.AddAsync(idea, ct); + return await GenerateScriptAsync(idea.Id, ct); + } + + private static string ExtractJson(string response) + { + var trimmed = response.Trim(); + if (trimmed.StartsWith("```")) + { + var firstNewline = trimmed.IndexOf('\n'); + var lastBackticks = trimmed.LastIndexOf("```"); + if (firstNewline > 0 && lastBackticks > firstNewline) + { + trimmed = trimmed[(firstNewline + 1)..lastBackticks].Trim(); + } + } + return trimmed; + } + + private record ScriptDto(string? ScriptText, JsonElement? Scenes, int EstimatedDurationSeconds); +} diff --git a/src/ClipForge.Infrastructure/Services/SubtitleService.cs b/src/ClipForge.Infrastructure/Services/SubtitleService.cs new file mode 100644 index 0000000000000000000000000000000000000000..007bcc785b92b5134b309373979ff14cfcb821b5 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/SubtitleService.cs @@ -0,0 +1,102 @@ +using System.Text; +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class SubtitleService : ISubtitleService +{ + private readonly IVideoAssetRepository _videoAssetRepository; + private readonly IVideoScriptRepository _scriptRepository; + private readonly IRepository _captionRepository; + private readonly StorageSettings _storage; + private readonly ILogger _logger; + + public SubtitleService( + IVideoAssetRepository videoAssetRepository, + IVideoScriptRepository scriptRepository, + IRepository captionRepository, + IOptions storage, + ILogger logger) + { + _videoAssetRepository = videoAssetRepository; + _scriptRepository = scriptRepository; + _captionRepository = captionRepository; + _storage = storage.Value; + _logger = logger; + } + + public async Task GenerateSubtitlesAsync(Guid videoAssetId, CancellationToken ct = default) + { + var videoAsset = await _videoAssetRepository.GetByIdAsync(videoAssetId, ct) + ?? throw new InvalidOperationException($"Video asset {videoAssetId} not found"); + + var script = await _scriptRepository.GetByIdAsync(videoAsset.VideoScriptId, ct) + ?? throw new InvalidOperationException($"Script not found for video asset {videoAssetId}"); + + _logger.LogInformation("Generating subtitles for video asset {VideoAssetId}", videoAssetId); + + var srtContent = await GenerateSrtFromTextAsync(script.ScriptText, videoAsset.DurationSeconds, ct); + + // Save SRT file + var subtitleDir = Path.Combine(_storage.BasePath, _storage.SubtitleFolder); + Directory.CreateDirectory(subtitleDir); + + var srtPath = Path.Combine(subtitleDir, $"{videoAssetId}.srt"); + await File.WriteAllTextAsync(srtPath, srtContent, Encoding.UTF8, ct); + + var captionAsset = new CaptionAsset + { + VideoAssetId = videoAssetId, + SrtFilePath = srtPath, + CaptionStyle = "dynamic", + FontFamily = "Montserrat", + FontSize = 48, + FontColor = "#FFFFFF", + StrokeColor = "#000000", + StrokeWidth = 2 + }; + + await _captionRepository.AddAsync(captionAsset, ct); + + _logger.LogInformation("Subtitles generated: {SrtPath}", srtPath); + return captionAsset; + } + + public Task GenerateSrtFromTextAsync(string text, double totalDuration, CancellationToken ct = default) + { + // Split text into segments of ~5-8 words for dynamic captions + var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var segments = new List(); + var wordsPerSegment = 5; + + for (int i = 0; i < words.Length; i += wordsPerSegment) + { + var segment = string.Join(" ", words.Skip(i).Take(wordsPerSegment)); + segments.Add(segment); + } + + var timePerSegment = totalDuration / segments.Count; + var sb = new StringBuilder(); + + for (int i = 0; i < segments.Count; i++) + { + var startTime = TimeSpan.FromSeconds(i * timePerSegment); + var endTime = TimeSpan.FromSeconds((i + 1) * timePerSegment); + + sb.AppendLine((i + 1).ToString()); + sb.AppendLine($"{FormatSrtTime(startTime)} --> {FormatSrtTime(endTime)}"); + sb.AppendLine(segments[i]); + sb.AppendLine(); + } + + return Task.FromResult(sb.ToString()); + } + + private static string FormatSrtTime(TimeSpan time) + => $"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2},{time.Milliseconds:D3}"; +} diff --git a/src/ClipForge.Infrastructure/Services/VideoAssemblyService.cs b/src/ClipForge.Infrastructure/Services/VideoAssemblyService.cs new file mode 100644 index 0000000000000000000000000000000000000000..5dac9478d1e3b6e642b431fa76d514f733ba98d7 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/VideoAssemblyService.cs @@ -0,0 +1,161 @@ +using System.Text.Json; +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class VideoAssemblyService : IVideoAssemblyService +{ + private readonly IVideoScriptRepository _scriptRepository; + private readonly IRepository _voiceRepository; + private readonly IVideoAssetRepository _videoAssetRepository; + private readonly IFfmpegService _ffmpeg; + private readonly IStockMediaService _stockMedia; + private readonly ISubtitleService _subtitleService; + private readonly StorageSettings _storage; + private readonly ILogger _logger; + + public VideoAssemblyService( + IVideoScriptRepository scriptRepository, + IRepository voiceRepository, + IVideoAssetRepository videoAssetRepository, + IFfmpegService ffmpeg, + IStockMediaService stockMedia, + ISubtitleService subtitleService, + IOptions storage, + ILogger logger) + { + _scriptRepository = scriptRepository; + _voiceRepository = voiceRepository; + _videoAssetRepository = videoAssetRepository; + _ffmpeg = ffmpeg; + _stockMedia = stockMedia; + _subtitleService = subtitleService; + _storage = storage.Value; + _logger = logger; + } + + public async Task AssembleVideoAsync(Guid scriptId, CancellationToken ct = default) + { + var script = await _scriptRepository.GetByIdAsync(scriptId, ct) + ?? throw new InvalidOperationException($"Script {scriptId} not found"); + + _logger.LogInformation("Starting video assembly for script {ScriptId}", scriptId); + + // Create video asset record + var videoAsset = new VideoAsset + { + VideoScriptId = scriptId, + Status = "processing" + }; + await _videoAssetRepository.AddAsync(videoAsset, ct); + + try + { + // 1. Get voice asset (should already exist) + var voiceAssets = await _voiceRepository.GetAllAsync(ct); + var voiceAsset = voiceAssets.FirstOrDefault(v => v is VoiceAsset va && va.VideoScriptId == scriptId) as VoiceAsset + ?? throw new InvalidOperationException($"Voice asset not found for script {scriptId}. Generate voice first."); + + // 2. Download background clips from YouTube + var scenes = ParseScenes(script.Scenes); + var tempDir = Path.Combine(_storage.BasePath, _storage.TempFolder, videoAsset.Id.ToString()); + Directory.CreateDirectory(tempDir); + + var backgroundClips = new List(); + + // Use the first 2-3 most specific scene descriptions as search queries + var searchQueries = scenes.Take(3).ToList(); + + foreach (var query in searchQueries) + { + if (backgroundClips.Count >= 8) break; + var neededPerQuery = Math.Max(3, (8 - backgroundClips.Count)); + var clips = await _stockMedia.DownloadMultipleVideosAsync(query, neededPerQuery, tempDir, ct); + backgroundClips.AddRange(clips); + } + + // If still not enough, try a broader search with the topic + if (backgroundClips.Count < 3) + { + var idea = await _scriptRepository.GetByIdAsync(scriptId, ct); + var broadQuery = script.ScriptText[..Math.Min(60, script.ScriptText.Length)]; + var extras = await _stockMedia.DownloadMultipleVideosAsync(broadQuery, 4, tempDir, ct); + backgroundClips.AddRange(extras); + } + + if (backgroundClips.Count == 0) + throw new InvalidOperationException("Could not download any background clips for the video."); + + // 3. Assemble video + var videoDir = Path.Combine(_storage.BasePath, _storage.VideoFolder); + Directory.CreateDirectory(videoDir); + + var rawVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}_raw.mp4"); + await _ffmpeg.AssembleVerticalVideoAsync(voiceAsset.FilePath, backgroundClips, rawVideoPath, ct); + + // 4. Generate subtitles + var duration = await _ffmpeg.GetMediaDurationAsync(rawVideoPath, ct); + videoAsset.DurationSeconds = duration; + await _videoAssetRepository.UpdateAsync(videoAsset, ct); + + var captionAsset = await _subtitleService.GenerateSubtitlesAsync(videoAsset.Id, ct); + + // 5. Burn subtitles into video + var finalVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}.mp4"); + await _ffmpeg.AddSubtitlesToVideoAsync(rawVideoPath, captionAsset.SrtFilePath, finalVideoPath, ct); + + // 6. Generate thumbnail + var thumbDir = Path.Combine(_storage.BasePath, _storage.ThumbnailFolder); + Directory.CreateDirectory(thumbDir); + var thumbPath = Path.Combine(thumbDir, $"{videoAsset.Id}.jpg"); + await _ffmpeg.GenerateThumbnailAsync(finalVideoPath, thumbPath, ct: ct); + + // 7. Update video asset + var fileInfo = new FileInfo(finalVideoPath); + videoAsset.FilePath = finalVideoPath; + videoAsset.ThumbnailPath = thumbPath; + videoAsset.FileSizeBytes = fileInfo.Length; + videoAsset.DurationSeconds = await _ffmpeg.GetMediaDurationAsync(finalVideoPath, ct); + videoAsset.Status = "completed"; + await _videoAssetRepository.UpdateAsync(videoAsset, ct); + + // Cleanup raw video + if (File.Exists(rawVideoPath)) + File.Delete(rawVideoPath); + + _logger.LogInformation("Video assembly completed: {FilePath}", finalVideoPath); + return videoAsset; + } + catch (Exception ex) + { + _logger.LogError(ex, "Video assembly failed for script {ScriptId}", scriptId); + videoAsset.Status = "failed"; + await _videoAssetRepository.UpdateAsync(videoAsset, ct); + throw; + } + } + + private static List ParseScenes(string scenesJson) + { + try + { + using var doc = JsonDocument.Parse(scenesJson); + var scenes = new List(); + foreach (var element in doc.RootElement.EnumerateArray()) + { + if (element.TryGetProperty("description", out var desc)) + scenes.Add(desc.GetString() ?? "nature"); + } + return scenes.Count > 0 ? scenes : ["nature", "city", "technology"]; + } + catch + { + return ["nature", "city", "technology"]; + } + } +} diff --git a/src/ClipForge.Infrastructure/Services/VoiceGenerationService.cs b/src/ClipForge.Infrastructure/Services/VoiceGenerationService.cs new file mode 100644 index 0000000000000000000000000000000000000000..2109f03ae2c6493b8b639a71be80962f9214ecc7 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/VoiceGenerationService.cs @@ -0,0 +1,80 @@ +using ClipForge.Core.Entities; +using ClipForge.Core.Interfaces; +using ClipForge.Core.Interfaces.Services; +using ClipForge.Infrastructure.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace ClipForge.Infrastructure.Services; + +public class VoiceGenerationService : IVoiceGenerationService +{ + private readonly EdgeTtsService _edgeTts; + private readonly IVideoScriptRepository _scriptRepository; + private readonly IRepository _voiceRepository; + private readonly IFfmpegService _ffmpeg; + private readonly StorageSettings _storage; + private readonly ILogger _logger; + + public VoiceGenerationService( + EdgeTtsService edgeTts, + IVideoScriptRepository scriptRepository, + IRepository voiceRepository, + IFfmpegService ffmpeg, + IOptions storage, + ILogger logger) + { + _edgeTts = edgeTts; + _scriptRepository = scriptRepository; + _voiceRepository = voiceRepository; + _ffmpeg = ffmpeg; + _storage = storage.Value; + _logger = logger; + } + + public async Task GenerateVoiceAsync(Guid scriptId, string voiceId = "pt-BR-FranciscaNeural", CancellationToken ct = default) + { + var script = await _scriptRepository.GetByIdAsync(scriptId, ct) + ?? throw new InvalidOperationException($"Script {scriptId} not found"); + + _logger.LogInformation("Generating voice for script {ScriptId} with Edge TTS voice {VoiceId}", scriptId, voiceId); + + // Map simple voice names to Edge TTS voices + var edgeVoice = voiceId switch + { + "alloy" or "female" or "francisca" => EdgeTtsService.Voices.FranciscaPtBr, + "male" or "antonio" => EdgeTtsService.Voices.AntonioNeural, + "young" or "thalita" => EdgeTtsService.Voices.ThalitaNeural, + _ when voiceId.Contains("Neural") => voiceId, // Already a full Edge voice name + _ => EdgeTtsService.Voices.FranciscaPtBr + }; + + var audioBytes = await _edgeTts.SynthesizeSpeechAsync(script.ScriptText, edgeVoice, ct); + + // Save audio file + var audioDir = Path.Combine(_storage.BasePath, _storage.AudioFolder); + Directory.CreateDirectory(audioDir); + + var fileName = $"{scriptId}_{edgeVoice}.mp3"; + var filePath = Path.Combine(audioDir, fileName); + await File.WriteAllBytesAsync(filePath, audioBytes, ct); + + // Get duration + var duration = await _ffmpeg.GetMediaDurationAsync(filePath, ct); + + var voiceAsset = new VoiceAsset + { + VideoScriptId = scriptId, + FilePath = filePath, + VoiceProvider = "edge-tts", + VoiceId = edgeVoice, + DurationSeconds = duration, + FileSizeBytes = audioBytes.Length + }; + + await _voiceRepository.AddAsync(voiceAsset, ct); + + _logger.LogInformation("Voice generated: {FilePath}, duration: {Duration}s", filePath, duration); + return voiceAsset; + } +} diff --git a/src/ClipForge.Infrastructure/Services/YouTubeMediaService.cs b/src/ClipForge.Infrastructure/Services/YouTubeMediaService.cs new file mode 100644 index 0000000000000000000000000000000000000000..fce7ed0b87d45bca9b13455718a3ed274346d987 --- /dev/null +++ b/src/ClipForge.Infrastructure/Services/YouTubeMediaService.cs @@ -0,0 +1,156 @@ +using System.Diagnostics; +using System.Text.Json; +using ClipForge.Core.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Infrastructure.Services; + +/// +/// Downloads clips from YouTube using yt-dlp. +/// Strategy: search for relevant videos, download them, then use FFmpeg to cut segments. +/// +public class YouTubeMediaService : IStockMediaService +{ + private readonly ILogger _logger; + + public YouTubeMediaService(ILogger logger) + { + _logger = logger; + } + + public async Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) + { + var clips = await DownloadMultipleVideosAsync(query, 1, outputDir, ct); + return clips.FirstOrDefault() ?? string.Empty; + } + + public async Task> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default) + { + _logger.LogInformation("YouTube: searching '{Query}', need {Count} clips", query, count); + Directory.CreateDirectory(outputDir); + + var downloadedFiles = new List(); + + // Search YouTube for relevant videos + var searchCount = Math.Max(count * 2, 6); + var args = $"\"ytsearch{searchCount}:{query}\" --dump-json --flat-playlist --no-download --quiet --no-warnings --no-check-certificates"; + + var searchOutput = await RunAndGetOutputAsync(args, ct); + if (string.IsNullOrEmpty(searchOutput)) return downloadedFiles; + + var videos = new List<(string Id, string Title)>(); + foreach (var line in searchOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + try + { + using var doc = JsonDocument.Parse(line.Trim()); + var root = doc.RootElement; + var id = root.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? "" : ""; + var title = root.TryGetProperty("title", out var t) ? t.GetString() ?? "" : ""; + var duration = root.TryGetProperty("duration", out var d) ? d.GetDouble() : 0; + + // Skip very short (<15s) or very long (>600s) videos + if (!string.IsNullOrEmpty(id) && duration > 15 && duration < 600) + { + videos.Add((id, title)); + _logger.LogInformation(" Found: '{Title}' ({Duration}s)", title[..Math.Min(60, title.Length)], duration); + } + } + catch { } + } + + // Download videos and cut 8-second segments from different parts + foreach (var video in videos.Take(count + 2)) + { + if (downloadedFiles.Count >= count) break; + + var outputFile = Path.Combine(outputDir, $"{Guid.NewGuid()}.mp4"); + var url = $"https://www.youtube.com/watch?v={video.Id}"; + + // Download full video (limited duration) + var dlArgs = $"\"{url}\" " + + $"-f \"bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best\" " + + $"--merge-output-format mp4 " + + $"-o \"{outputFile}\" " + + $"--no-playlist --quiet --no-warnings " + + $"--no-check-certificates " + + $"--socket-timeout 30 " + + $"--retries 3"; // Only download first 15 seconds + + _logger.LogInformation(" Downloading: '{Title}'...", video.Title[..Math.Min(50, video.Title.Length)]); + var success = await RunAsync(dlArgs, ct); + + if (success && File.Exists(outputFile) && new FileInfo(outputFile).Length > 100000) + { + downloadedFiles.Add(outputFile); + _logger.LogInformation(" ✓ Downloaded ({Size}KB): '{Title}'", + new FileInfo(outputFile).Length / 1024, video.Title[..Math.Min(40, video.Title.Length)]); + } + else + { + _logger.LogWarning(" ✗ Failed: '{Title}'", video.Title[..Math.Min(40, video.Title.Length)]); + if (File.Exists(outputFile)) File.Delete(outputFile); + } + } + + _logger.LogInformation("YouTube: downloaded {Count} clips for '{Query}'", downloadedFiles.Count, query); + return downloadedFiles; + } + + private async Task RunAndGetOutputAsync(string arguments, CancellationToken ct) + { + try + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "yt-dlp", + Arguments = arguments, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + var output = await process.StandardOutput.ReadToEndAsync(ct); + await process.WaitForExitAsync(ct); + return output; + } + catch (Exception ex) + { + _logger.LogError(ex, "yt-dlp failed"); + return string.Empty; + } + } + + private async Task RunAsync(string arguments, CancellationToken ct) + { + try + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "yt-dlp", + Arguments = arguments, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + process.Start(); + await process.StandardError.ReadToEndAsync(ct); + await process.WaitForExitAsync(ct); + return process.ExitCode == 0; + } + catch + { + return false; + } + } +} diff --git a/src/ClipForge.Workers/ClipForge.Workers.csproj b/src/ClipForge.Workers/ClipForge.Workers.csproj new file mode 100644 index 0000000000000000000000000000000000000000..420376527265615534c8d45c1b65d58d7fd7c683 --- /dev/null +++ b/src/ClipForge.Workers/ClipForge.Workers.csproj @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + net9.0 + enable + enable + + + diff --git a/src/ClipForge.Workers/Jobs/FullPipelineJob.cs b/src/ClipForge.Workers/Jobs/FullPipelineJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..031379cdc87878733405b0fc5fe9fdb5ecb8797d --- /dev/null +++ b/src/ClipForge.Workers/Jobs/FullPipelineJob.cs @@ -0,0 +1,62 @@ +using ClipForge.Core.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace ClipForge.Workers.Jobs; + +public class FullPipelineJob +{ + private readonly IIdeaGenerationService _ideaService; + private readonly IScriptGenerationService _scriptService; + private readonly IVoiceGenerationService _voiceService; + private readonly IVideoAssemblyService _assemblyService; + private readonly ILogger _logger; + + public FullPipelineJob( + IIdeaGenerationService ideaService, + IScriptGenerationService scriptService, + IVoiceGenerationService voiceService, + IVideoAssemblyService assemblyService, + ILogger logger) + { + _ideaService = ideaService; + _scriptService = scriptService; + _voiceService = voiceService; + _assemblyService = assemblyService; + _logger = logger; + } + + public async Task ExecuteAsync(string niche, string platform = "tiktok", string voiceId = "alloy") + { + _logger.LogInformation("Starting full pipeline for niche '{Niche}' on {Platform}", niche, platform); + + try + { + // Step 1: Generate idea + _logger.LogInformation("Step 1: Generating idea..."); + var idea = await _ideaService.GenerateIdeaAsync(niche, platform); + _logger.LogInformation("Idea generated: {Title}", idea.Title); + + // Step 2: Generate script + _logger.LogInformation("Step 2: Generating script..."); + var script = await _scriptService.GenerateScriptAsync(idea.Id); + _logger.LogInformation("Script generated, duration: {Duration}s", script.EstimatedDurationSeconds); + + // Step 3: Generate voice + _logger.LogInformation("Step 3: Generating voice..."); + var voice = await _voiceService.GenerateVoiceAsync(script.Id, voiceId); + _logger.LogInformation("Voice generated: {Duration}s", voice.DurationSeconds); + + // Step 4: Assemble video (includes subtitles) + _logger.LogInformation("Step 4: Assembling video..."); + var video = await _assemblyService.AssembleVideoAsync(script.Id); + _logger.LogInformation("Video assembled: {FilePath}, size: {Size}MB", video.FilePath, video.FileSizeBytes / 1024.0 / 1024.0); + + _logger.LogInformation("Full pipeline completed successfully for niche '{Niche}'", niche); + } + catch (Exception ex) + { + _logger.LogError(ex, "Full pipeline failed for niche '{Niche}'", niche); + throw; + } + } +} diff --git a/src/ClipForge.slnx b/src/ClipForge.slnx new file mode 100644 index 0000000000000000000000000000000000000000..a6a8d2917b9edb5307390fe152dd4242d3d2e3b4 --- /dev/null +++ b/src/ClipForge.slnx @@ -0,0 +1,7 @@ + + + + + + +