Skip to content

Commit

Permalink
feat: add the video distribution logic
Browse files Browse the repository at this point in the history
The first version is for configuring the parameters for sending videos to contacts. Only a part is ready now
  • Loading branch information
ZenonEl committed Jan 11, 2025
1 parent f1c0f91 commit 3fdd6a8
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 12 deletions.
2 changes: 1 addition & 1 deletion TelegramBot/Handlers/GroupUpdateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static async Task HandleGroupUpdate(Update update, ITelegramBotClient bot
if (Utils.Utils.IsLink(link))
{
Message statusMessage = await botClient.SendMessage(update.Message.Chat.Id, Config.GetResourceString("WaitDownloadingVideo"), cancellationToken: cancellationToken);
_ = TelegramBot.HandleVideoRequest(botClient, link, update.Message.Chat.Id, statusMessage, true, text);
_ = TelegramBot.HandleVideoRequest(botClient, link, update.Message.Chat.Id, statusMessage: statusMessage, groupChat: true, caption: text);
}
else
{
Expand Down
7 changes: 5 additions & 2 deletions TelegramBot/Handlers/PrivateUpdateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@ public static async Task ProcessMessage(ITelegramBotClient botClient, Update upd

if (Utils.Utils.IsLink(link))
{
Message statusMessage = await botClient.SendMessage(chatId, Config.GetResourceString("WaitDownloadingVideo"), cancellationToken: cancellationToken);
_ = TelegramBot.HandleVideoRequest(botClient, link, chatId, statusMessage, caption: text);
int replyToMessageId = update.Message.MessageId;
Message statusMessage = await botClient.SendMessage(chatId, Config.GetResourceString("WaitDownloadingVideo"),
replyParameters: new ReplyParameters { MessageId = replyToMessageId }, cancellationToken: cancellationToken);
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId, Config.GetResourceString("VideoDistributionQuestion"), replyMarkup: KeyboardUtils.GetVideoDistributionKeyboardMarkup(), cancellationToken: cancellationToken);
TelegramBot.userStates[chatId] = new ProcessVideoDC(link, statusMessage, text);
}
else if (update.Message.Text == "/start")
{
Expand Down
18 changes: 9 additions & 9 deletions TelegramBot/MediaDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,14 @@ private static async Task UpdateHandler(ITelegramBotClient botClient, Update upd
}
}

public static async Task HandleVideoRequest(ITelegramBotClient botClient, string videoUrl, long chatId, Message statusMessage, bool groupChat = false, string caption = "")
public static async Task HandleVideoRequest(ITelegramBotClient botClient, string videoUrl, long chatId,
Message statusMessage, List<long>? targetUserIds = null, bool groupChat = false, string caption = "")
{
byte[]? videoBytes = await VideoGet.DownloadVideoAsync(botClient, videoUrl, statusMessage, cancellationToken);
if (videoBytes != null)
{
Log.Debug("Video successfully downloaded.");
await SendVideoToTelegram(videoBytes, chatId, botClient, statusMessage, groupChat, caption);
await SendVideoToTelegram(videoBytes, chatId, botClient, statusMessage, targetUserIds, groupChat, caption);
Log.Debug("Video successfully received.");
return;
}
Expand All @@ -121,7 +122,7 @@ public static async Task HandleVideoRequest(ITelegramBotClient botClient, string
}

public static async Task SendVideoToTelegram(byte[] videoBytes, long chatId, ITelegramBotClient botClient,
Message statusMessage, bool groupChat = false, string caption = "")
Message statusMessage, List<long>? targetUserIds, bool groupChat = false, string caption = "")
{
using (var memoryStream = new MemoryStream(videoBytes))
using (var progressStream = new Utils.ProgressReportingStream(memoryStream))
Expand Down Expand Up @@ -176,7 +177,7 @@ await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId,
else
FileId = message.Document!.FileId;

if (!groupChat)
if (!groupChat && targetUserIds != null && targetUserIds.Count > 0)
{
try
{
Expand All @@ -189,7 +190,7 @@ await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId,
Log.Debug(ex, "Error editing message.");
}
Log.Debug("Starting video distribution to contacts.");
await SendVideoToContacts(FileId, chatId, botClient, statusMessage, caption);
await SendVideoToContacts(FileId, chatId, botClient, statusMessage, targetUserIds, caption);
try
{
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId,
Expand All @@ -204,12 +205,11 @@ await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId,
}
}

private static async Task SendVideoToContacts(string fileId, long telegramId, ITelegramBotClient botClient, Message statusMessage, string caption = "")
private static async Task SendVideoToContacts(string fileId, long telegramId, ITelegramBotClient botClient, Message statusMessage, List<long> targetUserIds, string caption = "")
{
int userId = DBforGetters.GetUserIDbyTelegramID(telegramId);
var contactUserTGIds = await CoreDB.GetContactUserTGIds(userId);
var mutedByUserIds = DBforGetters.GetUsersIdForMuteContactId(userId);
var filteredContactUserTGIds = contactUserTGIds.Except(mutedByUserIds).ToList();
List<long> mutedByUserIds = DBforGetters.GetUsersIdForMuteContactId(userId);
List<long> filteredContactUserTGIds = targetUserIds.Except(mutedByUserIds).ToList();

Log.Information($"Sending video to ({filteredContactUserTGIds.Count}) users.");
Log.Information($"User {userId} is muted by: {mutedByUserIds.Count}");
Expand Down
146 changes: 146 additions & 0 deletions TelegramBot/States/VideoDistributionConfigurator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
using Telegram.Bot;
using Telegram.Bot.Types;
using DataBase;
using MediaTelegramBot.Utils;
using TelegramMediaRelayBot;


namespace MediaTelegramBot;

public class ProcessVideoDC : IUserState
{
public UsersGroupState currentState;
public string link { get; set; }
public Message statusMessage { get; set; }
public string text { get; set; }
private string action = "";
private List<long> targetUserIds = new List<long>();

public ProcessVideoDC(string Link, Message StatusMessage, string Text)
{
link = Link;
statusMessage = StatusMessage;
text = Text;
currentState = UsersGroupState.ProcessAction;
}

public string GetCurrentState()
{
return currentState.ToString();
}

public async Task ProcessState(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
long chatId = Utils.Utils.GetIDfromUpdate(update);
if (!TelegramBot.userStates.TryGetValue(chatId, out IUserState? value))
return;

var userState = (ProcessVideoDC)value;

switch (userState.currentState)
{
case UsersGroupState.ProcessAction:
if (update.CallbackQuery != null)
{
string callbackData = update.CallbackQuery.Data!;
switch (callbackData)
{
case "send_to_all_contacts":
userState.action = "send_to_all_contacts";
await PrepareTargetUserIds(chatId, userState);
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId, Config.GetResourceString("ConfirmDecision"), replyMarkup: KeyboardUtils.GetConfirmForActionKeyboardMarkup(), cancellationToken: cancellationToken);
break;
case "send_to_default_groups":
userState.action = "send_to_default_groups";
await PrepareTargetUserIds(chatId, userState);
break;
case "send_to_specified_groups":
userState.action = "send_to_specified_groups";
await botClient.SendMessage(chatId, "Please enter group IDs separated by spaces:", cancellationToken: cancellationToken);
userState.currentState = UsersGroupState.ProcessData;
break;
case "send_to_specified_users":
userState.action = "send_to_specified_users";
await botClient.SendMessage(chatId, "Please enter user IDs separated by spaces:", cancellationToken: cancellationToken);
userState.currentState = UsersGroupState.ProcessData;
break;
case "send_only_to_me":
userState.action = "send_only_to_me";
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId, Config.GetResourceString("ConfirmDecision"), replyMarkup: KeyboardUtils.GetConfirmForActionKeyboardMarkup(), cancellationToken: cancellationToken);
userState.currentState = UsersGroupState.Finish;
break;
case "main_menu":
await Utils.Utils.HandleStateBreakCommand(botClient, update, chatId, removeReplyMarkup: false);
break;
}
}
break;

case UsersGroupState.ProcessData:
if (update.Message != null)
{
string input = update.Message.Text!;
if (input.Contains(" "))
{
string[] ids = input.Split(' ');
if (ids.All(id => long.TryParse(id, out _)))
{
targetUserIds = ids.Select(long.Parse).ToList();
await PrepareTargetUserIds(chatId, userState);
}
else
{
await botClient.SendMessage(chatId, "Invalid input. Please enter numbers separated by spaces.", cancellationToken: cancellationToken);
}
}
else
{
if (long.TryParse(input, out long id))
{
targetUserIds.Add(id);
await PrepareTargetUserIds(chatId, userState);
}
else
{
await botClient.SendMessage(chatId, "Invalid input. Please enter a number.", cancellationToken: cancellationToken);
}
}
}
break;

case UsersGroupState.Finish:
if (update.CallbackQuery != null && update.CallbackQuery.Data == "main_menu" ||
update.Message != null)
{
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId, Config.GetResourceString("VideoDistributionQuestion"), replyMarkup: KeyboardUtils.GetVideoDistributionKeyboardMarkup(), cancellationToken: cancellationToken);
userState.currentState = UsersGroupState.ProcessAction;
return;
}
await botClient.EditMessageText(statusMessage.Chat.Id, statusMessage.MessageId, Config.GetResourceString("WaitDownloadingVideo"), cancellationToken: cancellationToken);
TelegramBot.userStates.Remove(chatId);
_ = TelegramBot.HandleVideoRequest(botClient, link, chatId, statusMessage, targetUserIds, caption: text);
break;
}
}

private async Task PrepareTargetUserIds(long chatId, ProcessVideoDC userState)
{
int userId = DBforGetters.GetUserIDbyTelegramID(chatId);
switch (userState.action)
{
case "send_to_all_contacts":
List<long> contactUserTGIds = await CoreDB.GetAllContactUserTGIds(userId);
List<long> mutedByUserIds = DBforGetters.GetUsersIdForMuteContactId(userId);
targetUserIds = contactUserTGIds.Except(mutedByUserIds).ToList();
break;
case "send_to_default_groups":
targetUserIds = new List<long>();
break;
case "send_to_specified_groups":
case "send_to_specified_users":
break;
}

userState.currentState = UsersGroupState.Finish;
}
}

0 comments on commit 3fdd6a8

Please sign in to comment.