| 1 | using Microsoft.Extensions.Configuration; |
| 2 | using Tomlyn; |
| 3 | |
| 4 | namespace TelegramNotifier; |
| 5 | |
| 6 | public class ConfigurationAccessor |
| 7 | { |
| 8 | public TelegramSettings Settings { get; set; } |
| 9 | public ApplicationSettings ApplicationSettings { get; set; } |
| 10 | |
| 11 | public ConfigurationAccessor() |
| 12 | { |
| 13 | var currDir = Directory.GetCurrentDirectory(); |
| 14 | var pathToml = Path.Combine(currDir, "appsettings.toml"); |
| 15 | var pathJson = Path.Combine(currDir, "appsettings.json"); |
| 16 | |
| 17 | if (File.Exists(pathToml)) |
| 18 | { |
| 19 | var tomlText = File.ReadAllText(pathToml); |
| 20 | var model = TomlSerializer.Deserialize<AppConfigToml>(tomlText) ?? new AppConfigToml(); |
| 21 | Settings = model.TelegramSettings ?? new TelegramSettings(); |
| 22 | ApplicationSettings = model.ApplicationSettings ?? new ApplicationSettings(); |
| 23 | } |
| 24 | else if (File.Exists(pathJson)) |
| 25 | { |
| 26 | var configuration = new ConfigurationBuilder() |
| 27 | .AddJsonFile(pathJson, optional: true) |
| 28 | .Build(); |
| 29 | Settings = configuration.GetSection(nameof(TelegramSettings)).Get<TelegramSettings>() ?? new TelegramSettings(); |
| 30 | ApplicationSettings = configuration.GetSection(nameof(ApplicationSettings)).Get<ApplicationSettings>() ?? new ApplicationSettings(); |
| 31 | } |
| 32 | else |
| 33 | { |
| 34 | Settings = new TelegramSettings(); |
| 35 | ApplicationSettings = new ApplicationSettings(); |
| 36 | } |
| 37 | |
| 38 | ApplyDefaults(); |
| 39 | } |
| 40 | |
| 41 | void ApplyDefaults() |
| 42 | { |
| 43 | if (string.IsNullOrWhiteSpace(Settings.SessionPathName) || Settings.SessionPathName.Contains('<')) |
| 44 | Settings.SessionPathName = "WTelegram.session"; |
| 45 | if (string.IsNullOrWhiteSpace(Settings.LogFileName) || Settings.LogFileName.Contains('<')) |
| 46 | Settings.LogFileName = "wtelegram.log"; |
| 47 | if (string.IsNullOrWhiteSpace(ApplicationSettings.SavedMediaLocationPath) || ApplicationSettings.SavedMediaLocationPath.Contains('<')) |
| 48 | ApplicationSettings.SavedMediaLocationPath = "SavedMedia"; |
| 49 | } |
| 50 | } |
| 51 | |