BotSharp/src/Infrastructure/BotSharp.Core/Files/BotSharpFileService.Conversation.cs

322 lines
11 KiB
C#
Raw Normal View History

2024-06-06 01:16:48 +00:00
using BotSharp.Abstraction.Browsing;
2024-06-12 03:07:58 +00:00
using BotSharp.Abstraction.Browsing.Models;
2024-06-06 01:16:48 +00:00
using Microsoft.EntityFrameworkCore;
2024-05-22 15:39:04 +00:00
using System.IO;
2024-06-06 18:30:39 +00:00
using System.Linq;
2024-05-22 15:39:04 +00:00
using System.Threading;
namespace BotSharp.Core.Files;
public partial class BotSharpFileService
{
2024-06-07 04:02:10 +00:00
public async Task<IEnumerable<MessageFileModel>> GetChatImages(string conversationId, string source, IEnumerable<string> fileTypes,
List<RoleDialogModel> conversations, int? offset = null)
2024-05-22 15:39:04 +00:00
{
var files = new List<MessageFileModel>();
if (string.IsNullOrEmpty(conversationId) || conversations.IsNullOrEmpty())
{
2024-06-07 04:02:10 +00:00
return new List<MessageFileModel>();
2024-05-22 15:39:04 +00:00
}
if (offset <= 0)
{
offset = MIN_OFFSET;
}
else if (offset > MAX_OFFSET)
{
offset = MAX_OFFSET;
}
2024-06-06 18:30:39 +00:00
var messageIds = new List<string>();
if (offset.HasValue)
{
messageIds = conversations.Select(x => x.MessageId).Distinct().TakeLast(offset.Value).ToList();
}
else
{
messageIds = conversations.Select(x => x.MessageId).Distinct().ToList();
}
2024-06-07 04:02:10 +00:00
files = await GetMessageFiles(conversationId, messageIds, source, fileTypes);
return files;
}
private async Task<List<MessageFileModel>> GetMessageFiles(string conversationId, IEnumerable<string> messageIds, string source, IEnumerable<string> fileTypes)
{
var files = new List<MessageFileModel>();
if (string.IsNullOrEmpty(conversationId) || messageIds.IsNullOrEmpty() || fileTypes.IsNullOrEmpty()) return files;
var isNeedScreenShot = fileTypes.Any(x => _allowScreenShotTypes.Contains(x));
var onlyScreenShot = fileTypes.All(x => _allowScreenShotTypes.Contains(x));
try
{
2024-06-12 03:07:58 +00:00
var msgInfo = new MessageInfo
{
ContextId = Guid.NewGuid().ToString()
};
2024-06-07 04:02:10 +00:00
var web = _services.GetRequiredService<IWebBrowser>();
var preFixPath = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER);
if (isNeedScreenShot)
{
2024-06-12 03:07:58 +00:00
await web.LaunchBrowser(msgInfo);
2024-06-07 04:02:10 +00:00
}
foreach (var messageId in messageIds)
{
var dir = Path.Combine(preFixPath, messageId, source);
if (!ExistDirectory(dir)) continue;
foreach (var subDir in Directory.GetDirectories(dir))
{
var file = Directory.GetFiles(subDir).FirstOrDefault();
if (file == null) continue;
var index = subDir.Split(Path.DirectorySeparatorChar).Last();
var contentType = GetFileContentType(file);
if ((!isNeedScreenShot || (isNeedScreenShot && !onlyScreenShot)) && _allowedImageTypes.Contains(contentType))
{
var model = new MessageFileModel()
{
MessageId = messageId,
FileStorageUrl = file,
ContentType = contentType
};
files.Add(model);
}
else if ((isNeedScreenShot && !onlyScreenShot || onlyScreenShot) && !_allowedImageTypes.Contains(contentType))
{
var screenShotDir = Path.Combine(subDir, SCREENSHOT_FILE_FOLDER);
if (ExistDirectory(screenShotDir) && Directory.GetFiles(screenShotDir).Any())
{
file = Directory.GetFiles(screenShotDir).First();
contentType = GetFileContentType(file);
var model = new MessageFileModel()
{
MessageId = messageId,
FileStorageUrl = file,
ContentType = contentType
};
files.Add(model);
}
else
{
2024-06-12 03:07:58 +00:00
await web.GoToPage(msgInfo, new PageActionArgs { Url = file });
2024-06-07 04:02:10 +00:00
var path = Path.Combine(subDir, SCREENSHOT_FILE_FOLDER, $"{Guid.NewGuid()}.png");
2024-06-12 03:07:58 +00:00
await web.ScreenshotAsync(msgInfo, path);
2024-06-07 04:02:10 +00:00
contentType = GetFileContentType(path);
var model = new MessageFileModel()
{
MessageId = messageId,
FileStorageUrl = path,
ContentType = contentType
};
files.Add(model);
}
}
}
}
if (isNeedScreenShot)
{
2024-06-12 03:07:58 +00:00
await web.CloseBrowser(msgInfo.ContextId);
2024-06-07 04:02:10 +00:00
}
}
catch (Exception ex)
{
_logger.LogWarning($"Error when reading conversation ({conversationId}) files: {ex.Message}");
}
2024-05-22 15:39:04 +00:00
return files;
}
2024-06-06 19:57:41 +00:00
public IEnumerable<MessageFileModel> GetMessageFiles(string conversationId, IEnumerable<string> messageIds,
string source, bool imageOnly = false)
2024-05-22 15:39:04 +00:00
{
var files = new List<MessageFileModel>();
if (messageIds.IsNullOrEmpty()) return files;
foreach (var messageId in messageIds)
{
2024-06-06 19:57:41 +00:00
var dir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER, messageId, source);
2024-05-22 15:39:04 +00:00
if (!ExistDirectory(dir))
{
continue;
}
2024-06-06 19:57:41 +00:00
foreach (var subDir in Directory.GetDirectories(dir))
2024-05-22 15:39:04 +00:00
{
2024-06-06 19:57:41 +00:00
var index = subDir.Split(Path.DirectorySeparatorChar).Last();
2024-05-22 15:39:04 +00:00
2024-06-06 19:57:41 +00:00
foreach (var file in Directory.GetFiles(subDir))
2024-05-22 15:39:04 +00:00
{
2024-06-06 19:57:41 +00:00
var contentType = GetFileContentType(file);
if (imageOnly && !_allowedImageTypes.Contains(contentType))
{
continue;
}
var fileName = Path.GetFileNameWithoutExtension(file);
var extension = Path.GetExtension(file);
var fileType = extension.Substring(1);
var model = new MessageFileModel()
{
MessageId = messageId,
FileUrl = $"/conversation/{conversationId}/message/{messageId}/{source}/file/{index}/{fileName}",
FileStorageUrl = file,
FileName = fileName,
FileType = fileType,
ContentType = contentType
};
files.Add(model);
}
2024-05-22 15:39:04 +00:00
}
}
return files;
}
2024-06-06 19:57:41 +00:00
public string GetMessageFile(string conversationId, string messageId, string source, string index, string fileName)
2024-05-22 15:39:04 +00:00
{
2024-06-06 19:57:41 +00:00
var dir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER, messageId, source, index);
2024-05-22 15:39:04 +00:00
if (!ExistDirectory(dir))
{
return string.Empty;
}
var found = Directory.GetFiles(dir).FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).IsEqualTo(fileName));
return found;
}
2024-06-06 19:57:41 +00:00
public bool HasConversationUserFiles(string conversationId)
2024-06-06 18:30:39 +00:00
{
if (string.IsNullOrEmpty(conversationId)) return false;
2024-06-07 04:02:10 +00:00
var dir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER);
2024-06-06 18:30:39 +00:00
if (!ExistDirectory(dir)) return false;
2024-06-07 14:44:29 +00:00
return Directory.GetDirectories(dir).Any();
2024-06-06 18:30:39 +00:00
}
2024-06-06 19:57:41 +00:00
public bool SaveMessageFiles(string conversationId, string messageId, string source, List<BotSharpFile> files)
2024-05-22 15:39:04 +00:00
{
if (files.IsNullOrEmpty()) return false;
var dir = GetConversationFileDirectory(conversationId, messageId, createNewDir: true);
if (!ExistDirectory(dir)) return false;
try
{
for (int i = 0; i < files.Count; i++)
{
var file = files[i];
if (string.IsNullOrEmpty(file.FileData))
{
continue;
}
var (_, bytes) = GetFileInfoFromData(file.FileData);
Thread.Sleep(100);
2024-06-06 19:57:41 +00:00
var subDir = Path.Combine(dir, source, $"{i + 1}");
if (!ExistDirectory(subDir))
2024-06-06 01:16:48 +00:00
{
2024-06-06 19:57:41 +00:00
Directory.CreateDirectory(subDir);
2024-06-06 01:16:48 +00:00
}
2024-06-06 19:57:41 +00:00
File.WriteAllBytes(Path.Combine(subDir, file.FileName), bytes);
2024-06-06 01:16:48 +00:00
}
2024-05-22 15:39:04 +00:00
return true;
}
catch (Exception ex)
{
_logger.LogWarning($"Error when saving conversation files: {ex.Message}");
return false;
}
}
public bool DeleteMessageFiles(string conversationId, IEnumerable<string> messageIds, string targetMessageId, string? newMessageId = null)
{
if (string.IsNullOrEmpty(conversationId) || messageIds == null) return false;
if (!string.IsNullOrEmpty(targetMessageId) && !string.IsNullOrEmpty(newMessageId))
{
var prevDir = GetConversationFileDirectory(conversationId, targetMessageId);
var newDir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER, newMessageId);
if (ExistDirectory(prevDir))
{
if (ExistDirectory(newDir))
{
Directory.Delete(newDir, true);
}
Directory.Move(prevDir, newDir);
2024-06-06 19:57:41 +00:00
Thread.Sleep(100);
var botDir = Path.Combine(newDir, BOT_FILE_FOLDER);
if (ExistDirectory(botDir))
{
Directory.Delete(botDir, true);
}
2024-05-22 15:39:04 +00:00
}
}
foreach (var messageId in messageIds)
{
var dir = GetConversationFileDirectory(conversationId, messageId);
2024-05-31 17:02:34 +00:00
if (!ExistDirectory(dir)) continue;
2024-05-22 15:39:04 +00:00
Thread.Sleep(100);
Directory.Delete(dir, true);
}
return true;
}
public bool DeleteConversationFiles(IEnumerable<string> conversationIds)
{
if (conversationIds.IsNullOrEmpty()) return false;
foreach (var conversationId in conversationIds)
{
var convDir = FindConversationDirectory(conversationId);
if (!ExistDirectory(convDir)) continue;
Directory.Delete(convDir, true);
}
return true;
}
#region Private methods
private string GetConversationFileDirectory(string? conversationId, string? messageId, bool createNewDir = false)
{
if (string.IsNullOrEmpty(conversationId) || string.IsNullOrEmpty(messageId))
{
return string.Empty;
}
var dir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId, FILE_FOLDER, messageId);
if (!Directory.Exists(dir) && createNewDir)
{
Directory.CreateDirectory(dir);
}
return dir;
}
private string? FindConversationDirectory(string conversationId)
{
if (string.IsNullOrEmpty(conversationId)) return null;
var dir = Path.Combine(_baseDir, CONVERSATION_FOLDER, conversationId);
return dir;
}
#endregion
}