|
| 1 | +using Microsoft.Extensions.Hosting; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Microsoft.Extensions.Options; |
| 4 | +using SlackLineBridge.Models; |
| 5 | +using SlackLineBridge.Models.Configurations; |
| 6 | +using System; |
| 7 | +using System.Collections.Concurrent; |
| 8 | +using System.Collections.Generic; |
| 9 | +using System.Linq; |
| 10 | +using System.Net.Http; |
| 11 | +using System.Security.Cryptography; |
| 12 | +using System.Text; |
| 13 | +using System.Text.Json; |
| 14 | +using System.Threading; |
| 15 | +using System.Threading.Tasks; |
| 16 | + |
| 17 | +namespace SlackLineBridge.Services |
| 18 | +{ |
| 19 | + public class LineMessageProcessingService : BackgroundService |
| 20 | + { |
| 21 | + private readonly IOptionsMonitor<SlackChannels> _slackChannels; |
| 22 | + private readonly IOptionsMonitor<LineChannels> _lineChannels; |
| 23 | + private readonly IOptionsMonitor<SlackLineBridges> _bridges; |
| 24 | + private readonly IHttpClientFactory _clientFactory; |
| 25 | + private readonly ILogger<LineMessageProcessingService> _logger; |
| 26 | + private readonly ConcurrentQueue<(string signature, string body)> _queue; |
| 27 | + private readonly string _lineChannelSecret; |
| 28 | + |
| 29 | + public LineMessageProcessingService( |
| 30 | + IOptionsMonitor<SlackChannels> slackChannels, |
| 31 | + IOptionsMonitor<LineChannels> lineChannels, |
| 32 | + IOptionsMonitor<SlackLineBridges> bridges, |
| 33 | + IHttpClientFactory clientFactory, |
| 34 | + ConcurrentQueue<(string signature, string body)> lineRequestQueue, |
| 35 | + string lineChannelSecret, |
| 36 | + ILogger<LineMessageProcessingService> logger) |
| 37 | + { |
| 38 | + _slackChannels = slackChannels; |
| 39 | + _lineChannels = lineChannels; |
| 40 | + _bridges = bridges; |
| 41 | + _clientFactory = clientFactory; |
| 42 | + _logger = logger; |
| 43 | + _queue = lineRequestQueue; |
| 44 | + _lineChannelSecret = lineChannelSecret; |
| 45 | + } |
| 46 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 47 | + { |
| 48 | + _logger.LogDebug($"LineMessageProcessingService is starting."); |
| 49 | + |
| 50 | + stoppingToken.Register(() => _logger.LogDebug($" LineMessageProcessing background task is stopping.")); |
| 51 | + |
| 52 | + while (!stoppingToken.IsCancellationRequested) |
| 53 | + { |
| 54 | + if (_queue.TryDequeue(out var request)) |
| 55 | + { |
| 56 | + _logger.LogInformation("Processing request from line: " + request.body); |
| 57 | + |
| 58 | + var signature = GetHMAC(request.body, _lineChannelSecret); |
| 59 | + _logger.LogDebug($"LINE signature check (expected:{request.signature}, calculated:{signature})"); |
| 60 | + if (request.signature != signature) |
| 61 | + { |
| 62 | + _logger.LogInformation("LINE signature missmatch."); |
| 63 | + continue; |
| 64 | + } |
| 65 | + |
| 66 | + var data = JsonSerializer.Deserialize<JsonElement>(request.body); |
| 67 | + |
| 68 | + foreach (var e in data.GetProperty("events").EnumerateArray()) |
| 69 | + { |
| 70 | + switch (e.GetProperty("type").GetString()) |
| 71 | + { |
| 72 | + case "message": |
| 73 | + { |
| 74 | + LineChannel lineChannel = GetLineChannel(e); |
| 75 | + if (lineChannel == null) |
| 76 | + { |
| 77 | + _logger.LogInformation($"message from unknown line channel: {GetLineEventSourceId(e)}"); |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + var bridges = GetBridges(lineChannel); |
| 82 | + if (!bridges.Any()) |
| 83 | + { |
| 84 | + continue; |
| 85 | + } |
| 86 | + string userName = null; |
| 87 | + if (e.GetProperty("source").TryGetProperty("userId", out var userId)) |
| 88 | + { |
| 89 | + var client = _clientFactory.CreateClient("Line"); |
| 90 | + |
| 91 | + try |
| 92 | + { |
| 93 | + var result = await client.GetAsync($"profile/{userId}"); |
| 94 | + if (result.IsSuccessStatusCode) |
| 95 | + { |
| 96 | + var profile = await JsonSerializer.DeserializeAsync<JsonElement>(await result.Content.ReadAsStreamAsync()); |
| 97 | + userName = profile.GetProperty("displayName").GetString(); |
| 98 | + } |
| 99 | + } |
| 100 | + catch (Exception ex) |
| 101 | + { |
| 102 | + _logger.LogError(ex, "get profile data failed"); |
| 103 | + } |
| 104 | + |
| 105 | + if (userName == null) |
| 106 | + { |
| 107 | + userName = $"Unknown ({userId})"; |
| 108 | + } |
| 109 | + } |
| 110 | + else |
| 111 | + { |
| 112 | + userName = "Unknown"; |
| 113 | + } |
| 114 | + |
| 115 | + var message = e.GetProperty("message"); |
| 116 | + var type = message.GetProperty("type").GetString(); |
| 117 | + var text = type switch |
| 118 | + { |
| 119 | + "text" => message.GetProperty("text").GetString(), |
| 120 | + _ => $"<{type}>", |
| 121 | + }; |
| 122 | + |
| 123 | + foreach (var bridge in bridges) |
| 124 | + { |
| 125 | + var slackChannel = _slackChannels.CurrentValue.Channels.FirstOrDefault(x => x.Name == bridge.Slack); |
| 126 | + if (slackChannel == null) |
| 127 | + { |
| 128 | + _logger.LogError($"bridge configured but cannot find target slackChannel: {bridge.Slack}"); |
| 129 | + continue; |
| 130 | + } |
| 131 | + |
| 132 | + await SendToSlack(slackChannel.WebhookUrl, slackChannel.ChannelId, userName, text); |
| 133 | + } |
| 134 | + } |
| 135 | + break; |
| 136 | + default: |
| 137 | + { |
| 138 | + var sourceId = GetLineEventSourceId(e); |
| 139 | + if (sourceId == null) |
| 140 | + { |
| 141 | + var type = e.GetProperty("type").GetString(); |
| 142 | + _logger.LogInformation($"{type} event from sourceId: {e.GetProperty("source").GetProperty("type").GetString()}"); |
| 143 | + continue; |
| 144 | + } |
| 145 | + } |
| 146 | + break; |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + await Task.Delay(1000, stoppingToken); |
| 152 | + } |
| 153 | + |
| 154 | + _logger.LogDebug($"LineMessageProcessing background task is stopping."); |
| 155 | + } |
| 156 | + |
| 157 | + private async Task SendToSlack(string webhookUrl, string channelId, string userName, string text) |
| 158 | + { |
| 159 | + var client = _clientFactory.CreateClient(); |
| 160 | + |
| 161 | + var message = new |
| 162 | + { |
| 163 | + channel = channelId, |
| 164 | + username = userName, |
| 165 | + icon_emoji = ":line:", |
| 166 | + text |
| 167 | + }; |
| 168 | + |
| 169 | + await client.PostAsync(webhookUrl, new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8, "application/json")); |
| 170 | + } |
| 171 | + |
| 172 | + private LineChannel GetLineChannel(JsonElement e) |
| 173 | + { |
| 174 | + var sourceId = GetLineEventSourceId(e); |
| 175 | + return _lineChannels.CurrentValue.Channels.FirstOrDefault(x => x.Id == sourceId); |
| 176 | + } |
| 177 | + |
| 178 | + private IEnumerable<Models.Configurations.SlackLineBridge> GetBridges(LineChannel channel) |
| 179 | + { |
| 180 | + return _bridges.CurrentValue.Bridges.Where(x => x.Line == channel.Name); |
| 181 | + } |
| 182 | + |
| 183 | + private string GetLineEventSourceId(JsonElement e) |
| 184 | + { |
| 185 | + var source = e.GetProperty("source"); |
| 186 | + var type = source.GetProperty("type").GetString(); |
| 187 | + switch (type) |
| 188 | + { |
| 189 | + case "user": |
| 190 | + return source.GetProperty("userId").GetString(); |
| 191 | + case "group": |
| 192 | + return source.GetProperty("groupId").GetString(); |
| 193 | + case "room": |
| 194 | + return source.GetProperty("roomId").GetString(); |
| 195 | + default: |
| 196 | + _logger.LogError($"unknown source type: {type}"); |
| 197 | + return null; |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + private static string GetHMAC(string text, string key) |
| 202 | + { |
| 203 | + var encoding = new UTF8Encoding(); |
| 204 | + |
| 205 | + var textBytes = encoding.GetBytes(text); |
| 206 | + var keyBytes = encoding.GetBytes(key); |
| 207 | + |
| 208 | + byte[] hashBytes; |
| 209 | + |
| 210 | + using (var hash = new HMACSHA256(keyBytes)) |
| 211 | + { |
| 212 | + hashBytes = hash.ComputeHash(textBytes); |
| 213 | + } |
| 214 | + |
| 215 | + return Convert.ToBase64String(hashBytes); |
| 216 | + } |
| 217 | + } |
| 218 | +} |
0 commit comments