Initial commit

This commit is contained in:
barelyprofessional
2024-03-25 20:11:49 +08:00
commit 9f92fc8e27
62 changed files with 17831 additions and 0 deletions

454
KfChatDotNetGui/.gitignore vendored Normal file
View File

@@ -0,0 +1,454 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

13
KfChatDotNetGui/App.axaml Normal file
View File

@@ -0,0 +1,13 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:KfChatDotNetGui"
x:Class="KfChatDotNetGui.App" RequestedThemeVariant="Dark">
<Application.DataTemplates>
<local:ViewLocator/>
</Application.DataTemplates>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
</Application.Styles>
</Application>

View File

@@ -0,0 +1,71 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using KfChatDotNetGui.Views;
using Newtonsoft.Json;
using NLog;
namespace KfChatDotNetGui
{
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
var logger = LogManager.GetCurrentClassLogger();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var dataContext = new MainWindowViewModel();
if (File.Exists("rooms.json"))
{
var rooms = JsonConvert.DeserializeObject<RoomSettingsModel>(File.ReadAllText("rooms.json"));
dataContext.RoomList = rooms!.Rooms;
}
dataContext.Messages.Add(new MainWindowViewModel.MessageViewModel
{
Author = "SneedChat",
Messages = new ObservableCollection<MainWindowViewModel.InnerMessageViewModel>{
new(){
Message = "Welcome to my shitty chat client.",
MessageId = 0,
OwnMessage = false
},
new()
{
Message = "Click on Settings -> Identity to configure your XenForo token so you may connect to SneedChat",
MessageId = 0,
OwnMessage = false
}
},
PostedAt = DateTimeOffset.Now,
AuthorId = -1
});
if (dataContext.RoomList.Count == 0)
{
dataContext.Messages[0].Messages.Add(new MainWindowViewModel.InnerMessageViewModel
{
Message = "Also it looks like you have no rooms configured. Click on Settings -> Rooms to configure the room list",
MessageId = 0,
OwnMessage = false
});
}
desktop.MainWindow = new MainWindow
{
DataContext = dataContext
};
}
base.OnFrameworkInitializationCompleted();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

View File

@@ -0,0 +1,42 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using KfChatDotNetGui.Models;
using Newtonsoft.Json;
namespace KfChatDotNetGui.Helpers;
public static class ForumIdentity
{
public static async Task<ForumIdentityModel?> GetForumIdentity(string xfSession, Uri sneedChatUri, string? antiDdosPowCookie = null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("xf_session", xfSession, "/", sneedChatUri.Host));
if (antiDdosPowCookie != null)
{
cookies.Add(new Cookie("z_ddos_pow", antiDdosPowCookie, "/", sneedChatUri.Host));
}
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.All, CookieContainer = cookies}))
{
client.DefaultRequestHeaders.UserAgent.TryParseAdd("KfChatDotNetGui/1.0");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
var response = await client.GetAsync(sneedChatUri);
response.EnsureSuccessStatusCode();
var html = await response.Content.ReadAsStringAsync();
var accountRegex = new Regex(@"user: (.+),");
var match = accountRegex.Match(html);
if (!match.Success)
{
throw new Exception("Shitty regex failed to extract account information");
}
var accountJs = match.Groups[1].Value;
return JsonConvert.DeserializeObject<ForumIdentityModel>(accountJs);
}
}
}

View File

@@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<!--Avalonia doesen't support TrimMode=link currently,but we are working on that https://github.com/AvaloniaUI/Avalonia/issues/6892 -->
<TrimMode>copyused</TrimMode>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<LangVersion>default</LangVersion>
</PropertyGroup>
<ItemGroup>
<Folder Include="Models\" />
<AvaloniaResource Include="Assets\**" />
<None Remove=".gitignore" />
</ItemGroup>
<ItemGroup>
<!--This helps with theme dll-s trimming.
If you will publish your application in self-contained mode with p:PublishTrimmed=true and it will use Fluent theme Default theme will be trimmed from the output and vice versa.
https://github.com/AvaloniaUI/Avalonia/issues/5593 -->
<TrimmableAssembly Include="Avalonia.Themes.Fluent" />
<TrimmableAssembly Include="Avalonia.Themes.Default" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.0.10" />
<PackageReference Include="Avalonia.Desktop" Version="11.0.10" />
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.0.10" />
<PackageReference Include="Avalonia.ReactiveUI" Version="11.0.10" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.0.10" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.59" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="ReactiveUI" Version="19.5.72" />
</ItemGroup>
<ItemGroup>
<None Remove="NLog.config" />
<Content Include="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace KfChatDotNetGui.Models;
public class ForumIdentityModel
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("avatar_url")]
public Uri AvatarUrl { get; set; }
// Guessing it'll be the user ID as an int but no idea as this list is empty for me
[JsonProperty("ignored_users")]
public List<string> IgnoredUsers { get; set; }
[JsonProperty("is_staff")]
public bool IsStaff { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System.Collections.Generic;
namespace KfChatDotNetGui.Models;
public class RoomSettingsModel
{
public class RoomList
{
public string Name { get; set; }
public int Id { get; set; }
}
public List<RoomList> Rooms { get; set; }
}

View File

@@ -0,0 +1,12 @@
using System;
namespace KfChatDotNetGui.Models;
public class SettingsModel
{
public string XfSessionToken { get; set; }
public Uri WsUri { get; set; }
public int ReconnectTimeout { get; set; }
public string AntiDdosPow { get; set; }
public string Username { get; set; }
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="~/nlog-internal.log">
<targets>
<target xsi:type="Console" name="console"/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="console" />
</rules>
</nlog>

3483
KfChatDotNetGui/NLog.xsd Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
using Avalonia;
using Avalonia.ReactiveUI;
using System;
namespace KfChatDotNetGui
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.UseReactiveUI();
}
}

