1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using Utils;
- namespace DhcpServer
- {
- internal static class DhcpEntryManager
- {
- private static readonly string EntriesDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DhcpEntries");
- private static readonly HashSet<char> InvalidFileNameChars = new HashSet<char>(Path.GetInvalidFileNameChars());
- private static string FilterUserClass(string input)
- {
- if (input == null) return null;
- var sb = new StringBuilder(input);
- sb.FilterChars(InvalidFileNameChars);
- sb.Insert(0, '-');
- return sb.ToString();
- }
-
- private static string GetEntryPath(string mac, string userClass = null)
- {
- return Path.Combine(EntriesDir, "MAC-" + mac + FilterUserClass(userClass) + ".json");
- }
- private static string GetDefaultEntryPath(string userClass = null)
- {
- return Path.Combine(EntriesDir, "Default" + FilterUserClass(userClass) + ".json");
- }
- public static bool CreateDefaultEntryIfNoExist()
- {
- var path = GetDefaultEntryPath();
- if (File.Exists(path)) return false;
- if (false == Directory.Exists(EntriesDir)) Directory.CreateDirectory(EntriesDir);
- File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
- return true;
- }
- public static DhcpEntry GetDefaultEntry(string userClass = null)
- {
- var path = GetDefaultEntryPath(userClass);
- if (File.Exists(path)) return JsonConvert.DeserializeObject<DhcpEntry>(File.ReadAllText(path));
- var createNew = new DhcpEntry();
- File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
- return createNew;
- }
- public static DhcpEntry GetClientEntry(string mac, string userClass = null)
- {
- var path = GetEntryPath(mac, userClass);
- if (File.Exists(path)) return JsonConvert.DeserializeObject<DhcpEntry>(File.ReadAllText(path));
- var createNew = new DhcpEntry();
- File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
- return createNew;
- }
- }
- }
|