Removed unused projects from the solution. They now just live in "old"

This commit is contained in:
barelyprofessional
2025-06-07 17:39:36 -05:00
parent be355e83df
commit 3ce03fa1e7
45 changed files with 0 additions and 16620 deletions

View File

@@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\KfChatDotNetBot\KfChatDotNetBot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.4.0" />
</ItemGroup>
<ItemGroup>
<Content Update="NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -1,15 +0,0 @@
<?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="ColoredConsole" name="console"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console" />
</rules>
</nlog>

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +0,0 @@
// This new template sucks
using NLog;
var logger = LogManager.GetCurrentClassLogger();
logger.Info("Starting up");
var token = "authorization token!";
var proxy = "socks5://whatever:1080";
var discord = new KfChatDotNetBot.Services.DiscordService(token, proxy);
discord.StartWsClient().Wait();
logger.Info("Started");
var exitEvent = new ManualResetEvent(false);
exitEvent.WaitOne();

View File

@@ -2,20 +2,10 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetWsClient", "KfChatDotNetWsClient\KfChatDotNetWsClient.csproj", "{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetWsClient", "KfChatDotNetWsClient\KfChatDotNetWsClient.csproj", "{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetCli", "KfChatDotNetCli\KfChatDotNetCli.csproj", "{A4D19F8E-5A1F-4A66-BC42-214DB9D5429B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetGui", "KfChatDotNetGui\KfChatDotNetGui.csproj", "{B2A5D4EE-5EB6-4F0B-BB5E-2B87AAFBFB5B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KickWsClient", "KickWsClient\KickWsClient.csproj", "{DECBB95C-2C9F-44C2-AFA3-3741986FBA38}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KickWsClient", "KickWsClient\KickWsClient.csproj", "{DECBB95C-2C9F-44C2-AFA3-3741986FBA38}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetBot", "KfChatDotNetBot\KfChatDotNetBot.csproj", "{4734E0A4-150E-4915-B905-928BB4BE3FF6}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetBot", "KfChatDotNetBot\KfChatDotNetBot.csproj", "{4734E0A4-150E-4915-B905-928BB4BE3FF6}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreeXplWsClient", "ThreeXplWsClient\ThreeXplWsClient.csproj", "{3D72D70A-48AD-4EE8-89DC-C78153EEA879}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreeXplCliClient", "ThreeXplCliClient\ThreeXplCliClient.csproj", "{D098E281-5535-4A07-9514-57AF78704B0C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CliDiscordPacketDump", "CliDiscordPacketDump\CliDiscordPacketDump.csproj", "{792ECCCD-FAC3-4CE5-A760-988080960BB9}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -26,14 +16,6 @@ Global
{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Release|Any CPU.Build.0 = Release|Any CPU {B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Release|Any CPU.Build.0 = Release|Any CPU
{A4D19F8E-5A1F-4A66-BC42-214DB9D5429B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A4D19F8E-5A1F-4A66-BC42-214DB9D5429B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A4D19F8E-5A1F-4A66-BC42-214DB9D5429B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A4D19F8E-5A1F-4A66-BC42-214DB9D5429B}.Release|Any CPU.Build.0 = Release|Any CPU
{B2A5D4EE-5EB6-4F0B-BB5E-2B87AAFBFB5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2A5D4EE-5EB6-4F0B-BB5E-2B87AAFBFB5B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2A5D4EE-5EB6-4F0B-BB5E-2B87AAFBFB5B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2A5D4EE-5EB6-4F0B-BB5E-2B87AAFBFB5B}.Release|Any CPU.Build.0 = Release|Any CPU
{DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Debug|Any CPU.Build.0 = Debug|Any CPU {DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Release|Any CPU.ActiveCfg = Release|Any CPU {DECBB95C-2C9F-44C2-AFA3-3741986FBA38}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -42,17 +24,5 @@ Global
{4734E0A4-150E-4915-B905-928BB4BE3FF6}.Debug|Any CPU.Build.0 = Debug|Any CPU {4734E0A4-150E-4915-B905-928BB4BE3FF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4734E0A4-150E-4915-B905-928BB4BE3FF6}.Release|Any CPU.ActiveCfg = Release|Any CPU {4734E0A4-150E-4915-B905-928BB4BE3FF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4734E0A4-150E-4915-B905-928BB4BE3FF6}.Release|Any CPU.Build.0 = Release|Any CPU {4734E0A4-150E-4915-B905-928BB4BE3FF6}.Release|Any CPU.Build.0 = Release|Any CPU
{3D72D70A-48AD-4EE8-89DC-C78153EEA879}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3D72D70A-48AD-4EE8-89DC-C78153EEA879}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3D72D70A-48AD-4EE8-89DC-C78153EEA879}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3D72D70A-48AD-4EE8-89DC-C78153EEA879}.Release|Any CPU.Build.0 = Release|Any CPU
{D098E281-5535-4A07-9514-57AF78704B0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D098E281-5535-4A07-9514-57AF78704B0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D098E281-5535-4A07-9514-57AF78704B0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D098E281-5535-4A07-9514-57AF78704B0C}.Release|Any CPU.Build.0 = Release|Any CPU
{792ECCCD-FAC3-4CE5-A760-988080960BB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{792ECCCD-FAC3-4CE5-A760-988080960BB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{792ECCCD-FAC3-4CE5-A760-988080960BB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{792ECCCD-FAC3-4CE5-A760-988080960BB9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@@ -1,90 +0,0 @@
using KfChatDotNetWsClient;
using KfChatDotNetWsClient.Models;
using KfChatDotNetWsClient.Models.Events;
using KfChatDotNetWsClient.Models.Json;
using NLog;
using Spectre.Console;
using Websocket.Client;
namespace KfChatDotNetCli;
public class ChatCliMain
{
private ChatClient _client;
private Logger _logger = LogManager.GetCurrentClassLogger();
private int _roomId;
public ChatCliMain(string xfSessionToken, int roomId)
{
_roomId = roomId;
_client = new ChatClient(new ChatClientConfigModel
{
WsUri = new Uri("wss://kiwifarms.st:9443/chat.ws"),
XfSessionToken = xfSessionToken
});
_client.OnMessages += OnMessages;
_client.OnDeleteMessages += OnDeleteMessages;
_client.OnUsersJoined += OnUsersJoined;
_client.OnUsersParted += OnUsersParted;
_client.OnWsReconnect += OnWsReconnected;
_client.StartWsClient().Wait();
if (_roomId != int.MaxValue)
{
_logger.Debug($"Joining room {_roomId}");
_client.JoinRoom(_roomId);
}
while (true)
{
var input = AnsiConsole.Prompt(new TextPrompt<string>("Enter Message:"));
_client.SendMessage(input);
}
// ReSharper disable once FunctionNeverReturns
}
private void OnMessages(object sender, List<MessageModel> messages, MessagesJsonModel jsonPayload)
{
_logger.Debug($"Received {messages.Count} message(s)");
foreach (var message in messages)
{
AnsiConsole.MarkupLine($"<{message.Author.Username}> {message.Message.EscapeMarkup()} ({message.MessageDate.LocalDateTime.ToShortTimeString()})");
}
}
private void OnDeleteMessages(object sender, List<int> messageIds)
{
_logger.Debug($"Received delete event for {messageIds}");
foreach (var id in messageIds)
{
AnsiConsole.MarkupLine($"[red]{id} message deleted![/]");
}
}
private void OnUsersJoined(object sender, List<UserModel> users, UsersJsonModel jsonPayload)
{
_logger.Debug($"Received {users.Count} user join events");
foreach (var user in users)
{
AnsiConsole.MarkupLine($"[green]{user.Username.EscapeMarkup()} joined![/]");
}
}
private void OnUsersParted(object sender, List<int> userIds)
{
_logger.Debug($"Received {userIds.Count} user part events");
foreach (var id in userIds)
{
AnsiConsole.MarkupLine($"[red]{id} left the chat...[/]");
}
}
private void OnWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
{
AnsiConsole.MarkupLine($"[red]Reconnected due to {reconnectionInfo.Type}[/]");
if (_roomId == int.MaxValue) return;
AnsiConsole.MarkupLine($"[green]Rejoining {_roomId}[/]");
_client.JoinRoom(_roomId);
}
}

View File

@@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>default</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="NLog" Version="5.4.0" />
<PackageReference Include="Spectre.Console" Version="0.48.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,15 +0,0 @@
<?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>

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
using System.Net;
using System.Text;
using CommandLine;
using NLog;
namespace KfChatDotNetCli
{
public class Program
{
public class Options
{
[Option('t', "token", Required = false, Default = null, HelpText = "XF session token from the 'xf_session' cookie")]
public string XfSessionToken { get; set; } = null!;
[Option("debug", Required = false, Default = false, HelpText = "Enable debug logging")]
public bool Debug { get; set; }
[Option('r', "room", Required = false, Default = int.MaxValue, HelpText = "Room ID to join on start")]
public int RoomId { get; set; }
}
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Parser.Default.ParseArguments<Options>(args).WithParsed(CliOptions);
}
static void CliOptions(Options options)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
if (options.Debug)
{
foreach (var rule in LogManager.Configuration.LoggingRules)
{
rule.EnableLoggingForLevel(LogLevel.Debug);
}
}
new ChatCliMain(options.XfSessionToken, options.RoomId);
}
}
}

View File

@@ -1,454 +0,0 @@
## 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

View File

@@ -1,13 +0,0 @@
<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

@@ -1,71 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using KfChatDotNetGui.Views;
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 = JsonSerializer.Deserialize<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.

Before

Width:  |  Height:  |  Size: 172 KiB

View File

@@ -1,42 +0,0 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using KfChatDotNetGui.Models;
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 JsonSerializer.Deserialize<ForumIdentityModel>(accountJs);
}
}
}

View File

@@ -1,36 +0,0 @@
<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.72" />
<PackageReference Include="ReactiveUI" Version="20.1.63" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace KfChatDotNetGui.Models;
public class ForumIdentityModel
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("username")]
public string Username { get; set; }
[JsonPropertyName("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
[JsonPropertyName("ignored_users")]
public List<string> IgnoredUsers { get; set; }
[JsonPropertyName("is_staff")]
public bool IsStaff { get; set; }
}

View File

@@ -1,14 +0,0 @@
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

@@ -1,12 +0,0 @@
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

@@ -1,15 +0,0 @@
<?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>

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +0,0 @@
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

@@ -1,28 +0,0 @@
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

@@ -1,47 +0,0 @@
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

@@ -1,126 +0,0 @@
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

@@ -1,20 +0,0 @@
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

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

View File

@@ -1,32 +0,0 @@
<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

@@ -1,117 +0,0 @@
using System;
using System.IO;
using System.Text.Json;
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 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
};
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText("settings.json", JsonSerializer.Serialize(settings, options));
}
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

@@ -1,107 +0,0 @@
<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

@@ -1,495 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Threading;
using KfChatDotNetGui.Models;
using KfChatDotNetGui.ViewModels;
using KfChatDotNetWsClient;
using KfChatDotNetWsClient.Models;
using KfChatDotNetWsClient.Models.Events;
using KfChatDotNetWsClient.Models.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 = null!;
private int _currentRoom;
private ForumIdentityModel? _forumIdentity = null!;
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 = JsonSerializer.Deserialize<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");
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 = JsonSerializer.Deserialize<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 = JsonSerializer.Deserialize<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 = JsonSerializer.Deserialize<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

@@ -1,28 +0,0 @@
<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

@@ -1,176 +0,0 @@
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.Text.Json;
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 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",
JsonSerializer.Serialize(roomSettings, new JsonSerializerOptions { WriteIndented = true }));
}
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 = JsonSerializer.Deserialize<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;
});
}
}
}