View File

@@ -0,0 +1,28 @@
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using KfChatDotNetGui.ViewModels;
namespace KfChatDotNetGui
{
public class ViewLocator : IDataTemplate
{
public Control Build(object data)
{
var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
return (Control) Activator.CreateInstance(type)!;
}
return new TextBlock {Text = "Not Found: " + name};
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using ReactiveUI;
namespace KfChatDotNetGui.ViewModels;
public class IdentitySettingsWindowViewModel : ViewModelBase
{
private Uri _wsUri = new ("wss://kiwifarms.net/chat.ws");
public Uri WsUri
{
get => _wsUri;
set => this.RaiseAndSetIfChanged(ref _wsUri, value);
}
private string _xfSessionToken;
public string XfSessionToken
{
get => _xfSessionToken;
set => this.RaiseAndSetIfChanged(ref _xfSessionToken, value);
}
private string _antiDdosPow;
public string AntiDdosPow
{
get => _antiDdosPow;
set => this.RaiseAndSetIfChanged(ref _antiDdosPow, value);
}
private string _username;
public string Username
{
get => _username;
set => this.RaiseAndSetIfChanged(ref _username, value);
}
private int _reconnectTimeout = 30;
public int ReconnectTimeout
{
get => _reconnectTimeout;
set => this.RaiseAndSetIfChanged(ref _reconnectTimeout, value);
}
}

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia.Media;
using JetBrains.Annotations;
using KfChatDotNetGui.Models;
using ReactiveUI;
namespace KfChatDotNetGui.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public class InnerMessageViewModel : INotifyPropertyChanged
{
private string _message;
public string Message
{
get => _message;
set
{
if (_message == value) return;
_message = value;
OnPropertyChanged();
}
}
private bool _isHighlighted = false;
public bool IsHighlighted
{
get => _isHighlighted;
set
{
if (_isHighlighted == value) return;
_isHighlighted = value;
OnPropertyChanged();
}
}
public int MessageId { get; set; }
public bool OwnMessage { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MessageViewModel : INotifyPropertyChanged
{
private ObservableCollection<InnerMessageViewModel> _messages;
public ObservableCollection<InnerMessageViewModel> Messages
{
get => _messages;
set
{
if (_messages == value) return;
_messages = value;
OnPropertyChanged();
}
}
public DateTimeOffset PostedAt { get; set; }
public string Author { get; set; }
public int AuthorId { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class UserListViewModel
{
public string Name { get; set; }
public int Id { get; set; }
}
private string _statusText = "Not connected";
public string Status
{
get => _statusText;
set => this.RaiseAndSetIfChanged(ref _statusText, value);
}
private int _userId;
public int UserId
{
get => _userId;
set => this.RaiseAndSetIfChanged(ref _userId, value);
}
private List<RoomSettingsModel.RoomList> _roomList = new();
public List<RoomSettingsModel.RoomList> RoomList
{
get => _roomList;
set => this.RaiseAndSetIfChanged(ref _roomList, value);
}
private ObservableCollection<UserListViewModel> _userList = new();
public ObservableCollection<UserListViewModel> UserList
{
get => _userList;
set => this.RaiseAndSetIfChanged(ref _userList, value);
}
private ObservableCollection<MessageViewModel> _messages = new();
public ObservableCollection<MessageViewModel> Messages
{
get => _messages;
set => this.RaiseAndSetIfChanged(ref _messages, value);
}
}
}

View File

@@ -0,0 +1,20 @@
using System.Collections.ObjectModel;
using KfChatDotNetGui.Models;
using ReactiveUI;
namespace KfChatDotNetGui.ViewModels;
public class RoomSettingsWindowViewModel : ViewModelBase
{
private ObservableCollection<RoomSettingsModel.RoomList> _roomList = new()
{
new RoomSettingsModel.RoomList {Id = 1, Name = "General"}
};
public ObservableCollection<RoomSettingsModel.RoomList> RoomList
{
get => _roomList;
set => this.RaiseAndSetIfChanged(ref _roomList, value);
}
}

View File

@@ -0,0 +1,8 @@
using ReactiveUI;
namespace KfChatDotNetGui.ViewModels
{
public class ViewModelBase : ReactiveObject
{
}
}

View File

@@ -0,0 +1,32 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:KfChatDotNetGui.ViewModels"
mc:Ignorable="d" d:DesignWidth="400" d:DesignHeight="250"
x:Class="KfChatDotNetGui.Views.IdentitySettingsWindow"
Width="450"
Height="360"
Title="Identity Settings">
<Design.DataContext>
<vm:IdentitySettingsWindowViewModel/>
</Design.DataContext>
<StackPanel Margin="10">
<Label>XenForo Session Token</Label>
<Grid ColumnDefinitions="*,Auto">
<TextBox Text="{Binding XfSessionToken}"/>
<Button Click="TestTokenButton_OnClick" Grid.Column="1">Test Token</Button>
</Grid>
<Label>SneedChat Websocket URL</Label>
<TextBox Text="{Binding WsUri}"/>
<Label>Websocket Timeout</Label>
<TextBox Text="{Binding ReconnectTimeout}"/>
<Label>Anti-DDoS PoW Cookie Value</Label>
<TextBox Text="{Binding AntiDdosPow}"/>
<Label>Forum Username (Only use if test token fails due to Anti-DDoS)</Label>
<TextBox Text="{Binding Username}"/>
<Button Margin="0, 10, 0, 0" Click="SaveButton_OnClick">Save</Button>
<TextBlock Margin="0, 10, 0, 0" Name="SaveResult" IsVisible="False"/>
</StackPanel>
</Window>

View File

@@ -0,0 +1,116 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Threading;
using KfChatDotNetGui.Helpers;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using Newtonsoft.Json;
using NLog;
namespace KfChatDotNetGui.Views;
public partial class IdentitySettingsWindow : Window
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public IdentitySettingsWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void SaveButton_OnClick(object? sender, RoutedEventArgs e)
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
try
{
var settings = new SettingsModel
{
XfSessionToken = (DataContext as IdentitySettingsWindowViewModel).XfSessionToken,
WsUri = (DataContext as IdentitySettingsWindowViewModel).WsUri,
ReconnectTimeout = (DataContext as IdentitySettingsWindowViewModel).ReconnectTimeout,
AntiDdosPow = (DataContext as IdentitySettingsWindowViewModel).AntiDdosPow,
Username = (DataContext as IdentitySettingsWindowViewModel).Username
};
File.WriteAllText("settings.json", JsonConvert.SerializeObject(settings, Formatting.Indented));
}
catch (Exception ex)
{
_logger.Error(ex);
saveResult.Foreground = Brushes.Red;
saveResult.Text = "Failed to save settings due to an error: " + ex.Message;
saveResult.IsVisible = true;
return;
}
saveResult.Foreground = Brushes.Green;
saveResult.Text = "Successfully saved settings!";
saveResult.IsVisible = true;
}
private void TestTokenButton_OnClick(object? sender, RoutedEventArgs e)
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = Brushes.Yellow;
saveResult.Text = "Testing XenForo token";
saveResult.IsVisible = true;
var kfHost = (DataContext as IdentitySettingsWindowViewModel).WsUri.Host;
Dispatcher.UIThread.Post(
() => TestXfToken((DataContext as IdentitySettingsWindowViewModel).XfSessionToken, kfHost, (DataContext as IdentitySettingsWindowViewModel).AntiDdosPow),
DispatcherPriority.Background);
}
public void UpdateSaveText(ISolidColorBrush brush, string text)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = brush;
saveResult.Text = text;
if (!saveResult.IsVisible)
{
saveResult.IsVisible = true;
}
});
}
public async Task TestXfToken(string xfToken, string kfHost, string? antiDdosPowToken = null)
{
ForumIdentityModel forumIdentity;
try
{
forumIdentity = await ForumIdentity.GetForumIdentity(xfToken, new Uri($"https://{kfHost}/test-chat"), antiDdosPowToken);
}
catch (Exception ex)
{
_logger.Error(ex);
UpdateSaveText(Brushes.Red, "Caught exception while testing token: " + ex.Message);
return;
}
if (forumIdentity == null)
{
UpdateSaveText(Brushes.Red, "Failed to parse SneedChat page, got a null when deserializing the user info");
return;
}
if (forumIdentity.Id == 0)
{
UpdateSaveText(Brushes.Red, "Token is invalid, SneedChat page returned Guest");
return;
}
UpdateSaveText(Brushes.Green, "Success! Token belongs to " + forumIdentity.Username);
}
}

