This commit is contained in:
Myx
2025-03-19 01:16:12 +01:00
commit 83a80b4b0f
28 changed files with 893 additions and 0 deletions

29
Pages/ClientPage.xaml Normal file
View File

@@ -0,0 +1,29 @@
<Page
x:Class="BeetleWire_UI.Pages.ClientPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BeetleWire_UI.Pages">
<Grid Padding="12">
<StackPanel>
<!-- Shared Folder Section -->
<TextBlock Text="Client" FontSize="20" FontWeight="Bold" Margin="0,0,0,12"/>
<TextBlock Text="Shared Folder Path:" FontWeight="Bold" />
<StackPanel Orientation="Horizontal">
<TextBox x:Name="SharedFolderPathTextBox" Width="500" Margin="0,0,12,0"/>
<Button Content="Set Folder" Click="SetFolderButton_Click"/>
</StackPanel>
<!-- Server Connection Section -->
<TextBlock Text="Server Address:"/>
<TextBox x:Name="ServerAddressTextBox" Text="127.0.0.1:1337" Margin="0,0,0,12"/>
<StackPanel Orientation="Horizontal">
<Button Content="Connect to Server" Click="ConnectButton_Click" Margin="0,0,0,12"/>
<Button Content="Save Connection" Click="SaveConnectionButton_Click" Margin="12,0,0,12"/>
</StackPanel>
<!-- File List and Download Section -->
<TextBlock Text="Available Files:"/>
<ListView x:Name="FilesListView" SelectionChanged="FilesListView_SelectionChanged" Height="200"/>
<ProgressBar x:Name="DownloadProgressBar" Height="20" Margin="0,12,0,0" Visibility="Collapsed"/>
<TextBlock x:Name="StatusTextBlock" Margin="0,12,0,0"/>
</StackPanel>
</Grid>
</Page>

170
Pages/ClientPage.xaml.cs Normal file
View File

