using ddAlter.DB; using ddAlter.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace ddAlter.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] public class gogsController : ControllerBase { public readonly IHttpClientFactory _httpClientFactory; public gogsController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpPost] [Route("gogs-msg")] async public Task GogsMessage([FromBody] GogsCommits body) { if (body.commits == null || body.commits.Count < 1) { return Ok(new { commits = "", result = "body为空", }); } string title = string.Format("【{0}】{1}提交了代码", body.repository.name, body.commits[0].committer.name); string text = string.Format("### 【{0}】{1}提交了代码 \n ", body.repository.name, body.commits[0].committer.name); for (int i = 0; i < body.commits.Count; i++) { text += string.Format("- [{0}]({1}) \n > {2} \n ", body.commits[i].id, body.commits[i].url.Replace("localhost", "192.168.1.222"), body.commits[i].message); } // 发送报警 var msg = new { msgtype = "markdown", markdown = new { title = title, text = text, }, //at = new //{ // isAtAll = true //} }; var sendMessage = JsonConvert.SerializeObject(msg); //https://oapi.dingtalk.com/robot/send?access_token=86ec01540e08233500a22e6a0f8a631fb4671901c6cf4d4cb80c16d59db3e675 var request = new HttpRequestMessage(HttpMethod.Post, "/robot/send?access_token=86ec01540e08233500a22e6a0f8a631fb4671901c6cf4d4cb80c16d59db3e675") { Content = new StringContent(sendMessage, Encoding.UTF8, "application/json") }; var client = _httpClientFactory.CreateClient("client_dd"); client.Timeout = TimeSpan.FromSeconds(10); var response = await client.SendAsync(request); var result = response.Content.ReadAsStringAsync(); return Ok(new { commits = body.commits, result = result, }); } } }