2023-01-05 15:32:21 +00:00
|
|
|
|
namespace BinaryDad.Notes.Services
|
|
|
|
|
{
|
|
|
|
|
public class FileNoteService : INoteService
|
|
|
|
|
{
|
2024-01-07 02:01:17 +00:00
|
|
|
|
private readonly string folderPath;
|
2023-01-05 15:32:21 +00:00
|
|
|
|
|
2024-01-07 02:01:17 +00:00
|
|
|
|
private static readonly string defaultFolderPath = "notes";
|
2023-08-04 22:26:22 +00:00
|
|
|
|
|
2023-01-05 15:32:21 +00:00
|
|
|
|
public FileNoteService(IConfiguration configuration)
|
|
|
|
|
{
|
2024-01-07 02:01:17 +00:00
|
|
|
|
folderPath = configuration["FileNoteService:ContentFolder"];
|
2023-08-04 22:26:22 +00:00
|
|
|
|
|
2024-01-07 02:01:17 +00:00
|
|
|
|
if (string.IsNullOrWhiteSpace(folderPath))
|
2023-08-04 22:26:22 +00:00
|
|
|
|
{
|
2024-01-07 02:01:17 +00:00
|
|
|
|
folderPath = defaultFolderPath;
|
2023-08-04 22:26:22 +00:00
|
|
|
|
}
|
2023-02-07 17:21:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-18 01:44:41 +00:00
|
|
|
|
public string GetText(string noteName)
|
2023-02-07 17:21:22 +00:00
|
|
|
|
{
|
|
|
|
|
CheckFile(noteName);
|
|
|
|
|
|
2023-05-12 16:13:35 +00:00
|
|
|
|
return File.ReadAllText(GetFilePath(noteName));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public ICollection<string> GetNoteNames()
|
|
|
|
|
{
|
2024-01-07 02:01:17 +00:00
|
|
|
|
return Directory.GetFiles(folderPath)
|
2023-05-12 16:38:13 +00:00
|
|
|
|
.Select(f => Path.GetFileName(f))
|
|
|
|
|
.ToList();
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-18 01:44:41 +00:00
|
|
|
|
public void SaveText(string content, string noteName)
|
2023-01-05 15:32:21 +00:00
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
File.WriteAllText(GetFilePath(noteName), content);
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-12 16:47:54 +00:00
|
|
|
|
public void DeleteNote(string noteName)
|
|
|
|
|
{
|
|
|
|
|
var filePath = GetFilePath(noteName);
|
|
|
|
|
|
|
|
|
|
File.Delete(filePath);
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-18 01:44:41 +00:00
|
|
|
|
private void CheckFile(string noteName)
|
2023-01-05 15:32:21 +00:00
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
var filePath = GetFilePath(noteName);
|
2023-02-07 17:21:22 +00:00
|
|
|
|
|
|
|
|
|
// ensure initialized
|
2023-05-12 16:13:35 +00:00
|
|
|
|
if (!File.Exists(filePath))
|
2023-02-07 17:21:22 +00:00
|
|
|
|
{
|
2024-01-07 02:01:17 +00:00
|
|
|
|
Directory.CreateDirectory(folderPath);
|
|
|
|
|
|
2023-05-12 16:38:13 +00:00
|
|
|
|
SaveText("Hi! Feel free to start typing. Everything will be saved soon after you are done typing.", noteName);
|
2023-02-07 17:21:22 +00:00
|
|
|
|
}
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
2023-02-07 17:21:22 +00:00
|
|
|
|
|
2023-05-18 01:44:41 +00:00
|
|
|
|
private string GetFilePath(string noteName)
|
2023-05-12 16:13:35 +00:00
|
|
|
|
{
|
|
|
|
|
noteName = noteName.Trim().ToLower();
|
|
|
|
|
|
2024-01-07 02:01:17 +00:00
|
|
|
|
return Path.Combine(folderPath, noteName);
|
2023-05-12 16:13:35 +00:00
|
|
|
|
}
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
}
|