@@ -0,0 +1,170 @@
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using BeetleWire_UI.Services;
using Microsoft.UI.Xaml.Navigation;
namespace BeetleWire_UI.Pages;
public sealed partial class ClientPage : Page
{
private ClientWebSocket _webSocket;
private CancellationTokenSource _cts = new CancellationTokenSource();
private string _sharedFolderPath;
private MainWindow _mainWindow;
public ClientPage()
{
this.InitializeComponent();
LoadSharedFolderPath();
EnsureSharedFolderExists();
}
private void LoadSharedFolderPath()
{
var localSettings = ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey("SharedFolderPath"))
{
_sharedFolderPath = localSettings.Values["SharedFolderPath"].ToString();
}
else
{
_sharedFolderPath = System.IO.Path.Combine(Environment.CurrentDirectory, "Shared");
}
SharedFolderPathTextBox.Text = _sharedFolderPath;
}
private void SaveSharedFolderPath()
{
var localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["SharedFolderPath"] = _sharedFolderPath;
}
private void SetFolderButton_Click(object sender, RoutedEventArgs e)
{
_sharedFolderPath = SharedFolderPathTextBox.Text.Trim();
if (string.IsNullOrEmpty(_sharedFolderPath))
{
StatusTextBlock.Text = "Folder path cannot be empty.";
return;
}
SaveSharedFolderPath();
EnsureSharedFolderExists();
StatusTextBlock.Text = $"Shared folder set to: {_sharedFolderPath}";
}
private void EnsureSharedFolderExists()
{
if (!System.IO.Directory.Exists(_sharedFolderPath))
{
try
{
System.IO.Directory.CreateDirectory(_sharedFolderPath);
}
catch (Exception ex)
{
StatusTextBlock.Text = $"Failed to create folder: {ex.Message}";
}
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var serverAddress = ServerAddressTextBox.Text;
var uri = new Uri($"ws://{serverAddress}");
try
{
await ConnectionManager.Instance.ConnectClientAsync(uri, _cts.Token);
StatusTextBlock.Text = "Connected to server.";
var fileList = await ReceiveFileListAsync();
FilesListView.ItemsSource = fileList;
_mainWindow?.UpdateClientStatus(true);
}
catch (Exception ex)
{
StatusTextBlock.Text = $"Error connecting: {ex.Message}";
}
}
private async Task<List<string>> ReceiveFileListAsync()
{
var buffer = new ArraySegment<byte>(new byte[4096]);
WebSocketReceiveResult result = await _webSocket.ReceiveAsync(buffer, _cts.Token);
string jsonString = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
var fileList = JsonSerializer.Deserialize<List<string>>(jsonString);
return fileList ?? new List<string>();
}
private async void FilesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (FilesListView.SelectedItem is string fileName)
{
StatusTextBlock.Text = $"Downloading {fileName}...";
DownloadProgressBar.Visibility = Visibility.Visible;
DownloadProgressBar.Value = 0;
byte[] requestBytes = Encoding.UTF8.GetBytes(fileName);
await _webSocket.SendAsync(new ArraySegment<byte>(requestBytes), WebSocketMessageType.Text, true, _cts.Token);
byte[] fileData = await ReceiveFileDataAsync();
string filePath = System.IO.Path.Combine(_sharedFolderPath, fileName);
System.IO.File.WriteAllBytes(filePath, fileData);
StatusTextBlock.Text = $"File {fileName} downloaded to {_sharedFolderPath}.";
DownloadProgressBar.Visibility = Visibility.Collapsed;
}
}
private async Task<byte[]> ReceiveFileDataAsync()
{
var buffer = new ArraySegment<byte>(new byte[8192]);
using (var ms = new System.IO.MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = await _webSocket.ReceiveAsync(buffer, _cts.Token);
ms.Write(buffer.Array, buffer.Offset, result.Count);
} while (!result.EndOfMessage);
return ms.ToArray();
}
}
private void SaveConnectionButton_Click(object sender, RoutedEventArgs e)
{
var serverAddress = ServerAddressTextBox.Text.Trim();
if (string.IsNullOrEmpty(serverAddress))
{
StatusTextBlock.Text = "Server address cannot be empty.";
return;
}
var localSettings = ApplicationData.Current.LocalSettings;
var connections = localSettings.Values["Connections"] as ApplicationDataCompositeValue ?? new ApplicationDataCompositeValue();
connections[serverAddress] = DateTime.Now.ToString();
localSettings.Values["Connections"] = connections;
StatusTextBlock.Text = $"Connection to {serverAddress} saved.";
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is MainWindow mainWindow)
{
_mainWindow = mainWindow;
}
else
{
_mainWindow = null;
}
}
}

View File

@@ -0,0 +1,12 @@
<Page
x:Class="BeetleWire_UI.Pages.ConnectionsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BeetleWire_UI.Pages">
<Grid Padding="12">
<StackPanel>
<TextBlock Text="Saved Connections" FontSize="20" FontWeight="Bold" Margin="0,0,0,12"/>
<ListView x:Name="ConnectionsListView" Height="200"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,27 @@
using Windows.Storage;
using Microsoft.UI.Xaml.Controls;
namespace BeetleWire_UI.Pages;
public sealed partial class ConnectionsPage : Page
{
public ConnectionsPage()
{
this.InitializeComponent();
LoadConnections();
}
private void LoadConnections()
{
var localSettings = ApplicationData.Current.LocalSettings;
var connections = localSettings.Values["Connections"] as ApplicationDataCompositeValue;
if (connections != null)
{
foreach (var connection in connections)
{
ConnectionsListView.Items.Add($"{connection.Key} - {connection.Value}");
}
}
}
}

19
Pages/ServerPage.xaml Normal file
View File

@@ -0,0 +1,19 @@
<Page
x:Class="BeetleWire_UI.Pages.ServerPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BeetleWire_UI.Pages">
<Grid Padding="12">
<StackPanel>
<TextBlock Text="Server" FontSize="20" FontWeight="Bold" Margin="0,0,0,12"/>
<TextBlock Text="Listening on:"/>
<TextBox x:Name="ServerAddressTextBox" Text="localhost:1337" Margin="0,0,0,12" Width="300"/>
<TextBlock Text="Directory:"/>
<TextBox x:Name="ServerDirectoryTextBox" Text="C:\Shared" Margin="0,0,0,12" Width="300"/>
<Button Content="Start Server" Click="StartServerButton_Click" Width="200"/>
<ScrollViewer Margin="0,12,0,0" Height="200">
<TextBlock x:Name="LogTextBlock" TextWrapping="Wrap"/>
</ScrollViewer>
</StackPanel>
</Grid>
</Page>

