Skip to content

Commit

Permalink
Remove Channel.ParentNameWithFallback
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrrrz committed Sep 7, 2023
1 parent 59344ce commit 5abe748
Show file tree
Hide file tree
Showing 24 changed files with 112 additions and 110 deletions.
9 changes: 3 additions & 6 deletions DiscordChatExporter.Cli/Commands/Base/ExportCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ await Parallel.ForEachAsync(
try
{
await progressContext.StartTaskAsync(
$"{channel.ParentNameWithFallback} / {channel.Name}",
channel.GetHierarchicalName(),
async progress =>
{
var guild = await Discord.GetGuildAsync(
Expand Down Expand Up @@ -263,10 +263,7 @@ await console.Error.WriteLineAsync(

foreach (var (channel, error) in errorsByChannel)
{
await console.Error.WriteAsync(
$"{channel.ParentNameWithFallback} / {channel.Name}: "
);

await console.Error.WriteAsync($"{channel.GetHierarchicalName()}: ");
using (console.WithForegroundColor(ConsoleColor.Red))
await console.Error.WriteLineAsync(error);
}
Expand Down Expand Up @@ -294,7 +291,7 @@ protected async ValueTask ExportAsync(IConsole console, IReadOnlyList<Snowflake>
var channel = await Discord.GetChannelAsync(channelId, cancellationToken);

// Unwrap categories
if (channel.Kind == ChannelKind.GuildCategory)
if (channel.IsCategory)
{
var guildChannels =
channelsByGuild.GetValueOrDefault(channel.GuildId)
Expand Down
14 changes: 7 additions & 7 deletions DiscordChatExporter.Cli/Commands/ExportAllCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ public override async ValueTask ExecuteAsync(IConsole console)
var channel in Discord.GetGuildChannelsAsync(guild.Id, cancellationToken)
)
{
if (channel.Kind == ChannelKind.GuildCategory)
if (channel.IsCategory)
continue;

if (!IncludeVoiceChannels && channel.Kind.IsVoice())
if (!IncludeVoiceChannels && channel.IsVoice)
continue;

channels.Add(channel);
Expand Down Expand Up @@ -129,15 +129,15 @@ await console.Error.WriteLineAsync(

// Filter out unwanted channels
if (!IncludeDirectChannels)
channels.RemoveAll(c => c.Kind.IsDirect());
channels.RemoveAll(c => c.IsDirect);
if (!IncludeGuildChannels)
channels.RemoveAll(c => c.Kind.IsGuild());
channels.RemoveAll(c => c.IsGuild);
if (!IncludeVoiceChannels)
channels.RemoveAll(c => c.Kind.IsVoice());
channels.RemoveAll(c => c.IsVoice);
if (ThreadInclusionMode == ThreadInclusionMode.None)
channels.RemoveAll(c => c.Kind.IsThread());
channels.RemoveAll(c => c.IsThread);
if (ThreadInclusionMode != ThreadInclusionMode.All)
channels.RemoveAll(c => c.Kind.IsThread() && c.IsArchived);
channels.RemoveAll(c => c is { IsThread: true, IsArchived: true });

await ExportAsync(console, channels);
}
Expand Down
4 changes: 2 additions & 2 deletions DiscordChatExporter.Cli/Commands/ExportGuildCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ public override async ValueTask ExecuteAsync(IConsole console)
// Regular channels
await foreach (var channel in Discord.GetGuildChannelsAsync(GuildId, cancellationToken))
{
if (channel.Kind == ChannelKind.GuildCategory)
if (channel.IsCategory)
continue;

if (!IncludeVoiceChannels && channel.Kind.IsVoice())
if (!IncludeVoiceChannels && channel.IsVoice)
continue;

channels.Add(channel);
Expand Down
10 changes: 4 additions & 6 deletions DiscordChatExporter.Cli/Commands/GetChannelsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public override async ValueTask ExecuteAsync(IConsole console)
var cancellationToken = console.RegisterCancellationHandler();

var channels = (await Discord.GetGuildChannelsAsync(GuildId, cancellationToken))
.Where(c => c.Kind != ChannelKind.GuildCategory)
.Where(c => IncludeVoiceChannels || !c.Kind.IsVoice())
.Where(c => !c.IsCategory)
.Where(c => IncludeVoiceChannels || !c.IsVoice)
.OrderBy(c => c.Parent?.Position)
.ThenBy(c => c.Name)
.ToArray();
Expand Down Expand Up @@ -72,11 +72,9 @@ await console.Output.WriteAsync(
using (console.WithForegroundColor(ConsoleColor.DarkGray))
await console.Output.WriteAsync(" | ");

// Channel category / name
// Channel name
using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteLineAsync(
$"{channel.ParentNameWithFallback} / {channel.Name}"
);
await console.Output.WriteLineAsync(channel.GetHierarchicalName());

var channelThreads = threads.Where(t => t.Parent?.Id == channel.Id).ToArray();
var channelThreadIdMaxLength = channelThreads
Expand Down
7 changes: 2 additions & 5 deletions DiscordChatExporter.Cli/Commands/GetDirectChannelsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public override async ValueTask ExecuteAsync(IConsole console)
var channels = (
await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken)
)
.Where(c => c.Kind != ChannelKind.GuildCategory)
.OrderByDescending(c => c.LastMessageId)
.ThenBy(c => c.Name)
.ToArray();
Expand All @@ -42,11 +41,9 @@ await console.Output.WriteAsync(
using (console.WithForegroundColor(ConsoleColor.DarkGray))
await console.Output.WriteAsync(" | ");

// Channel category / name
// Channel name
using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteLineAsync(
$"{channel.ParentNameWithFallback} / {channel.Name}"
);
await console.Output.WriteLineAsync(channel.GetHierarchicalName());
}
}
}
51 changes: 28 additions & 23 deletions DiscordChatExporter.Core/Discord/Data/Channel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
Expand All @@ -20,32 +21,36 @@ public partial record Channel(
Snowflake? LastMessageId
) : IHasId
{
// Used for visual backwards-compatibility with old exports, where
// channels without a parent (i.e. mostly DM channels) or channels
// with an inaccessible parent (i.e. inside private categories) had
// a fallback category created for them.
public string ParentNameWithFallback =>
Parent?.Name
?? Kind switch
{
ChannelKind.GuildCategory => "Category",
ChannelKind.GuildTextChat => "Text",
ChannelKind.DirectTextChat => "Private",
ChannelKind.DirectGroupTextChat => "Group",
ChannelKind.GuildPrivateThread => "Private Thread",
ChannelKind.GuildPublicThread => "Public Thread",
ChannelKind.GuildNews => "News",
ChannelKind.GuildNewsThread => "News Thread",
_ => "Default"
};
public bool IsDirect => Kind is ChannelKind.DirectTextChat or ChannelKind.DirectGroupTextChat;

public bool IsGuild => !IsDirect;

public bool IsCategory => Kind == ChannelKind.GuildCategory;

public bool IsVoice => Kind is ChannelKind.GuildVoiceChat or ChannelKind.GuildStageVoice;

public bool IsThread =>
Kind
is ChannelKind.GuildNewsThread
or ChannelKind.GuildPublicThread
or ChannelKind.GuildPrivateThread;

public bool IsEmpty => LastMessageId is null;

// Only needed for WPF data binding. Don't use anywhere else.
public bool IsVoice => Kind.IsVoice();
public IEnumerable<Channel> GetParents()
{
var current = Parent;
while (current is not null)
{
yield return current;
current = current.Parent;
}
}

public Channel? TryGetRootParent() => GetParents().LastOrDefault();

// Only needed for WPF data binding. Don't use anywhere else.
public bool IsThread => Kind.IsThread();
public string GetHierarchicalName() =>
string.Join(" / ", GetParents().Reverse().Select(c => c.Name).Append(Name));

public bool MayHaveMessagesAfter(Snowflake messageId) => !IsEmpty && messageId < LastMessageId;

Expand Down
17 changes: 0 additions & 17 deletions DiscordChatExporter.Core/Discord/Data/ChannelKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,3 @@ public enum ChannelKind
GuildDirectory = 14,
GuildForum = 15
}

public static class ChannelKindExtensions
{
public static bool IsDirect(this ChannelKind kind) =>
kind is ChannelKind.DirectTextChat or ChannelKind.DirectGroupTextChat;

public static bool IsGuild(this ChannelKind kind) => !kind.IsDirect();

public static bool IsVoice(this ChannelKind kind) =>
kind is ChannelKind.GuildVoiceChat or ChannelKind.GuildStageVoice;

public static bool IsThread(this ChannelKind kind) =>
kind
is ChannelKind.GuildNewsThread
or ChannelKind.GuildPublicThread
or ChannelKind.GuildPrivateThread;
}
7 changes: 6 additions & 1 deletion DiscordChatExporter.Core/Discord/Data/Guild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
namespace DiscordChatExporter.Core.Discord.Data;

// https://discord.com/developers/docs/resources/guild#guild-object
public record Guild(Snowflake Id, string Name, string IconUrl) : IHasId
public partial record Guild(Snowflake Id, string Name, string IconUrl) : IHasId
{
public bool IsDirect => Id == DirectMessages.Id;
}

public partial record Guild
{
// Direct messages are encapsulated within a special pseudo-guild for consistency
public static Guild DirectMessages { get; } =
Expand Down
8 changes: 7 additions & 1 deletion DiscordChatExporter.Core/Discord/Data/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ public partial record Message(
Interaction? Interaction
) : IHasId
{
public bool IsReplyLike => Kind == MessageKind.Reply || Interaction is not null;
public bool IsSystemNotification =>
Kind is >= MessageKind.RecipientAdd and <= MessageKind.ThreadCreated;

public bool IsReply => Kind == MessageKind.Reply;

// App interactions are rendered as replies in the Discord client, but they are not actually replies
public bool IsReplyLike => IsReply || Interaction is not null;

public IEnumerable<User> GetReferencedUsers()
{
Expand Down
5 changes: 0 additions & 5 deletions DiscordChatExporter.Core/Discord/Data/MessageKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,3 @@ public enum MessageKind
ThreadCreated = 18,
Reply = 19
}

public static class MessageKindExtensions
{
public static bool IsSystemNotification(this MessageKind kind) => (int)kind is >= 1 and <= 18;
}
5 changes: 3 additions & 2 deletions DiscordChatExporter.Core/Discord/DiscordClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,11 +286,12 @@ public async IAsyncEnumerable<Channel> GetGuildThreadsAsync(
yield break;

var tokenKind = _resolvedTokenKind ??= await GetTokenKindAsync(cancellationToken);

var channels = (await GetGuildChannelsAsync(guildId, cancellationToken))
// Categories cannot have threads
.Where(c => c.Kind != ChannelKind.GuildCategory)
.Where(c => !c.IsCategory)
// Voice channels cannot have threads
.Where(c => !c.Kind.IsVoice())
.Where(c => !c.IsVoice)
// Empty channels cannot have threads
.Where(c => !c.IsEmpty)
// If the 'before' boundary is specified, skip channels that don't have messages
Expand Down
2 changes: 1 addition & 1 deletion DiscordChatExporter.Core/Exporting/CsvMessageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public override async ValueTask WriteMessageAsync(
await _writer.WriteAsync(',');

// Message content
if (message.Kind.IsSystemNotification())
if (message.IsSystemNotification)
{
await _writer.WriteAsync(CsvEncode(message.GetFallbackContent()));
}
Expand Down
30 changes: 22 additions & 8 deletions DiscordChatExporter.Core/Exporting/ExportRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,21 @@ public static string GetDefaultOutputFileName(
{
var buffer = new StringBuilder();

// Guild and channel names
buffer.Append(
$"{guild.Name} - {channel.ParentNameWithFallback} - {channel.Name} [{channel.Id}]"
);
// Guild name
buffer.Append(guild.Name);

// Parent name
if (channel.Parent is not null)
buffer.Append(" - ").Append(channel.Parent.Name);

// Channel name and ID
buffer
.Append(" - ")
.Append(channel.Name)
.Append(' ')
.Append('[')
.Append(channel.Id)
.Append(']');

// Date range
if (after is not null || before is not null)
Expand Down Expand Up @@ -142,9 +153,8 @@ private static string FormatPath(
Channel channel,
Snowflake? after,
Snowflake? before
)
{
return Regex.Replace(
) =>
Regex.Replace(
path,
"%.",
m =>
Expand All @@ -153,14 +163,18 @@ private static string FormatPath(
{
"%g" => guild.Id.ToString(),
"%G" => guild.Name,
"%t" => channel.Parent?.Id.ToString() ?? "",
"%T" => channel.Parent?.Name ?? "",
"%c" => channel.Id.ToString(),
"%C" => channel.Name,
"%p" => channel.Position?.ToString(CultureInfo.InvariantCulture) ?? "0",
"%P"
=> channel.Parent?.Position?.ToString(CultureInfo.InvariantCulture)
?? "0",
"%a"
=> after?.ToDate().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
?? "",
Expand All @@ -172,12 +186,12 @@ private static string FormatPath(
"yyyy-MM-dd",
CultureInfo.InvariantCulture
),
"%%" => "%",
_ => m.Value
}
)
);
}

private static string GetOutputBaseFilePath(
Guild guild,
Expand Down
2 changes: 1 addition & 1 deletion DiscordChatExporter.Core/Exporting/HtmlMarkdownVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ protected override async ValueTask VisitMentionAsync(
else if (mention.Kind == MentionKind.Channel)
{
var channel = mention.TargetId?.Pipe(_context.TryGetChannel);
var symbol = channel?.Kind.IsVoice() == true ? "🔊" : "#";
var symbol = channel?.IsVoice == true ? "🔊" : "#";
var name = channel?.Name ?? "deleted-channel";

_buffer.Append(
Expand Down
10 changes: 5 additions & 5 deletions DiscordChatExporter.Core/Exporting/HtmlMessageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,22 @@ private bool CanJoinGroup(Message message)
if (_messageGroup.LastOrDefault() is not { } lastMessage)
return true;

// Reply messages cannot join existing groups because they need to appear first
if (message.Kind == MessageKind.Reply)
// Reply-like messages cannot join existing groups because they need to appear first
if (message.IsReplyLike)
return false;

// Grouping for system notifications
if (message.Kind.IsSystemNotification())
if (message.IsSystemNotification)
{
// Can only be grouped with other system notifications
if (!lastMessage.Kind.IsSystemNotification())
if (!lastMessage.IsSystemNotification)
return false;
}
// Grouping for normal messages
else
{
// Can only be grouped with other normal messages
if (lastMessage.Kind.IsSystemNotification())
if (lastMessage.IsSystemNotification)
return false;

// Messages must be within 7 minutes of each other
Expand Down
Loading

0 comments on commit 5abe748

Please sign in to comment.