View File

@@ -1,15 +0,0 @@
<?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="Debug" writeTo="console" />
</rules>
</nlog>

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
using System.Net;
using System.Text;
using Spectre.Console;
using ThreeXplWsClient.Events;
namespace ThreeXplCliClient
{
public class Program
{
static async Task Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
AnsiConsole.MarkupLine("[green]3xpl test client started[/]");
var cliClient = new ThreeXplClient();
await cliClient.Start();
}
}
}

View File

@@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.4.0" />
<PackageReference Include="Spectre.Console" Version="0.49.1" />
<PackageReference Include="System.Text.Json" Version="9.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ThreeXplWsClient\ThreeXplWsClient.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -1,41 +0,0 @@
using System.Text.Json;
using Spectre.Console;
using ThreeXplWsClient.Events;
namespace ThreeXplCliClient;
public class ThreeXplClient
{
private List<string> _addresses =
[
"0x3C736854AC7Cf8f24070aa3ceC72B8471d1f9781",
"0x2d709a3c76a28b45594d6a54be72d4ab0203c546"
];
public async Task Start()
{
var client = new ThreeXplWsClient.ThreeXplWsClient();
client.OnThreeXplPush += OnThreeXplEvent;
await client.StartWsClient();
while (true)
{
var prompt = AnsiConsole.Ask<string>("Channel: ");
client.SendSubscribeRequest(prompt);
AnsiConsole.MarkupLine($"[green]Subbed at {DateTime.Now:O}[/]");
}
}
private void OnThreeXplEvent(object sender, ThreeXplPushModel e, int connectionId)
{
//AnsiConsole.MarkupLine("[blue]Received event from 3xpl[/]");
foreach (var txn in e.Pub.Data.Data)
{
if (txn.Address == null) return;
if (_addresses.Contains(txn.Address))
{
AnsiConsole.MarkupLine($"[green]Saw txn I'm interested in: {txn.Address}, effect {txn.Effect}, currency {txn.Currency}[/]");
continue;
}
//AnsiConsole.MarkupLine($"[gray]Saw txn I'm not interested in: {txn.Address}, effect {txn.Effect}, currency {txn.Currency}[/]");
}
}
}

