using StackExchange.Redis; using Telegram.Bot.Types; namespace nsszcontactbot; public class PhotosManager(ConnectionMultiplexer redis, string PhotoBasePath) { private readonly IDatabase _redisDb = redis.GetDatabase(); private readonly string _basePath = PhotoBasePath; private const string Key = "cache:photos"; private const string DefaultPhotoFileId = "AgACAgIAAxkDAAIDTWgtK4jsuoRTb7C4p0uhfVAOvWy2AAK1-TEb3cloSdmbxB-nuRFCAQADAgADcwADNgQ"; public async Task CacheEmployeePhotoAsync(Employee employee, string fileId, TimeSpan ttl = default) { string entryName = GetEntryName(employee); _redisDb.HashSetAsync(Key, [new(entryName, fileId)]).ConfigureAwait(false); ttl = ttl == default ? TimeSpan.FromDays(30) : ttl; _redisDb.HashFieldExpireAsync(Key, [new(entryName)], ttl).ConfigureAwait(false); } public async Task GetEmployeePhotoAsync(Employee employee) { string entryName = GetEntryName(employee); var val = await _redisDb.HashGetAsync(Key, entryName); if (val != RedisValue.Null && val.HasValue) { return InputFile.FromFileId(val!); } else { string photoPath = Path.Combine(_basePath, $"{employee.Id}.jpg"); photoPath = File.Exists(photoPath) ? photoPath : Path.Combine(_basePath, $"{employee.FullName}.jpg"); if (File.Exists(photoPath)) { var fileStream = new FileStream( photoPath, FileMode.Open, FileAccess.Read ); return InputFile.FromStream(fileStream); } return InputFile.FromFileId(DefaultPhotoFileId);; } } private static string GetEntryName(Employee employee) => $"employee:{employee.Id}:fileid"; }