Skip to content

Commit

Permalink
dm names
Browse files Browse the repository at this point in the history
-show usernames for dms
-cache guilds,users,channels
-refactor frontends to use one message content function
-also the same for channel names
  • Loading branch information
exp111 committed Nov 27, 2023
1 parent 17d216c commit f4cee9e
Show file tree
Hide file tree
Showing 17 changed files with 220 additions and 112 deletions.
2 changes: 1 addition & 1 deletion Turbulence.Core/ViewModels/ChannelListViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public async void Receive(ServerSelectedMsg m)

public void Receive(DMsSelectedMsg message)
{
//TODO: sort?
//TODO: sort
Channels.ReplaceAll(message.Channels);
}
}
Expand Down
13 changes: 12 additions & 1 deletion Turbulence.Core/ViewModels/Design/DesignChannelListViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,18 @@ public DesignChannelListViewModel()
new(12345678)
},
Type = ChannelType.DM,
Name = "DMs"
Name = "DM"
},
new()
{
Id = new(0),
RecipientIDs = new Snowflake[]
{
new(12345678),
new(12345679)
},
Type = ChannelType.GROUP_DM,
Name = "Group DM"
},
});
SelectedChannel = text;
Expand Down
10 changes: 1 addition & 9 deletions Turbulence.Core/ViewModels/MessagesViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.DependencyInjection;
using CommunityToolkit.Mvvm.Messaging;
using System.Collections.Generic;
using Turbulence.Discord;
using Turbulence.Discord.Models.DiscordChannel;
using static Turbulence.Discord.Models.DiscordChannel.ChannelType;

namespace Turbulence.Core.ViewModels;

Expand Down Expand Up @@ -45,13 +43,7 @@ public async Task RequestMoreMessages(bool older = true)

public async void Receive(ChannelSelectedMsg message)
{
Title = message.Channel.Type switch
{
DM => $"Messages: {(message.Channel.Recipients is { } recipients
? recipients.First().Username
: (await _client.GetChannel(message.Channel.Id)).Recipients?.First().Username) ?? "unknown"}",
_ => $"Messages: {message.Channel.Name}",
};
Title = $"Messages: {await _client.GetChannelName(message.Channel)}";

var channelMessages = await _client.GetMessages(message.Channel.Id);
CurrentMessages.Clear();
Expand Down
32 changes: 32 additions & 0 deletions Turbulence.Desktop/Converters/ChannelNameConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Avalonia.Controls;
using Avalonia.Data.Converters;
using CommunityToolkit.Mvvm.DependencyInjection;
using System.Globalization;
using Turbulence.Discord;
using Turbulence.Discord.Models.DiscordChannel;

namespace Turbulence.Desktop.Converters;

public class ChannelNameConverter : IValueConverter
{
private readonly IPlatformClient _client = Ioc.Default.GetService<IPlatformClient>()!;

public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is not Channel channel)
return null;

if (Design.IsDesignMode)
{
return channel.Name;
}

//TODO: fetch names from client (cache)
return Task.Run(() => _client.GetChannelName(channel)).Result;
}

public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
27 changes: 0 additions & 27 deletions Turbulence.Desktop/Converters/DMNameConverter.cs

This file was deleted.

15 changes: 5 additions & 10 deletions Turbulence.Desktop/Converters/MessageContentConverter.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
using Avalonia.Data.Converters;
using CommunityToolkit.Mvvm.DependencyInjection;
using System.Globalization;
using Turbulence.Discord;
using Turbulence.Discord.Models.DiscordChannel;
using static Turbulence.Discord.Models.DiscordChannel.MessageType;

namespace Turbulence.Desktop.Converters;

public class MessageContentConverter : IValueConverter
{
private readonly IPlatformClient _client = Ioc.Default.GetService<IPlatformClient>()!;

public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is not Message message)
return null;

var author = message.GetBestAuthorName();
return message.Type switch
{
THREAD_CREATED => $"{author} created thread \"{message.Content}\"",
CALL => $"{author} started a voice call",
CHANNEL_PINNED_MESSAGE => $"{author} pinned a message.",
USER_JOIN => $"{author} joined the server.",
_ => message.Content,
};
return _client.GetMessageContent(message);
}

