Skip to content

Commit 6e593a1

Browse files
Merge pull request #1033 from discord-csharp/1032
Start V3, refactor code paste service
2 parents 5b4f02e + 3255837 commit 6e593a1

File tree

10 files changed

+82
-130
lines changed

10 files changed

+82
-130
lines changed

.editorconfig

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ dotnet_naming_style.interface_style.capitalization = pascal_case
7676
dotnet_naming_style.interface_style.required_prefix = I
7777

7878
# Async methods are suffixed with Async
79-
dotnet_naming_rule.async_methods_should_be_suffixed.severity = warning
79+
dotnet_naming_rule.async_methods_should_be_suffixed.severity = none
8080
dotnet_naming_rule.async_methods_should_be_suffixed.symbols = async_methods
8181
dotnet_naming_rule.async_methods_should_be_suffixed.style = async_method_style
8282

src/Modix.Bot/Modules/IlModule.cs

+7-5
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
using Discord.Commands;
88
using Microsoft.Extensions.Options;
99
using Modix.Data.Models.Core;
10+
using Modix.Services;
1011
using Modix.Services.AutoRemoveMessage;
11-
using Modix.Services.CodePaste;
1212
using Modix.Services.CommandHelp;
1313
using Modix.Services.Utilities;
1414
using Serilog;
@@ -22,12 +22,12 @@ public class IlModule : ModuleBase
2222
{
2323
private const string DefaultIlRemoteUrl = "http://csdiscord-repl-service:31337/Il";
2424
private readonly string _ilUrl;
25-
private readonly CodePasteService _pasteService;
25+
private readonly PasteService _pasteService;
2626
private readonly IAutoRemoveMessageService _autoRemoveMessageService;
2727
private readonly IHttpClientFactory _httpClientFactory;
2828

2929
public IlModule(
30-
CodePasteService pasteService,
30+
PasteService pasteService,
3131
IAutoRemoveMessageService autoRemoveMessageService,
3232
IHttpClientFactory httpClientFactory,
3333
IOptions<ModixConfig> modixConfig)
@@ -118,10 +118,12 @@ private async Task<EmbedBuilder> BuildEmbedAsync(IGuildUser guildUser, string co
118118

119119
embed.AddField(a => a.WithName("Code").WithValue(Format.Code(code, "cs")));
120120

121+
const int MAX_LENGTH = 990;
122+
121123
embed.AddField(a => a.WithName($"Result:")
122-
.WithValue(Format.Code(result.TruncateTo(990), "asm")));
124+
.WithValue(Format.Code(result.TruncateTo(MAX_LENGTH), "asm")));
123125

124-
await embed.UploadToServiceIfBiggerThan(result, 990, _pasteService);
126+
await embed.UploadToServiceIfBiggerThan(result, MAX_LENGTH, _pasteService);
125127

126128
return embed;
127129
}

src/Modix.Bot/Modules/ReplModule.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
using Discord.Commands;
99
using Microsoft.Extensions.Options;
1010
using Modix.Data.Models.Core;
11+
using Modix.Services;
1112
using Modix.Services.AutoRemoveMessage;
12-
using Modix.Services.CodePaste;
1313
using Modix.Services.CommandHelp;
1414
using Modix.Services.Utilities;
1515
using Newtonsoft.Json;
@@ -36,12 +36,12 @@ public class ReplModule : ModuleBase
3636
private const int MaxFormattedFieldSize = 1000;
3737
private const string DefaultReplRemoteUrl = "http://csdiscord-repl-service:31337/Eval";
3838
private readonly string _replUrl;
39-
private readonly CodePasteService _pasteService;
39+
private readonly PasteService _pasteService;
4040
private readonly IAutoRemoveMessageService _autoRemoveMessageService;
4141
private readonly IHttpClientFactory _httpClientFactory;
4242

4343
public ReplModule(
44-
CodePasteService pasteService,
44+
PasteService pasteService,
4545
IAutoRemoveMessageService autoRemoveMessageService,
4646
IHttpClientFactory httpClientFactory,
4747
IOptions<ModixConfig> modixConfig)

src/Modix.Services/CodePaste/CodePasteService.cs

-79
This file was deleted.

src/Modix.Services/CodePaste/CodePasteSetup.cs

-11
This file was deleted.

