using Knot.Shared.Kernel; using Knot.Shared.Kernel.Configuration; using Microsoft.Extensions.Configuration; using MediatR; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Host.Application.WebRtc.Queries; public record IceServerDto(string[] Urls, string? Username = null, string? Credential = null); public record IceServersResultDto(List IceServers); public record GetIceServersQuery : IQuery; internal sealed class GetIceServersQueryHandler : IQueryHandler { private readonly IConfiguration _configuration; private readonly ISettingsService _settingsService; public GetIceServersQueryHandler(IConfiguration configuration, ISettingsService settingsService) { _configuration = configuration; _settingsService = settingsService; } public Task> Handle(GetIceServersQuery request, CancellationToken cancellationToken) { var settings = _settingsService.Current; if (!settings.EnableCalls) { return Task.FromResult(Result.Failure(new Error( Knot.Shared.Kernel.Constants.Errors.DisabledByAdmin, "Сервис отключен администратором." ))); } var turnUrl = !string.IsNullOrEmpty(settings.TurnHost) ? $"turn:{settings.TurnHost}:{settings.TurnPort}" : _configuration["WebRtc:TurnUrl"]; var turnUsername = !string.IsNullOrEmpty(settings.TurnUser) ? settings.TurnUser : _configuration["WebRtc:TurnUsername"]; var turnSecret = !string.IsNullOrEmpty(settings.TurnSecret) ? settings.TurnSecret : _configuration["WebRtc:TurnPassword"]; var iceServers = new List(); if (!string.IsNullOrEmpty(turnUrl)) { var stunUrl = turnUrl.Replace("turn:", "stun:"); iceServers.Add(new IceServerDto(new[] { stunUrl })); if (!string.IsNullOrEmpty(turnUsername)) { iceServers.Add(new IceServerDto( new[] { turnUrl, turnUrl + "?transport=tcp" }, turnUsername, !string.IsNullOrEmpty(turnSecret) ? turnSecret : turnUsername )); } else { iceServers.Add(new IceServerDto(new[] { turnUrl, turnUrl + "?transport=tcp" })); } } return Task.FromResult(Result.Success(new IceServersResultDto(iceServers))); } }