public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class ChannelTemplateSelector : IDataTemplate
var channel = (Channel)param!;
var type = channel.Type switch
{
ChannelType.DM => "dm",
ChannelType.DM or ChannelType.GROUP_DM => "dm",
ChannelType.GUILD_CATEGORY => "category",
_ => "channel",
};
Expand Down
6 changes: 5 additions & 1 deletion Turbulence.Desktop/Views/Main/ChannelBarView.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:v="clr-namespace:Turbulence.Desktop.Views.Main"
xmlns:vm="clr-namespace:Turbulence.Core.ViewModels;assembly=Turbulence.Core"
xmlns:converters="using:Turbulence.Desktop.Converters"
x:DataType="vm:ChannelBarViewModel"
mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="500"
Height="40"
x:Class="Turbulence.Desktop.Views.Main.ChannelBarView">
<UserControl.DataContext>
<vm:ChannelBarViewModel />
</UserControl.DataContext>
<UserControl.Resources>
<converters:ChannelNameConverter x:Key="ChannelNameConverter" />
</UserControl.Resources>
<UserControl.Styles>
<Style Selector="Grid">
<Setter Property="Background" Value="#313338" />
Expand Down Expand Up @@ -38,7 +42,7 @@
<Grid RowDefinitions="*,auto">
<DockPanel IsVisible="{Binding !!Channel}" LastChildFill="False">
<StackPanel Margin="20,0" Orientation="Horizontal" DockPanel.Dock="Left">
<TextBlock FontWeight="SemiBold" Text="{Binding Channel.Name}" />
<TextBlock FontWeight="SemiBold" Text="{Binding Channel, Converter={StaticResource ChannelNameConverter}}" />
<Separator Height="20" Width="1" IsVisible="{Binding !!Channel.Topic}" />
<TextBlock Text="{Binding Channel.Topic}" />
</StackPanel>
Expand Down
6 changes: 3 additions & 3 deletions Turbulence.Desktop/Views/Main/ChannelListView.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</UserControl.DataContext>
<UserControl.Resources>
<converters:ObjectEqualsMultiConverter x:Key="EqualsConverter" />
<converters:DMNameConverter x:Key="DMNameConverter" />
<converters:ChannelNameConverter x:Key="ChannelNameConverter" />
</UserControl.Resources>
<UserControl.Styles>
<Style Selector="Button">
Expand Down Expand Up @@ -45,10 +45,10 @@
</MultiBinding>
</Classes.Checked>
<Grid ColumnDefinitions="20,*">
<!--The icon-->
<!--TODO: The icon-->
<TextBlock HorizontalAlignment="Center">#</TextBlock>
<!--User Name-->
<TextBlock Text="{Binding RecipientIDs, Converter={StaticResource DMNameConverter}}" Grid.Column="1" Margin="5,0" />
<TextBlock Text="{Binding ., Converter={StaticResource ChannelNameConverter}}" Grid.Column="1" Margin="5,0" />
</Grid>
</Button>
</DataTemplate>
Expand Down
5 changes: 5 additions & 0 deletions Turbulence.Discord/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ public static async Task<GuildMember> GetCurrentUserGuildMember(HttpClient clien
return await Get<GuildMember>(client, $"/users/@me/guilds/{guildId}/member");
}

public static async Task<User> GetUser(HttpClient client, ulong userId)
{
return await Get<User>(client, $"/users/{userId}");
}

