mirror of
https://github.com/barelyprofessional/KfChatDotNet.git
synced 2026-04-30 03:22:04 -04:00
Initial commit
This commit is contained in:
34
.gitignore
vendored
Normal file
34
.gitignore
vendored
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Common IntelliJ Platform excludes
|
||||||
|
|
||||||
|
# User specific
|
||||||
|
**/.idea/**/workspace.xml
|
||||||
|
**/.idea/**/tasks.xml
|
||||||
|
**/.idea/shelf/*
|
||||||
|
**/.idea/dictionaries
|
||||||
|
**/.idea/httpRequests/
|
||||||
|
|
||||||
|
# Sensitive or high-churn files
|
||||||
|
**/.idea/**/dataSources/
|
||||||
|
**/.idea/**/dataSources.ids
|
||||||
|
**/.idea/**/dataSources.xml
|
||||||
|
**/.idea/**/dataSources.local.xml
|
||||||
|
**/.idea/**/sqlDataSources.xml
|
||||||
|
**/.idea/**/dynamic.xml
|
||||||
|
|
||||||
|
# Rider
|
||||||
|
# Rider auto-generates .iml files, and contentModel.xml
|
||||||
|
**/.idea/**/*.iml
|
||||||
|
**/.idea/**/contentModel.xml
|
||||||
|
**/.idea/**/modules.xml
|
||||||
|
|
||||||
|
*.suo
|
||||||
|
*.user
|
||||||
|
.vs/
|
||||||
|
[Bb]in/
|
||||||
|
[Oo]bj/
|
||||||
|
_UpgradeReport_Files/
|
||||||
|
[Pp]ackages/
|
||||||
|
|
||||||
|
Thumbs.db
|
||||||
|
Desktop.ini
|
||||||
|
.DS_Store
|
||||||
13
.idea/.idea.KfChatDotNet/.idea/.gitignore
generated
vendored
Normal file
13
.idea/.idea.KfChatDotNet/.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Rider ignored files
|
||||||
|
/.idea.KfChatDotNet.iml
|
||||||
|
/modules.xml
|
||||||
|
/contentModel.xml
|
||||||
|
/projectSettingsUpdater.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
14
.idea/.idea.KfChatDotNet/.idea/avalonia.xml
generated
Normal file
14
.idea/.idea.KfChatDotNet/.idea/avalonia.xml
generated
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AvaloniaProject">
|
||||||
|
<option name="projectPerEditor">
|
||||||
|
<map>
|
||||||
|
<entry key="KfChatDotNetGui/App.axaml" value="KfChatDotNetGui/KfChatDotNetGui.csproj" />
|
||||||
|
<entry key="KfChatDotNetGui/Views/ChatBoxView.axaml" value="KfChatDotNetGui/KfChatDotNetGui.csproj" />
|
||||||
|
<entry key="KfChatDotNetGui/Views/IdentitySettingsWindow.axaml" value="KfChatDotNetGui/KfChatDotNetGui.csproj" />
|
||||||
|
<entry key="KfChatDotNetGui/Views/MainWindow.axaml" value="KfChatDotNetGui/KfChatDotNetGui.csproj" />
|
||||||
|
<entry key="KfChatDotNetGui/Views/RoomSettingsWindow.axaml" value="KfChatDotNetGui/KfChatDotNetGui.csproj" />
|
||||||
|
</map>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
4
.idea/.idea.KfChatDotNet/.idea/encodings.xml
generated
Normal file
4
.idea/.idea.KfChatDotNet/.idea/encodings.xml
generated
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
|
||||||
|
</project>
|
||||||
8
.idea/.idea.KfChatDotNet/.idea/indexLayout.xml
generated
Normal file
8
.idea/.idea.KfChatDotNet/.idea/indexLayout.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="UserContentModel">
|
||||||
|
<attachedFolders />
|
||||||
|
<explicitIncludes />
|
||||||
|
<explicitExcludes />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
6
.idea/.idea.KfChatDotNet/.idea/sqldialects.xml
generated
Normal file
6
.idea/.idea.KfChatDotNet/.idea/sqldialects.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="SqlDialectMappings">
|
||||||
|
<file url="file://$PROJECT_DIR$/KfChatDotNetKickBot/Helpers.cs" dialect="SQLite" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
6
.idea/.idea.KfChatDotNet/.idea/vcs.xml
generated
Normal file
6
.idea/.idea.KfChatDotNet/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
40
KfChatDotNet.sln
Normal file
40
KfChatDotNet.sln
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetWsClient", "KfChatDotNetWsClient\KfChatDotNetWsClient.csproj", "{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}"
|
||||||
|
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}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KfChatDotNetKickBot", "KfChatDotNetKickBot\KfChatDotNetKickBot.csproj", "{4734E0A4-150E-4915-B905-928BB4BE3FF6}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{B3BC806A-7FFC-47BD-9C18-45CD2B99F9F8}.Debug|Any CPU.ActiveCfg = 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.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.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.Build.0 = Release|Any CPU
|
||||||
|
{4734E0A4-150E-4915-B905-928BB4BE3FF6}.Debug|Any CPU.ActiveCfg = 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.Build.0 = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
||||||
85
KfChatDotNetCli/ChatCliMain.cs
Normal file
85
KfChatDotNetCli/ChatCliMain.cs
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
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/chat.ws"),
|
||||||
|
XfSessionToken = xfSessionToken
|
||||||
|
});
|
||||||
|
|
||||||
|
_client.OnMessages += OnMessages;
|
||||||
|
_client.OnDeleteMessages += OnDeleteMessages;
|
||||||
|
_client.OnUsersJoined += OnUsersJoined;
|
||||||
|
_client.OnUsersParted += OnUsersParted;
|
||||||
|
_client.OnWsReconnect += OnWsReconnected;
|
||||||
|
|
||||||
|
_client.StartWsClient().Wait();
|
||||||
|
_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}[/]");
|
||||||
|
AnsiConsole.MarkupLine($"[green]Rejoining {_roomId}[/]");
|
||||||
|
_client.JoinRoom(_roomId);
|
||||||
|
}
|
||||||
|
}
|
||||||
28
KfChatDotNetCli/KfChatDotNetCli.csproj
Normal file
28
KfChatDotNetCli/KfChatDotNetCli.csproj
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<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.2.8" />
|
||||||
|
<PackageReference Include="Spectre.Console" Version="0.48.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="NLog.config" />
|
||||||
|
<Content Include="NLog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
15
KfChatDotNetCli/NLog.config
Normal file
15
KfChatDotNetCli/NLog.config
Normal 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
KfChatDotNetCli/NLog.xsd
Normal file
3483
KfChatDotNetCli/NLog.xsd
Normal file
File diff suppressed because it is too large
Load Diff
40
KfChatDotNetCli/Program.cs
Normal file
40
KfChatDotNetCli/Program.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
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 = true, 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
454
KfChatDotNetGui/.gitignore
vendored
Normal file
454
KfChatDotNetGui/.gitignore
vendored
Normal 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
13
KfChatDotNetGui/App.axaml
Normal 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>
|
||||||
71
KfChatDotNetGui/App.axaml.cs
Normal file
71
KfChatDotNetGui/App.axaml.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
KfChatDotNetGui/Assets/avalonia-logo.ico
Normal file
BIN
KfChatDotNetGui/Assets/avalonia-logo.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 172 KiB |
42
KfChatDotNetGui/Helpers/ForumIdentity.cs
Normal file
42
KfChatDotNetGui/Helpers/ForumIdentity.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
43
KfChatDotNetGui/KfChatDotNetGui.csproj
Normal file
43
KfChatDotNetGui/KfChatDotNetGui.csproj
Normal 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>
|
||||||
20
KfChatDotNetGui/Models/ForumIdentityModel.cs
Normal file
20
KfChatDotNetGui/Models/ForumIdentityModel.cs
Normal 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; }
|
||||||
|
}
|
||||||
14
KfChatDotNetGui/Models/RoomSettingsModel.cs
Normal file
14
KfChatDotNetGui/Models/RoomSettingsModel.cs
Normal 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; }
|
||||||
|
}
|
||||||
12
KfChatDotNetGui/Models/SettingsModel.cs
Normal file
12
KfChatDotNetGui/Models/SettingsModel.cs
Normal 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; }
|
||||||
|
}
|
||||||
15
KfChatDotNetGui/NLog.config
Normal file
15
KfChatDotNetGui/NLog.config
Normal 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
3483
KfChatDotNetGui/NLog.xsd
Normal file
File diff suppressed because it is too large
Load Diff
23
KfChatDotNetGui/Program.cs
Normal file
23
KfChatDotNetGui/Program.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
28
KfChatDotNetGui/ViewLocator.cs
Normal file
28
KfChatDotNetGui/ViewLocator.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
126
KfChatDotNetGui/ViewModels/MainWindowViewModel.cs
Normal file
126
KfChatDotNetGui/ViewModels/MainWindowViewModel.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
KfChatDotNetGui/ViewModels/RoomSettingsWindowViewModel.cs
Normal file
20
KfChatDotNetGui/ViewModels/RoomSettingsWindowViewModel.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
8
KfChatDotNetGui/ViewModels/ViewModelBase.cs
Normal file
8
KfChatDotNetGui/ViewModels/ViewModelBase.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
using ReactiveUI;
|
||||||
|
|
||||||
|
namespace KfChatDotNetGui.ViewModels
|
||||||
|
{
|
||||||
|
public class ViewModelBase : ReactiveObject
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
32
KfChatDotNetGui/Views/IdentitySettingsWindow.axaml
Normal file
32
KfChatDotNetGui/Views/IdentitySettingsWindow.axaml
Normal 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>
|
||||||
116
KfChatDotNetGui/Views/IdentitySettingsWindow.axaml.cs
Normal file
116
KfChatDotNetGui/Views/IdentitySettingsWindow.axaml.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
107
KfChatDotNetGui/Views/MainWindow.axaml
Normal file
107
KfChatDotNetGui/Views/MainWindow.axaml
Normal 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>
|
||||||
499
KfChatDotNetGui/Views/MainWindow.axaml.cs
Normal file
499
KfChatDotNetGui/Views/MainWindow.axaml.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
28
KfChatDotNetGui/Views/RoomSettingsWindow.axaml
Normal file
28
KfChatDotNetGui/Views/RoomSettingsWindow.axaml
Normal 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>
|
||||||
174
KfChatDotNetGui/Views/RoomSettingsWindow.axaml.cs
Normal file
174
KfChatDotNetGui/Views/RoomSettingsWindow.axaml.cs
Normal 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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
36
KfChatDotNetKickBot/Helpers.cs
Normal file
36
KfChatDotNetKickBot/Helpers.cs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using NLog;
|
||||||
|
|
||||||
|
namespace KfChatDotNetKickBot;
|
||||||
|
|
||||||
|
public static class Helpers
|
||||||
|
{
|
||||||
|
// This ended up being pretty useless as it turns out Firefox doesn't store session cookies in cookies.sqlite
|
||||||
|
// But I'll leave it here in case it becomes useful one day
|
||||||
|
public static async Task<string?> GetXfToken(string cookieName, string cookieDomain, string containerPath)
|
||||||
|
{
|
||||||
|
var logger = LogManager.GetCurrentClassLogger();
|
||||||
|
await using var connection = new SqliteConnection($"Data Source={containerPath}");
|
||||||
|
|
||||||
|
await connection.OpenAsync();
|
||||||
|
logger.Debug($"Opened {containerPath}");
|
||||||
|
|
||||||
|
var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT value FROM moz_cookies WHERE host = $host AND name = $name ORDER BY creationTime DESC LIMIT 1";
|
||||||
|
command.Parameters.AddWithValue("$host", cookieDomain);
|
||||||
|
command.Parameters.AddWithValue("$name", cookieName);
|
||||||
|
logger.Debug("Created command");
|
||||||
|
logger.Debug(command.CommandText);
|
||||||
|
|
||||||
|
await using var reader = await command.ExecuteReaderAsync();
|
||||||
|
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
logger.Debug("Reading first row, which will be immediately returned anyway");
|
||||||
|
return reader.GetString(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Error("Fucked up while retrieving cookie. Cookie doesn't exist?");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
32
KfChatDotNetKickBot/KfChatDotNetKickBot.csproj
Normal file
32
KfChatDotNetKickBot/KfChatDotNetKickBot.csproj
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.3" />
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="NLog" Version="5.2.8" />
|
||||||
|
<PackageReference Include="Spectre.Console" Version="0.48.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\KfChatDotNetWsClient\KfChatDotNetWsClient.csproj" />
|
||||||
|
<ProjectReference Include="..\KickWsClient\KickWsClient.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Update="NLog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
<None Remove="config.json" />
|
||||||
|
<Content Include="config.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
164
KfChatDotNetKickBot/KickBot.cs
Normal file
164
KfChatDotNetKickBot/KickBot.cs
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
using KfChatDotNetWsClient;
|
||||||
|
using KfChatDotNetWsClient.Models;
|
||||||
|
using KfChatDotNetWsClient.Models.Events;
|
||||||
|
using KfChatDotNetWsClient.Models.Json;
|
||||||
|
using KickWsClient.Models;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using NLog;
|
||||||
|
using Spectre.Console;
|
||||||
|
using Websocket.Client;
|
||||||
|
|
||||||
|
namespace KfChatDotNetKickBot;
|
||||||
|
|
||||||
|
public class KickBot
|
||||||
|
{
|
||||||
|
private ChatClient _kfClient;
|
||||||
|
private KickWsClient.KickWsClient _kickClient;
|
||||||
|
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||||
|
private Models.ConfigModel _config;
|
||||||
|
private Thread _pingThread;
|
||||||
|
private bool _pingEnabled = true;
|
||||||
|
|
||||||
|
public KickBot()
|
||||||
|
{
|
||||||
|
_logger.Info("Bot starting!");
|
||||||
|
const string configPath = "config.json";
|
||||||
|
if (!Path.Exists(configPath))
|
||||||
|
{
|
||||||
|
_logger.Error($"{configPath} is missing! Exiting");
|
||||||
|
Environment.Exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
_config = JsonConvert.DeserializeObject<Models.ConfigModel>(File.ReadAllText(configPath)) ??
|
||||||
|
throw new InvalidOperationException();
|
||||||
|
|
||||||
|
_kfClient = new ChatClient(new ChatClientConfigModel
|
||||||
|
{
|
||||||
|
WsUri = _config.KfWsEndpoint,
|
||||||
|
XfSessionToken = GetXfToken(),
|
||||||
|
CookieDomain = _config.KfWsEndpoint.Host,
|
||||||
|
Proxy = _config.KfProxy,
|
||||||
|
ReconnectTimeout = _config.KfReconnectTimeout
|
||||||
|
});
|
||||||
|
|
||||||
|
_kickClient = new KickWsClient.KickWsClient(_config.PusherEndpoint.ToString(),
|
||||||
|
_config.PusherProxy, _config.PusherReconnectTimeout);
|
||||||
|
|
||||||
|
_kfClient.OnMessages += OnKfChatMessage;
|
||||||
|
_kfClient.OnUsersParted += OnUsersParted;
|
||||||
|
_kfClient.OnUsersJoined += OnUsersJoined;
|
||||||
|
_kfClient.OnWsDisconnection += OnKfWsDisconnected;
|
||||||
|
_kfClient.OnWsReconnect += OnKfWsReconnected;
|
||||||
|
|
||||||
|
_kickClient.OnStreamerIsLive += OnStreamerIsLive;
|
||||||
|
_kickClient.OnChatMessage += OnKickChatMessage;
|
||||||
|
_kickClient.OnWsReconnect += OnPusherWsReconnected;
|
||||||
|
_kickClient.OnPusherSubscriptionSucceeded += OnPusherSubscriptionSucceeded;
|
||||||
|
|
||||||
|
_kfClient.StartWsClient().Wait();
|
||||||
|
_kfClient.JoinRoom(_config.KfChatRoomId);
|
||||||
|
|
||||||
|
_kickClient.StartWsClient().Wait();
|
||||||
|
foreach (var channel in _config.PusherChannels)
|
||||||
|
{
|
||||||
|
_kickClient.SendPusherSubscribe(channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
_pingThread = new Thread(PingThread);
|
||||||
|
_pingThread.Start();
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var input = AnsiConsole.Prompt(new TextPrompt<string>("Enter Message:"));
|
||||||
|
_kfClient.SendMessage(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PingThread()
|
||||||
|
{
|
||||||
|
while (_pingEnabled)
|
||||||
|
{
|
||||||
|
Thread.Sleep(TimeSpan.FromSeconds(15));
|
||||||
|
_logger.Debug("Pinging KF and Pusher");
|
||||||
|
_kfClient.SendMessage("/ping");
|
||||||
|
_kickClient.SendPusherPing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetXfToken()
|
||||||
|
{
|
||||||
|
//return Helpers.GetXfToken("xf_session", _config.KfWsEndpoint.Host, _config.FirefoxCookieContainer).Result ??
|
||||||
|
// throw new InvalidOperationException();
|
||||||
|
return _config.XfTokenValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnStreamerIsLive(object sender, KickModels.StreamerIsLiveEventModel? e)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnKfChatMessage(object sender, List<MessageModel> messages, MessagesJsonModel jsonPayload)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Received {messages.Count} message(s)");
|
||||||
|
foreach (var message in messages)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[yellow]KF[/] <{message.Author.Username}> {message.Message.EscapeMarkup()} ({message.MessageDate.LocalDateTime.ToShortTimeString()})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnKickChatMessage(object sender, KickModels.ChatMessageEventModel? e)
|
||||||
|
{
|
||||||
|
if (e == null) return;
|
||||||
|
AnsiConsole.MarkupLine($"[green]Kick[/] <{e.Sender.Username}> {e.Content.EscapeMarkup()} ({e.CreatedAt.LocalDateTime.ToShortTimeString()})");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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 OnKfWsDisconnected(object sender, DisconnectionInfo disconnectionInfo)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[red]Sneedchat disconnected due to {disconnectionInfo.Type}[/]");
|
||||||
|
AnsiConsole.MarkupLine("[yellow]Grabbing fresh token from browser[/]");
|
||||||
|
var token = GetXfToken();
|
||||||
|
AnsiConsole.MarkupLine($"[green]Obtained token = {token.EscapeMarkup()}[/]");
|
||||||
|
_kfClient.UpdateToken(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnKfWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[red]Sneedchat reconnected due to {reconnectionInfo.Type}[/]");
|
||||||
|
AnsiConsole.MarkupLine($"[green]Rejoining {_config.KfChatRoomId}[/]");
|
||||||
|
_kfClient.JoinRoom(_config.KfChatRoomId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnPusherWsReconnected(object sender, ReconnectionInfo reconnectionInfo)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[red]Pusher reconnected due to {reconnectionInfo.Type}[/]");
|
||||||
|
foreach (var channel in _config.PusherChannels)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[green]Rejoining {channel}[/]");
|
||||||
|
_kickClient.SendPusherSubscribe(channel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnPusherSubscriptionSucceeded(object sender, PusherModels.BasePusherEventModel? e)
|
||||||
|
{
|
||||||
|
AnsiConsole.MarkupLine($"[green]Pusher indicates subscription to {e?.Channel.EscapeMarkup()} was successful[/]");
|
||||||
|
}
|
||||||
|
}
|
||||||
24
KfChatDotNetKickBot/Models.cs
Normal file
24
KfChatDotNetKickBot/Models.cs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
namespace KfChatDotNetKickBot;
|
||||||
|
|
||||||
|
public class Models
|
||||||
|
{
|
||||||
|
public class ConfigModel
|
||||||
|
{
|
||||||
|
public Uri PusherEndpoint { get; set; } =
|
||||||
|
new("wss://ws-us2.pusher.com/app/eb1d5f283081a78b932c?protocol=7&client=js&version=7.6.0&flash=false");
|
||||||
|
|
||||||
|
public Uri KfWsEndpoint { get; set; } = new("wss://kiwifarms.st:9443/chat.ws");
|
||||||
|
|
||||||
|
public List<string> PusherChannels { get; set; } = [];
|
||||||
|
public int KfChatRoomId { get; set; }
|
||||||
|
// Proxy to use for connecting to Sneedchat
|
||||||
|
public string? KfProxy { get; set; }
|
||||||
|
// Proxy to use for the Pusher websocket
|
||||||
|
// e.g. socks5://blahblah:1080
|
||||||
|
public string? PusherProxy { get; set; }
|
||||||
|
public int KfReconnectTimeout { get; set; } = 30;
|
||||||
|
public int PusherReconnectTimeout { get; set; } = 30;
|
||||||
|
// Todo: Find a way to extract this from the browser as it's not valid forever
|
||||||
|
public string? XfTokenValue { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
15
KfChatDotNetKickBot/NLog.config
Normal file
15
KfChatDotNetKickBot/NLog.config
Normal 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="Debug" writeTo="console" />
|
||||||
|
</rules>
|
||||||
|
</nlog>
|
||||||
3483
KfChatDotNetKickBot/NLog.xsd
Normal file
3483
KfChatDotNetKickBot/NLog.xsd
Normal file
File diff suppressed because it is too large
Load Diff
15
KfChatDotNetKickBot/Program.cs
Normal file
15
KfChatDotNetKickBot/Program.cs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using NLog;
|
||||||
|
|
||||||
|
namespace KfChatDotNetKickBot
|
||||||
|
{
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
static void Main(string[] args)
|
||||||
|
{
|
||||||
|
Console.OutputEncoding = Encoding.UTF8;
|
||||||
|
new KickBot();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
KfChatDotNetKickBot/config.json
Normal file
6
KfChatDotNetKickBot/config.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"PusherChannels": ["chatrooms.2507974.v2", "channel.2515504"],
|
||||||
|
"KfProxy": "socks5://us-lax-wg-socks5-203.relays.mullvad.net:1080",
|
||||||
|
"KfChatRoomId": 15,
|
||||||
|
"XfTokenValue": "fill this in with the value from xf_session"
|
||||||
|
}
|
||||||
285
KfChatDotNetWsClient/ChatClient.cs
Normal file
285
KfChatDotNetWsClient/ChatClient.cs
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using KfChatDotNetWsClient.Models;
|
||||||
|
using KfChatDotNetWsClient.Models.Events;
|
||||||
|
using KfChatDotNetWsClient.Models.Json;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using NLog;
|
||||||
|
using Websocket.Client;
|
||||||
|
// It's a fucking lie. You must use conditional access or you WILL get NullReferenceErrors if an event is not in use
|
||||||
|
// ReSharper disable ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient;
|
||||||
|
|
||||||
|
public class ChatClient
|
||||||
|
{
|
||||||
|
public event EventHandlers.OnMessagesEventHandler OnMessages;
|
||||||
|
public event EventHandlers.OnUsersPartedEventHandler OnUsersParted;
|
||||||
|
public event EventHandlers.OnUsersJoinedEventHandler OnUsersJoined;
|
||||||
|
public event EventHandlers.OnWsReconnectEventHandler OnWsReconnect;
|
||||||
|
public event EventHandlers.OnDeleteMessagesEventHandler OnDeleteMessages;
|
||||||
|
public event EventHandlers.OnWsDisconnectionEventHandler OnWsDisconnection;
|
||||||
|
public event EventHandlers.OnFailedToJoinRoom OnFailedToJoinRoom;
|
||||||
|
public event EventHandlers.OnUnknownCommand OnUnknownCommand;
|
||||||
|
private WebsocketClient _wsClient;
|
||||||
|
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||||
|
private ChatClientConfigModel _config;
|
||||||
|
|
||||||
|
public ChatClient(ChatClientConfigModel config)
|
||||||
|
{
|
||||||
|
_config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateConfig(ChatClientConfigModel config)
|
||||||
|
{
|
||||||
|
_config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateToken(string newToken)
|
||||||
|
{
|
||||||
|
_config.XfSessionToken = newToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StartWsClient()
|
||||||
|
{
|
||||||
|
_wsClient = await CreateWsClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Disconnect()
|
||||||
|
{
|
||||||
|
_wsClient.Stop(WebSocketCloseStatus.NormalClosure, "Closing websocket").Wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<WebsocketClient> CreateWsClient()
|
||||||
|
{
|
||||||
|
var factory = new Func<ClientWebSocket>(() =>
|
||||||
|
{
|
||||||
|
var clientWs = new ClientWebSocket();
|
||||||
|
// Guest mode
|
||||||
|
if (_config.XfSessionToken == null)
|
||||||
|
{
|
||||||
|
return clientWs;
|
||||||
|
}
|
||||||
|
|
||||||
|
var cookieContainer = new CookieContainer();
|
||||||
|
cookieContainer.Add(new Cookie("xf_session", _config.XfSessionToken, "/", _config.CookieDomain));
|
||||||
|
clientWs.Options.Cookies = cookieContainer;
|
||||||
|
if (_config.Proxy != null)
|
||||||
|
{
|
||||||
|
clientWs.Options.Proxy = new WebProxy(_config.Proxy);
|
||||||
|
}
|
||||||
|
|
||||||
|
return clientWs;
|
||||||
|
});
|
||||||
|
|
||||||
|
var client = new WebsocketClient(_config.WsUri, factory)
|
||||||
|
{
|
||||||
|
ReconnectTimeout = TimeSpan.FromSeconds(_config.ReconnectTimeout)
|
||||||
|
};
|
||||||
|
|
||||||
|
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!");
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
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(disconnectionInfo.Exception);
|
||||||
|
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||||
|
{
|
||||||
|
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||||
|
if (reconnectionInfo.Type == ReconnectionType.Initial)
|
||||||
|
{
|
||||||
|
_logger.Error("Not firing the reconnection event as this is the initial event");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
OnWsReconnect?.Invoke(this, reconnectionInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsMessageReceived(ResponseMessage message)
|
||||||
|
{
|
||||||
|
if (message.Text == null)
|
||||||
|
{
|
||||||
|
_logger.Info("Websocket message was null, ignoring packet");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.Text.StartsWith("You cannot join this room"))
|
||||||
|
{
|
||||||
|
_logger.Debug("Got a message saying we failed to join the room");
|
||||||
|
OnFailedToJoinRoom?.Invoke(this, message.Text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.Text.StartsWith("Unknown command"))
|
||||||
|
{
|
||||||
|
_logger.Debug("Unknown command received");
|
||||||
|
OnUnknownCommand?.Invoke(this, message.Text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Dictionary<string, object> packetType = new Dictionary<string, object>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
packetType = JsonConvert.DeserializeObject<Dictionary<string, object>>(message.Text)!;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.Error("Failed to parse packet");
|
||||||
|
_logger.Error(e);
|
||||||
|
_logger.Error($"Packet contents: {message.Text}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Debug($"Received packet from KF: {string.Join(',', packetType.Keys)}");
|
||||||
|
// Message(s) received
|
||||||
|
if (packetType.ContainsKey("messages"))
|
||||||
|
{
|
||||||
|
_logger.Debug("Looks like it's a chat message");
|
||||||
|
WsChatMessagesReceived(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// User(s) joined
|
||||||
|
if (packetType.ContainsKey("users"))
|
||||||
|
{
|
||||||
|
_logger.Debug("Looks like this is a user(s) joined packet");
|
||||||
|
WsChatUsersJoined(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// User(s) parted
|
||||||
|
if (packetType.ContainsKey("user"))
|
||||||
|
{
|
||||||
|
_logger.Debug("Looks like this is a user(s) parted packet");
|
||||||
|
WsChatUsersParted(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packetType.ContainsKey("delete"))
|
||||||
|
{
|
||||||
|
_logger.Debug($"Looks like this is a message deletion packet");
|
||||||
|
WsDeleteMessagesReceived(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Info($"Received packet this was not handled: {message.Text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void JoinRoom(int roomId)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Joining {roomId}");
|
||||||
|
_wsClient.Send($"/join {roomId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendMessage(string message)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Sending '{message}'");
|
||||||
|
_wsClient.Send(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void DeleteMessage(int messageId)
|
||||||
|
{
|
||||||
|
_logger.Debug($"Deleting {messageId}");
|
||||||
|
_wsClient.Send($"/delete {messageId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EditMessage(int messageId, string newMessage)
|
||||||
|
{
|
||||||
|
// Explicitly set formatting to none as it must be inline (Newtonsoft will do this by default but just wanting to be explicit)
|
||||||
|
var payload = JsonConvert.SerializeObject(new EditMessageJsonModel {Id = messageId, Message = newMessage},
|
||||||
|
Formatting.None);
|
||||||
|
_logger.Debug($"Editing {messageId} with '{newMessage}'");
|
||||||
|
_wsClient.Send($"/edit {payload}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsDeleteMessagesReceived(ResponseMessage message)
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<DeleteMessagesJsonModel>(message.Text);
|
||||||
|
_logger.Debug($"Received delete packet for messages: {string.Join(',', data.MessageIdsToDelete)}");
|
||||||
|
OnDeleteMessages?.Invoke(this, data.MessageIdsToDelete);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsChatMessagesReceived(ResponseMessage message)
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<MessagesJsonModel>(message.Text);
|
||||||
|
var messages = new List<MessageModel>();
|
||||||
|
foreach (var chatMessage in data.Messages)
|
||||||
|
{
|
||||||
|
var model = new MessageModel
|
||||||
|
{
|
||||||
|
Author = new UserModel
|
||||||
|
{
|
||||||
|
Id = chatMessage.Author.Id,
|
||||||
|
Username = chatMessage.Author.Username,
|
||||||
|
AvatarUrl = chatMessage.Author.AvatarUrl,
|
||||||
|
// It isn't sent on chat messages
|
||||||
|
LastActivity = null
|
||||||
|
},
|
||||||
|
Message = chatMessage.Message,
|
||||||
|
MessageId = chatMessage.MessageId,
|
||||||
|
MessageRaw = chatMessage.MessageRaw,
|
||||||
|
RoomId = chatMessage.RoomId
|
||||||
|
};
|
||||||
|
|
||||||
|
if(chatMessage.MessageEditDate == 0)
|
||||||
|
{
|
||||||
|
model.MessageEditDate = null;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
model.MessageEditDate = DateTimeOffset.FromUnixTimeSeconds(chatMessage.MessageEditDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
model.MessageDate = DateTimeOffset.FromUnixTimeSeconds(chatMessage.MessageDate);
|
||||||
|
|
||||||
|
messages.Add(model);
|
||||||
|
}
|
||||||
|
_logger.Debug($"Received {messages.Count} chat messages");
|
||||||
|
if (messages.Count == 1)
|
||||||
|
{
|
||||||
|
_logger.Debug($"{JsonConvert.SerializeObject(messages[0], Formatting.Indented)}");
|
||||||
|
}
|
||||||
|
OnMessages?.Invoke(this, messages, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsChatUsersJoined(ResponseMessage message)
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<UsersJsonModel>(message.Text);
|
||||||
|
var users = new List<UserModel>();
|
||||||
|
foreach (var user in data.Users.Keys)
|
||||||
|
{
|
||||||
|
users.Add(new UserModel
|
||||||
|
{
|
||||||
|
Id = int.Parse(user),
|
||||||
|
Username = data.Users[user].Username,
|
||||||
|
AvatarUrl = data.Users[user].AvatarUrl,
|
||||||
|
LastActivity = DateTimeOffset.FromUnixTimeSeconds(data.Users[user].LastActivity)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
var usersJoined= data.Users.Select(user => int.Parse(user.Key)).ToList();
|
||||||
|
_logger.Debug($"Following users have joined: {string.Join(',', usersJoined)}");
|
||||||
|
OnUsersJoined?.Invoke(this, users, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsChatUsersParted(ResponseMessage message)
|
||||||
|
{
|
||||||
|
// {"user":{"1337":false}}
|
||||||
|
var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, bool>>>(message.Text);
|
||||||
|
var usersParted = data!["user"].Select(user => int.Parse(user.Key)).ToList();
|
||||||
|
_logger.Debug($"Following users have parted: {string.Join(',', usersParted)}");
|
||||||
|
OnUsersParted?.Invoke(this, usersParted);
|
||||||
|
}
|
||||||
|
}
|
||||||
23
KfChatDotNetWsClient/KfChatDotNetWsClient.csproj
Normal file
23
KfChatDotNetWsClient/KfChatDotNetWsClient.csproj
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<LangVersion>default</LangVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="NLog" Version="5.2.8" />
|
||||||
|
<PackageReference Include="Websocket.Client" Version="5.1.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="NLog.config" />
|
||||||
|
<Content Include="NLog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
12
KfChatDotNetWsClient/Models/ChatClientConfigModel.cs
Normal file
12
KfChatDotNetWsClient/Models/ChatClientConfigModel.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace KfChatDotNetWsClient.Models;
|
||||||
|
|
||||||
|
public class ChatClientConfigModel
|
||||||
|
{
|
||||||
|
// XF session token. Sent as a cookie to auth the user
|
||||||
|
public string? XfSessionToken { get; set; }
|
||||||
|
// Currently wss://kiwifarms.net/chat.ws
|
||||||
|
public Uri WsUri { get; set; }
|
||||||
|
public int ReconnectTimeout { get; set; } = 30;
|
||||||
|
public string CookieDomain { get; set; } = "kiwifarms.net";
|
||||||
|
public string? Proxy { get; set; }
|
||||||
|
}
|
||||||
28
KfChatDotNetWsClient/Models/Events/EventHandlers.cs
Normal file
28
KfChatDotNetWsClient/Models/Events/EventHandlers.cs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
using KfChatDotNetWsClient.Models.Json;
|
||||||
|
using Websocket.Client;
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient.Models.Events;
|
||||||
|
|
||||||
|
public class EventHandlers
|
||||||
|
{
|
||||||
|
public delegate void OnMessagesEventHandler(object sender, List<MessageModel> messages,
|
||||||
|
MessagesJsonModel jsonPayload);
|
||||||
|
|
||||||
|
// When a user first joins the chat, this event will fire with the entire user list (which may be massive)
|
||||||
|
// But when users join in the course of a regular chat, it'll be one at a time
|
||||||
|
public delegate void OnUsersJoinedEventHandler(object sender, List<UserModel> users, UsersJsonModel jsonPayload);
|
||||||
|
|
||||||
|
// Usually only one user parts at a time, but theoretically the model could support more than one at a time
|
||||||
|
public delegate void OnUsersPartedEventHandler(object sender, List<int> userIds);
|
||||||
|
|
||||||
|
public delegate void OnWsReconnectEventHandler(object sender, ReconnectionInfo reconnectionInfo);
|
||||||
|
|
||||||
|
// Usually only one is sent at a time but it is a list hence the pluralization
|
||||||
|
public delegate void OnDeleteMessagesEventHandler(object sender, List<int> messageIds);
|
||||||
|
|
||||||
|
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo disconnectionInfo);
|
||||||
|
|
||||||
|
public delegate void OnFailedToJoinRoom(object sender, string message);
|
||||||
|
|
||||||
|
public delegate void OnUnknownCommand(object sender, string message);
|
||||||
|
}
|
||||||
12
KfChatDotNetWsClient/Models/Events/MessageModel.cs
Normal file
12
KfChatDotNetWsClient/Models/Events/MessageModel.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace KfChatDotNetWsClient.Models.Events;
|
||||||
|
|
||||||
|
public class MessageModel
|
||||||
|
{
|
||||||
|
public UserModel Author { get; set; }
|
||||||
|
public string Message { get; set; }
|
||||||
|
public int MessageId { get; set; }
|
||||||
|
public DateTimeOffset? MessageEditDate { get; set; }
|
||||||
|
public DateTimeOffset MessageDate { get; set; }
|
||||||
|
public string MessageRaw { get; set; }
|
||||||
|
public int RoomId { get; set; }
|
||||||
|
}
|
||||||
10
KfChatDotNetWsClient/Models/Events/UserModel.cs
Normal file
10
KfChatDotNetWsClient/Models/Events/UserModel.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace KfChatDotNetWsClient.Models.Events;
|
||||||
|
|
||||||
|
public class UserModel
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Username { get; set; }
|
||||||
|
public Uri AvatarUrl { get; set; }
|
||||||
|
// Unset if it's related to a chat message
|
||||||
|
public DateTimeOffset? LastActivity { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient.Models.Json;
|
||||||
|
|
||||||
|
public class DeleteMessagesJsonModel
|
||||||
|
{
|
||||||
|
[JsonProperty("delete")]
|
||||||
|
public List<int> MessageIdsToDelete { get; set; }
|
||||||
|
}
|
||||||
12
KfChatDotNetWsClient/Models/Json/EditMessageJsonModel.cs
Normal file
12
KfChatDotNetWsClient/Models/Json/EditMessageJsonModel.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient.Models.Json;
|
||||||
|
|
||||||
|
public class EditMessageJsonModel
|
||||||
|
{
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("message")]
|
||||||
|
public string Message { get; set; }
|
||||||
|
}
|
||||||
59
KfChatDotNetWsClient/Models/Json/MessagesJsonModel.cs
Normal file
59
KfChatDotNetWsClient/Models/Json/MessagesJsonModel.cs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Converters;
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient.Models.Json;
|
||||||
|
|
||||||
|
// {
|
||||||
|
// "messages": [
|
||||||
|
// {
|
||||||
|
// "author": {
|
||||||
|
// "id": 110635,
|
||||||
|
// "username": "felted",
|
||||||
|
// "avatar_url": "https://kiwifarms.net/data/avatars/m/110/110635.jpg?1657300618"
|
||||||
|
// },
|
||||||
|
// "message": "Nigger.",
|
||||||
|
// "message_id": 4390866,
|
||||||
|
// "message_edit_date": 0,
|
||||||
|
// "message_date": 1657317093,
|
||||||
|
// "message_raw": "Nigger.",
|
||||||
|
// "room_id": 10
|
||||||
|
// }
|
||||||
|
// ]
|
||||||
|
// }
|
||||||
|
|
||||||
|
// message_raw contains the original bbcode for the message
|
||||||
|
// message is the HTML-version the web client renders with emotes transformed into images, etc.
|
||||||
|
|
||||||
|
public class MessagesJsonModel
|
||||||
|
{
|
||||||
|
public class AuthorModel
|
||||||
|
{
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public string Username { get; set; }
|
||||||
|
[JsonProperty("avatar_url")]
|
||||||
|
public Uri AvatarUrl { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MessageModel
|
||||||
|
{
|
||||||
|
[JsonProperty("author")]
|
||||||
|
public AuthorModel Author { get; set; }
|
||||||
|
[JsonProperty("message")]
|
||||||
|
public string Message { get; set; }
|
||||||
|
[JsonProperty("message_id")]
|
||||||
|
public int MessageId { get; set; }
|
||||||
|
[JsonProperty("message_edit_date")]
|
||||||
|
public int MessageEditDate { get; set; }
|
||||||
|
[JsonProperty("message_date")]
|
||||||
|
public int MessageDate { get; set; }
|
||||||
|
[JsonProperty("message_raw")]
|
||||||
|
public string MessageRaw { get; set; }
|
||||||
|
[JsonProperty("room_id")]
|
||||||
|
public int RoomId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonProperty("messages")]
|
||||||
|
public List<MessageModel> Messages { get; set; }
|
||||||
|
}
|
||||||
32
KfChatDotNetWsClient/Models/Json/UsersJsonModel.cs
Normal file
32
KfChatDotNetWsClient/Models/Json/UsersJsonModel.cs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace KfChatDotNetWsClient.Models.Json;
|
||||||
|
|
||||||
|
// {
|
||||||
|
// "users": {
|
||||||
|
// "1337": {
|
||||||
|
// "id": 1337,
|
||||||
|
// "username": "Example User",
|
||||||
|
// "avatar_url": "https://kiwifarms.net/data/avatars/m/13/1337.jpg?1648885311",
|
||||||
|
// "last_activity": 1657316000
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
public class UsersJsonModel
|
||||||
|
{
|
||||||
|
public class UserModel
|
||||||
|
{
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public string Username { get; set; }
|
||||||
|
[JsonProperty("avatar_url")]
|
||||||
|
public Uri AvatarUrl { get; set; }
|
||||||
|
[JsonProperty("last_activity")]
|
||||||
|
public int LastActivity { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonProperty("users")]
|
||||||
|
public Dictionary<string, UserModel> Users { get; set; }
|
||||||
|
}
|
||||||
15
KfChatDotNetWsClient/NLog.config
Normal file
15
KfChatDotNetWsClient/NLog.config
Normal 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="Debug" writeTo="console" />
|
||||||
|
</rules>
|
||||||
|
</nlog>
|
||||||
3483
KfChatDotNetWsClient/NLog.xsd
Normal file
3483
KfChatDotNetWsClient/NLog.xsd
Normal file
File diff suppressed because it is too large
Load Diff
267
KickWsClient/KickWsClient.cs
Normal file
267
KickWsClient/KickWsClient.cs
Normal file
@@ -0,0 +1,267 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using KickWsClient.Models;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Websocket.Client;
|
||||||
|
using NLog;
|
||||||
|
|
||||||
|
|
||||||
|
namespace KickWsClient;
|
||||||
|
|
||||||
|
public class KickWsClient
|
||||||
|
{
|
||||||
|
public event EventHandlers.OnPusherConnectionEstablishedEventHandler OnPusherConnectionEstablished;
|
||||||
|
public event EventHandlers.OnPusherSubscriptionSucceededEventHandler OnPusherSubscriptionSucceeded;
|
||||||
|
public event EventHandlers.OnPusherPongEventHandler OnPusherPong;
|
||||||
|
public event EventHandlers.OnFollowersUpdatedEventHandler OnFollowersUpdated;
|
||||||
|
public event EventHandlers.OnChatMessageEventHandler OnChatMessage;
|
||||||
|
public event EventHandlers.OnChannelSubscriptionEventHandler OnChannelSubscription;
|
||||||
|
public event EventHandlers.OnSubscriptionEventHandler OnSubscription;
|
||||||
|
public event EventHandlers.OnMessageDeletedEventHandler OnMessageDeleted;
|
||||||
|
public event EventHandlers.OnUserBannedEventHandler OnUserBanned;
|
||||||
|
public event EventHandlers.OnUserUnbannedEventHandler OnUserUnbanned;
|
||||||
|
public event EventHandlers.OnUpdatedLiveStreamEventHandler OnUpdatedLiveStream;
|
||||||
|
public event EventHandlers.OnStopStreamBroadcastEventHandler OnStopStreamBroadcast;
|
||||||
|
public event EventHandlers.OnStreamerIsLiveEventHandler OnStreamerIsLive;
|
||||||
|
public event EventHandlers.OnWsDisconnectionEventHandler OnWsDisconnection;
|
||||||
|
public event EventHandlers.OnWsReconnectEventHandler OnWsReconnect;
|
||||||
|
// You really shouldn't use this unless you're extending the functionality of the library, e.g. adding support for
|
||||||
|
// not yet implemented message types.
|
||||||
|
public event EventHandlers.OnWsMessageReceivedEventHandler OnWsMessageReceived;
|
||||||
|
public event EventHandlers.OnPollUpdateEventHandler OnPollUpdate;
|
||||||
|
|
||||||
|
private WebsocketClient _wsClient;
|
||||||
|
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||||
|
private Uri _kickPusherUri;
|
||||||
|
private int _reconnectTimeout;
|
||||||
|
private string? _proxy;
|
||||||
|
|
||||||
|
public KickWsClient(
|
||||||
|
string kickPusherUri =
|
||||||
|
"wss://ws-us2.pusher.com/app/eb1d5f283081a78b932c?protocol=7&client=js&version=7.6.0&flash=false",
|
||||||
|
string? proxy = null, int reconnectTimeout = 30)
|
||||||
|
{
|
||||||
|
_kickPusherUri = new Uri(kickPusherUri);
|
||||||
|
_proxy = proxy;
|
||||||
|
_reconnectTimeout = reconnectTimeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StartWsClient()
|
||||||
|
{
|
||||||
|
_logger.Debug("StartWsClient() called, creating client");
|
||||||
|
_wsClient = await CreateWsClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Disconnect()
|
||||||
|
{
|
||||||
|
_logger.Debug("Disconnect() called, closing Websocket");
|
||||||
|
_wsClient.Stop(WebSocketCloseStatus.NormalClosure, "Closing websocket").Wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<WebsocketClient> 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(_kickPusherUri, factory)
|
||||||
|
{
|
||||||
|
ReconnectTimeout = TimeSpan.FromSeconds(_reconnectTimeout)
|
||||||
|
};
|
||||||
|
|
||||||
|
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!");
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
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(disconnectionInfo.Exception);
|
||||||
|
OnWsDisconnection?.Invoke(this, disconnectionInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsReconnection(ReconnectionInfo reconnectionInfo)
|
||||||
|
{
|
||||||
|
_logger.Error($"Websocket connection dropped and reconnected. Reconnection type is {reconnectionInfo.Type}");
|
||||||
|
if (reconnectionInfo.Type == ReconnectionType.Initial)
|
||||||
|
{
|
||||||
|
_logger.Error("Not firing the reconnection event as this is the initial event");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
OnWsReconnect?.Invoke(this, reconnectionInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send a generic Pusher packet
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="eventName">Event name</param>
|
||||||
|
/// <param name="data">Event data</param>
|
||||||
|
public void SendPusherPacket(string eventName, object data)
|
||||||
|
{
|
||||||
|
var pkt = new PusherModels.BasePusherRequestModel { Event = eventName, Data = data};
|
||||||
|
var json = JsonConvert.SerializeObject(pkt);
|
||||||
|
_logger.Debug("Sending message to Pusher");
|
||||||
|
_logger.Debug(json);
|
||||||
|
_wsClient.Send(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send a ping packet. You should expect a pong response immediately after
|
||||||
|
/// </summary>
|
||||||
|
public void SendPusherPing()
|
||||||
|
{
|
||||||
|
SendPusherPacket("pusher:ping", new object());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send a pusher subscribe packet to subscribe to a channel or chatroom. You should receive a subscription succeeded packet
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channel">Channel string e.g. channel.2515504</param>
|
||||||
|
/// <param name="auth">Optional authentication string. Empty string means guest</param>
|
||||||
|
public void SendPusherSubscribe(string channel, string auth = "")
|
||||||
|
{
|
||||||
|
var subPacket = new PusherModels.PusherSubscribeRequestModel { Auth = auth, Channel = channel };
|
||||||
|
SendPusherPacket("pusher:subscribe", subPacket);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send pusher unsubscribe packet to unsub from a channel or chatroom. Expect no response
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channel">Channel string e.g. channel.2515504</param>
|
||||||
|
public void SendPusherUnsubscribe(string channel)
|
||||||
|
{
|
||||||
|
var unsubPacket = new PusherModels.PusherUnsubscribeRequestModel { Channel = channel };
|
||||||
|
SendPusherPacket("pusher:unsubscribe", unsubPacket);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WsMessageReceived(ResponseMessage message)
|
||||||
|
{
|
||||||
|
OnWsMessageReceived?.Invoke(this, message);
|
||||||
|
|
||||||
|
if (message.Text == null)
|
||||||
|
{
|
||||||
|
_logger.Info("Websocket message was null, ignoring packet");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
PusherModels.BasePusherEventModel pusherMsg;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
pusherMsg = JsonConvert.DeserializeObject<PusherModels.BasePusherEventModel>(message.Text) ??
|
||||||
|
throw new InvalidOperationException();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.Error("Failed to parse Pusher message. Exception follows:");
|
||||||
|
_logger.Error(e);
|
||||||
|
_logger.Error("--- Message from Pusher follows ---");
|
||||||
|
_logger.Error(message.Text);
|
||||||
|
_logger.Error("--- /end of message ---");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.Debug($"Pusher event receievd: {pusherMsg.Event}");
|
||||||
|
|
||||||
|
switch (pusherMsg.Event)
|
||||||
|
{
|
||||||
|
case "pusher:connection_established":
|
||||||
|
{
|
||||||
|
var data =
|
||||||
|
JsonConvert.DeserializeObject<PusherModels.PusherConnectionEstablishedEventModel>(pusherMsg.Data);
|
||||||
|
OnPusherConnectionEstablished?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "pusher_internal:subscription_succeeded":
|
||||||
|
OnPusherSubscriptionSucceeded?.Invoke(this, pusherMsg);
|
||||||
|
return;
|
||||||
|
case "pusher:pong":
|
||||||
|
OnPusherPong?.Invoke(this, pusherMsg);
|
||||||
|
return;
|
||||||
|
case @"App\Events\FollowersUpdated":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.FollowersUpdatedEventModel>(pusherMsg.Data);
|
||||||
|
OnFollowersUpdated?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\ChatMessageEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.ChatMessageEventModel>(pusherMsg.Data);
|
||||||
|
OnChatMessage?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\ChannelSubscriptionEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.ChannelSubscriptionEventModel>(pusherMsg.Data);
|
||||||
|
OnChannelSubscription?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\SubscriptionEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.SubscriptionEventModel>(pusherMsg.Data);
|
||||||
|
OnSubscription?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\MessageDeletedEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.MessageDeletedEventModel>(pusherMsg.Data);
|
||||||
|
OnMessageDeleted?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\UserBannedEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.UserBannedEventModel>(pusherMsg.Data);
|
||||||
|
OnUserBanned?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\UserUnbannedEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.UserUnbannedEventModel>(pusherMsg.Data);
|
||||||
|
OnUserUnbanned?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\LiveStream\UpdatedLiveStreamEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.UpdatedLiveStreamEventModel>(pusherMsg.Data);
|
||||||
|
OnUpdatedLiveStream?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\StopStreamBroadcast":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.StopStreamBroadcastEventModel>(pusherMsg.Data);
|
||||||
|
OnStopStreamBroadcast?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\StreamerIsLive":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.StreamerIsLiveEventModel>(pusherMsg.Data);
|
||||||
|
OnStreamerIsLive?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case @"App\Events\PollUpdateEvent":
|
||||||
|
{
|
||||||
|
var data = JsonConvert.DeserializeObject<KickModels.PollUpdateEventModel>(pusherMsg.Data);
|
||||||
|
OnPollUpdate?.Invoke(this, data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
_logger.Info("Event unhandled. JOSN payload follows");
|
||||||
|
_logger.Info(message.Text);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
KickWsClient/KickWsClient.csproj
Normal file
15
KickWsClient/KickWsClient.csproj
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="NLog" Version="5.2.8" />
|
||||||
|
<PackageReference Include="Websocket.Client" Version="5.1.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
41
KickWsClient/Models/EventHandlers.cs
Normal file
41
KickWsClient/Models/EventHandlers.cs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
using Websocket.Client;
|
||||||
|
|
||||||
|
namespace KickWsClient.Models;
|
||||||
|
|
||||||
|
public class EventHandlers
|
||||||
|
{
|
||||||
|
public delegate void OnPusherConnectionEstablishedEventHandler(object sender,
|
||||||
|
PusherModels.PusherConnectionEstablishedEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnPusherSubscriptionSucceededEventHandler(object sender, PusherModels.BasePusherEventModel e);
|
||||||
|
|
||||||
|
public delegate void OnPusherPongEventHandler(object sender, PusherModels.BasePusherEventModel e);
|
||||||
|
|
||||||
|
public delegate void OnFollowersUpdatedEventHandler(object sender, KickModels.FollowersUpdatedEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnChatMessageEventHandler(object sender, KickModels.ChatMessageEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnChannelSubscriptionEventHandler(object sender, KickModels.ChannelSubscriptionEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnSubscriptionEventHandler(object sender, KickModels.SubscriptionEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnMessageDeletedEventHandler(object sender, KickModels.MessageDeletedEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnUserBannedEventHandler(object sender, KickModels.UserBannedEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnUserUnbannedEventHandler(object sender, KickModels.UserUnbannedEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnUpdatedLiveStreamEventHandler(object sender, KickModels.UpdatedLiveStreamEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnStopStreamBroadcastEventHandler(object sender, KickModels.StopStreamBroadcastEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnStreamerIsLiveEventHandler(object sender, KickModels.StreamerIsLiveEventModel? e);
|
||||||
|
|
||||||
|
public delegate void OnWsDisconnectionEventHandler(object sender, DisconnectionInfo e);
|
||||||
|
|
||||||
|
public delegate void OnWsReconnectEventHandler(object sender, ReconnectionInfo e);
|
||||||
|
|
||||||
|
public delegate void OnWsMessageReceivedEventHandler(object sender, ResponseMessage e);
|
||||||
|
|
||||||
|
public delegate void OnPollUpdateEventHandler(object sender, KickModels.PollUpdateEventModel? e);
|
||||||
|
}
|
||||||
519
KickWsClient/Models/KickModels.cs
Normal file
519
KickWsClient/Models/KickModels.cs
Normal file
@@ -0,0 +1,519 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace KickWsClient.Models;
|
||||||
|
|
||||||
|
public class KickModels
|
||||||
|
{
|
||||||
|
public class ChatMessageSenderIdentityBadgeModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Internal type for badge e.g. moderator
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("type")]
|
||||||
|
public required string Type { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Friendly name for badge e.g. Moderator
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("text")]
|
||||||
|
public required string Text { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Count (if applicable) for badge (e.g. sub count for gifted subs)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("count")]
|
||||||
|
public int? Count { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageSenderIdentityModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// User's hex color
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("color")]
|
||||||
|
public required string Color { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Badges a user has
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("badges")]
|
||||||
|
public List<ChatMessageSenderIdentityBadgeModel> Badges = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageSenderModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Kick internal user ID
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Kick display name
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Kick slug (for URLs)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("slug")]
|
||||||
|
public required string Slug { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Identity info for display color and badges
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("identity")]
|
||||||
|
public required ChatMessageSenderIdentityModel Identity { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageMetadataOriginalSenderModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Original sender's user ID
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Original sender's username
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageMetadataOriginalMessageModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID (GUID) of the original message
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Content of the original message
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("content")]
|
||||||
|
public required string Content { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageMetadataModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Sender of the message that this message is in reply to
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("original_sender")]
|
||||||
|
public required ChatMessageMetadataOriginalSenderModel OriginalSender { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Content of the message that this message is in reply to
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("original_message")]
|
||||||
|
public required ChatMessageMetadataOriginalMessageModel OriginalMessage { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FollowersUpdatedEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Channel follower count
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("followersCount")]
|
||||||
|
public int FollowersCount { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// ID to identify what chatroom this event belongs to
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("chatroom_id")]
|
||||||
|
public int ChatroomId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Maybe returns your username if you're auth'd? No idea. Just returned null for me
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public string? Username { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Epoch value that signifies ???
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("created_at")]
|
||||||
|
public int? CreatedAtEpoch { get; set; }
|
||||||
|
// It returned true even though I'm not signed in which makes no sense, so I'll assume there's a chance it'll
|
||||||
|
// suddenly appear and mark as nullable as it's not really a useful property anyway.
|
||||||
|
/// <summary>
|
||||||
|
/// Does it mean we're following? Who knows, returns true even if you're a guest
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("followed")]
|
||||||
|
public bool? Followed { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatMessageEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Message unique GUID that's referenced for replies and deletions
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Chatroom ID you can use to differentiate this from other rooms if you sub to multiple at a time
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("chatroom_id")]
|
||||||
|
public int ChatroomId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Content of the message. Emotes are encoded like [emote:161238:russW] which translates to -> https://files.kick.com/emotes/161238/fullsize
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("content")]
|
||||||
|
public required string Content { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Regular message is 'message', replies are 'reply'
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("type")]
|
||||||
|
public required string Type { get; set; }
|
||||||
|
// Why created at is an epoch for followers updated but ISO8601 for chat messages is just a mystery
|
||||||
|
/// <summary>
|
||||||
|
/// Time message was sent
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("created_at")]
|
||||||
|
public DateTimeOffset CreatedAt { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Sender of the message
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("sender")]
|
||||||
|
public required ChatMessageSenderModel Sender { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Message metadata which is set for replies only
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("metadata")]
|
||||||
|
public ChatMessageMetadataModel? Metadata { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChannelSubscriptionEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// User IDs of subscription recipients
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("user_ids")]
|
||||||
|
public List<int> UserIds { get; set; } = [];
|
||||||
|
/// <summary>
|
||||||
|
/// Username of the person who subbed / gifted
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Channel ID where the sub event occurred
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel_id")]
|
||||||
|
public int ChannelId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SubscriptionEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of channel where the subscription event occurred
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("chatroom_id")]
|
||||||
|
public int ChatroomId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Username of the person who bought a sub
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Number of months they've subbed now (e.g. 2 if they bought their 2nd month)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("months")]
|
||||||
|
public int Months { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MessageDeletedMessageModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the message that was deleted
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MessageDeletedEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of this event (NOT the message to be removed!)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Message that was deleted
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("message")]
|
||||||
|
public required MessageDeletedMessageModel Message { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserBannedUserModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the user. Note it'll be 0 for the janny
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// User's username
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Slug suitable for URLs
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("slug")]
|
||||||
|
public required string Slug { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserBannedEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// GUID of the event
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// User who was banished
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("user")]
|
||||||
|
public required UserBannedUserModel User { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Janny who did the sweeping
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("banned_by")]
|
||||||
|
public required UserBannedUserModel BannedBy { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Datetime that the ban expires. Null for permabans
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("expires_at")]
|
||||||
|
public DateTimeOffset? ExpiresAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserUnbannedEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// GUID of the event
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public required string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// User who was unbanned
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("user")]
|
||||||
|
public required UserBannedUserModel User { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Janny who unbanned
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("unbanned_by")]
|
||||||
|
public required UserBannedUserModel UnbannedBy { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UpdatedLiveStreamCategoryParentModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID representing the category
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Slug representing the category
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("slug")]
|
||||||
|
public required string Slug { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UpdatedLiveStreamCategoryModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the category
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Friendly name of the category
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("name")]
|
||||||
|
public required string Name { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Category's slug for forming URls etc.
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("slug")]
|
||||||
|
public required string Slug { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Tags for the category
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("tags")]
|
||||||
|
public List<string> Tags { get; set; } = [];
|
||||||
|
/// <summary>
|
||||||
|
/// Parent category, if one is present. I think there usually is one, but made it nullable just in case
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("parent_category")]
|
||||||
|
public UpdatedLiveStreamCategoryParentModel? ParentCategory { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UpdatedLiveStreamEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the livestream (numeric)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Livestream slug
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("slug")]
|
||||||
|
public required string Slug { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Livestream title
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("session_title")]
|
||||||
|
public required string SessionTitle { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Livestream start time
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("created_at")]
|
||||||
|
public DateTimeOffset CreatedAt { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Language of the livestream (e.g. English)
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("language")]
|
||||||
|
public string? Language { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the stream is marked as for a mature audience
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("is_mature")]
|
||||||
|
public bool IsMature { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Number of viewers presently watching
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("viewers")]
|
||||||
|
public int Viewers { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Category of the livestream. I believe this is always required but marked it as nullable just in case
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("category")]
|
||||||
|
public UpdatedLiveStreamCategoryModel? Category { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StopStreamBroadcastLiveStreamChannelModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the channel
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the streamer was sent to ban world
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("is_banned")]
|
||||||
|
public bool IsBanned { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StopStreamBroadcastLiveStreamModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Livestream event ID
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Channel that stopped streaming
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel")]
|
||||||
|
public required StopStreamBroadcastLiveStreamChannelModel Channel { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StopStreamBroadcastEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Object containing information related to the livestream that stopped
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("livestream")]
|
||||||
|
public required StopStreamBroadcastLiveStreamModel Livestream { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StreamerIsLiveLiveStreamModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the livestream
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the channel
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel_id")]
|
||||||
|
public int ChannelId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Title of the stream
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("session_title")]
|
||||||
|
public required string SessionTitle { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// No idea, just null on my end
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("source")]
|
||||||
|
public string? Source { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Time stream started
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("created_at")]
|
||||||
|
public DateTimeOffset CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class StreamerIsLiveEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Object containing information related to the livestream that has just started
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("livestream")]
|
||||||
|
public required StreamerIsLiveLiveStreamModel Livestream { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PollUpdatePollOptionModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// ID of the poll option
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("id")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Label of the poll option
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("label")]
|
||||||
|
public required string Label { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Number of votes the poll option has gotten
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("votes")]
|
||||||
|
public int Votes { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PollUpdatePollModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Title of the poll
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("title")]
|
||||||
|
public required string Title { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Poll options
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("options")]
|
||||||
|
public List<PollUpdatePollOptionModel> Options { get; set; } = [];
|
||||||
|
/// <summary>
|
||||||
|
/// Duration of the poll in seconds
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("duration")]
|
||||||
|
public int Duration { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Remaining time in seconds
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("remaining")]
|
||||||
|
public int Remaining { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Time in seconds to display the results after completion?
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("result_display_duration")]
|
||||||
|
public int ResultDisplayDuration { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PollUpdateEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Poll data
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("poll")]
|
||||||
|
public required PollUpdatePollModel Poll { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
76
KickWsClient/Models/PusherModels.cs
Normal file
76
KickWsClient/Models/PusherModels.cs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace KickWsClient.Models;
|
||||||
|
|
||||||
|
public class PusherModels
|
||||||
|
{
|
||||||
|
public class BasePusherEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Name of the event
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("event")]
|
||||||
|
public required string Event { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Stringified JSON payload
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("data")]
|
||||||
|
public required string Data { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Channel where event originates. Only included events where a channel is applicable
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel")]
|
||||||
|
public string? Channel { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class BasePusherRequestModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Name of the event
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("event")]
|
||||||
|
public required string Event { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Data as object. It's only stringified for responses
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("data")]
|
||||||
|
public required object Data { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PusherConnectionEstablishedEventModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Internal socket ID
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("socket_id")]
|
||||||
|
public required string SocketId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Timeout on no activity in seconds
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("activity_timeout")]
|
||||||
|
public int ActivityTimeout { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PusherSubscribeRequestModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Token to authenticate with, use an empty string for guest.
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("auth")]
|
||||||
|
public string Auth { get; set; } = "";
|
||||||
|
/// <summary>
|
||||||
|
/// Channel you wish to subscribe to. 'channel.2515504' for stream events. 'chatrooms.2515504.v2' for chat where 2515504 is the channel ID
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel")]
|
||||||
|
public required string Channel { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PusherUnsubscribeRequestModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Channel you wish to unsubscribe from, e.g. 'channel.2515504'
|
||||||
|
/// </summary>
|
||||||
|
[JsonProperty("channel")]
|
||||||
|
public required string Channel { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
7
global.json
Normal file
7
global.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"sdk": {
|
||||||
|
"version": "8.0.0",
|
||||||
|
"rollForward": "latestMajor",
|
||||||
|
"allowPrerelease": true
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user