src/Modix.Services/PasteService.cs

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#nullable enable
2+
using System.Net.Http;
3+
using System.Threading.Tasks;
4+
using Microsoft.Extensions.Logging;
5+
using Modix.Services.Utilities;
6+
using Newtonsoft.Json.Linq;
7+
8+
namespace Modix.Services;
9+
10+
public class PasteService(IHttpClientFactory httpClientFactory, ILogger<PasteService> logger)
11+
{
12+
private const string PASTE_URL = "https://paste.mod.gg/";
13+
14+
public async Task<string?> UploadPaste(string textToUpload)
15+
{
16+
var content = FormatUtilities.BuildContent(textToUpload);
17+
18+
var client = httpClientFactory.CreateClient(HttpClientNames.TimeoutFiveSeconds);
19+
20+
var response = await client.PostAsync($"{PASTE_URL}documents", content);
21+
22+
if (!response.IsSuccessStatusCode)
23+
{
24+
var body = await response.Content.ReadAsStringAsync();
25+
26+
logger.LogError("Failed uploading paste to {Url}, failed with response {ResponseCode}, with body: {Body}",
27+
PASTE_URL,
28+
response.StatusCode,
29+
body);
30+
31+
return null;
32+
}
33+
34+
var urlResponse = await response.Content.ReadAsStringAsync();
35+
var pasteKey = JObject.Parse(urlResponse)["key"]?.Value<string>();
36+
37+
return $"{PASTE_URL}{pasteKey}";
38+
}
39+
}

src/Modix.Services/Utilities/DiscordWebhookSink.cs

+11-9
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using System.Threading.Tasks;
55
using Discord;
66
using Discord.Webhook;
7-
using Modix.Services.CodePaste;
87
using Newtonsoft.Json;
98
using Serilog;
109
using Serilog.Configuration;
@@ -15,7 +14,7 @@ namespace Modix.Services.Utilities;
1514