161
Pages/ServerPage.xaml.cs Normal file
View File

@@ -0,0 +1,161 @@
using BeetleWire_UI.Services;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.UI.Xaml.Navigation;
namespace BeetleWire_UI.Pages;
public sealed partial class ServerPage : Page
{
private HttpListener _listener;
private MainWindow _mainWindow;
public ServerPage()
{
this.InitializeComponent();
}
private void StartServerButton_Click(object sender, RoutedEventArgs e)
{
string serverAddress = ServerAddressTextBox.Text.Trim();
string dirPath = ServerDirectoryTextBox.Text.Trim();
if (!Directory.Exists(dirPath))
{
Log("Directory does not exist: " + dirPath);
return;
}
string prefix = $"http://{serverAddress}/";
try
{
ConnectionManager.Instance.StartServer(prefix);
Log($"Server listening on {serverAddress}");
// Update the main window status
_mainWindow.UpdateServerStatus(true);
}
catch (Exception ex)
{
Log("Failed to start listener: " + ex.Message);
}
}
private async Task RunServerLoopAsync(string dirPath, CancellationToken token)
{
try
{
while (!token.IsCancellationRequested)
{
// Wait for an incoming HTTP request.
var context = await _listener.GetContextAsync();
// Check if it's a WebSocket request.
if (context.Request.IsWebSocketRequest)
{
_ = ProcessWebSocketRequestAsync(context, dirPath, token);
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
catch (Exception ex)
{
Log("Server loop error: " + ex.Message);
}
}
private async Task ProcessWebSocketRequestAsync(HttpListenerContext context, string dirPath, CancellationToken token)
{
HttpListenerWebSocketContext wsContext = null;
try
{
wsContext = await context.AcceptWebSocketAsync(null);
Log("WebSocket connection established.");
}
catch (Exception ex)
{
Log("WebSocket handshake error: " + ex.Message);
context.Response.StatusCode = 500;
context.Response.Close();
return;
}
WebSocket webSocket = wsContext.WebSocket;
try
{
// List files in the directory.
List<string> fileList = new List<string>();
foreach (var file in Directory.EnumerateFiles(dirPath))
{
fileList.Add(Path.GetFileName(file));
}
string fileListJson = JsonSerializer.Serialize(fileList);
byte[] listBytes = Encoding.UTF8.GetBytes(fileListJson);
await webSocket.SendAsync(new ArraySegment<byte>(listBytes), WebSocketMessageType.Text, true, token);
Log("Sent file list.");
// Wait for the client to request a file.
byte[] recvBuffer = new byte[4096];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(recvBuffer), token);
if (result.MessageType == WebSocketMessageType.Text)
{
string requestedFile = Encoding.UTF8.GetString(recvBuffer, 0, result.Count);
Log($"Client requested file: {requestedFile}");
string filePath = Path.Combine(dirPath, requestedFile);
if (File.Exists(filePath))
{
byte[] fileBytes = await File.ReadAllBytesAsync(filePath, token);
await webSocket.SendAsync(new ArraySegment<byte>(fileBytes), WebSocketMessageType.Binary, true, token);
Log("Sent file data.");
}
else
{
Log("Requested file not found.");
}
}
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", token);
Log("WebSocket connection closed.");
}
catch (Exception ex)
{
Log("Error during WebSocket communication: " + ex.Message);
}
}
// Helper to update the log (on UI thread).
private void Log(string message)
{
DispatcherQueue.TryEnqueue(() => {
LogTextBlock.Text += $"{DateTime.Now:T} - {message}\n";
});
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is MainWindow mainWindow)
{
_mainWindow = mainWindow;
}
else
{
_mainWindow = null;
}
}
}