View File

@@ -0,0 +1,107 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:KfChatDotNetGui.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
Width="800"
Height="450"
x:Class="KfChatDotNetGui.Views.MainWindow"
Icon="/Assets/avalonia-logo.ico"
Title="KfChatDotNetGui">
<Design.DataContext>
<vm:MainWindowViewModel/>
</Design.DataContext>
<Window.Styles>
<Style Selector="ListBoxItem">
<Setter Property="VerticalContentAlignment" Value="Stretch" />
</Style>
</Window.Styles>
<Grid RowDefinitions="Auto,*,Auto,Auto">
<Menu Grid.Row="0">
<MenuItem Header="_File">
<MenuItem Click="ConnectMenuItem_OnClick" Header="_Connect"/>
<Separator/>
<MenuItem Click="ExitMenuItem_OnClick" Header="_Exit"/>
</MenuItem>
<MenuItem Header="_Settings">
<MenuItem Click="IdentitySettings_OnClick" Header="_Identity"/>
<MenuItem Click="RoomSettingsMenuItem_OnClick" Header="_Rooms"/>
<MenuItem Header="_Preferences"/>
</MenuItem>
</Menu>
<Grid Grid.Row="1" ColumnDefinitions="100,4,*,4,200">
<ListBox SelectionChanged="RoomList_OnSelectionChanged" Grid.Column="0" Name="RoomList" ItemsSource="{Binding RoomList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GridSplitter Grid.Column="1"/>
<ListBox Grid.Column="2" Name="ChatMessageList" ItemsSource="{Binding Messages}">
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="VerticalAlignment" Value="Stretch"/>
</Style>
</ListBox.Styles>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="Auto,*">
<!-- <Image VerticalAlignment="Top" Margin="0,0,5,0" MaxHeight="32" Grid.Column="0" Source="{Binding Avatar}"/> -->
<Grid Grid.Column="1" RowDefinitions="Auto,Auto">
<Grid Grid.Row="0" ColumnDefinitions="Auto,Auto">
<Button Grid.Column="0" Click="AuthorNameButton_OnClick" Foreground="LightBlue" Background="Transparent" Padding="0" Margin="0,0,5,0" Content="{Binding Author}"/>
<TextBlock Grid.Column="1" FontSize="10" VerticalAlignment="Center" Foreground="Gray" Text="{Binding PostedAt}"/>
</Grid>
<!-- <TextBlock TextWrapping="Wrap" FontWeight="Light" Grid.Row="1" Text="{Binding Message}"/> -->
<ListBox Grid.Row="1" ItemsSource="{Binding Messages}" PointerEntered="OuterMessageRow_OnPointerEnter" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="0"/>
<Setter Property="Margin" Value="0"/>
</Style>
<Style Selector="Button">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="11"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Margin" Value="0,0,5,0"/>
</Style>
</ListBox.Styles>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,Auto" RowDefinitions="*">
<TextBlock Grid.Column="0" TextWrapping="Wrap" FontWeight="Light" Text="{Binding Message}"/>
<WrapPanel Grid.Column="1" IsVisible="{Binding IsHighlighted}">
<Button Click="MessageEditButton_OnClick" IsVisible="{Binding OwnMessage}" Foreground="Orange">Edit</Button>
<Button Click="MessageDeleteButton_OnClick" IsVisible="{Binding OwnMessage}" Foreground="Red">Delete</Button>
<Button Click="CopyButton_OnClick" Foreground="LightBlue">Copy</Button>
</WrapPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GridSplitter Grid.Column="3"></GridSplitter>
<ListBox Grid.Column="4" Name="UserList" ItemsSource="{Binding UserList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
<Grid Margin="1" Grid.Row="2" ColumnDefinitions="*,Auto">
<TextBox KeyDown="NewChatMessage_OnKeyDown" Name="NewChatMessage" Grid.Column="0" BorderBrush="Gray" TextWrapping="NoWrap"/>
<Button Click="NewChatMessageSubmitButton_OnClick" Grid.Column="1">Send</Button>
</Grid>
<TextBlock Grid.Row="3" Text="{Binding Status}"/>
</Grid>
</Window>

