Finish migration to MongoDb and general improvements

This commit is contained in:
2024-12-15 21:22:36 +03:30
parent 29011e34f9
commit dc38ce927f
13 changed files with 370 additions and 416 deletions

View File

@@ -1,5 +1,6 @@
using JsonFlatFileDataStore;
using System.Text;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using mstdnCats.Models;
using Telegram.Bot;
@@ -10,25 +11,20 @@ namespace mstdnCats.Services;
public class HandleDbBackup
{
public static async Task HandleDbBackupAsync(TelegramBotClient _bot, ILogger<MastodonBot>? logger, string dbname, string adminId,IDocumentCollection<Post> _bkDb,IMongoCollection<Post> _db)
public static async Task HandleDbBackupAsync(TelegramBotClient _bot, ILogger<MastodonBot>? logger, string dbname,
string adminId, IMongoCollection<Post> _db)
{
logger?.LogInformation("Backup requested");
// Retrieve all posts from DB (Exclude _id field from mongoDB since it is not needed nor implemented in Post model)
var posts = _db.AsQueryable().ToList();
// Retrieve all existing posts in backup DB
var existingPosts = _bkDb.AsQueryable().ToList();
// Insert new posts that are not in backup DB (First saves all the new ones in a list and then inserts them all at once)
var newPosts = posts.Where(x => !existingPosts.Any(y => y.mstdnPostId == x.mstdnPostId)).ToList();
await _bkDb.InsertManyAsync(newPosts);
await using Stream stream = System.IO.File.OpenRead("./data/" + dbname+"_BK.json");
var message = await _bot.SendDocument(adminId, document: InputFile.FromStream(stream, dbname+"_BK.json"),
caption: "Backup of " + dbname + "\nCreated at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss" + "\nCurrent post count: " + _db.AsQueryable().Count()), parseMode: ParseMode.Html);
var json = _db.Find(new BsonDocument()).ToList().ToJson();
var bytes = Encoding.UTF8.GetBytes(json);
var stream = new MemoryStream(bytes);
await _bot.SendDocument(adminId, InputFile.FromStream(stream, "backup.json"),
"Backup of your collection\nCreated at " +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss" + "\nCurrent post count: " + _db.CountDocuments(new BsonDocument())),
ParseMode.Html);
logger?.LogInformation("Backup sent");
}
}