View File

@@ -1,24 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ThreeXplWsClient;
public class ThreeXplDateTimeConverter : JsonConverter<DateTime>
{
// 2025-05-05 23:53:08
private const string Format = "yyyy-MM-dd HH:mm:ss";
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var input = reader.GetString();
if (input == null)
{
throw new NullReferenceException("Tried to convert a string to DateTime that was null");
}
return DateTime.ParseExact(input, Format, null);
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(Format));
}
}

View File

@@ -1,22 +0,0 @@
using Websocket.Client;
namespace ThreeXplWsClient.Events;
public class EventHandlers
{
public delegate void OnThreeXplPing(object sender, int connectionId);
public delegate void OnThreeXplPush(object sender, ThreeXplPushModel e, int connectionId);
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo e, int connectionId);
public delegate void OnWsReconnectEventHandler(object sender, ReconnectionInfo e, int connectionId);
public delegate void OnWsMessageReceivedEventHandler(object sender, ResponseMessage e, int connectionId);
public delegate void OnThreeXplConnect(object sender, ThreeXplConnectDataModel e, int connectionId);
public delegate void OnThreeXplError(object sender, ThreeXplErrorModel e, int connectionId);
public delegate void OnThreeXplSubscribe(object sender, ThreeXplSubscribeModel e, int connectionId);
}

