too many changes

This commit is contained in:
2026-10-07 02:17:30 +04:00
parent 0c7f3bce90
commit bcf985c17d
74 changed files with 4048 additions and 78 deletions
@@ -1,11 +1,17 @@
using Amazon.Runtime;
using Amazon.S3;
using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
using MemeVault.Infrastructure.Options;
using MemeVault.Infrastructure.Persistence;
using MemeVault.Infrastructure.Persistence.Repositories;
using MemeVault.Infrastructure.Persistence.Repositories;
using MemeVault.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using Telegram.Bot;
namespace MemeVault.Infrastructure;
@@ -15,6 +21,7 @@ public static class InfrastructureServiceExtensions
this IServiceCollection services,
IConfiguration config)
{
// ── PostgreSQL / EF Core ──────────────────────────────────────────────
services.AddDbContext<AppDbContext>(opts =>
opts.UseNpgsql(config.GetConnectionString("Postgres")));
@@ -24,8 +31,57 @@ public static class InfrastructureServiceExtensions
services.AddScoped<ICollectionRepository, CollectionRepository>();
services.AddScoped<ICollectionInviteRepository, CollectionInviteRepository>();
var redisConn = config.GetConnectionString("Redis") ?? "localhost:6379";
services.AddStackExchangeRedisCache(opts => opts.Configuration = redisConn);
// ── Redis ─────────────────────────────────────────────────────────────
var redisConn = config.GetConnectionString("Redis")
?? throw new InvalidOperationException(
"Required configuration value 'ConnectionStrings:Redis' is missing or empty.");
var multiplexer = ConnectionMultiplexer.Connect(redisConn);
services.AddSingleton<IConnectionMultiplexer>(multiplexer);
services.AddStackExchangeRedisCache(opts =>
{
opts.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(multiplexer);
});
// ── Options ───────────────────────────────────────────────────────────
services.AddOptions<S3Options>()
.BindConfiguration(S3Options.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<TelegramApiOptions>()
.BindConfiguration(TelegramApiOptions.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
// ── S3 / MinIO ────────────────────────────────────────────────────────
services.AddSingleton<IAmazonS3>(sp =>
{
var opts = sp.GetRequiredService<IOptions<S3Options>>().Value;
var credentials = new BasicAWSCredentials(opts.AccessKey, opts.SecretKey);
var cfg = new AmazonS3Config
{
ServiceURL = opts.ServiceUrl,
ForcePathStyle = true,
UseHttp = opts.ServiceUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase),
};
return new AmazonS3Client(credentials, cfg);
});
services.AddScoped<IFileStorage, S3FileStorage>();
// ── Telegram Bot Client ───────────────────────────────────────────────
services.AddSingleton<ITelegramBotClient>(sp =>
{
var opts = sp.GetRequiredService<IOptions<TelegramApiOptions>>().Value;
var clientOptions = new TelegramBotClientOptions(
token: opts.BotToken,
baseUrl: opts.ApiBaseUrl);
return new TelegramBotClient(clientOptions);
});
services.AddScoped<ITelegramFileCacheService, TelegramFileCacheService>();
services.AddScoped<ITelegramQueryAnswerer, TelegramQueryAnswererService>();
return services;
}
@@ -11,9 +11,13 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" Version="3.7.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.12" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.12" />
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.12" />
<PackageReference Include="Telegram.Bot" Version="22.10.3.2" />
</ItemGroup>
</Project>
@@ -0,0 +1,302 @@
// <auto-generated />
using System;
using MemeVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20261006171407_AddCollectionNsfw")]
partial class AddCollectionNsfw
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("FirstName")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("first_name");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("last_seen_at");
b.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("username");
b.HasKey("Id");
b.HasIndex("TelegramId")
.IsUnique()
.HasDatabaseName("ix_bot_users_telegram_id");
b.ToTable("bot_users", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("description");
b.Property<bool>("IsInbox")
.HasColumnType("boolean")
.HasColumnName("is_inbox");
b.Property<bool>("IsNsfw")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasColumnName("is_nsfw");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("name");
b.Property<string>("ShareToken")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("share_token");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Visibility")
.IsRequired()
.HasColumnType("text")
.HasColumnName("visibility");
b.HasKey("Id");
b.HasIndex("ShareToken")
.IsUnique()
.HasDatabaseName("ix_collections_share_token")
.HasFilter("share_token IS NOT NULL");
b.ToTable("collections", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<long>("CreatedByTelegramId")
.HasColumnType("bigint")
.HasColumnName("created_by_telegram_id");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean")
.HasColumnName("is_revoked");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("revoked_at");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("character varying(32)")
.HasColumnName("token");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_collection_invites_collection_id");
b.HasIndex("Token")
.IsUnique()
.HasDatabaseName("ix_collection_invites_token");
b.ToTable("collection_invites", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<string>("Caption")
.HasMaxLength(4096)
.HasColumnType("character varying(4096)")
.HasColumnName("caption");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("MediaGroupId")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("media_group_id");
b.Property<long>("OwnerTelegramId")
.HasColumnType("bigint")
.HasColumnName("owner_telegram_id");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text")
.HasColumnName("type");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string[]>("_tags")
.IsRequired()
.HasColumnType("text[]")
.HasColumnName("tags");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_media_items_collection");
b.HasIndex("OwnerTelegramId")
.HasDatabaseName("ix_media_items_owner");
b.HasIndex("_tags")
.HasDatabaseName("ix_media_items_tags");
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
b.ToTable("media_items", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
{
b1.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b1.Property<DateTimeOffset>("AddedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("added_at");
b1.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b1.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b1.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b1.HasKey("Id");
b1.HasIndex("CollectionId", "TelegramId")
.IsUnique()
.HasDatabaseName("ix_collection_members_unique");
b1.ToTable("collection_members", (string)null);
b1.WithOwner()
.HasForeignKey("CollectionId");
});
b.Navigation("Members");
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
{
b1.Property<Guid>("MediaItemId")
.HasColumnType("uuid");
b1.Property<string>("Origin")
.HasColumnType("text")
.HasColumnName("source_origin");
b1.Property<string>("Reference")
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.HasColumnName("source_reference");
b1.HasKey("MediaItemId");
b1.ToTable("media_items");
b1.WithOwner()
.HasForeignKey("MediaItemId");
});
b.Navigation("Source");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddCollectionNsfw : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "is_nsfw",
table: "collections",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "is_nsfw",
table: "collections");
}
}
}
@@ -0,0 +1,306 @@
// <auto-generated />
using System;
using MemeVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20261006221608_AddCollectionInviteExpiry")]
partial class AddCollectionInviteExpiry
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("FirstName")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("first_name");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("last_seen_at");
b.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("username");
b.HasKey("Id");
b.HasIndex("TelegramId")
.IsUnique()
.HasDatabaseName("ix_bot_users_telegram_id");
b.ToTable("bot_users", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("description");
b.Property<bool>("IsInbox")
.HasColumnType("boolean")
.HasColumnName("is_inbox");
b.Property<bool>("IsNsfw")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasColumnName("is_nsfw");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("name");
b.Property<string>("ShareToken")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("share_token");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Visibility")
.IsRequired()
.HasColumnType("text")
.HasColumnName("visibility");
b.HasKey("Id");
b.HasIndex("ShareToken")
.IsUnique()
.HasDatabaseName("ix_collections_share_token")
.HasFilter("share_token IS NOT NULL");
b.ToTable("collections", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<long>("CreatedByTelegramId")
.HasColumnType("bigint")
.HasColumnName("created_by_telegram_id");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean")
.HasColumnName("is_revoked");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("revoked_at");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("character varying(32)")
.HasColumnName("token");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_collection_invites_collection_id");
b.HasIndex("Token")
.IsUnique()
.HasDatabaseName("ix_collection_invites_token");
b.ToTable("collection_invites", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<string>("Caption")
.HasMaxLength(4096)
.HasColumnType("character varying(4096)")
.HasColumnName("caption");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("MediaGroupId")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("media_group_id");
b.Property<long>("OwnerTelegramId")
.HasColumnType("bigint")
.HasColumnName("owner_telegram_id");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text")
.HasColumnName("type");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string[]>("_tags")
.IsRequired()
.HasColumnType("text[]")
.HasColumnName("tags");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_media_items_collection");
b.HasIndex("OwnerTelegramId")
.HasDatabaseName("ix_media_items_owner");
b.HasIndex("_tags")
.HasDatabaseName("ix_media_items_tags");
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
b.ToTable("media_items", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
{
b1.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b1.Property<DateTimeOffset>("AddedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("added_at");
b1.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b1.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b1.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b1.HasKey("Id");
b1.HasIndex("CollectionId", "TelegramId")
.IsUnique()
.HasDatabaseName("ix_collection_members_unique");
b1.ToTable("collection_members", (string)null);
b1.WithOwner()
.HasForeignKey("CollectionId");
});
b.Navigation("Members");
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
{
b1.Property<Guid>("MediaItemId")
.HasColumnType("uuid");
b1.Property<string>("Origin")
.HasColumnType("text")
.HasColumnName("source_origin");
b1.Property<string>("Reference")
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.HasColumnName("source_reference");
b1.HasKey("MediaItemId");
b1.ToTable("media_items");
b1.WithOwner()
.HasForeignKey("MediaItemId");
});
b.Navigation("Source");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,29 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddCollectionInviteExpiry : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTimeOffset>(
name: "expires_at",
table: "collection_invites",
type: "timestamp with time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "expires_at",
table: "collection_invites");
}
}
}
@@ -81,6 +81,12 @@ namespace MemeVault.Infrastructure.Migrations
.HasColumnType("boolean")
.HasColumnName("is_inbox");
b.Property<bool>("IsNsfw")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasColumnName("is_nsfw");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
@@ -130,6 +136,10 @@ namespace MemeVault.Infrastructure.Migrations
.HasColumnType("bigint")
.HasColumnName("created_by_telegram_id");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean")
.HasColumnName("is_revoked");
@@ -0,0 +1,26 @@
using System.ComponentModel.DataAnnotations;
namespace MemeVault.Infrastructure.Options;
public sealed class S3Options
{
public const string Section = "S3";
/// <summary>
/// S3/MinIO endpoint — used both by the .NET SDK for uploads/downloads
/// and as the base URL in generated presigned links.
/// Must be reachable both from the server and from the browser.
/// </summary>
[Required]
public string ServiceUrl { get; set; } = string.Empty;
[Required]
public string AccessKey { get; set; } = string.Empty;
[Required]
public string SecretKey { get; set; } = string.Empty;
/// <summary>Bucket where cached Telegram files are stored.</summary>
[Required]
public string BucketName { get; set; } = string.Empty;
}
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace MemeVault.Infrastructure.Options;
/// <summary>
/// Options for calling the Telegram Bot API from Infrastructure services.
/// Reads from the same "Telegram" config section as MemeVault.Api.
/// </summary>
public sealed class TelegramApiOptions
{
public const string Section = "Telegram";
[Required]
public string BotToken { get; set; } = string.Empty;
/// <summary>
/// Custom Telegram Bot API server base URL (e.g. a local server).
/// Null means the official https://api.telegram.org — the library handles the default.
/// </summary>
public string? ApiBaseUrl { get; set; }
}
@@ -29,6 +29,11 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
.HasColumnName("is_inbox")
.IsRequired();
builder.Property(x => x.IsNsfw)
.HasColumnName("is_nsfw")
.IsRequired()
.HasDefaultValue(false);
builder.Property(x => x.Visibility)
.HasColumnName("visibility")
.HasConversion<string>()
@@ -39,6 +39,7 @@ public sealed class CollectionInviteConfiguration : IEntityTypeConfiguration<Col
.HasDatabaseName("ix_collection_invites_collection_id");
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
builder.Property(x => x.ExpiresAt).HasColumnName("expires_at");
builder.Property(x => x.IsRevoked).HasColumnName("is_revoked");
builder.Property(x => x.RevokedAt).HasColumnName("revoked_at");
}
@@ -32,6 +32,16 @@ public sealed class CollectionRepository : ICollectionRepository
.ToListAsync(ct);
}
public async Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct)
{
return await _db.Collections
.Include(c => c.Members)
.Where(c => c.Members.Any(m => m.TelegramId == telegramId))
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым
.ThenBy(x => x.Name)
.ToListAsync(ct);
}
public Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct) =>
_db.Collections
.Include(c => c.Members)
@@ -42,12 +42,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
long ownerTelegramId,
TagSearchQuery query,
int limit,
bool includeNsfw,
CancellationToken ct)
{
var sql = _db.MediaItems.Where(x => x.OwnerTelegramId == ownerTelegramId);
if (query.IsEmpty)
{
if (!includeNsfw)
sql = sql.Where(x => !_db.Collections.Any(c => c.Id == x.CollectionId && c.IsNsfw));
return await sql
.OrderByDescending(x => x.CreatedAt)
.Take(limit)
@@ -79,6 +83,9 @@ public sealed class MediaItemRepository : IMediaItemRepository
conditions.Add($"caption ILIKE {{{idx}}}");
}
if (!includeNsfw)
conditions.Add("NOT EXISTS (SELECT 1 FROM collections c WHERE c.id = collection_id AND c.is_nsfw = true)");
var where = string.Join(" AND ", conditions);
var rawSql = $"SELECT * FROM media_items WHERE {where} ORDER BY created_at DESC LIMIT {limit}";
@@ -87,6 +94,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
.ToListAsync(ct);
}
public async Task<Dictionary<Guid, int>> GetCountsByCollectionIdsAsync(
IReadOnlyList<Guid> collectionIds, CancellationToken ct)
{
return await _db.MediaItems
.Where(x => collectionIds.Contains(x.CollectionId))
.GroupBy(x => x.CollectionId)
.Select(g => new { CollectionId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.CollectionId, x => x.Count, ct);
}
public async Task AddAsync(MediaItem item, CancellationToken ct)
{
await _db.MediaItems.AddAsync(item, ct);
@@ -0,0 +1,66 @@
using Amazon.S3;
using Amazon.S3.Model;
using MemeVault.Application.Common;
using MemeVault.Domain.ValueObjects;
using MemeVault.Infrastructure.Options;
using Microsoft.Extensions.Options;
namespace MemeVault.Infrastructure.Services;
/// <summary>
/// S3/MinIO-backed implementation of <see cref="IFileStorage"/>.
/// </summary>
public sealed class S3FileStorage : IFileStorage
{
private readonly IAmazonS3 _s3;
private readonly S3Options _opts;
public S3FileStorage(IAmazonS3 s3, IOptions<S3Options> opts)
{
_s3 = s3;
_opts = opts.Value;
}
public async Task<MediaSource> UploadAsync(
Stream content,
string objectKey,
string contentType,
long ownerTelegramId,
CancellationToken ct = default)
{
var request = new PutObjectRequest
{
BucketName = _opts.BucketName,
Key = objectKey,
InputStream = content,
ContentType = contentType,
// CalcMD5 + autoCloseStream defaults are fine
};
await _s3.PutObjectAsync(request, ct);
return MediaSource.FromS3(objectKey);
}
public async Task<string> GetDownloadUrlAsync(
string objectKey,
TimeSpan expiry,
CancellationToken ct = default)
{
var request = new GetPreSignedUrlRequest
{
BucketName = _opts.BucketName,
Key = objectKey,
Expires = DateTime.UtcNow.Add(expiry),
Protocol = _opts.ServiceUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? Protocol.HTTPS
: Protocol.HTTP,
};
return await _s3.GetPreSignedURLAsync(request);
}
public async Task DeleteAsync(string objectKey, CancellationToken ct = default)
{
await _s3.DeleteObjectAsync(_opts.BucketName, objectKey, ct);
}
}
@@ -0,0 +1,165 @@
using System.IO.Pipelines;
using System.Security.Cryptography;
using System.Text;
using Amazon.S3;
using Amazon.S3.Model;
using MemeVault.Application.Common;
using MemeVault.Infrastructure.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using Telegram.Bot;
namespace MemeVault.Infrastructure.Services;
/// <summary>
/// Fetches a Telegram file, caches it in S3, and returns a pre-signed download URL.
///
/// Flow per request:
/// 1. Acquire Redis lock (SET … NX EX 60).
/// 2. Check whether the object already exists in S3 (HeadObject).
/// 3. If cache miss: call Telegram getFile → stream to S3 with ContentLength.
/// 4. Generate and return a pre-signed URL regardless of cache hit/miss.
/// 5. Release Redis lock.
/// </summary>
public sealed class TelegramFileCacheService : ITelegramFileCacheService
{
private const string CacheKeyPrefix = "cache/";
private const string LockKeyPrefix = "lock:file:";
private const int LockTtlSeconds = 60;
private readonly IConnectionMultiplexer _redis;
private readonly IAmazonS3 _s3;
private readonly IFileStorage _storage;
private readonly ITelegramBotClient _botClient;
private readonly S3Options _s3Opts;
private readonly ILogger<TelegramFileCacheService> _logger;
public TelegramFileCacheService(
IConnectionMultiplexer redis,
IAmazonS3 s3,
IFileStorage storage,
ITelegramBotClient botClient,
IOptions<S3Options> s3Opts,
ILogger<TelegramFileCacheService> logger)
{
_redis = redis;
_s3 = s3;
_storage = storage;
_botClient = botClient;
_s3Opts = s3Opts.Value;
_logger = logger;
}
public async Task<string> GetCachedUrlAsync(
string telegramFileId,
TimeSpan urlExpiry,
CancellationToken ct = default)
{
var hash = ComputeHash(telegramFileId);
var s3Key = $"{CacheKeyPrefix}{hash}";
var lockKey = $"{LockKeyPrefix}{hash}";
var db = _redis.GetDatabase();
// ── 1. Acquire Redis lock ─────────────────────────────────────────────
var lockAcquired = await db.StringSetAsync(
lockKey, "1",
TimeSpan.FromSeconds(LockTtlSeconds),
When.NotExists);
try
{
// ── 2. Check S3 ───────────────────────────────────────────────────
var existsInS3 = await ObjectExistsAsync(s3Key, ct);
// ── 3. Cache miss: fetch from Telegram and upload to S3 ───────────
if (!existsInS3)
{
_logger.LogInformation("Cache miss for fileId {FileId}, fetching from Telegram.", telegramFileId);
await FetchAndCacheAsync(telegramFileId, s3Key, ct);
}
// ── 4. Generate presigned URL ─────────────────────────────────────
return await _storage.GetDownloadUrlAsync(s3Key, urlExpiry, ct);
}
finally
{
// ── 5. Release lock (only if we acquired it) ──────────────────────
if (lockAcquired)
await db.KeyDeleteAsync(lockKey);
}
}
// ── Private helpers ───────────────────────────────────────────────────────
private static string ComputeHash(string fileId)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(fileId));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
private async Task<bool> ObjectExistsAsync(string key, CancellationToken ct)
{
try
{
await _s3.GetObjectMetadataAsync(_s3Opts.BucketName, key, ct);
return true;
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return false;
}
}
private async Task FetchAndCacheAsync(string telegramFileId, string s3Key, CancellationToken ct)
{
// Resolve file_path and file_size via Bot API
var file = await _botClient.GetFile(telegramFileId, ct);
var filePath = file.FilePath ?? throw new InvalidOperationException("Telegram returned null file_path.");
var contentType = InferContentType(filePath);
// Stream from Telegram to S3 via a pipe — no full buffering
var pipe = new Pipe();
// Download runs on a thread-pool thread, writing into the pipe writer
var downloadTask = Task.Run(async () =>
{
try { await _botClient.DownloadFile(filePath, pipe.Writer.AsStream(), ct); }
finally { pipe.Writer.Complete(); }
}, CancellationToken.None);
var putRequest = new PutObjectRequest
{
BucketName = _s3Opts.BucketName,
Key = s3Key,
InputStream = pipe.Reader.AsStream(),
ContentType = contentType,
};
// Provide ContentLength when available so the AWS SDK doesn't buffer internally
if (file.FileSize.HasValue)
putRequest.Headers.ContentLength = file.FileSize.Value;
await Task.WhenAll(_s3.PutObjectAsync(putRequest, ct), downloadTask);
_logger.LogInformation(
"Cached Telegram fileId {FileId} → S3 key {Key} ({Bytes} bytes).",
telegramFileId, s3Key, file.FileSize);
}
private static string InferContentType(string filePath)
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
return ext switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".webp" => "image/webp",
".mp4" => "video/mp4",
".webm" => "video/webm",
".tgs" => "application/x-tgsticker",
".ogg" => "audio/ogg",
_ => "application/octet-stream",
};
}
}
@@ -0,0 +1,79 @@
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Domain.Enums;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types.InlineQueryResults;
namespace MemeVault.Infrastructure.Services;
/// <summary>
/// Вызывает Telegram Bot API answerWebAppQuery, чтобы отправить медиа в чат.
/// Формирует нужный InlineQueryResult в зависимости от типа медиа.
/// </summary>
public sealed class TelegramQueryAnswererService : ITelegramQueryAnswerer
{
private readonly ITelegramBotClient _botClient;
private readonly ILogger<TelegramQueryAnswererService> _logger;
public TelegramQueryAnswererService(
ITelegramBotClient botClient,
ILogger<TelegramQueryAnswererService> logger)
{
_botClient = botClient;
_logger = logger;
}
public async Task AnswerAsync(string queryId, MediaItem item, CancellationToken ct = default)
{
var result = BuildResult(item);
await _botClient.AnswerWebAppQuery(queryId, result, ct);
_logger.LogInformation(
"Sent item {ItemId} (type={Type}) to chat via queryId {QueryId}",
item.Id, item.Type, queryId);
}
// ── Строим нужный тип InlineQueryResult ──────────────────────────────────
private static InlineQueryResult BuildResult(MediaItem item)
{
var id = item.Id.ToString();
var fileId = item.Source?.Reference;
var caption = item.Caption;
return item.Type switch
{
MediaType.Photo => new InlineQueryResultCachedPhoto(id,
fileId ?? throw new InvalidOperationException("Photo has no file_id"))
{
Caption = caption,
},
MediaType.Video => new InlineQueryResultCachedVideo(id,
fileId ?? throw new InvalidOperationException("Video has no file_id"),
title: caption?[..Math.Min(60, caption.Length)] ?? "Video")
{
Caption = caption,
},
MediaType.Sticker => new InlineQueryResultCachedSticker(id,
fileId ?? throw new InvalidOperationException("Sticker has no file_id")),
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id,
fileId ?? throw new InvalidOperationException("Animation has no file_id"))
{
Caption = caption,
},
MediaType.Text => new InlineQueryResultArticle(id,
title: caption?[..Math.Min(60, caption?.Length ?? 0)] ?? "Текст",
inputMessageContent: new InputTextMessageContent(caption ?? string.Empty))
{
Description = caption,
},
_ => throw new NotSupportedException($"MediaType {item.Type} is not supported for chat sending."),
};
}
}