View File

@@ -0,0 +1,499 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Markup.Xaml;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using KfChatDotNetWsClient;
using KfChatDotNetWsClient.Models;
using KfChatDotNetWsClient.Models.Events;
using KfChatDotNetWsClient.Models.Json;
using Newtonsoft.Json;
using NLog;
using Websocket.Client;
namespace KfChatDotNetGui.Views
{
public partial class MainWindow : Window
{
private Logger _logger = LogManager.GetCurrentClassLogger();
// Using an empty config as we can update it later through the UpdateConfig method
// Having this instance created early is handy for wiring up the events
private ChatClient _chatClient = new(new ChatClientConfigModel());
private SettingsModel _settings;
private int _currentRoom;
private ForumIdentityModel _forumIdentity;
public MainWindow()
{
InitializeComponent();
_chatClient.OnMessages += OnMessages;
_chatClient.OnUsersJoined += OnUsersJoined;
_chatClient.OnUsersParted += OnUsersParted;
_chatClient.OnWsReconnect += OnOnWsReconnect;
_chatClient.OnWsDisconnection += OnOnWsDisconnection;
_chatClient.OnDeleteMessages += OnDeleteMessages;
_chatClient.OnFailedToJoinRoom += OnFailedToJoinRoom;
}
private void OnFailedToJoinRoom(object sender, string message)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
UpdateStatus($"Failed to join room, room ID {_currentRoom} is probably invalid");
});
}
private void OnDeleteMessages(object sender, List<int> messageIds)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
_logger.Info($"Received delete event for following message IDs: {string.Join(',', messageIds)}");
// Gotta make a copy of all the messages (annoyingly) as we'll be deleting stuff and .NET has a very obvious limitation there
var messages = (DataContext as MainWindowViewModel).Messages.ToList();
foreach (var message in messages)
{
foreach (var innerMessage in message.Messages.Where(m => messageIds.Contains(m.MessageId)))
{
// Remove the parent message thingy as otherwise it just shows as a blank item
if (message.Messages.Count == 1)
{
_logger.Info("Removing parent message box");
(DataContext as MainWindowViewModel).Messages.Remove(message);
}
// Go scavenging if there are multiple messages and we don't want to lose the lot
else
{
(DataContext as MainWindowViewModel)
.Messages[(DataContext as MainWindowViewModel).Messages.IndexOf(message)].Messages
.Remove(innerMessage);
}
_logger.Info($"Removed {innerMessage.MessageId}");
}
}
});
}
private void OnOnWsDisconnection(object sender, DisconnectionInfo disconnectionInfo)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
UpdateStatus($"Disconnected from SneedChat due to {disconnectionInfo.Type}. Client should automatically attempt to reconnect");
});
}
private void OnOnWsReconnect(object sender, ReconnectionInfo reconnectionInfo)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
UpdateStatus("Reconnected to SneedChat. Reason was " + reconnectionInfo.Type);
(DataContext as MainWindowViewModel).Messages.Clear();
(DataContext as MainWindowViewModel).UserList.Clear();
});
_chatClient.JoinRoom(_currentRoom);
}
private void IdentitySettings_OnClick(object? sender, RoutedEventArgs e)
{
var context = new IdentitySettingsWindowViewModel();
if (File.Exists("settings.json"))
{
var settings = JsonConvert.DeserializeObject<SettingsModel>(File.ReadAllText("settings.json"));
context.WsUri = settings.WsUri;
context.XfSessionToken = settings.XfSessionToken;
context.ReconnectTimeout = settings.ReconnectTimeout;
context.AntiDdosPow = settings.AntiDdosPow;
context.Username = settings.Username;
}
var identitySettingsWindow = new IdentitySettingsWindow
{
DataContext = context
};
identitySettingsWindow.ShowDialog(this);
identitySettingsWindow.Closed += (o, args) =>
{
ReloadSettings();
};
}
private void ExitMenuItem_OnClick(object? sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private async Task ConnectToSneedChat()
{
UpdateStatus("Connecting to SneedChat");
if (!File.Exists("settings.json"))
{
_logger.Error("Cannot find settings.json and therefore unable to connect to SneedChat, notifying the user through the status bar");
UpdateStatus("Unable to connect as client has not been configured (settings.json missing)");
return;
}
ReloadSettings();
UpdateStatus("Testing XenForo token validity");
ForumIdentityModel forumIdentity;
if (string.IsNullOrEmpty(_settings.Username))
{
try
{
forumIdentity = await Helpers.ForumIdentity.GetForumIdentity(_settings.XfSessionToken,
new Uri($"https://{_settings.WsUri.Host}/test-chat"), _settings.AntiDdosPow);
}
catch (Exception ex)
{
_logger.Error(ex);
UpdateStatus("Failed to test XenForo token, caught exception " + ex.Message);
return;
}
}
else
{
forumIdentity = new ForumIdentityModel
{
Username = _settings.Username,
Id = int.MaxValue
};
}
if (forumIdentity == null)
{
UpdateStatus("Failed to deserialize account info on SneedChat page");
return;
}
if (forumIdentity.Id == 0)
{
UpdateStatus("Token failed, SneedChat page returned Guest");
return;
}
UpdateStatus("Token works! It belongs to " + forumIdentity.Username);
_forumIdentity = forumIdentity;
(DataContext as MainWindowViewModel).UserId = _forumIdentity.Id;
var roomListControl = this.FindControl<ListBox>("RoomList");
RoomSettingsModel.RoomList initialRoom;
if (roomListControl.SelectedItem == null)
{
initialRoom = (DataContext as MainWindowViewModel).RoomList.First();
}
else
{
initialRoom = (RoomSettingsModel.RoomList) roomListControl.SelectedItem;
}
_chatClient.UpdateConfig(new ChatClientConfigModel
{
CookieDomain = _settings.WsUri.Host,
ReconnectTimeout = _settings.ReconnectTimeout,
WsUri = _settings.WsUri,
XfSessionToken = _settings.XfSessionToken
});
await _chatClient.StartWsClient();
_chatClient.JoinRoom(initialRoom.Id);
_currentRoom = initialRoom.Id;
UpdateStatus("Connected!");
}
private void OnUsersJoined(object sender, List<UserModel> users, UsersJsonModel jsonPayload)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
foreach (var user in users)
{
if ((DataContext as MainWindowViewModel).UserList.FirstOrDefault(x => x.Id == user.Id) != null)
{
_logger.Info($"{user.Username} ({user.Id}) is already in the list but has joined again. New tab? Ignoring!");
continue;
}
(DataContext as MainWindowViewModel).UserList.Add(new MainWindowViewModel.UserListViewModel
{
Id = user.Id,
Name = user.Username
});
}
UpdateUserTotalStatus();
});
}
private void OnUsersParted(object sender, List<int> userIds)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
foreach (var id in userIds)
{
var row = (DataContext as MainWindowViewModel).UserList.FirstOrDefault(x => x.Id == id);
if (row == null)
{
_logger.Info($"A user ({id}) who isn't in the list has parted, ignoring!");
continue;
}
(DataContext as MainWindowViewModel).UserList.Remove(row);
}
UpdateUserTotalStatus();
});
}
private void OnMessages(object sender, List<MessageModel> messages, MessagesJsonModel jsonPayload)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
var previousMessage = (DataContext as MainWindowViewModel).Messages.LastOrDefault();
if (previousMessage == null)
{
previousMessage = new MainWindowViewModel.MessageViewModel {AuthorId = -1};
}
foreach (var message in messages)
{
_logger.Info("Received message, data payload next");
_logger.Info(JsonConvert.SerializeObject(message, Formatting.Indented));
if (message.RoomId != _currentRoom)
{
_logger.Info($"Message {message.MessageId} belongs to another room (we're in {_currentRoom}, this one was for {message.RoomId}), ignoring.");
continue;
}
if (message.MessageEditDate != null)
{
_logger.Info("Received an edit. Going to rewrite message if it already exists, " +
"if it doesn't, nothing will happen as this would occur when loading historically modified messages.");
foreach (var msg in (DataContext as MainWindowViewModel).Messages)
{
foreach (var innerMsg in msg.Messages.Where(m => m.MessageId == message.MessageId))
{
innerMsg.Message = WebUtility.HtmlDecode(message.MessageRaw);
_logger.Info("Found the original message, text has been overwritten");
return;
}
}
_logger.Info("Never ended up finding the original message so this was probably historical");
}
if (previousMessage.AuthorId == message.Author.Id)
{
_logger.Info("Found a message from the same author, merging");
var lastMessage = (DataContext as MainWindowViewModel).Messages.Last();
lastMessage.Messages.Add(new MainWindowViewModel.InnerMessageViewModel
{
Message = WebUtility.HtmlDecode(message.MessageRaw),
MessageId = message.MessageId,
OwnMessage = _forumIdentity.Username == message.Author.Username
});
continue;
}
var viewMessage = new MainWindowViewModel.MessageViewModel
{
Author = message.Author.Username,
Messages = new ObservableCollection<MainWindowViewModel.InnerMessageViewModel>
{
new()
{
Message = WebUtility.HtmlDecode(message.MessageRaw),
MessageId = message.MessageId,
OwnMessage = _forumIdentity.Username == message.Author.Username
}
},
PostedAt = message.MessageDate.LocalDateTime,
AuthorId = message.Author.Id
};
(DataContext as MainWindowViewModel).Messages.Add(viewMessage);
previousMessage = viewMessage;
}
var messagesControl = this.FindControl<ListBox>("ChatMessageList");
messagesControl.ScrollIntoView((DataContext as MainWindowViewModel).Messages.Last());
});
}
private void UpdateStatus(string newStatus)
{
(DataContext as MainWindowViewModel)!.Status = newStatus;
}
private void ConnectMenuItem_OnClick(object? sender, RoutedEventArgs e)
{
Dispatcher.UIThread.Post(() => ConnectToSneedChat(), DispatcherPriority.Background);
}
private void RoomSettingsMenuItem_OnClick(object? sender, RoutedEventArgs e)
{
var context = new RoomSettingsWindowViewModel();
if (File.Exists("rooms.json"))
{
var settings = JsonConvert.DeserializeObject<RoomSettingsModel>(File.ReadAllText("rooms.json"));
context.RoomList.Clear();
foreach (var room in settings.Rooms)
{
context.RoomList.Add(new RoomSettingsModel.RoomList
{
Id = room.Id,
Name = room.Name
});
}
}
var roomSettingsWindow = new RoomSettingsWindow
{
DataContext = context
};
roomSettingsWindow.ShowDialog(this);
roomSettingsWindow.Closed += (o, args) =>
{
ReloadRoomList();
};
}
private void ReloadSettings()
{
if (!File.Exists("settings.json"))
{
_logger.Error("Was asked to reload the settings but settings.json doesn't exist so I won't bother");
return;
}
var settings = JsonConvert.DeserializeObject<SettingsModel>(File.ReadAllText("settings.json"));
_settings = settings;
}
private void ReloadRoomList()
{
if (!File.Exists("rooms.json"))
{
_logger.Error("Was asked to reload the room list but rooms.json doesn't exist so I won't bother");
return;
}
var rooms = JsonConvert.DeserializeObject<RoomSettingsModel>(File.ReadAllText("rooms.json"));
(DataContext as MainWindowViewModel)!.RoomList = rooms!.Rooms;
}
private void RoomList_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (!_chatClient.IsConnected())
{
UpdateStatus("Cannot join room as client is not connected");
return;
}
var roomListControl = this.FindControl<ListBox>("RoomList");
var room = (RoomSettingsModel.RoomList) roomListControl.SelectedItem!;
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (room == null)
{
_logger.Info("Got a selection change on room list with a null selected item. This seems to just happen sometimes, ignoring.");
return;
}
UpdateStatus($"Connected! Changing to {room.Name}");
(DataContext as MainWindowViewModel).Messages.Clear();
(DataContext as MainWindowViewModel).UserList.Clear();
_chatClient.JoinRoom(room.Id);
_currentRoom = room.Id;
}
private MainWindowViewModel.MessageViewModel? GetCurrentlySelectedMessage()
{
var messagesControl = this.FindControl<ListBox>("ChatMessageList");
return messagesControl.SelectedItem as MainWindowViewModel.MessageViewModel;
}
private void NewChatMessage_OnKeyDown(object? sender, KeyEventArgs e)
{
if (e.Key is not (Key.Enter or Key.Return))
{
return;
}
TrySendMessageFromTextBox();
}
private void NewChatMessageSubmitButton_OnClick(object? sender, RoutedEventArgs e)
{
TrySendMessageFromTextBox();
}
private void TrySendMessageFromTextBox()
{
if (!_chatClient.IsConnected())
{
UpdateStatus("Cannot send a message while disconnected");
return;
}
var newChatMessage = this.FindControl<TextBox>("NewChatMessage");
_chatClient.SendMessage(newChatMessage.Text);
newChatMessage.Clear();
}
private void UpdateUserTotalStatus()
{
var userCount = (DataContext as MainWindowViewModel).UserList.Count;
UpdateStatus($"Connected! {userCount} users in chat");
}
private void MessageEditButton_OnClick(object? sender, RoutedEventArgs e)
{
_logger.Info("Edit button clicked for " + ((e.Source as Button).DataContext as MainWindowViewModel.InnerMessageViewModel).MessageId);
}
private void CopyButton_OnClick(object? sender, RoutedEventArgs e)
{
var message = (e.Source as Button).DataContext as MainWindowViewModel.InnerMessageViewModel;
if (message == null)
{
_logger.Info("Caught a null when trying to access the inner message model instance for the purposes of copying");
return;
}
_logger.Info($"Copying {message.MessageId} to clipboard");
GetTopLevel(e.Source as Button)?.Clipboard?.SetTextAsync(message.Message).Wait();
}
private void InnerMessageRow_OnPointerEnter(object? sender, PointerEventArgs e)
{
((e.Source as ListBoxItem).DataContext as MainWindowViewModel.InnerMessageViewModel).IsHighlighted = true;
}
private void InnerMessageRow_OnPointerLeave(object? sender, PointerEventArgs e)
{
((e.Source as ListBoxItem).DataContext as MainWindowViewModel.InnerMessageViewModel).IsHighlighted = false;
}
private void OuterMessageRow_OnPointerEnter(object? sender, PointerEventArgs e)
{
var children = (e.Source as ListBox).GetLogicalChildren().Cast<ListBoxItem>();
foreach (var child in children)
{
// Bit of a ghetto hack but it ensures that there's only ever one subscriber
child.PointerEntered -= InnerMessageRow_OnPointerEnter;
child.PointerExited -= InnerMessageRow_OnPointerLeave;
child.PointerEntered += InnerMessageRow_OnPointerEnter;
child.PointerExited += InnerMessageRow_OnPointerLeave;
}
}
private void MessageDeleteButton_OnClick(object? sender, RoutedEventArgs e)
{
var newChatMessage = this.FindControl<TextBox>("NewChatMessage");
var messageId = ((e.Source as Button).DataContext as MainWindowViewModel.InnerMessageViewModel).MessageId;
newChatMessage.Text = "/delete " + messageId;
}
private void AuthorNameButton_OnClick(object? sender, RoutedEventArgs e)
{
var message = (e.Source as Button).DataContext as MainWindowViewModel.MessageViewModel;
var newChatMessage = this.FindControl<TextBox>("NewChatMessage");
newChatMessage.Text += $"@{message.Author}, ";
newChatMessage.Focus();
newChatMessage.SelectionStart = newChatMessage.Text.Length;
newChatMessage.SelectionEnd = newChatMessage.Text.Length;
}
}
}

