Compare commits

..

3 Commits

3 changed files with 109 additions and 7 deletions

View File

@ -19,7 +19,7 @@ public class AutoScanApp
private readonly IScheduler _scheduler;
private readonly IChainerListenerFactory _chainerListenerFactory;
public Func<AutoScanOptions, Task>? OnScanCompleted { get; set; }
public Func<Task>? OnScanCompleted { get; set; }
public AutoScanApp(IOptions<AutoScanOptions> options, ILogger<AutoScanApp> logger, IScheduler scheduler, IChainerListenerFactory chainerListenerFactory)
{
@ -72,7 +72,7 @@ public class AutoScanApp
.AddJob(downloaderJob)
.AddJob(scannerJob)
.AddJob(cleanJob)
.OnFinish(async () => await OnScanCompleted?.Invoke(_options))
.OnFinish(async () => await OnScanCompleted?.Invoke())
.Build();
_scheduler.ListenerManager.AddJobListener(chainer, GroupMatcher<JobKey>.GroupEquals(GROUP_NAME));
@ -90,6 +90,24 @@ public class AutoScanApp
await _scheduler.TriggerJob(jobKey);
}
public string[] GetLastScanPictures()
{
if (_options.Scanner?.DetectionFolder is null)
return [];
return Directory.GetFiles(_options.Scanner.DetectionFolder , "*.jpg");
}
public string? GetVideoPath(string name)
{
var path = Path.Combine(_options.Scanner.DetectionFolder, name + ".avi");
if (!File.Exists(path))
{
_logger.LogWarning("File {Path} does not exist", path);
return null;
}
return path;
}
private string CronFromAt(string at)
{

View File

@ -17,6 +17,8 @@ public class BotHandler : IUpdateHandler
private readonly List<Chat> _subscribers = [];
private readonly Dictionary<string, BotCommand> _commands;
public Func<TextMessage, Task>? OnReply { get; set; } = null;
private readonly IBotClient _bot;
public BotHandler(IBotClient bot, IOptions<TelegramOptions> telegramConfiguration, ILogger<BotHandler> logger)
@ -114,6 +116,20 @@ public class BotHandler : IUpdateHandler
}
}
public async Task SendVideo(long chatId, string path)
{
_logger.LogInformation("Sending video to {ChatId}", chatId);
await using var stream = File.OpenRead(path);
var send = new SendVideoFile(chatId.ToString(), stream);
var response = await _bot.HandleAsync(send);
if (!response.Ok)
{
_logger.LogError("Error sending video.");
}
_logger.LogInformation("Video sent to {ChatId}", chatId);
stream.Close();
}
public async Task UpdatePhotos(string[] paths)
{
if (_subscribers.Count == 0)
@ -133,7 +149,10 @@ public class BotHandler : IUpdateHandler
private async Task UpdatePhotosInt(string[] paths)
{
var streams = paths.Select(File.OpenRead).ToList();
var photos = streams.Select(stream => new PhotoFile(stream)).Cast<IGroupableMedia>().ToList();
var photos = streams.Select(stream => new PhotoFile(stream)
{
Caption = Path.GetFileNameWithoutExtension(stream.Name)
}).Cast<IGroupableMedia>().ToList();
var s0 = _subscribers.FirstOrDefault()?.Id.ToString();
if(s0 is null)
@ -180,12 +199,44 @@ public class BotHandler : IUpdateHandler
await _bot.HandleAsync(send);
}
/// <summary>
/// Send photos to a specific chat
/// </summary>
/// <param name="chatId"></param>
/// <param name="paths"></param>
public async Task SendPhotos(long chatId, string[] paths)
{
var streams = paths.Select(File.OpenRead).ToArray();
var photos = streams.Select(stream => new PhotoFile(stream)
{
Caption = Path.GetFileNameWithoutExtension(stream.Name)
}).Cast<IGroupableMedia>().ToArray();
var request = new SendMediaGroup(chatId.ToString(), photos);
var response = await _bot.HandleAsync(request);
if (!response.Ok)
{
_logger.LogError("Error sending photos.");
}
foreach (var stream in streams)
{
stream.Close();
await stream.DisposeAsync();
}
}
private async Task OnMessage(TextMessage msg)
{
if(!_commands.TryGetValue(msg.Text, out var command))
{
if (msg.ReplyToMessage != null && OnReply is not null)
{
await OnReply(msg);
return;
}
await SendHelp(msg);
return;
}

View File

@ -1,5 +1,6 @@
using AutoScan;
using Microsoft.Extensions.Logging;
using Telegram.Bots.Types;
namespace CasaBotApp.Extensions;
@ -26,19 +27,51 @@ public static class CommandRegister
await autoScanApp.StartNewScan();
}
});
botHandler.RegisterCommand(new BotCommand
{
Command = "/lastScan",
Description = "Send the images from the last scan",
Action = async (message, ctx) =>
{
var images = autoScanApp.GetLastScanPictures();
if (images.Length == 0)
{
await ctx.Responder(message, "No images found");
return;
}
await botHandler.SendPhotos(message.Chat.Id, images);
}
});
botHandler.OnReply = async msg =>
{
var originalMsg = msg.ReplyToMessage;
// Check if the original message is a photo and has a caption
if (originalMsg is not PhotoMessage photoMessage || photoMessage.Caption is null)
return;
var videoPath = autoScanApp.GetVideoPath(photoMessage.Caption);
if (string.IsNullOrEmpty(videoPath))
return;
await botHandler.SendVideo(msg.Chat.Id, videoPath);
};
}
public static void UpdateOnScanCompleted(BotHandler botHandler, AutoScanApp autoScanApp, ILogger logger)
{
autoScanApp.OnScanCompleted = async options =>
autoScanApp.OnScanCompleted = async () =>
{
logger.LogInformation("Scan completed at {At}", DateTime.Now);
try
{
//list all the images in the detection folder
if (options.Scanner?.DetectionFolder is null)
var images = autoScanApp.GetLastScanPictures();
if (images.Length == 0)
{
await botHandler.Update("No images found");
return;
var images = Directory.GetFiles(options.Scanner.DetectionFolder , "*.jpg");
}
await botHandler.Update($"Scan completed, found {images.Length} images");
await botHandler.UpdatePhotos(images);
}catch(Exception ex)