-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActionTrigger.cs
More file actions
77 lines (65 loc) · 2.35 KB
/
ActionTrigger.cs
File metadata and controls
77 lines (65 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#:property Nullable=disable
#:property PublishAot=false
using System.Net;
using System.Text;
using System.Text.Json;
JsonSerializerOptions _options = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
Conf _conf = Deserialize<Conf>(GetEnvValue("ActionTrigger_Conf".ToUpper()));
HttpClient _scClient = null;
if (!string.IsNullOrWhiteSpace(_conf.ScKey))
{
_scClient = new HttpClient();
}
string owner = GetEnvValue("GITHUB_ACTOR");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", owner);
client.DefaultRequestHeaders.Add("Authorization", $"token {_conf.Token}");
Console.WriteLine("Action触发器开始运行...");
foreach (Req req in _conf.Reqs)
{
string badInfo = null;
string event_type = string.IsNullOrWhiteSpace(req.EventType) ? $"{req.Name} api" : req.EventType;
try
{
var httpResponseMessage = await client.PostAsync($"https://api.github.com/repos/{owner}/{req.Repo}/dispatches", new StringContent($@"{{""event_type"":""{event_type}"",""client_payload"":{{""name"":""{req.Name}""}}}}", Encoding.UTF8, "application/json"));
if (httpResponseMessage.StatusCode != HttpStatusCode.NoContent)
{//请求失败
badInfo = $"请求失败. code: {httpResponseMessage.StatusCode}, msg: {await httpResponseMessage.Content.ReadAsStringAsync()}";
}
}
catch (Exception ex)
{
badInfo = $"ex: {ex.Message}";
}
await Notify($"{req.Repo}: {event_type}: {badInfo ?? "ok"}", badInfo != null);
}
Console.WriteLine("Action运行完毕");
async Task Notify(string msg, bool isFailed = false)
{
Console.WriteLine(msg);
if (_conf.ScType == "Always" || (isFailed && _conf.ScType == "Failed"))
{
await _scClient?.GetAsync($"https://sctapi.ftqq.com/{_conf.ScKey}.send?title=ActionTrigger-{(isFailed ? "bad" : "ok")}&desp={msg}");
}
}
T Deserialize<T>(string json) => JsonSerializer.Deserialize<T>(json, _options);
string GetEnvValue(string key) => Environment.GetEnvironmentVariable(key);
#region Conf
class Conf
{
public string Token { get; set; }
public Req[] Reqs { get; set; }
public string ScKey { get; set; }
public string ScType { get; set; }
}
class Req
{
public string Repo { get; set; }
public string EventType { get; set; }
public string Name { get; set; }
}
#endregion