Archived
1
0
This repository has been archived on 2021-10-19. You can view files and clone it, but cannot push or open issues or pull requests.
nonabgs/Journal/JournalStream.cs

88 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NonaBGS.Journal;
using System.IO;
namespace NonaBGS.Journal {
public class JournalStream {
private PlayerJournal journal = null;
private FileSystemWatcher watcher = null;
private Dictionary<string, StreamReader> streams = new Dictionary<string, StreamReader>();
public delegate void NewJournalEntryDelegate(Entry entry);
public event NewJournalEntryDelegate NewJournalEntry;
public PlayerJournal Journal {
get => journal;
set => journal = value;
}
public JournalStream() {
}
public JournalStream(PlayerJournal journal) {
this.journal = journal;
Open();
}
public void Open() {
if (watcher != null) {
return;
}
watcher = new FileSystemWatcher(journal.Location);
watcher.NotifyFilter = NotifyFilters.FileName |
NotifyFilters.LastWrite |
NotifyFilters.Size;
watcher.Changed += Watcher_Changed;
watcher.Created += Watcher_Created;
watcher.Filter = "*.log";
watcher.EnableRaisingEvents = true;
}
public void Close() {
if (watcher != null) {
watcher.EnableRaisingEvents = false;
}
watcher = null;
streams.Clear();
}
private void Watcher_Created(object sender, FileSystemEventArgs e) {
if (!streams.ContainsKey(e.FullPath) && JournalFile.VerifyFile(e.FullPath)) {
streams[e.FullPath] = new StreamReader(e.FullPath);
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e) {
if (!streams.ContainsKey(e.FullPath) && JournalFile.VerifyFile(e.FullPath)) {
var filestream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
streams[e.FullPath] = new StreamReader(filestream);
}
var stream = streams[e.FullPath];
if (stream == null) {
return;
}
string line;
while ((line = stream.ReadLine()) != null) {
try {
Entry entry = Entry.Parse(line);
NewJournalEntry?.Invoke(entry);
} catch (Exception) {
}
}
}
}
}