View File

@@ -1,111 +0,0 @@
using System.Text.Json.Serialization;
namespace ThreeXplWsClient.Events;
public class BaseThreeXplPacketModel
{
[JsonPropertyName("connect")]
public ThreeXplConnectDataModel? Connect { get; set; }
[JsonPropertyName("id")]
public int? Id { get; set; }
[JsonPropertyName("error")]
public ThreeXplErrorModel? Error { get; set; }
[JsonPropertyName("subscribe")]
public ThreeXplSubscribeModel? Subscribe { get; set; }
[JsonPropertyName("push")]
public ThreeXplPushModel? Push { get; set; }
}
public class ThreeXplDataModel
{
[JsonPropertyName("blockchain")]
public string? Blockchain { get; set; }
[JsonPropertyName("module")]
public string? Module { get; set; }
[JsonPropertyName("block")]
public int? Block { get; set; }
[JsonPropertyName("transaction")]
public string? Transaction { get; set; }
[JsonPropertyName("sort_key")]
public int? SortKey { get; set; }
[JsonPropertyName("time")]
[JsonConverter(typeof(ThreeXplDateTimeConverter))]
public DateTime Time { get; set; }
[JsonPropertyName("currency")]
public string? Currency { get; set; }
[JsonPropertyName("effect")]
public string? Effect { get; set; }
[JsonPropertyName("failed")]
public bool? Failed { get; set; }
[JsonPropertyName("extra")]
public object? Extra { get; set; }
[JsonPropertyName("extra_indexed")]
public object? ExtraIndexed { get; set; }
[JsonPropertyName("address")]
public string? Address { get; set; }
}
public class ThreeXplContextModel
{
// "time":"0.21778600 1718465848"
[JsonPropertyName("time")]
public string? Time { get; set; }
}
public class ThreeXplConnectDataModel
{
[JsonPropertyName("client")]
public string? Client { get; set; }
[JsonPropertyName("version")]
public string? Version { get; set; }
[JsonPropertyName("ping")]
public int? Ping { get; set; }
[JsonPropertyName("pong")]
public bool? Pong { get; set; }
}
public class ThreeXplErrorModel
{
[JsonPropertyName("code")]
public int? Code { get; set; }
[JsonPropertyName("Message")]
public string? Message { get; set; }
[JsonPropertyName("temporary")]
public bool? Temporary { get; set; }
}
public class ThreeXplSubscribeModel
{
[JsonPropertyName("recoverable")]
public bool? Recoverable { get; set; }
[JsonPropertyName("epoch")]
public string? Epoch { get; set; }
[JsonPropertyName("positioned")]
public bool? Positioned { get; set; }
}
public class ThreeXplPushModel
{
[JsonPropertyName("channel")]
public required string Channel { get; set; }
[JsonPropertyName("pub")]
public required ThreeXplPushPubModel Pub { get; set; }
[JsonPropertyName("offset")]
public int? Offset { get; set; }
}
public class ThreeXplPushPubModel
{
[JsonPropertyName("data")]
public required ThreeXplPushDataModel Data { get; set; }
}
public class ThreeXplPushDataModel
{
[JsonPropertyName("data")]
public required List<ThreeXplDataModel> Data { get; set; }
[JsonPropertyName("context")]
public required ThreeXplContextModel Context { get; set; }
}

