Compare commits

..

18 Commits

Author SHA1 Message Date
Alexey Golub dbf15c7bee Update version 2020-03-26 23:32:51 +02:00
Alexey Golub a41a4ca8a7 [HTML] Fix occasionally wrong user colors 2020-03-26 23:32:41 +02:00
Alexey Golub c098f4b137 [HTML] Use nicknames when rendering mentions 2020-03-26 23:22:21 +02:00
Alexey Golub ff15257d23 Fix bugs in previous PR 2020-03-26 22:59:36 +02:00
Will Kennedy 79e43c4144 Add support for Guild Member object & included data (#279) 2020-03-26 14:36:55 +02:00
Alexey Golub 7bb8038ce9 Revert "[GUI] Publish as 32-bit for maximum compatibility"
This reverts commit ee27167998.
2020-03-26 14:02:13 +02:00
Alexey Golub ee27167998 [GUI] Publish as 32-bit for maximum compatibility
Closes #243
2020-03-25 22:25:24 +02:00
Alexey Golub 9f4277ae84 Add parallel exporting
Closes #264
2020-03-25 19:22:33 +02:00
Alexey Golub 70a1c9db8c Clean up warnings 2020-03-23 19:11:15 +02:00
Will Kennedy 378f0a20db [HTML] Update CSS for mentions (#278) 2020-03-14 14:21:53 +02:00
Alexey Golub a24fe3906c Update GitHub Actions workflows 2020-02-16 20:33:30 +02:00
Alexey Golub eececb6701 Update version 2020-02-04 14:05:44 +02:00
Alexey Golub d3adf19500 Simplify display text for export formats 2020-02-04 14:04:26 +02:00
Alexey Golub a01835efb6 [CLI] Cleanup 2020-02-04 12:14:53 +02:00
Alexey Golub 1d39fe9c53 Update readme 2020-02-03 18:10:06 +02:00
Alexey Golub 9f6090b3af Add JSON message writer
Closes #103
2020-02-03 17:47:42 +02:00
Alexey Golub 9fa40dca00 Add text search in the channel list
Closes #184
2020-02-03 14:18:27 +02:00
Alexey Golub 8a4f306012 Update CliFx to v1.0 2020-01-30 16:34:36 +02:00
47 changed files with 671 additions and 221 deletions
+5 -5
View File
@@ -11,10 +11,10 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v1
uses: actions/checkout@v2
- name: Install .NET Core
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v1.4.0
with:
dotnet-version: 3.1.100
@@ -34,7 +34,7 @@ jobs:
- name: Create release
id: create_release
uses: actions/create-release@v1
uses: actions/create-release@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -46,7 +46,7 @@ jobs:
prerelease: false
- name: Upload release asset (CLI)
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1.0.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -56,7 +56,7 @@ jobs:
asset_content_type: application/zip
- name: Upload release asset (GUI)
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1.0.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
+4 -4
View File
@@ -8,10 +8,10 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v1
uses: actions/checkout@v2
- name: Install .NET Core
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v1.4.0
with:
dotnet-version: 3.1.100
@@ -22,13 +22,13 @@ jobs:
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
- name: Upload build artifacts (CLI)
uses: actions/upload-artifact@master
uses: actions/upload-artifact@v1
with:
name: DiscordChatExporter.CLI
path: DiscordChatExporter.Cli/bin/Publish/
- name: Upload build artifact (GUI)
uses: actions/upload-artifact@master
uses: actions/upload-artifact@v1
with:
name: DiscordChatExporter
path: DiscordChatExporter.Gui/bin/Publish/
+13
View File
@@ -1,3 +1,16 @@
### v2.19 (26-Mar-2020)
- Added parallel exporting. This option allows you to export multiple channels faster by doing it in parallel. You can configure the parallel limit in settings (GUI) or with the `--parallel` option (CLI). Default value is `1`, which means there is no parallelization. Warning: be careful when using this option, as this will result in higher volume of concurrent HTTP requests sent to Discord, which might get you flagged. Use at your own risk.
- [HTML] Added support for user colors. User names are now appropriately colored according to the assigned guild roles.
- [HTML] Added support for nicknames. User names are replaced with nicknames where it's applicable. It's still possible to see the full user name by hovering your mouse over the nickname.
- [HTML] Improved styling for mentions to bring it more in line with how it looks in Discord.
### v2.18 (04-Feb-2020)
- Added JSON export format. It's a structured data format which is easy to parse. If you're using DiscordChatExporter to export chat logs for further ingestion by another tool, this is most likely the format you will want to use.
- [GUI] You can now quickly jump to a specific channel in a list. For example, if you want to jump to a channel named "General", you can simply press the 'g' key in the channel list view. You can also press 'g', 'e' and 'n' in quick succession which will jump to the next channel that starts with "gen". This mechanic is consistent with other Windows applications.
- [CLI] Improved help text screen.
### v2.17 (12-Jan-2020)
- Fixed an issue where an empty file was produced when exporting a channel with no messages (for specified period). With the new behavior, no file will be created and instead a message will be shown to the user informing of the failure.
@@ -1,6 +1,6 @@
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Services;
namespace DiscordChatExporter.Cli.Commands
@@ -8,14 +8,14 @@ namespace DiscordChatExporter.Cli.Commands
[Command("export", Description = "Export a channel.")]
public class ExportChannelCommand : ExportCommandBase
{
[CommandOption("channel", 'c', IsRequired = true, Description= "Channel ID.")]
public string ChannelId { get; set; }
[CommandOption("channel", 'c', IsRequired = true, Description = "Channel ID.")]
public string ChannelId { get; set; } = "";
public ExportChannelCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
: base(settingsService, dataService, exportService)
{
}
public override async Task ExecuteAsync(IConsole console) => await ExportAsync(console, ChannelId);
public override async ValueTask ExecuteAsync(IConsole console) => await ExportAsync(console, ChannelId);
}
}
@@ -1,8 +1,8 @@
using System;
using System.IO;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using CliFx.Utilities;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Services;
@@ -19,7 +19,7 @@ namespace DiscordChatExporter.Cli.Commands
public ExportFormat ExportFormat { get; set; } = ExportFormat.HtmlDark;
[CommandOption("output", 'o', Description = "Output file or directory path.")]
public string? OutputPath { get; set; }
public string OutputPath { get; set; } = Directory.GetCurrentDirectory();
[CommandOption("after", Description = "Limit to messages sent after this date.")]
public DateTimeOffset? After { get; set; }
@@ -40,7 +40,7 @@ namespace DiscordChatExporter.Cli.Commands
ExportService = exportService;
}
protected async Task ExportAsync(IConsole console, Guild guild, Channel channel)
protected async ValueTask ExportAsync(IConsole console, Guild guild, Channel channel)
{
if (!string.IsNullOrWhiteSpace(DateFormat))
SettingsService.DateFormat = DateFormat;
@@ -48,23 +48,23 @@ namespace DiscordChatExporter.Cli.Commands
console.Output.Write($"Exporting channel [{channel.Name}]... ");
var progress = console.CreateProgressTicker();
var outputPath = OutputPath ?? Directory.GetCurrentDirectory();
await ExportService.ExportChatLogAsync(GetToken(), guild, channel,
outputPath, ExportFormat, PartitionLimit,
await ExportService.ExportChatLogAsync(Token, guild, channel,
OutputPath, ExportFormat, PartitionLimit,
After, Before, progress);
console.Output.WriteLine();
console.Output.WriteLine("Done.");
}
protected async Task ExportAsync(IConsole console, Channel channel)
protected async ValueTask ExportAsync(IConsole console, Channel channel)
{
var guild = await DataService.GetGuildAsync(GetToken(), channel.GuildId);
var guild = await DataService.GetGuildAsync(Token, channel.GuildId);
await ExportAsync(console, guild, channel);
}
protected async Task ExportAsync(IConsole console, string channelId)
protected async ValueTask ExportAsync(IConsole console, string channelId)
{
var channel = await DataService.GetChannelAsync(GetToken(), channelId);
var channel = await DataService.GetChannelAsync(Token, channelId);
await ExportAsync(console, channel);
}
}
@@ -1,50 +1,25 @@
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Models.Exceptions;
using DiscordChatExporter.Core.Services;
using DiscordChatExporter.Core.Services.Exceptions;
namespace DiscordChatExporter.Cli.Commands
{
[Command("exportdm", Description = "Export all direct message channels.")]
public class ExportDirectMessagesCommand : ExportCommandBase
public class ExportDirectMessagesCommand : ExportMultipleCommandBase
{
public ExportDirectMessagesCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
: base(settingsService, dataService, exportService)
{
}
public override async Task ExecuteAsync(IConsole console)
public override async ValueTask ExecuteAsync(IConsole console)
{
// Get channels
var channels = await DataService.GetDirectMessageChannelsAsync(GetToken());
var directMessageChannels = await DataService.GetDirectMessageChannelsAsync(Token);
var channels = directMessageChannels.OrderBy(c => c.Name).ToArray();
// Order channels
channels = channels.OrderBy(c => c.Name).ToArray();
// Loop through channels
foreach (var channel in channels)
{
try
{
await ExportAsync(console, channel);
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
{
console.Error.WriteLine("You don't have access to this channel.");
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
console.Error.WriteLine("This channel doesn't exist.");
}
catch (DomainException ex)
{
console.Error.WriteLine(ex.Message);
}
}
await ExportMultipleAsync(console, channels);
}
}
}
@@ -1,54 +1,33 @@
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Models.Exceptions;
using DiscordChatExporter.Core.Services;
using DiscordChatExporter.Core.Services.Exceptions;
namespace DiscordChatExporter.Cli.Commands
{
[Command("exportguild", Description = "Export all channels within specified guild.")]
public class ExportGuildCommand : ExportCommandBase
public class ExportGuildCommand : ExportMultipleCommandBase
{
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
public string GuildId { get; set; }
public string GuildId { get; set; } = "";
public ExportGuildCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
: base(settingsService, dataService, exportService)
{
}
public override async Task ExecuteAsync(IConsole console)
public override async ValueTask ExecuteAsync(IConsole console)
{
// Get channels
var channels = await DataService.GetGuildChannelsAsync(GetToken(), GuildId);
var guildChannels = await DataService.GetGuildChannelsAsync(Token, GuildId);
// Filter and order channels
channels = channels.Where(c => c.Type.IsExportable()).OrderBy(c => c.Name).ToArray();
var channels = guildChannels
.Where(c => c.Type.IsExportable())
.OrderBy(c => c.Name)
.ToArray();
// Loop through channels
foreach (var channel in channels)
{
try
{
await ExportAsync(console, channel);
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
{
console.Error.WriteLine("You don't have access to this channel.");
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
console.Error.WriteLine("This channel doesn't exist.");
}
catch (DomainException ex)
{
console.Error.WriteLine(ex.Message);
}
}
await ExportMultipleAsync(console, channels);
}
}
}
@@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Utilities;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Models.Exceptions;
using DiscordChatExporter.Core.Services;
using DiscordChatExporter.Core.Services.Exceptions;
using Gress;
using Tyrrrz.Extensions;
namespace DiscordChatExporter.Cli.Commands
{
public abstract class ExportMultipleCommandBase : ExportCommandBase
{
[CommandOption("parallel", Description = "Export this number of separate channels in parallel.")]
public int ParallelLimit { get; set; } = 1;
protected ExportMultipleCommandBase(SettingsService settingsService, DataService dataService, ExportService exportService)
: base(settingsService, dataService, exportService)
{
}
protected async ValueTask ExportMultipleAsync(IConsole console, IReadOnlyList<Channel> channels)
{
// This uses a separate route from ExportCommandBase because the progress ticker is not thread-safe
// Ugly code ahead. Will need to refactor.
if (!string.IsNullOrWhiteSpace(DateFormat))
SettingsService.DateFormat = DateFormat;
// Progress
console.Output.Write($"Exporting {channels.Count} channels... ");
var ticker = console.CreateProgressTicker();
// TODO: refactor this after improving Gress
var progressManager = new ProgressManager();
progressManager.PropertyChanged += (sender, args) => ticker.Report(progressManager.Progress);
var operations = progressManager.CreateOperations(channels.Count);
// Export channels
using var semaphore = new SemaphoreSlim(ParallelLimit.ClampMin(1));
var errors = new List<string>();
await Task.WhenAll(channels.Select(async (channel, i) =>
{
var operation = operations[i];
await semaphore.WaitAsync();
var guild = await DataService.GetGuildAsync(Token, channel.GuildId);
try
{
await ExportService.ExportChatLogAsync(Token, guild, channel,
OutputPath, ExportFormat, PartitionLimit,
After, Before, operation);
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
{
errors.Add("You don't have access to this channel.");
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
errors.Add("This channel doesn't exist.");
}
catch (DomainException ex)
{
errors.Add(ex.Message);
}
finally
{
semaphore.Release();
operation.Dispose();
}
}));
ticker.Report(1);
console.Output.WriteLine();
foreach (var error in errors)
console.Error.WriteLine(error);
console.Output.WriteLine("Done.");
}
}
}
@@ -1,7 +1,7 @@
using System.Linq;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Services;
@@ -11,22 +11,22 @@ namespace DiscordChatExporter.Cli.Commands
public class GetChannelsCommand : TokenCommandBase
{
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
public string GuildId { get; set; }
public string GuildId { get; set; } = "";
public GetChannelsCommand(DataService dataService)
: base(dataService)
{
}
public override async Task ExecuteAsync(IConsole console)
public override async ValueTask ExecuteAsync(IConsole console)
{
// Get channels
var channels = await DataService.GetGuildChannelsAsync(GetToken(), GuildId);
var guildChannels = await DataService.GetGuildChannelsAsync(Token, GuildId);
// Filter and order channels
channels = channels.Where(c => c.Type.IsExportable()).OrderBy(c => c.Name).ToArray();
var channels = guildChannels
.Where(c => c.Type.IsExportable())
.OrderBy(c => c.Name)
.ToArray();
// Print result
foreach (var channel in channels)
console.Output.WriteLine($"{channel.Id} | {channel.Name}");
}
@@ -1,7 +1,7 @@
using System.Linq;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Services;
namespace DiscordChatExporter.Cli.Commands
@@ -14,15 +14,11 @@ namespace DiscordChatExporter.Cli.Commands
{
}
public override async Task ExecuteAsync(IConsole console)
public override async ValueTask ExecuteAsync(IConsole console)
{
// Get channels
var channels = await DataService.GetDirectMessageChannelsAsync(GetToken());
var directMessageChannels = await DataService.GetDirectMessageChannelsAsync(Token);
var channels = directMessageChannels.OrderBy(c => c.Name).ToArray();
// Order channels
channels = channels.OrderBy(c => c.Name).ToArray();
// Print result
foreach (var channel in channels)
console.Output.WriteLine($"{channel.Id} | {channel.Name}");
}
@@ -1,7 +1,7 @@
using System.Linq;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Services;
namespace DiscordChatExporter.Cli.Commands
@@ -14,16 +14,11 @@ namespace DiscordChatExporter.Cli.Commands
{
}
public override async Task ExecuteAsync(IConsole console)
public override async ValueTask ExecuteAsync(IConsole console)
{
// Get guilds
var guilds = await DataService.GetUserGuildsAsync(GetToken());
var guilds = await DataService.GetUserGuildsAsync(Token);
// Order guilds
guilds = guilds.OrderBy(g => g.Name).ToArray();
// Print result
foreach (var guild in guilds)
foreach (var guild in guilds.OrderBy(g => g.Name))
console.Output.WriteLine($"{guild.Id} | {guild.Name}");
}
}
@@ -2,14 +2,13 @@
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
namespace DiscordChatExporter.Cli.Commands
{
[Command("guide", Description = "Explains how to obtain token, guild or channel ID.")]
public class GuideCommand : ICommand
{
public Task ExecuteAsync(IConsole console)
public ValueTask ExecuteAsync(IConsole console)
{
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get user token:"));
console.Output.WriteLine(" 1. Open Discord");
@@ -48,7 +47,7 @@ namespace DiscordChatExporter.Cli.Commands
console.Output.WriteLine("If you still have unanswered questions, check out the wiki:");
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
return Task.CompletedTask;
return default;
}
}
}
@@ -1,7 +1,6 @@
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Services;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Services;
@@ -12,18 +11,18 @@ namespace DiscordChatExporter.Cli.Commands
protected DataService DataService { get; }
[CommandOption("token", 't', IsRequired = true, Description = "Authorization token.")]
public string TokenValue { get; set; }
public string TokenValue { get; set; } = "";
[CommandOption("bot", 'b', Description = "Whether this authorization token belongs to a bot.")]
public bool IsBotToken { get; set; }
protected AuthToken Token => new AuthToken(IsBotToken ? AuthTokenType.Bot : AuthTokenType.User, TokenValue);
protected TokenCommandBase(DataService dataService)
{
DataService = dataService;
}
protected AuthToken GetToken() => new AuthToken(IsBotToken ? AuthTokenType.Bot : AuthTokenType.User, TokenValue);
public abstract Task ExecuteAsync(IConsole console);
public abstract ValueTask ExecuteAsync(IConsole console);
}
}
@@ -7,8 +7,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CliFx" Version="0.0.8" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" />
<PackageReference Include="CliFx" Version="1.0.0" />
<PackageReference Include="Gress" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.1" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
</ItemGroup>
+4 -3
View File
@@ -1,4 +1,5 @@
using System;
using System.Drawing;
using System.Threading.Tasks;
using CliFx;
using DiscordChatExporter.Cli.Commands;
@@ -30,13 +31,13 @@ namespace DiscordChatExporter.Cli
return services.BuildServiceProvider();
}
public static Task<int> Main(string[] args)
public static async Task<int> Main(string[] args)
{
var serviceProvider = ConfigureServices();
return new CliApplicationBuilder()
return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly()
.UseCommandFactory(schema => (ICommand) serviceProvider.GetService(schema.Type))
.UseTypeActivator(serviceProvider.GetService)
.Build()
.RunAsync(args);
}
@@ -5,6 +5,7 @@
PlainText,
HtmlDark,
HtmlLight,
Csv
Csv,
Json
}
}
@@ -18,16 +18,18 @@ namespace DiscordChatExporter.Core.Models
ExportFormat.HtmlDark => "html",
ExportFormat.HtmlLight => "html",
ExportFormat.Csv => "csv",
ExportFormat.Json => "json",
_ => throw new ArgumentOutOfRangeException(nameof(format))
};
public static string GetDisplayName(this ExportFormat format) =>
format switch
{
ExportFormat.PlainText => "Plain Text",
ExportFormat.PlainText => "TXT",
ExportFormat.HtmlDark => "HTML (Dark)",
ExportFormat.HtmlLight => "HTML (Light)",
ExportFormat.Csv => "Comma Separated Values (CSV)",
ExportFormat.Csv => "CSV",
ExportFormat.Json => "JSON",
_ => throw new ArgumentOutOfRangeException(nameof(format))
};
}
+29 -8
View File
@@ -1,6 +1,11 @@
namespace DiscordChatExporter.Core.Models
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace DiscordChatExporter.Core.Models
{
// https://discordapp.string.IsNullOrWhiteSpace(com/developers/docs/resources/guild#guild-object
// https://discordapp.com/developers/docs/resources/guild#guild-object
public partial class Guild : IHasId
{
@@ -10,13 +15,19 @@
public string? IconHash { get; }
public IReadOnlyList<Role> Roles { get; }
public Dictionary<string, Member?> Members { get; }
public string IconUrl { get; }
public Guild(string id, string name, string? iconHash)
public Guild(string id, string name, IReadOnlyList<Role> roles, string? iconHash)
{
Id = id;
Name = name;
IconHash = iconHash;
Roles = roles;
Members = new Dictionary<string, Member?>();
IconUrl = GetIconUrl(id, iconHash);
}
@@ -26,13 +37,23 @@
public partial class Guild
{
public static string GetIconUrl(string id, string? iconHash)
{
return !string.IsNullOrWhiteSpace(iconHash)
public static string GetUserColor(Guild guild, User user) =>
guild.Members.GetValueOrDefault(user.Id, null)
?.Roles
.Select(r => guild.Roles.FirstOrDefault(role => r == role.Id))
.Where(r => r != null)
.Where(r => r.Color != Color.Black)
.Where(r => r.Color.R + r.Color.G + r.Color.B > 0)
.Aggregate<Role, Role?>(null, (a, b) => (a?.Position ?? 0) > b.Position ? a : b)
?.ColorAsHex ?? "";
public static string GetUserNick(Guild guild, User user) => guild.Members.GetValueOrDefault(user.Id)?.Nick ?? user.Name;
public static string GetIconUrl(string id, string? iconHash) =>
!string.IsNullOrWhiteSpace(iconHash)
? $"https://cdn.discordapp.com/icons/{id}/{iconHash}.png"
: "https://cdn.discordapp.com/embed/avatars/0.png";
}
public static Guild DirectMessages { get; } = new Guild("@me", "Direct Messages", null);
public static Guild DirectMessages { get; } = new Guild("@me", "Direct Messages", Array.Empty<Role>(), null);
}
}
+23
View File
@@ -0,0 +1,23 @@
using System.Collections.Generic;
using System.Linq;
namespace DiscordChatExporter.Core.Models
{
// https://discordapp.com/developers/docs/resources/guild#guild-member-object
public class Member
{
public string UserId { get; }
public string? Nick { get; }
public IReadOnlyList<string> Roles { get; }
public Member(string userId, string? nick, IReadOnlyList<string> roles)
{
UserId = userId;
Nick = nick;
Roles = roles;
}
}
}
+15 -3
View File
@@ -1,4 +1,6 @@
namespace DiscordChatExporter.Core.Models
using System.Drawing;
namespace DiscordChatExporter.Core.Models
{
// https://discordapp.com/developers/docs/topics/permissions#role-object
@@ -8,10 +10,20 @@
public string Name { get; }
public Role(string id, string name)
public Color Color { get; }
public string ColorAsHex => $"#{Color.ToArgb() & 0xffffff:X6}";
public string ColorAsRgb => $"{Color.R}, {Color.G}, {Color.B}";
public int Position { get; }
public Role(string id, string name, Color color, int position)
{
Id = id;
Name = name;
Color = color;
Position = position;
}
public override string ToString() => Name;
@@ -19,6 +31,6 @@
public partial class Role
{
public static Role CreateDeletedRole(string id) => new Role(id, "deleted-role");
public static Role CreateDeletedRole(string id) => new Role(id, "deleted-role", Color.Black, -1);
}
}
@@ -7,19 +7,28 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
{
public class CsvMessageWriter : MessageWriterBase
{
public CsvMessageWriter(TextWriter writer, RenderContext context)
: base(writer, context)
private readonly TextWriter _writer;
public CsvMessageWriter(Stream stream, RenderContext context)
: base(stream, context)
{
_writer = new StreamWriter(stream);
}
public override async Task WritePreambleAsync()
{
await Writer.WriteLineAsync(CsvRenderingLogic.FormatHeader(Context));
await _writer.WriteLineAsync(CsvRenderingLogic.FormatHeader(Context));
}
public override async Task WriteMessageAsync(Message message)
{
await Writer.WriteLineAsync(CsvRenderingLogic.FormatMessage(Context, message));
await _writer.WriteLineAsync(CsvRenderingLogic.FormatMessage(Context, message));
}
public override async ValueTask DisposeAsync()
{
await _writer.DisposeAsync();
await base.DisposeAsync();
}
}
}
@@ -14,6 +14,7 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
{
public partial class HtmlMessageWriter : MessageWriterBase
{
private readonly TextWriter _writer;
private readonly string _themeName;
private readonly List<Message> _messageGroupBuffer = new List<Message>();
@@ -23,9 +24,10 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
private long _messageCount;
public HtmlMessageWriter(TextWriter writer, RenderContext context, string themeName)
: base(writer, context)
public HtmlMessageWriter(Stream stream, RenderContext context, string themeName)
: base(stream, context)
{
_writer = new StreamWriter(stream);
_themeName = themeName;
_preambleTemplate = Template.Parse(GetPreambleTemplateCode());
@@ -73,11 +75,15 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
scriptObject.Import("FormatMarkdown",
new Func<string, string>(m => HtmlRenderingLogic.FormatMarkdown(Context, m)));
scriptObject.Import("GetUserColor", new Func<Guild, User, string>(Guild.GetUserColor));
scriptObject.Import("GetUserNick", new Func<Guild, User, string>(Guild.GetUserNick));
// Push model
templateContext.PushGlobal(scriptObject);
// Push output
templateContext.PushOutput(new TextWriterOutput(Writer));
templateContext.PushOutput(new TextWriterOutput(_writer));
return templateContext;
}
@@ -131,6 +137,12 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
await templateContext.EvaluateAsync(_postambleTemplate.Page);
}
public override async ValueTask DisposeAsync()
{
await _writer.DisposeAsync();
await base.DisposeAsync();
}
}
public partial class HtmlMessageWriter
@@ -0,0 +1,222 @@
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Rendering.Internal;
using DiscordChatExporter.Core.Rendering.Logic;
namespace DiscordChatExporter.Core.Rendering.Formatters
{
public class JsonMessageWriter : MessageWriterBase
{
private readonly Utf8JsonWriter _writer;
private long _messageCount;
public JsonMessageWriter(Stream stream, RenderContext context)
: base(stream, context)
{
_writer = new Utf8JsonWriter(stream, new JsonWriterOptions
{
Indented = true
});
}
public override async Task WritePreambleAsync()
{
// Root object (start)
_writer.WriteStartObject();
// Guild
_writer.WriteStartObject("guild");
_writer.WriteString("id", Context.Guild.Id);
_writer.WriteString("name", Context.Guild.Name);
_writer.WriteString("iconUrl", Context.Guild.IconUrl);
_writer.WriteEndObject();
// Channel
_writer.WriteStartObject("channel");
_writer.WriteString("id", Context.Channel.Id);
_writer.WriteString("type", Context.Channel.Type.ToString());
_writer.WriteString("name", Context.Channel.Name);
_writer.WriteString("topic", Context.Channel.Topic);
_writer.WriteEndObject();
// Date range
_writer.WriteStartObject("dateRange");
_writer.WriteString("after", Context.After);
_writer.WriteString("before", Context.Before);
_writer.WriteEndObject();
// Message array (start)
_writer.WriteStartArray("messages");
await _writer.FlushAsync();
}
public override async Task WriteMessageAsync(Message message)
{
_writer.WriteStartObject();
// Metadata
_writer.WriteString("id", message.Id);
_writer.WriteString("type", message.Type.ToString());
_writer.WriteString("timestamp", message.Timestamp);
_writer.WriteString("timestampEdited", message.EditedTimestamp);
_writer.WriteBoolean("isPinned", message.IsPinned);
// Content
var content = PlainTextRenderingLogic.FormatMessageContent(Context, message);
_writer.WriteString("content", content);
// Author
_writer.WriteStartObject("author");
_writer.WriteString("id", message.Author.Id);
_writer.WriteString("name", message.Author.Name);
_writer.WriteString("discriminator", $"{message.Author.Discriminator:0000}");
_writer.WriteBoolean("isBot", message.Author.IsBot);
_writer.WriteString("avatarUrl", message.Author.AvatarUrl);
_writer.WriteEndObject();
// Attachments
_writer.WriteStartArray("attachments");
foreach (var attachment in message.Attachments)
{
_writer.WriteStartObject();
_writer.WriteString("id", attachment.Id);
_writer.WriteString("url", attachment.Url);
_writer.WriteString("fileName", attachment.FileName);
_writer.WriteNumber("fileSizeBytes", (long) attachment.FileSize.Bytes);
_writer.WriteEndObject();
}
_writer.WriteEndArray();
// Embeds
_writer.WriteStartArray("embeds");
foreach (var embed in message.Embeds)
{
_writer.WriteStartObject();
_writer.WriteString("title", embed.Title);
_writer.WriteString("url", embed.Url);
_writer.WriteString("timestamp", embed.Timestamp);
_writer.WriteString("description", embed.Description);
// Author
if (embed.Author != null)
{
_writer.WriteStartObject("author");
_writer.WriteString("name", embed.Author.Name);
_writer.WriteString("url", embed.Author.Url);
_writer.WriteString("iconUrl", embed.Author.IconUrl);
_writer.WriteEndObject();
}
// Thumbnail
if (embed.Thumbnail != null)
{
_writer.WriteStartObject("thumbnail");
_writer.WriteString("url", embed.Thumbnail.Url);
_writer.WriteNumber("width", embed.Thumbnail.Width);
_writer.WriteNumber("height", embed.Thumbnail.Height);
_writer.WriteEndObject();
}
// Image
if (embed.Image != null)
{
_writer.WriteStartObject("image");
_writer.WriteString("url", embed.Image.Url);
_writer.WriteNumber("width", embed.Image.Width);
_writer.WriteNumber("height", embed.Image.Height);
_writer.WriteEndObject();
}
// Footer
if (embed.Footer != null)
{
_writer.WriteStartObject("footer");
_writer.WriteString("text", embed.Footer.Text);
_writer.WriteString("iconUrl", embed.Footer.IconUrl);
_writer.WriteEndObject();
}
// Fields
_writer.WriteStartArray("fields");
foreach (var field in embed.Fields)
{
_writer.WriteStartObject();
_writer.WriteString("name", field.Name);
_writer.WriteString("value", field.Value);
_writer.WriteBoolean("isInline", field.IsInline);
_writer.WriteEndObject();
}
_writer.WriteEndArray();
_writer.WriteEndObject();
}
_writer.WriteEndArray();
// Reactions
_writer.WriteStartArray("reactions");
foreach (var reaction in message.Reactions)
{
_writer.WriteStartObject();
// Emoji
_writer.WriteStartObject("emoji");
_writer.WriteString("id", reaction.Emoji.Id);
_writer.WriteString("name", reaction.Emoji.Name);
_writer.WriteBoolean("isAnimated", reaction.Emoji.IsAnimated);
_writer.WriteString("imageUrl", reaction.Emoji.ImageUrl);
_writer.WriteEndObject();
// Count
_writer.WriteNumber("count", reaction.Count);
_writer.WriteEndObject();
}
_writer.WriteEndArray();
_writer.WriteEndObject();
_messageCount++;
// Flush every 100 messages
if (_messageCount % 100 == 0)
await _writer.FlushAsync();
}
public override async Task WritePostambleAsync()
{
// Message array (end)
_writer.WriteEndArray();
// Message count
_writer.WriteNumber("messageCount", _messageCount);
// Root object (end)
_writer.WriteEndObject();
await _writer.FlushAsync();
}
public override async ValueTask DisposeAsync()
{
await _writer.DisposeAsync();
await base.DisposeAsync();
}
}
}
@@ -7,13 +7,13 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
{
public abstract class MessageWriterBase : IAsyncDisposable
{
protected TextWriter Writer { get; }
protected Stream Stream { get; }
protected RenderContext Context { get; }
protected MessageWriterBase(TextWriter writer, RenderContext context)
protected MessageWriterBase(Stream stream, RenderContext context)
{
Writer = writer;
Stream = stream;
Context = context;
}
@@ -23,6 +23,6 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
public virtual Task WritePostambleAsync() => Task.CompletedTask;
public async ValueTask DisposeAsync() => await Writer.DisposeAsync();
public virtual async ValueTask DisposeAsync() => await Stream.DisposeAsync();
}
}
@@ -7,30 +7,39 @@ namespace DiscordChatExporter.Core.Rendering.Formatters
{
public class PlainTextMessageWriter : MessageWriterBase
{
private readonly TextWriter _writer;
private long _messageCount;
public PlainTextMessageWriter(TextWriter writer, RenderContext context)
: base(writer, context)
public PlainTextMessageWriter(Stream stream, RenderContext context)
: base(stream, context)
{
_writer = new StreamWriter(stream);
}
public override async Task WritePreambleAsync()
{
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatPreamble(Context));
await _writer.WriteLineAsync(PlainTextRenderingLogic.FormatPreamble(Context));
}
public override async Task WriteMessageAsync(Message message)
{
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatMessage(Context, message));
await Writer.WriteLineAsync();
await _writer.WriteLineAsync(PlainTextRenderingLogic.FormatMessage(Context, message));
await _writer.WriteLineAsync();
_messageCount++;
}
public override async Task WritePostambleAsync()
{
await Writer.WriteLineAsync();
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatPostamble(_messageCount));
await _writer.WriteLineAsync();
await _writer.WriteLineAsync(PlainTextRenderingLogic.FormatPostamble(_messageCount));
}
public override async ValueTask DisposeAsync()
{
await _writer.DisposeAsync();
await base.DisposeAsync();
}
}
}
@@ -1,4 +1,6 @@
using System.Text;
using System;
using System.Text;
using System.Text.Json;
namespace DiscordChatExporter.Core.Rendering.Internal
{
@@ -17,5 +19,25 @@ namespace DiscordChatExporter.Core.Rendering.Internal
return builder;
}
public static void WriteString(this Utf8JsonWriter writer, string propertyName, DateTimeOffset? value)
{
writer.WritePropertyName(propertyName);
if (value != null)
writer.WriteStringValue(value.Value);
else
writer.WriteNullValue();
}
public static void WriteNumber(this Utf8JsonWriter writer, string propertyName, int? value)
{
writer.WritePropertyName(propertyName);
if (value != null)
writer.WriteNumberValue(value.Value);
else
writer.WriteNullValue();
}
}
}
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
@@ -97,7 +98,9 @@ namespace DiscordChatExporter.Core.Rendering.Logic
var user = context.MentionableUsers.FirstOrDefault(u => u.Id == mentionNode.Id) ??
User.CreateUnknownUser(mentionNode.Id);
return $"<span class=\"mention\" title=\"{HtmlEncode(user.FullName)}\">@{HtmlEncode(user.Name)}</span>";
var nick = Guild.GetUserNick(context.Guild, user);
return $"<span class=\"mention\" title=\"{HtmlEncode(user.FullName)}\">@{HtmlEncode(nick)}</span>";
}
// Channel mention node
@@ -114,8 +117,11 @@ namespace DiscordChatExporter.Core.Rendering.Logic
{
var role = context.MentionableRoles.FirstOrDefault(r => r.Id == mentionNode.Id) ??
Role.CreateDeletedRole(mentionNode.Id);
string style = "";
if (role.Color != Color.Black)
style = $"style=\"color: {role.ColorAsHex}; background-color: rgba({role.ColorAsRgb}, 0.1); font-weight: 400;\"";
return $"<span class=\"mention\">@{HtmlEncode(role.Name)}</span>";
return $"<span class=\"mention\" {style}>@{HtmlEncode(role.Name)}</span>";
}
}
@@ -128,7 +134,8 @@ namespace DiscordChatExporter.Core.Rendering.Logic
// Make emoji large if it's jumbo
var jumboableCssClass = isJumbo ? "emoji--large" : null;
return $"<img class=\"emoji {jumboableCssClass}\" alt=\"{emojiNode.Name}\" title=\"{emojiNode.Name}\" src=\"{emojiImageUrl}\" />";
return
$"<img class=\"emoji {jumboableCssClass}\" alt=\"{emojiNode.Name}\" title=\"{emojiNode.Name}\" src=\"{emojiImageUrl}\" />";
}
// Link node
@@ -99,21 +99,24 @@ namespace DiscordChatExporter.Core.Rendering
private static MessageWriterBase CreateMessageWriter(string filePath, ExportFormat format, RenderContext context)
{
// Create inner writer (it will get disposed by the wrapper)
var writer = File.CreateText(filePath);
// Create a stream (it will get disposed by the writer)
var stream = File.Create(filePath);
// Create formatter
if (format == ExportFormat.PlainText)
return new PlainTextMessageWriter(writer, context);
return new PlainTextMessageWriter(stream, context);
if (format == ExportFormat.Csv)
return new CsvMessageWriter(writer, context);
return new CsvMessageWriter(stream, context);
if (format == ExportFormat.HtmlDark)
return new HtmlMessageWriter(writer, context, "Dark");
return new HtmlMessageWriter(stream, context, "Dark");
if (format == ExportFormat.HtmlLight)
return new HtmlMessageWriter(writer, context, "Light");
return new HtmlMessageWriter(stream, context, "Light");
if (format == ExportFormat.Json)
return new JsonMessageWriter(stream, context);
throw new InvalidOperationException($"Unknown export format [{format}].");
}
@@ -82,6 +82,10 @@ img {
}
.mention {
border-radius: 3px;
padding: 0 2px;
color: #7289da;
background: rgba(114, 137, 218, .1);
font-weight: 500;
}
@@ -26,10 +26,6 @@ a {
color: #b9bbbe !important;
}
.mention {
color: #7289da;
}
/* === Preamble === */
.preamble__entry {
@@ -27,11 +27,6 @@ a {
color: #657b83 !important;
}
.mention {
background-color: #f1f3fb;
color: #7289da;
}
/* Preamble */
.preamble__entry {
@@ -5,7 +5,7 @@
</div>
<div class="chatlog__messages">
{{~ # Author name and timestamp ~}}
<span class="chatlog__author-name" title="{{ MessageGroup.Author.FullName | html.escape }}" data-user-id="{{ MessageGroup.Author.Id | html.escape }}">{{ MessageGroup.Author.Name | html.escape }}</span>
<span class="chatlog__author-name" title="{{ MessageGroup.Author.FullName | html.escape }}" data-user-id="{{ MessageGroup.Author.Id | html.escape }}" style="color: {{ GetUserColor Context.Guild MessageGroup.Author }}">{{ GetUserNick Context.Guild MessageGroup.Author | html.escape }}</span>
{{~ # Bot tag ~}}
{{~ if MessageGroup.Author.IsBot ~}}
@@ -21,13 +21,23 @@ namespace DiscordChatExporter.Core.Services
return new User(id, discriminator, name, avatarHash, isBot);
}
private Member ParseMember(JToken json)
{
var userId = ParseUser(json["user"]!).Id;
var nick = json["nick"]?.Value<string>();
var roles = (json["roles"] ?? Enumerable.Empty<JToken>()).Select(j => j.Value<string>()).ToArray();
return new Member(userId, nick, roles);
}
private Guild ParseGuild(JToken json)
{
var id = json["id"]!.Value<string>();
var name = json["name"]!.Value<string>();
var iconHash = json["icon"]!.Value<string>();
var roles = (json["roles"] ?? Enumerable.Empty<JToken>()).Select(ParseRole).ToArray();
return new Guild(id, name, iconHash);
return new Guild(id, name, roles, iconHash);
}
private Channel ParseChannel(JToken json)
@@ -64,8 +74,10 @@ namespace DiscordChatExporter.Core.Services
{
var id = json["id"]!.Value<string>();
var name = json["name"]!.Value<string>();
var color = json["color"]!.Value<int>();
var position = json["position"]!.Value<int>();
return new Role(id, name);
return new Role(id, name, Color.FromArgb(color), position);
}
private Attachment ParseAttachment(JToken json)
@@ -42,6 +42,11 @@ namespace DiscordChatExporter.Core.Services
}
private async Task<JToken> GetApiResponseAsync(AuthToken token, string route)
{
return (await GetApiResponseAsync(token, route, true))!;
}
private async Task<JToken?> GetApiResponseAsync(AuthToken token, string route, bool errorOnFail)
{
using var response = await _httpPolicy.ExecuteAsync(async () =>
{
@@ -56,7 +61,10 @@ namespace DiscordChatExporter.Core.Services
// We throw our own exception here because default one doesn't have status code
if (!response.IsSuccessStatusCode)
throw new HttpErrorStatusCodeException(response.StatusCode, response.ReasonPhrase);
{
if (errorOnFail) throw new HttpErrorStatusCodeException(response.StatusCode, response.ReasonPhrase);
else return null;
}
var jsonRaw = await response.Content.ReadAsStringAsync();
return JToken.Parse(jsonRaw);
@@ -74,6 +82,15 @@ namespace DiscordChatExporter.Core.Services
return guild;
}
public async Task<Member?> GetGuildMemberAsync(AuthToken token, string guildId, string userId)
{
var response = await GetApiResponseAsync(token, $"guilds/{guildId}/members/{userId}", false);
if (response == null) return null;
var member = ParseMember(response);
return member;
}
public async Task<Channel> GetChannelAsync(AuthToken token, string channelId)
{
var response = await GetApiResponseAsync(token, $"channels/{channelId}");
@@ -97,10 +114,11 @@ namespace DiscordChatExporter.Core.Services
if (!response.HasValues)
yield break;
foreach (var guild in response.Select(ParseGuild))
// Get full guild object
foreach (var guildId in response.Select(j => j["id"]!.Value<string>()))
{
yield return guild;
afterId = guild.Id;
yield return await GetGuildAsync(token, guildId);
afterId = guildId;
}
}
}
@@ -125,18 +143,6 @@ namespace DiscordChatExporter.Core.Services
return channels;
}
public async Task<IReadOnlyList<Role>> GetGuildRolesAsync(AuthToken token, string guildId)
{
// Special case for direct messages pseudo-guild
if (guildId == Guild.DirectMessages.Id)
return Array.Empty<Role>();
var response = await GetApiResponseAsync(token, $"guilds/{guildId}/roles");
var roles = response.Select(ParseRole).ToArray();
return roles;
}
private async Task<Message> GetLastMessageAsync(AuthToken token, string channelId, DateTimeOffset? before = null)
{
var route = $"channels/{channelId}/messages?limit=1";
@@ -34,7 +34,7 @@ namespace DiscordChatExporter.Core.Services
// Create context
var mentionableUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
var mentionableChannels = await _dataService.GetGuildChannelsAsync(token, guild.Id);
var mentionableRoles = await _dataService.GetGuildRolesAsync(token, guild.Id);
var mentionableRoles = guild.Roles;
var context = new RenderContext
(
@@ -50,8 +50,21 @@ namespace DiscordChatExporter.Core.Services
await foreach (var message in _dataService.GetMessagesAsync(token, channel.Id, after, before, progress))
{
// Add encountered users to the list of mentionable users
mentionableUsers.Add(message.Author);
mentionableUsers.AddRange(message.MentionedUsers);
var encounteredUsers = new List<User>();
encounteredUsers.Add(message.Author);
encounteredUsers.AddRange(message.MentionedUsers);
mentionableUsers.AddRange(encounteredUsers);
foreach (User u in encounteredUsers)
{
if(!guild.Members.ContainsKey(u.Id))
{
var member = await _dataService.GetGuildMemberAsync(token, guild.Id, u.Id);
guild.Members[u.Id] = member;
}
}
// Render message
await renderer.RenderMessageAsync(message);
@@ -11,6 +11,8 @@ namespace DiscordChatExporter.Core.Services
public bool IsTokenPersisted { get; set; } = true;
public int ParallelLimit { get; set; } = 1;
public AuthToken? LastToken { get; set; }
public ExportFormat LastExportFormat { get; set; } = ExportFormat.HtmlDark;
@@ -16,11 +16,11 @@
<PackageReference Include="Gress" Version="1.1.1" />
<PackageReference Include="MaterialDesignColors" Version="1.2.2" />
<PackageReference Include="MaterialDesignThemes" Version="3.0.1" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.3" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.19" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="1.1.0" />
<PackageReference Include="Stylet" Version="1.3.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
<PackageReference Include="PropertyChanged.Fody" Version="3.2.3" PrivateAssets="all" />
<PackageReference Include="PropertyChanged.Fody" Version="3.2.5" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
@@ -32,7 +32,7 @@
<Target Name="Format XAML" AfterTargets="BeforeBuild">
<Exec Command="dotnet tool restore" />
<Exec Command="dotnet xstyler -r -d &quot;$(MSBuildProjectDirectory)&quot;" />
<Exec Command="dotnet xstyler -r -d ." />
</Target>
</Project>
@@ -5,13 +5,13 @@ namespace DiscordChatExporter.Gui.ViewModels.Components
{
public partial class ChannelViewModel : PropertyChangedBase
{
public Channel Model { get; set; }
public Channel? Model { get; set; }
public string? Category { get; set; }
}
public partial class ChannelViewModel
{
public static implicit operator Channel(ChannelViewModel viewModel) => viewModel.Model;
public static implicit operator Channel?(ChannelViewModel? viewModel) => viewModel?.Model;
}
}
@@ -6,13 +6,13 @@ namespace DiscordChatExporter.Gui.ViewModels.Components
{
public partial class GuildViewModel : PropertyChangedBase
{
public Guild Model { get; set; }
public Guild? Model { get; set; }
public IReadOnlyList<ChannelViewModel> Channels { get; set; }
public IReadOnlyList<ChannelViewModel>? Channels { get; set; }
}
public partial class GuildViewModel
{
public static implicit operator Guild(GuildViewModel viewModel) => viewModel.Model;
public static implicit operator Guild?(GuildViewModel? viewModel) => viewModel?.Model;
}
}
@@ -14,11 +14,11 @@ namespace DiscordChatExporter.Gui.ViewModels.Dialogs
private readonly DialogManager _dialogManager;
private readonly SettingsService _settingsService;
public GuildViewModel Guild { get; set; }
public GuildViewModel? Guild { get; set; }
public IReadOnlyList<ChannelViewModel> Channels { get; set; }
public IReadOnlyList<ChannelViewModel>? Channels { get; set; }
public bool IsSingleChannel => Channels.Count == 1;
public bool IsSingleChannel => Channels == null || Channels.Count == 1;
public string? OutputPath { get; set; }
@@ -62,7 +62,7 @@ namespace DiscordChatExporter.Gui.ViewModels.Dialogs
var channel = Channels.Single();
// Generate default file name
var defaultFileName = ExportLogic.GetDefaultExportFileName(SelectedFormat, Guild, channel, After, Before);
var defaultFileName = ExportLogic.GetDefaultExportFileName(SelectedFormat, Guild!, channel!, After, Before);
// Generate filter
var ext = SelectedFormat.GetFileExtension();
@@ -1,5 +1,6 @@
using DiscordChatExporter.Core.Services;
using DiscordChatExporter.Gui.ViewModels.Framework;
using Tyrrrz.Extensions;
namespace DiscordChatExporter.Gui.ViewModels.Dialogs
{
@@ -25,6 +26,12 @@ namespace DiscordChatExporter.Gui.ViewModels.Dialogs
set => _settingsService.IsTokenPersisted = value;
}
public int ParallelLimit
{
get => _settingsService.ParallelLimit;
set => _settingsService.ParallelLimit = value.Clamp(1, 10);
}
public SettingsViewModel(SettingsService settingsService)
{
_settingsService = settingsService;
@@ -5,7 +5,8 @@ namespace DiscordChatExporter.Gui.ViewModels.Framework
{
public abstract class DialogScreen<T> : PropertyChangedBase
{
public T DialogResult { get; private set; }
// ReSharper disable once RedundantDefaultMemberInitializer
public T DialogResult { get; private set; } = default!;
public event EventHandler? Closed;
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Models.Exceptions;
@@ -178,7 +179,7 @@ namespace DiscordChatExporter.Gui.ViewModels
// Create guild view model
var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild,
channelViewModels.OrderBy(c => c.Category)
.ThenBy(c => c.Model.Name)
.ThenBy(c => c.Model!.Name)
.ToArray());
// Add to list
@@ -210,7 +211,7 @@ namespace DiscordChatExporter.Gui.ViewModels
// Create guild view model
var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild,
channelViewModels.OrderBy(c => c.Category)
.ThenBy(c => c.Model.Name)
.ThenBy(c => c.Model!.Name)
.ToArray());
// Add to list
@@ -256,18 +257,21 @@ namespace DiscordChatExporter.Gui.ViewModels
return;
// Create a progress operation for each channel to export
var operations = ProgressManager.CreateOperations(dialog.Channels.Count);
var operations = ProgressManager.CreateOperations(dialog.Channels!.Count);
// Export channels
var successfulExportCount = 0;
for (var i = 0; i < dialog.Channels.Count; i++)
using var semaphore = new SemaphoreSlim(_settingsService.ParallelLimit.ClampMin(1));
await Task.WhenAll(dialog.Channels.Select(async (channel, i) =>
{
var operation = operations[i];
var channel = dialog.Channels[i];
await semaphore.WaitAsync();
try
{
await _exportService.ExportChatLogAsync(token, dialog.Guild, channel,
await _exportService.ExportChatLogAsync(token, dialog.Guild!, channel!,
dialog.OutputPath!, dialog.SelectedFormat, dialog.PartitionLimit,
dialog.After, dialog.Before, operation);
@@ -275,11 +279,11 @@ namespace DiscordChatExporter.Gui.ViewModels
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
{
Notifications.Enqueue($"You don't have access to channel [{channel.Model.Name}]");
Notifications.Enqueue($"You don't have access to channel [{channel.Model!.Name}]");
}
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Notifications.Enqueue($"Channel [{channel.Model.Name}] doesn't exist");
Notifications.Enqueue($"Channel [{channel.Model!.Name}] doesn't exist");
}
catch (DomainException ex)
{
@@ -288,8 +292,9 @@ namespace DiscordChatExporter.Gui.ViewModels
finally
{
operation.Dispose();
semaphore.Release();
}
}
}));
// Notify of overall completion
if (successfulExportCount > 0)
@@ -56,6 +56,21 @@
IsChecked="{Binding IsTokenPersisted}" />
</DockPanel>
<!-- Parallel limit -->
<StackPanel Background="Transparent" ToolTip="How many channels can be exported at the same time">
<TextBlock Margin="16,8">
<Run Text="Parallel limit:" />
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="{Binding ParallelLimit, Mode=OneWay}" />
</TextBlock>
<Slider
Margin="16,8"
IsSnapToTickEnabled="True"
Maximum="10"
Minimum="1"
TickFrequency="1"
Value="{Binding ParallelLimit}" />
</StackPanel>
<!-- Save button -->
<Button
Margin="8"
+2 -1
View File
@@ -246,7 +246,8 @@
<ListBox
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding SelectedGuild.Channels}"
SelectionMode="Extended">
SelectionMode="Extended"
TextSearch.TextPath="Model.Name">
<i:Interaction.Behaviors>
<behaviors:ChannelViewModelMultiSelectionListBoxBehavior SelectedItems="{Binding SelectedChannels}" />
</i:Interaction.Behaviors>
+1 -1
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Version>2.17</Version>
<Version>2.19</Version>
<Company>Tyrrrz</Company>
<Copyright>Copyright (c) Alexey Golub</Copyright>
<LangVersion>latest</LangVersion>
+1 -1
View File
@@ -31,7 +31,7 @@ Note: This application requires .NET Core runtime in order to run:
- Supports file partitioning based on message count
- Uses custom markdown parser compatible with Discord syntax
- Handles all rich media features, including attachments, embeds, emojis, etc
- Renders to: HTML (dark & light themes), plain text (minimal), CSV (structured)
- Renders to HTML (dark & light), TXT, CSV, JSON
## Screenshots