using Application.Domain.Entities; using Application.Models; using Infrastructure.Data; using Infrastructure.Extensions; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Swashbuckle.AspNetCore.Annotations; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace FBeeService.Controllers { public class HomeController : Controller { private readonly IRepository _repo; private readonly IHttpClientFactory _httpClientFactory; private readonly DeviceService _deviceService; public HomeController(IHttpClientFactory httpClientFactory, DeviceService deviceService, IRepository repo) { this._repo = repo; this._httpClientFactory = httpClientFactory; this._deviceService = deviceService; } public IActionResult Index() { Task.Run(() => { this._deviceService.Notify(); }); return View(this._repo.ReadOnlyTable().ToList()); } #region smart plug [HttpGet] [Route("/smartplug/api")] [SwaggerOperation("API")] [ApiExplorerSettings(IgnoreApi = true)] public string Switch2Api() { return GetApiJson("/smartplug/"); } [SwaggerOperation("开")] [HttpGet] [Route("/smartplug/21on")] public ApiResponse SmartPlugOn([SwaggerParameter("设备Id")]string id) { try { this._deviceService.SmartPlugOn(id); } catch (Exception ex) { ex.PrintStack(); return ApiResponse.Error(ex.Message); } return ApiResponse.AsyncSuccess(); } [SwaggerOperation("关")] [HttpGet] [Route("/smartplug/22off")] public ApiResponse SmartPlugOff([SwaggerParameter("设备Id")]string id) { try { this._deviceService.SmartPlugOff(id); } catch (Exception ex) { ex.PrintStack(); return ApiResponse.Error(ex.Message); } return ApiResponse.AsyncSuccess(); } #endregion smart plug private string GetApiJson(string prefix) { var url = new UriBuilder { Host = Request.Host.Host, Port = Request.Host.Port ?? 80, Path = "/swagger/v1/swagger.json" }.ToString(); var hc = this._httpClientFactory.CreateClient(); var result = hc.GetStringAsync(url).Result; var json = JsonConvert.DeserializeObject(result) as JObject; var paths = json.Properties().FirstOrDefault(o => o.Name == "paths").Value as JObject; var names = paths.Properties().Select(o => o.Name).ToList(); foreach (var item in names) { if (!item.StartsWith(prefix)) { paths.Remove(item); } } var realResult = JsonConvert.SerializeObject(json); return realResult; } } }