Compare commits

...

20 Commits

Author SHA1 Message Date
Oleksii Holub e2780d6666 Update version 2022-03-06 19:41:11 +02:00
Oleksii Holub b996215e36 Add messages about war in Ukraine 2022-03-06 19:24:22 +02:00
Oleksii Holub 08d9af534b Add terms of use 2022-03-05 09:30:41 -08:00
Oleksii Holub bef110a193 Add fuck russia banner to readme 2022-02-23 18:25:23 +02:00
Oleksii Holub 12555e576f Update NuGet packages 2022-02-21 22:47:40 +02:00
Oleksii Holub afb4bc67ae Auto-detect dark mode preference in GUI 2022-02-20 22:29:23 +02:00
Oleksii Holub f80a5fe644 Fix multiline quote rendering in HTML
Fixes #756
2022-02-19 00:49:56 +02:00
Oleksii Holub b7dca87fb9 Add reaction filter
Closes #715
2022-02-19 00:28:38 +02:00
Oleksii Holub 8ecc2940b0 HTML-escape links inside HTML export instead of URL-escaping 2022-02-19 00:26:54 +02:00
Oleksii Holub 407c2bd2ae Don't crash on invalid mentions
Fixes #816
2022-02-19 00:26:53 +02:00
Oleksii Holub 5b563d4f00 Cleanup some code 2022-02-19 00:26:53 +02:00
Tomlacko ecb615ecf1 Fix for extremely long file extensions (#812) 2022-02-17 19:58:47 -08:00
Oleksii Holub 7c212ef893 Update NuGet packages 2022-02-16 14:34:01 +02:00
Oleksii Holub 36b4a45f3a Update Gress 2022-02-16 14:30:26 +02:00
Oleksii Holub 51cc132e5d Display 24-hour time pickers for appropriate cultures in GUI
Related to #808
2022-02-10 17:23:39 +02:00
Oleksii Holub cf83cbd89c Add support for stickers (#802) 2022-02-05 16:26:23 -08:00
Oleksii Holub d51d0d4872 Use snowflakes in more places 2022-02-06 01:15:56 +02:00
Oleksii Holub 2467caac9f Use api v9 2022-02-05 20:19:16 +02:00
Oleksii Holub bd98f4cb6a Refactor StringPart into StringSegment 2022-02-05 04:10:35 +02:00
Oleksii Holub fc7191d74c Fix changelog date for last entry 2022-01-27 18:44:40 +02:00
48 changed files with 697 additions and 305 deletions
+11 -1
View File
@@ -1,4 +1,14 @@
### v2.32 (15-Dec-2021) ### v2.33 (06-Mar-2022)
- Added messages informing about war in Ukraine and available ways to help.
- Added support for rendering stickers in HTML and JSON. Lottie-based stickers currently cannot be displayed in HTML exports (see [#803](https://github.com/Tyrrrz/DiscordChatExporter/issues/803)).
- Added a new `reaction:` message filter which can be used to check if someone reacted to a message with a specific emoji. You can either pass the emoji name (e.g. `reaction:LUL`) or its ID (e.g. `reaction:41771983429993937`).
- [GUI] Added auto-detection for dark mode. If your system is configured to prefer dark mode in applications, DiscordChatExporter will use it by default instead of light mode.
- Fixed an issue which caused the export process to crash when downloading media files with extremely long file extensions. (Thanks [@Tomlacko](https://github.com/Tomlacko))
- Fixed an issue which caused the export process to crash on invalid mentions.
- [GUI] Fixed an issue where the time pickers used to specify export ranges always displayed time in 12-hour format, instead of respecting the system locale.
### v2.32 (27-Jan-2022)
- Token kind (user or bot) is now detected automatically. Removed the button to switch token kind in GUI. Option `-b|--bot` in CLI is now deprecated and does nothing. - Token kind (user or bot) is now detected automatically. Removed the button to switch token kind in GUI. Option `-b|--bot` in CLI is now deprecated and does nothing.
- Updated user token extraction guide to reflect the fact that devtools are no longer accessible in the desktop version of Discord client. The recommended workaround is to open Discord in browser. (Thanks [@Dhananjay-JSR](https://github.com/Dhananjay-JSR)) - Updated user token extraction guide to reflect the fact that devtools are no longer accessible in the desktop version of Discord client. The recommended workaround is to open Discord in browser. (Thanks [@Dhananjay-JSR](https://github.com/Dhananjay-JSR))
+1 -1
View File
@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Version>2.32</Version> <Version>2.33</Version>
<Company>Tyrrrz</Company> <Company>Tyrrrz</Company>
<Copyright>Copyright (c) Oleksii Holub</Copyright> <Copyright>Copyright (c) Oleksii Holub</Copyright>
<LangVersion>preview</LangVersion> <LangVersion>preview</LangVersion>
@@ -15,11 +15,11 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AngleSharp" Version="0.16.1" /> <PackageReference Include="AngleSharp" Version="0.16.1" />
<PackageReference Include="FluentAssertions" Version="6.4.0" /> <PackageReference Include="FluentAssertions" Version="6.5.1" />
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" /> <PackageReference Include="GitHubActionsTestLogger" Version="1.3.0" PrivateAssets="all" />
<PackageReference Include="JsonExtensions" Version="1.2.0" /> <PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="coverlet.msbuild" Version="3.1.0" PrivateAssets="all" /> <PackageReference Include="coverlet.msbuild" Version="3.1.2" PrivateAssets="all" />
<PackageReference Include="System.Reactive" Version="5.0.0" /> <PackageReference Include="System.Reactive" Version="5.0.0" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" />
@@ -0,0 +1,45 @@
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record StickerSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_a_PNG_based_sticker_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.StickerTestCases,
Snowflake.Parse("939670623158943754")
);
var container = message.QuerySelector("[title='rock']");
var sourceUrl = container?.QuerySelector("img")?.GetAttribute("src");
// Assert
container.Should().NotBeNull();
sourceUrl.Should().Be("https://discord.com/stickers/904215665597120572.png");
}
[Fact]
public async Task Message_with_a_Lottie_based_sticker_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.StickerTestCases,
Snowflake.Parse("939670526517997590")
);
var container = message.QuerySelector("[title='Yikes']");
var sourceUrl = container?.QuerySelector("div[data-source]")?.GetAttribute("data-source");
// Assert
container.Should().NotBeNull();
sourceUrl.Should().Be("https://discord.com/stickers/816087132447178774.json");
}
}
@@ -0,0 +1,54 @@
using System.Linq;
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.JsonWriting;
public record StickerSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_a_PNG_based_sticker_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.StickerTestCases,
Snowflake.Parse("939670623158943754")
);
var sticker = message
.GetProperty("stickers")
.EnumerateArray()
.Single();
// Assert
sticker.GetProperty("id").GetString().Should().Be("904215665597120572");
sticker.GetProperty("name").GetString().Should().Be("rock");
sticker.GetProperty("format").GetString().Should().Be("PngAnimated");
sticker.GetProperty("sourceUrl").GetString().Should().Be("https://discord.com/stickers/904215665597120572.png");
}
[Fact]
public async Task Message_with_a_Lottie_based_sticker_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.StickerTestCases,
Snowflake.Parse("939670526517997590")
);
var sticker = message
.GetProperty("stickers")
.EnumerateArray()
.Single();
// Assert
sticker.GetProperty("id").GetString().Should().Be("816087132447178774");
sticker.GetProperty("name").GetString().Should().Be("Yikes");
sticker.GetProperty("format").GetString().Should().Be("Lottie");
sticker.GetProperty("sourceUrl").GetString().Should().Be("https://discord.com/stickers/816087132447178774.json");
}
}
@@ -59,6 +59,6 @@ public record PartitioningSpecs(TempOutputFixture TempOutput) : IClassFixture<Te
// Assert // Assert
Directory.EnumerateFiles(dirPath, fileNameWithoutExt + "*") Directory.EnumerateFiles(dirPath, fileNameWithoutExt + "*")
.Should() .Should()
.HaveCount(2); .HaveCount(3);
} }
} }
@@ -10,6 +10,8 @@ public static class ChannelIds
public static Snowflake EmbedTestCases { get; } = Snowflake.Parse("866472452459462687"); public static Snowflake EmbedTestCases { get; } = Snowflake.Parse("866472452459462687");
public static Snowflake StickerTestCases { get; } = Snowflake.Parse("939668868253769729");
public static Snowflake FilterTestCases { get; } = Snowflake.Parse("866744075033641020"); public static Snowflake FilterTestCases { get; } = Snowflake.Parse("866744075033641020");
public static Snowflake MentionTestCases { get; } = Snowflake.Parse("866458801389174794"); public static Snowflake MentionTestCases { get; } = Snowflake.Parse("866458801389174794");
@@ -14,6 +14,7 @@ using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Exporting; using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering; using DiscordChatExporter.Core.Exporting.Filtering;
using DiscordChatExporter.Core.Exporting.Partitioning; using DiscordChatExporter.Core.Exporting.Partitioning;
using Gress;
namespace DiscordChatExporter.Cli.Commands.Base; namespace DiscordChatExporter.Cli.Commands.Base;
@@ -78,8 +79,7 @@ public abstract class ExportCommandBase : TokenCommandBase
{ {
try try
{ {
await progressContext.StartTaskAsync( await progressContext.StartTaskAsync($"{channel.Category.Name} / {channel.Name}",
$"{channel.Category.Name} / {channel.Name}",
async progress => async progress =>
{ {
var guild = await Discord.GetGuildAsync(channel.GuildId, innerCancellationToken); var guild = await Discord.GetGuildAsync(channel.GuildId, innerCancellationToken);
@@ -98,7 +98,11 @@ public abstract class ExportCommandBase : TokenCommandBase
DateFormat DateFormat
); );
await Exporter.ExportChannelAsync(request, progress, innerCancellationToken); await Exporter.ExportChannelAsync(
request,
progress.ToPercentageBased(),
innerCancellationToken
);
} }
); );
} }
@@ -162,4 +166,16 @@ public abstract class ExportCommandBase : TokenCommandBase
await ExecuteAsync(console, channels); await ExecuteAsync(console, channels);
} }
public override ValueTask ExecuteAsync(IConsole console)
{
// War in Ukraine message
console.Output.WriteLine("==================================================");
console.Output.WriteLine("⚠ UKRAINE IS AT WAR!");
console.Output.WriteLine("LEARN MORE & HELP: https://tyrrrz.me");
console.Output.WriteLine("==================================================");
console.Output.WriteLine("");
return default;
}
} }
@@ -15,6 +15,8 @@ public class ExportAllCommand : ExportCommandBase
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var channels = new List<Channel>(); var channels = new List<Channel>();
@@ -15,6 +15,9 @@ public class ExportChannelsCommand : ExportCommandBase
[CommandOption("channel", 'c', IsRequired = true, Description = "Channel ID(s).")] [CommandOption("channel", 'c', IsRequired = true, Description = "Channel ID(s).")]
public IReadOnlyList<Snowflake> ChannelIds { get; init; } = Array.Empty<Snowflake>(); public IReadOnlyList<Snowflake> ChannelIds { get; init; } = Array.Empty<Snowflake>();
public override async ValueTask ExecuteAsync(IConsole console) => public override async ValueTask ExecuteAsync(IConsole console)
{
await base.ExecuteAsync(console);
await base.ExecuteAsync(console, ChannelIds); await base.ExecuteAsync(console, ChannelIds);
}
} }
@@ -13,6 +13,8 @@ public class ExportDirectMessagesCommand : ExportCommandBase
{ {
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
await console.Output.WriteLineAsync("Fetching channels..."); await console.Output.WriteLineAsync("Fetching channels...");
@@ -16,6 +16,8 @@ public class ExportGuildCommand : ExportCommandBase
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
await console.Output.WriteLineAsync("Fetching channels..."); await console.Output.WriteLineAsync("Fetching channels...");
@@ -6,9 +6,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CliFx" Version="2.2.1" /> <PackageReference Include="CliFx" Version="2.2.2" />
<PackageReference Include="Spectre.Console" Version="0.43.0" /> <PackageReference Include="Spectre.Console" Version="0.43.0" />
<PackageReference Include="Gress" Version="1.2.0" /> <PackageReference Include="Gress" Version="2.0.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -10,14 +10,14 @@ namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/emoji#emoji-object // https://discord.com/developers/docs/resources/emoji#emoji-object
public partial record Emoji( public partial record Emoji(
// Only present on custom emoji // Only present on custom emoji
string? Id, Snowflake? Id,
// Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂) // Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂)
string Name, string Name,
bool IsAnimated, bool IsAnimated,
string ImageUrl) string ImageUrl)
{ {
// Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile) // Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile)
public string Code => !string.IsNullOrWhiteSpace(Id) public string Code => Id is not null
? Name ? Name
: EmojiIndex.TryGetCode(Name) ?? Name; : EmojiIndex.TryGetCode(Name) ?? Name;
} }
@@ -32,18 +32,18 @@ public partial record Emoji
.Select(r => r.Value.ToString("x")) .Select(r => r.Value.ToString("x"))
); );
private static string GetImageUrl(string id, bool isAnimated) => isAnimated private static string GetImageUrl(Snowflake id, bool isAnimated) => isAnimated
? $"https://cdn.discordapp.com/emojis/{id}.gif" ? $"https://cdn.discordapp.com/emojis/{id}.gif"
: $"https://cdn.discordapp.com/emojis/{id}.png"; : $"https://cdn.discordapp.com/emojis/{id}.png";
private static string GetImageUrl(string name) => private static string GetImageUrl(string name) =>
$"https://twemoji.maxcdn.com/2/svg/{GetTwemojiName(name)}.svg"; $"https://twemoji.maxcdn.com/2/svg/{GetTwemojiName(name)}.svg";
public static string GetImageUrl(string? id, string? name, bool isAnimated) public static string GetImageUrl(Snowflake? id, string? name, bool isAnimated)
{ {
// Custom emoji // Custom emoji
if (!string.IsNullOrWhiteSpace(id)) if (id is not null)
return GetImageUrl(id, isAnimated); return GetImageUrl(id.Value, isAnimated);
// Standard emoji // Standard emoji
if (!string.IsNullOrWhiteSpace(name)) if (!string.IsNullOrWhiteSpace(name))
@@ -55,7 +55,7 @@ public partial record Emoji
public static Emoji Parse(JsonElement json) public static Emoji Parse(JsonElement json)
{ {
var id = json.GetPropertyOrNull("id")?.GetNonWhiteSpaceStringOrNull(); var id = json.GetPropertyOrNull("id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
var name = json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull(); var name = json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull();
var isAnimated = json.GetPropertyOrNull("animated")?.GetBooleanOrNull() ?? false; var isAnimated = json.GetPropertyOrNull("animated")?.GetBooleanOrNull() ?? false;
@@ -21,6 +21,7 @@ public record Message(
string Content, string Content,
IReadOnlyList<Attachment> Attachments, IReadOnlyList<Attachment> Attachments,
IReadOnlyList<Embed> Embeds, IReadOnlyList<Embed> Embeds,
IReadOnlyList<Sticker> Stickers,
IReadOnlyList<Reaction> Reactions, IReadOnlyList<Reaction> Reactions,
IReadOnlyList<User> MentionedUsers, IReadOnlyList<User> MentionedUsers,
MessageReference? Reference, MessageReference? Reference,
@@ -60,6 +61,10 @@ public record Message(
json.GetPropertyOrNull("embeds")?.EnumerateArrayOrNull()?.Select(Embed.Parse).ToArray() ?? json.GetPropertyOrNull("embeds")?.EnumerateArrayOrNull()?.Select(Embed.Parse).ToArray() ??
Array.Empty<Embed>(); Array.Empty<Embed>();
var stickers =
json.GetPropertyOrNull("sticker_items")?.EnumerateArrayOrNull()?.Select(Sticker.Parse).ToArray() ??
Array.Empty<Sticker>();
var reactions = var reactions =
json.GetPropertyOrNull("reactions")?.EnumerateArrayOrNull()?.Select(Reaction.Parse).ToArray() ?? json.GetPropertyOrNull("reactions")?.EnumerateArrayOrNull()?.Select(Reaction.Parse).ToArray() ??
Array.Empty<Reaction>(); Array.Empty<Reaction>();
@@ -79,6 +84,7 @@ public record Message(
content, content,
attachments, attachments,
embeds, embeds,
stickers,
reactions, reactions,
mentionedUsers, mentionedUsers,
messageReference, messageReference,
@@ -0,0 +1,25 @@
using System.Text.Json;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
public record Sticker(Snowflake Id, string Name, StickerFormat Format, string SourceUrl)
{
private static string GetSourceUrl(Snowflake id, StickerFormat format)
{
var extension = format == StickerFormat.Lottie ? "json" : "png";
return $"https://discord.com/stickers/{id}.{extension}";
}
public static Sticker Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonWhiteSpaceString();
var format = (StickerFormat)json.GetProperty("format_type").GetInt32();
var sourceUrl = GetSourceUrl(id, format);
return new Sticker(id, name, format, sourceUrl);
}
}
@@ -0,0 +1,8 @@
namespace DiscordChatExporter.Core.Discord.Data;
public enum StickerFormat
{
Png = 1,
PngAnimated = 2,
Lottie = 3
}
@@ -12,6 +12,7 @@ using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Exceptions; using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Utils; using DiscordChatExporter.Core.Utils;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
using Gress;
using JsonExtensions.Http; using JsonExtensions.Http;
using JsonExtensions.Reading; using JsonExtensions.Reading;
@@ -20,7 +21,7 @@ namespace DiscordChatExporter.Core.Discord;
public class DiscordClient public class DiscordClient
{ {
private readonly string _token; private readonly string _token;
private readonly Uri _baseUri = new("https://discord.com/api/v8/", UriKind.Absolute); private readonly Uri _baseUri = new("https://discord.com/api/v9/", UriKind.Absolute);
private TokenKind _tokenKind = TokenKind.Unknown; private TokenKind _tokenKind = TokenKind.Unknown;
@@ -273,7 +274,7 @@ public class DiscordClient
Snowflake channelId, Snowflake channelId,
Snowflake? after = null, Snowflake? after = null,
Snowflake? before = null, Snowflake? before = null,
IProgress<double>? progress = null, IProgress<Percentage>? progress = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default) [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
// Get the last message in the specified range. // Get the last message in the specified range.
@@ -322,16 +323,13 @@ public class DiscordClient
var exportedDuration = (message.Timestamp - firstMessage.Timestamp).Duration(); var exportedDuration = (message.Timestamp - firstMessage.Timestamp).Duration();
var totalDuration = (lastMessage.Timestamp - firstMessage.Timestamp).Duration(); var totalDuration = (lastMessage.Timestamp - firstMessage.Timestamp).Duration();
if (totalDuration > TimeSpan.Zero) progress.Report(Percentage.FromFraction(
{ // Avoid division by zero if all messages have the exact same timestamp
progress.Report(exportedDuration / totalDuration); // (which may be the case if there's only one message in the channel)
} totalDuration > TimeSpan.Zero
// Avoid division by zero if all messages have the exact same timestamp ? exportedDuration / totalDuration
// (which may be the case if there's only one message in the channel) : 1
else ));
{
progress.Report(1);
}
} }
yield return message; yield return message;
@@ -5,6 +5,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gress" Version="2.0.1" />
<PackageReference Include="JsonExtensions" Version="1.2.0" /> <PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.0" /> <PackageReference Include="MiniRazor.CodeGen" Version="2.2.0" />
<PackageReference Include="Polly" Version="7.2.3" /> <PackageReference Include="Polly" Version="7.2.3" />
@@ -8,6 +8,7 @@ using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Discord.Data.Common; using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Exceptions; using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
using Gress;
namespace DiscordChatExporter.Core.Exporting; namespace DiscordChatExporter.Core.Exporting;
@@ -19,7 +20,7 @@ public class ChannelExporter
public async ValueTask ExportChannelAsync( public async ValueTask ExportChannelAsync(
ExportRequest request, ExportRequest request,
IProgress<double>? progress = null, IProgress<Percentage>? progress = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
// Build context // Build context
@@ -44,6 +44,12 @@ internal static class FilterGrammar
.Select(v => (MessageFilter) new MentionsMessageFilter(v)) .Select(v => (MessageFilter) new MentionsMessageFilter(v))
.Named("mentions:<value>"); .Named("mentions:<value>");
private static readonly TextParser<MessageFilter> ReactionFilter = Span
.EqualToIgnoreCase("reaction:")
.IgnoreThen(String)
.Select(v => (MessageFilter) new ReactionMessageFilter(v))
.Named("reaction:<value>");
private static readonly TextParser<MessageFilter> HasFilter = Span private static readonly TextParser<MessageFilter> HasFilter = Span
.EqualToIgnoreCase("has:") .EqualToIgnoreCase("has:")
.IgnoreThen(Parse.OneOf( .IgnoreThen(Parse.OneOf(
@@ -72,6 +78,7 @@ internal static class FilterGrammar
GroupedFilter, GroupedFilter,
FromFilter, FromFilter,
MentionsFilter, MentionsFilter,
ReactionFilter,
HasFilter, HasFilter,
ContainsFilter ContainsFilter
); );
@@ -0,0 +1,18 @@
using System;
using System.Linq;
using DiscordChatExporter.Core.Discord.Data;
namespace DiscordChatExporter.Core.Exporting.Filtering;
internal class ReactionMessageFilter : MessageFilter
{
private readonly string _value;
public ReactionMessageFilter(string value) => _value = value;
public override bool IsMatch(Message message) => message.Reactions.Any(r =>
string.Equals(_value, r.Emoji.Id?.ToString(), StringComparison.OrdinalIgnoreCase) ||
string.Equals(_value, r.Emoji.Name, StringComparison.OrdinalIgnoreCase) ||
string.Equals(_value, r.Emoji.Code, StringComparison.OrdinalIgnoreCase)
);
}
@@ -103,7 +103,15 @@ internal partial class MediaDownloader
// Otherwise, use the original file name but inject the hash in the middle // Otherwise, use the original file name but inject the hash in the middle
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var fileExtension = Path.GetExtension(fileName); var fileExtension = Path.GetExtension(fileName);
// Probably not a file extension, just a dot in a long file name
// https://github.com/Tyrrrz/DiscordChatExporter/issues/708
if (fileExtension.Length > 41)
{
fileNameWithoutExtension = fileName;
fileExtension = "";
}
return PathEx.EscapeFileName(fileNameWithoutExtension.Truncate(42) + '-' + urlHash + fileExtension); return PathEx.EscapeFileName(fileNameWithoutExtension.Truncate(42) + '-' + urlHash + fileExtension);
} }
} }
@@ -1,6 +1,7 @@
@using System @using System
@using System.Linq @using System.Linq
@using System.Threading.Tasks @using System.Threading.Tasks
@using DiscordChatExporter.Core.Discord.Data
@using DiscordChatExporter.Core.Exporting.Writers.Html; @using DiscordChatExporter.Core.Exporting.Writers.Html;
@namespace DiscordChatExporter.Core.Exporting.Writers.Html @namespace DiscordChatExporter.Core.Exporting.Writers.Html
@@ -411,6 +412,21 @@
} }
} }
@{/* Stickers */}
@foreach (var sticker in message.Stickers)
{
<div class="chatlog__sticker" title="@sticker.Name">
@if (sticker.Format is StickerFormat.Png or StickerFormat.PngAnimated)
{
<img class="chatlog__sticker--media" src="@(await ResolveUrlAsync(sticker.SourceUrl))" alt="Sticker">
}
else if (sticker.Format == StickerFormat.Lottie)
{
<div class="chatlog__sticker--media" data-source="@(await ResolveUrlAsync(sticker.SourceUrl))"></div>
}
</div>
}
@{/* Message reactions */} @{/* Message reactions */}
@if (message.Reactions.Any()) @if (message.Reactions.Any())
{ {
@@ -113,8 +113,7 @@
margin: 0.05em 0; margin: 0.05em 0;
} }
.quote::before { .quote-border {
content: "";
margin-right: 0.5em; margin-right: 0.5em;
border: 2px solid @Themed("#4f545c", "#c7ccd1"); border: 2px solid @Themed("#4f545c", "#c7ccd1");
border-radius: 3px; border-radius: 3px;
@@ -597,6 +596,16 @@
border-radius: 3px; border-radius: 3px;
} }
.chatlog__sticker {
width: 180px;
height: 180px;
}
.chatlog__sticker--media {
max-width: 100%;
max-height: 100%;
}
.chatlog__reactions { .chatlog__reactions {
display: flex; display: flex;
} }
@@ -660,7 +669,29 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
<script> <script>
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.pre--multiline').forEach(block => hljs.highlightBlock(block)); document.querySelectorAll('.pre--multiline').forEach(e => hljs.highlightBlock(e));
});
</script>
@{/* Lottie animation support */}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.8.1/lottie.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.chatlog__sticker--media[data-source]').forEach(e => {
const imageDataUrl = e.getAttribute('data-source');
const anim = lottie.loadAnimation({
container: e,
renderer: 'svg',
loop: true,
autoplay: true,
path: imageDataUrl
});
anim.addEventListener('data_failed', () =>
e.innerHTML = '<strong>[Sticker cannot be rendered]</strong>'
);
});
}); });
</script> </script>
@@ -161,6 +161,21 @@ internal class JsonMessageWriter : MessageWriter
await _writer.FlushAsync(cancellationToken); await _writer.FlushAsync(cancellationToken);
} }
private async ValueTask WriteStickerAsync(
Sticker sticker,
CancellationToken cancellationToken = default)
{
_writer.WriteStartObject();
_writer.WriteString("id", sticker.Id.ToString());
_writer.WriteString("name", sticker.Name);
_writer.WriteString("format", sticker.Format.ToString());
_writer.WriteString("sourceUrl", await Context.ResolveMediaUrlAsync(sticker.SourceUrl, cancellationToken));
_writer.WriteEndObject();
await _writer.FlushAsync(cancellationToken);
}
private async ValueTask WriteReactionAsync( private async ValueTask WriteReactionAsync(
Reaction reaction, Reaction reaction,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
@@ -169,7 +184,7 @@ internal class JsonMessageWriter : MessageWriter
// Emoji // Emoji
_writer.WriteStartObject("emoji"); _writer.WriteStartObject("emoji");
_writer.WriteString("id", reaction.Emoji.Id); _writer.WriteString("id", reaction.Emoji.Id.ToString());
_writer.WriteString("name", reaction.Emoji.Name); _writer.WriteString("name", reaction.Emoji.Name);
_writer.WriteBoolean("isAnimated", reaction.Emoji.IsAnimated); _writer.WriteBoolean("isAnimated", reaction.Emoji.IsAnimated);
_writer.WriteString("imageUrl", await Context.ResolveMediaUrlAsync(reaction.Emoji.ImageUrl, cancellationToken)); _writer.WriteString("imageUrl", await Context.ResolveMediaUrlAsync(reaction.Emoji.ImageUrl, cancellationToken));
@@ -276,6 +291,14 @@ internal class JsonMessageWriter : MessageWriter
_writer.WriteEndArray(); _writer.WriteEndArray();
// Stickers
_writer.WriteStartArray("stickers");
foreach (var sticker in message.Stickers)
await WriteStickerAsync(sticker, cancellationToken);
_writer.WriteEndArray();
// Reactions // Reactions
_writer.WriteStartArray("reactions"); _writer.WriteStartArray("reactions");
@@ -3,7 +3,6 @@ using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data; using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Markdown; using DiscordChatExporter.Core.Markdown;
using DiscordChatExporter.Core.Markdown.Parsing; using DiscordChatExporter.Core.Markdown.Parsing;
@@ -40,7 +39,8 @@ internal partial class HtmlMarkdownVisitor : MarkdownVisitor
FormattingKind.Strikethrough => ("<s>", "</s>"), FormattingKind.Strikethrough => ("<s>", "</s>"),
FormattingKind.Spoiler => ( FormattingKind.Spoiler => (
"<span class=\"spoiler-text spoiler-text--hidden\" onclick=\"showSpoiler(event, this)\">", "</span>"), "<span class=\"spoiler-text spoiler-text--hidden\" onclick=\"showSpoiler(event, this)\">", "</span>"),
FormattingKind.Quote => ("<div class=\"quote\">", "</div>"), FormattingKind.Quote => (
"<div class=\"quote\"><div class=\"quote-border\"></div><div class=\"quote-content\">", "</div></div>"),
_ => throw new ArgumentOutOfRangeException(nameof(formatting.Kind)) _ => throw new ArgumentOutOfRangeException(nameof(formatting.Kind))
}; };
@@ -85,8 +85,8 @@ internal partial class HtmlMarkdownVisitor : MarkdownVisitor
_buffer.Append( _buffer.Append(
!string.IsNullOrWhiteSpace(linkedMessageId) !string.IsNullOrWhiteSpace(linkedMessageId)
? $"<a href=\"{Uri.EscapeUriString(link.Url)}\" onclick=\"scrollToMessage(event, '{linkedMessageId}')\">" ? $"<a href=\"{HtmlEncode(link.Url)}\" onclick=\"scrollToMessage(event, '{linkedMessageId}')\">"
: $"<a href=\"{Uri.EscapeUriString(link.Url)}\">" : $"<a href=\"{HtmlEncode(link.Url)}\">"
); );
var result = base.VisitLink(link); var result = base.VisitLink(link);
@@ -108,28 +108,34 @@ internal partial class HtmlMarkdownVisitor : MarkdownVisitor
protected override MarkdownNode VisitMention(MentionNode mention) protected override MarkdownNode VisitMention(MentionNode mention)
{ {
var mentionId = Snowflake.TryParse(mention.Id); if (mention.Kind == MentionKind.Everyone)
if (mention.Kind == MentionKind.Meta)
{ {
_buffer _buffer
.Append("<span class=\"mention\">") .Append("<span class=\"mention\">")
.Append("@").Append(HtmlEncode(mention.Id)) .Append("@everyone")
.Append("</span>");
}
else if (mention.Kind == MentionKind.Here)
{
_buffer
.Append("<span class=\"mention\">")
.Append("@here")
.Append("</span>"); .Append("</span>");
} }
else if (mention.Kind == MentionKind.User) else if (mention.Kind == MentionKind.User)
{ {
var member = mentionId?.Pipe(_context.TryGetMember); var member = mention.TargetId?.Pipe(_context.TryGetMember);
var fullName = member?.User.FullName ?? "Unknown"; var fullName = member?.User.FullName ?? "Unknown";
var nick = member?.Nick ?? "Unknown"; var nick = member?.Nick ?? "Unknown";
_buffer _buffer
.Append($"<span class=\"mention\" title=\"{HtmlEncode(fullName)}\">") .Append($"<span class=\"mention\" title=\"{HtmlEncode(fullName)}\">")
.Append("@").Append(HtmlEncode(nick)) .Append('@').Append(HtmlEncode(nick))
.Append("</span>"); .Append("</span>");
} }
else if (mention.Kind == MentionKind.Channel) else if (mention.Kind == MentionKind.Channel)
{ {
var channel = mentionId?.Pipe(_context.TryGetChannel); var channel = mention.TargetId?.Pipe(_context.TryGetChannel);
var symbol = channel?.IsVoiceChannel == true ? "🔊" : "#"; var symbol = channel?.IsVoiceChannel == true ? "🔊" : "#";
var name = channel?.Name ?? "deleted-channel"; var name = channel?.Name ?? "deleted-channel";
@@ -140,7 +146,7 @@ internal partial class HtmlMarkdownVisitor : MarkdownVisitor
} }
else if (mention.Kind == MentionKind.Role) else if (mention.Kind == MentionKind.Role)
{ {
var role = mentionId?.Pipe(_context.TryGetRole); var role = mention.TargetId?.Pipe(_context.TryGetRole);
var name = role?.Name ?? "deleted-role"; var name = role?.Name ?? "deleted-role";
var color = role?.Color; var color = role?.Color;
@@ -150,7 +156,7 @@ internal partial class HtmlMarkdownVisitor : MarkdownVisitor
_buffer _buffer
.Append($"<span class=\"mention\" style=\"{style}\">") .Append($"<span class=\"mention\" style=\"{style}\">")
.Append("@").Append(HtmlEncode(name)) .Append('@').Append(HtmlEncode(name))
.Append("</span>"); .Append("</span>");
} }
@@ -1,5 +1,4 @@
using System.Text; using System.Text;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Markdown; using DiscordChatExporter.Core.Markdown;
using DiscordChatExporter.Core.Markdown.Parsing; using DiscordChatExporter.Core.Markdown.Parsing;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
@@ -36,21 +35,24 @@ internal partial class PlainTextMarkdownVisitor : MarkdownVisitor
protected override MarkdownNode VisitMention(MentionNode mention) protected override MarkdownNode VisitMention(MentionNode mention)
{ {
var mentionId = Snowflake.TryParse(mention.Id); if (mention.Kind == MentionKind.Everyone)
if (mention.Kind == MentionKind.Meta)
{ {
_buffer.Append($"@{mention.Id}"); _buffer.Append("@everyone");
}
else if (mention.Kind == MentionKind.Here)
{
_buffer.Append("@here");
} }
else if (mention.Kind == MentionKind.User) else if (mention.Kind == MentionKind.User)
{ {
var member = mentionId?.Pipe(_context.TryGetMember); var member = mention.TargetId?.Pipe(_context.TryGetMember);
var name = member?.User.Name ?? "Unknown"; var name = member?.User.Name ?? "Unknown";
_buffer.Append($"@{name}"); _buffer.Append($"@{name}");
} }
else if (mention.Kind == MentionKind.Channel) else if (mention.Kind == MentionKind.Channel)
{ {
var channel = mentionId?.Pipe(_context.TryGetChannel); var channel =mention.TargetId?.Pipe(_context.TryGetChannel);
var name = channel?.Name ?? "deleted-channel"; var name = channel?.Name ?? "deleted-channel";
_buffer.Append($"#{name}"); _buffer.Append($"#{name}");
@@ -61,7 +63,7 @@ internal partial class PlainTextMarkdownVisitor : MarkdownVisitor
} }
else if (mention.Kind == MentionKind.Role) else if (mention.Kind == MentionKind.Role)
{ {
var role = mentionId?.Pipe(_context.TryGetRole); var role = mention.TargetId?.Pipe(_context.TryGetRole);
var name = role?.Name ?? "deleted-role"; var name = role?.Name ?? "deleted-role";
_buffer.Append($"@{name}"); _buffer.Append($"@{name}");
@@ -98,6 +98,25 @@ internal class PlainTextMessageWriter : MessageWriter
} }
} }
private async ValueTask WriteStickersAsync(
IReadOnlyList<Sticker> stickers,
CancellationToken cancellationToken = default)
{
if (!stickers.Any())
return;
await _writer.WriteLineAsync("{Stickers}");
foreach (var sticker in stickers)
{
cancellationToken.ThrowIfCancellationRequested();
await _writer.WriteLineAsync(await Context.ResolveMediaUrlAsync(sticker.SourceUrl, cancellationToken));
}
await _writer.WriteLineAsync();
}
private async ValueTask WriteReactionsAsync( private async ValueTask WriteReactionsAsync(
IReadOnlyList<Reaction> reactions, IReadOnlyList<Reaction> reactions,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
@@ -156,9 +175,10 @@ internal class PlainTextMessageWriter : MessageWriter
await _writer.WriteLineAsync(); await _writer.WriteLineAsync();
// Attachments, embeds, reactions // Attachments, embeds, reactions, etc.
await WriteAttachmentsAsync(message.Attachments, cancellationToken); await WriteAttachmentsAsync(message.Attachments, cancellationToken);
await WriteEmbedsAsync(message.Embeds, cancellationToken); await WriteEmbedsAsync(message.Embeds, cancellationToken);
await WriteStickersAsync(message.Stickers, cancellationToken);
await WriteReactionsAsync(message.Reactions, cancellationToken); await WriteReactionsAsync(message.Reactions, cancellationToken);
await _writer.WriteLineAsync(); await _writer.WriteLineAsync();
@@ -1,21 +1,22 @@
using DiscordChatExporter.Core.Utils; using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Utils;
namespace DiscordChatExporter.Core.Markdown; namespace DiscordChatExporter.Core.Markdown;
internal record EmojiNode( internal record EmojiNode(
// Only present on custom emoji // Only present on custom emoji
string? Id, Snowflake? Id,
// Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂) // Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂)
string Name, string Name,
bool IsAnimated) : MarkdownNode bool IsAnimated) : MarkdownNode
{ {
public bool IsCustomEmoji => Id is not null;
// Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile) // Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile)
public string Code => !string.IsNullOrWhiteSpace(Id) public string Code => IsCustomEmoji
? Name ? Name
: EmojiIndex.TryGetCode(Name) ?? Name; : EmojiIndex.TryGetCode(Name) ?? Name;
public bool IsCustomEmoji => !string.IsNullOrWhiteSpace(Id);
public EmojiNode(string name) public EmojiNode(string name)
: this(null, name, false) : this(null, name, false)
{ {
@@ -2,7 +2,8 @@
internal enum MentionKind internal enum MentionKind
{ {
Meta, Everyone,
Here,
User, User,
Channel, Channel,
Role Role
@@ -1,3 +1,6 @@
namespace DiscordChatExporter.Core.Markdown; using DiscordChatExporter.Core.Discord;
internal record MentionNode(string Id, MentionKind Kind) : MarkdownNode; namespace DiscordChatExporter.Core.Markdown;
// Null ID means it's a meta mention or an invalid mention
internal record MentionNode(Snowflake? TargetId, MentionKind Kind) : MarkdownNode;
@@ -16,7 +16,7 @@ internal class AggregateMatcher<T> : IMatcher<T>
{ {
} }
public ParsedMatch<T>? TryMatch(StringPart stringPart) public ParsedMatch<T>? TryMatch(StringSegment segment)
{ {
ParsedMatch<T>? earliestMatch = null; ParsedMatch<T>? earliestMatch = null;
@@ -24,19 +24,19 @@ internal class AggregateMatcher<T> : IMatcher<T>
foreach (var matcher in _matchers) foreach (var matcher in _matchers)
{ {
// Try to match // Try to match
var match = matcher.TryMatch(stringPart); var match = matcher.TryMatch(segment);
// If there's no match - continue // If there's no match - continue
if (match is null) if (match is null)
continue; continue;
// If this match is earlier than previous earliest - replace // If this match is earlier than previous earliest - replace
if (earliestMatch is null || match.StringPart.StartIndex < earliestMatch.StringPart.StartIndex) if (earliestMatch is null || match.Segment.StartIndex < earliestMatch.Segment.StartIndex)
earliestMatch = match; earliestMatch = match;
// If the earliest match starts at the very beginning - break, // If the earliest match starts at the very beginning - break,
// because it's impossible to find a match earlier than that // because it's impossible to find a match earlier than that
if (earliestMatch.StringPart.StartIndex == stringPart.StartIndex) if (earliestMatch.Segment.StartIndex == segment.StartIndex)
break; break;
} }
@@ -5,44 +5,57 @@ namespace DiscordChatExporter.Core.Markdown.Parsing;
internal interface IMatcher<T> internal interface IMatcher<T>
{ {
ParsedMatch<T>? TryMatch(StringPart stringPart); ParsedMatch<T>? TryMatch(StringSegment segment);
} }
internal static class MatcherExtensions internal static class MatcherExtensions
{ {
public static IEnumerable<ParsedMatch<T>> MatchAll<T>(this IMatcher<T> matcher, public static IEnumerable<ParsedMatch<T>> MatchAll<T>(
StringPart stringPart, Func<StringPart, T> transformFallback) this IMatcher<T> matcher,
StringSegment segment,
Func<StringSegment, T> transformFallback)
{ {
// Loop through segments divided by individual matches // Loop through segments divided by individual matches
var currentIndex = stringPart.StartIndex; var currentIndex = segment.StartIndex;
while (currentIndex < stringPart.EndIndex) while (currentIndex < segment.EndIndex)
{ {
// Find a match within this segment // Find a match within this segment
var match = matcher.TryMatch(stringPart.Slice(currentIndex, stringPart.EndIndex - currentIndex)); var match = matcher.TryMatch(
segment.Relocate(
currentIndex,
segment.EndIndex - currentIndex
)
);
// If there's no match - break
if (match is null) if (match is null)
break; break;
// If this match doesn't start immediately at current index - transform and yield fallback first // If this match doesn't start immediately at the current position - transform and yield fallback first
if (match.StringPart.StartIndex > currentIndex) if (match.Segment.StartIndex > currentIndex)
{ {
var fallbackPart = stringPart.Slice(currentIndex, match.StringPart.StartIndex - currentIndex); var fallbackSegment = segment.Relocate(
yield return new ParsedMatch<T>(fallbackPart, transformFallback(fallbackPart)); currentIndex,
match.Segment.StartIndex - currentIndex
);
yield return new ParsedMatch<T>(fallbackSegment, transformFallback(fallbackSegment));
} }
// Yield match
yield return match; yield return match;
// Shift current index to the end of the match // Shift current index to the end of the match
currentIndex = match.StringPart.StartIndex + match.StringPart.Length; currentIndex = match.Segment.StartIndex + match.Segment.Length;
} }
// If EOL wasn't reached - transform and yield remaining part as fallback // If EOL hasn't been reached - transform and yield remaining part as fallback
if (currentIndex < stringPart.EndIndex) if (currentIndex < segment.EndIndex)
{ {
var fallbackPart = stringPart.Slice(currentIndex); var fallbackSegment = segment.Relocate(
yield return new ParsedMatch<T>(fallbackPart, transformFallback(fallbackPart)); currentIndex,
segment.EndIndex - currentIndex
);
yield return new ParsedMatch<T>(fallbackSegment, transformFallback(fallbackSegment));
} }
} }
} }
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Utils; using DiscordChatExporter.Core.Utils;
namespace DiscordChatExporter.Core.Markdown.Parsing; namespace DiscordChatExporter.Core.Markdown.Parsing;
@@ -23,7 +24,7 @@ internal static partial class MarkdownParser
// Capture any character until the earliest double asterisk not followed by an asterisk // Capture any character until the earliest double asterisk not followed by an asterisk
private static readonly IMatcher<MarkdownNode> BoldFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> BoldFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Bold, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Bold, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the earliest single asterisk not preceded or followed by an asterisk // Capture any character until the earliest single asterisk not preceded or followed by an asterisk
@@ -31,54 +32,54 @@ internal static partial class MarkdownParser
// Closing asterisk must not be preceded by whitespace // Closing asterisk must not be preceded by whitespace
private static readonly IMatcher<MarkdownNode> ItalicFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> ItalicFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Italic, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Italic, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the earliest triple asterisk not followed by an asterisk // Capture any character until the earliest triple asterisk not followed by an asterisk
private static readonly IMatcher<MarkdownNode> ItalicBoldFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> ItalicBoldFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("\\*(\\*\\*.+?\\*\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("\\*(\\*\\*.+?\\*\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Italic, Parse(p.Slice(m.Groups[1]), BoldFormattingNodeMatcher)) (s, m) => new FormattingNode(FormattingKind.Italic, Parse(s.Relocate(m.Groups[1]), BoldFormattingNodeMatcher))
); );
// Capture any character except underscore until an underscore // Capture any character except underscore until an underscore
// Closing underscore must not be followed by a word character // Closing underscore must not be followed by a word character
private static readonly IMatcher<MarkdownNode> ItalicAltFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> ItalicAltFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("_([^_]+)_(?!\\w)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("_([^_]+)_(?!\\w)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Italic, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Italic, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the earliest double underscore not followed by an underscore // Capture any character until the earliest double underscore not followed by an underscore
private static readonly IMatcher<MarkdownNode> UnderlineFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> UnderlineFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("__(.+?)__(?!_)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("__(.+?)__(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Underline, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Underline, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the earliest triple underscore not followed by an underscore // Capture any character until the earliest triple underscore not followed by an underscore
private static readonly IMatcher<MarkdownNode> ItalicUnderlineFormattingNodeMatcher = private static readonly IMatcher<MarkdownNode> ItalicUnderlineFormattingNodeMatcher =
new RegexMatcher<MarkdownNode>( new RegexMatcher<MarkdownNode>(
new Regex("_(__.+?__)_(?!_)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("_(__.+?__)_(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Italic, (s, m) => new FormattingNode(FormattingKind.Italic,
Parse(p.Slice(m.Groups[1]), UnderlineFormattingNodeMatcher)) Parse(s.Relocate(m.Groups[1]), UnderlineFormattingNodeMatcher))
); );
// Capture any character until the earliest double tilde // Capture any character until the earliest double tilde
private static readonly IMatcher<MarkdownNode> StrikethroughFormattingNodeMatcher = private static readonly IMatcher<MarkdownNode> StrikethroughFormattingNodeMatcher =
new RegexMatcher<MarkdownNode>( new RegexMatcher<MarkdownNode>(
new Regex("~~(.+?)~~", DefaultRegexOptions | RegexOptions.Singleline), new Regex("~~(.+?)~~", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Strikethrough, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Strikethrough, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the earliest double pipe // Capture any character until the earliest double pipe
private static readonly IMatcher<MarkdownNode> SpoilerFormattingNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> SpoilerFormattingNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("\\|\\|(.+?)\\|\\|", DefaultRegexOptions | RegexOptions.Singleline), new Regex("\\|\\|(.+?)\\|\\|", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Spoiler, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Spoiler, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any character until the end of the line // Capture any character until the end of the line
// Opening 'greater than' character must be followed by whitespace // Opening 'greater than' character must be followed by whitespace
private static readonly IMatcher<MarkdownNode> SingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> SingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("^>\\s(.+\n?)", DefaultRegexOptions), new Regex("^>\\s(.+\n?)", DefaultRegexOptions),
(p, m) => new FormattingNode(FormattingKind.Quote, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Quote, Parse(s.Relocate(m.Groups[1])))
); );
// Repeatedly capture any character until the end of the line // Repeatedly capture any character until the end of the line
@@ -97,7 +98,7 @@ internal static partial class MarkdownParser
// Opening 'greater than' characters must be followed by whitespace // Opening 'greater than' characters must be followed by whitespace
private static readonly IMatcher<MarkdownNode> MultiLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> MultiLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("^>>>\\s(.+)", DefaultRegexOptions | RegexOptions.Singleline), new Regex("^>>>\\s(.+)", DefaultRegexOptions | RegexOptions.Singleline),
(p, m) => new FormattingNode(FormattingKind.Quote, Parse(p.Slice(m.Groups[1]))) (s, m) => new FormattingNode(FormattingKind.Quote, Parse(s.Relocate(m.Groups[1])))
); );
/* Code blocks */ /* Code blocks */
@@ -123,31 +124,31 @@ internal static partial class MarkdownParser
// Capture @everyone // Capture @everyone
private static readonly IMatcher<MarkdownNode> EveryoneMentionNodeMatcher = new StringMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> EveryoneMentionNodeMatcher = new StringMatcher<MarkdownNode>(
"@everyone", "@everyone",
_ => new MentionNode("everyone", MentionKind.Meta) _ => new MentionNode(null, MentionKind.Everyone)
); );
// Capture @here // Capture @here
private static readonly IMatcher<MarkdownNode> HereMentionNodeMatcher = new StringMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> HereMentionNodeMatcher = new StringMatcher<MarkdownNode>(
"@here", "@here",
_ => new MentionNode("here", MentionKind.Meta) _ => new MentionNode(null, MentionKind.Here)
); );
// Capture <@123456> or <@!123456> // Capture <@123456> or <@!123456>
private static readonly IMatcher<MarkdownNode> UserMentionNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> UserMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("<@!?(\\d+)>", DefaultRegexOptions), new Regex("<@!?(\\d+)>", DefaultRegexOptions),
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.User) (_, m) => new MentionNode(Snowflake.TryParse(m.Groups[1].Value), MentionKind.User)
); );
// Capture <#123456> // Capture <#123456>
private static readonly IMatcher<MarkdownNode> ChannelMentionNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> ChannelMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("<#!?(\\d+)>", DefaultRegexOptions), new Regex("<#!?(\\d+)>", DefaultRegexOptions),
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.Channel) (_, m) => new MentionNode(Snowflake.TryParse(m.Groups[1].Value), MentionKind.Channel)
); );
// Capture <@&123456> // Capture <@&123456>
private static readonly IMatcher<MarkdownNode> RoleMentionNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> RoleMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("<@&(\\d+)>", DefaultRegexOptions), new Regex("<@&(\\d+)>", DefaultRegexOptions),
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.Role) (_, m) => new MentionNode(Snowflake.TryParse(m.Groups[1].Value), MentionKind.Role)
); );
/* Emoji */ /* Emoji */
@@ -177,7 +178,11 @@ internal static partial class MarkdownParser
// Capture <:lul:123456> or <a:lul:123456> // Capture <:lul:123456> or <a:lul:123456>
private static readonly IMatcher<MarkdownNode> CustomEmojiNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> CustomEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("<(a)?:(.+?):(\\d+?)>", DefaultRegexOptions), new Regex("<(a)?:(.+?):(\\d+?)>", DefaultRegexOptions),
(_, m) => new EmojiNode(m.Groups[3].Value, m.Groups[2].Value, !string.IsNullOrWhiteSpace(m.Groups[1].Value)) (_, m) => new EmojiNode(
Snowflake.TryParse(m.Groups[3].Value),
m.Groups[2].Value,
!string.IsNullOrWhiteSpace(m.Groups[1].Value)
)
); );
/* Links */ /* Links */
@@ -185,7 +190,7 @@ internal static partial class MarkdownParser
// Capture [title](link) // Capture [title](link)
private static readonly IMatcher<MarkdownNode> TitledLinkNodeMatcher = new RegexMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> TitledLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
new Regex("\\[(.+?)\\]\\((.+?)\\)", DefaultRegexOptions), new Regex("\\[(.+?)\\]\\((.+?)\\)", DefaultRegexOptions),
(p, m) => new LinkNode(m.Groups[2].Value, Parse(p.Slice(m.Groups[1]))) (s, m) => new LinkNode(m.Groups[2].Value, Parse(s.Relocate(m.Groups[1])))
); );
// Capture any non-whitespace character after http:// or https:// // Capture any non-whitespace character after http:// or https://
@@ -207,7 +212,7 @@ internal static partial class MarkdownParser
// This escapes it from matching for formatting // This escapes it from matching for formatting
private static readonly IMatcher<MarkdownNode> ShrugTextNodeMatcher = new StringMatcher<MarkdownNode>( private static readonly IMatcher<MarkdownNode> ShrugTextNodeMatcher = new StringMatcher<MarkdownNode>(
@"¯\_(ツ)_/¯", @"¯\_(ツ)_/¯",
p => new TextNode(p.ToString()) s => new TextNode(s.ToString())
); );
// Capture some specific emoji that don't get rendered // Capture some specific emoji that don't get rendered
@@ -323,24 +328,24 @@ internal static partial class MarkdownParser
UnixTimestampNodeMatcher UnixTimestampNodeMatcher
); );
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart, IMatcher<MarkdownNode> matcher) => private static IReadOnlyList<MarkdownNode> Parse(StringSegment segment, IMatcher<MarkdownNode> matcher) =>
matcher matcher
.MatchAll(stringPart, p => new TextNode(p.ToString())) .MatchAll(segment, s => new TextNode(s.ToString()))
.Select(r => r.Value) .Select(r => r.Value)
.ToArray(); .ToArray();
} }
internal static partial class MarkdownParser internal static partial class MarkdownParser
{ {
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart) => private static IReadOnlyList<MarkdownNode> Parse(StringSegment segment) =>
Parse(stringPart, AggregateNodeMatcher); Parse(segment, AggregateNodeMatcher);
private static IReadOnlyList<MarkdownNode> ParseMinimal(StringPart stringPart) => private static IReadOnlyList<MarkdownNode> ParseMinimal(StringSegment segment) =>
Parse(stringPart, MinimalAggregateNodeMatcher); Parse(segment, MinimalAggregateNodeMatcher);
public static IReadOnlyList<MarkdownNode> Parse(string input) => public static IReadOnlyList<MarkdownNode> Parse(string input) =>
Parse(new StringPart(input)); Parse(new StringSegment(input));
public static IReadOnlyList<MarkdownNode> ParseMinimal(string input) => public static IReadOnlyList<MarkdownNode> ParseMinimal(string input) =>
ParseMinimal(new StringPart(input)); ParseMinimal(new StringSegment(input));
} }
@@ -2,13 +2,13 @@
internal class ParsedMatch<T> internal class ParsedMatch<T>
{ {
public StringPart StringPart { get; } public StringSegment Segment { get; }
public T Value { get; } public T Value { get; }
public ParsedMatch(StringPart stringPart, T value) public ParsedMatch(StringSegment segment, T value)
{ {
StringPart = stringPart; Segment = segment;
Value = value; Value = value;
} }
} }
@@ -6,17 +6,17 @@ namespace DiscordChatExporter.Core.Markdown.Parsing;
internal class RegexMatcher<T> : IMatcher<T> internal class RegexMatcher<T> : IMatcher<T>
{ {
private readonly Regex _regex; private readonly Regex _regex;
private readonly Func<StringPart, Match, T?> _transform; private readonly Func<StringSegment, Match, T?> _transform;
public RegexMatcher(Regex regex, Func<StringPart, Match, T?> transform) public RegexMatcher(Regex regex, Func<StringSegment, Match, T?> transform)
{ {
_regex = regex; _regex = regex;
_transform = transform; _transform = transform;
} }
public ParsedMatch<T>? TryMatch(StringPart stringPart) public ParsedMatch<T>? TryMatch(StringSegment segment)
{ {
var match = _regex.Match(stringPart.Target, stringPart.StartIndex, stringPart.Length); var match = _regex.Match(segment.Source, segment.StartIndex, segment.Length);
if (!match.Success) if (!match.Success)
return null; return null;
@@ -25,14 +25,14 @@ internal class RegexMatcher<T> : IMatcher<T>
// Which is super weird because regex.Match(string, int) takes the whole input in context. // Which is super weird because regex.Match(string, int) takes the whole input in context.
// So in order to properly account for ^/$ regex tokens, we need to make sure that // So in order to properly account for ^/$ regex tokens, we need to make sure that
// the expression also matches on the bigger part of the input. // the expression also matches on the bigger part of the input.
if (!_regex.IsMatch(stringPart.Target[..stringPart.EndIndex], stringPart.StartIndex)) if (!_regex.IsMatch(segment.Source[..segment.EndIndex], segment.StartIndex))
return null; return null;
var stringPartMatch = stringPart.Slice(match.Index, match.Length); var segmentMatch = segment.Relocate(match);
var value = _transform(stringPartMatch, match); var value = _transform(segmentMatch, match);
return value is not null return value is not null
? new ParsedMatch<T>(stringPartMatch, value) ? new ParsedMatch<T>(segmentMatch, value)
: null; : null;
} }
} }
@@ -6,31 +6,31 @@ internal class StringMatcher<T> : IMatcher<T>
{ {
private readonly string _needle; private readonly string _needle;
private readonly StringComparison _comparison; private readonly StringComparison _comparison;
private readonly Func<StringPart, T?> _transform; private readonly Func<StringSegment, T?> _transform;
public StringMatcher(string needle, StringComparison comparison, Func<StringPart, T?> transform) public StringMatcher(string needle, StringComparison comparison, Func<StringSegment, T?> transform)
{ {
_needle = needle; _needle = needle;
_comparison = comparison; _comparison = comparison;
_transform = transform; _transform = transform;
} }
public StringMatcher(string needle, Func<StringPart, T> transform) public StringMatcher(string needle, Func<StringSegment, T> transform)
: this(needle, StringComparison.Ordinal, transform) : this(needle, StringComparison.Ordinal, transform)
{ {
} }
public ParsedMatch<T>? TryMatch(StringPart stringPart) public ParsedMatch<T>? TryMatch(StringSegment segment)
{ {
var index = stringPart.Target.IndexOf(_needle, stringPart.StartIndex, stringPart.Length, _comparison); var index = segment.Source.IndexOf(_needle, segment.StartIndex, segment.Length, _comparison);
if (index < 0) if (index < 0)
return null; return null;
var stringPartMatch = stringPart.Slice(index, _needle.Length); var segmentMatch = segment.Relocate(index, _needle.Length);
var value = _transform(stringPartMatch); var value = _transform(segmentMatch);
return value is not null return value is not null
? new ParsedMatch<T>(stringPartMatch, value) ? new ParsedMatch<T>(segmentMatch, value)
: null; : null;
} }
} }
@@ -1,21 +0,0 @@
using System.Text.RegularExpressions;
namespace DiscordChatExporter.Core.Markdown.Parsing;
internal readonly record struct StringPart(string Target, int StartIndex, int Length)
{
public int EndIndex => StartIndex + Length;
public StringPart(string target)
: this(target, 0, target.Length)
{
}
public StringPart Slice(int newStartIndex, int newLength) => new(Target, newStartIndex, newLength);
public StringPart Slice(int newStartIndex) => Slice(newStartIndex, EndIndex - newStartIndex);
public StringPart Slice(Capture capture) => Slice(capture.Index, capture.Length);
public override string ToString() => Target.Substring(StartIndex, Length);
}
@@ -0,0 +1,19 @@
using System.Text.RegularExpressions;
namespace DiscordChatExporter.Core.Markdown.Parsing;
internal readonly record struct StringSegment(string Source, int StartIndex, int Length)
{
public int EndIndex => StartIndex + Length;
public StringSegment(string target)
: this(target, 0, target.Length)
{
}
public StringSegment Relocate(int newStartIndex, int newLength) => new(Source, newStartIndex, newLength);
public StringSegment Relocate(Capture capture) => Relocate(capture.Index, capture.Length);
public override string ToString() => Source.Substring(StartIndex, Length);
}
@@ -2,5 +2,5 @@
namespace DiscordChatExporter.Core.Markdown; namespace DiscordChatExporter.Core.Markdown;
// Null means invalid date // Null date means invalid timestamp
internal record UnixTimestampNode(DateTimeOffset? Date) : MarkdownNode; internal record UnixTimestampNode(DateTimeOffset? Date) : MarkdownNode;
@@ -13,7 +13,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gress" Version="1.2.0" /> <PackageReference Include="Gress" Version="2.0.1" />
<PackageReference Include="MaterialDesignColors" Version="2.0.4" /> <PackageReference Include="MaterialDesignColors" Version="2.0.4" />
<PackageReference Include="MaterialDesignThemes" Version="4.3.0" /> <PackageReference Include="MaterialDesignThemes" Version="4.3.0" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" /> <PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
@@ -22,7 +22,7 @@
<PackageReference Include="Stylet" Version="1.3.6" /> <PackageReference Include="Stylet" Version="1.3.6" />
<PackageReference Include="Tyrrrz.Settings" Version="1.3.4" /> <PackageReference Include="Tyrrrz.Settings" Version="1.3.4" />
<PackageReference Include="PropertyChanged.Fody" Version="3.4.0" PrivateAssets="all" /> <PackageReference Include="PropertyChanged.Fody" Version="3.4.0" PrivateAssets="all" />
<PackageReference Include="DotnetRuntimeBootstrapper" Version="2.0.3" PrivateAssets="all" /> <PackageReference Include="DotnetRuntimeBootstrapper" Version="2.2.0" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -1,13 +1,14 @@
using DiscordChatExporter.Core.Exporting; using DiscordChatExporter.Core.Exporting;
using Microsoft.Win32;
using Tyrrrz.Settings; using Tyrrrz.Settings;
namespace DiscordChatExporter.Gui.Services; namespace DiscordChatExporter.Gui.Services;
public class SettingsService : SettingsManager public partial class SettingsService : SettingsManager
{ {
public bool IsAutoUpdateEnabled { get; set; } = true; public bool IsAutoUpdateEnabled { get; set; } = true;
public bool IsDarkModeEnabled { get; set; } public bool IsDarkModeEnabled { get; set; } = IsDarkModeEnabledByDefault();
public bool IsTokenPersisted { get; set; } = true; public bool IsTokenPersisted { get; set; } = true;
@@ -35,4 +36,21 @@ public class SettingsService : SettingsManager
} }
public bool ShouldSerializeLastToken() => IsTokenPersisted; public bool ShouldSerializeLastToken() => IsTokenPersisted;
}
public partial class SettingsService
{
private static bool IsDarkModeEnabledByDefault()
{
try
{
return Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", false
)?.GetValue("AppsUseLightTheme") is 0;
}
catch
{
return false;
}
}
} }
@@ -0,0 +1,10 @@
using System.Globalization;
namespace DiscordChatExporter.Gui.Utils;
internal static class Internationalization
{
public static bool Is24Hours =>
string.IsNullOrWhiteSpace(CultureInfo.CurrentCulture.DateTimeFormat.AMDesignator) &&
string.IsNullOrWhiteSpace(CultureInfo.CurrentCulture.DateTimeFormat.PMDesignator);
}
@@ -13,6 +13,7 @@ using DiscordChatExporter.Gui.Utils;
using DiscordChatExporter.Gui.ViewModels.Dialogs; using DiscordChatExporter.Gui.ViewModels.Dialogs;
using DiscordChatExporter.Gui.ViewModels.Framework; using DiscordChatExporter.Gui.ViewModels.Framework;
using Gress; using Gress;
using Gress.Completable;
using MaterialDesignThemes.Wpf; using MaterialDesignThemes.Wpf;
using Stylet; using Stylet;
@@ -25,15 +26,17 @@ public class RootViewModel : Screen
private readonly SettingsService _settingsService; private readonly SettingsService _settingsService;
private readonly UpdateService _updateService; private readonly UpdateService _updateService;
private readonly AutoResetProgressMuxer _progressMuxer;
private DiscordClient? _discord; private DiscordClient? _discord;
public ISnackbarMessageQueue Notifications { get; } = new SnackbarMessageQueue(TimeSpan.FromSeconds(5));
public IProgressManager ProgressManager { get; } = new ProgressManager();
public bool IsBusy { get; private set; } public bool IsBusy { get; private set; }
public bool IsProgressIndeterminate { get; private set; } public ProgressContainer<Percentage> Progress { get; } = new();
public bool IsProgressIndeterminate => IsBusy && Progress.Current.Fraction is <= 0 or >= 1;
public SnackbarMessageQueue Notifications { get; } = new(TimeSpan.FromSeconds(5));
public string? Token { get; set; } public string? Token { get; set; }
@@ -60,20 +63,12 @@ public class RootViewModel : Screen
_settingsService = settingsService; _settingsService = settingsService;
_updateService = updateService; _updateService = updateService;
_progressMuxer = Progress.CreateMuxer().WithAutoReset();
DisplayName = $"{App.Name} v{App.VersionString}"; DisplayName = $"{App.Name} v{App.VersionString}";
// Update busy state when progress manager changes this.Bind(o => o.IsBusy, (_, _) => NotifyOfPropertyChange(() => IsProgressIndeterminate));
ProgressManager.Bind(o => o.IsActive, (_, _) => Progress.Bind(o => o.Current, (_, _) => NotifyOfPropertyChange(() => IsProgressIndeterminate));
IsBusy = ProgressManager.IsActive
);
ProgressManager.Bind(o => o.IsActive, (_, _) =>
IsProgressIndeterminate = ProgressManager.IsActive && ProgressManager.Progress is <= 0 or >= 1
);
ProgressManager.Bind(o => o.Progress, (_, _) =>
IsProgressIndeterminate = ProgressManager.IsActive && ProgressManager.Progress is <= 0 or >= 1
);
} }
private async ValueTask CheckForUpdatesAsync() private async ValueTask CheckForUpdatesAsync()
@@ -123,6 +118,19 @@ public class RootViewModel : Screen
App.SetLightTheme(); App.SetLightTheme();
} }
// War in Ukraine message
Notifications.Enqueue(
"⚠ UKRAINE IS AT WAR!",
"LEARN MORE & HELP", _ =>
{
ProcessEx.StartShellExecute("https://tyrrrz.me");
},
null,
true,
true,
TimeSpan.FromMinutes(1)
);
await CheckForUpdatesAsync(); await CheckForUpdatesAsync();
} }
@@ -147,7 +155,8 @@ public class RootViewModel : Screen
public async void PopulateGuildsAndChannels() public async void PopulateGuildsAndChannels()
{ {
using var operation = ProgressManager.CreateOperation(); IsBusy = true;
var progress = _progressMuxer.CreateInput();
try try
{ {
@@ -183,6 +192,11 @@ public class RootViewModel : Screen
await _dialogManager.ShowDialogAsync(dialog); await _dialogManager.ShowDialogAsync(dialog);
} }
finally
{
progress.ReportCompletion();
IsBusy = false;
}
} }
public bool CanExportChannels => public bool CanExportChannels =>
@@ -194,6 +208,8 @@ public class RootViewModel : Screen
public async void ExportChannels() public async void ExportChannels()
{ {
IsBusy = true;
try try
{ {
if (_discord is null || SelectedGuild is null || SelectedChannels is null || !SelectedChannels.Any()) if (_discord is null || SelectedGuild is null || SelectedChannels is null || !SelectedChannels.Any())
@@ -205,18 +221,22 @@ public class RootViewModel : Screen
var exporter = new ChannelExporter(_discord); var exporter = new ChannelExporter(_discord);
var operations = ProgressManager.CreateOperations(dialog.Channels!.Count); var progresses = Enumerable
.Range(0, dialog.Channels!.Count)
.Select(_ => _progressMuxer.CreateInput())
.ToArray();
var successfulExportCount = 0; var successfulExportCount = 0;
await Parallel.ForEachAsync( await Parallel.ForEachAsync(
dialog.Channels.Zip(operations), dialog.Channels.Zip(progresses),
new ParallelOptions new ParallelOptions
{ {
MaxDegreeOfParallelism = Math.Max(1, _settingsService.ParallelLimit) MaxDegreeOfParallelism = Math.Max(1, _settingsService.ParallelLimit)
}, },
async (tuple, cancellationToken) => async (tuple, cancellationToken) =>
{ {
var (channel, operation) = tuple; var (channel, progress) = tuple;
try try
{ {
@@ -234,7 +254,7 @@ public class RootViewModel : Screen
_settingsService.DateFormat _settingsService.DateFormat
); );
await exporter.ExportChannelAsync(request, operation, cancellationToken); await exporter.ExportChannelAsync(request, progress, cancellationToken);
Interlocked.Increment(ref successfulExportCount); Interlocked.Increment(ref successfulExportCount);
} }
@@ -244,7 +264,7 @@ public class RootViewModel : Screen
} }
finally finally
{ {
operation.Dispose(); progress.ReportCompletion();
} }
} }
); );
@@ -262,5 +282,9 @@ public class RootViewModel : Screen
await _dialogManager.ShowDialogAsync(dialog); await _dialogManager.ShowDialogAsync(dialog);
} }
finally
{
IsBusy = false;
}
} }
} }
@@ -1,17 +1,18 @@
<UserControl <UserControl
Style="{DynamicResource MaterialDesignRoot}"
Width="380"
d:DataContext="{d:DesignInstance Type=dialogs:ExportSetupViewModel}"
mc:Ignorable="d"
x:Class="DiscordChatExporter.Gui.Views.Dialogs.ExportSetupView" x:Class="DiscordChatExporter.Gui.Views.Dialogs.ExportSetupView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters" xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:dialogs="clr-namespace:DiscordChatExporter.Gui.ViewModels.Dialogs" xmlns:dialogs="clr-namespace:DiscordChatExporter.Gui.ViewModels.Dialogs"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:s="https://github.com/canton7/Stylet" xmlns:s="https://github.com/canton7/Stylet"
Width="380" xmlns:utils="clr-namespace:DiscordChatExporter.Gui.Utils"
d:DataContext="{d:DesignInstance Type=dialogs:ExportSetupViewModel}" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
Style="{DynamicResource MaterialDesignRoot}"
mc:Ignorable="d">
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
@@ -29,8 +30,8 @@
<!-- Guild icon --> <!-- Guild icon -->
<Ellipse <Ellipse
Grid.Column="0" Grid.Column="0"
Width="32" Height="32"
Height="32"> Width="32">
<Ellipse.Fill> <Ellipse.Fill>
<ImageBrush ImageSource="{Binding Guild.IconUrl}" /> <ImageBrush ImageSource="{Binding Guild.IconUrl}" />
</Ellipse.Fill> </Ellipse.Fill>
@@ -38,12 +39,12 @@
<!-- Placeholder (for multiple channels) --> <!-- Placeholder (for multiple channels) -->
<TextBlock <TextBlock
Grid.Column="1"
Margin="8,0,0,0"
VerticalAlignment="Center"
FontSize="19" FontSize="19"
FontWeight="Light" FontWeight="Light"
Grid.Column="1"
Margin="8,0,0,0"
TextTrimming="CharacterEllipsis" TextTrimming="CharacterEllipsis"
VerticalAlignment="Center"
Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}"> Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}">
<Run Text="{Binding Channels.Count, Mode=OneWay}" /> <Run Text="{Binding Channels.Count, Mode=OneWay}" />
<Run Text="channels selected" /> <Run Text="channels selected" />
@@ -51,12 +52,12 @@
<!-- Category and channel name (for single channel) --> <!-- Category and channel name (for single channel) -->
<TextBlock <TextBlock
Grid.Column="1"
Margin="8,0,0,0"
VerticalAlignment="Center"
FontSize="19" FontSize="19"
FontWeight="Light" FontWeight="Light"
Grid.Column="1"
Margin="8,0,0,0"
TextTrimming="CharacterEllipsis" TextTrimming="CharacterEllipsis"
VerticalAlignment="Center"
Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.Instance}}"> Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
<Run Text="{Binding Channels[0].Category.Name, Mode=OneWay}" ToolTip="{Binding Channels[0].Category.Name, Mode=OneWay}" /> <Run Text="{Binding Channels[0].Category.Name, Mode=OneWay}" ToolTip="{Binding Channels[0].Category.Name, Mode=OneWay}" />
<Run Text="/" /> <Run Text="/" />
@@ -68,21 +69,21 @@
</Grid> </Grid>
<Border <Border
Grid.Row="1"
Padding="0,8"
BorderBrush="{DynamicResource MaterialDesignDivider}" BorderBrush="{DynamicResource MaterialDesignDivider}"
BorderThickness="0,1"> BorderThickness="0,1"
Grid.Row="1"
Padding="0,8">
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"> <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<StackPanel> <StackPanel>
<!-- Format --> <!-- Format -->
<ComboBox <ComboBox
Margin="16,8"
materialDesign:HintAssist.Hint="Format"
materialDesign:HintAssist.IsFloating="True"
IsReadOnly="True" IsReadOnly="True"
ItemsSource="{Binding AvailableFormats}" ItemsSource="{Binding AvailableFormats}"
Margin="16,8"
SelectedItem="{Binding SelectedFormat}" SelectedItem="{Binding SelectedFormat}"
Style="{DynamicResource MaterialDesignOutlinedComboBox}"> Style="{DynamicResource MaterialDesignOutlinedComboBox}"
materialDesign:HintAssist.Hint="Format"
materialDesign:HintAssist.IsFloating="True">
<ComboBox.ItemTemplate> <ComboBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<TextBlock Text="{Binding Converter={x:Static converters:ExportFormatToStringConverter.Instance}}" /> <TextBlock Text="{Binding Converter={x:Static converters:ExportFormatToStringConverter.Instance}}" />
@@ -104,64 +105,66 @@
<RowDefinition Height="*" /> <RowDefinition Height="*" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<DatePicker <DatePicker
Grid.Row="0"
Grid.Column="0"
Margin="16,8,16,4"
materialDesign:HintAssist.Hint="After (date)"
materialDesign:HintAssist.IsFloating="True"
DisplayDateEnd="{Binding BeforeDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}" DisplayDateEnd="{Binding BeforeDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}"
Grid.Column="0"
Grid.Row="0"
Margin="16,8,16,4"
SelectedDate="{Binding AfterDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}" SelectedDate="{Binding AfterDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}"
Style="{DynamicResource MaterialDesignOutlinedDatePicker}" Style="{DynamicResource MaterialDesignOutlinedDatePicker}"
ToolTip="Only include messages sent after this date" /> ToolTip="Only include messages sent after this date"
materialDesign:HintAssist.Hint="After (date)"
materialDesign:HintAssist.IsFloating="True" />
<DatePicker <DatePicker
Grid.Row="0"
Grid.Column="1"
Margin="16,8,16,4"
materialDesign:HintAssist.Hint="Before (date)"
materialDesign:HintAssist.IsFloating="True"
DisplayDateStart="{Binding AfterDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}" DisplayDateStart="{Binding AfterDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}"
Grid.Column="1"
Grid.Row="0"
Margin="16,8,16,4"
SelectedDate="{Binding BeforeDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}" SelectedDate="{Binding BeforeDate, Converter={x:Static converters:DateTimeOffsetToDateTimeConverter.Instance}}"
Style="{DynamicResource MaterialDesignOutlinedDatePicker}" Style="{DynamicResource MaterialDesignOutlinedDatePicker}"
ToolTip="Only include messages sent before this date" /> ToolTip="Only include messages sent before this date"
materialDesign:HintAssist.Hint="Before (date)"
materialDesign:HintAssist.IsFloating="True" />
<materialDesign:TimePicker <materialDesign:TimePicker
Grid.Row="1"
Grid.Column="0" Grid.Column="0"
Margin="16,4,16,8" Grid.Row="1"
materialDesign:HintAssist.Hint="After (time)" Is24Hours="{x:Static utils:Internationalization.Is24Hours}"
materialDesign:HintAssist.IsFloating="True"
IsEnabled="{Binding IsAfterDateSet}" IsEnabled="{Binding IsAfterDateSet}"
Margin="16,4,16,8"
SelectedTime="{Binding AfterTime, Converter={x:Static converters:TimeSpanToDateTimeConverter.Instance}}" SelectedTime="{Binding AfterTime, Converter={x:Static converters:TimeSpanToDateTimeConverter.Instance}}"
Style="{DynamicResource MaterialDesignOutlinedTimePicker}" Style="{DynamicResource MaterialDesignOutlinedTimePicker}"
ToolTip="Only include messages sent after this time" /> ToolTip="Only include messages sent after this time"
materialDesign:HintAssist.Hint="After (time)"
materialDesign:HintAssist.IsFloating="True" />
<materialDesign:TimePicker <materialDesign:TimePicker
Grid.Row="1"
Grid.Column="1" Grid.Column="1"
Margin="16,4,16,8" Grid.Row="1"
materialDesign:HintAssist.Hint="Before (time)" Is24Hours="{x:Static utils:Internationalization.Is24Hours}"
materialDesign:HintAssist.IsFloating="True"
IsEnabled="{Binding IsBeforeDateSet}" IsEnabled="{Binding IsBeforeDateSet}"
Margin="16,4,16,8"
SelectedTime="{Binding BeforeTime, Converter={x:Static converters:TimeSpanToDateTimeConverter.Instance}}" SelectedTime="{Binding BeforeTime, Converter={x:Static converters:TimeSpanToDateTimeConverter.Instance}}"
Style="{DynamicResource MaterialDesignOutlinedTimePicker}" Style="{DynamicResource MaterialDesignOutlinedTimePicker}"
ToolTip="Only include messages sent before this time" /> ToolTip="Only include messages sent before this time"
materialDesign:HintAssist.Hint="Before (time)"
materialDesign:HintAssist.IsFloating="True" />
</Grid> </Grid>
<!-- Partitioning --> <!-- Partitioning -->
<TextBox <TextBox
Margin="16,8" Margin="16,8"
materialDesign:HintAssist.Hint="Partition limit"
materialDesign:HintAssist.IsFloating="True"
Style="{DynamicResource MaterialDesignOutlinedTextBox}" Style="{DynamicResource MaterialDesignOutlinedTextBox}"
Text="{Binding PartitionLimitValue}" Text="{Binding PartitionLimitValue}"
ToolTip="Split output into partitions, each limited to this number of messages (e.g. '100') or file size (e.g. '10mb')" /> ToolTip="Split output into partitions, each limited to this number of messages (e.g. '100') or file size (e.g. '10mb')"
materialDesign:HintAssist.Hint="Partition limit"
materialDesign:HintAssist.IsFloating="True" />
<!-- Filtering --> <!-- Filtering -->
<TextBox <TextBox
Margin="16,8" Margin="16,8"
materialDesign:HintAssist.Hint="Message filter"
materialDesign:HintAssist.IsFloating="True"
Style="{DynamicResource MaterialDesignOutlinedTextBox}" Style="{DynamicResource MaterialDesignOutlinedTextBox}"
Text="{Binding MessageFilterValue}" Text="{Binding MessageFilterValue}"
ToolTip="Only include messages that satisfy this filter (e.g. 'from:foo#1234' or 'has:image')." /> ToolTip="Only include messages that satisfy this filter (e.g. 'from:foo#1234' or 'has:image')."
materialDesign:HintAssist.Hint="Message filter"
materialDesign:HintAssist.IsFloating="True" />
<!-- Download media --> <!-- Download media -->
<Grid Margin="16,16" ToolTip="Download referenced media content (user avatars, attached files, embedded images, etc)"> <Grid Margin="16,16" ToolTip="Download referenced media content (user avatars, attached files, embedded images, etc)">
@@ -172,13 +175,13 @@
<TextBlock <TextBlock
Grid.Column="0" Grid.Column="0"
VerticalAlignment="Center" Text="Download media"
Text="Download media" /> VerticalAlignment="Center" />
<ToggleButton <ToggleButton
Grid.Column="1" Grid.Column="1"
HorizontalAlignment="Right" HorizontalAlignment="Right"
VerticalAlignment="Center" IsChecked="{Binding ShouldDownloadMedia}"
IsChecked="{Binding ShouldDownloadMedia}" /> VerticalAlignment="Center" />
</Grid> </Grid>
</StackPanel> </StackPanel>
</StackPanel> </StackPanel>
@@ -195,8 +198,8 @@
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Button <Button
Grid.Column="0"
Command="{s:Action ToggleAdvancedSection}" Command="{s:Action ToggleAdvancedSection}"
Grid.Column="0"
IsDefault="True" IsDefault="True"
ToolTip="Toggle advanced options"> ToolTip="Toggle advanced options">
<Button.Style> <Button.Style>
@@ -214,17 +217,17 @@
</Button> </Button>
<Button <Button
Grid.Column="2"
Command="{s:Action Confirm}" Command="{s:Action Confirm}"
Content="EXPORT" Content="EXPORT"
Grid.Column="2"
IsDefault="True" IsDefault="True"
Style="{DynamicResource MaterialDesignOutlinedButton}" /> Style="{DynamicResource MaterialDesignOutlinedButton}" />
<Button <Button
Grid.Column="3"
Margin="8,0,0,0"
Command="{s:Action Close}" Command="{s:Action Close}"
Content="CANCEL" Content="CANCEL"
Grid.Column="3"
IsCancel="True" IsCancel="True"
Margin="8,0,0,0"
Style="{DynamicResource MaterialDesignOutlinedButton}" /> Style="{DynamicResource MaterialDesignOutlinedButton}" />
</Grid> </Grid>
</Grid> </Grid>
+63 -63
View File
@@ -1,7 +1,16 @@
<Window <Window
Background="{DynamicResource MaterialDesignPaper}"
FocusManager.FocusedElement="{Binding ElementName=TokenValueTextBox}"
Height="550"
Icon="/DiscordChatExporter;component/favicon.ico"
MinWidth="325"
Style="{DynamicResource MaterialDesignRoot}"
Width="600"
WindowStartupLocation="CenterScreen"
d:DataContext="{d:DesignInstance Type=viewModels:RootViewModel}"
mc:Ignorable="d"
x:Class="DiscordChatExporter.Gui.Views.RootView" x:Class="DiscordChatExporter.Gui.Views.RootView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behaviors="clr-namespace:DiscordChatExporter.Gui.Behaviors" xmlns:behaviors="clr-namespace:DiscordChatExporter.Gui.Behaviors"
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase" xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters" xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters"
@@ -11,21 +20,12 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:s="https://github.com/canton7/Stylet" xmlns:s="https://github.com/canton7/Stylet"
xmlns:viewModels="clr-namespace:DiscordChatExporter.Gui.ViewModels" xmlns:viewModels="clr-namespace:DiscordChatExporter.Gui.ViewModels"
Width="600" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
Height="550"
MinWidth="325"
d:DataContext="{d:DesignInstance Type=viewModels:RootViewModel}"
Background="{DynamicResource MaterialDesignPaper}"
FocusManager.FocusedElement="{Binding ElementName=TokenValueTextBox}"
Icon="/DiscordChatExporter;component/favicon.ico"
Style="{DynamicResource MaterialDesignRoot}"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d">
<Window.TaskbarItemInfo> <Window.TaskbarItemInfo>
<TaskbarItemInfo ProgressState="Normal" ProgressValue="{Binding ProgressManager.Progress}" /> <TaskbarItemInfo ProgressState="Normal" ProgressValue="{Binding Progress.Current.Fraction}" />
</Window.TaskbarItemInfo> </Window.TaskbarItemInfo>
<Window.Resources> <Window.Resources>
<CollectionViewSource x:Key="AvailableChannelsViewSource" Source="{Binding AvailableChannels, Mode=OneWay}"> <CollectionViewSource Source="{Binding AvailableChannels, Mode=OneWay}" x:Key="AvailableChannelsViewSource">
<CollectionViewSource.GroupDescriptions> <CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Category.Name" /> <PropertyGroupDescription PropertyName="Category.Name" />
</CollectionViewSource.GroupDescriptions> </CollectionViewSource.GroupDescriptions>
@@ -46,7 +46,7 @@
</Grid.RowDefinitions> </Grid.RowDefinitions>
<!-- Toolbar --> <!-- Toolbar -->
<Grid Grid.Row="0" Background="{DynamicResource MaterialDesignDarkBackground}"> <Grid Background="{DynamicResource MaterialDesignDarkBackground}" Grid.Row="0">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
@@ -54,8 +54,8 @@
<!-- Token and pull data button --> <!-- Token and pull data button -->
<materialDesign:Card <materialDesign:Card
Grid.Row="0"
Grid.Column="0" Grid.Column="0"
Grid.Row="0"
Margin="12,12,0,12"> Margin="12,12,0,12">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -66,74 +66,74 @@
<!-- Token icon --> <!-- Token icon -->
<materialDesign:PackIcon <materialDesign:PackIcon
Foreground="{DynamicResource PrimaryHueMidBrush}"
Grid.Column="0" Grid.Column="0"
Width="24"
Height="24" Height="24"
Kind="Password"
Margin="8" Margin="8"
VerticalAlignment="Center" VerticalAlignment="Center"
Foreground="{DynamicResource PrimaryHueMidBrush}" Width="24" />
Kind="Password" />
<!-- Token value --> <!-- Token value -->
<TextBox <TextBox
x:Name="TokenValueTextBox" BorderThickness="0"
FontSize="16"
Grid.Column="1" Grid.Column="1"
Margin="0,6,6,8" Margin="0,6,6,8"
Text="{Binding Token, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Bottom" VerticalAlignment="Bottom"
materialDesign:HintAssist.Hint="Token" materialDesign:HintAssist.Hint="Token"
materialDesign:TextFieldAssist.DecorationVisibility="Hidden" materialDesign:TextFieldAssist.DecorationVisibility="Hidden"
materialDesign:TextFieldAssist.TextBoxViewMargin="0,0,2,0" materialDesign:TextFieldAssist.TextBoxViewMargin="0,0,2,0"
BorderThickness="0" x:Name="TokenValueTextBox" />
FontSize="16"
Text="{Binding Token, UpdateSourceTrigger=PropertyChanged}" />
<!-- Pull data button --> <!-- Pull data button -->
<Button <Button
Command="{s:Action PopulateGuildsAndChannels}"
Grid.Column="2" Grid.Column="2"
IsDefault="True"
Margin="0,6,6,6" Margin="0,6,6,6"
Padding="4" Padding="4"
Command="{s:Action PopulateGuildsAndChannels}"
IsDefault="True"
Style="{DynamicResource MaterialDesignFlatButton}" Style="{DynamicResource MaterialDesignFlatButton}"
ToolTip="Pull available guilds and channels (Enter)"> ToolTip="Pull available guilds and channels (Enter)">
<materialDesign:PackIcon <materialDesign:PackIcon
Width="24"
Height="24" Height="24"
Kind="ArrowRight" /> Kind="ArrowRight"
Width="24" />
</Button> </Button>
</Grid> </Grid>
</materialDesign:Card> </materialDesign:Card>
<!-- Settings button --> <!-- Settings button -->
<Button <Button
Command="{s:Action ShowSettings}"
Foreground="{DynamicResource MaterialDesignDarkForeground}"
Grid.Column="1" Grid.Column="1"
Margin="6" Margin="6"
Padding="4" Padding="4"
Command="{s:Action ShowSettings}"
Foreground="{DynamicResource MaterialDesignDarkForeground}"
Style="{DynamicResource MaterialDesignFlatButton}" Style="{DynamicResource MaterialDesignFlatButton}"
ToolTip="Settings"> ToolTip="Settings">
<Button.Resources> <Button.Resources>
<SolidColorBrush x:Key="MaterialDesignFlatButtonClick" Color="#4C4C4C" /> <SolidColorBrush Color="#4C4C4C" x:Key="MaterialDesignFlatButtonClick" />
</Button.Resources> </Button.Resources>
<materialDesign:PackIcon <materialDesign:PackIcon
Width="24"
Height="24" Height="24"
Kind="Settings" /> Kind="Settings"
Width="24" />
</Button> </Button>
</Grid> </Grid>
<!-- Progress bar --> <!-- Progress bar -->
<ProgressBar <ProgressBar
Grid.Row="1"
Background="{DynamicResource MaterialDesignDarkBackground}" Background="{DynamicResource MaterialDesignDarkBackground}"
Grid.Row="1"
IsIndeterminate="{Binding IsProgressIndeterminate}" IsIndeterminate="{Binding IsProgressIndeterminate}"
Value="{Binding ProgressManager.Progress, Mode=OneWay}" /> Value="{Binding Progress.Current.Fraction, Mode=OneWay}" />
<!-- Content --> <!-- Content -->
<Grid <Grid
Grid.Row="2"
Background="{DynamicResource MaterialDesignCardBackground}" Background="{DynamicResource MaterialDesignCardBackground}"
Grid.Row="2"
IsEnabled="{Binding IsBusy, Converter={x:Static converters:InverseBoolConverter.Instance}}"> IsEnabled="{Binding IsBusy, Converter={x:Static converters:InverseBoolConverter.Instance}}">
<Grid.Resources> <Grid.Resources>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -143,7 +143,7 @@
<!-- Placeholder / usage instructions --> <!-- Placeholder / usage instructions -->
<Grid Visibility="{Binding AvailableGuilds, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}"> <Grid Visibility="{Binding AvailableGuilds, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}">
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"> <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<TextBlock Margin="32,16" FontSize="14"> <TextBlock FontSize="14" Margin="32,16">
<Run FontSize="18" Text="Please provide authentication token to continue" /> <Run FontSize="18" Text="Please provide authentication token to continue" />
<LineBreak /> <LineBreak />
<LineBreak /> <LineBreak />
@@ -151,9 +151,9 @@
<!-- User token --> <!-- User token -->
<InlineUIContainer> <InlineUIContainer>
<materialDesign:PackIcon <materialDesign:PackIcon
Margin="1,0,0,-2"
Foreground="{DynamicResource PrimaryHueMidBrush}" Foreground="{DynamicResource PrimaryHueMidBrush}"
Kind="Account" /> Kind="Account"
Margin="1,0,0,-2" />
</InlineUIContainer> </InlineUIContainer>
<Run FontSize="16" Text="Authenticate using your personal account" /> <Run FontSize="16" Text="Authenticate using your personal account" />
<LineBreak /> <LineBreak />
@@ -199,9 +199,9 @@
<!-- Bot token --> <!-- Bot token -->
<InlineUIContainer> <InlineUIContainer>
<materialDesign:PackIcon <materialDesign:PackIcon
Margin="1,0,0,-2"
Foreground="{DynamicResource PrimaryHueMidBrush}" Foreground="{DynamicResource PrimaryHueMidBrush}"
Kind="Robot" /> Kind="Robot"
Margin="1,0,0,-2" />
</InlineUIContainer> </InlineUIContainer>
<Run FontSize="16" Text="Authenticate as a bot" /> <Run FontSize="16" Text="Authenticate as a bot" />
<LineBreak /> <LineBreak />
@@ -235,9 +235,9 @@
<!-- Guilds --> <!-- Guilds -->
<Border <Border
Grid.Column="0"
BorderBrush="{DynamicResource MaterialDesignDivider}" BorderBrush="{DynamicResource MaterialDesignDivider}"
BorderThickness="0,0,1,0"> BorderThickness="0,0,1,0"
Grid.Column="0">
<ListBox <ListBox
ItemsSource="{Binding AvailableGuilds}" ItemsSource="{Binding AvailableGuilds}"
ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden"
@@ -246,24 +246,24 @@
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<Grid <Grid
Margin="-8"
Background="Transparent" Background="Transparent"
Cursor="Hand" Cursor="Hand"
Margin="-8"
ToolTip="{Binding Name}"> ToolTip="{Binding Name}">
<!-- Guild icon placeholder --> <!-- Guild icon placeholder -->
<Ellipse <Ellipse
Width="48" Fill="{DynamicResource MaterialDesignDivider}"
Height="48" Height="48"
Margin="12,4,12,4" Margin="12,4,12,4"
Fill="{DynamicResource MaterialDesignDivider}" /> Width="48" />
<!-- Guild icon --> <!-- Guild icon -->
<Ellipse <Ellipse
Width="48"
Height="48" Height="48"
Margin="12,4,12,4" Margin="12,4,12,4"
Stroke="{DynamicResource MaterialDesignDivider}" Stroke="{DynamicResource MaterialDesignDivider}"
StrokeThickness="1"> StrokeThickness="1"
Width="48">
<Ellipse.Fill> <Ellipse.Fill>
<ImageBrush ImageSource="{Binding IconUrl}" /> <ImageBrush ImageSource="{Binding IconUrl}" />
</Ellipse.Fill> </Ellipse.Fill>
@@ -293,13 +293,13 @@
<Setter.Value> <Setter.Value>
<ControlTemplate d:DataContext="{x:Type CollectionViewGroup}"> <ControlTemplate d:DataContext="{x:Type CollectionViewGroup}">
<Expander <Expander
Margin="0"
Padding="0"
Background="Transparent" Background="Transparent"
BorderBrush="{DynamicResource MaterialDesignDivider}" BorderBrush="{DynamicResource MaterialDesignDivider}"
BorderThickness="0,0,0,1" BorderThickness="0,0,0,1"
Header="{Binding Name}" Header="{Binding Name}"
IsExpanded="False"> IsExpanded="False"
Margin="0"
Padding="0">
<ItemsPresenter /> <ItemsPresenter />
</Expander> </Expander>
</ControlTemplate> </ControlTemplate>
@@ -311,7 +311,7 @@
</ListBox.GroupStyle> </ListBox.GroupStyle>
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<Grid Margin="-8" Background="Transparent"> <Grid Background="Transparent" Margin="-8">
<Grid.InputBindings> <Grid.InputBindings>
<MouseBinding Command="{s:Action ExportChannels}" MouseAction="LeftDoubleClick" /> <MouseBinding Command="{s:Action ExportChannels}" MouseAction="LeftDoubleClick" />
</Grid.InputBindings> </Grid.InputBindings>
@@ -324,27 +324,27 @@
<!-- Channel icon --> <!-- Channel icon -->
<materialDesign:PackIcon <materialDesign:PackIcon
Grid.Column="0" Grid.Column="0"
Kind="Pound"
Margin="16,7,0,6" Margin="16,7,0,6"
VerticalAlignment="Center" VerticalAlignment="Center" />
Kind="Pound" />
<!-- Channel name --> <!-- Channel name -->
<TextBlock <TextBlock
FontSize="14"
Grid.Column="1" Grid.Column="1"
Margin="3,8,8,8" Margin="3,8,8,8"
VerticalAlignment="Center" Text="{Binding Name, Mode=OneWay}"
FontSize="14" VerticalAlignment="Center" />
Text="{Binding Name, Mode=OneWay}" />
<!-- Is selected checkmark --> <!-- Is selected checkmark -->
<materialDesign:PackIcon <materialDesign:PackIcon
Grid.Column="2" Grid.Column="2"
Width="24"
Height="24" Height="24"
Kind="Check"
Margin="8,0" Margin="8,0"
VerticalAlignment="Center" VerticalAlignment="Center"
Kind="Check" Visibility="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Converter={x:Static s:BoolToVisibilityConverter.Instance}, Mode=OneWay}"
Visibility="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Converter={x:Static s:BoolToVisibilityConverter.Instance}, Mode=OneWay}" /> Width="24" />
</Grid> </Grid>
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
@@ -354,16 +354,16 @@
<!-- Export button --> <!-- Export button -->
<Button <Button
Margin="32,24"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Command="{s:Action ExportChannels}" Command="{s:Action ExportChannels}"
HorizontalAlignment="Right"
Margin="32,24"
Style="{DynamicResource MaterialDesignFloatingActionAccentButton}" Style="{DynamicResource MaterialDesignFloatingActionAccentButton}"
VerticalAlignment="Bottom"
Visibility="{Binding CanExportChannels, Converter={x:Static s:BoolToVisibilityConverter.Instance}}"> Visibility="{Binding CanExportChannels, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
<materialDesign:PackIcon <materialDesign:PackIcon
Width="32"
Height="32" Height="32"
Kind="Download" /> Kind="Download"
Width="32" />
</Button> </Button>
<!-- Notifications snackbar --> <!-- Notifications snackbar -->
+14 -4
View File
@@ -6,15 +6,25 @@
[![Downloads](https://img.shields.io/github/downloads/Tyrrrz/DiscordChatExporter/total.svg)](https://github.com/Tyrrrz/DiscordChatExporter/releases) [![Downloads](https://img.shields.io/github/downloads/Tyrrrz/DiscordChatExporter/total.svg)](https://github.com/Tyrrrz/DiscordChatExporter/releases)
[![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm) [![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm)
[![Donate](https://img.shields.io/badge/donate-$$$-purple.svg)](https://tyrrrz.me/donate) [![Donate](https://img.shields.io/badge/donate-$$$-purple.svg)](https://tyrrrz.me/donate)
[![Fuck Russia](https://img.shields.io/badge/fuck-russia-black.svg)](https://twitter.com/Tyrrrz/status/1495972128977571848)
**Project status: active**. [What does it mean?](https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md) **Project status: active**<sup>[[?]](https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md)</sup>
**DiscordChatExporter** can be used to export message history from a [Discord](https://discord.com) channel to a file. **DiscordChatExporter** can be used to export message history from a [Discord](https://discord.com) channel to a file.
It works with direct messages, group messages, and server channels, and supports Discord's dialect of markdown as well as all other rich media features. It works with direct messages, group messages, and server channels, and supports Discord's dialect of markdown as well as all other rich media features.
**If you have questions or issues, please refer to the [wiki](https://github.com/Tyrrrz/DiscordChatExporter/wiki)**. **If you have questions or issues, please refer to the [wiki](https://github.com/Tyrrrz/DiscordChatExporter/wiki)**
💬 **If you want to chat, join my [Discord server](https://discord.gg/2SUWKFnHSm)**. ## Terms of use
By using this project or its source code, for any purpose and in any shape or form, you grant your **implicit agreement** to all the following statements:
- You **condemn Russia and its military aggression against Ukraine**
- You **recognize that Russia is an occupant that unlawfully invaded a sovereign state**
- You **support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas**
- You **reject false narratives perpetuated by Russian state propaganda**
To learn more about the war and how you can help, [click here](https://tyrrrz.me). Glory to Ukraine! 🇺🇦
## Download ## Download
@@ -115,4 +125,4 @@ To do that, navigate to its directory and use `dotnet run`:
```sh ```sh
> cd DiscordChatExporter.Gui > cd DiscordChatExporter.Gui
> dotnet run > dotnet run
``` ```