102 lines
3.0 KiB
C#
102 lines
3.0 KiB
C#
using LiteDB;
|
|
using VideoStudy.Shared;
|
|
|
|
namespace VideoStudy.Shared.Services;
|
|
|
|
public class PersistenceService
|
|
{
|
|
private readonly string _basePath;
|
|
private readonly string _dbPath;
|
|
|
|
public PersistenceService()
|
|
{
|
|
// Define a pasta base em %USERPROFILE%/MeuVideoStudy
|
|
// Funciona em Windows, macOS e Linux (limitado pelo ambiente MAUI)
|
|
_basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "MeuVideoStudy");
|
|
_dbPath = Path.Combine(_basePath, "videostudy.db");
|
|
|
|
if (!Directory.Exists(_basePath))
|
|
{
|
|
Directory.CreateDirectory(_basePath);
|
|
}
|
|
}
|
|
|
|
public string GetBasePath() => _basePath;
|
|
|
|
/// <summary>
|
|
/// Retorna as subpastas físicas dentro do diretório base.
|
|
/// </summary>
|
|
public List<string> GetFolders()
|
|
{
|
|
if (!Directory.Exists(_basePath)) return new List<string>();
|
|
|
|
return Directory.GetDirectories(_basePath)
|
|
.Select(Path.GetFileName)
|
|
.Where(name => name != null)
|
|
.ToList()!;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cria uma nova pasta física.
|
|
/// </summary>
|
|
public void CreateFolder(string folderName)
|
|
{
|
|
var path = Path.Combine(_basePath, folderName);
|
|
if (!Directory.Exists(path))
|
|
{
|
|
Directory.CreateDirectory(path);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Salva o PDF no disco e registra no LiteDB.
|
|
/// </summary>
|
|
public async Task<VideoStudySession> SaveSessionAsync(byte[] pdfData, string title, string? youtubeId, string folderName = "Geral")
|
|
{
|
|
// Garantir que a pasta existe
|
|
var folderPath = Path.Combine(_basePath, folderName);
|
|
if (!Directory.Exists(folderPath))
|
|
{
|
|
Directory.CreateDirectory(folderPath);
|
|
}
|
|
|
|
// Criar nome de arquivo seguro
|
|
var safeTitle = string.Join("_", title.Split(Path.GetInvalidFileNameChars()));
|
|
var fileName = $"{safeTitle}_{DateTime.Now:yyyyMMdd_HHmmss}.pdf";
|
|
var filePath = Path.Combine(folderPath, fileName);
|
|
|
|
// Gravar arquivo físico
|
|
await File.WriteAllBytesAsync(filePath, pdfData);
|
|
|
|
// Registrar no LiteDB
|
|
using var db = new LiteDatabase(_dbPath);
|
|
var collection = db.GetCollection<VideoStudySession>("sessions");
|
|
|
|
var session = new VideoStudySession
|
|
{
|
|
Title = title,
|
|
YouTubeId = youtubeId ?? "local",
|
|
FilePath = filePath,
|
|
FolderName = folderName,
|
|
CreatedAt = DateTime.Now
|
|
};
|
|
|
|
collection.Insert(session);
|
|
collection.EnsureIndex(x => x.Title);
|
|
|
|
return session;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupera todas as sessões do banco.
|
|
/// </summary>
|
|
public List<VideoStudySession> GetAllSessions()
|
|
{
|
|
using var db = new LiteDatabase(_dbPath);
|
|
return db.GetCollection<VideoStudySession>("sessions")
|
|
.FindAll()
|
|
.OrderByDescending(x => x.CreatedAt)
|
|
.ToList();
|
|
}
|
|
}
|