refactor: 枚举移入Models目录,命名空间更新为Rainbow.Entity.Models
大石头 authored at 2026-07-02 12:54:58
2.05 KiB
RainbowBridge
using Microsoft.AspNetCore.Mvc;
using Rainbow.Entity;
using Rainbow.Services;

namespace Rainbow.Web.Controllers;

[ApiController]
[Route("api/dhcp-bindings")]
public class DhcpBindingController : ControllerBase
{
    private readonly DnsmasqManager _dnsmasqManager;

    /// <summary>构造 DHCP 静态绑定控制器</summary>
    /// <param name="dnsmasqManager">Dnsmasq 配置管理器</param>
    public DhcpBindingController(DnsmasqManager dnsmasqManager) => _dnsmasqManager = dnsmasqManager;

    [HttpGet] public ActionResult<IList<DhcpBinding>> GetBindings() => Ok(DhcpBinding.FindAllWithCache());

    [HttpPost]
    public ActionResult Add([FromBody] DhcpBinding binding)
    {
        binding.Insert();
        TryApplyDnsmasq();
        return Ok(new { success = true });
    }

    [HttpPost("bulk")]
    public ActionResult BulkImport([FromBody] List<DhcpBinding> bindings)
    {
        if (bindings == null || bindings.Count == 0)
            return BadRequest(new { error = ApiMessages.BulkImportEmpty(HttpContext) });

        var added = 0;
        var skipped = 0;
        foreach (var b in bindings)
        {
            // 跳过已存在的 MAC
            var existing = DhcpBinding.FindByMac(b.Mac);
            if (existing != null) { skipped++; continue; }
            b.Enable = true;
            b.Insert();
            added++;
        }
        TryApplyDnsmasq();
        return Ok(new { success = true, added, skipped, total = bindings.Count, message = ApiMessages.ImportSuccess(HttpContext, added, skipped) });
    }

    [HttpDelete("{id}")]
    public ActionResult Delete(Int32 id)
    {
        var e = DhcpBinding.FindById(id);
        if (e == null) return NotFound();
        e.Delete();
        TryApplyDnsmasq();
        return Ok(new { success = true });
    }

    /// <summary>尝试应用 dnsmasq 配置(最佳努力)</summary>
    private void TryApplyDnsmasq()
    {
        _ = Task.Run(async () =>
        {
            try
            {
                await _dnsmasqManager.ApplyAsync();
            }
            catch { }
        });
    }
}