1615
public sealed class DiscordWebhookSink : ILogEventSink, IAsyncDisposable
1716
{
18-
private readonly Lazy<CodePasteService> _codePasteService;
17+
private readonly Lazy<PasteService> _codePasteService;
1918
private readonly DiscordWebhookClient _discordWebhookClient;
2019
private readonly IFormatProvider _formatProvider;
2120
private readonly JsonSerializerSettings _jsonSerializerSettings;
@@ -27,7 +26,7 @@ public DiscordWebhookSink(
2726
ulong webhookId,
2827
string webhookToken,
2928
IFormatProvider formatProvider,
30-
Lazy<CodePasteService> codePasteService)
29+
Lazy<PasteService> codePasteService)
3130
{
3231
_codePasteService = codePasteService;
3332
_discordWebhookClient = new DiscordWebhookClient(webhookId, webhookToken);
@@ -75,12 +74,15 @@ public async Task ProcessLogEventItemsAsync()
7574

7675
var eventAsJson = JsonConvert.SerializeObject(logEvent, _jsonSerializerSettings);
7776

78-
var url = await _codePasteService.Value.UploadCodeAsync(eventAsJson);
77+
var url = await _codePasteService.Value.UploadPaste(eventAsJson);
7978

80-
message.AddField(new EmbedFieldBuilder()
81-
.WithIsInline(false)
82-
.WithName("Full Log Event")
83-
.WithValue($"[view on paste.mod.gg]({url})"));
79+
if (!string.IsNullOrWhiteSpace(url))
80+
{
81+
message.AddField(new EmbedFieldBuilder()
82+
.WithIsInline(false)
83+
.WithName("Full Log Event")
84+
.WithValue($"[view on paste.mod.gg]({url})"));
85+
}
8486
}
8587
catch (Exception ex)
8688
{
@@ -121,7 +123,7 @@ public async ValueTask DisposeAsync()
121123

122124
public static class DiscordWebhookSinkExtensions
123125
{
124-
public static LoggerConfiguration DiscordWebhookSink(this LoggerSinkConfiguration config, ulong id, string token, LogEventLevel minLevel, Lazy<CodePasteService> codePasteService)
126+
public static LoggerConfiguration DiscordWebhookSink(this LoggerSinkConfiguration config, ulong id, string token, LogEventLevel minLevel, Lazy<PasteService> codePasteService)
125127
=> config.Sink(new DiscordWebhookSink(id, token, null, codePasteService), minLevel);
126128
}
127129

src/Modix.Services/Utilities/FormatUtilities.cs

+17-18
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,10 @@
88
using System.Text;
99
using System.Text.RegularExpressions;
1010
using System.Threading.Tasks;
11-
1211
using Discord;
13-
1412
using Humanizer;
1513
using Humanizer.Localisation;
16-
1714
using Modix.Data.Models.Moderation;
18-
using Modix.Services.CodePaste;
1915

2016
namespace Modix.Services.Utilities
2117
{
@@ -38,18 +34,16 @@ public static string StripFormatting(string code) =>
3834
//strip out the ` characters and code block markers
3935
_buildContentRegex.Replace(code.Trim(), string.Empty);
4036

41-
public static async Task UploadToServiceIfBiggerThan(this EmbedBuilder embed, string content, uint size, CodePasteService service)
37+
public static async Task UploadToServiceIfBiggerThan(this EmbedBuilder embed, string content, uint size,
38+
PasteService service)
4239
{
4340
if (content.Length > size)
4441
{
45-
try
46-
{
47-
var resultLink = await service.UploadCodeAsync(content);
48-
embed.AddField(a => a.WithName("More...").WithValue($"[View on Hastebin]({resultLink})"));
49-
}
50-
catch (WebException we)
42+
var resultLink = await service.UploadPaste(content);
43+
44+
if (!string.IsNullOrWhiteSpace(resultLink))
5145
{
52-
embed.AddField(a => a.WithName("More...").WithValue(we.Message));
46+
embed.AddField(a => a.WithName("More...").WithValue($"[View on paste.mod.gg]({resultLink})"));
5347
}
5448
}
5549
}
@@ -87,7 +81,8 @@ public static IReadOnlyCollection<string> CollapsePlurals(IReadOnlyCollection<st
8781
Value: x
8882
));
8983

90-
var groupedBySingulars = withSingulars.GroupBy(x => x.Singular, x => x.Value, new SequenceEqualityComparer<string>());
84+
var groupedBySingulars =
85+
withSingulars.GroupBy(x => x.Singular, x => x.Value, new SequenceEqualityComparer<string>());
9186

9287
var withDistinctParts = new HashSet<string>[groupedBySingulars.Count()][];
9388

@@ -129,7 +124,8 @@ public static IReadOnlyCollection<string> CollapsePlurals(IReadOnlyCollection<st
129124
? word.First()
130125
: word.Last();
131126

132-
parenthesized[aliasIndex][wordIndex] = $"{longestForm[..indexOfDifference]}({longestForm[indexOfDifference..]})";
127+
parenthesized[aliasIndex][wordIndex] =
128+
$"{longestForm[..indexOfDifference]}({longestForm[indexOfDifference..]})";
133129
}
134130
else
135131
{
@@ -202,6 +198,7 @@ public static string FormatCodeForEmbed(string language, string sourceCode, int
202198
AddRemainingLineComment();
203199
break;
204200
}
201+
205202
braceOnlyLinesEliminated++;
206203
}
207204
else if (!TryAddLine(line))
@@ -244,11 +241,13 @@ public static string FormatCodeForEmbed(string language, string sourceCode, int
244241
bool TryAddLine(string line)
245242
{
246243
var remainingCount = GetRemainingLineCount();
247-
var possibleRemainingLineCommentLength = remainingCount > 1 // 1, because the current line is included in the count
248-
? GetRemainingLineCountComment(remainingCount).Length
249-
: 0;
244+
var possibleRemainingLineCommentLength =
245+
remainingCount > 1 // 1, because the current line is included in the count
246+
? GetRemainingLineCountComment(remainingCount).Length
247+
: 0;
250248

251-
if (line.Length + currentLength + possibleRemainingLineCommentLength + 1 > maxLength) // +1 because of the newline that will be added later
249+
if (line.Length + currentLength + possibleRemainingLineCommentLength + 1 >
250+
maxLength) // +1 because of the newline that will be added later
252251
return false;
253252

254253
processedLines.Add(line);

src/Modix/Extensions/ServiceCollectionExtensions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
using Modix.Data.Repositories;
2323
using Modix.Services;
2424
using Modix.Services.AutoRemoveMessage;
25-
using Modix.Services.CodePaste;
2625
using Modix.Services.CommandHelp;
2726
using Modix.Services.Core;
2827
using Modix.Services.Csharp;
@@ -157,7 +156,6 @@ public static IServiceCollection AddModix(
157156
.AddModixCore()
158157
.AddModixModeration()
159158
.AddModixPromotions()
160-
.AddCodePaste()
161159
.AddCommandHelp()
162160
.AddGuildStats()
163161
.AddModixTags()
@@ -166,6 +164,8 @@ public static IServiceCollection AddModix(
166164
.AddEmojiStats()
167165
.AddImages();
168166

167+
services.AddScoped<PasteService>();
168+
169169
services.AddScoped<IQuoteService, QuoteService>();
170170
services.AddSingleton<IBehavior, MessageLinkBehavior>();
171171
services.AddMemoryCache();

src/Modix/Program.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
using Modix.Configuration;
1818
using Modix.Data;
1919
using Modix.Data.Models.Core;
20-
using Modix.Services.CodePaste;
20+
using Modix.Services;
2121
using Modix.Services.Utilities;
2222
using Modix.Web;
2323
using Newtonsoft.Json.Converters;
@@ -106,7 +106,7 @@ private static void ConfigureServices(WebApplicationBuilder builder, IConfigurat
106106
if (webhookId.HasValue && webhookToken != null)
107107
{
108108
lc
109-
.WriteTo.DiscordWebhookSink(webhookId.Value, webhookToken, LogEventLevel.Error, new Lazy<CodePasteService>(sp.GetRequiredService<CodePasteService>));
109+
.WriteTo.DiscordWebhookSink(webhookId.Value, webhookToken, LogEventLevel.Error, new Lazy<PasteService>(sp.GetRequiredService<PasteService>));
110110
}
111111
});
112112

0 commit comments

Comments
 (0)