mirror of
https://github.com/chylex/Discord-History-Tracker.git
synced 2025-08-17 19:31:42 +02:00
Compare commits
31 Commits
Author | SHA1 | Date | |
---|---|---|---|
edc23d616d
|
|||
db191f87fd
|
|||
e8677c09b4
|
|||
378c54908e
|
|||
07af4ae00f
|
|||
c262e5aaa4
|
|||
96e125b812
|
|||
c0123b9f91
|
|||
2ec9c7cbc3
|
|||
4cfe19d369
|
|||
f449859ad9
|
|||
ae5630cf96
|
|||
75c8202c77
|
|||
e9e8c95a19
|
|||
879a69608c
|
|||
560c515ecf
|
|||
ec8c00853a
|
|||
5888d13d7c
|
|||
15db0cca8e
|
|||
52998f7d7a
|
|||
c2e302f8bb
|
|||
9f506aceb2
|
|||
bbb50dc50c
|
|||
3f763bbf6b
|
|||
be3a7d6d80
|
|||
bd78051a9d
|
|||
6a24befca1
|
|||
09dce7b062
|
|||
396c622d9c
|
|||
73bf16a21e
|
|||
25071d4323
|
1
app/.idea/.idea.DiscordHistoryTracker/.idea/.gitignore
generated
vendored
1
app/.idea/.idea.DiscordHistoryTracker/.idea/.gitignore
generated
vendored
@@ -2,7 +2,6 @@
|
||||
/contentModel.xml
|
||||
/dataSources
|
||||
/dataSources.local.xml
|
||||
/dataSources.xml
|
||||
/dictionaries
|
||||
/httpRequests/
|
||||
/misc.xml
|
||||
|
@@ -4,8 +4,11 @@
|
||||
<option name="projectPerEditor">
|
||||
<map>
|
||||
<entry key="Desktop/App.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Dialogs/CheckBoxDialog.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Dialogs/MessageDialog.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Dialogs/ProgressDialog.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Main/AboutWindow.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Main/Controls/FilterPanel.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Main/Controls/StatusBar.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Main/MainContentScreen.axaml" value="Desktop/Desktop.csproj" />
|
||||
<entry key="Desktop/Main/MainWindow.axaml" value="Desktop/Desktop.csproj" />
|
||||
|
@@ -13,10 +13,10 @@
|
||||
<CssCodeStyleSettings>
|
||||
<option name="HEX_COLOR_LOWER_CASE" value="true" />
|
||||
</CssCodeStyleSettings>
|
||||
<DB2CodeStyleSettings version="5">
|
||||
<DB2CodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</DB2CodeStyleSettings>
|
||||
<DerbyCodeStyleSettings version="5">
|
||||
<DerbyCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</DerbyCodeStyleSettings>
|
||||
<GoCodeStyleSettings>
|
||||
@@ -26,10 +26,13 @@
|
||||
<option name="WRAP_FUNC_PARAMS" value="5" />
|
||||
<option name="WRAP_FUNC_RESULT" value="5" />
|
||||
</GoCodeStyleSettings>
|
||||
<H2CodeStyleSettings version="5">
|
||||
<H2CodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</H2CodeStyleSettings>
|
||||
<HSQLCodeStyleSettings version="5">
|
||||
<H2CodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</H2CodeStyleSettings>
|
||||
<HSQLCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</HSQLCodeStyleSettings>
|
||||
<HTMLCodeStyleSettings>
|
||||
@@ -85,10 +88,10 @@
|
||||
<LessCodeStyleSettings>
|
||||
<option name="HEX_COLOR_LOWER_CASE" value="true" />
|
||||
</LessCodeStyleSettings>
|
||||
<MSSQLCodeStyleSettings version="5">
|
||||
<MSSQLCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</MSSQLCodeStyleSettings>
|
||||
<MySQLCodeStyleSettings version="5">
|
||||
<MySQLCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</MySQLCodeStyleSettings>
|
||||
<Objective-C>
|
||||
@@ -98,7 +101,7 @@
|
||||
<option name="SPACE_BEFORE_INIT_LIST" value="true" />
|
||||
<option name="SPACE_AFTER_DICTIONARY_LITERAL_COLON" value="false" />
|
||||
</Objective-C>
|
||||
<OracleCodeStyleSettings version="5">
|
||||
<OracleCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</OracleCodeStyleSettings>
|
||||
<PHPCodeStyleSettings>
|
||||
@@ -116,7 +119,7 @@
|
||||
<option name="NEW_LINE_AFTER_PHP_OPENING_TAG" value="true" />
|
||||
<option name="SPACE_AROUND_ASSIGNMENT_IN_DECLARE" value="true" />
|
||||
</PHPCodeStyleSettings>
|
||||
<PostgresCodeStyleSettings version="5">
|
||||
<PostgresCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</PostgresCodeStyleSettings>
|
||||
<Properties>
|
||||
@@ -143,13 +146,13 @@
|
||||
<option name="INDENT_WHEN_CASES" value="true" />
|
||||
<option name="CHAIN_CALLS_ALIGNMENT" value="2" />
|
||||
</Ruby>
|
||||
<SQLiteCodeStyleSettings version="5">
|
||||
<SQLiteCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</SQLiteCodeStyleSettings>
|
||||
<ScssCodeStyleSettings>
|
||||
<option name="HEX_COLOR_LOWER_CASE" value="true" />
|
||||
</ScssCodeStyleSettings>
|
||||
<SqlCodeStyleSettings version="5">
|
||||
<SqlCodeStyleSettings version="6">
|
||||
<option name="KEYWORD_CASE" value="2" />
|
||||
<option name="TYPE_CASE" value="2" />
|
||||
<option name="CUSTOM_TYPE_CASE" value="2" />
|
||||
@@ -175,7 +178,7 @@
|
||||
<option name="VIEW_INDENT_QUERY" value="true" />
|
||||
<option name="EXPR_CASE_WHEN_WRAP" value="false" />
|
||||
</SqlCodeStyleSettings>
|
||||
<SybaseCodeStyleSettings version="5">
|
||||
<SybaseCodeStyleSettings version="6">
|
||||
<option name="USE_GENERIC_STYLE" value="true" />
|
||||
</SybaseCodeStyleSettings>
|
||||
<TypeScriptCodeStyleSettings version="0">
|
||||
|
12
app/.idea/.idea.DiscordHistoryTracker/.idea/dataSources.xml
generated
Normal file
12
app/.idea/.idea.DiscordHistoryTracker/.idea/dataSources.xml
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="empty.dht" read-only="true" uuid="e01b8deb-489e-470a-9011-f6548927191e">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/empty.dht</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
@@ -1,6 +1,6 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Desktop" type="DotNetProject" factoryName=".NET Project">
|
||||
<option name="EXE_PATH" value="$PROJECT_DIR$/Desktop/bin/Debug/net5.0/Desktop.exe" />
|
||||
<option name="EXE_PATH" value="$PROJECT_DIR$/Desktop/bin/Debug/net5.0/DiscordHistoryTracker.exe" />
|
||||
<option name="PROGRAM_PARAMETERS" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/Desktop/bin/Debug/net5.0" />
|
||||
<option name="PASS_PARENT_ENVS" value="1" />
|
||||
|
23
app/.idea/.idea.DiscordHistoryTracker/.idea/runConfigurations/Minify.xml
generated
Normal file
23
app/.idea/.idea.DiscordHistoryTracker/.idea/runConfigurations/Minify.xml
generated
Normal file
@@ -0,0 +1,23 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Minify" type="PythonConfigurationType" factoryName="Python">
|
||||
<module name="rider.module" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<envs>
|
||||
<env name="PYTHONUNBUFFERED" value="1" />
|
||||
</envs>
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="IS_MODULE_SDK" value="false" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="false" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="false" />
|
||||
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/minify.py" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="SHOW_COMMAND_LINE" value="false" />
|
||||
<option name="EMULATE_TERMINAL" value="false" />
|
||||
<option name="MODULE_MODE" value="false" />
|
||||
<option name="REDIRECT_INPUT" value="false" />
|
||||
<option name="INPUT_FILE" value="" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
@@ -1,5 +1,6 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:common="clr-namespace:DHT.Desktop.Common"
|
||||
x:Class="DHT.Desktop.App">
|
||||
|
||||
<Application.Styles>
|
||||
@@ -8,20 +9,20 @@
|
||||
|
||||
<Style Selector="Button">
|
||||
<Setter Property="Padding" Value="10 7 10 6" />
|
||||
<Setter Property="Background" Value="#D2D2D2" />
|
||||
<Setter Property="Background" Value="#DDDDDD" />
|
||||
<Setter Property="BorderBrush" Value="#999999" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Button /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="TextBlock.Foreground" Value="#070707" />
|
||||
<Setter Property="Background" Value="#D2D2D2" />
|
||||
<Setter Property="TextBlock.Foreground" Value="#060606" />
|
||||
<Setter Property="Background" Value="#DDDDDD" />
|
||||
<Setter Property="BorderBrush" Value="#999999" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="Button:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="#DEDEDE" />
|
||||
<Setter Property="Background" Value="#E7E7E7" />
|
||||
<Setter Property="BorderBrush" Value="#A2A2A2" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
@@ -29,28 +30,25 @@
|
||||
<Setter Property="RenderTransform" Value="none" />
|
||||
</Style>
|
||||
<Style Selector="Button:pressed /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="#E5E5E5" />
|
||||
<Setter Property="Background" Value="#EBEBEB" />
|
||||
<Setter Property="BorderBrush" Value="#A5A5A5" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="Button:disabled /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="TextBlock.Foreground" Value="#909090" />
|
||||
<Setter Property="TextBlock.Foreground" Value="#7A7A7A" />
|
||||
<Setter Property="Background" Value="#E9E9E9" />
|
||||
<Setter Property="BorderBrush" Value="#BFBFBF" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
|
||||
<Style Selector="TextBox">
|
||||
<Setter Property="BorderBrush" Value="#999999" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
<Setter Property="SelectionBrush" Value="#72C0FF" />
|
||||
<Setter Property="Background" Value="#F4F4F4" />
|
||||
<Setter Property="Padding" Value="6 0" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="TextBox /template/ Border#PART_BorderElement">
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="TextBox:pointerover /template/ Border#PART_BorderElement">
|
||||
<Setter Property="BorderBrush" Value="#999999" />
|
||||
<Setter Property="Background" Value="#F8F8F8" />
|
||||
@@ -68,6 +66,59 @@
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style Selector="Expander">
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="Expander /template/ ToggleButton#ExpanderHeader">
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="Template">
|
||||
<ControlTemplate>
|
||||
<Border x:Name="ToggleButtonBackground">
|
||||
<Grid ColumnDefinitions="Auto,*" RowDefinitions="35">
|
||||
<Border x:Name="ExpandCollapseChevronBorder"
|
||||
Grid.Column="0"
|
||||
Width="35"
|
||||
Height="35"
|
||||
Margin="2,0"
|
||||
RenderTransformOrigin="50%,50%">
|
||||
<Path x:Name="ExpandCollapseChevron"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
RenderTransformOrigin="50%,50%"
|
||||
Stretch="None"
|
||||
Stroke="{DynamicResource ExpanderChevronForeground}"
|
||||
StrokeThickness="1" />
|
||||
<Border.RenderTransform>
|
||||
<RotateTransform />
|
||||
</Border.RenderTransform>
|
||||
</Border>
|
||||
<ContentPresenter x:Name="PART_ContentPresenter"
|
||||
Grid.Column="1"
|
||||
Margin="0"
|
||||
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalContentAlignment="Center"
|
||||
Background="Transparent"
|
||||
BorderBrush="Transparent"
|
||||
BorderThickness="0"
|
||||
Content="{TemplateBinding Content}"
|
||||
ContentTemplate="{TemplateBinding ContentTemplate}"
|
||||
TextBlock.Foreground="{DynamicResource ExpanderForeground}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
</Application.Styles>
|
||||
|
||||
<Application.Resources>
|
||||
|
||||
<common:NumberValueConverter x:Key="NumberValueConverter" />
|
||||
|
||||
<Thickness x:Key="ExpanderHeaderPadding">15,0</Thickness>
|
||||
<Thickness x:Key="ExpanderContentPadding">15</Thickness>
|
||||
<SolidColorBrush x:Key="ExpanderDropDownBackground" Color="#FCFCFC" />
|
||||
|
||||
</Application.Resources>
|
||||
|
||||
</Application>
|
||||
|
64
app/Desktop/Common/DatabaseGui.cs
Normal file
64
app/Desktop/Common/DatabaseGui.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Server.Database;
|
||||
using DHT.Server.Database.Exceptions;
|
||||
using DHT.Server.Database.Sqlite;
|
||||
using DHT.Server.Logging;
|
||||
|
||||
namespace DHT.Desktop.Common {
|
||||
public static class DatabaseGui {
|
||||
private const string DatabaseFileInitialName = "archive.dht";
|
||||
|
||||
private static readonly List<FileDialogFilter> DatabaseFileDialogFilter = new() {
|
||||
new FileDialogFilter {
|
||||
Name = "Discord History Tracker Database",
|
||||
Extensions = { "dht" }
|
||||
}
|
||||
};
|
||||
|
||||
public static OpenFileDialog NewOpenDatabaseFileDialog() {
|
||||
return new OpenFileDialog {
|
||||
Title = "Open Database File",
|
||||
InitialFileName = DatabaseFileInitialName,
|
||||
Filters = DatabaseFileDialogFilter
|
||||
};
|
||||
}
|
||||
|
||||
public static SaveFileDialog NewOpenOrCreateDatabaseFileDialog() {
|
||||
return new SaveFileDialog {
|
||||
Title = "Open or Create Database File",
|
||||
InitialFileName = DatabaseFileInitialName,
|
||||
Filters = DatabaseFileDialogFilter
|
||||
};
|
||||
}
|
||||
|
||||
public static async Task<IDatabaseFile?> TryOpenOrCreateDatabaseFromPath(string path, Window window, Func<Task<bool>> checkCanUpgradeDatabase) {
|
||||
IDatabaseFile? file = null;
|
||||
|
||||
try {
|
||||
file = await SqliteDatabaseFile.OpenOrCreate(path, checkCanUpgradeDatabase);
|
||||
} catch (InvalidDatabaseVersionException ex) {
|
||||
await Dialog.ShowOk(window, "Database Error", "Database '" + Path.GetFileName(path) + "' appears to be corrupted (invalid version: " + ex.Version + ").");
|
||||
} catch (DatabaseTooNewException ex) {
|
||||
await Dialog.ShowOk(window, "Database Error", "Database '" + Path.GetFileName(path) + "' was opened in a newer version of DHT (database version " + ex.DatabaseVersion + ", app version " + ex.CurrentVersion + ").");
|
||||
} catch (Exception ex) {
|
||||
Log.Error(ex);
|
||||
await Dialog.ShowOk(window, "Database Error", "Database '" + Path.GetFileName(path) + "' could not be opened:" + ex.Message);
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
public static async Task<DialogResult.YesNo> ShowCanUpgradeDatabaseDialog(Window window) {
|
||||
return await Dialog.ShowYesNo(window, "Database Upgrade", "This database was created with an older version of DHT. If you proceed, the database will be upgraded and will no longer open in previous versions of DHT. Do you want to proceed with the upgrade?");
|
||||
}
|
||||
|
||||
public static async Task<DialogResult.YesNo> ShowCanUpgradeMultipleDatabaseDialog(Window window) {
|
||||
return await Dialog.ShowYesNo(window, "Database Upgrade", "One or more databases were created with an older version of DHT. If you proceed, these databases will be upgraded and will no longer open in previous versions of DHT. Otherwise, these databases will be skipped. Do you want to proceed with the upgrade?");
|
||||
}
|
||||
}
|
||||
}
|
15
app/Desktop/Common/NumberValueConverter.cs
Normal file
15
app/Desktop/Common/NumberValueConverter.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
|
||||
namespace DHT.Desktop.Common {
|
||||
public class NumberValueConverter : IValueConverter {
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
return string.Format(Program.Culture, "{0:n0}", value);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
19
app/Desktop/Common/TextFormat.cs
Normal file
19
app/Desktop/Common/TextFormat.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace DHT.Desktop.Common {
|
||||
public static class TextFormat {
|
||||
public static string Format(this int number) {
|
||||
return number.ToString("N0", Program.Culture);
|
||||
}
|
||||
|
||||
public static string Format(this long number) {
|
||||
return number.ToString("N0", Program.Culture);
|
||||
}
|
||||
|
||||
public static string Pluralize(this int number, string singular) {
|
||||
return number.Format() + "\u00A0" + (number == 1 ? singular : singular + "s");
|
||||
}
|
||||
|
||||
public static string Pluralize(this long number, string singular) {
|
||||
return number.Format() + "\u00A0" + (number == 1 ? singular : singular + "s");
|
||||
}
|
||||
}
|
||||
}
|
@@ -12,7 +12,7 @@
|
||||
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<AssemblyName>DiscordHistoryTracker</AssemblyName>
|
||||
<Version>31.0.0.0</Version>
|
||||
<Version>33.1.0.0</Version>
|
||||
<AssemblyVersion>$(Version)</AssemblyVersion>
|
||||
<FileVersion>$(Version)</FileVersion>
|
||||
<PackageVersion>$(Version)</PackageVersion>
|
||||
@@ -22,12 +22,12 @@
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="0.10.3" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="0.10.3" />
|
||||
<PackageReference Include="Avalonia" Version="0.10.10" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="0.10.10" />
|
||||
<ProjectReference Include="..\Server\Server.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<PackageReference Include="Avalonia.Diagnostics" Version="0.10.3" />
|
||||
<PackageReference Include="Avalonia.Diagnostics" Version="0.10.10" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Update="Windows\MainWindow.axaml.cs">
|
||||
|
61
app/Desktop/Dialogs/CheckBoxDialog.axaml
Normal file
61
app/Desktop/Dialogs/CheckBoxDialog.axaml
Normal file
@@ -0,0 +1,61 @@
|
||||
<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:dialogs="clr-namespace:DHT.Desktop.Dialogs"
|
||||
mc:Ignorable="d" d:DesignWidth="500"
|
||||
x:Class="DHT.Desktop.Dialogs.CheckBoxDialog"
|
||||
Title="{Binding Title}"
|
||||
Icon="avares://DiscordHistoryTracker/Resources/icon.ico"
|
||||
Width="500" SizeToContent="Height" CanResize="False"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<Window.DataContext>
|
||||
<dialogs:CheckBoxDialogModel />
|
||||
</Window.DataContext>
|
||||
|
||||
<Window.Styles>
|
||||
<Style Selector="Panel.buttons">
|
||||
<Setter Property="Margin" Value="0 20 0 0" />
|
||||
</Style>
|
||||
<Style Selector="Panel.buttons > WrapPanel.right">
|
||||
<Setter Property="HorizontalAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style Selector="Panel.buttons Button">
|
||||
<Setter Property="MinWidth" Value="80" />
|
||||
</Style>
|
||||
<Style Selector="Panel.buttons > WrapPanel.left Button">
|
||||
<Setter Property="Margin" Value="0 0 8 0" />
|
||||
</Style>
|
||||
<Style Selector="Panel.buttons > WrapPanel.right Button">
|
||||
<Setter Property="Margin" Value="8 0 0 0" />
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<StackPanel Margin="20">
|
||||
<ScrollViewer MaxHeight="400">
|
||||
<ItemsControl Items="{Binding Items}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<CheckBox IsChecked="{Binding Checked}">
|
||||
<Label>
|
||||
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" />
|
||||
</Label>
|
||||
</CheckBox>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
<Panel Classes="buttons">
|
||||
<WrapPanel Classes="left">
|
||||
<Button Command="{Binding SelectAll}" IsEnabled="{Binding !AreAllSelected}">Select All</Button>
|
||||
<Button Command="{Binding SelectNone}" IsEnabled="{Binding !AreNoneSelected}">Select None</Button>
|
||||
</WrapPanel>
|
||||
<WrapPanel Classes="right">
|
||||
<Button Click="ClickOk">OK</Button>
|
||||
<Button Click="ClickCancel">Cancel</Button>
|
||||
</WrapPanel>
|
||||
</Panel>
|
||||
</StackPanel>
|
||||
|
||||
</Window>
|
28
app/Desktop/Dialogs/CheckBoxDialog.axaml.cs
Normal file
28
app/Desktop/Dialogs/CheckBoxDialog.axaml.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public class CheckBoxDialog : Window {
|
||||
public CheckBoxDialog() {
|
||||
InitializeComponent();
|
||||
#if DEBUG
|
||||
this.AttachDevTools();
|
||||
#endif
|
||||
}
|
||||
|
||||
private void InitializeComponent() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public void ClickOk(object? sender, RoutedEventArgs e) {
|
||||
Close(DialogResult.OkCancel.Ok);
|
||||
}
|
||||
|
||||
public void ClickCancel(object? sender, RoutedEventArgs e) {
|
||||
Close(DialogResult.OkCancel.Cancel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
70
app/Desktop/Dialogs/CheckBoxDialogModel.cs
Normal file
70
app/Desktop/Dialogs/CheckBoxDialogModel.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using DHT.Desktop.Models;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public class CheckBoxDialogModel : BaseModel {
|
||||
public string Title { get; init; } = "";
|
||||
|
||||
private IReadOnlyList<CheckBoxItem> items = Array.Empty<CheckBoxItem>();
|
||||
|
||||
public IReadOnlyList<CheckBoxItem> Items {
|
||||
get => items;
|
||||
|
||||
protected set {
|
||||
foreach (var item in items) {
|
||||
item.PropertyChanged -= OnItemPropertyChanged;
|
||||
}
|
||||
|
||||
items = value;
|
||||
|
||||
foreach (var item in items) {
|
||||
item.PropertyChanged += OnItemPropertyChanged;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool pauseCheckEvents = false;
|
||||
|
||||
public bool AreAllSelected => Items.All(item => item.Checked);
|
||||
public bool AreNoneSelected => Items.All(item => !item.Checked);
|
||||
|
||||
public void SelectAll() => SetAllChecked(true);
|
||||
public void SelectNone() => SetAllChecked(false);
|
||||
|
||||
private void SetAllChecked(bool isChecked) {
|
||||
pauseCheckEvents = true;
|
||||
|
||||
foreach (var item in Items) {
|
||||
item.Checked = isChecked;
|
||||
}
|
||||
|
||||
pauseCheckEvents = false;
|
||||
UpdateBulkButtons();
|
||||
}
|
||||
|
||||
private void UpdateBulkButtons() {
|
||||
OnPropertyChanged(nameof(AreAllSelected));
|
||||
OnPropertyChanged(nameof(AreNoneSelected));
|
||||
}
|
||||
|
||||
private void OnItemPropertyChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
if (!pauseCheckEvents && e.PropertyName == nameof(CheckBoxItem.Checked)) {
|
||||
UpdateBulkButtons();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class CheckBoxDialogModel<T> : CheckBoxDialogModel {
|
||||
public new IReadOnlyList<CheckBoxItem<T>> Items { get; }
|
||||
|
||||
public IEnumerable<CheckBoxItem<T>> SelectedItems => Items.Where(item => item.Checked);
|
||||
|
||||
public CheckBoxDialogModel(IEnumerable<CheckBoxItem<T>> items) {
|
||||
this.Items = new List<CheckBoxItem<T>>(items);
|
||||
base.Items = this.Items;
|
||||
}
|
||||
}
|
||||
}
|
24
app/Desktop/Dialogs/CheckBoxItem.cs
Normal file
24
app/Desktop/Dialogs/CheckBoxItem.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using DHT.Desktop.Models;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public class CheckBoxItem : BaseModel {
|
||||
public string Title { get; init; } = "";
|
||||
public object? Item { get; init; } = null;
|
||||
|
||||
private bool isChecked = false;
|
||||
|
||||
public bool Checked {
|
||||
get => isChecked;
|
||||
set => Change(ref isChecked, value);
|
||||
}
|
||||
}
|
||||
|
||||
public class CheckBoxItem<T> : CheckBoxItem {
|
||||
public new T Item { get; }
|
||||
|
||||
public CheckBoxItem(T item) {
|
||||
this.Item = item;
|
||||
base.Item = item;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,9 +1,15 @@
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public static class Dialog {
|
||||
public static async Task ShowOk(Window owner, string title, string message) {
|
||||
if (!Dispatcher.UIThread.CheckAccess()) {
|
||||
await Dispatcher.UIThread.InvokeAsync(() => ShowOk(owner, title, message));
|
||||
return;
|
||||
}
|
||||
|
||||
await new MessageDialog {
|
||||
DataContext = new MessageDialogModel {
|
||||
Title = title,
|
||||
@@ -14,6 +20,10 @@ namespace DHT.Desktop.Dialogs {
|
||||
}
|
||||
|
||||
public static async Task<DialogResult.OkCancel> ShowOkCancel(Window owner, string title, string message) {
|
||||
if (!Dispatcher.UIThread.CheckAccess()) {
|
||||
return await Dispatcher.UIThread.InvokeAsync(() => ShowOkCancel(owner, title, message));
|
||||
}
|
||||
|
||||
var result = await new MessageDialog {
|
||||
DataContext = new MessageDialogModel {
|
||||
Title = title,
|
||||
@@ -27,6 +37,10 @@ namespace DHT.Desktop.Dialogs {
|
||||
}
|
||||
|
||||
public static async Task<DialogResult.YesNo> ShowYesNo(Window owner, string title, string message) {
|
||||
if (!Dispatcher.UIThread.CheckAccess()) {
|
||||
return await Dispatcher.UIThread.InvokeAsync(() => ShowYesNo(owner, title, message));
|
||||
}
|
||||
|
||||
var result = await new MessageDialog {
|
||||
DataContext = new MessageDialogModel {
|
||||
Title = title,
|
||||
@@ -40,6 +54,10 @@ namespace DHT.Desktop.Dialogs {
|
||||
}
|
||||
|
||||
public static async Task<DialogResult.YesNoCancel> ShowYesNoCancel(Window owner, string title, string message) {
|
||||
if (!Dispatcher.UIThread.CheckAccess()) {
|
||||
return await Dispatcher.UIThread.InvokeAsync(() => ShowYesNoCancel(owner, title, message));
|
||||
}
|
||||
|
||||
var result = await new MessageDialog {
|
||||
DataContext = new MessageDialogModel {
|
||||
Title = title,
|
||||
|
@@ -3,46 +3,56 @@ using System;
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public static class DialogResult {
|
||||
public enum All {
|
||||
Ok, Yes, No, Cancel
|
||||
Ok,
|
||||
Yes,
|
||||
No,
|
||||
Cancel
|
||||
}
|
||||
|
||||
public enum OkCancel {
|
||||
Closed, Ok, Cancel
|
||||
Closed,
|
||||
Ok,
|
||||
Cancel
|
||||
}
|
||||
|
||||
public enum YesNo {
|
||||
Closed, Yes, No
|
||||
Closed,
|
||||
Yes,
|
||||
No
|
||||
}
|
||||
|
||||
public enum YesNoCancel {
|
||||
Closed, Yes, No, Cancel
|
||||
Closed,
|
||||
Yes,
|
||||
No,
|
||||
Cancel
|
||||
}
|
||||
|
||||
public static OkCancel ToOkCancel(this All? result) {
|
||||
return result switch {
|
||||
null => OkCancel.Closed,
|
||||
All.Ok => OkCancel.Ok,
|
||||
All.Cancel => OkCancel.Cancel,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to ok/cancel.")
|
||||
null => OkCancel.Closed,
|
||||
All.Ok => OkCancel.Ok,
|
||||
All.Cancel => OkCancel.Cancel,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to ok/cancel.")
|
||||
};
|
||||
}
|
||||
|
||||
public static YesNo ToYesNo(this All? result) {
|
||||
return result switch {
|
||||
null => YesNo.Closed,
|
||||
All.Yes => YesNo.Yes,
|
||||
All.No => YesNo.No,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to yes/no.")
|
||||
null => YesNo.Closed,
|
||||
All.Yes => YesNo.Yes,
|
||||
All.No => YesNo.No,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to yes/no.")
|
||||
};
|
||||
}
|
||||
|
||||
public static YesNoCancel ToYesNoCancel(this All? result) {
|
||||
return result switch {
|
||||
null => YesNoCancel.Closed,
|
||||
All.Yes => YesNoCancel.Yes,
|
||||
All.No => YesNoCancel.No,
|
||||
All.Cancel => YesNoCancel.Cancel,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to yes/no/cancel.")
|
||||
null => YesNoCancel.Closed,
|
||||
All.Yes => YesNoCancel.Yes,
|
||||
All.No => YesNoCancel.No,
|
||||
All.Cancel => YesNoCancel.Cancel,
|
||||
_ => throw new ArgumentException("Cannot convert dialog result " + result + " to yes/no/cancel.")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
7
app/Desktop/Dialogs/IProgressCallback.cs
Normal file
7
app/Desktop/Dialogs/IProgressCallback.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public interface IProgressCallback {
|
||||
Task Update(string message, int finishedItems, int totalItems);
|
||||
}
|
||||
}
|
@@ -6,7 +6,8 @@
|
||||
mc:Ignorable="d" d:DesignWidth="500"
|
||||
x:Class="DHT.Desktop.Dialogs.MessageDialog"
|
||||
Title="{Binding Title}"
|
||||
Width="500" SizeToContent="Height"
|
||||
Icon="avares://DiscordHistoryTracker/Resources/icon.ico"
|
||||
Width="500" SizeToContent="Height" CanResize="False"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<Window.DataContext>
|
||||
|
42
app/Desktop/Dialogs/ProgressDialog.axaml
Normal file
42
app/Desktop/Dialogs/ProgressDialog.axaml
Normal file
@@ -0,0 +1,42 @@
|
||||
<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:dialogs="clr-namespace:DHT.Desktop.Dialogs"
|
||||
mc:Ignorable="d" d:DesignWidth="500"
|
||||
x:Class="DHT.Desktop.Dialogs.ProgressDialog"
|
||||
Title="{Binding Title}"
|
||||
Icon="avares://DiscordHistoryTracker/Resources/icon.ico"
|
||||
Opened="Loaded"
|
||||
Closing="OnClosing"
|
||||
Width="500" SizeToContent="Height" CanResize="False"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<Window.DataContext>
|
||||
<dialogs:ProgressDialogModel />
|
||||
</Window.DataContext>
|
||||
|
||||
<Window.Styles>
|
||||
<Style Selector="TextBlock">
|
||||
<Setter Property="FontSize" Value="15" />
|
||||
<Setter Property="TextWrapping" Value="Wrap" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.items">
|
||||
<Setter Property="Margin" Value="10 0 0 0" />
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="TextWrapping" Value="NoWrap" />
|
||||
</Style>
|
||||
<Style Selector="ProgressBar">
|
||||
<Setter Property="Margin" Value="0 15 0 0" />
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<StackPanel Margin="20">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding Items}" Classes="items" />
|
||||
<TextBlock DockPanel.Dock="Left" Text="{Binding Message}" />
|
||||
</DockPanel>
|
||||
<ProgressBar Value="{Binding Progress}" />
|
||||
</StackPanel>
|
||||
|
||||
</Window>
|
38
app/Desktop/Dialogs/ProgressDialog.axaml.cs
Normal file
38
app/Desktop/Dialogs/ProgressDialog.axaml.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public class ProgressDialog : Window {
|
||||
private bool isFinished = false;
|
||||
|
||||
public ProgressDialog() {
|
||||
InitializeComponent();
|
||||
#if DEBUG
|
||||
this.AttachDevTools();
|
||||
#endif
|
||||
}
|
||||
|
||||
private void InitializeComponent() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public void OnClosing(object? sender, CancelEventArgs e) {
|
||||
e.Cancel = !isFinished;
|
||||
}
|
||||
|
||||
public void Loaded(object? sender, EventArgs e) {
|
||||
if (DataContext is ProgressDialogModel model) {
|
||||
Task.Run(model.StartTask).ContinueWith(OnFinished, TaskScheduler.FromCurrentSynchronizationContext());
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFinished(Task task) {
|
||||
isFinished = true;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
65
app/Desktop/Dialogs/ProgressDialogModel.cs
Normal file
65
app/Desktop/Dialogs/ProgressDialogModel.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Threading;
|
||||
using DHT.Desktop.Common;
|
||||
using DHT.Desktop.Models;
|
||||
|
||||
namespace DHT.Desktop.Dialogs {
|
||||
public class ProgressDialogModel : BaseModel {
|
||||
public string Title { get; init; } = "";
|
||||
|
||||
private string message = "";
|
||||
|
||||
public string Message {
|
||||
get => message;
|
||||
private set => Change(ref message, value);
|
||||
}
|
||||
|
||||
private string items = "";
|
||||
|
||||
public string Items {
|
||||
get => items;
|
||||
private set => Change(ref items, value);
|
||||
}
|
||||
|
||||
private int progress = 0;
|
||||
|
||||
public int Progress {
|
||||
get => progress;
|
||||
private set => Change(ref progress, value);
|
||||
}
|
||||
|
||||
private readonly TaskRunner? task;
|
||||
|
||||
[Obsolete("Designer")]
|
||||
public ProgressDialogModel() {}
|
||||
|
||||
public ProgressDialogModel(TaskRunner task) {
|
||||
this.task = task;
|
||||
}
|
||||
|
||||
internal async Task StartTask() {
|
||||
if (task != null) {
|
||||
await task(new Callback(this));
|
||||
}
|
||||
}
|
||||
|
||||
public delegate Task TaskRunner(IProgressCallback callback);
|
||||
|
||||
private class Callback : IProgressCallback {
|
||||
private readonly ProgressDialogModel model;
|
||||
|
||||
public Callback(ProgressDialogModel model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
async Task IProgressCallback.Update(string message, int finishedItems, int totalItems) {
|
||||
await Dispatcher.UIThread.InvokeAsync(() => {
|
||||
model.Message = message;
|
||||
model.Items = finishedItems.Format() + " / " + totalItems.Format();
|
||||
model.Progress = 100 * finishedItems / totalItems;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -16,4 +16,3 @@ namespace DHT.Desktop.Main {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
57
app/Desktop/Main/Controls/FilterPanel.axaml
Normal file
57
app/Desktop/Main/Controls/FilterPanel.axaml
Normal file
@@ -0,0 +1,57 @@
|
||||
<UserControl 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:controls="clr-namespace:DHT.Desktop.Main.Controls"
|
||||
mc:Ignorable="d"
|
||||
x:Class="DHT.Desktop.Main.Controls.FilterPanel">
|
||||
|
||||
<Design.DataContext>
|
||||
<controls:FilterPanelModel />
|
||||
</Design.DataContext>
|
||||
|
||||
<UserControl.Styles>
|
||||
<Style Selector="WrapPanel > StackPanel">
|
||||
<Setter Property="Margin" Value="0 20 40 0" />
|
||||
<Setter Property="Spacing" Value="4" />
|
||||
</Style>
|
||||
<Style Selector="Grid > Label">
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Grid > CalendarDatePicker">
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="IsTodayHighlighted" Value="True" />
|
||||
<Setter Property="SelectedDateFormat" Value="Short" />
|
||||
</Style>
|
||||
<Style Selector="Button">
|
||||
<Setter Property="Margin" Value="0 0 0 8" />
|
||||
</Style>
|
||||
</UserControl.Styles>
|
||||
|
||||
<WrapPanel>
|
||||
<StackPanel>
|
||||
<CheckBox IsChecked="{Binding FilterByDate}">Filter by Date</CheckBox>
|
||||
<Grid ColumnDefinitions="Auto, 4, 125" RowDefinitions="Auto, 4, Auto" Margin="4 0">
|
||||
<Label Grid.Row="0" Grid.Column="0">From:</Label>
|
||||
<CalendarDatePicker Grid.Row="0" Grid.Column="2" x:Name="StartDatePicker" IsEnabled="{Binding FilterByDate}" SelectedDateChanged="CalendarDatePicker_OnSelectedDateChanged" />
|
||||
<Label Grid.Row="2" Grid.Column="0">To:</Label>
|
||||
<CalendarDatePicker Grid.Row="2" Grid.Column="2" x:Name="EndDatePicker" IsEnabled="{Binding FilterByDate}" SelectedDateChanged="CalendarDatePicker_OnSelectedDateChanged" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<StackPanel>
|
||||
<CheckBox IsChecked="{Binding FilterByChannel}">Filter by Channel</CheckBox>
|
||||
<Button Command="{Binding OpenChannelFilterDialog}" IsEnabled="{Binding FilterByChannel}">Select Channels...</Button>
|
||||
<TextBlock Text="{Binding ChannelFilterLabel}" />
|
||||
</StackPanel>
|
||||
<StackPanel>
|
||||
<CheckBox IsChecked="{Binding FilterByUser}">Filter by User</CheckBox>
|
||||
<Button Command="{Binding OpenUserFilterDialog}" IsEnabled="{Binding FilterByUser}">Select Users...</Button>
|
||||
<TextBlock Text="{Binding UserFilterLabel}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
|
||||
</UserControl>
|
32
app/Desktop/Main/Controls/FilterPanel.axaml.cs
Normal file
32
app/Desktop/Main/Controls/FilterPanel.axaml.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace DHT.Desktop.Main.Controls {
|
||||
public class FilterPanel : UserControl {
|
||||
private CalendarDatePicker StartDatePicker => this.FindControl<CalendarDatePicker>("StartDatePicker");
|
||||
private CalendarDatePicker EndDatePicker => this.FindControl<CalendarDatePicker>("EndDatePicker");
|
||||
|
||||
public FilterPanel() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void InitializeComponent() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
|
||||
var culture = Program.Culture;
|
||||
foreach (var picker in new CalendarDatePicker[] { StartDatePicker, EndDatePicker }) {
|
||||
picker.FirstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
|
||||
picker.SelectedDateFormat = CalendarDatePickerFormat.Custom;
|
||||
picker.CustomDateFormatString = culture.DateTimeFormat.ShortDatePattern;
|
||||
picker.Watermark = culture.DateTimeFormat.ShortDatePattern;
|
||||
}
|
||||
}
|
||||
|
||||
public void CalendarDatePicker_OnSelectedDateChanged(object? sender, SelectionChangedEventArgs e) {
|
||||
if (DataContext is FilterPanelModel model) {
|
||||
model.StartDate = StartDatePicker.SelectedDate;
|
||||
model.EndDate = EndDatePicker.SelectedDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
236
app/Desktop/Main/Controls/FilterPanelModel.cs
Normal file
236
app/Desktop/Main/Controls/FilterPanelModel.cs
Normal file
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Common;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Desktop.Models;
|
||||
using DHT.Server.Data;
|
||||
using DHT.Server.Data.Filters;
|
||||
using DHT.Server.Database;
|
||||
|
||||
namespace DHT.Desktop.Main.Controls {
|
||||
public class FilterPanelModel : BaseModel {
|
||||
private static readonly HashSet<string> FilterProperties = new () {
|
||||
nameof(FilterByDate),
|
||||
nameof(StartDate),
|
||||
nameof(EndDate),
|
||||
nameof(FilterByChannel),
|
||||
nameof(IncludedChannels),
|
||||
nameof(FilterByUser),
|
||||
nameof(IncludedUsers)
|
||||
};
|
||||
|
||||
public event PropertyChangedEventHandler? FilterPropertyChanged;
|
||||
|
||||
public bool HasAnyFilters => FilterByDate || FilterByChannel || FilterByUser;
|
||||
|
||||
private bool filterByDate = false;
|
||||
private DateTime? startDate = null;
|
||||
private DateTime? endDate = null;
|
||||
private bool filterByChannel = false;
|
||||
private HashSet<ulong>? includedChannels = null;
|
||||
private bool filterByUser = false;
|
||||
private HashSet<ulong>? includedUsers = null;
|
||||
|
||||
public bool FilterByDate {
|
||||
get => filterByDate;
|
||||
set => Change(ref filterByDate, value);
|
||||
}
|
||||
|
||||
public DateTime? StartDate {
|
||||
get => startDate;
|
||||
set => Change(ref startDate, value);
|
||||
}
|
||||
|
||||
public DateTime? EndDate {
|
||||
get => endDate;
|
||||
set => Change(ref endDate, value);
|
||||
}
|
||||
|
||||
public bool FilterByChannel {
|
||||
get => filterByChannel;
|
||||
set => Change(ref filterByChannel, value);
|
||||
}
|
||||
|
||||
public HashSet<ulong> IncludedChannels {
|
||||
get => includedChannels ?? db.GetAllChannels().Select(channel => channel.Id).ToHashSet();
|
||||
set => Change(ref includedChannels, value);
|
||||
}
|
||||
|
||||
public bool FilterByUser {
|
||||
get => filterByUser;
|
||||
set => Change(ref filterByUser, value);
|
||||
}
|
||||
|
||||
public HashSet<ulong> IncludedUsers {
|
||||
get => includedUsers ?? db.GetAllUsers().Select(user => user.Id).ToHashSet();
|
||||
set => Change(ref includedUsers, value);
|
||||
}
|
||||
|
||||
private string channelFilterLabel = "";
|
||||
|
||||
public string ChannelFilterLabel {
|
||||
get => channelFilterLabel;
|
||||
set => Change(ref channelFilterLabel, value);
|
||||
}
|
||||
|
||||
private string userFilterLabel = "";
|
||||
|
||||
public string UserFilterLabel {
|
||||
get => userFilterLabel;
|
||||
set => Change(ref userFilterLabel, value);
|
||||
}
|
||||
|
||||
private readonly Window window;
|
||||
private readonly IDatabaseFile db;
|
||||
|
||||
[Obsolete("Designer")]
|
||||
public FilterPanelModel() : this(null!, DummyDatabaseFile.Instance) {}
|
||||
|
||||
public FilterPanelModel(Window window, IDatabaseFile db) {
|
||||
this.window = window;
|
||||
this.db = db;
|
||||
|
||||
UpdateChannelFilterLabel();
|
||||
UpdateUserFilterLabel();
|
||||
|
||||
PropertyChanged += OnPropertyChanged;
|
||||
db.Statistics.PropertyChanged += OnDbStatisticsChanged;
|
||||
}
|
||||
|
||||
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
if (e.PropertyName != null && FilterProperties.Contains(e.PropertyName)) {
|
||||
FilterPropertyChanged?.Invoke(sender, e);
|
||||
}
|
||||
|
||||
if (e.PropertyName is nameof(FilterByChannel) or nameof(IncludedChannels)) {
|
||||
UpdateChannelFilterLabel();
|
||||
}
|
||||
else if (e.PropertyName is nameof(FilterByUser) or nameof(IncludedUsers)) {
|
||||
UpdateUserFilterLabel();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDbStatisticsChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
if (e.PropertyName == nameof(DatabaseStatistics.TotalChannels)) {
|
||||
UpdateChannelFilterLabel();
|
||||
}
|
||||
else if (e.PropertyName == nameof(DatabaseStatistics.TotalUsers)) {
|
||||
UpdateUserFilterLabel();
|
||||
}
|
||||
}
|
||||
|
||||
public async void OpenChannelFilterDialog() {
|
||||
var servers = db.GetAllServers().ToDictionary(server => server.Id);
|
||||
var items = new List<CheckBoxItem<ulong>>();
|
||||
var included = IncludedChannels;
|
||||
|
||||
foreach (var channel in db.GetAllChannels()) {
|
||||
var channelId = channel.Id;
|
||||
var channelName = channel.Name;
|
||||
|
||||
string title;
|
||||
if (servers.TryGetValue(channel.Server, out var server)) {
|
||||
var titleBuilder = new StringBuilder();
|
||||
var serverType = server.Type;
|
||||
|
||||
titleBuilder.Append('[')
|
||||
.Append(ServerTypes.ToString(serverType))
|
||||
.Append("] ");
|
||||
|
||||
if (serverType == ServerType.DirectMessage) {
|
||||
titleBuilder.Append(channelName);
|
||||
}
|
||||
else {
|
||||
titleBuilder.Append(server.Name)
|
||||
.Append(" - ")
|
||||
.Append(channelName);
|
||||
}
|
||||
|
||||
title = titleBuilder.ToString();
|
||||
}
|
||||
else {
|
||||
title = channelName;
|
||||
}
|
||||
|
||||
items.Add(new CheckBoxItem<ulong>(channelId) {
|
||||
Title = title,
|
||||
Checked = included.Contains(channelId)
|
||||
});
|
||||
}
|
||||
|
||||
var result = await OpenIdFilterDialog(window, "Included Channels", items);
|
||||
if (result != null) {
|
||||
IncludedChannels = result;
|
||||
}
|
||||
}
|
||||
|
||||
public async void OpenUserFilterDialog() {
|
||||
var items = new List<CheckBoxItem<ulong>>();
|
||||
var included = IncludedUsers;
|
||||
|
||||
foreach (var user in db.GetAllUsers()) {
|
||||
var name = user.Name;
|
||||
var discriminator = user.Discriminator;
|
||||
|
||||
items.Add(new CheckBoxItem<ulong>(user.Id) {
|
||||
Title = discriminator == null ? name : name + " #" + discriminator,
|
||||
Checked = included.Contains(user.Id)
|
||||
});
|
||||
}
|
||||
|
||||
var result = await OpenIdFilterDialog(window, "Included Users", items);
|
||||
if (result != null) {
|
||||
IncludedUsers = result;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateChannelFilterLabel() {
|
||||
long total = db.Statistics.TotalChannels;
|
||||
long included = FilterByChannel ? IncludedChannels.Count : total;
|
||||
ChannelFilterLabel = "Selected " + included.Format() + " / " + total.Pluralize("channel") + ".";
|
||||
}
|
||||
|
||||
private void UpdateUserFilterLabel() {
|
||||
long total = db.Statistics.TotalUsers;
|
||||
long included = FilterByUser ? IncludedUsers.Count : total;
|
||||
UserFilterLabel = "Selected " + included.Format() + " / " + total.Pluralize("user") + ".";
|
||||
}
|
||||
|
||||
public MessageFilter CreateFilter() {
|
||||
MessageFilter filter = new();
|
||||
|
||||
if (FilterByDate) {
|
||||
filter.StartDate = StartDate;
|
||||
filter.EndDate = EndDate;
|
||||
}
|
||||
|
||||
if (FilterByChannel) {
|
||||
filter.ChannelIds = new HashSet<ulong>(IncludedChannels);
|
||||
}
|
||||
|
||||
if (FilterByUser) {
|
||||
filter.UserIds = new HashSet<ulong>(IncludedUsers);
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static async Task<HashSet<ulong>?> OpenIdFilterDialog(Window window, string title, List<CheckBoxItem<ulong>> items) {
|
||||
items.Sort((item1, item2) => item1.Title.CompareTo(item2.Title));
|
||||
|
||||
var model = new CheckBoxDialogModel<ulong>(items) {
|
||||
Title = title
|
||||
};
|
||||
|
||||
var dialog = new CheckBoxDialog { DataContext = model };
|
||||
var result = await dialog.ShowDialog<DialogResult.OkCancel>(window);
|
||||
|
||||
return result == DialogResult.OkCancel.Ok ? model.SelectedItems.Select(item => item.Item).ToHashSet() : null;
|
||||
}
|
||||
}
|
||||
}
|
@@ -41,17 +41,17 @@
|
||||
<Rectangle />
|
||||
<StackPanel Orientation="Vertical">
|
||||
<TextBlock Classes="label">Servers</TextBlock>
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalServers, StringFormat={}{0:n0}}" />
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalServers, Converter={StaticResource NumberValueConverter}}" />
|
||||
</StackPanel>
|
||||
<Rectangle />
|
||||
<StackPanel Orientation="Vertical">
|
||||
<TextBlock Classes="label">Channels</TextBlock>
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalChannels, StringFormat={}{0:n0}}" />
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalChannels, Converter={StaticResource NumberValueConverter}}" />
|
||||
</StackPanel>
|
||||
<Rectangle />
|
||||
<StackPanel Orientation="Vertical">
|
||||
<TextBlock Classes="label">Messages</TextBlock>
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalMessages, StringFormat={}{0:n0}}" />
|
||||
<TextBlock Classes="value" Text="{Binding DatabaseStatistics.TotalMessages, Converter={StaticResource NumberValueConverter}}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
|
@@ -19,11 +19,11 @@ namespace DHT.Desktop.Main.Controls {
|
||||
public string StatusText {
|
||||
get {
|
||||
return CurrentStatus switch {
|
||||
Status.Starting => "STARTING",
|
||||
Status.Ready => "READY",
|
||||
Status.Stopping => "STOPPING",
|
||||
Status.Stopped => "STOPPED",
|
||||
_ => ""
|
||||
Status.Starting => "STARTING",
|
||||
Status.Ready => "READY",
|
||||
Status.Stopping => "STOPPING",
|
||||
Status.Stopped => "STOPPED",
|
||||
_ => ""
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@@ -12,7 +12,7 @@
|
||||
</Design.DataContext>
|
||||
|
||||
<UserControl.Styles>
|
||||
<Style Selector="TabControl WrapPanel">
|
||||
<Style Selector="TabControl ItemsPresenter > WrapPanel">
|
||||
<Setter Property="Background" Value="#546A9F" />
|
||||
</Style>
|
||||
<Style Selector="TabItem">
|
||||
|
@@ -7,7 +7,7 @@
|
||||
x:Class="DHT.Desktop.Main.MainWindow"
|
||||
Title="Discord History Tracker"
|
||||
Icon="avares://DiscordHistoryTracker/Resources/icon.ico"
|
||||
Width="800" Height="450"
|
||||
Width="800" Height="500"
|
||||
MinWidth="480" MinHeight="240"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
|
||||
|
@@ -10,12 +10,21 @@
|
||||
<pages:DatabasePageModel />
|
||||
</Design.DataContext>
|
||||
|
||||
<UserControl.Styles>
|
||||
<Style Selector="WrapPanel > Button">
|
||||
<Setter Property="Margin" Value="0 0 10 10" />
|
||||
</Style>
|
||||
</UserControl.Styles>
|
||||
|
||||
<StackPanel Spacing="10">
|
||||
<DockPanel>
|
||||
<Button Command="{Binding CloseDatabase}" DockPanel.Dock="Right">Close Database</Button>
|
||||
<TextBox Text="{Binding Db.Path}" Width="NaN" Margin="0 0 10 0" IsEnabled="True" />
|
||||
</DockPanel>
|
||||
<Button Command="{Binding OpenDatabaseFolder}">Open Database Folder</Button>
|
||||
<WrapPanel>
|
||||
<Button Command="{Binding OpenDatabaseFolder}">Open Database Folder</Button>
|
||||
<Button Command="{Binding MergeWithDatabase}">Merge with Database(s)...</Button>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
|
||||
</UserControl>
|
||||
|
@@ -1,10 +1,14 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Common;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Desktop.Models;
|
||||
using DHT.Server.Database;
|
||||
using DHT.Server.Logging;
|
||||
using DHT.Server.Service;
|
||||
|
||||
namespace DHT.Desktop.Main.Pages {
|
||||
@@ -50,9 +54,101 @@ namespace DHT.Desktop.Main.Pages {
|
||||
}
|
||||
}
|
||||
|
||||
public async void MergeWithDatabase() {
|
||||
var fileDialog = DatabaseGui.NewOpenDatabaseFileDialog();
|
||||
fileDialog.Directory = Path.GetDirectoryName(Db.Path);
|
||||
fileDialog.AllowMultiple = true;
|
||||
|
||||
string[]? paths = await fileDialog.ShowAsync(window);
|
||||
if (paths == null || paths.Length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
ProgressDialog progressDialog = new ProgressDialog();
|
||||
progressDialog.DataContext = new ProgressDialogModel(async callback => await MergeWithDatabaseFromPaths(Db, paths, progressDialog, callback)) {
|
||||
Title = "Database Merge"
|
||||
};
|
||||
|
||||
await progressDialog.ShowDialog(window);
|
||||
}
|
||||
|
||||
public void CloseDatabase() {
|
||||
ServerLauncher.Stop();
|
||||
DatabaseClosed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private static async Task MergeWithDatabaseFromPaths(IDatabaseFile target, string[] paths, ProgressDialog dialog, IProgressCallback callback) {
|
||||
int total = paths.Length;
|
||||
|
||||
DialogResult.YesNo? upgradeResult = null;
|
||||
|
||||
async Task<bool> CheckCanUpgradeDatabase() {
|
||||
upgradeResult ??= total > 1
|
||||
? await DatabaseGui.ShowCanUpgradeMultipleDatabaseDialog(dialog)
|
||||
: await DatabaseGui.ShowCanUpgradeDatabaseDialog(dialog);
|
||||
|
||||
return DialogResult.YesNo.Yes == upgradeResult;
|
||||
}
|
||||
|
||||
var oldStatistics = target.Statistics.Clone();
|
||||
int successful = 0;
|
||||
int finished = 0;
|
||||
|
||||
foreach (string path in paths) {
|
||||
await callback.Update(Path.GetFileName(path), finished, total);
|
||||
++finished;
|
||||
|
||||
if (!File.Exists(path)) {
|
||||
await Dialog.ShowOk(dialog, "Database Error", "Database '" + Path.GetFileName(path) + "' no longer exists.");
|
||||
continue;
|
||||
}
|
||||
|
||||
IDatabaseFile? db = await DatabaseGui.TryOpenOrCreateDatabaseFromPath(path, dialog, CheckCanUpgradeDatabase);
|
||||
if (db == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
target.AddFrom(db);
|
||||
} catch (Exception ex) {
|
||||
Log.Error(ex);
|
||||
await Dialog.ShowOk(dialog, "Database Error", "Database '" + Path.GetFileName(path) + "' could not be merged: " + ex.Message);
|
||||
continue;
|
||||
} finally {
|
||||
db.Dispose();
|
||||
}
|
||||
|
||||
++successful;
|
||||
}
|
||||
|
||||
await callback.Update("Done", finished, total);
|
||||
|
||||
if (successful == 0) {
|
||||
await Dialog.ShowOk(dialog, "Database Merge", "Nothing was merged.");
|
||||
return;
|
||||
}
|
||||
|
||||
var newStatistics = target.Statistics;
|
||||
long newServers = newStatistics.TotalServers - oldStatistics.TotalServers;
|
||||
long newChannels = newStatistics.TotalChannels - oldStatistics.TotalChannels;
|
||||
long newMessages = newStatistics.TotalMessages - oldStatistics.TotalMessages;
|
||||
|
||||
StringBuilder message = new StringBuilder();
|
||||
message.Append("Processed ");
|
||||
|
||||
if (successful == total) {
|
||||
message.Append(successful.Pluralize("database file"));
|
||||
}
|
||||
else {
|
||||
message.Append(successful.Format()).Append(" out of ").Append(total.Pluralize("database file"));
|
||||
}
|
||||
|
||||
message.Append(" and added:\n\n \u2022 ");
|
||||
message.Append(newServers.Pluralize("server")).Append("\n \u2022 ");
|
||||
message.Append(newChannels.Pluralize("channel")).Append("\n \u2022 ");
|
||||
message.Append(newMessages.Pluralize("message"));
|
||||
|
||||
await Dialog.ShowOk(dialog, "Database Merge", message.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -15,6 +15,10 @@
|
||||
<Setter Property="FontFamily" Value="Consolas,Courier" />
|
||||
<Setter Property="FontSize" Value="15" />
|
||||
</Style>
|
||||
<Style Selector="WrapPanel > StackPanel">
|
||||
<Setter Property="Orientation" Value="Vertical" />
|
||||
<Setter Property="Margin" Value="0 0 10 10" />
|
||||
</Style>
|
||||
</UserControl.Styles>
|
||||
|
||||
<StackPanel Spacing="10">
|
||||
@@ -26,23 +30,25 @@
|
||||
<Button Command="{Binding OnClickToggleButton}" Content="{Binding ToggleButtonText}" IsEnabled="{Binding IsToggleButtonEnabled}" />
|
||||
</StackPanel>
|
||||
<Expander Header="Advanced Settings">
|
||||
<StackPanel Spacing="10" Margin="0 10 0 0">
|
||||
<StackPanel Spacing="10">
|
||||
<TextBlock TextWrapping="Wrap">
|
||||
The following settings determine how the tracking script communicates with this application. If you change them, you will have to copy and apply the tracking script again.
|
||||
</TextBlock>
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<StackPanel Orientation="Vertical">
|
||||
<WrapPanel>
|
||||
<StackPanel>
|
||||
<Label Target="Port">Port</Label>
|
||||
<TextBox x:Name="Port" Width="70" Text="{Binding InputPort}" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Vertical">
|
||||
<StackPanel>
|
||||
<Label Target="Token">Token</Label>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBox x:Name="Token" Width="200" Text="{Binding InputToken}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<Button Command="{Binding OnClickRandomizeToken}" VerticalAlignment="Bottom">Randomize Token</Button>
|
||||
</StackPanel>
|
||||
<StackPanel VerticalAlignment="Bottom">
|
||||
<Button Command="{Binding OnClickRandomizeToken}">Randomize Token</Button>
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Button IsEnabled="{Binding HasMadeChanges}" Command="{Binding OnClickApplyChanges}">Apply & Restart</Button>
|
||||
<Button IsEnabled="{Binding HasMadeChanges}" Command="{Binding OnClickCancelChanges}">Cancel</Button>
|
||||
|
@@ -3,7 +3,6 @@ using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Desktop.Main.Controls;
|
||||
using DHT.Desktop.Models;
|
||||
@@ -140,11 +139,9 @@ namespace DHT.Desktop.Main.Pages {
|
||||
IsToggleButtonEnabled = true;
|
||||
}
|
||||
|
||||
private void ServerLauncherOnServerManagementExceptionCaught(object? sender, Exception ex) {
|
||||
private async void ServerLauncherOnServerManagementExceptionCaught(object? sender, Exception ex) {
|
||||
Log.Error(ex);
|
||||
|
||||
string message = ex.Message;
|
||||
Dispatcher.UIThread.Post(async () => { await Dialog.ShowOk(window, "Server Error", message); });
|
||||
await Dialog.ShowOk(window, "Server Error", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:pages="clr-namespace:DHT.Desktop.Main.Pages"
|
||||
xmlns:controls="clr-namespace:DHT.Desktop.Main.Controls"
|
||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||
x:Class="DHT.Desktop.Main.Pages.ViewerPage">
|
||||
|
||||
@@ -11,34 +12,27 @@
|
||||
</Design.DataContext>
|
||||
|
||||
<UserControl.Styles>
|
||||
<Style Selector="Grid > Label">
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Grid > CalendarDatePicker">
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="IsTodayHighlighted" Value="True" />
|
||||
<Setter Property="SelectedDateFormat" Value="Short" />
|
||||
<Style Selector="Expander">
|
||||
<Setter Property="Margin" Value="0 25 0 0" />
|
||||
</Style>
|
||||
</UserControl.Styles>
|
||||
|
||||
<StackPanel Orientation="Vertical" Spacing="20">
|
||||
<StackPanel Orientation="Vertical">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
|
||||
<Button Command="{Binding OnClickOpenViewer}" Margin="0 0 5 0">Open Viewer</Button>
|
||||
<Button Command="{Binding OnClickSaveViewer}" Margin="5 0 0 0">Save Viewer</Button>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding ExportedMessageText}" />
|
||||
<StackPanel>
|
||||
<CheckBox IsChecked="{Binding FilterByDate}">Filter by Date</CheckBox>
|
||||
<Grid ColumnDefinitions="Auto, 4, 140" RowDefinitions="Auto, 4, Auto" Margin="4">
|
||||
<Label Grid.Row="0" Grid.Column="0">From:</Label>
|
||||
<CalendarDatePicker Grid.Row="0" Grid.Column="2" x:Name="StartDatePicker" IsEnabled="{Binding FilterByDate}" SelectedDateChanged="CalendarDatePicker_OnSelectedDateChanged" />
|
||||
<Label Grid.Row="2" Grid.Column="0">To:</Label>
|
||||
<CalendarDatePicker Grid.Row="2" Grid.Column="2" x:Name="EndDatePicker" IsEnabled="{Binding FilterByDate}" SelectedDateChanged="CalendarDatePicker_OnSelectedDateChanged" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding ExportedMessageText}" Margin="0 20 0 0" />
|
||||
<controls:FilterPanel DataContext="{Binding FilterModel}" />
|
||||
<Expander Header="Database Tools">
|
||||
<StackPanel Orientation="Vertical" Spacing="10">
|
||||
<StackPanel Orientation="Vertical" Spacing="4">
|
||||
<RadioButton GroupName="DatabaseToolFilterMode" IsEnabled="{Binding HasFilters}" IsChecked="{Binding DatabaseToolFilterModeKeep}">Keep Only Messages Matching Filters</RadioButton>
|
||||
<RadioButton GroupName="DatabaseToolFilterMode" IsEnabled="{Binding HasFilters}" IsChecked="{Binding DatabaseToolFilterModeRemove}">Remove Messages Matching Filters</RadioButton>
|
||||
</StackPanel>
|
||||
<Button IsEnabled="{Binding HasFilters}" Command="{Binding OnClickApplyFiltersToDatabase}">Apply Filters to Database</Button>
|
||||
</StackPanel>
|
||||
</Expander>
|
||||
</StackPanel>
|
||||
|
||||
</UserControl>
|
||||
|
@@ -10,12 +10,5 @@ namespace DHT.Desktop.Main.Pages {
|
||||
private void InitializeComponent() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public void CalendarDatePicker_OnSelectedDateChanged(object? sender, SelectionChangedEventArgs e) {
|
||||
if (DataContext is ViewerPageModel model) {
|
||||
model.StartDate = this.FindControl<CalendarDatePicker>("StartDatePicker").SelectedDate;
|
||||
model.EndDate = this.FindControl<CalendarDatePicker>("EndDatePicker").SelectedDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -6,6 +6,9 @@ using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Common;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Desktop.Main.Controls;
|
||||
using DHT.Desktop.Models;
|
||||
using DHT.Desktop.Resources;
|
||||
using DHT.Server.Data.Filters;
|
||||
@@ -16,26 +19,17 @@ namespace DHT.Desktop.Main.Pages {
|
||||
public class ViewerPageModel : BaseModel {
|
||||
public string ExportedMessageText { get; private set; } = "";
|
||||
|
||||
private bool filterByDate = false;
|
||||
public bool DatabaseToolFilterModeKeep { get; set; } = true;
|
||||
public bool DatabaseToolFilterModeRemove { get; set; } = false;
|
||||
|
||||
public bool FilterByDate {
|
||||
get => filterByDate;
|
||||
set => Change(ref filterByDate, value);
|
||||
private bool hasFilters = false;
|
||||
|
||||
public bool HasFilters {
|
||||
get => hasFilters;
|
||||
set => Change(ref hasFilters, value);
|
||||
}
|
||||
|
||||
private DateTime? startDate = null;
|
||||
|
||||
public DateTime? StartDate {
|
||||
get => startDate;
|
||||
set => Change(ref startDate, value);
|
||||
}
|
||||
|
||||
private DateTime? endDate = null;
|
||||
|
||||
public DateTime? EndDate {
|
||||
get => endDate;
|
||||
set => Change(ref endDate, value);
|
||||
}
|
||||
private FilterPanelModel FilterModel { get; }
|
||||
|
||||
private readonly Window window;
|
||||
private readonly IDatabaseFile db;
|
||||
@@ -47,15 +41,15 @@ namespace DHT.Desktop.Main.Pages {
|
||||
this.window = window;
|
||||
this.db = db;
|
||||
|
||||
this.PropertyChanged += OnPropertyChanged;
|
||||
this.FilterModel = new FilterPanelModel(window, db);
|
||||
this.FilterModel.FilterPropertyChanged += OnFilterPropertyChanged;
|
||||
this.db.Statistics.PropertyChanged += OnDbStatisticsChanged;
|
||||
UpdateStatistics();
|
||||
}
|
||||
|
||||
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
if (e.PropertyName is nameof(FilterByDate) or nameof(StartDate) or nameof(EndDate)) {
|
||||
UpdateStatistics();
|
||||
}
|
||||
private void OnFilterPropertyChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
UpdateStatistics();
|
||||
HasFilters = FilterModel.HasAnyFilters;
|
||||
}
|
||||
|
||||
private void OnDbStatisticsChanged(object? sender, PropertyChangedEventArgs e) {
|
||||
@@ -64,24 +58,13 @@ namespace DHT.Desktop.Main.Pages {
|
||||
}
|
||||
}
|
||||
|
||||
private MessageFilter CreateFilter() {
|
||||
MessageFilter filter = new();
|
||||
|
||||
if (FilterByDate) {
|
||||
filter.StartDate = StartDate;
|
||||
filter.EndDate = EndDate;
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
private void UpdateStatistics() {
|
||||
ExportedMessageText = "Will export " + db.CountMessages(CreateFilter()) + " out of " + db.Statistics.TotalMessages + " message(s).";
|
||||
ExportedMessageText = "Will export " + db.CountMessages(FilterModel.CreateFilter()).Format() + " out of " + db.Statistics.TotalMessages.Format() + " message(s).";
|
||||
OnPropertyChanged(nameof(ExportedMessageText));
|
||||
}
|
||||
|
||||
private async Task<string> GenerateViewerContents() {
|
||||
string json = ViewerJsonExport.Generate(db, CreateFilter());
|
||||
string json = ViewerJsonExport.Generate(db, FilterModel.CreateFilter());
|
||||
|
||||
string index = await ResourceLoader.ReadTextAsync("Viewer/index.html");
|
||||
string viewer = index.Replace("/*[JS]*/", await ResourceLoader.ReadJoinedAsync("Viewer/scripts/", '\n'))
|
||||
@@ -97,7 +80,8 @@ namespace DHT.Desktop.Main.Pages {
|
||||
int counter = 0;
|
||||
|
||||
while (File.Exists(fullPath)) {
|
||||
fullPath = Path.Combine(rootPath, filenameBase + "-" + (++counter) + ".html");
|
||||
++counter;
|
||||
fullPath = Path.Combine(rootPath, filenameBase + "-" + counter + ".html");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(rootPath);
|
||||
@@ -119,10 +103,25 @@ namespace DHT.Desktop.Main.Pages {
|
||||
}
|
||||
}.ShowAsync(window);
|
||||
|
||||
string path = await dialog;
|
||||
string? path = await dialog;
|
||||
if (!string.IsNullOrEmpty(path)) {
|
||||
await File.WriteAllTextAsync(path, await GenerateViewerContents());
|
||||
}
|
||||
}
|
||||
|
||||
public async void OnClickApplyFiltersToDatabase() {
|
||||
var filter = FilterModel.CreateFilter();
|
||||
|
||||
if (DatabaseToolFilterModeKeep) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Keep Matching Messages in This Database", db.CountMessages(filter).Pluralize("message") + " will be kept, and the rest will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
db.RemoveMessages(filter, MessageFilterRemovalMode.KeepMatching);
|
||||
}
|
||||
}
|
||||
else if (DatabaseToolFilterModeRemove) {
|
||||
if (DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Remove Matching Messages in This Database", db.CountMessages(filter).Pluralize("message") + " will be removed from this database. This action cannot be undone. Proceed?")) {
|
||||
db.RemoveMessages(filter, MessageFilterRemovalMode.RemoveMatching);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -28,7 +28,7 @@
|
||||
|
||||
<Panel Name="RootPanel">
|
||||
<StackPanel Margin="42">
|
||||
<TextBlock Text="{Binding Version, StringFormat=Discord History Tracker v.{0}}" FontSize="25" Margin="0 0 0 30" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="{Binding Version, StringFormat=Discord History Tracker v{0}}" FontSize="25" Margin="0 0 0 30" HorizontalAlignment="Center" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
|
||||
<Button Command="{Binding OpenOrCreateDatabase}">Open or Create Database</Button>
|
||||
|
@@ -1,14 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using DHT.Desktop.Common;
|
||||
using DHT.Desktop.Dialogs;
|
||||
using DHT.Desktop.Models;
|
||||
using DHT.Server.Database;
|
||||
using DHT.Server.Database.Exceptions;
|
||||
using DHT.Server.Database.Sqlite;
|
||||
using DHT.Server.Logging;
|
||||
|
||||
namespace DHT.Desktop.Main {
|
||||
public class WelcomeScreenModel : BaseModel {
|
||||
@@ -29,19 +26,10 @@ namespace DHT.Desktop.Main {
|
||||
}
|
||||
|
||||
public async void OpenOrCreateDatabase() {
|
||||
var dialog = new SaveFileDialog {
|
||||
Title = "Open or Create Database File",
|
||||
InitialFileName = "archive.dht",
|
||||
Directory = Path.GetDirectoryName(dbFilePath),
|
||||
Filters = new List<FileDialogFilter> {
|
||||
new() {
|
||||
Name = "Discord History Tracker Database",
|
||||
Extensions = { "dht" }
|
||||
}
|
||||
}
|
||||
}.ShowAsync(window);
|
||||
var dialog = DatabaseGui.NewOpenOrCreateDatabaseFileDialog();
|
||||
dialog.Directory = Path.GetDirectoryName(dbFilePath);
|
||||
|
||||
string path = await dialog;
|
||||
string? path = await dialog.ShowAsync(window);
|
||||
if (!string.IsNullOrWhiteSpace(path)) {
|
||||
await OpenOrCreateDatabaseFromPath(path);
|
||||
}
|
||||
@@ -53,24 +41,14 @@ namespace DHT.Desktop.Main {
|
||||
}
|
||||
|
||||
dbFilePath = path;
|
||||
|
||||
try {
|
||||
Db = await SqliteDatabaseFile.OpenOrCreate(path, CheckCanUpgradeDatabase);
|
||||
} catch (InvalidDatabaseVersionException ex) {
|
||||
await Dialog.ShowOk(window, "Database Error", "This database appears to be corrupted (invalid version: " + ex.Version + ").");
|
||||
} catch (DatabaseTooNewException ex) {
|
||||
await Dialog.ShowOk(window, "Database Error", "This database was opened in a newer version of DHT (database version " + ex.DatabaseVersion + ", app version " + ex.CurrentVersion + ").");
|
||||
} catch (Exception ex) {
|
||||
Log.Error(ex);
|
||||
await Dialog.ShowOk(window, "Database Error", ex.Message);
|
||||
}
|
||||
Db = await DatabaseGui.TryOpenOrCreateDatabaseFromPath(path, window, CheckCanUpgradeDatabase);
|
||||
|
||||
OnPropertyChanged(nameof(Db));
|
||||
OnPropertyChanged(nameof(HasDatabase));
|
||||
}
|
||||
|
||||
private async Task<bool> CheckCanUpgradeDatabase() {
|
||||
return DialogResult.YesNo.Yes == await Dialog.ShowYesNo(window, "Database Upgrade", "This database was created with an older version of DHT. If you proceed, the database will be upgraded and will no longer open in previous versions of DHT. Do you want to proceed?");
|
||||
return DialogResult.YesNo.Yes == await DatabaseGui.ShowCanUpgradeDatabaseDialog(window);
|
||||
}
|
||||
|
||||
public void CloseDatabase() {
|
||||
@@ -81,7 +59,7 @@ namespace DHT.Desktop.Main {
|
||||
}
|
||||
|
||||
public async void ShowAboutDialog() {
|
||||
await new AboutWindow() { DataContext = new AboutWindowModel() }.ShowDialog(this.window);
|
||||
await new AboutWindow { DataContext = new AboutWindowModel() }.ShowDialog(this.window);
|
||||
}
|
||||
|
||||
public void Exit() {
|
||||
|
@@ -5,6 +5,7 @@ using Avalonia;
|
||||
namespace DHT.Desktop {
|
||||
internal static class Program {
|
||||
public static string Version { get; }
|
||||
public static CultureInfo Culture { get; }
|
||||
|
||||
static Program() {
|
||||
Version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "";
|
||||
@@ -12,6 +13,7 @@ namespace DHT.Desktop {
|
||||
Version = Version[..^2];
|
||||
}
|
||||
|
||||
Culture = CultureInfo.CurrentCulture;
|
||||
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
|
||||
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
|
||||
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
|
||||
|
9
app/Resources/Tracker/bootstrap.js
vendored
9
app/Resources/Tracker/bootstrap.js
vendored
@@ -97,7 +97,7 @@
|
||||
const info = DISCORD.getSelectedChannel();
|
||||
|
||||
if (!info) {
|
||||
GUI.setStatus("Stopped");
|
||||
GUI.setStatus("Error (Unknown Channel)");
|
||||
stopTrackingDelayed();
|
||||
return;
|
||||
}
|
||||
@@ -130,14 +130,9 @@
|
||||
|
||||
STATE.onTrackingStateChanged(enabled => {
|
||||
if (enabled) {
|
||||
if (DISCORD.getSelectedChannel() == null) {
|
||||
stopTrackingDelayed(() => alert("The selected channel is not visible in the channel list."));
|
||||
return;
|
||||
}
|
||||
|
||||
const messages = DISCORD.getMessages();
|
||||
|
||||
if (messages == null) {
|
||||
if (messages.length === 0) {
|
||||
stopTrackingDelayed(() => alert("Cannot see any messages."));
|
||||
return;
|
||||
}
|
||||
|
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
||||
const STATE=function(){let serverPort=-1;let serverToken="";const post=function(endpoint,json){const aborter=new AbortController;const timeout=window.setTimeout(()=>aborter.abort(),5e3);return new Promise(async(resolve,reject)=>{let r;try{r=await fetch("http://127.0.0.1:"+serverPort+endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-DHT-Token":serverToken},credentials:"omit",redirect:"error",body:JSON.stringify(json),signal:aborter.signal})}catch(e){if(e.name==="AbortError"){reject({status:"DISCONNECTED"});return}else{reject({status:"ERROR",message:e.message});return}}finally{window.clearTimeout(timeout)}if(r.status===200){resolve(r);return}try{const message=await r.text();reject({status:"ERROR",message:message})}catch(e){reject({status:"ERROR",message:e.message})}})};const trackingStateChangedListeners=[];let isTracking=false;const addedChannels=new Set;const addedUsers=new Set;return{setup(port,token){serverPort=port;serverToken=token},onTrackingStateChanged(callback){trackingStateChangedListeners.push(callback);callback(isTracking)},isTracking(){return isTracking},setIsTracking(state){if(isTracking!==state){isTracking=state;if(isTracking){addedChannels.clear();addedUsers.clear()}for(const callback of trackingStateChangedListeners){callback(isTracking)}}},async addDiscordChannel(serverInfo,channelInfo){if(addedChannels.has(channelInfo.id)){return}const server={id:serverInfo.id,name:serverInfo.name,type:serverInfo.type};const channel={id:channelInfo.id,name:channelInfo.name};if("extra"in channelInfo){channel.position=channelInfo.extra.position;channel.topic=channelInfo.extra.topic;channel.nsfw=channelInfo.extra.nsfw}await post("/track-channel",{server:server,channel:channel});addedChannels.add(channelInfo.id)},async addDiscordMessages(channelId,discordMessageArray){const userInfo={};let hasNewUsers=false;for(const msg of discordMessageArray){const user=msg.author;if(!addedUsers.has(user.id)){const obj={id:user.id,name:user.username};if(user.avatar){obj.avatar=user.avatar}if(!user.bot){obj.discriminator=user.discriminator}userInfo[user.id]=obj;hasNewUsers=true}}if(hasNewUsers){await post("/track-users",Object.values(userInfo));for(const id of Object.keys(userInfo)){addedUsers.add(id)}}const response=await post("/track-messages",discordMessageArray.map(msg=>{const obj={id:msg.id,sender:msg.author.id,channel:msg.channel_id,text:msg.content,timestamp:msg.timestamp.toDate().getTime()};if(msg.editedTimestamp!==null){obj.editTimestamp=msg.editedTimestamp.toDate().getTime()}if(msg.messageReference!==null){obj.repliedToId=msg.messageReference.message_id}if(msg.attachments.length>0){obj.attachments=msg.attachments.map(attachment=>{const mapped={id:attachment.id,name:attachment.filename,size:attachment.size,url:attachment.url};if(attachment.content_type){mapped.type=attachment.content_type}return mapped})}if(msg.embeds.length>0){obj.embeds=msg.embeds.map(embed=>{const mapped={};for(const key of Object.keys(embed)){if(key==="id"){continue}if(key==="rawTitle"){mapped["title"]=embed[key]}else if(key==="rawDescription"){mapped["description"]=embed[key]}else{mapped[key]=embed[key]}}return JSON.stringify(mapped)})}if(msg.reactions.length>0){obj.reactions=msg.reactions.map(reaction=>{const emoji=reaction.emoji;const mapped={count:reaction.count};if(emoji.id){mapped.id=emoji.id}if(emoji.name){mapped.name=emoji.name}if(emoji.animated){mapped.isAnimated=emoji.animated}return mapped})}return obj}));const anyNewMessages=await response.text();return anyNewMessages==="1"}}}();
|
||||
const STATE=function(){let serverPort=-1;let serverToken="";const post=function(endpoint,json){const aborter=new AbortController;const timeout=window.setTimeout(()=>aborter.abort(),5e3);return new Promise(async(resolve,reject)=>{let r;try{r=await fetch("http://127.0.0.1:"+serverPort+endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-DHT-Token":serverToken},credentials:"omit",redirect:"error",body:JSON.stringify(json),signal:aborter.signal})}catch(e){if(e.name==="AbortError"){reject({status:"DISCONNECTED"});return}else{reject({status:"ERROR",message:e.message});return}}finally{window.clearTimeout(timeout)}if(r.status===200){resolve(r);return}try{const message=await r.text();reject({status:"ERROR",message:message})}catch(e){reject({status:"ERROR",message:e.message})}})};const trackingStateChangedListeners=[];let isTracking=false;const addedChannels=new Set;const addedUsers=new Set;return{setup(port,token){serverPort=port;serverToken=token},onTrackingStateChanged(callback){trackingStateChangedListeners.push(callback);callback(isTracking)},isTracking(){return isTracking},setIsTracking(state){if(isTracking!==state){isTracking=state;if(isTracking){addedChannels.clear();addedUsers.clear()}for(const callback of trackingStateChangedListeners){callback(isTracking)}}},async addDiscordChannel(serverInfo,channelInfo){if(addedChannels.has(channelInfo.id)){return}const server={id:serverInfo.id,name:serverInfo.name,type:serverInfo.type};const channel={id:channelInfo.id,name:channelInfo.name};if("extra"in channelInfo){const extra=channelInfo.extra;if("parent"in extra){channel.parent=extra.parent}channel.position=extra.position;channel.topic=extra.topic;channel.nsfw=extra.nsfw}await post("/track-channel",{server:server,channel:channel});addedChannels.add(channelInfo.id)},async addDiscordMessages(channelId,discordMessageArray){discordMessageArray=discordMessageArray.filter(msg=>(msg.type===0||msg.type===19||msg.type===21)&&msg.state==="SENT");if(discordMessageArray.length===0){return false}const userInfo={};let hasNewUsers=false;for(const msg of discordMessageArray){const user=msg.author;if(!addedUsers.has(user.id)){const obj={id:user.id,name:user.username};if(user.avatar){obj.avatar=user.avatar}if(!user.bot){obj.discriminator=user.discriminator}userInfo[user.id]=obj;hasNewUsers=true}}if(hasNewUsers){await post("/track-users",Object.values(userInfo));for(const id of Object.keys(userInfo)){addedUsers.add(id)}}const response=await post("/track-messages",discordMessageArray.map(msg=>{const obj={id:msg.id,sender:msg.author.id,channel:msg.channel_id,text:msg.content,timestamp:msg.timestamp.toDate().getTime()};if(msg.editedTimestamp!==null){obj.editTimestamp=msg.editedTimestamp.toDate().getTime()}if(msg.messageReference!==null){obj.repliedToId=msg.messageReference.message_id}if(msg.attachments.length>0){obj.attachments=msg.attachments.map(attachment=>{const mapped={id:attachment.id,name:attachment.filename,size:attachment.size,url:attachment.url};if(attachment.content_type){mapped.type=attachment.content_type}return mapped})}if(msg.embeds.length>0){obj.embeds=msg.embeds.map(embed=>{const mapped={};for(const key of Object.keys(embed)){if(key==="id"){continue}if(key==="rawTitle"){mapped["title"]=embed[key]}else if(key==="rawDescription"){mapped["description"]=embed[key]}else{mapped[key]=embed[key]}}return JSON.stringify(mapped)})}if(msg.reactions.length>0){obj.reactions=msg.reactions.map(reaction=>{const emoji=reaction.emoji;const mapped={count:reaction.count};if(emoji.id){mapped.id=emoji.id}if(emoji.name){mapped.name=emoji.name}if(emoji.animated){mapped.isAnimated=emoji.animated}return mapped})}return obj}));const anyNewMessages=await response.text();return anyNewMessages==="1"}}}();
|
@@ -1,10 +1,15 @@
|
||||
// noinspection JSUnresolvedVariable
|
||||
class DISCORD {
|
||||
static getMessageOuterElement() {
|
||||
return DOM.queryReactClass("messagesWrapper");
|
||||
}
|
||||
|
||||
static getMessageScrollerElement() {
|
||||
return this.getMessageOuterElement().querySelector("[class*='scroller-']");
|
||||
return DOM.queryReactClass("scroller", this.getMessageOuterElement());
|
||||
}
|
||||
|
||||
static getMessageElements() {
|
||||
return this.getMessageOuterElement().querySelectorAll("[class*='message-']");
|
||||
}
|
||||
|
||||
static hasMoreMessages() {
|
||||
@@ -41,7 +46,7 @@ class DISCORD {
|
||||
return;
|
||||
}
|
||||
|
||||
const anyMessage = this.getMessageOuterElement().querySelector("[class*='message-']");
|
||||
const anyMessage = DOM.queryReactClass("message", this.getMessageOuterElement());
|
||||
const messageCount = anyMessage ? anyMessage.parentElement.children.length : 0;
|
||||
|
||||
if (messageCount > 300) {
|
||||
@@ -85,33 +90,74 @@ class DISCORD {
|
||||
}, 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the property object of a message element.
|
||||
* @returns { null | { message: DiscordMessage, channel: Object } }
|
||||
*/
|
||||
static getMessageElementProps(ele) {
|
||||
const props = DOM.getReactProps(ele);
|
||||
|
||||
if (props.children && props.children.length >= 4) {
|
||||
const childProps = props.children[3].props;
|
||||
|
||||
if ("message" in childProps && "channel" in childProps) {
|
||||
return childProps;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array containing currently loaded messages.
|
||||
*/
|
||||
static getMessages() {
|
||||
try {
|
||||
const messages = [];
|
||||
|
||||
for (const ele of this.getMessageElements()) {
|
||||
const props = this.getMessageElementProps(ele);
|
||||
|
||||
if (props != null) {
|
||||
messages.push(props.message);
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an object containing the selected server and channel information.
|
||||
* For types DM and GROUP, the server and channel ids and names are identical.
|
||||
* @returns {{}|null}
|
||||
* @returns { {} | null }
|
||||
*/
|
||||
static getSelectedChannel() {
|
||||
try {
|
||||
let obj;
|
||||
let channelListEle = DOM.queryReactClass("privateChannels");
|
||||
|
||||
if (channelListEle) {
|
||||
const channel = DOM.queryReactClass("selected", channelListEle);
|
||||
for (const ele of this.getMessageElements()) {
|
||||
const props = this.getMessageElementProps(ele);
|
||||
|
||||
if (!channel || !("href" in channel) || !channel.href.includes("/@me/")) {
|
||||
return null;
|
||||
if (props != null) {
|
||||
obj = props.channel;
|
||||
break;
|
||||
}
|
||||
|
||||
const linkSplit = channel.href.split("/");
|
||||
const id = linkSplit[linkSplit.length - 1];
|
||||
|
||||
if (!(/^\d+$/.test(id))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (!obj) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const dms = DOM.queryReactClass("privateChannels");
|
||||
|
||||
if (dms) {
|
||||
let name;
|
||||
|
||||
for (const ele of channel.querySelectorAll("[class^='name-'] *")) {
|
||||
for (const ele of dms.querySelectorAll("[class*='channel-'] [class*='selected-'] [class^='name-'] *, [class*='channel-'][class*='selected-'] [class^='name-'] *")) {
|
||||
const node = Array.prototype.find.call(ele.childNodes, node => node.nodeType === Node.TEXT_NODE);
|
||||
|
||||
if (node) {
|
||||
@@ -124,87 +170,49 @@ class DISCORD {
|
||||
return null;
|
||||
}
|
||||
|
||||
const icon = channel.querySelector("img[class*='avatar']");
|
||||
const iconParent = icon && icon.closest("foreignObject");
|
||||
const iconMask = iconParent && iconParent.getAttribute("mask");
|
||||
let type;
|
||||
|
||||
obj = {
|
||||
"server": { id, name, type: (iconMask && iconMask.includes("#svg-mask-avatar-default")) ? "GROUP" : "DM" },
|
||||
"channel": { id, name }
|
||||
};
|
||||
// https://discord.com/developers/docs/resources/channel#channel-object-channel-types
|
||||
switch (obj.type) {
|
||||
case 1: type = "DM"; break;
|
||||
case 3: type = "GROUP"; break;
|
||||
default: return null;
|
||||
}
|
||||
|
||||
const id = obj.id;
|
||||
const server = { id, name, type };
|
||||
const channel = { id, name };
|
||||
|
||||
return { server, channel };
|
||||
}
|
||||
else {
|
||||
channelListEle = document.getElementById("channels");
|
||||
else if (obj.guild_id) {
|
||||
const server = {
|
||||
"id": obj.guild_id,
|
||||
"name": document.querySelector("nav header > h1").innerText,
|
||||
"type": "SERVER"
|
||||
};
|
||||
|
||||
const channel = channelListEle.querySelector("[class*='modeSelected']").parentElement;
|
||||
// noinspection JSUnresolvedVariable
|
||||
const props = DOM.getReactProps(channel).children.props;
|
||||
|
||||
if (!props) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// noinspection JSUnresolvedVariable
|
||||
const channelObj = props.channel || props.children().props.channel;
|
||||
|
||||
if (!channelObj) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// noinspection JSUnresolvedVariable
|
||||
obj = {
|
||||
"server": {
|
||||
"id": channelObj.guild_id,
|
||||
"name": document.querySelector("nav header > h1").innerText,
|
||||
"type": "SERVER"
|
||||
},
|
||||
"channel": {
|
||||
"id": channelObj.id,
|
||||
"name": channelObj.name,
|
||||
"extra": {
|
||||
"position": channelObj.position,
|
||||
"topic": channelObj.topic,
|
||||
"nsfw": channelObj.nsfw
|
||||
}
|
||||
const channel = {
|
||||
"id": obj.id,
|
||||
"name": obj.name,
|
||||
"extra": {
|
||||
"nsfw": obj.nsfw
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return obj.channel.length === 0 ? null : obj;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array containing currently loaded messages, or null if the messages cannot be retrieved.
|
||||
*/
|
||||
static getMessages() {
|
||||
try {
|
||||
const scroller = this.getMessageScrollerElement();
|
||||
const props = DOM.getReactProps(scroller);
|
||||
let wrappers;
|
||||
|
||||
try {
|
||||
// noinspection JSUnresolvedVariable
|
||||
wrappers = props.children.props.children.props.children.props.children.find(ele => Array.isArray(ele));
|
||||
} catch (e) { // old version compatibility
|
||||
wrappers = props.children.find(ele => Array.isArray(ele));
|
||||
}
|
||||
|
||||
const messages = [];
|
||||
|
||||
for (const obj of wrappers) {
|
||||
// noinspection JSUnresolvedVariable
|
||||
const nested = obj.props;
|
||||
|
||||
if (nested && nested.message) {
|
||||
messages.push(nested.message);
|
||||
if (obj.parent_id) {
|
||||
channel["extra"]["parent"] = obj.parent_id;
|
||||
}
|
||||
else {
|
||||
channel["extra"]["position"] = obj.position;
|
||||
channel["extra"]["topic"] = obj.topic;
|
||||
}
|
||||
|
||||
return { server, channel };
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
|
||||
return messages;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return null;
|
||||
@@ -231,11 +239,16 @@ class DISCORD {
|
||||
}
|
||||
}
|
||||
else {
|
||||
const channelIconNormal = "M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41045 9L8.35045 15H14.3504L15.4104 9H9.41045Z";
|
||||
const channelIconSpecial = "M14 8C14 7.44772 13.5523 7 13 7H9.76001L10.3657 3.58738C10.4201 3.28107 10.1845 3 9.87344 3H8.88907C8.64664 3 8.43914 3.17391 8.39677 3.41262L7.76001 7H4.18011C3.93722 7 3.72946 7.17456 3.68759 7.41381L3.51259 8.41381C3.45905 8.71977 3.69449 9 4.00511 9H7.41001L6.35001 15H2.77011C2.52722 15 2.31946 15.1746 2.27759 15.4138L2.10259 16.4138C2.04905 16.7198 2.28449 17 2.59511 17H6.00001L5.39427 20.4126C5.3399 20.7189 5.57547 21 5.88657 21H6.87094C7.11337 21 7.32088 20.8261 7.36325 20.5874L8.00001 17H14L13.3943 20.4126C13.3399 20.7189 13.5755 21 13.8866 21H14.8709C15.1134 21 15.3209 20.8261 15.3632 20.5874L16 17H19.5799C19.8228 17 20.0306 16.8254 20.0724 16.5862L20.2474 15.5862C20.301 15.2802 20.0655 15 19.7549 15H16.35L16.6758 13.1558C16.7823 12.5529 16.3186 12 15.7063 12C15.2286 12 14.8199 12.3429 14.7368 12.8133L14.3504 15H8.35045L9.41045 9H13C13.5523 9 14 8.55228 14 8Z";
|
||||
const channelIcons = [
|
||||
/* normal */ "M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41045 9L8.35045 15H14.3504L15.4104 9H9.41045Z",
|
||||
/* normal + thread */ "M5.43309 21C5.35842 21 5.30189 20.9325 5.31494 20.859L5.99991 17H2.14274C2.06819 17 2.01168 16.9327 2.02453 16.8593L2.33253 15.0993C2.34258 15.0419 2.39244 15 2.45074 15H6.34991L7.40991 9H3.55274C3.47819 9 3.42168 8.93274 3.43453 8.85931L3.74253 7.09931C3.75258 7.04189 3.80244 7 3.86074 7H7.75991L8.45234 3.09903C8.46251 3.04174 8.51231 3 8.57049 3H10.3267C10.4014 3 10.4579 3.06746 10.4449 3.14097L9.75991 7H15.7599L16.4523 3.09903C16.4625 3.04174 16.5123 3 16.5705 3H18.3267C18.4014 3 18.4579 3.06746 18.4449 3.14097L17.7599 7H21.6171C21.6916 7 21.7481 7.06725 21.7353 7.14069L21.4273 8.90069C21.4172 8.95811 21.3674 9 21.3091 9H17.4099L17.0495 11.04H15.05L15.4104 9H9.41035L8.35035 15H10.5599V17H7.99991L7.30749 20.901C7.29732 20.9583 7.24752 21 7.18934 21H5.43309Z",
|
||||
/* nsfw or private */ "M14 8C14 7.44772 13.5523 7 13 7H9.76001L10.3657 3.58738C10.4201 3.28107 10.1845 3 9.87344 3H8.88907C8.64664 3 8.43914 3.17391 8.39677 3.41262L7.76001 7H4.18011C3.93722 7 3.72946 7.17456 3.68759 7.41381L3.51259 8.41381C3.45905 8.71977 3.69449 9 4.00511 9H7.41001L6.35001 15H2.77011C2.52722 15 2.31946 15.1746 2.27759 15.4138L2.10259 16.4138C2.04905 16.7198 2.28449 17 2.59511 17H6.00001L5.39427 20.4126C5.3399 20.7189 5.57547 21 5.88657 21H6.87094C7.11337 21 7.32088 20.8261 7.36325 20.5874L8.00001 17H14L13.3943 20.4126C13.3399 20.7189 13.5755 21 13.8866 21H14.8709C15.1134 21 15.3209 20.8261 15.3632 20.5874L16 17H19.5799C19.8228 17 20.0306 16.8254 20.0724 16.5862L20.2474 15.5862C20.301 15.2802 20.0655 15 19.7549 15H16.35L16.6758 13.1558C16.7823 12.5529 16.3186 12 15.7063 12C15.2286 12 14.8199 12.3429 14.7368 12.8133L14.3504 15H8.35045L9.41045 9H13C13.5523 9 14 8.55228 14 8Z",
|
||||
/* nsfw + thread */ "M14.4 7C14.5326 7 14.64 7.10745 14.64 7.24V8.76C14.64 8.89255 14.5326 9 14.4 9H9.41045L8.35045 15H10.56V17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H14.4Z",
|
||||
/* private + thread */ "M15.44 6.99992C15.5725 6.99992 15.68 7.10737 15.68 7.23992V8.75992C15.68 8.89247 15.5725 8.99992 15.44 8.99992H9.41045L8.35045 14.9999H10.56V16.9999H8.00001L7.36325 20.5873C7.32088 20.826 7.11337 20.9999 6.87094 20.9999H5.88657C5.57547 20.9999 5.3399 20.7189 5.39427 20.4125L6.00001 16.9999H2.59511C2.28449 16.9999 2.04905 16.7197 2.10259 16.4137L2.27759 15.4137C2.31946 15.1745 2.52722 14.9999 2.77011 14.9999H6.35001L7.41001 8.99992H4.00511C3.69449 8.99992 3.45905 8.71969 3.51259 8.41373L3.68759 7.41373C3.72946 7.17448 3.93722 6.99992 4.18011 6.99992H7.76001L8.39677 3.41254C8.43914 3.17384 8.64664 2.99992 8.88907 2.99992H9.87344C10.1845 2.99992 10.4201 3.28099 10.3657 3.58731L9.76001 6.99992H15.44Z"
|
||||
];
|
||||
|
||||
const isValidChannelClass = cls => cls.includes("wrapper-") && !cls.includes("clickable-");
|
||||
const isValidChannelType = ele => !!ele.querySelector("path[d=\"" + channelIconNormal + "\"]") || !!ele.querySelector("path[d=\"" + channelIconSpecial + "\"]");
|
||||
const isValidChannelType = ele => channelIcons.some(icon => !!ele.querySelector("path[d=\"" + icon + "\"]"));
|
||||
const isValidChannel = ele => ele.childElementCount > 0 && isValidChannelClass(ele.children[0].className) && isValidChannelType(ele);
|
||||
|
||||
const channelListEle = document.querySelector("div[class*='sidebar'] > nav[class*='container'] > div[class*='scroller']");
|
||||
|
@@ -75,6 +75,8 @@ const STATE = (function() {
|
||||
* @property {Object[]} embeds
|
||||
* @property {DiscordMessageReaction[]} [reactions]
|
||||
* @property {DiscordMessageReference} [messageReference]
|
||||
* @property {Number} type
|
||||
* @property {String} state
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -156,9 +158,15 @@ const STATE = (function() {
|
||||
};
|
||||
|
||||
if ("extra" in channelInfo) {
|
||||
channel.position = channelInfo.extra.position;
|
||||
channel.topic = channelInfo.extra.topic;
|
||||
channel.nsfw = channelInfo.extra.nsfw;
|
||||
const extra = channelInfo.extra;
|
||||
|
||||
if ("parent" in extra) {
|
||||
channel.parent = extra.parent;
|
||||
}
|
||||
|
||||
channel.position = extra.position;
|
||||
channel.topic = extra.topic;
|
||||
channel.nsfw = extra.nsfw;
|
||||
}
|
||||
|
||||
await post("/track-channel", { server, channel });
|
||||
@@ -170,6 +178,13 @@ const STATE = (function() {
|
||||
* @param {DiscordMessage[]} discordMessageArray
|
||||
*/
|
||||
async addDiscordMessages(channelId, discordMessageArray) {
|
||||
// https://discord.com/developers/docs/resources/channel#message-object-message-types
|
||||
discordMessageArray = discordMessageArray.filter(msg => (msg.type === 0 || msg.type === 19 || msg.type === 21) && msg.state === "SENT");
|
||||
|
||||
if (discordMessageArray.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const userInfo = {};
|
||||
let hasNewUsers = false;
|
||||
|
||||
|
@@ -171,7 +171,7 @@ const DISCORD = (function() {
|
||||
return DOM.getHumanReadableTime(value);
|
||||
}
|
||||
else if (property === "contents") {
|
||||
return value == null || value.length === 0 ? "" : processMessageContents(value);
|
||||
return value && value.length > 0 ? processMessageContents(value) : "";
|
||||
}
|
||||
else if (property === "embeds") {
|
||||
if (!value) {
|
||||
@@ -225,8 +225,8 @@ const DISCORD = (function() {
|
||||
return STATE.hasActiveFilter ? "<span class='info jump' data-jump='" + value + "'>Jump to message</span>" : "";
|
||||
}
|
||||
else if (property === "reply") {
|
||||
if (value === null) {
|
||||
return "";
|
||||
if (!value) {
|
||||
return value === null ? "<span class='reply-contents reply-missing'>(replies to an unknown message)</span>" : "";
|
||||
}
|
||||
|
||||
const user = "<span class='reply-username' title='#" + (value.user.tag ? value.user.tag : "????") + "'>" + value.user.name + "</span>";
|
||||
@@ -236,7 +236,7 @@ const DISCORD = (function() {
|
||||
return "<span class='jump' data-jump='" + value.id + "'>Jump to reply</span><span class='user'>" + avatar + user + "</span>" + contents;
|
||||
}
|
||||
else if (property === "reactions"){
|
||||
if (value === null){
|
||||
if (!value){
|
||||
return "";
|
||||
}
|
||||
|
||||
|
@@ -118,7 +118,13 @@ const GUI = (function() {
|
||||
resetActiveFilter();
|
||||
|
||||
const index = STATE.navigateToMessage(jump);
|
||||
DOM.id("messages").children[index].scrollIntoView();
|
||||
|
||||
if (index === -1) {
|
||||
alert("Message not found.");
|
||||
}
|
||||
else {
|
||||
DOM.id("messages").children[index].scrollIntoView();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
@@ -29,29 +29,132 @@ const STATE = (function() {
|
||||
return loadedFileMeta ? loadedFileMeta.users : [];
|
||||
};
|
||||
|
||||
const getServer = function(index) {
|
||||
return loadedFileMeta.servers[index] || { "name": "<unknown>", "type": "unknown" };
|
||||
};
|
||||
|
||||
const generateChannelHierarchy = function() {
|
||||
/**
|
||||
* @type {Map<string, Set>}
|
||||
*/
|
||||
const hierarchy = new Map();
|
||||
|
||||
if (!loadedFileMeta) {
|
||||
return hierarchy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Set}
|
||||
*/
|
||||
function getChildren(parentId) {
|
||||
let children = hierarchy.get(parentId);
|
||||
|
||||
if (!children) {
|
||||
children = new Set();
|
||||
hierarchy.set(parentId, children);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
for (const [ id, channel ] of Object.entries(loadedFileMeta.channels)) {
|
||||
getChildren(channel.parent || "").add(id);
|
||||
}
|
||||
|
||||
const unreachableIds = new Set(hierarchy.keys());
|
||||
|
||||
function reachIds(parentId) {
|
||||
unreachableIds.delete(parentId);
|
||||
|
||||
const children = hierarchy.get(parentId);
|
||||
|
||||
if (children) {
|
||||
for (const id of children) {
|
||||
reachIds(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reachIds("");
|
||||
|
||||
const rootChildren = getChildren("");
|
||||
|
||||
for (const unreachableId of unreachableIds) {
|
||||
for (const id of hierarchy.get(unreachableId)) {
|
||||
rootChildren.add(id);
|
||||
}
|
||||
|
||||
hierarchy.delete(unreachableId);
|
||||
}
|
||||
|
||||
return hierarchy;
|
||||
};
|
||||
|
||||
const generateChannelOrder = function() {
|
||||
if (!loadedFileMeta) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const channels = loadedFileMeta.channels;
|
||||
const hierarchy = generateChannelHierarchy();
|
||||
|
||||
function getSortedSubTree(parentId) {
|
||||
const children = hierarchy.get(parentId);
|
||||
if (!children) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sortedChildren = Array.from(children);
|
||||
|
||||
sortedChildren.sort((id1, id2) => {
|
||||
const c1 = channels[id1];
|
||||
const c2 = channels[id2];
|
||||
const s1 = getServer(c1.server);
|
||||
const s2 = getServer(c2.server);
|
||||
|
||||
return s1.type.localeCompare(s2.type, "en") ||
|
||||
s1.name.toLocaleLowerCase().localeCompare(s2.name.toLocaleLowerCase(), undefined, { numeric: true }) ||
|
||||
(c1.position || -1) - (c2.position || -1) ||
|
||||
c1.name.toLocaleLowerCase().localeCompare(c2.name.toLocaleLowerCase(), undefined, { numeric: true });
|
||||
});
|
||||
|
||||
const subTree = [];
|
||||
|
||||
for (const id of sortedChildren) {
|
||||
subTree.push(id);
|
||||
subTree.push(...getSortedSubTree(id));
|
||||
}
|
||||
|
||||
return subTree;
|
||||
}
|
||||
|
||||
const orderArray = getSortedSubTree("");
|
||||
const orderMap = {};
|
||||
|
||||
for (let i = 0; i < orderArray.length; i++) {
|
||||
orderMap[orderArray[i]] = i;
|
||||
}
|
||||
|
||||
return orderMap;
|
||||
};
|
||||
|
||||
const getChannelList = function() {
|
||||
if (!loadedFileMeta) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const channels = loadedFileMeta.channels;
|
||||
const channelOrder = generateChannelOrder();
|
||||
|
||||
return Object.keys(channels).map(key => ({
|
||||
"id": key,
|
||||
"name": channels[key].name,
|
||||
"server": loadedFileMeta.servers[channels[key].server] || { "name": "<unknown>", "type": "unknown" },
|
||||
"server": getServer(channels[key].server),
|
||||
"msgcount": getFilteredMessageKeys(key).length,
|
||||
"topic": channels[key].topic || "",
|
||||
"nsfw": channels[key].nsfw || false,
|
||||
"position": channels[key].position || -1
|
||||
})).sort((ac, bc) => {
|
||||
const as = ac.server;
|
||||
const bs = bc.server;
|
||||
|
||||
return as.type.localeCompare(bs.type, "en") ||
|
||||
as.name.toLocaleLowerCase().localeCompare(bs.name.toLocaleLowerCase(), undefined, { numeric: true }) ||
|
||||
ac.position - bc.position ||
|
||||
ac.name.toLocaleLowerCase().localeCompare(bc.name.toLocaleLowerCase(), undefined, { numeric: true });
|
||||
return channelOrder[ac.id] - channelOrder[bc.id];
|
||||
});
|
||||
};
|
||||
|
||||
@@ -59,6 +162,26 @@ const STATE = (function() {
|
||||
return loadedFileData[channel] || {};
|
||||
};
|
||||
|
||||
const getMessageById = function(id) {
|
||||
for (const messages of Object.values(loadedFileData)) {
|
||||
if (id in messages) {
|
||||
return messages[id];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getMessageChannel = function(id) {
|
||||
for (const [ channel, messages ] of Object.entries(loadedFileData)) {
|
||||
if (id in messages) {
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getMessageList = function() {
|
||||
if (!loadedMessages) {
|
||||
return [];
|
||||
@@ -83,28 +206,47 @@ const STATE = (function() {
|
||||
const user = getUser(message.u);
|
||||
const avatar = user.avatar ? { id: getUserId(message.u), path: user.avatar } : null;
|
||||
|
||||
const reply = ("r" in message && message.r in messages) ? messages[message.r] : null;
|
||||
const replyUser = reply ? getUser(reply.u) : null;
|
||||
const replyAvatar = replyUser && replyUser.avatar ? { id: getUserId(reply.u), path: replyUser.avatar } : null;
|
||||
const replyObj = reply ? {
|
||||
"id": message.r,
|
||||
"user": replyUser,
|
||||
"avatar": replyAvatar,
|
||||
"contents": reply.m
|
||||
} : null;
|
||||
|
||||
return {
|
||||
const obj = {
|
||||
user,
|
||||
avatar,
|
||||
"timestamp": message.t,
|
||||
"contents": ("m" in message) ? message.m : null,
|
||||
"embeds": ("e" in message) ? message.e.map(embed => JSON.parse(embed)) : [],
|
||||
"attachments": ("a" in message) ? message.a : [],
|
||||
"edit": ("te" in message) ? message.te : null,
|
||||
"jump": key,
|
||||
"reply": replyObj,
|
||||
"reactions": ("re" in message) ? message.re : null
|
||||
};
|
||||
|
||||
if ("m" in message) {
|
||||
obj["contents"] = message.m;
|
||||
}
|
||||
|
||||
if ("e" in message) {
|
||||
obj["embeds"] = message.e.map(embed => JSON.parse(embed));
|
||||
}
|
||||
|
||||
if ("a" in message) {
|
||||
obj["attachments"] = message.a;
|
||||
}
|
||||
|
||||
if ("te" in message) {
|
||||
obj["edit"] = message.te;
|
||||
}
|
||||
|
||||
if ("r" in message) {
|
||||
const replyMessage = getMessageById(message.r);
|
||||
const replyUser = replyMessage ? getUser(replyMessage.u) : null;
|
||||
const replyAvatar = replyUser && replyUser.avatar ? { id: getUserId(replyMessage.u), path: replyUser.avatar } : null;
|
||||
|
||||
obj["reply"] = replyMessage ? {
|
||||
"id": message.r,
|
||||
"user": replyUser,
|
||||
"avatar": replyAvatar,
|
||||
"contents": replyMessage.m
|
||||
} : null;
|
||||
}
|
||||
|
||||
if ("re" in message) {
|
||||
obj["reactions"] = message.re;
|
||||
}
|
||||
|
||||
return obj;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -175,15 +317,18 @@ const STATE = (function() {
|
||||
},
|
||||
|
||||
getChannelName(channel) {
|
||||
return loadedFileMeta.channels[channel].name || channel;
|
||||
const channelObj = loadedFileMeta.channels[channel];
|
||||
return (channelObj && channelObj.name) || channel;
|
||||
},
|
||||
|
||||
getUserTag(user) {
|
||||
return loadedFileMeta.users[user].tag;
|
||||
const userObj = loadedFileMeta.users[user];
|
||||
return (userObj && userObj.tag) || "????";
|
||||
},
|
||||
|
||||
getUserName(user) {
|
||||
return loadedFileMeta.users[user].name || user;
|
||||
const userObj = loadedFileMeta.users[user];
|
||||
return (userObj && userObj.name) || user;
|
||||
},
|
||||
|
||||
selectChannel(channel) {
|
||||
@@ -247,13 +392,20 @@ const STATE = (function() {
|
||||
|
||||
navigateToMessage(id) {
|
||||
if (!loadedMessages) {
|
||||
return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
const channel = getMessageChannel(id);
|
||||
|
||||
if (channel !== null && channel !== selectedChannel) {
|
||||
triggerChannelsRefreshed(channel);
|
||||
this.selectChannel(channel);
|
||||
}
|
||||
|
||||
const index = loadedMessages.indexOf(id);
|
||||
|
||||
if (index === -1) {
|
||||
return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
currentPage = Math.max(1, Math.min(this.getPageCount(), 1 + Math.floor(index / messagesPerPage)));
|
||||
|
@@ -221,6 +221,10 @@
|
||||
padding: 1px 2px;
|
||||
}
|
||||
|
||||
.reply-missing {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.reactions {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@ namespace DHT.Server.Data {
|
||||
public ulong Id { get; init; }
|
||||
public ulong Server { get; init; }
|
||||
public string Name { get; init; }
|
||||
public ulong? ParentId { get; init; }
|
||||
public int? Position { get; init; }
|
||||
public string? Topic { get; init; }
|
||||
public bool? Nsfw { get; init; }
|
||||
|
@@ -6,6 +6,8 @@ namespace DHT.Server.Data.Filters {
|
||||
public DateTime? StartDate { get; set; }
|
||||
public DateTime? EndDate { get; set; }
|
||||
|
||||
public HashSet<ulong> MessageIds { get; } = new();
|
||||
public HashSet<ulong>? ChannelIds { get; set; } = null;
|
||||
public HashSet<ulong>? UserIds { get; set; } = null;
|
||||
public HashSet<ulong>? MessageIds { get; set; } = null;
|
||||
}
|
||||
}
|
||||
|
6
app/Server/Data/Filters/MessageFilterRemovalMode.cs
Normal file
6
app/Server/Data/Filters/MessageFilterRemovalMode.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace DHT.Server.Data.Filters {
|
||||
public enum MessageFilterRemovalMode {
|
||||
KeepMatching,
|
||||
RemoveMatching
|
||||
}
|
||||
}
|
@@ -8,28 +8,28 @@ namespace DHT.Server.Data {
|
||||
public static class ServerTypes {
|
||||
public static ServerType? FromString(string? str) {
|
||||
return str switch {
|
||||
"SERVER" => ServerType.Server,
|
||||
"GROUP" => ServerType.Group,
|
||||
"DM" => ServerType.DirectMessage,
|
||||
_ => null
|
||||
"SERVER" => ServerType.Server,
|
||||
"GROUP" => ServerType.Group,
|
||||
"DM" => ServerType.DirectMessage,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToString(ServerType? type) {
|
||||
return type switch {
|
||||
ServerType.Server => "SERVER",
|
||||
ServerType.Group => "GROUP",
|
||||
ServerType.DirectMessage => "DM",
|
||||
_ => "UNKNOWN"
|
||||
ServerType.Server => "SERVER",
|
||||
ServerType.Group => "GROUP",
|
||||
ServerType.DirectMessage => "DM",
|
||||
_ => "UNKNOWN"
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToJsonViewerString(ServerType? type) {
|
||||
return type switch {
|
||||
ServerType.Server => "server",
|
||||
ServerType.Group => "group",
|
||||
ServerType.DirectMessage => "user",
|
||||
_ => "unknown"
|
||||
ServerType.Server => "server",
|
||||
ServerType.Group => "group",
|
||||
ServerType.DirectMessage => "user",
|
||||
_ => "unknown"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
16
app/Server/Database/DatabaseExtensions.cs
Normal file
16
app/Server/Database/DatabaseExtensions.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace DHT.Server.Database {
|
||||
public static class DatabaseExtensions {
|
||||
public static void AddFrom(this IDatabaseFile target, IDatabaseFile source) {
|
||||
foreach (var server in source.GetAllServers()) {
|
||||
target.AddServer(server);
|
||||
}
|
||||
|
||||
foreach (var channel in source.GetAllChannels()) {
|
||||
target.AddChannel(channel);
|
||||
}
|
||||
|
||||
target.AddUsers(source.GetAllUsers().ToArray());
|
||||
target.AddMessages(source.GetMessages().ToArray());
|
||||
}
|
||||
}
|
||||
}
|
@@ -5,6 +5,7 @@ namespace DHT.Server.Database {
|
||||
public class DatabaseStatistics : INotifyPropertyChanged {
|
||||
private long totalServers;
|
||||
private long totalChannels;
|
||||
private long totalUsers;
|
||||
private long totalMessages;
|
||||
|
||||
public long TotalServers {
|
||||
@@ -17,6 +18,11 @@ namespace DHT.Server.Database {
|
||||
internal set => Change(out totalChannels, value);
|
||||
}
|
||||
|
||||
public long TotalUsers {
|
||||
get => totalUsers;
|
||||
internal set => Change(out totalUsers, value);
|
||||
}
|
||||
|
||||
public long TotalMessages {
|
||||
get => totalMessages;
|
||||
internal set => Change(out totalMessages, value);
|
||||
@@ -28,5 +34,14 @@ namespace DHT.Server.Database {
|
||||
field = value;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
|
||||
public DatabaseStatistics Clone() {
|
||||
return new DatabaseStatistics {
|
||||
totalServers = totalServers,
|
||||
totalChannels = totalChannels,
|
||||
totalUsers = TotalUsers,
|
||||
totalMessages = totalMessages
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -40,6 +40,8 @@ namespace DHT.Server.Database {
|
||||
return new();
|
||||
}
|
||||
|
||||
public void RemoveMessages(MessageFilter filter, MessageFilterRemovalMode mode) {}
|
||||
|
||||
public void Dispose() {
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
@@ -8,26 +8,48 @@ using DHT.Server.Data.Filters;
|
||||
namespace DHT.Server.Database.Export {
|
||||
public static class ViewerJsonExport {
|
||||
public static string Generate(IDatabaseFile db, MessageFilter? filter = null) {
|
||||
JsonSerializerOptions opts = new();
|
||||
var includedUserIds = new HashSet<ulong>();
|
||||
var includedChannelIds = new HashSet<ulong>();
|
||||
var includedServerIds = new HashSet<ulong>();
|
||||
|
||||
var includedMessages = db.GetMessages(filter);
|
||||
var includedChannels = new List<Channel>();
|
||||
|
||||
foreach (var message in includedMessages) {
|
||||
includedUserIds.Add(message.Sender);
|
||||
includedChannelIds.Add(message.Channel);
|
||||
}
|
||||
|
||||
foreach (var channel in db.GetAllChannels()) {
|
||||
if (includedChannelIds.Contains(channel.Id)) {
|
||||
includedChannels.Add(channel);
|
||||
includedServerIds.Add(channel.Server);
|
||||
}
|
||||
}
|
||||
|
||||
var opts = new JsonSerializerOptions();
|
||||
opts.Converters.Add(new ViewerJsonSnowflakeSerializer());
|
||||
|
||||
var users = GenerateUserList(db, out var userindex, out var userIndices);
|
||||
var servers = GenerateServerList(db, out var serverindex);
|
||||
var channels = GenerateChannelList(db, serverindex);
|
||||
var users = GenerateUserList(db, includedUserIds, out var userindex, out var userIndices);
|
||||
var servers = GenerateServerList(db, includedServerIds, out var serverindex);
|
||||
var channels = GenerateChannelList(includedChannels, serverindex);
|
||||
|
||||
return JsonSerializer.Serialize(new {
|
||||
meta = new { users, userindex, servers, channels },
|
||||
data = GenerateMessageList(db, filter, userIndices)
|
||||
data = GenerateMessageList(includedMessages, userIndices)
|
||||
}, opts);
|
||||
}
|
||||
|
||||
private static dynamic GenerateUserList(IDatabaseFile db, out List<string> userindex, out Dictionary<ulong, int> userIndices) {
|
||||
private static dynamic GenerateUserList(IDatabaseFile db, HashSet<ulong> userIds, out List<string> userindex, out Dictionary<ulong, int> userIndices) {
|
||||
var users = new Dictionary<string, dynamic>();
|
||||
userindex = new List<string>();
|
||||
userIndices = new Dictionary<ulong, int>();
|
||||
|
||||
foreach (var user in db.GetAllUsers()) {
|
||||
var id = user.Id.ToString();
|
||||
var id = user.Id;
|
||||
if (!userIds.Contains(id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
dynamic obj = new ExpandoObject();
|
||||
obj.name = user.Name;
|
||||
@@ -40,20 +62,26 @@ namespace DHT.Server.Database.Export {
|
||||
obj.tag = user.Discriminator;
|
||||
}
|
||||
|
||||
userIndices[user.Id] = users.Count;
|
||||
userindex.Add(id);
|
||||
users[id] = obj;
|
||||
var idStr = id.ToString();
|
||||
userIndices[id] = users.Count;
|
||||
userindex.Add(idStr);
|
||||
users[idStr] = obj;
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
private static dynamic GenerateServerList(IDatabaseFile db, out Dictionary<ulong, int> serverIndices) {
|
||||
private static dynamic GenerateServerList(IDatabaseFile db, HashSet<ulong> serverIds, out Dictionary<ulong, int> serverIndices) {
|
||||
var servers = new List<dynamic>();
|
||||
serverIndices = new Dictionary<ulong, int>();
|
||||
|
||||
foreach (var server in db.GetAllServers()) {
|
||||
serverIndices[server.Id] = servers.Count;
|
||||
var id = server.Id;
|
||||
if (!serverIds.Contains(id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
serverIndices[id] = servers.Count;
|
||||
servers.Add(new {
|
||||
name = server.Name,
|
||||
type = ServerTypes.ToJsonViewerString(server.Type)
|
||||
@@ -63,14 +91,18 @@ namespace DHT.Server.Database.Export {
|
||||
return servers;
|
||||
}
|
||||
|
||||
private static dynamic GenerateChannelList(IDatabaseFile db, Dictionary<ulong, int> serverIndices) {
|
||||
private static dynamic GenerateChannelList(List<Channel> includedChannels, Dictionary<ulong, int> serverIndices) {
|
||||
var channels = new Dictionary<string, dynamic>();
|
||||
|
||||
foreach (var channel in db.GetAllChannels()) {
|
||||
foreach (var channel in includedChannels) {
|
||||
dynamic obj = new ExpandoObject();
|
||||
obj.server = serverIndices[channel.Server];
|
||||
obj.name = channel.Name;
|
||||
|
||||
if (channel.ParentId != null) {
|
||||
obj.parent = channel.ParentId;
|
||||
}
|
||||
|
||||
if (channel.Position != null) {
|
||||
obj.position = channel.Position;
|
||||
}
|
||||
@@ -89,10 +121,10 @@ namespace DHT.Server.Database.Export {
|
||||
return channels;
|
||||
}
|
||||
|
||||
private static dynamic GenerateMessageList(IDatabaseFile db, MessageFilter? filter, Dictionary<ulong, int> userIndices) {
|
||||
private static dynamic GenerateMessageList(List<Message> includedMessages, Dictionary<ulong, int> userIndices) {
|
||||
var data = new Dictionary<string, Dictionary<string, dynamic>>();
|
||||
|
||||
foreach (var grouping in db.GetMessages(filter).GroupBy(message => message.Channel)) {
|
||||
foreach (var grouping in includedMessages.GroupBy(message => message.Channel)) {
|
||||
var channel = grouping.Key.ToString();
|
||||
var channelData = new Dictionary<string, dynamic>();
|
||||
|
||||
|
@@ -20,5 +20,6 @@ namespace DHT.Server.Database {
|
||||
void AddMessages(Message[] messages);
|
||||
int CountMessages(MessageFilter? filter = null);
|
||||
List<Message> GetMessages(MessageFilter? filter = null);
|
||||
void RemoveMessages(MessageFilter filter, MessageFilterRemovalMode mode);
|
||||
}
|
||||
}
|
||||
|
@@ -5,7 +5,7 @@ using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace DHT.Server.Database.Sqlite {
|
||||
internal class Schema {
|
||||
internal const int Version = 1;
|
||||
internal const int Version = 2;
|
||||
|
||||
private readonly SqliteConnection conn;
|
||||
|
||||
@@ -64,6 +64,7 @@ namespace DHT.Server.Database.Sqlite {
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
server INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
parent_id INTEGER,
|
||||
position INTEGER,
|
||||
topic TEXT,
|
||||
nsfw INTEGER)");
|
||||
@@ -79,7 +80,7 @@ namespace DHT.Server.Database.Sqlite {
|
||||
|
||||
Execute(@"CREATE TABLE attachments (
|
||||
message_id INTEGER NOT NULL,
|
||||
attachment_id INTEGER NOT NULL PRIMARY KEY NOT NULL,
|
||||
attachment_id INTEGER NOT NULL PRIMARY KEY NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT,
|
||||
url TEXT NOT NULL,
|
||||
@@ -105,6 +106,10 @@ namespace DHT.Server.Database.Sqlite {
|
||||
|
||||
private void UpgradeSchemas(int dbVersion) {
|
||||
Execute("UPDATE metadata SET value = " + Version + " WHERE key = 'version'");
|
||||
|
||||
if (dbVersion <= 1) {
|
||||
Execute("ALTER TABLE channels ADD parent_id INTEGER");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DHT.Server.Collections;
|
||||
using DHT.Server.Data;
|
||||
@@ -32,6 +33,7 @@ namespace DHT.Server.Database.Sqlite {
|
||||
this.Statistics = new DatabaseStatistics();
|
||||
UpdateServerStatistics();
|
||||
UpdateChannelStatistics();
|
||||
UpdateUserStatistics();
|
||||
UpdateMessageStatistics();
|
||||
}
|
||||
|
||||
@@ -72,13 +74,14 @@ namespace DHT.Server.Database.Sqlite {
|
||||
|
||||
public void AddChannel(Channel channel) {
|
||||
using var cmd = conn.Upsert("channels", new[] {
|
||||
"id", "server", "name", "position", "topic", "nsfw"
|
||||
"id", "server", "name", "parent_id", "position", "topic", "nsfw"
|
||||
});
|
||||
|
||||
var channelParams = cmd.Parameters;
|
||||
channelParams.AddAndSet(":id", channel.Id);
|
||||
channelParams.AddAndSet(":server", channel.Server);
|
||||
channelParams.AddAndSet(":name", channel.Name);
|
||||
channelParams.AddAndSet(":parent_id", channel.ParentId);
|
||||
channelParams.AddAndSet(":position", channel.Position);
|
||||
channelParams.AddAndSet(":topic", channel.Topic);
|
||||
channelParams.AddAndSet(":nsfw", channel.Nsfw);
|
||||
@@ -89,7 +92,7 @@ namespace DHT.Server.Database.Sqlite {
|
||||
public List<Channel> GetAllChannels() {
|
||||
var list = new List<Channel>();
|
||||
|
||||
using var cmd = conn.Command("SELECT id, server, name, position, topic, nsfw FROM channels");
|
||||
using var cmd = conn.Command("SELECT id, server, name, parent_id, position, topic, nsfw FROM channels");
|
||||
using var reader = cmd.ExecuteReader();
|
||||
|
||||
while (reader.Read()) {
|
||||
@@ -97,9 +100,10 @@ namespace DHT.Server.Database.Sqlite {
|
||||
Id = (ulong) reader.GetInt64(0),
|
||||
Server = (ulong) reader.GetInt64(1),
|
||||
Name = reader.GetString(2),
|
||||
Position = reader.IsDBNull(3) ? null : reader.GetInt32(3),
|
||||
Topic = reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
Nsfw = reader.IsDBNull(5) ? null : reader.GetBoolean(5)
|
||||
ParentId = reader.IsDBNull(3) ? null : (ulong) reader.GetInt64(3),
|
||||
Position = reader.IsDBNull(4) ? null : reader.GetInt32(4),
|
||||
Topic = reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
Nsfw = reader.IsDBNull(6) ? null : reader.GetBoolean(6)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -127,6 +131,7 @@ namespace DHT.Server.Database.Sqlite {
|
||||
}
|
||||
|
||||
tx.Commit();
|
||||
UpdateUserStatistics();
|
||||
}
|
||||
|
||||
public List<User> GetAllUsers() {
|
||||
@@ -299,6 +304,24 @@ namespace DHT.Server.Database.Sqlite {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void RemoveMessages(MessageFilter filter, MessageFilterRemovalMode mode) {
|
||||
var whereClause = filter.GenerateWhereClause(invert: mode == MessageFilterRemovalMode.KeepMatching);
|
||||
if (string.IsNullOrEmpty(whereClause)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Rider is being stupid...
|
||||
StringBuilder build = new StringBuilder()
|
||||
.Append("DELETE ")
|
||||
.Append("FROM messages")
|
||||
.Append(whereClause);
|
||||
|
||||
using var cmd = conn.Command(build.ToString());
|
||||
cmd.ExecuteNonQuery();
|
||||
|
||||
UpdateMessageStatistics();
|
||||
}
|
||||
|
||||
private MultiDictionary<ulong, Attachment> GetAllAttachments() {
|
||||
var dict = new MultiDictionary<ulong, Attachment>();
|
||||
|
||||
@@ -367,6 +390,11 @@ namespace DHT.Server.Database.Sqlite {
|
||||
Statistics.TotalChannels = cmd.ExecuteScalar() as long? ?? 0;
|
||||
}
|
||||
|
||||
private void UpdateUserStatistics() {
|
||||
using var cmd = conn.Command("SELECT COUNT(*) FROM users");
|
||||
Statistics.TotalUsers = cmd.ExecuteScalar() as long? ?? 0;
|
||||
}
|
||||
|
||||
private void UpdateMessageStatistics() {
|
||||
using var cmd = conn.Command("SELECT COUNT(*) FROM messages");
|
||||
Statistics.TotalMessages = cmd.ExecuteScalar() as long? ?? 0L;
|
||||
|
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using DHT.Server.Data.Filters;
|
||||
|
||||
namespace DHT.Server.Database.Sqlite {
|
||||
public static class SqliteMessageFilter {
|
||||
public static string GenerateWhereClause(this MessageFilter? filter) {
|
||||
public static string GenerateWhereClause(this MessageFilter? filter, bool invert = false) {
|
||||
if (filter == null) {
|
||||
return "";
|
||||
}
|
||||
@@ -15,15 +14,33 @@ namespace DHT.Server.Database.Sqlite {
|
||||
if (filter.StartDate != null) {
|
||||
conditions.Add("timestamp >= " + new DateTimeOffset(filter.StartDate.Value).ToUnixTimeMilliseconds());
|
||||
}
|
||||
|
||||
if (filter.EndDate != null) {
|
||||
conditions.Add("timestamp <= " + new DateTimeOffset(filter.EndDate.Value).ToUnixTimeMilliseconds());
|
||||
}
|
||||
|
||||
if (filter.MessageIds.Count > 0) {
|
||||
conditions.Add("(" + string.Join(" OR ", filter.MessageIds.Select(id => "message_id = " + id)) + ")");
|
||||
if (filter.ChannelIds != null) {
|
||||
conditions.Add("channel_id IN (" + string.Join(",", filter.ChannelIds) + ")");
|
||||
}
|
||||
|
||||
return conditions.Count == 0 ? "" : " WHERE " + string.Join(" AND ", conditions);
|
||||
if (filter.UserIds != null) {
|
||||
conditions.Add("sender_id IN (" + string.Join(",", filter.UserIds) + ")");
|
||||
}
|
||||
|
||||
if (filter.MessageIds != null) {
|
||||
conditions.Add("message_id IN (" + string.Join(",", filter.MessageIds) + ")");
|
||||
}
|
||||
|
||||
if (conditions.Count == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (invert) {
|
||||
return " WHERE NOT (" + string.Join(" AND ", conditions) + ")";
|
||||
}
|
||||
else {
|
||||
return " WHERE " + string.Join(" AND ", conditions);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -27,24 +27,24 @@ namespace DHT.Server.Endpoints {
|
||||
var requestToken = request.Headers["X-DHT-Token"];
|
||||
if (requestToken.Count != 1 || requestToken[0] != parameters.Token) {
|
||||
Log.Error("Token: " + (requestToken.Count == 1 ? requestToken[0] : "<missing>"));
|
||||
response.StatusCode = (int)HttpStatusCode.Forbidden;
|
||||
response.StatusCode = (int) HttpStatusCode.Forbidden;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var (statusCode, output) = await Respond(ctx);
|
||||
response.StatusCode = (int)statusCode;
|
||||
response.StatusCode = (int) statusCode;
|
||||
|
||||
if (output != null) {
|
||||
await response.WriteAsJsonAsync(output);
|
||||
}
|
||||
} catch (HttpException e) {
|
||||
Log.Error(e);
|
||||
response.StatusCode = (int)e.StatusCode;
|
||||
response.StatusCode = (int) e.StatusCode;
|
||||
await response.WriteAsync(e.Message);
|
||||
} catch (Exception e) {
|
||||
Log.Error(e);
|
||||
response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||
response.StatusCode = (int) HttpStatusCode.InternalServerError;
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -32,6 +32,7 @@ namespace DHT.Server.Endpoints {
|
||||
Id = json.RequireSnowflake("id", path),
|
||||
Server = serverId,
|
||||
Name = json.RequireString("name", path),
|
||||
ParentId = json.HasKey("parent") ? json.RequireSnowflake("parent", path) : null,
|
||||
Position = json.HasKey("position") ? json.RequireInt("position", path, min: 0) : null,
|
||||
Topic = json.HasKey("topic") ? json.RequireString("topic", path) : null,
|
||||
Nsfw = json.HasKey("nsfw") ? json.RequireBool("nsfw", path) : null
|
||||
|
@@ -22,17 +22,19 @@ namespace DHT.Server.Endpoints {
|
||||
throw new HttpException(HttpStatusCode.BadRequest, "Expected root element to be an array.");
|
||||
}
|
||||
|
||||
MessageFilter addedMessageIdFilter = new();
|
||||
Message[] messages = new Message[root.GetArrayLength()];
|
||||
var addedMessageIds = new HashSet<ulong>();
|
||||
var messages = new Message[root.GetArrayLength()];
|
||||
|
||||
int i = 0;
|
||||
foreach (JsonElement ele in root.EnumerateArray()) {
|
||||
var message = ReadMessage(ele, "message");
|
||||
messages[i++] = message;
|
||||
addedMessageIdFilter.MessageIds.Add(message.Id);
|
||||
addedMessageIds.Add(message.Id);
|
||||
}
|
||||
|
||||
bool anyNewMessages = Db.CountMessages(addedMessageIdFilter) < messages.Length;
|
||||
var addedMessageFilter = new MessageFilter { MessageIds = addedMessageIds };
|
||||
bool anyNewMessages = Db.CountMessages(addedMessageFilter) < messages.Length;
|
||||
|
||||
Db.AddMessages(messages);
|
||||
|
||||
return (HttpStatusCode.OK, anyNewMessages ? 1 : 0);
|
||||
@@ -56,7 +58,7 @@ namespace DHT.Server.Endpoints {
|
||||
Name = ele.RequireString("name", path),
|
||||
Type = ele.HasKey("type") ? ele.RequireString("type", path) : null,
|
||||
Url = ele.RequireString("url", path),
|
||||
Size = (ulong)ele.RequireLong("size", path)
|
||||
Size = (ulong) ele.RequireLong("size", path)
|
||||
});
|
||||
|
||||
private static IEnumerable<Embed> ReadEmbeds(JsonElement.ArrayEnumerator array, string path) => array.Select(ele => new Embed {
|
||||
|
@@ -18,7 +18,7 @@ namespace DHT.Server.Endpoints {
|
||||
throw new HttpException(HttpStatusCode.BadRequest, "Expected root element to be an array.");
|
||||
}
|
||||
|
||||
User[] users = new User[root.GetArrayLength()];
|
||||
var users = new User[root.GetArrayLength()];
|
||||
int i = 0;
|
||||
|
||||
foreach (JsonElement user in root.EnumerateArray()) {
|
||||
|
@@ -8,7 +8,7 @@
|
||||
<Authors>chylex</Authors>
|
||||
<Company>DiscordHistoryTracker</Company>
|
||||
<Product>DiscordHistoryTrackerServer</Product>
|
||||
<Version>31.0.0.0</Version>
|
||||
<Version>33.1.0.0</Version>
|
||||
<AssemblyVersion>$(Version)</AssemblyVersion>
|
||||
<FileVersion>$(Version)</FileVersion>
|
||||
<PackageVersion>$(Version)</PackageVersion>
|
||||
|
@@ -16,7 +16,7 @@ namespace DHT.Server.Service {
|
||||
|
||||
services.AddCors(cors => {
|
||||
cors.AddDefaultPolicy(builder => {
|
||||
builder.WithOrigins("https://discord.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader();
|
||||
builder.WithOrigins("https://discord.com", "https://discordapp.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
25
app/build.sh
Executable file
25
app/build.sh
Executable file
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
if [ ! -f "DiscordHistoryTracker.sln" ]; then
|
||||
echo "Missing DiscordHistoryTracker.sln in working directory!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
makezip() {
|
||||
pushd "./bin/$1"
|
||||
zip -9 -r "../$1.zip" .
|
||||
popd
|
||||
}
|
||||
|
||||
rm -rf "./bin"
|
||||
|
||||
configurations=(win-x64 linux-x64 osx-x64)
|
||||
|
||||
for cfg in ${configurations[@]}; do
|
||||
dotnet publish Desktop -c Release -r "$cfg" -o "./bin/$cfg" -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishReadyToRun=false -p:PublishTrimmed=true --self-contained true
|
||||
makezip "$cfg"
|
||||
done
|
||||
|
||||
dotnet publish Desktop -c Release -o "./bin/portable" --self-contained false
|
||||
makezip "portable"
|
BIN
app/empty.dht
Normal file
BIN
app/empty.dht
Normal file
Binary file not shown.
6
app/global.json
Normal file
6
app/global.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "5.0.0",
|
||||
"rollForward": "latestMinor"
|
||||
}
|
||||
}
|
15
app/minify.py
Normal file
15
app/minify.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# Python 3
|
||||
|
||||
import glob
|
||||
import os
|
||||
|
||||
uglifyjs = os.path.abspath("../lib/uglifyjs")
|
||||
input_dir = os.path.abspath("./Resources/Tracker/scripts")
|
||||
output_dir = os.path.abspath("./Resources/Tracker/scripts.min")
|
||||
|
||||
for file in glob.glob(input_dir + "/*.js"):
|
||||
name = os.path.basename(file)
|
||||
print("Minifying {0}...".format(name))
|
||||
os.system("{0} {1} -o {2}/{3}".format(uglifyjs, file, output_dir, name))
|
||||
|
||||
print("Done!")
|
Reference in New Issue
Block a user