View File

@@ -0,0 +1,28 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:KfChatDotNetGui.ViewModels"
mc:Ignorable="d" d:DesignWidth="350" d:DesignHeight="320"
x:Class="KfChatDotNetGui.Views.RoomSettingsWindow"
Width="350"
Height="320"
Title="Room Settings">
<Design.DataContext>
<vm:RoomSettingsWindowViewModel/>
</Design.DataContext>
<StackPanel Margin="10">
<Label>Room List</Label>
<DataGrid Name="RoomGrid" ItemsSource="{Binding RoomList}" AutoGenerateColumns="True" Height="150" VerticalScrollBarVisibility="Visible"/>
<WrapPanel Margin="0,10,0,0">
<Button Click="AddRowButton_OnClick" Margin="0,0,5,0">Add Row</Button>
<Button Click="DeleteSelectedRowsButton_OnClick">Delete Selected Rows</Button>
</WrapPanel>
<WrapPanel Margin="0,10,0,0">
<Button Margin="0,0,5,0" Click="SaveButton_OnClick">Save</Button>
<Button Click="AutoDetectButton_OnClick">Auto-Detect</Button>
</WrapPanel>
<TextBlock TextWrapping="Wrap" Margin="0, 10, 0, 0" Name="SaveResult" IsVisible="False"/>
</StackPanel>
</Window>

