diff --git a/FreeTubeSyncer/REST/Syncer.cs b/FreeTubeSyncer/REST/Syncer.cs index 89aedd4..cf1360f 100644 --- a/FreeTubeSyncer/REST/Syncer.cs +++ b/FreeTubeSyncer/REST/Syncer.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; @@ -19,6 +20,13 @@ public interface ISyncer void HandleDatabaseChange(string dbName, string entryObject); void Sync(); bool IsDirty(); + void Enable(); + void Disable(); + bool IsEnabled(); + + void UpdateBaseUrl(string baseUrl); + void SetEnabled(bool enabled); + Task PingApi(); } public class Syncer : ISyncer where T : class, IDataModel, new() @@ -32,23 +40,50 @@ public class Syncer : ISyncer where T : class, IDataModel, new() private bool _isDirty = false; private bool _syncing = false; + private bool _enabled = true; - public Syncer(DBSyncWatcher watcher, string dbPath, string dbName, string restEndpoint) + public Syncer(DBSyncWatcher watcher, string dbPath, string dbName, string restBaseUrl, string restEndpoint) { _watcher = watcher; _watcher.WatchFiles[dbName] = typeof(T); _watcher.OnDatabaseChange += HandleDatabaseChange; - _client = new RestClient(new RestClientOptions("http://192.168.1.30:5050")); + _client = new RestClient(new RestClientOptions(restBaseUrl)); _dbPath = dbPath; _dbName = dbName; _restEndpoint = restEndpoint; - FetchDatabase().Wait(); } public bool IsDirty() => _isDirty; + public bool IsEnabled() => _enabled; + public void Enable() => _enabled = true; + public void Disable() => _enabled = false; + public void SetEnabled(bool enabled) => _enabled = enabled; + + public void UpdateBaseUrl(string baseUrl) + { + _client.Dispose(); + _client = new RestClient(new RestClientOptions(baseUrl)); + } + + public async Task PingApi() + { + try + { + var res = await _client.ExecuteHeadAsync(new RestRequest("/ping")); + if (res.StatusCode == HttpStatusCode.NotFound) + return true; + } + catch (Exception ex) + { + return false; + } + + return false; + } public async Task ReadDatabase() { + if (!_enabled) return; var lines = File.ReadAllLines(_dbPath); foreach (var entry in lines) { @@ -76,6 +111,7 @@ public class Syncer : ISyncer where T : class, IDataModel, new() public async Task FetchDatabase() { + if (!_enabled) return; var entries = await _client.GetAsync>(_restEndpoint); if (entries == null) return; foreach (var entry in entries) @@ -98,6 +134,7 @@ public class Syncer : ISyncer where T : class, IDataModel, new() public async void HandleDatabaseChange(string dbName, string entryObject) { + if (!_enabled) return; if (dbName != _dbName) return; @@ -133,6 +170,7 @@ public class Syncer : ISyncer where T : class, IDataModel, new() public void Sync() { + if (!_enabled) return; if (!_isDirty) return; _syncing = true;