using FileShare_Common.Core; using FileShare_Services.Core; using QRCoder; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace FileShare_Services.Services.QrCode { public sealed class QrCodeService : IQrCodeService { public Task GenerateQrCodeAsync(ServiceEndpointContext ctx) { var ip = GetLanIpAddress(); if (ip is null) throw new InvalidOperationException("无法获取局域网IP地址"); var url = $"http://{ip}:5206"; var base64 = GeneratePngBase64(url); return Task.FromResult(ResponseHelper.Ok(new QrCodeResponse(url, base64))); } private static string GeneratePngBase64(string content) { using var generator = new QRCodeGenerator(); using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.Q); using var png = new PngByteQRCode(data); var bytes = png.GetGraphic(20); return $"data:image/png;base64,{Convert.ToBase64String(bytes)}"; } private static string? GetLanIpAddress() { return NetworkInterface.GetAllNetworkInterfaces() .Where(ni => ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback) .SelectMany(ni => ni.GetIPProperties().UnicastAddresses) .Select(ua => ua.Address) .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip) && !ip.ToString().StartsWith("169.254")) ?.ToString(); } } }