View File

@@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Threading;
using HtmlAgilityPack;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using Newtonsoft.Json;
using NLog;
namespace KfChatDotNetGui.Views;
public partial class RoomSettingsWindow : Window
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public RoomSettingsWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void SaveButton_OnClick(object? sender, RoutedEventArgs e)
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
try
{
var roomSettings = new RoomSettingsModel
{
Rooms = new List<RoomSettingsModel.RoomList>()
};
foreach (var room in (DataContext as RoomSettingsWindowViewModel).RoomList)
{
roomSettings.Rooms.Add(new RoomSettingsModel.RoomList
{
Id = room.Id,
Name = room.Name
});
}
File.WriteAllText("rooms.json", JsonConvert.SerializeObject(roomSettings, Formatting.Indented));
}
catch (Exception ex)
{
_logger.Error(e);
saveResult.Foreground = Brushes.Red;
saveResult.Text = "Failed to save rooms due to an error: " + ex.Message;
saveResult.IsVisible = true;
return;
}
saveResult.Foreground = Brushes.Green;
saveResult.Text = "Successfully saved rooms!";
saveResult.IsVisible = true;
}
private void AddRowButton_OnClick(object? sender, RoutedEventArgs e)
{
(DataContext as RoomSettingsWindowViewModel).RoomList.Add(new RoomSettingsModel.RoomList());
}
private void DeleteSelectedRowsButton_OnClick(object? sender, RoutedEventArgs e)
{
var roomGrid = this.FindControl<DataGrid>("RoomGrid");
var roomList = (DataContext as RoomSettingsWindowViewModel).RoomList.ToList();
foreach (var room in roomGrid.SelectedItems)
{
roomList.Remove(room as RoomSettingsModel.RoomList);
}
(DataContext as RoomSettingsWindowViewModel).RoomList =
new ObservableCollection<RoomSettingsModel.RoomList>(roomList);
}
private void AutoDetectButton_OnClick(object? sender, RoutedEventArgs e)
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = Brushes.Yellow;
saveResult.Text = "Downloading the SneedChat page";
saveResult.IsVisible = true;
Dispatcher.UIThread.Post(() => AutoDetectRooms(), DispatcherPriority.Background);
}
private async Task AutoDetectRooms()
{
var kfDomain = "kiwifarms.net";
if (File.Exists("settings.json"))
{
var settings = JsonConvert.DeserializeObject<SettingsModel>(await File.ReadAllTextAsync("settings.json"));
kfDomain = settings.WsUri.Host;
}
Uri sneedChatUri = new Uri($"https://{kfDomain}/test-chat");
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.All}))
{
client.DefaultRequestHeaders.UserAgent.TryParseAdd("KfChatDotNetGui/1.0");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
HttpResponseMessage response = await client.GetAsync(sneedChatUri);
if (!response.IsSuccessStatusCode)
{
_logger.Error($"Got HTTP error {response.StatusCode} when fetching {sneedChatUri}");
Dispatcher.UIThread.InvokeAsync(() =>
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = Brushes.Red;
saveResult.Text = $"Failed to load the SneedChat page due to an HTTP error (Status code {response.StatusCode})";
saveResult.IsVisible = true;
});
return;
}
var html = await response.Content.ReadAsStringAsync();
var document = new HtmlDocument();
document.LoadHtml(html);
var roomList = document.DocumentNode.SelectNodes("//a[@class=\"chat-room\"]");
if (roomList == null)
{
_logger.Error("Chat room list is null, xpath for it is probably broken");
Dispatcher.UIThread.InvokeAsync(() =>
{
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = Brushes.Red;
saveResult.Text = "Failed to parse the SneedChat page, list of rooms was null";
saveResult.IsVisible = true;
});
return;
}
List<RoomSettingsModel.RoomList> roomListModel = new List<RoomSettingsModel.RoomList>();
foreach (var element in roomList)
{
roomListModel.Add(new RoomSettingsModel.RoomList
{
Id = element.GetAttributeValue("data-id", 0),
Name = WebUtility.HtmlDecode(element.InnerText)
});
}
Dispatcher.UIThread.InvokeAsync(() =>
{
(DataContext as RoomSettingsWindowViewModel).RoomList.Clear();
foreach (var room in roomListModel)
{
(DataContext as RoomSettingsWindowViewModel).RoomList.Add(room);
}
var saveResult = this.FindControl<TextBlock>("SaveResult");
saveResult.Foreground = Brushes.Green;
saveResult.Text = "Populated list using SneedChat page. Remember to hit Save when you're done!";
saveResult.IsVisible = true;
});
}
}
}