Added new read code for reading data in from a database file. Added Logger to log when a file is created, or the file has been changed. Changed Error to log as error, instead of Console writting.
97 lines
No EOL
2.6 KiB
C#
97 lines
No EOL
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using Serilog;
|
|
|
|
namespace FreeTubeSyncer.Library;
|
|
|
|
public class DBSyncWatcher
|
|
{
|
|
private FileSystemWatcher _watcher;
|
|
public Dictionary<string, Type> WatchFiles { get; set; } = [];
|
|
|
|
public delegate void DatabaseChange(string db, string value);
|
|
public event DatabaseChange OnDatabaseChange;
|
|
|
|
public bool Locked = false;
|
|
|
|
public DBSyncWatcher(string path)
|
|
{
|
|
_watcher = new FileSystemWatcher(path);
|
|
_watcher.NotifyFilter = NotifyFilters.LastWrite |
|
|
NotifyFilters.CreationTime;
|
|
|
|
_watcher.Changed += HandleChanged;
|
|
_watcher.Created += HandleCreated;
|
|
_watcher.Error += HandleError;
|
|
|
|
_watcher.Filter = "*.db";
|
|
_watcher.IncludeSubdirectories = true;
|
|
_watcher.EnableRaisingEvents = true;
|
|
}
|
|
|
|
private void HandleChanged(object sender, FileSystemEventArgs e)
|
|
{
|
|
if (e.ChangeType != WatcherChangeTypes.Changed) return;
|
|
|
|
while (Locked)
|
|
{
|
|
Thread.Sleep(100);
|
|
}
|
|
|
|
var dbName = Path.GetFileName(e.FullPath);
|
|
|
|
if (!WatchFiles.Keys.Contains(dbName)) return;
|
|
|
|
Log.Information("Database File Changed: {DbName}", dbName);
|
|
|
|
var data = new List<string>();
|
|
|
|
using var fh = File.OpenText(e.FullPath);
|
|
while (!fh.EndOfStream)
|
|
data.Add(fh.ReadLine() ?? string.Empty);
|
|
|
|
foreach (var line in data)
|
|
{
|
|
if (line == "") continue;
|
|
var type = WatchFiles[dbName];
|
|
OnDatabaseChange?.Invoke(dbName, line);
|
|
}
|
|
}
|
|
|
|
private void HandleCreated(object sender, FileSystemEventArgs e)
|
|
{
|
|
if (e.ChangeType != WatcherChangeTypes.Created) return;
|
|
|
|
while (Locked)
|
|
{
|
|
Thread.Sleep(100);
|
|
}
|
|
|
|
var dbName = Path.GetFileName(e.FullPath);
|
|
|
|
if (!WatchFiles.Keys.Contains(dbName)) return;
|
|
|
|
Log.Information("Database File Created: {DbName}", dbName);
|
|
|
|
var data = new List<string>();
|
|
using var fh = File.OpenText(e.FullPath);
|
|
|
|
while (!fh.EndOfStream)
|
|
data.Add(fh.ReadLine() ?? string.Empty);
|
|
|
|
foreach (var line in data)
|
|
{
|
|
if (line == "") continue;
|
|
var type = WatchFiles[dbName];
|
|
OnDatabaseChange?.Invoke(dbName, line);
|
|
}
|
|
}
|
|
|
|
private void HandleError(object sender, ErrorEventArgs e)
|
|
{
|
|
Log.Error("Error: {Message}\n{StackTrace}", e.GetException().Message, e.GetException().StackTrace);
|
|
}
|
|
} |