123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- using Microsoft.AspNetCore.Http;
- using System.Text.RegularExpressions;
- using SlackAPI;
- using System.Text.Json;
- using System;
- using sera_slackbot.Library;
- using System.Web;
- namespace sera_slackbot.Commands
- {
- public class CurlBotCommand : IBotCommand
- {
- private JsonFileSaver saver;
- private RestApiRequester requester;
- private string channelId;
- private string userId;
- private string text;
- private string message;
- public CurlBotCommand(JsonFileReader reader, JsonFileSaver saver)
- {
- this.saver = saver;
- requester = new RestApiRequester();
- }
- public void ExtractValidData(JsonElement slackEvent)
- {
- this.text = slackEvent.GetProperty("text").ToString();
- this.channelId = slackEvent.GetProperty("channel").ToString();
- this.userId = slackEvent.GetProperty("user").ToString();
- }
- public bool WillTrigger(JsonElement slackEvent)
- {
- var text = slackEvent.GetProperty("text").ToString();
- return text.Contains("curl", StringComparison.InvariantCultureIgnoreCase);
- }
- public dynamic Run(SlackClient client)
- {
- var curlUrl = this.GetValidUrl(text);
- var awaiter = requester.GetJson(curlUrl).GetAwaiter();
- awaiter.OnCompleted(() =>
- {
- try
- {
- string jsonResult = JsonSerializer.Serialize(awaiter.GetResult(), new JsonSerializerOptions { WriteIndented = true });
- jsonResult = jsonResult.Substring(0, Math.Min(jsonResult.Length, 255));
- client.PostMessage(response => { }, channelId, $"I made the request and I got ```{jsonResult}```");
- }
- catch (Exception)
- {
- string resultString = awaiter.GetResult();
- resultString = HttpUtility.HtmlEncode(resultString);
- resultString = resultString.Substring(0, Math.Min(resultString.Length, 255));
- client.PostMessage(response => { }, channelId, $"I made the request and I got ```{resultString}```");
- }
- });
- client.PostMessage(response => { }, channelId, $"Ok, I'll see if I can get you '{curlUrl}'. Just a moment.");
- return new
- {
- code = StatusCodes.Status200OK,
- body = ""
- };
- }
- private string GetValidUrl(string text)
- {
- var urlMatch = new Regex("\"(.*?)\"").Match(text);
- var curlUrl = string.Empty;
- if (urlMatch.Success)
- {
- curlUrl = urlMatch.Groups[1].Value;
- }
- if (curlUrl.StartsWith("<"))
- {
- var slackFormattedMatch = new Regex("<(.*?)\\|.*?>").Match(curlUrl);
- if (slackFormattedMatch.Success)
- {
- curlUrl = slackFormattedMatch.Groups[1].Value;
- }
- else
- {
- slackFormattedMatch = new Regex("<(.*?)>").Match(curlUrl);
- if (slackFormattedMatch.Success)
- {
- curlUrl = slackFormattedMatch.Groups[1].Value;
- }
- }
- }
- else if (!curlUrl.StartsWith("http"))
- {
- curlUrl = "http://" + curlUrl;
- }
- return curlUrl;
- }
- }
- }
|