View File

@@ -1,17 +0,0 @@
using System.Text.Json.Serialization;
namespace ThreeXplWsClient.Models;
public class GetWebsocketTokenModel
{
[JsonPropertyName("data")]
public required string Data { get; set; }
[JsonPropertyName("context")]
public GetWebSocketTokenContextModel? Context { get; set; }
}
public class GetWebSocketTokenContextModel
{
[JsonPropertyName("code")]
public int? Code { get; set; }
}

View File

@@ -1,31 +0,0 @@
using System.Text.Json.Serialization;
namespace ThreeXplWsClient.Models;
public class ConnectRequestModel
{
[JsonPropertyName("connect")]
public required ConnectRequestTokenModel Connect { get; set; }
[JsonPropertyName("id")]
public int Id { get; set; } = 1;
}
public class ConnectRequestTokenModel
{
[JsonPropertyName("token")]
public required string Token { get; set; }
}
public class SubscribeRequestModel
{
[JsonPropertyName("subscribe")]
public required SubscribeRequestChannelModel Subscribe { get; set; }
[JsonPropertyName("id")]
public int Id { get; set; } = 2;
}
public class SubscribeRequestChannelModel
{
[JsonPropertyName("channel")]
public required string Channel { get; set; }
}

View File

@@ -1,236 +0,0 @@
using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text.Json;
using NLog;
using ThreeXplWsClient.Events;
using ThreeXplWsClient.Models;
using Websocket.Client;
namespace ThreeXplWsClient;
public class ThreeXplWsClient
{
public event EventHandlers.OnWsMessageReceivedEventHandler OnWsMessageReceived;
public event EventHandlers.OnWsDisconnectionEventHandler OnWsDisconnection;
public event EventHandlers.OnWsReconnectEventHandler OnWsReconnect;
public event EventHandlers.OnThreeXplPing OnThreeXplPing;
public event EventHandlers.OnThreeXplPush OnThreeXplPush;
public event EventHandlers.OnThreeXplConnect OnThreeXplConnect;
public event EventHandlers.OnThreeXplError OnThreeXplError;
public event EventHandlers.OnThreeXplSubscribe OnThreeXplSubscribe;
private WebsocketClient _wsClient;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private string? _wsJwt;
private DateTime _wsJwtLastRetrieved = DateTime.Now;
private int _wsJwtValidityPeriodSeconds;
private string? _proxy;
private int _reconnectTimeout;
private Uri _wsUri;
// Basically they have a limit of 10 subscriptions per connection and I have more than 10 addresses to monitor, so
// I give each connection an ID number as that way I know what addresses need to be resubscribed in the event of a
// connection drop. This ID is included with every event fired and set when the class is constructed.
private int _connectionId;
/// <summary>
/// Client for the 3xpl WebSocket API
/// </summary>
/// <param name="threeXplWsUri">URI for the websocket API, published at https://3xpl.com/data/websocket-api</param>
/// <param name="proxy">Web proxy to use for the WebSocket connection</param>
/// <param name="reconnectTimeout">Reconnect timeout, defaults to 30 seconds as 3xpl tells us to expect a ping every 25 seconds</param>
/// <param name="jwtValidityPeriodSeconds">How long the JWT is valid for. Set to int.MaxValue if you've manually provided a non-expiring token</param>
/// <param name="jwtApiToken">Manually provide a JWT if you have access to create your own</param>
/// <param name="connectionId">ID that can be used to differentiate multiple 3xpl connections</param>
public ThreeXplWsClient(string threeXplWsUri = "wss://stream.3xpl.net", string? proxy = null,
int reconnectTimeout = 30, int jwtValidityPeriodSeconds = 600, string? jwtApiToken = null, int connectionId = 0)
{
_wsUri = new Uri(threeXplWsUri);
_proxy = proxy;
_reconnectTimeout = reconnectTimeout;
_wsJwtValidityPeriodSeconds = jwtValidityPeriodSeconds;
_wsJwt = jwtApiToken;
_connectionId = connectionId;
}
private async Task RefreshApiToken()
{
_logger.Debug("Refreshing the API token");
if (_wsJwtValidityPeriodSeconds == int.MaxValue)
{
_logger.Debug($"Token is non expiring as it is set to {int.MaxValue}");
return;
}
if (_wsJwt != null && _wsJwtLastRetrieved.AddSeconds(_wsJwtValidityPeriodSeconds) >= DateTime.Now)
{
_logger.Debug(
$"Token has not yet expired. Its expiration date is {_wsJwtLastRetrieved.AddSeconds(_wsJwtValidityPeriodSeconds):yyyy-MM-dd HH:mm:ss}");
return;
}
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All };
if (_proxy != null)
{
handler.Proxy = new WebProxy(_proxy);
handler.UseProxy = true;
}
using var client = new HttpClient(handler);
var token = await client.GetFromJsonAsync<GetWebsocketTokenModel>("https://3xpl.com/get-websockets-token");
if (token == null)
{
_logger.Error("Caught a null when retrieving a WebSocket JWT from 3xpl");
throw new InvalidOperationException("Caught a null when retrieving a WebSocket JWT from 3xp");
}
_wsJwt = token.Data;
_wsJwtLastRetrieved = DateTime.Now;
}
public async Task StartWsClient()
{
_logger.Debug("StartWsClient() called, creating client");
await CreateWsClient();
}
private async Task CreateWsClient()
{
var factory = new Func<ClientWebSocket>(() =>
{
var clientWs = new ClientWebSocket();
if (_proxy == null) return clientWs;
clientWs.Options.Proxy = new WebProxy(_proxy);
return clientWs;
});
var client = new WebsocketClient(_wsUri, factory)
{
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout)
};
_wsClient = client;
client.ReconnectionHappened.Subscribe(WsReconnection);
client.MessageReceived.Subscribe(WsMessageReceived);
client.DisconnectionHappened.Subscribe(WsDisconnection);
_logger.Debug("Websocket client has been built, about to start");
await client.Start();
_logger.Debug("Websocket client started!");
}
public bool IsConnected()
{
return _wsClient is { IsRunning: true };
}
private void WsDisconnection(DisconnectionInfo disconnectionInfo)
{
_logger.Error($"Client disconnected from the chat (or never successfully connected). Type is {disconnectionInfo.Type}");
_logger.Error($"Close Status => {disconnectionInfo.CloseStatus}; Close Status Description => {disconnectionInfo.CloseStatusDescription}");
_logger.Error(disconnectionInfo.Exception);
OnWsDisconnection?.Invoke(this, disconnectionInfo, _connectionId);
}
private void SendConnectRequest()
{
if (_wsJwt == null)
{
_logger.Error("JWT was null.");
throw new InvalidOperationException("JWT was null");
}
var data = new ConnectRequestModel { Connect = new ConnectRequestTokenModel { Token = _wsJwt } };
var payload = JsonSerializer.Serialize(data);
_logger.Debug("Sending the following payload to 3xpl");
_logger.Debug(payload);
_wsClient.Send(payload);
}
private void WsReconnection(ReconnectionInfo reconnectionInfo)
{
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
_logger.Info("Refreshing JWT");
RefreshApiToken().Wait();
_logger.Info("Sending connect request");
SendConnectRequest();
OnWsReconnect?.Invoke(this, reconnectionInfo, _connectionId);
}
public void SendSubscribeRequest(string channel)
{
var data = new SubscribeRequestModel { Subscribe = new SubscribeRequestChannelModel { Channel = channel }};
var payload = JsonSerializer.Serialize(data);
_logger.Debug("Sending the following subscription payload to 3xpl");
_logger.Debug(payload);
_wsClient.Send(payload);
}
private void WsMessageReceived(ResponseMessage message)
{
OnWsMessageReceived?.Invoke(this, message, _connectionId);
_logger.Debug("Received JSON from 3xpl");
_logger.Debug(message.Text);
if (message.Text == null)
{
_logger.Info("Websocket message was null, ignoring packet");
return;
}
if (message.Text == "{}")
{
_logger.Debug("Received ping from 3xpl. Sending back a pong and invoking event");
_wsClient.Send("{}");
OnThreeXplPing?.Invoke(this, _connectionId);
return;
}
BaseThreeXplPacketModel threeXplPacket;
try
{
threeXplPacket = JsonSerializer.Deserialize<BaseThreeXplPacketModel>(message.Text) ??
throw new InvalidOperationException();
}
catch (Exception e)
{
_logger.Error("Failed to parse 3xpl payload. Exception follows:");
_logger.Error(e);
_logger.Error("--- Message from 3xpl follows ---");
_logger.Error(message.Text);
_logger.Error("--- /end of message ---");
return;
}
if (threeXplPacket.Connect != null)
{
_logger.Debug("Received connect packet from 3xpl, invoking event");
OnThreeXplConnect?.Invoke(this, threeXplPacket.Connect, _connectionId);
return;
}
if (threeXplPacket.Push != null)
{
_logger.Debug("Received data event from 3xpl");
OnThreeXplPush?.Invoke(this, threeXplPacket.Push, _connectionId);
return;
}
if (threeXplPacket.Error != null)
{
_logger.Debug("Received error packet from 3xpl");
OnThreeXplError?.Invoke(this, threeXplPacket.Error, _connectionId);
return;
}
if (threeXplPacket.Subscribe != null)
{
_logger.Debug("Received subscribe packet from 3xpl");
OnThreeXplSubscribe?.Invoke(this, threeXplPacket.Subscribe, _connectionId);
return;
}
_logger.Error("Failed to handle 3xpl packet");
_logger.Error("--- Message from 3xpl follows ---");
_logger.Error(message.Text);
_logger.Error("--- /end of message ---");
}
}

View File

@@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.4.0" />
<PackageReference Include="System.Text.Json" Version="9.0.1" />
<PackageReference Include="Websocket.Client" Version="5.1.2" />
</ItemGroup>
</Project>