public static async Task<Channel> GetChannel(HttpClient client, ulong channelId)
{
return await Get<Channel>(client, $"/channels/{channelId}");
Expand Down
60 changes: 52 additions & 8 deletions Turbulence.Discord/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ public Task SendIdentify(string token)
// TODO: probably shouldnt be static?
public User? CurrentUser { get; set; }
//public static List<dynamic> MemberInfos = new(); // TODO: should we like put the roles into a simple array?
public static Dictionary<Snowflake, Guild> Guilds = new();
//public static List<dynamic> ServerSettings = new(); // TODO: listen to the guild settings update event

// TODO: move these into a gateway class thingy?
Expand Down Expand Up @@ -323,7 +322,9 @@ public async void HandleGatewayMessage(GatewayPayload msg)

// Cache that shit // TODO: cache more/all. probably also need like private channels etc
foreach (var guild in ready.Guilds)
Guilds.Add(guild.Id, guild);
_cache.SetGuild(guild);
foreach (var user in ready.Users)
_cache.SetUser(user);
// foreach (var guildSetting in ready.user_guild_settings.entries)
// ServerSettings.Add(guildSetting);
CurrentUser = ready.User;
Expand Down Expand Up @@ -437,7 +438,30 @@ public async Task<Message> SendMessage(string content, Channel channelId)

public async Task<Guild> GetGuild(Snowflake guildId)
{
return Guilds.TryGetValue(guildId, out var ret) ? ret : await Api.GetGuild(HttpClient, guildId);
if (_cache.GetGuild(guildId) is { } guild)
return guild;
guild = await Api.GetGuild(HttpClient, guildId);
_logger?.Log($"Requested guild {guild.Name} ({guild.Id})", LogType.Networking, LogLevel.Debug);
_cache.SetGuild(guild);
return guild;
}
public async Task<User> GetUser(Snowflake userId)
{
if (_cache.GetUser(userId) is { } user)
return user;
user = await Api.GetUser(HttpClient, userId);
_logger?.Log($"Requested user {user.Username} ({user.Id})", LogType.Networking, LogLevel.Debug);
_cache.SetUser(user);
return user;
}
public async Task<Channel> GetChannel(Snowflake channelId)
{
if (_cache.GetChannel(channelId) is { } channel)
return channel;
channel = await Api.GetChannel(HttpClient, channelId);
_logger?.Log($"Requested channel {channel.Name} ({channel.Id})", LogType.Networking, LogLevel.Debug);
_cache.SetChannel(channel);
return channel;
}

public async Task<byte[]> GetAvatarAsync(User user, int size = 128)
Expand Down Expand Up @@ -474,11 +498,6 @@ public async Task<byte[]> GetEmojiAsync(Emoji emoji, int size = 32)
return img;
}

public async Task<Channel> GetChannel(Snowflake channelId)
{
return await Api.GetChannel(HttpClient, channelId);
}

public async Task<Message[]> GetPinnedMessages(Snowflake channelId)
{
return await Api.GetPinnedMessages(HttpClient, channelId);
Expand All @@ -488,5 +507,30 @@ public async Task<SearchResult> SearchMessages(SearchRequest request)
{
return await Api.SearchMessages(HttpClient, request);
}

public async Task<string> GetChannelName(Channel channel)
{
return channel.Type switch
{
ChannelType.DM or ChannelType.GROUP_DM => string.Join(", ",
(channel.Recipients is { } recipients
? recipients : (await GetChannel(channel.Id)).Recipients!).Select(u => u.GetBestName())),
_ => $"{channel.Name}",
};
}

public string GetMessageContent(Message message)
{
var author = message.GetBestAuthorName();
return message.Type switch
{
MessageType.THREAD_CREATED => $"{author} created thread \"{message.Content}\"",
MessageType.CALL => $"{author} started a voice call",
MessageType.CHANNEL_PINNED_MESSAGE => $"{author} pinned a message.",
MessageType.USER_JOIN => $"{author} joined the server.",
MessageType.RECIPIENT_ADD => $"{author} added {message.Mentions[0].GlobalName}.",
_ => message.Content,
};
}
}
}
4 changes: 3 additions & 1 deletion Turbulence.Discord/IPlatformClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public interface IPlatformClient
public User? CurrentUser { get; set; }
public Task<byte[]> GetAvatarAsync(User user, int size = 128);
public Task<byte[]> GetEmojiAsync(Emoji emoji, int size = 32);

public Task<string> GetChannelName(Channel channel);
public string GetMessageContent(Message message);

#region Discord specific shit that should not be here

public bool SendGatewayMessage<T>(GatewayOpcode opcode, T data);
Expand Down
2 changes: 1 addition & 1 deletion Turbulence.Discord/Models/DiscordChannel/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,6 @@ public static class MessageExtensions {
public static string GetBestAuthorName(this Message message)
{
// TODO: message.Member is null for some reason
return message.Member?.Nick ?? message.Author.GlobalName ?? message.Author.Username;
return message.Member?.Nick ?? message.Author.GetBestName();
}
}
9 changes: 9 additions & 0 deletions Turbulence.Discord/Models/DiscordUser/User.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using Turbulence.Discord.Models.DiscordChannel;

namespace Turbulence.Discord.Models.DiscordUser;

Expand Down Expand Up @@ -121,3 +122,11 @@ public record User {
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? AvatarDecoration { get; init; }
}

public static class UserExtensions
{
public static string GetBestName(this User user)
{
return user.GlobalName ?? user.Username;
}
}
Loading

0 comments on commit f4cee9e

Please sign in to comment.