Add Ping backend

.NET 10 solution for Ping, a Discord style chat app: Domain, Application
and Infrastructure projects plus the Api host. SignalR for chat and
presence, LiveKit for call tokens, EF Core on Postgres, S3 compatible
storage for attachments, and OIDC auth shared with the Musify Zitadel
instance. Includes the Compose stack for local development.
This commit is contained in:
2026-09-21 19:32:55 +02:00
commit 0623875dfa
126 changed files with 5048 additions and 0 deletions
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace Ping.Infrastructure.Configuration
{
public class DatabaseConfiguration
{
public const string SectionName = "Database";
[Required]
public required string ConnectionString { get; set; }
}
}
@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
namespace Ping.Infrastructure.Configuration
{
public class InfrastructureStorageConfiguration
{
public const string SectionName = "InfrastructureStorage";
[Url]
[Required]
public required string Address { get; set; }
[Required]
public required string AccessKey { get; set; }
[Required]
public required string SecretAccessKey { get; set; }
[Required]
public bool ForcePathStyle { get; set; }
[Required]
public bool UseHttp { get; set; }
}
}
@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace Ping.Infrastructure.Configuration
{
public class LiveKitConfiguration
{
public const string SectionName = "LiveKit";
[Required]
public required string ApiKey { get; set; }
[Required]
public required string ApiSecret { get; set; }
public int TokenTtlMinutes { get; set; } = 240;
}
}
@@ -0,0 +1,5 @@
{
"Database": {
"ConnectionString": ""
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Ping.Domain.Abstractions;
namespace Ping.Infrastructure.Persistence
{
public sealed class AuditableEntityInterceptor : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
ApplyTimestamps(eventData.Context);
return base.SavingChanges(eventData, result);
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
ApplyTimestamps(eventData.Context);
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
private static void ApplyTimestamps(DbContext? context)
{
if (context is null)
return;
context.ChangeTracker.DetectChanges();
var now = DateTime.UtcNow;
foreach (var entry in context.ChangeTracker.Entries<IAuditable>())
{
if (entry.State == EntityState.Added)
{
entry.Entity.CreatedAt = now;
entry.Entity.UpdatedAt = now;
}
else if (entry.State == EntityState.Modified)
{
entry.Entity.UpdatedAt = now;
}
}
}
}
}
@@ -0,0 +1,131 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Ping.Domain.Entities;
using Ping.Infrastructure.Configuration;
using AppIDatabase = Ping.Application.Contracts.IDatabase;
namespace Ping.Infrastructure.Persistence
{
public class Database(DatabaseConfiguration configuration) : DbContext, AppIDatabase
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(configuration.ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ServerMember>()
.HasKey(m => new { m.ServerId, m.UserId });
modelBuilder.Entity<ServerMember>()
.HasOne(m => m.Server)
.WithMany(s => s.Members)
.HasForeignKey(m => m.ServerId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ServerMember>()
.HasOne(m => m.User)
.WithMany(u => u.ServerMemberships)
.HasForeignKey(m => m.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Server>()
.HasOne(s => s.Owner)
.WithMany()
.HasForeignKey(s => s.OwnerId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Channel>()
.HasOne(c => c.ServerNavigation)
.WithMany(s => s.Channels)
.HasForeignKey(c => c.ServerId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ChannelMember>()
.HasKey(m => new { m.ChannelId, m.UserId });
modelBuilder.Entity<ChannelMember>()
.HasOne(m => m.Channel)
.WithMany(c => c.Members)
.HasForeignKey(m => m.ChannelId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ChannelMember>()
.HasOne(m => m.User)
.WithMany()
.HasForeignKey(m => m.UserId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Message>()
.HasOne(m => m.Channel)
.WithMany()
.HasForeignKey(m => m.ChannelId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Message>()
.HasOne(m => m.Author)
.WithMany()
.HasForeignKey(m => m.AuthorId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Message>()
.HasIndex(m => new { m.ChannelId, m.CreatedAt });
modelBuilder.Entity<Attachment>()
.HasOne(a => a.Message)
.WithMany(m => m.Attachments)
.HasForeignKey(a => a.MessageId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Friendship>()
.HasOne(f => f.Requester)
.WithMany()
.HasForeignKey(f => f.RequesterId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Friendship>()
.HasOne(f => f.Addressee)
.WithMany()
.HasForeignKey(f => f.AddresseeId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Friendship>()
.HasIndex(f => new { f.RequesterId, f.AddresseeId })
.IsUnique();
}
public DbSet<User> Users => Set<User>();
public DbSet<Friendship> Friendships => Set<Friendship>();
public DbSet<Server> Servers => Set<Server>();
public DbSet<ServerMember> ServerMembers => Set<ServerMember>();
public DbSet<Channel> Channels => Set<Channel>();
public DbSet<ChannelMember> ChannelMembers => Set<ChannelMember>();
public DbSet<Message> Messages => Set<Message>();
public DbSet<Attachment> Attachments => Set<Attachment>();
public async Task<Ping.Application.Contracts.IDatabaseTransaction> BeginTransactionAsync(
System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken)
{
var transaction = await Database.BeginTransactionAsync(isolationLevel, cancellationToken);
return new DatabaseTransaction(transaction);
}
private sealed class DatabaseTransaction(IDbContextTransaction inner) : Ping.Application.Contracts.IDatabaseTransaction
{
public Task CommitAsync(CancellationToken cancellationToken) =>
inner.CommitAsync(cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}
}
@@ -0,0 +1,31 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Ping.Application.Contracts;
using Ping.Infrastructure.Configuration;
namespace Ping.Infrastructure.Persistence
{
public static class DatabaseDependencyInjection
{
public static IServiceCollection AddDatabase(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<DatabaseConfiguration>()
.Bind(configuration.GetRequiredSection(DatabaseConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<DatabaseConfiguration>>().Value);
serviceDescriptors.AddSingleton<AuditableEntityInterceptor>();
serviceDescriptors.AddDbContext<Database>((serviceProvider, options) =>
options.AddInterceptors(serviceProvider.GetRequiredService<AuditableEntityInterceptor>()));
serviceDescriptors.AddScoped<IDatabase>(serviceProvider => serviceProvider.GetRequiredService<Database>());
return serviceDescriptors;
}
}
}
@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Ping.Infrastructure.Configuration;
namespace Ping.Infrastructure.Persistence
{
public class DatabaseDesignTimeFactory : IDesignTimeDbContextFactory<Database>
{
public Database CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("DesignSettings.json", optional: true)
.AddUserSecrets<DatabaseDesignTimeFactory>()
.AddEnvironmentVariables()
.Build();
var databaseConfiguration = configuration
.GetRequiredSection(DatabaseConfiguration.SectionName)
.Get<DatabaseConfiguration>()
?? throw new InvalidOperationException($"{DatabaseConfiguration.SectionName} configuration section not found.");
return new Database(databaseConfiguration);
}
}
}
@@ -0,0 +1,413 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Ping.Infrastructure.Persistence;
#nullable disable
namespace Ping.Infrastructure.Persistence.Migrations
{
[DbContext(typeof(Database))]
[Migration("20260916023908_InitialCreate")]
partial class InitialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Ping.Domain.Entities.Attachment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Bucket")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("FileName")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<long>("SizeBytes")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("MessageId");
b.ToTable("Attachment");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<int>("Position")
.HasColumnType("integer");
b.Property<Guid?>("ServerId")
.HasColumnType("uuid");
b.Property<string>("Topic")
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ServerId");
b.ToTable("Channel");
});
modelBuilder.Entity("Ping.Domain.Entities.ChannelMember", b =>
{
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("ChannelId", "UserId");
b.HasIndex("UserId");
b.ToTable("ChannelMembers");
});
modelBuilder.Entity("Ping.Domain.Entities.Friendship", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("AddresseeId")
.HasColumnType("bigint");
b.Property<long?>("BlockedById")
.HasColumnType("bigint");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("RequesterId")
.HasColumnType("bigint");
b.Property<DateTime?>("RespondedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Status")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AddresseeId");
b.HasIndex("RequesterId", "AddresseeId")
.IsUnique();
b.ToTable("Friendship");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("AuthorId")
.HasColumnType("bigint");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("character varying(4000)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("EditedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("ReplyToMessageId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.HasIndex("ChannelId", "CreatedAt");
b.ToTable("Message");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("IconUrl")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<long>("OwnerId")
.HasColumnType("bigint");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OwnerId");
b.ToTable("Server");
});
modelBuilder.Entity("Ping.Domain.Entities.ServerMember", b =>
{
b.Property<Guid>("ServerId")
.HasColumnType("uuid");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<DateTime>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Nickname")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("ServerId", "UserId");
b.HasIndex("UserId");
b.ToTable("ServerMember");
});
modelBuilder.Entity("Ping.Domain.Entities.User", b =>
{
b.Property<long>("Id")
.HasColumnType("bigint");
b.Property<string>("AvatarUrl")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("NormalizedUsername")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Attachment", b =>
{
b.HasOne("Ping.Domain.Entities.Message", "Message")
.WithMany("Attachments")
.HasForeignKey("MessageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Message");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.HasOne("Ping.Domain.Entities.Server", "ServerNavigation")
.WithMany("Channels")
.HasForeignKey("ServerId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("ServerNavigation");
});
modelBuilder.Entity("Ping.Domain.Entities.ChannelMember", b =>
{
b.HasOne("Ping.Domain.Entities.Channel", "Channel")
.WithMany("Members")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
b.Navigation("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Friendship", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Addressee")
.WithMany()
.HasForeignKey("AddresseeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "Requester")
.WithMany()
.HasForeignKey("RequesterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Addressee");
b.Navigation("Requester");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Author")
.WithMany()
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Ping.Domain.Entities.Channel", "Channel")
.WithMany()
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Author");
b.Navigation("Channel");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Ping.Domain.Entities.ServerMember", b =>
{
b.HasOne("Ping.Domain.Entities.Server", "Server")
.WithMany("Members")
.HasForeignKey("ServerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "User")
.WithMany("ServerMemberships")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Server");
b.Navigation("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.Navigation("Members");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.Navigation("Attachments");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.Navigation("Channels");
b.Navigation("Members");
});
modelBuilder.Entity("Ping.Domain.Entities.User", b =>
{
b.Navigation("ServerMemberships");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,283 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Ping.Infrastructure.Persistence.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false),
Username = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
NormalizedUsername = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
DisplayName = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
AvatarUrl = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Friendship",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
RequesterId = table.Column<long>(type: "bigint", nullable: false),
AddresseeId = table.Column<long>(type: "bigint", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false),
BlockedById = table.Column<long>(type: "bigint", nullable: true),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
RespondedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Friendship", x => x.Id);
table.ForeignKey(
name: "FK_Friendship_User_AddresseeId",
column: x => x.AddresseeId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Friendship_User_RequesterId",
column: x => x.RequesterId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Server",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
IconUrl = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
OwnerId = table.Column<long>(type: "bigint", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Server", x => x.Id);
table.ForeignKey(
name: "FK_Server_User_OwnerId",
column: x => x.OwnerId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Channel",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ServerId = table.Column<Guid>(type: "uuid", nullable: true),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
Topic = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: true),
Type = table.Column<int>(type: "integer", nullable: false),
Position = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Channel", x => x.Id);
table.ForeignKey(
name: "FK_Channel_Server_ServerId",
column: x => x.ServerId,
principalTable: "Server",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ServerMember",
columns: table => new
{
ServerId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<long>(type: "bigint", nullable: false),
Nickname = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
Role = table.Column<int>(type: "integer", nullable: false),
JoinedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ServerMember", x => new { x.ServerId, x.UserId });
table.ForeignKey(
name: "FK_ServerMember_Server_ServerId",
column: x => x.ServerId,
principalTable: "Server",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ServerMember_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ChannelMembers",
columns: table => new
{
ChannelId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChannelMembers", x => new { x.ChannelId, x.UserId });
table.ForeignKey(
name: "FK_ChannelMembers_Channel_ChannelId",
column: x => x.ChannelId,
principalTable: "Channel",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ChannelMembers_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Message",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ChannelId = table.Column<Guid>(type: "uuid", nullable: false),
AuthorId = table.Column<long>(type: "bigint", nullable: false),
Content = table.Column<string>(type: "character varying(4000)", maxLength: 4000, nullable: false),
ReplyToMessageId = table.Column<Guid>(type: "uuid", nullable: true),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
EditedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Message", x => x.Id);
table.ForeignKey(
name: "FK_Message_Channel_ChannelId",
column: x => x.ChannelId,
principalTable: "Channel",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Message_User_AuthorId",
column: x => x.AuthorId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Attachment",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
MessageId = table.Column<Guid>(type: "uuid", nullable: false),
Bucket = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
Key = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
FileName = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
ContentType = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
SizeBytes = table.Column<long>(type: "bigint", nullable: false),
Kind = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Attachment", x => x.Id);
table.ForeignKey(
name: "FK_Attachment_Message_MessageId",
column: x => x.MessageId,
principalTable: "Message",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Attachment_MessageId",
table: "Attachment",
column: "MessageId");
migrationBuilder.CreateIndex(
name: "IX_Channel_ServerId",
table: "Channel",
column: "ServerId");
migrationBuilder.CreateIndex(
name: "IX_ChannelMembers_UserId",
table: "ChannelMembers",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Friendship_AddresseeId",
table: "Friendship",
column: "AddresseeId");
migrationBuilder.CreateIndex(
name: "IX_Friendship_RequesterId_AddresseeId",
table: "Friendship",
columns: new[] { "RequesterId", "AddresseeId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Message_AuthorId",
table: "Message",
column: "AuthorId");
migrationBuilder.CreateIndex(
name: "IX_Message_ChannelId_CreatedAt",
table: "Message",
columns: new[] { "ChannelId", "CreatedAt" });
migrationBuilder.CreateIndex(
name: "IX_Server_OwnerId",
table: "Server",
column: "OwnerId");
migrationBuilder.CreateIndex(
name: "IX_ServerMember_UserId",
table: "ServerMember",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Attachment");
migrationBuilder.DropTable(
name: "ChannelMembers");
migrationBuilder.DropTable(
name: "Friendship");
migrationBuilder.DropTable(
name: "ServerMember");
migrationBuilder.DropTable(
name: "Message");
migrationBuilder.DropTable(
name: "Channel");
migrationBuilder.DropTable(
name: "Server");
migrationBuilder.DropTable(
name: "User");
}
}
}
@@ -0,0 +1,411 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Ping.Infrastructure.Persistence;
#nullable disable
namespace Ping.Infrastructure.Persistence.Migrations
{
[DbContext(typeof(Database))]
partial class DatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Ping.Domain.Entities.Attachment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Bucket")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("FileName")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<long>("SizeBytes")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("MessageId");
b.ToTable("Attachment");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<int>("Position")
.HasColumnType("integer");
b.Property<Guid?>("ServerId")
.HasColumnType("uuid");
b.Property<string>("Topic")
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ServerId");
b.ToTable("Channel");
});
modelBuilder.Entity("Ping.Domain.Entities.ChannelMember", b =>
{
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("ChannelId", "UserId");
b.HasIndex("UserId");
b.ToTable("ChannelMembers");
});
modelBuilder.Entity("Ping.Domain.Entities.Friendship", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("AddresseeId")
.HasColumnType("bigint");
b.Property<long?>("BlockedById")
.HasColumnType("bigint");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("RequesterId")
.HasColumnType("bigint");
b.Property<DateTime?>("RespondedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Status")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AddresseeId");
b.HasIndex("RequesterId", "AddresseeId")
.IsUnique();
b.ToTable("Friendship");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("AuthorId")
.HasColumnType("bigint");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("character varying(4000)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("EditedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("ReplyToMessageId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.HasIndex("ChannelId", "CreatedAt");
b.ToTable("Message");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("IconUrl")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<long>("OwnerId")
.HasColumnType("bigint");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OwnerId");
b.ToTable("Server");
});
modelBuilder.Entity("Ping.Domain.Entities.ServerMember", b =>
{
b.Property<Guid>("ServerId")
.HasColumnType("uuid");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<DateTime>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Nickname")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("ServerId", "UserId");
b.HasIndex("UserId");
b.ToTable("ServerMember");
});
modelBuilder.Entity("Ping.Domain.Entities.User", b =>
{
b.Property<long>("Id")
.HasColumnType("bigint");
b.Property<string>("AvatarUrl")
.HasMaxLength(2048)
.HasColumnType("character varying(2048)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("NormalizedUsername")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Attachment", b =>
{
b.HasOne("Ping.Domain.Entities.Message", "Message")
.WithMany("Attachments")
.HasForeignKey("MessageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Message");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.HasOne("Ping.Domain.Entities.Server", "ServerNavigation")
.WithMany("Channels")
.HasForeignKey("ServerId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("ServerNavigation");
});
modelBuilder.Entity("Ping.Domain.Entities.ChannelMember", b =>
{
b.HasOne("Ping.Domain.Entities.Channel", "Channel")
.WithMany("Members")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
b.Navigation("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Friendship", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Addressee")
.WithMany()
.HasForeignKey("AddresseeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "Requester")
.WithMany()
.HasForeignKey("RequesterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Addressee");
b.Navigation("Requester");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Author")
.WithMany()
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Ping.Domain.Entities.Channel", "Channel")
.WithMany()
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Author");
b.Navigation("Channel");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.HasOne("Ping.Domain.Entities.User", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Ping.Domain.Entities.ServerMember", b =>
{
b.HasOne("Ping.Domain.Entities.Server", "Server")
.WithMany("Members")
.HasForeignKey("ServerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Ping.Domain.Entities.User", "User")
.WithMany("ServerMemberships")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Server");
b.Navigation("User");
});
modelBuilder.Entity("Ping.Domain.Entities.Channel", b =>
{
b.Navigation("Members");
});
modelBuilder.Entity("Ping.Domain.Entities.Message", b =>
{
b.Navigation("Attachments");
});
modelBuilder.Entity("Ping.Domain.Entities.Server", b =>
{
b.Navigation("Channels");
b.Navigation("Members");
});
modelBuilder.Entity("Ping.Domain.Entities.User", b =>
{
b.Navigation("ServerMemberships");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Ping.Infrastructure</AssemblyName>
<RootNamespace>Ping.Infrastructure</RootNamespace>
<UserSecretsId>8baf35f2-9845-462f-a87a-570d56d13c58</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" />
<PackageReference Include="Livekit.Server.Sdk.Dotnet" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ping.Application\Ping.Application.csproj" />
<ProjectReference Include="..\Ping.Domain\Ping.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Persistence\Migrations\" />
</ItemGroup>
</Project>
@@ -0,0 +1,27 @@
using Livekit.Server.Sdk.Dotnet;
using Ping.Application.Contracts;
using Ping.Infrastructure.Configuration;
namespace Ping.Infrastructure.Services
{
public class CallTokenService(LiveKitConfiguration configuration) : ICallTokenService
{
public CallAccessToken CreateAccessToken(string roomName, string identity, string? displayName)
{
var token = new AccessToken(configuration.ApiKey, configuration.ApiSecret)
.WithIdentity(identity)
.WithName(displayName ?? identity)
.WithGrants(new VideoGrants
{
RoomJoin = true,
Room = roomName,
CanPublish = true,
CanSubscribe = true,
CanPublishData = true,
})
.WithTtl(TimeSpan.FromMinutes(configuration.TokenTtlMinutes));
return new CallAccessToken(token.ToJwt(), roomName);
}
}
}
@@ -0,0 +1,52 @@
using Amazon.S3;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Ping.Application.Contracts;
using Ping.Infrastructure.Configuration;
namespace Ping.Infrastructure.Services
{
public static class ServicesDependencyInjection
{
public static IServiceCollection AddStorageService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<InfrastructureStorageConfiguration>()
.Bind(configuration.GetRequiredSection(InfrastructureStorageConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<InfrastructureStorageConfiguration>>().Value);
serviceDescriptors.AddSingleton<IAmazonS3>(serviceProvider =>
{
var storageConfiguration = serviceProvider.GetRequiredService<InfrastructureStorageConfiguration>();
var s3Configuration = new AmazonS3Config
{
ServiceURL = storageConfiguration.Address,
ForcePathStyle = storageConfiguration.ForcePathStyle,
UseHttp = storageConfiguration.UseHttp,
};
return new AmazonS3Client(storageConfiguration.AccessKey, storageConfiguration.SecretAccessKey, s3Configuration);
});
serviceDescriptors.AddScoped<IStorageService, StorageService>();
return serviceDescriptors;
}
public static IServiceCollection AddCallTokenService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
.AddOptionsWithValidateOnStart<LiveKitConfiguration>()
.Bind(configuration.GetRequiredSection(LiveKitConfiguration.SectionName))
.ValidateDataAnnotations();
serviceDescriptors.AddSingleton(serviceProvider =>
serviceProvider.GetRequiredService<IOptions<LiveKitConfiguration>>().Value);
serviceDescriptors.AddSingleton<ICallTokenService, CallTokenService>();
return serviceDescriptors;
}
}
}
@@ -0,0 +1,94 @@
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;
using Ping.Application.Contracts;
using Ping.Infrastructure.Configuration;
namespace Ping.Infrastructure.Services
{
public class StorageService(IAmazonS3 amazonS3, ILogger<StorageService> logger, InfrastructureStorageConfiguration storageClientConfiguration)
: IStorageService
{
public async Task<Stream> GetFileAsync(string bucket, string key, CancellationToken cancellationToken)
{
var request = new GetObjectRequest { BucketName = bucket, Key = key };
try
{
var response = await amazonS3.GetObjectAsync(request, cancellationToken);
logger.LogDebug("Retrieved file from S3 {Bucket}/{Key}", bucket, key);
return response.ResponseStream;
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to get file from S3 {Bucket}/{Key}", bucket, key);
throw;
}
}
public async Task<string> GetUrlAsync(string bucket, string key, TimeSpan expirationTime, CancellationToken cancellationToken)
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS,
};
logger.LogDebug("Generating pre-signed URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
}
public async Task<string> GetUploadUrlAsync(
string bucket,
string key,
string contentType,
TimeSpan expirationTime,
CancellationToken cancellationToken,
bool preventOverwrite = true)
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Expires = DateTime.UtcNow + expirationTime,
Protocol = storageClientConfiguration.UseHttp ? Protocol.HTTP : Protocol.HTTPS,
Verb = HttpVerb.PUT,
ContentType = contentType,
};
if (preventOverwrite)
request.Headers["If-None-Match"] = "*";
logger.LogDebug("Generating pre-signed upload URL for {Bucket}/{Key}", bucket, key);
return await amazonS3.GetPreSignedURLAsync(request);
}
public async Task<ObjectMetaData?> HeadObjectAsync(string bucket, string key, CancellationToken cancellationToken)
{
try
{
var response = await amazonS3.GetObjectMetadataAsync(bucket, key, cancellationToken);
return new ObjectMetaData(response.Headers.ContentType, response.ContentLength);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
catch (Exception exception)
{
logger.LogError(exception, "HEAD failed for {Bucket}/{Key}", bucket, key);
throw;
}
}
public async Task RemoveFileAsync(string bucket, string key, CancellationToken cancellationToken)
{
var request = new DeleteObjectRequest { BucketName = bucket, Key = key };
logger.LogDebug("Removing file from S3 {Bucket}/{Key}", bucket, key);
await amazonS3.DeleteObjectAsync(request, cancellationToken);
}
}
}