mirror of
https://github.com/Tyrrrz/DiscordChatExporter.git
synced 2026-07-07 06:39:33 +02:00
Compare commits
71 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fa61bf75a | |||
| 1976e3ad08 | |||
| adbe544c57 | |||
| 6f4d1c3d77 | |||
| 33f71c1612 | |||
| 9b78472e05 | |||
| 1f6d1f21e6 | |||
| 918cb4820f | |||
| 32af1aa05d | |||
| dda32d8af2 | |||
| d1d82f975b | |||
| b1de9c4eca | |||
| 48ec4d085a | |||
| 668ac70fae | |||
| 0d1ce38489 | |||
| 666f2d8d4a | |||
| 2dd0742c1c | |||
| 69fe8af87a | |||
| e493357a9f | |||
| 492003c75a | |||
| 28175e2110 | |||
| a564906719 | |||
| 019278f6d4 | |||
| 5161593e0f | |||
| 847a05a269 | |||
| f09f30c7bd | |||
| 88727a1fe6 | |||
| bb98049df7 | |||
| e519bdcc6f | |||
| 1356d4483a | |||
| 4a3dc5c5ee | |||
| e665356890 | |||
| 7b614ed448 | |||
| 6531462220 | |||
| e89f2735a0 | |||
| 01d276a9dc | |||
| c446d4069a | |||
| ba5718aaf5 | |||
| 20ff4a15eb | |||
| 991dfccf3c | |||
| 524c86b8f2 | |||
| e4b0d60c40 | |||
| 65c5df89f4 | |||
| 659c499bd0 | |||
| b6fcbac030 | |||
| b3e2dd3994 | |||
| ba5790e312 | |||
| 2859a740eb | |||
| b88a1f8b47 | |||
| 78b44aed19 | |||
| 13925c69af | |||
| e22e1c03fb | |||
| bf5cedb646 | |||
| 17b0161ade | |||
| fa1e84b518 | |||
| 6d5ed9e9ca | |||
| bdaeea5512 | |||
| dddb13fcc5 | |||
| cacbb58683 | |||
| ca727e9f23 | |||
| fd15b62adf | |||
| 78d01b47b4 | |||
| daf38153f4 | |||
| ac91c536dd | |||
| 0dbd619244 | |||
| 0d3510222e | |||
| 083bdef419 | |||
| d620010e85 | |||
| beadc25e61 | |||
| 8bc29c4928 | |||
| 0b14952346 |
@@ -1,3 +1,45 @@
|
||||
### v2.10.2 (10-Mar-2019)
|
||||
|
||||
- [HTML] Updated message grouping algorithm to make it the same as in Discord. Removed "message group limit" setting and parameter.
|
||||
- [HTML] Added small margin at the end of the chatlog so it doesn't look like it was truncated.
|
||||
- [CLI] Fixed an issue where the app would crash if stdout was redirected. Progress will not be reported in such cases.
|
||||
|
||||
### v2.10.1 (06-Mar-2019)
|
||||
|
||||
- [HTML] Fixed an issue where multiple emojis on a single line would get rendered as one emoji.
|
||||
- [HTML] Fixed an issue where an open square bracket character would incorrectly render as an emoji.
|
||||
- [HTML] Added alt text to emoji images so that they will be rendered using default font when Twemoji images are not available.
|
||||
|
||||
### v2.10 (03-Mar-2019)
|
||||
|
||||
- [HTML] Reworked the entire markdown parsing engine which fixes numerous rendering inconsistencies (over 15 issues fixed).
|
||||
- [HTML] Added support for animated emojis.
|
||||
- [HTML] Standard emojis are now rendered using Twemoji, the same image set that Discord uses.
|
||||
- [HTML] Fixed an issue where video attachments would render incorrectly.
|
||||
- [HTML] Minor fixes in styling.
|
||||
- [GUI] Aggregated export progress is now shown in the taskbar.
|
||||
- [GUI] Checkmarks are now displayed next to channels that are selected.
|
||||
- [CLI] Added progress reporting when exporting chat logs.
|
||||
|
||||
### v2.9.1 (10-Feb-2019)
|
||||
|
||||
- Fixed an issue where some of the last messages in a channel would sometimes not get exported.
|
||||
|
||||
### v2.9 (09-Feb-2019)
|
||||
|
||||
- Added categories to channel list in GUI. Channels are now also grouped by category.
|
||||
- Added ability to export multiple channels at once in GUI by selecting them with shift or ctrl keys.
|
||||
- Added CLI command to export all available channels in a guild (`exportguild`).
|
||||
- Added CLI command to export all direct message channels (`exportdm`).
|
||||
- Added retry policy for 503 status code errors to prevent random crashes.
|
||||
- Changed how channels are exported in GUI. Now you need to select them first and then click a button to export. You can also double click a single channel to export it as before.
|
||||
- Improved default file name generation by adding date ranges and channel ID to the file name.
|
||||
- Improved naming of files exported with partitioning.
|
||||
- Improved usage instructions.
|
||||
- Improved GUI layout and styling.
|
||||
- Fixed an issue where dialogs would sometimes appear over other windows.
|
||||
- Fixed an issue where launching DiscordChatExporter from Windows Start Menu would make it crash.
|
||||
|
||||
### v2.8 (03-Nov-2018)
|
||||
|
||||
- Added support for partitioning which lets you split the output into multiple files by setting the partition message limit (`-p` parameter for CLI).
|
||||
|
||||
@@ -2,10 +2,12 @@ New-Item "$PSScriptRoot\bin" -ItemType Directory -Force
|
||||
|
||||
# GUI
|
||||
$files = @()
|
||||
$files += Get-Item -Path "$PSScriptRoot\..\License.txt"
|
||||
$files += Get-ChildItem -Path "$PSScriptRoot\..\DiscordChatExporter.Gui\bin\Release\*" -Include "*.exe", "*.dll", "*.config"
|
||||
$files | Compress-Archive -DestinationPath "$PSScriptRoot\bin\DiscordChatExporter.zip" -Force
|
||||
|
||||
# CLI
|
||||
$files = @()
|
||||
$files += Get-Item -Path "$PSScriptRoot\..\License.txt"
|
||||
$files += Get-ChildItem -Path "$PSScriptRoot\..\DiscordChatExporter.Cli\bin\Release\net461\*" -Include "*.exe", "*.dll", "*.config"
|
||||
$files | Compress-Archive -DestinationPath "$PSScriptRoot\bin\DiscordChatExporter.CLI.zip" -Force
|
||||
@@ -1,26 +1,24 @@
|
||||
using CommonServiceLocator;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using GalaSoft.MvvmLight.Ioc;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using StyletIoC;
|
||||
|
||||
namespace DiscordChatExporter.Cli
|
||||
{
|
||||
public class Container
|
||||
public static class Container
|
||||
{
|
||||
public Container()
|
||||
{
|
||||
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
|
||||
SimpleIoc.Default.Reset();
|
||||
public static IContainer Instance { get; }
|
||||
|
||||
// Services
|
||||
SimpleIoc.Default.Register<IDataService, DataService>();
|
||||
SimpleIoc.Default.Register<IExportService, ExportService>();
|
||||
SimpleIoc.Default.Register<ISettingsService, SettingsService>();
|
||||
SimpleIoc.Default.Register<IUpdateService, UpdateService>();
|
||||
}
|
||||
|
||||
public T Resolve<T>(string key = null)
|
||||
static Container()
|
||||
{
|
||||
return ServiceLocator.Current.GetInstance<T>(key);
|
||||
var builder = new StyletIoCBuilder();
|
||||
|
||||
// Autobind services in the .Core assembly
|
||||
builder.Autobind(typeof(DataService).Assembly);
|
||||
|
||||
// Bind settings as singleton
|
||||
builder.Bind<SettingsService>().ToSelf().InSingletonScope();
|
||||
|
||||
// Set instance
|
||||
Instance = builder.BuildContainer();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,15 @@
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net461</TargetFramework>
|
||||
<Version>2.8</Version>
|
||||
<Version>2.10.2</Version>
|
||||
<Company>Tyrrrz</Company>
|
||||
<Copyright>Copyright (c) 2017-2018 Alexey Golub</Copyright>
|
||||
<Copyright>Copyright (c) Alexey Golub</Copyright>
|
||||
<ApplicationIcon>..\favicon.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommandLineParser" Version="2.2.1" />
|
||||
<PackageReference Include="CommonServiceLocator" Version="2.0.3" />
|
||||
<PackageReference Include="MvvmLightLibs" Version="5.4.1" />
|
||||
<PackageReference Include="CommandLineParser" Version="2.3.0" />
|
||||
<PackageReference Include="Stylet" Version="1.1.22" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.5.1" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Internal
|
||||
{
|
||||
internal class InlineProgress : IProgress<double>, IDisposable
|
||||
{
|
||||
private readonly int _posX;
|
||||
private readonly int _posY;
|
||||
|
||||
public InlineProgress()
|
||||
{
|
||||
// If output is not redirected - save initial cursor position
|
||||
if (!Console.IsOutputRedirected)
|
||||
{
|
||||
_posX = Console.CursorLeft;
|
||||
_posY = Console.CursorTop;
|
||||
}
|
||||
}
|
||||
|
||||
public void Report(double progress)
|
||||
{
|
||||
// If output is not redirected - reset cursor position and write progress
|
||||
if (!Console.IsOutputRedirected)
|
||||
{
|
||||
Console.SetCursorPosition(_posX, _posY);
|
||||
Console.WriteLine($"{progress:P1}");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// If output is not redirected - reset cursor position
|
||||
if (!Console.IsOutputRedirected)
|
||||
Console.SetCursorPosition(_posX, _posY);
|
||||
|
||||
// Inform about completion
|
||||
Console.WriteLine("Completed ✓");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,28 +11,25 @@ namespace DiscordChatExporter.Cli
|
||||
private static void PrintTokenHelp()
|
||||
{
|
||||
Console.WriteLine("# To get user token:");
|
||||
Console.WriteLine(" 1. Open Discord app");
|
||||
Console.WriteLine(" 2. Log in if you haven't");
|
||||
Console.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
|
||||
Console.WriteLine(" 4. Press Ctrl+R to trigger reload");
|
||||
Console.WriteLine(" 5. Navigate to the Application tab");
|
||||
Console.WriteLine(" 6. Select \"Local Storage\" > \"https://discordapp.com\" on the left");
|
||||
Console.WriteLine(" 7. Find \"token\" under key and copy the value");
|
||||
Console.WriteLine(" 1. Open Discord");
|
||||
Console.WriteLine(" 2. Press Ctrl+Shift+I to show developer tools");
|
||||
Console.WriteLine(" 3. Press Ctrl+R to reload");
|
||||
Console.WriteLine(" 4. Navigate to the Application tab");
|
||||
Console.WriteLine(" 5. Select \"Local Storage\" > \"https://discordapp.com\" on the left");
|
||||
Console.WriteLine(" 6. Find \"token\" under key and copy the value");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("# To get bot token:");
|
||||
Console.WriteLine(" 1. Go to Discord developer portal");
|
||||
Console.WriteLine(" 2. Log in if you haven't");
|
||||
Console.WriteLine(" 3. Open your application's settings");
|
||||
Console.WriteLine(" 4. Navigate to the Bot section on the left");
|
||||
Console.WriteLine(" 5. Under Token click Copy");
|
||||
Console.WriteLine(" 2. Open your application's settings");
|
||||
Console.WriteLine(" 3. Navigate to the Bot section on the left");
|
||||
Console.WriteLine(" 4. Under Token click Copy");
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("# To get guild or channel ID:");
|
||||
Console.WriteLine(" 1. Open Discord app");
|
||||
Console.WriteLine(" 2. Log in if you haven't");
|
||||
Console.WriteLine(" 3. Open Settings");
|
||||
Console.WriteLine(" 4. Go to Appearance section");
|
||||
Console.WriteLine(" 5. Enable Developer Mode");
|
||||
Console.WriteLine(" 6. Right click on the desired guild or channel and click Copy ID");
|
||||
Console.WriteLine(" 1. Open Discord");
|
||||
Console.WriteLine(" 2. Open Settings");
|
||||
Console.WriteLine(" 3. Go to Appearance section");
|
||||
Console.WriteLine(" 4. Enable Developer Mode");
|
||||
Console.WriteLine(" 5. Right click on the desired guild or channel and click Copy ID");
|
||||
}
|
||||
|
||||
public static void Main(string[] args)
|
||||
@@ -40,7 +37,9 @@ namespace DiscordChatExporter.Cli
|
||||
// Get all verb types
|
||||
var verbTypes = new[]
|
||||
{
|
||||
typeof(ExportChatOptions),
|
||||
typeof(ExportChannelOptions),
|
||||
typeof(ExportDirectMessagesOptions),
|
||||
typeof(ExportGuildOptions),
|
||||
typeof(GetChannelsOptions),
|
||||
typeof(GetDirectMessageChannelsOptions),
|
||||
typeof(GetGuildsOptions)
|
||||
@@ -50,7 +49,9 @@ namespace DiscordChatExporter.Cli
|
||||
var parsedArgs = Parser.Default.ParseArguments(args, verbTypes);
|
||||
|
||||
// Execute commands
|
||||
parsedArgs.WithParsed<ExportChatOptions>(o => new ExportChatVerb(o).Execute());
|
||||
parsedArgs.WithParsed<ExportChannelOptions>(o => new ExportChannelVerb(o).Execute());
|
||||
parsedArgs.WithParsed<ExportDirectMessagesOptions>(o => new ExportDirectMessagesVerb(o).Execute());
|
||||
parsedArgs.WithParsed<ExportGuildOptions>(o => new ExportGuildVerb(o).Execute());
|
||||
parsedArgs.WithParsed<GetChannelsOptions>(o => new GetChannelsVerb(o).Execute());
|
||||
parsedArgs.WithParsed<GetDirectMessageChannelsOptions>(o => new GetDirectMessageChannelsVerb(o).Execute());
|
||||
parsedArgs.WithParsed<GetGuildsOptions>(o => new GetGuildsVerb(o).Execute());
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Cli.Internal;
|
||||
using DiscordChatExporter.Cli.Verbs.Options;
|
||||
using DiscordChatExporter.Core.Helpers;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs
|
||||
{
|
||||
public class ExportChannelVerb : Verb<ExportChannelOptions>
|
||||
{
|
||||
public ExportChannelVerb(ExportChannelOptions options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get services
|
||||
var settingsService = Container.Instance.Get<SettingsService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
var exportService = Container.Instance.Get<ExportService>();
|
||||
|
||||
// Configure settings
|
||||
if (Options.DateFormat.IsNotBlank())
|
||||
settingsService.DateFormat = Options.DateFormat;
|
||||
|
||||
// Track progress
|
||||
Console.Write($"Exporting channel [{Options.ChannelId}]... ");
|
||||
using (var progress = new InlineProgress())
|
||||
{
|
||||
// Get chat log
|
||||
var chatLog = await dataService.GetChatLogAsync(Options.GetToken(), Options.ChannelId,
|
||||
Options.After, Options.Before, progress);
|
||||
|
||||
// Generate file path if not set or is a directory
|
||||
var filePath = Options.OutputPath;
|
||||
if (filePath.IsBlank() || ExportHelper.IsDirectoryPath(filePath))
|
||||
{
|
||||
// Generate default file name
|
||||
var fileName = ExportHelper.GetDefaultExportFileName(Options.ExportFormat, chatLog.Guild,
|
||||
chatLog.Channel, Options.After, Options.Before);
|
||||
|
||||
// Combine paths
|
||||
filePath = Path.Combine(filePath ?? "", fileName);
|
||||
}
|
||||
|
||||
// Export
|
||||
exportService.ExportChatLog(chatLog, filePath, Options.ExportFormat, Options.PartitionLimit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Cli.Verbs.Options;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs
|
||||
{
|
||||
public class ExportChatVerb : Verb<ExportChatOptions>
|
||||
{
|
||||
public ExportChatVerb(ExportChatOptions options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get services
|
||||
var container = new Container();
|
||||
var settingsService = container.Resolve<ISettingsService>();
|
||||
var dataService = container.Resolve<IDataService>();
|
||||
var exportService = container.Resolve<IExportService>();
|
||||
|
||||
// Configure settings
|
||||
if (Options.DateFormat.IsNotBlank())
|
||||
settingsService.DateFormat = Options.DateFormat;
|
||||
if (Options.MessageGroupLimit > 0)
|
||||
settingsService.MessageGroupLimit = Options.MessageGroupLimit;
|
||||
|
||||
// Get chat log
|
||||
var chatLog = await dataService.GetChatLogAsync(Options.GetToken(), Options.ChannelId,
|
||||
Options.After, Options.Before);
|
||||
|
||||
// Generate file path if not set
|
||||
var filePath = Options.FilePath;
|
||||
if (filePath == null || filePath.EndsWith("/") || filePath.EndsWith("\\"))
|
||||
{
|
||||
filePath += $"{chatLog.Guild.Name} - {chatLog.Channel.Name}.{Options.ExportFormat.GetFileExtension()}"
|
||||
.Replace(Path.GetInvalidFileNameChars(), '_');
|
||||
}
|
||||
|
||||
// Export
|
||||
exportService.ExportChatLog(chatLog, filePath, Options.ExportFormat, Options.PartitionLimit);
|
||||
|
||||
// Print result
|
||||
Console.WriteLine($"Exported chat to [{filePath}]");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Cli.Internal;
|
||||
using DiscordChatExporter.Cli.Verbs.Options;
|
||||
using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Helpers;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs
|
||||
{
|
||||
public class ExportDirectMessagesVerb : Verb<ExportDirectMessagesOptions>
|
||||
{
|
||||
public ExportDirectMessagesVerb(ExportDirectMessagesOptions options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get services
|
||||
var settingsService = Container.Instance.Get<SettingsService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
var exportService = Container.Instance.Get<ExportService>();
|
||||
|
||||
// Configure settings
|
||||
if (Options.DateFormat.IsNotBlank())
|
||||
settingsService.DateFormat = Options.DateFormat;
|
||||
|
||||
// Get channels
|
||||
var channels = await dataService.GetDirectMessageChannelsAsync(Options.GetToken());
|
||||
|
||||
// Order channels
|
||||
channels = channels.OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Loop through channels
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Track progress
|
||||
Console.Write($"Exporting channel [{channel.Name}]... ");
|
||||
using (var progress = new InlineProgress())
|
||||
{
|
||||
// Get chat log
|
||||
var chatLog = await dataService.GetChatLogAsync(Options.GetToken(), channel,
|
||||
Options.After, Options.Before, progress);
|
||||
|
||||
// Generate default file name
|
||||
var fileName = ExportHelper.GetDefaultExportFileName(Options.ExportFormat, chatLog.Guild,
|
||||
chatLog.Channel, Options.After, Options.Before);
|
||||
|
||||
// Generate file path
|
||||
var filePath = Path.Combine(Options.OutputPath ?? "", fileName);
|
||||
|
||||
// Export
|
||||
exportService.ExportChatLog(chatLog, filePath, Options.ExportFormat, Options.PartitionLimit);
|
||||
}
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
Console.Error.WriteLine("You don't have access to this channel");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
Console.Error.WriteLine("This channel doesn't exist");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Cli.Internal;
|
||||
using DiscordChatExporter.Cli.Verbs.Options;
|
||||
using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Helpers;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs
|
||||
{
|
||||
public class ExportGuildVerb : Verb<ExportGuildOptions>
|
||||
{
|
||||
public ExportGuildVerb(ExportGuildOptions options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get services
|
||||
var settingsService = Container.Instance.Get<SettingsService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
var exportService = Container.Instance.Get<ExportService>();
|
||||
|
||||
// Configure settings
|
||||
if (Options.DateFormat.IsNotBlank())
|
||||
settingsService.DateFormat = Options.DateFormat;
|
||||
|
||||
// Get channels
|
||||
var channels = await dataService.GetGuildChannelsAsync(Options.GetToken(), Options.GuildId);
|
||||
|
||||
// Filter and order channels
|
||||
channels = channels.Where(c => c.Type == ChannelType.GuildTextChat).OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Loop through channels
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Track progress
|
||||
Console.Write($"Exporting channel [{channel.Name}]... ");
|
||||
using (var progress = new InlineProgress())
|
||||
{
|
||||
// Get chat log
|
||||
var chatLog = await dataService.GetChatLogAsync(Options.GetToken(), channel,
|
||||
Options.After, Options.Before, progress);
|
||||
|
||||
// Generate default file name
|
||||
var fileName = ExportHelper.GetDefaultExportFileName(Options.ExportFormat, chatLog.Guild,
|
||||
chatLog.Channel, Options.After, Options.Before);
|
||||
|
||||
// Generate file path
|
||||
var filePath = Path.Combine(Options.OutputPath ?? "", fileName);
|
||||
|
||||
// Export
|
||||
exportService.ExportChatLog(chatLog, filePath, Options.ExportFormat, Options.PartitionLimit);
|
||||
}
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
Console.Error.WriteLine("You don't have access to this channel");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
Console.Error.WriteLine("This channel doesn't exist");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Cli.Verbs.Options;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs
|
||||
{
|
||||
@@ -18,15 +17,16 @@ namespace DiscordChatExporter.Cli.Verbs
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get data service
|
||||
var container = new Container();
|
||||
var dataService = container.Resolve<IDataService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
|
||||
// Get channels
|
||||
var channels = await dataService.GetGuildChannelsAsync(Options.GetToken(), Options.GuildId);
|
||||
|
||||
// Filter and order channels
|
||||
channels = channels.Where(c => c.Type == ChannelType.GuildTextChat).OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Print result
|
||||
foreach (var channel in channels.Where(c => c.Type.IsEither(ChannelType.GuildTextChat))
|
||||
.OrderBy(c => c.Name))
|
||||
foreach (var channel in channels)
|
||||
Console.WriteLine($"{channel.Id} | {channel.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,16 @@ namespace DiscordChatExporter.Cli.Verbs
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get data service
|
||||
var container = new Container();
|
||||
var dataService = container.Resolve<IDataService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
|
||||
// Get channels
|
||||
var channels = await dataService.GetDirectMessageChannelsAsync(Options.GetToken());
|
||||
|
||||
// Order channels
|
||||
channels = channels.OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Print result
|
||||
foreach (var channel in channels.OrderBy(c => c.Name))
|
||||
foreach (var channel in channels)
|
||||
Console.WriteLine($"{channel.Id} | {channel.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,16 @@ namespace DiscordChatExporter.Cli.Verbs
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
// Get data service
|
||||
var container = new Container();
|
||||
var dataService = container.Resolve<IDataService>();
|
||||
var dataService = Container.Instance.Get<DataService>();
|
||||
|
||||
// Get guilds
|
||||
var guilds = await dataService.GetUserGuildsAsync(Options.GetToken());
|
||||
|
||||
// Order guilds
|
||||
guilds = guilds.OrderBy(g => g.Name).ToArray();
|
||||
|
||||
// Print result
|
||||
foreach (var guild in guilds.OrderBy(g => g.Name))
|
||||
foreach (var guild in guilds)
|
||||
Console.WriteLine($"{guild.Id} | {guild.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using CommandLine;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
{
|
||||
[Verb("export", HelpText = "Export channel.")]
|
||||
public class ExportChannelOptions : ExportOptions
|
||||
{
|
||||
[Option('c', "channel", Required = true, HelpText = "Channel ID.")]
|
||||
public string ChannelId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using CommandLine;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
{
|
||||
[Verb("exportdm", HelpText = "Export all direct message channels.")]
|
||||
public class ExportDirectMessagesOptions : ExportOptions
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using CommandLine;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
{
|
||||
[Verb("exportguild", HelpText = "Export all channels within a given guild.")]
|
||||
public class ExportGuildOptions : ExportOptions
|
||||
{
|
||||
[Option('g', "guild", Required = true, HelpText = "Guild ID.")]
|
||||
public string GuildId { get; set; }
|
||||
}
|
||||
}
|
||||
+3
-10
@@ -4,17 +4,13 @@ using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
{
|
||||
[Verb("export", HelpText = "Export channel chat log to a file.")]
|
||||
public class ExportChatOptions : TokenOptions
|
||||
public abstract class ExportOptions : TokenOptions
|
||||
{
|
||||
[Option('c', "channel", Required = true, HelpText = "Channel ID.")]
|
||||
public string ChannelId { get; set; }
|
||||
|
||||
[Option('f', "format", Default = ExportFormat.HtmlDark, HelpText = "Output file format.")]
|
||||
public ExportFormat ExportFormat { get; set; }
|
||||
|
||||
[Option('o', "output", Default = null, HelpText = "Output file path.")]
|
||||
public string FilePath { get; set; }
|
||||
[Option('o', "output", Default = null, HelpText = "Output file or directory path.")]
|
||||
public string OutputPath { get; set; }
|
||||
|
||||
[Option("after", Default = null, HelpText = "Limit to messages sent after this date.")]
|
||||
public DateTime? After { get; set; }
|
||||
@@ -27,8 +23,5 @@ namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
|
||||
[Option("dateformat", Default = null, HelpText = "Date format used in output.")]
|
||||
public string DateFormat { get; set; }
|
||||
|
||||
[Option("grouplimit", Default = 0, HelpText = "Message group limit.")]
|
||||
public int MessageGroupLimit { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Verbs.Options
|
||||
{
|
||||
public class TokenOptions
|
||||
public abstract class TokenOptions
|
||||
{
|
||||
[Option('t', "token", Required = true, HelpText = "Authorization token.")]
|
||||
public string TokenValue { get; set; }
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net461</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Sprache" Version="2.2.0" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.5.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class EmojiNode : Node
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public bool IsAnimated { get; }
|
||||
|
||||
public bool IsCustomEmoji => Id.IsNotBlank();
|
||||
|
||||
public EmojiNode(string lexeme, string id, string name, bool isAnimated)
|
||||
: base(lexeme)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IsAnimated = isAnimated;
|
||||
}
|
||||
|
||||
public EmojiNode(string lexeme, string name)
|
||||
: this(lexeme, null, name, false)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Emoji> {Name}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class FormattedNode : Node
|
||||
{
|
||||
public string Token { get; }
|
||||
|
||||
public TextFormatting Formatting { get; }
|
||||
|
||||
public IReadOnlyList<Node> Children { get; }
|
||||
|
||||
public FormattedNode(string lexeme, string token, TextFormatting formatting, IReadOnlyList<Node> children)
|
||||
: base(lexeme)
|
||||
{
|
||||
Token = token;
|
||||
Formatting = formatting;
|
||||
Children = children;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Formatting}> ({Children.Count} direct children)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class InlineCodeBlockNode : Node
|
||||
{
|
||||
public string Code { get; }
|
||||
|
||||
public InlineCodeBlockNode(string lexeme, string code)
|
||||
: base(lexeme)
|
||||
{
|
||||
Code = code;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Code> {Code}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using Sprache;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown.Internal
|
||||
{
|
||||
// The following parsing logic is meant to replicate Discord's markdown grammar as close as possible
|
||||
internal static class Grammar
|
||||
{
|
||||
/* Formatting */
|
||||
|
||||
// Capture until the earliest double asterisk not followed by an asterisk
|
||||
private static readonly Parser<Node> BoldFormattedNode =
|
||||
Parse.RegexMatch(new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "**", TextFormatting.Bold, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Capture until the earliest single asterisk not preceded or followed by an asterisk
|
||||
// Can't have whitespace right after opening or right before closing asterisk
|
||||
private static readonly Parser<Node> ItalicFormattedNode =
|
||||
Parse.RegexMatch(new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "*", TextFormatting.Italic, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Can't have underscores inside
|
||||
// Can't have word characters right after closing underscore
|
||||
private static readonly Parser<Node> ItalicAltFormattedNode =
|
||||
Parse.RegexMatch(new Regex("_([^_]+?)_(?!\\w)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "_", TextFormatting.Italic, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Treated as a separate entity for simplicity
|
||||
// Capture until the earliest triple asterisk not preceded or followed by an asterisk
|
||||
private static readonly Parser<Node> ItalicBoldFormattedNode =
|
||||
Parse.RegexMatch(new Regex("\\*(\\*\\*(?:.+?)\\*\\*)\\*(?!\\*)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "*", TextFormatting.Italic, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Capture until the earliest double underscore not followed by an underscore
|
||||
private static readonly Parser<Node> UnderlineFormattedNode =
|
||||
Parse.RegexMatch(new Regex("__(.+?)__(?!_)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "__", TextFormatting.Underline, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Treated as a separate entity for simplicity
|
||||
// Capture until the earliest triple underscore not preceded or followed by an underscore
|
||||
private static readonly Parser<Node> ItalicUnderlineFormattedNode =
|
||||
Parse.RegexMatch(new Regex("_(__(?:.+?)__)_(?!_)", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "_", TextFormatting.Italic, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Strikethrough is safe
|
||||
private static readonly Parser<Node> StrikethroughFormattedNode =
|
||||
Parse.RegexMatch(new Regex("~~(.+?)~~", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "~~", TextFormatting.Strikethrough, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Spoiler is safe
|
||||
private static readonly Parser<Node> SpoilerFormattedNode =
|
||||
Parse.RegexMatch(new Regex("\\|\\|(.+?)\\|\\|", RegexOptions.Singleline))
|
||||
.Select(m => new FormattedNode(m.Value, "||", TextFormatting.Spoiler, BuildTree(m.Groups[1].Value)));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyFormattedNode =
|
||||
ItalicBoldFormattedNode.Or(ItalicUnderlineFormattedNode)
|
||||
.Or(BoldFormattedNode).Or(ItalicFormattedNode)
|
||||
.Or(UnderlineFormattedNode).Or(ItalicAltFormattedNode)
|
||||
.Or(StrikethroughFormattedNode).Or(SpoilerFormattedNode);
|
||||
|
||||
/* Code blocks */
|
||||
|
||||
// Can't have backticks inside and surrounding whitespace is trimmed
|
||||
private static readonly Parser<Node> InlineCodeBlockNode =
|
||||
Parse.RegexMatch(new Regex("`\\s*([^`]+?)\\s*`", RegexOptions.Singleline))
|
||||
.Select(m => new InlineCodeBlockNode(m.Value, m.Groups[1].Value));
|
||||
|
||||
// The first word is a language identifier if it's the only word followed by a newline, the rest is code
|
||||
private static readonly Parser<Node> MultilineCodeBlockNode =
|
||||
Parse.RegexMatch(new Regex("```(?:(\\w*?)?(?:\\s*?\\n))?(.+?)```", RegexOptions.Singleline))
|
||||
.Select(m => new MultilineCodeBlockNode(m.Value, m.Groups[1].Value, m.Groups[2].Value));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyCodeBlockNode = MultilineCodeBlockNode.Or(InlineCodeBlockNode);
|
||||
|
||||
/* Mentions */
|
||||
|
||||
// @everyone or @here
|
||||
private static readonly Parser<Node> MetaMentionNode = Parse.RegexMatch("@(everyone|here)")
|
||||
.Select(m => new MentionNode(m.Value, m.Groups[1].Value, MentionType.Meta));
|
||||
|
||||
// <@123456> or <@!123456>
|
||||
private static readonly Parser<Node> UserMentionNode = Parse.RegexMatch("<@!?(\\d+)>")
|
||||
.Select(m => new MentionNode(m.Value, m.Groups[1].Value, MentionType.User));
|
||||
|
||||
// <#123456>
|
||||
private static readonly Parser<Node> ChannelMentionNode = Parse.RegexMatch("<#(\\d+)>")
|
||||
.Select(m => new MentionNode(m.Value, m.Groups[1].Value, MentionType.Channel));
|
||||
|
||||
// <@&123456>
|
||||
private static readonly Parser<Node> RoleMentionNode = Parse.RegexMatch("<@&(\\d+)>")
|
||||
.Select(m => new MentionNode(m.Value, m.Groups[1].Value, MentionType.Role));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyMentionNode =
|
||||
MetaMentionNode.Or(UserMentionNode).Or(ChannelMentionNode).Or(RoleMentionNode);
|
||||
|
||||
/* Emojis */
|
||||
|
||||
// Matches all standard unicode emojis
|
||||
private static readonly Parser<Node> StandardEmojiNode = Parse.RegexMatch(
|
||||
"([\\u2700-\\u27bf]|" +
|
||||
"(?:\\ud83c[\\udde6-\\uddff]){2}|" +
|
||||
"[\\ud800-\\udbff][\\udc00-\\udfff]|" +
|
||||
"[\\u0023-\\u0039]\\u20e3|" +
|
||||
"\\u3299|\\u3297|\\u303d|\\u3030|\\u24c2|\\ud83c[\\udd70-\\udd71]|\\ud83c[\\udd7e-\\udd7f]|\\ud83c\\udd8e|\\ud83c[\\udd91-\\udd9a]|\\ud83c[\\udde6-\\uddff]|" +
|
||||
"\\ud83c[\\ude01-\\ude02]|\\ud83c\\ude1a|\\ud83c\\ude2f|\\ud83c[\\ude32-\\ude3a]|\\ud83c[\\ude50-\\ude51]|\\u203c|\\u2049|[\\u25aa-\\u25ab]|" +
|
||||
"\\u25b6|\\u25c0|[\\u25fb-\\u25fe]|\\u00a9|\\u00ae|\\u2122|\\u2139|\\ud83c\\udc04|[\\u2600-\\u26FF]|\\u2b05|\\u2b06|\\u2b07|\\u2b1b|\\u2b1c|\\u2b50|" +
|
||||
"\\u2b55|\\u231a|\\u231b|\\u2328|\\u23cf|[\\u23e9-\\u23f3]|[\\u23f8-\\u23fa]|\\ud83c\\udccf|\\u2934|\\u2935|[\\u2190-\\u21ff])")
|
||||
.Select(m => new EmojiNode(m.Value, m.Groups[1].Value));
|
||||
|
||||
// <:lul:123456> or <a:lul:123456>
|
||||
private static readonly Parser<Node> CustomEmojiNode = Parse.RegexMatch("<(a)?:(.+?):(\\d+)>")
|
||||
.Select(m => new EmojiNode(m.Value, m.Groups[3].Value, m.Groups[2].Value, m.Groups[1].Value.IsNotBlank()));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyEmojiNode = StandardEmojiNode.Or(CustomEmojiNode);
|
||||
|
||||
/* Links */
|
||||
|
||||
// [title](link)
|
||||
private static readonly Parser<Node> TitledLinkNode = Parse.RegexMatch("\\[(.+?)\\]\\((.+?)\\)")
|
||||
.Select(m => new LinkNode(m.Value, m.Groups[2].Value, m.Groups[1].Value));
|
||||
|
||||
// Starts with http:// or https://, stops at the last non-whitespace character followed by whitespace or punctuation character
|
||||
private static readonly Parser<Node> AutoLinkNode = Parse.RegexMatch("(https?://\\S*[^\\.,:;\"\'\\s])")
|
||||
.Select(m => new LinkNode(m.Value, m.Groups[1].Value));
|
||||
|
||||
// Autolink surrounded by angular brackets
|
||||
private static readonly Parser<Node> HiddenLinkNode = Parse.RegexMatch("<(https?://\\S*[^\\.,:;\"\'\\s])>")
|
||||
.Select(m => new LinkNode(m.Value, m.Groups[1].Value));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyLinkNode = TitledLinkNode.Or(HiddenLinkNode).Or(AutoLinkNode);
|
||||
|
||||
/* Text */
|
||||
|
||||
// Shrug is an exception and needs to be exempt from formatting
|
||||
private static readonly Parser<Node> ShrugTextNode =
|
||||
Parse.String("¯\\_(ツ)_/¯").Text().Select(s => new TextNode(s));
|
||||
|
||||
// Backslash escapes any following unicode surrogate pair
|
||||
private static readonly Parser<Node> EscapedSurrogateTextNode =
|
||||
from slash in Parse.Char('\\')
|
||||
from high in Parse.AnyChar.Where(char.IsHighSurrogate)
|
||||
from low in Parse.AnyChar
|
||||
let lexeme = $"{slash}{high}{low}"
|
||||
let text = $"{high}{low}"
|
||||
select new TextNode(lexeme, text);
|
||||
|
||||
// Backslash escapes any following non-whitespace character except for digits and latin letters
|
||||
private static readonly Parser<Node> EscapedTextNode =
|
||||
Parse.RegexMatch("\\\\([^a-zA-Z0-9\\s])").Select(m => new TextNode(m.Value, m.Groups[1].Value));
|
||||
|
||||
// Combinator, order matters
|
||||
private static readonly Parser<Node> AnyTextNode = ShrugTextNode.Or(EscapedSurrogateTextNode).Or(EscapedTextNode);
|
||||
|
||||
/* Aggregator and fallback */
|
||||
|
||||
// Any node recognized by above patterns
|
||||
private static readonly Parser<Node> AnyRecognizedNode = AnyFormattedNode.Or(AnyCodeBlockNode)
|
||||
.Or(AnyMentionNode).Or(AnyEmojiNode).Or(AnyLinkNode).Or(AnyTextNode);
|
||||
|
||||
// Any node not recognized by above patterns (treated as plain text)
|
||||
private static readonly Parser<Node> FallbackNode =
|
||||
Parse.AnyChar.Except(AnyRecognizedNode).AtLeastOnce().Text().Select(s => new TextNode(s));
|
||||
|
||||
// Any node
|
||||
private static readonly Parser<Node> AnyNode = AnyRecognizedNode.Or(FallbackNode);
|
||||
|
||||
// Entry point
|
||||
public static IReadOnlyList<Node> BuildTree(string input) => AnyNode.Many().Parse(input).ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class LinkNode : Node
|
||||
{
|
||||
public string Url { get; }
|
||||
|
||||
public string Title { get; }
|
||||
|
||||
public LinkNode(string lexeme, string url, string title)
|
||||
: base(lexeme)
|
||||
{
|
||||
Url = url;
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public LinkNode(string lexeme, string url) : this(lexeme, url, url)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Link> {Title}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Markdown.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public static class MarkdownParser
|
||||
{
|
||||
public static IReadOnlyList<Node> Parse(string input) => Grammar.BuildTree(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class MentionNode : Node
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public MentionType Type { get; }
|
||||
|
||||
public MentionNode(string lexeme, string id, MentionType type)
|
||||
: base(lexeme)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Type} mention> {Id}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public enum MentionType
|
||||
{
|
||||
Meta,
|
||||
User,
|
||||
Channel,
|
||||
Role
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class MultilineCodeBlockNode : Node
|
||||
{
|
||||
public string Language { get; }
|
||||
|
||||
public string Code { get; }
|
||||
|
||||
public MultilineCodeBlockNode(string lexeme, string language, string code)
|
||||
: base(lexeme)
|
||||
{
|
||||
Language = language;
|
||||
Code = code;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Code [{Language}]> {Code}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public abstract class Node
|
||||
{
|
||||
public string Lexeme { get; }
|
||||
|
||||
protected Node(string lexeme)
|
||||
{
|
||||
Lexeme = lexeme;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public enum TextFormatting
|
||||
{
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
Strikethrough,
|
||||
Spoiler
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
public class TextNode : Node
|
||||
{
|
||||
public string Text { get; }
|
||||
|
||||
public TextNode(string lexeme, string text)
|
||||
: base(lexeme)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
|
||||
public TextNode(string text) : this(text, text)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,17 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net461</TargetFramework>
|
||||
<Version>2.8</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\PlainText.txt" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlDark.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlLight.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Html\Core.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Html\Shared.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Html\DarkTheme.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Html\LightTheme.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Csv.csv" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\PlainText\Template.txt" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlDark\Template.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlLight\Template.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlShared\Main.html" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlShared\Main.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlDark\Theme.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\HtmlLight\Theme.css" />
|
||||
<EmbeddedResource Include="Resources\ExportTemplates\Csv\Template.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -21,12 +20,17 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
|
||||
<PackageReference Include="Onova" Version="2.1.0" />
|
||||
<PackageReference Include="Polly" Version="6.0.1" />
|
||||
<PackageReference Include="Scriban" Version="1.2.1" />
|
||||
<PackageReference Include="ByteSize" Version="1.3.0" />
|
||||
<PackageReference Include="Failsafe" Version="1.1.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
|
||||
<PackageReference Include="Onova" Version="2.2.0" />
|
||||
<PackageReference Include="Scriban" Version="1.2.9" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.5.1" />
|
||||
<PackageReference Include="Tyrrrz.Settings" Version="1.3.2" />
|
||||
<PackageReference Include="Tyrrrz.Settings" Version="1.3.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Markdown\DiscordChatExporter.Core.Markdown.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Helpers
|
||||
{
|
||||
public static class ExportHelper
|
||||
{
|
||||
public static bool IsDirectoryPath(string path)
|
||||
=> path.Last() == Path.DirectorySeparatorChar ||
|
||||
path.Last() == Path.AltDirectorySeparatorChar ||
|
||||
Path.GetExtension(path).IsBlank();
|
||||
|
||||
public static string GetDefaultExportFileName(ExportFormat format, Guild guild, Channel channel,
|
||||
DateTime? from = null, DateTime? to = null)
|
||||
{
|
||||
var result = new StringBuilder();
|
||||
|
||||
// Append guild and channel names
|
||||
result.Append($"{guild.Name} - {channel.Name} [{channel.Id}]");
|
||||
|
||||
// Append date range
|
||||
if (from != null || to != null)
|
||||
{
|
||||
result.Append(" (");
|
||||
|
||||
// Both 'from' and 'to' are set
|
||||
if (from != null && to != null)
|
||||
{
|
||||
result.Append($"{from:yyyy-MM-dd} to {to:yyyy-MM-dd}");
|
||||
}
|
||||
// Only 'from' is set
|
||||
else if (from != null)
|
||||
{
|
||||
result.Append($"after {from:yyyy-MM-dd}");
|
||||
}
|
||||
// Only 'to' is set
|
||||
else
|
||||
{
|
||||
result.Append($"before {to:yyyy-MM-dd}");
|
||||
}
|
||||
|
||||
result.Append(")");
|
||||
}
|
||||
|
||||
// Append extension
|
||||
result.Append($".{format.GetFileExtension()}");
|
||||
|
||||
// Replace invalid chars
|
||||
foreach (var invalidChar in Path.GetInvalidFileNameChars())
|
||||
result.Replace(invalidChar, '_');
|
||||
|
||||
return result.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using Tyrrrz.Extensions;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
|
||||
namespace DiscordChatExporter.Core.Internal
|
||||
{
|
||||
@@ -14,10 +16,37 @@ namespace DiscordChatExporter.Core.Internal
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
public static string Base64Encode(this string str) => str.GetBytes().ToBase64();
|
||||
|
||||
public static string Base64Decode(this string str) => str.FromBase64().GetString();
|
||||
|
||||
public static Color ResetAlpha(this Color color) => Color.FromArgb(1, color);
|
||||
|
||||
public static string HtmlEncode(this string value) => WebUtility.HtmlEncode(value);
|
||||
|
||||
public static IEnumerable<IReadOnlyList<T>> GroupAdjacentWhile<T>(this IEnumerable<T> source,
|
||||
Func<IReadOnlyList<T>, T, bool> groupPredicate)
|
||||
{
|
||||
// Create buffer
|
||||
var buffer = new List<T>();
|
||||
|
||||
// Enumerate source
|
||||
foreach (var element in source)
|
||||
{
|
||||
// If buffer is not empty and group predicate failed - yield and flush buffer
|
||||
if (buffer.Any() && !groupPredicate(buffer, element))
|
||||
{
|
||||
yield return buffer;
|
||||
buffer = new List<T>(); // new instance to reset reference
|
||||
}
|
||||
|
||||
// Add element to buffer
|
||||
buffer.Add(element);
|
||||
}
|
||||
|
||||
// If buffer still has something after the source has been enumerated - yield
|
||||
if (buffer.Any())
|
||||
yield return buffer;
|
||||
}
|
||||
|
||||
public static IEnumerable<IReadOnlyList<T>> GroupAdjacentWhile<T>(this IEnumerable<T> source,
|
||||
Func<IReadOnlyList<T>, bool> groupPredicate)
|
||||
=> source.GroupAdjacentWhile((buffer, _) => groupPredicate(buffer));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
using System;
|
||||
using ByteSizeLib;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#attachment-object
|
||||
|
||||
@@ -12,13 +15,17 @@
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public bool IsImage => Width != null;
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
public long FileSize { get; }
|
||||
public bool IsImage => FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
|
||||
FileName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
|
||||
FileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
|
||||
FileName.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
|
||||
FileName.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public Attachment(string id, int? width, int? height, string url, string fileName, long fileSize)
|
||||
public ByteSize FileSize { get; }
|
||||
|
||||
public Attachment(string id, int? width, int? height, string url, string fileName, ByteSize fileSize)
|
||||
{
|
||||
Id = id;
|
||||
Url = url;
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string ParentId { get; }
|
||||
|
||||
public string GuildId { get; }
|
||||
|
||||
public string Name { get; }
|
||||
@@ -13,10 +15,11 @@
|
||||
public string Topic { get; }
|
||||
|
||||
public ChannelType Type { get; }
|
||||
|
||||
public Channel(string id, string guildId, string name, string topic, ChannelType type)
|
||||
|
||||
public Channel(string id, string parentId, string guildId, string name, string topic, ChannelType type)
|
||||
{
|
||||
Id = id;
|
||||
ParentId = parentId;
|
||||
GuildId = guildId;
|
||||
Name = name;
|
||||
Topic = topic;
|
||||
@@ -29,6 +32,6 @@
|
||||
public partial class Channel
|
||||
{
|
||||
public static Channel CreateDeletedChannel(string id) =>
|
||||
new Channel(id, null, "deleted-channel", null, ChannelType.GuildTextChat);
|
||||
new Channel(id, null, null, "deleted-channel", null, ChannelType.GuildTextChat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/emoji#emoji-object
|
||||
|
||||
public partial class Emoji
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public bool IsAnimated { get; }
|
||||
|
||||
public string ImageUrl
|
||||
{
|
||||
get
|
||||
{
|
||||
// Custom emoji
|
||||
if (Id.IsNotBlank())
|
||||
{
|
||||
// Animated
|
||||
if (IsAnimated)
|
||||
return $"https://cdn.discordapp.com/emojis/{Id}.gif";
|
||||
|
||||
// Non-animated
|
||||
return $"https://cdn.discordapp.com/emojis/{Id}.png";
|
||||
}
|
||||
|
||||
// Standard unicode emoji (via twemoji)
|
||||
return $"https://twemoji.maxcdn.com/2/72x72/{GetTwemojiName(Name)}.png";
|
||||
}
|
||||
}
|
||||
|
||||
public Emoji(string id, string name, bool isAnimated)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IsAnimated = isAnimated;
|
||||
}
|
||||
}
|
||||
|
||||
public partial class Emoji
|
||||
{
|
||||
private static IEnumerable<int> GetCodePoints(string emoji)
|
||||
{
|
||||
for (var i = 0; i < emoji.Length; i += char.IsHighSurrogate(emoji[i]) ? 2 : 1)
|
||||
yield return char.ConvertToUtf32(emoji, i);
|
||||
}
|
||||
|
||||
private static string GetTwemojiName(string emoji)
|
||||
=> GetCodePoints(emoji).Select(i => i.ToString("x")).JoinToString("-");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
@@ -33,45 +31,5 @@ namespace DiscordChatExporter.Core.Models
|
||||
|
||||
throw new ArgumentOutOfRangeException(nameof(format));
|
||||
}
|
||||
|
||||
public static IReadOnlyList<ChatLog> SplitIntoPartitions(this ChatLog chatLog, int partitionLimit)
|
||||
{
|
||||
// If chat log has fewer messages than the limit - just return chat log in a list
|
||||
if (chatLog.Messages.Count <= partitionLimit)
|
||||
return new[] {chatLog};
|
||||
|
||||
var result = new List<ChatLog>();
|
||||
|
||||
// Loop through messages
|
||||
var buffer = new List<Message>();
|
||||
foreach (var message in chatLog.Messages)
|
||||
{
|
||||
// Add message to buffer
|
||||
buffer.Add(message);
|
||||
|
||||
// If reached the limit - split and reset buffer
|
||||
if (buffer.Count >= partitionLimit)
|
||||
{
|
||||
// Add to result
|
||||
var chatLogPartition = new ChatLog(chatLog.Guild, chatLog.Channel, chatLog.From, chatLog.To, buffer,
|
||||
chatLog.Mentionables);
|
||||
result.Add(chatLogPartition);
|
||||
|
||||
// Reset the buffer instead of clearing to avoid mutations on existing references
|
||||
buffer = new List<Message>();
|
||||
}
|
||||
}
|
||||
|
||||
// Add what's remaining in buffer
|
||||
if (buffer.Any())
|
||||
{
|
||||
// Add to result
|
||||
var chatLogPartition = new ChatLog(chatLog.Guild, chatLog.Channel, chatLog.From, chatLog.To, buffer,
|
||||
chatLog.Mentionables);
|
||||
result.Add(chatLogPartition);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,15 +6,12 @@
|
||||
{
|
||||
public int Count { get; }
|
||||
|
||||
public string EmojiId { get; }
|
||||
public Emoji Emoji { get; }
|
||||
|
||||
public string EmojiName { get; }
|
||||
|
||||
public Reaction(int count, string emojiId, string emojiName)
|
||||
public Reaction(int count, Emoji emoji)
|
||||
{
|
||||
Count = count;
|
||||
EmojiId = emojiId;
|
||||
EmojiName = emojiName;
|
||||
Emoji = emoji;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
{{- }}"{{ message.Timestamp | FormatDate }}";
|
||||
|
||||
{{- }}"{{ message.Content | FormatContent }}";
|
||||
{{- }}"{{ message.Content | FormatMarkdown | string.replace "\"" "\"\"" }}";
|
||||
|
||||
{{- }}"{{ message.Attachments | array.map "Url" | array.join "," }}";
|
||||
{{~ end -}}
|
||||
|
Can't render this file because it contains an unexpected character in line 3 and column 9.
|
@@ -1,7 +0,0 @@
|
||||
{{
|
||||
$SharedStyleSheet = include "Html.Shared.css"
|
||||
$ThemeStyleSheet = include "Html.DarkTheme.css"
|
||||
StyleSheet = $SharedStyleSheet + "\n" + $ThemeStyleSheet
|
||||
}}
|
||||
|
||||
{{ include "Html.Core.html" }}
|
||||
@@ -0,0 +1,2 @@
|
||||
{{~ ThemeStyleSheet = include "HtmlDark.Theme.css" ~}}
|
||||
{{~ include "HtmlShared.Main.html" ~}}
|
||||
+15
-12
@@ -2,13 +2,17 @@
|
||||
|
||||
body {
|
||||
background-color: #36393e;
|
||||
color: #ffffffb3;
|
||||
color: #dcddde;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #0096cf;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #2f3136;
|
||||
}
|
||||
@@ -19,7 +23,6 @@ a {
|
||||
}
|
||||
|
||||
.mention {
|
||||
background-color: #738bd71a;
|
||||
color: #7289da;
|
||||
}
|
||||
|
||||
@@ -40,7 +43,7 @@ a {
|
||||
/* === CHATLOG === */
|
||||
|
||||
.chatlog__message-group {
|
||||
border-color: #ffffff0a;
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.chatlog__author-name {
|
||||
@@ -48,16 +51,16 @@ a {
|
||||
}
|
||||
|
||||
.chatlog__timestamp {
|
||||
color: #ffffff33;
|
||||
color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.chatlog__edited-timestamp {
|
||||
color: #ffffff33;
|
||||
color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.chatlog__embed-content-container {
|
||||
background-color: #2e30364d;
|
||||
border-color: #2e303699;
|
||||
background-color: rgba(46, 48, 54, 0.3);
|
||||
border-color: rgba(46, 48, 54, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name {
|
||||
@@ -73,7 +76,7 @@ a {
|
||||
}
|
||||
|
||||
.chatlog__embed-description {
|
||||
color: #ffffff99;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-field-name {
|
||||
@@ -81,17 +84,17 @@ a {
|
||||
}
|
||||
|
||||
.chatlog__embed-field-value {
|
||||
color: #ffffff99;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-footer {
|
||||
color: #ffffff99;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
background-color: #ffffff0a;
|
||||
background-color: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
color: #ffffff4d;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{{
|
||||
$SharedStyleSheet = include "Html.Shared.css"
|
||||
$ThemeStyleSheet = include "Html.LightTheme.css"
|
||||
StyleSheet = $SharedStyleSheet + "\n" + $ThemeStyleSheet
|
||||
}}
|
||||
|
||||
{{ include "Html.Core.html" }}
|
||||
@@ -0,0 +1,2 @@
|
||||
{{~ ThemeStyleSheet = include "HtmlLight.Theme.css" ~}}
|
||||
{{~ include "HtmlShared.Main.html" ~}}
|
||||
+9
-5
@@ -2,13 +2,17 @@
|
||||
|
||||
body {
|
||||
background-color: #ffffff;
|
||||
color: #737f8d;
|
||||
color: #747f8d;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #00b0f4;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
@@ -56,8 +60,8 @@ a {
|
||||
}
|
||||
|
||||
.chatlog__embed-content-container {
|
||||
background-color: #f9f9f94d;
|
||||
border-color: #cccccc4d;
|
||||
background-color: rgba(249, 249, 249, 0.3);
|
||||
border-color: rgba(204, 204, 204, 0.3);
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name {
|
||||
@@ -85,11 +89,11 @@ a {
|
||||
}
|
||||
|
||||
.chatlog__embed-footer {
|
||||
color: #4f535b99;
|
||||
color: rgba(79, 83, 91, 0.4);
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
background-color: #4f545c0f;
|
||||
background-color: rgba(79, 84, 92, 0.06);
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
+30
-21
@@ -17,9 +17,18 @@ img {
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.markdown {
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.3;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.pre {
|
||||
font-family: "Consolas", "Courier New", Courier, Monospace;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
@@ -34,25 +43,25 @@ img {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.mention {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.emoji {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
width: 1.45em;
|
||||
height: 1.45em;
|
||||
margin: 0 1px;
|
||||
vertical-align: middle;
|
||||
vertical-align: -0.4em;
|
||||
}
|
||||
|
||||
.emoji--small {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
}
|
||||
|
||||
.emoji--large {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.mention {
|
||||
font-weight: 600;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
}
|
||||
|
||||
/* === INFO === */
|
||||
@@ -101,6 +110,7 @@ img {
|
||||
|
||||
.chatlog {
|
||||
max-width: 100%;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.chatlog__message-group {
|
||||
@@ -130,6 +140,7 @@ img {
|
||||
|
||||
.chatlog__author-name {
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.chatlog__timestamp {
|
||||
@@ -144,7 +155,7 @@ img {
|
||||
}
|
||||
|
||||
.chatlog__edited-timestamp {
|
||||
margin-left: 5px;
|
||||
margin-left: 3px;
|
||||
font-size: .8em;
|
||||
}
|
||||
|
||||
@@ -283,21 +294,19 @@ img {
|
||||
}
|
||||
|
||||
.chatlog__reactions {
|
||||
display: flex;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 6px 2px 2px 2px;
|
||||
padding: 2px 6px 2px 2px;
|
||||
padding: 3px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__reaction-emoji {
|
||||
margin-left: 3px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
min-width: 9px;
|
||||
margin-left: 6px;
|
||||
font-size: .875em;
|
||||
vertical-align: middle;
|
||||
}
|
||||
+13
-18
@@ -6,7 +6,10 @@
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
<style>
|
||||
{{ StyleSheet }}
|
||||
{{ include "HtmlShared.Main.css" }}
|
||||
</style>
|
||||
<style>
|
||||
{{ ThemeStyleSheet }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -58,7 +61,7 @@
|
||||
{{~ # Content ~}}
|
||||
{{~ if message.Content ~}}
|
||||
<div class="chatlog__content">
|
||||
{{ message.Content | FormatContent }}
|
||||
<span class="markdown">{{ message.Content | FormatMarkdown }}</span>
|
||||
|
||||
{{~ # Edited timestamp ~}}
|
||||
{{~ if message.EditedTimestamp ~}}
|
||||
@@ -76,7 +79,7 @@
|
||||
<img class="chatlog__attachment-thumbnail" src="{{ attachment.Url }}" />
|
||||
{{~ # Non-image ~}}
|
||||
{{~ else ~}}
|
||||
Attachment: {{ attachment.FileName }} ({{ attachment.FileSize | FormatFileSize }})
|
||||
Attachment: {{ attachment.FileName }} ({{ attachment.FileSize }})
|
||||
{{~ end ~}}
|
||||
</a>
|
||||
</div>
|
||||
@@ -85,7 +88,7 @@
|
||||
{{~ # Embeds ~}}
|
||||
{{~ for embed in message.Embeds ~}}
|
||||
<div class="chatlog__embed">
|
||||
<div class="chatlog__embed-color-pill" style="background-color: rgba({{ embed.Color | FormatColor }})"></div>
|
||||
<div class="chatlog__embed-color-pill" style="background-color: rgba({{ embed.Color.R }},{{ embed.Color.G }},{{ embed.Color.B }},{{ embed.Color.A }})"></div>
|
||||
<div class="chatlog__embed-content-container">
|
||||
<div class="chatlog__embed-content">
|
||||
<div class="chatlog__embed-text">
|
||||
@@ -112,16 +115,16 @@
|
||||
{{~ if embed.Title ~}}
|
||||
<div class="chatlog__embed-title">
|
||||
{{~ if embed.Url ~}}
|
||||
<a class="chatlog__embed-title-link" href="{{ embed.Url }}">{{ embed.Title | FormatContent }}</a>
|
||||
<a class="chatlog__embed-title-link" href="{{ embed.Url }}"><span class="markdown">{{ embed.Title | FormatMarkdown }}</span></a>
|
||||
{{~ else ~}}
|
||||
{{ embed.Title | FormatContent }}
|
||||
<span class="markdown">{{ embed.Title | FormatMarkdown }}</span>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Description ~}}
|
||||
{{~ if embed.Description ~}}
|
||||
<div class="chatlog__embed-description">{{ embed.Description | FormatContent true }}</div>
|
||||
<div class="chatlog__embed-description"><span class="markdown">{{ embed.Description | FormatMarkdown }}</span></div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Fields ~}}
|
||||
@@ -130,10 +133,10 @@
|
||||
{{~ for field in embed.Fields ~}}
|
||||
<div class="chatlog__embed-field {{ if field.IsInline }} chatlog__embed-field--inline {{ end }}">
|
||||
{{~ if field.Name ~}}
|
||||
<div class="chatlog__embed-field-name">{{ field.Name | FormatContent }}</div>
|
||||
<div class="chatlog__embed-field-name"><span class="markdown">{{ field.Name | FormatMarkdown }}</span></div>
|
||||
{{~ end ~}}
|
||||
{{~ if field.Value ~}}
|
||||
<div class="chatlog__embed-field-value">{{ field.Value | FormatContent true }}</div>
|
||||
<div class="chatlog__embed-field-value"><span class="markdown">{{ field.Value | FormatMarkdown }}</span></div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
@@ -192,15 +195,7 @@
|
||||
<div class="chatlog__reactions">
|
||||
{{~ for reaction in message.Reactions ~}}
|
||||
<div class="chatlog__reaction">
|
||||
<span class="chatlog__reaction-emoji">
|
||||
{{~ # Custom emoji ~}}
|
||||
{{~ if reaction.EmojiId ~}}
|
||||
<img class="emoji emoji--small" title="{{ reaction.EmojiName }}" src="https://cdn.discordapp.com/emojis/{{ reaction.EmojiId }}.png" />
|
||||
{{~ # Default emoji ~}}
|
||||
{{~ else ~}}
|
||||
{{ reaction.EmojiName }}
|
||||
{{~ end ~}}
|
||||
</span>
|
||||
<img class="emoji emoji--small" alt="{{ reaction.Emoji.Name }}" title="{{ reaction.Emoji.Name }}" src="{{ reaction.Emoji.ImageUrl }}" />
|
||||
<span class="chatlog__reaction-count">{{ reaction.Count }}</span>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
+1
-1
@@ -12,7 +12,7 @@ Range: {{ if Model.From }}{{ Model.From | FormatDate }} {{ end }}{{ if Model.
|
||||
{{~ # Author name and timestamp ~}}
|
||||
{{~ }}[{{ message.Timestamp | FormatDate }}] {{ message.Author.FullName }}
|
||||
{{~ # Content ~}}
|
||||
{{~ message.Content | FormatContent }}
|
||||
{{~ message.Content | FormatMarkdown }}
|
||||
{{~ # Attachments ~}}
|
||||
{{~ for attachment in message.Attachments ~}}
|
||||
{{~ attachment.Url }}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using ByteSizeLib;
|
||||
using DiscordChatExporter.Core.Internal;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Newtonsoft.Json.Linq;
|
||||
@@ -33,6 +34,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
// Get basic data
|
||||
var id = json["id"].Value<string>();
|
||||
var parentId = json["parent_id"]?.Value<string>();
|
||||
var type = (ChannelType) json["type"].Value<int>();
|
||||
var topic = json["topic"]?.Value<string>();
|
||||
|
||||
@@ -50,7 +52,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
if (name.IsBlank())
|
||||
name = json["recipients"].Select(ParseUser).Select(u => u.Name).JoinToString(", ");
|
||||
|
||||
return new Channel(id, guildId, name, topic, type);
|
||||
return new Channel(id, parentId, guildId, name, topic, type);
|
||||
}
|
||||
|
||||
private Role ParseRole(JToken json)
|
||||
@@ -68,7 +70,9 @@ namespace DiscordChatExporter.Core.Services
|
||||
var width = json["width"]?.Value<int>();
|
||||
var height = json["height"]?.Value<int>();
|
||||
var fileName = json["filename"].Value<string>();
|
||||
var fileSize = json["size"].Value<long>();
|
||||
var fileSizeBytes = json["size"].Value<long>();
|
||||
|
||||
var fileSize = ByteSize.FromBytes(fileSizeBytes);
|
||||
|
||||
return new Attachment(id, width, height, url, fileName, fileSize);
|
||||
}
|
||||
@@ -139,13 +143,21 @@ namespace DiscordChatExporter.Core.Services
|
||||
return new Embed(title, url, timestamp, color, author, description, fields, thumbnail, image, footer);
|
||||
}
|
||||
|
||||
private Emoji ParseEmoji(JToken json)
|
||||
{
|
||||
var id = json["id"]?.Value<string>();
|
||||
var name = json["name"]?.Value<string>();
|
||||
var isAnimated = json["animated"]?.Value<bool>() ?? false;
|
||||
|
||||
return new Emoji(id, name, isAnimated);
|
||||
}
|
||||
|
||||
private Reaction ParseReaction(JToken json)
|
||||
{
|
||||
var count = json["count"].Value<int>();
|
||||
var emojiId = json["emoji"]["id"]?.Value<string>();
|
||||
var emojiName = json["emoji"]["name"].Value<string>();
|
||||
var emoji = ParseEmoji(json["emoji"]);
|
||||
|
||||
return new Reaction(count, emojiId, emojiName);
|
||||
return new Reaction(count, emoji);
|
||||
}
|
||||
|
||||
private Message ParseMessage(JToken json)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
@@ -8,25 +9,27 @@ using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using DiscordChatExporter.Core.Internal;
|
||||
using Polly;
|
||||
using Failsafe;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public partial class DataService : IDataService, IDisposable
|
||||
public partial class DataService : IDisposable
|
||||
{
|
||||
private readonly HttpClient _httpClient = new HttpClient();
|
||||
|
||||
private async Task<JToken> GetApiResponseAsync(AuthToken token, string resource, string endpoint,
|
||||
params string[] parameters)
|
||||
{
|
||||
// Create request policy
|
||||
var policy = Policy
|
||||
.Handle<HttpErrorStatusCodeException>(e => (int) e.StatusCode == 429)
|
||||
.WaitAndRetryAsync(10, i => TimeSpan.FromSeconds(0.4));
|
||||
// Create retry policy
|
||||
var retry = Retry.Create()
|
||||
.Catch<HttpErrorStatusCodeException>(false, e => e.StatusCode == HttpStatusCode.ServiceUnavailable)
|
||||
.Catch<HttpErrorStatusCodeException>(false, e => (int) e.StatusCode == 429)
|
||||
.WithMaxTryCount(10)
|
||||
.WithDelay(TimeSpan.FromSeconds(0.4));
|
||||
|
||||
// Send request
|
||||
return await policy.ExecuteAsync(async () =>
|
||||
return await retry.ExecuteAsync(async () =>
|
||||
{
|
||||
// Create request
|
||||
const string apiRoot = "https://discordapp.com/api/v6";
|
||||
@@ -38,10 +41,15 @@ namespace DiscordChatExporter.Core.Services
|
||||
: new AuthenticationHeaderValue(token.Value);
|
||||
|
||||
// Add parameters
|
||||
foreach (var parameter in parameters)
|
||||
foreach (var parameter in parameters.ExceptBlank())
|
||||
{
|
||||
var key = parameter.SubstringUntil("=");
|
||||
var value = parameter.SubstringAfter("=");
|
||||
|
||||
// Skip empty values
|
||||
if (value.IsBlank())
|
||||
continue;
|
||||
|
||||
request.RequestUri = request.RequestUri.SetQueryParameter(key, value);
|
||||
}
|
||||
|
||||
@@ -120,16 +128,9 @@ namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
var result = new List<Message>();
|
||||
|
||||
// Report indeterminate progress
|
||||
progress?.Report(-1);
|
||||
|
||||
// Get the snowflakes for the selected range
|
||||
var firstId = from != null ? from.Value.ToSnowflake() : "0";
|
||||
var lastId = to != null ? to.Value.ToSnowflake() : DateTime.MaxValue.ToSnowflake();
|
||||
|
||||
// Get the last message
|
||||
var response = await GetApiResponseAsync(token, "channels", $"{channelId}/messages",
|
||||
"limit=1", $"before={lastId}");
|
||||
"limit=1", $"before={to?.ToSnowflake()}");
|
||||
var lastMessage = response.Select(ParseMessage).FirstOrDefault();
|
||||
|
||||
// If the last message doesn't exist or it's outside of range - return
|
||||
@@ -140,7 +141,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
}
|
||||
|
||||
// Get other messages
|
||||
var offsetId = firstId;
|
||||
var offsetId = from?.ToSnowflake() ?? "0";
|
||||
while (true)
|
||||
{
|
||||
// Get message batch
|
||||
@@ -226,12 +227,9 @@ namespace DiscordChatExporter.Core.Services
|
||||
return new ChatLog(guild, channel, from, to, messages, mentionables);
|
||||
}
|
||||
|
||||
public async Task<ChatLog> GetChatLogAsync(AuthToken token, string channelId,
|
||||
public async Task<ChatLog> GetChatLogAsync(AuthToken token, Channel channel,
|
||||
DateTime? from = null, DateTime? to = null, IProgress<double> progress = null)
|
||||
{
|
||||
// Get channel
|
||||
var channel = await GetChannelAsync(token, channelId);
|
||||
|
||||
// Get guild
|
||||
var guild = channel.GuildId == Guild.DirectMessages.Id
|
||||
? Guild.DirectMessages
|
||||
@@ -241,6 +239,16 @@ namespace DiscordChatExporter.Core.Services
|
||||
return await GetChatLogAsync(token, guild, channel, from, to, progress);
|
||||
}
|
||||
|
||||
public async Task<ChatLog> GetChatLogAsync(AuthToken token, string channelId,
|
||||
DateTime? from = null, DateTime? to = null, IProgress<double> progress = null)
|
||||
{
|
||||
// Get channel
|
||||
var channel = await GetChannelAsync(token, channelId);
|
||||
|
||||
// Get the chat log
|
||||
return await GetChatLogAsync(token, channel, from, to, progress);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_httpClient.Dispose();
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
|
||||
public string GetPath(ExportFormat format)
|
||||
{
|
||||
return $"{ResourceRootNamespace}.{format}.{format.GetFileExtension()}";
|
||||
return $"{ResourceRootNamespace}.{format}.Template.{format.GetFileExtension()}";
|
||||
}
|
||||
|
||||
public string Load(TemplateContext context, SourceSpan callerSpan, string templatePath)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Core.Internal;
|
||||
using DiscordChatExporter.Core.Markdown;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Scriban.Runtime;
|
||||
using Tyrrrz.Extensions;
|
||||
@@ -19,329 +18,187 @@ namespace DiscordChatExporter.Core.Services
|
||||
private readonly ExportFormat _format;
|
||||
private readonly ChatLog _log;
|
||||
private readonly string _dateFormat;
|
||||
private readonly int _messageGroupLimit;
|
||||
|
||||
public TemplateModel(ExportFormat format, ChatLog log, string dateFormat, int messageGroupLimit)
|
||||
public TemplateModel(ExportFormat format, ChatLog log, string dateFormat)
|
||||
{
|
||||
_format = format;
|
||||
_log = log;
|
||||
_dateFormat = dateFormat;
|
||||
_messageGroupLimit = messageGroupLimit;
|
||||
}
|
||||
|
||||
private IEnumerable<MessageGroup> GroupMessages(IEnumerable<Message> messages)
|
||||
{
|
||||
// Group adjacent messages by timestamp and author
|
||||
var buffer = new List<Message>();
|
||||
foreach (var message in messages)
|
||||
=> messages.GroupAdjacentWhile((buffer, message) =>
|
||||
{
|
||||
var groupFirst = buffer.FirstOrDefault();
|
||||
// Break group if the author changed
|
||||
if (buffer.Last().Author.Id != message.Author.Id)
|
||||
return false;
|
||||
|
||||
// Group break condition
|
||||
var breakCondition =
|
||||
groupFirst != null &&
|
||||
(
|
||||
message.Author.Id != groupFirst.Author.Id ||
|
||||
(message.Timestamp - groupFirst.Timestamp).TotalHours > 1 ||
|
||||
message.Timestamp.Hour != groupFirst.Timestamp.Hour ||
|
||||
buffer.Count >= _messageGroupLimit
|
||||
);
|
||||
// Break group if last message was more than 7 minutes ago
|
||||
if ((message.Timestamp - buffer.Last().Timestamp).TotalMinutes > 7)
|
||||
return false;
|
||||
|
||||
// If condition is true - flush buffer
|
||||
if (breakCondition)
|
||||
{
|
||||
var group = new MessageGroup(groupFirst.Author, groupFirst.Timestamp, buffer);
|
||||
return true;
|
||||
}).Select(g => new MessageGroup(g.First().Author, g.First().Timestamp, g));
|
||||
|
||||
// Reset the buffer instead of clearing to avoid mutations on existing references
|
||||
buffer = new List<Message>();
|
||||
|
||||
yield return group;
|
||||
}
|
||||
|
||||
// Add message to buffer
|
||||
buffer.Add(message);
|
||||
}
|
||||
|
||||
// Add what's remaining in buffer
|
||||
if (buffer.Any())
|
||||
{
|
||||
var groupFirst = buffer.First();
|
||||
var group = new MessageGroup(groupFirst.Author, groupFirst.Timestamp, buffer);
|
||||
|
||||
yield return group;
|
||||
}
|
||||
}
|
||||
|
||||
private string HtmlEncode(string str) => WebUtility.HtmlEncode(str);
|
||||
|
||||
private string Format(IFormattable obj, string format) =>
|
||||
obj.ToString(format, CultureInfo.InvariantCulture);
|
||||
private string Format(IFormattable obj, string format)
|
||||
=> obj.ToString(format, CultureInfo.InvariantCulture);
|
||||
|
||||
private string FormatDate(DateTime dateTime) => Format(dateTime, _dateFormat);
|
||||
|
||||
private string FormatFileSize(long fileSize)
|
||||
private string FormatMarkdownPlainText(IReadOnlyList<Node> nodes)
|
||||
{
|
||||
string[] units = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
|
||||
double size = fileSize;
|
||||
var unit = 0;
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
while (size >= 1024)
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
size /= 1024;
|
||||
++unit;
|
||||
if (node is FormattedNode formattedNode)
|
||||
{
|
||||
var innerText = FormatMarkdownPlainText(formattedNode.Children);
|
||||
buffer.Append($"{formattedNode.Token}{innerText}{formattedNode.Token}");
|
||||
}
|
||||
|
||||
else if (node is MentionNode mentionNode && mentionNode.Type != MentionType.Meta)
|
||||
{
|
||||
if (mentionNode.Type == MentionType.User)
|
||||
{
|
||||
var user = _log.Mentionables.GetUser(mentionNode.Id);
|
||||
buffer.Append($"@{user.Name}");
|
||||
}
|
||||
|
||||
else if (mentionNode.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = _log.Mentionables.GetChannel(mentionNode.Id);
|
||||
buffer.Append($"#{channel.Name}");
|
||||
}
|
||||
|
||||
else if (mentionNode.Type == MentionType.Role)
|
||||
{
|
||||
var role = _log.Mentionables.GetRole(mentionNode.Id);
|
||||
buffer.Append($"@{role.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
else if (node is EmojiNode emojiNode)
|
||||
{
|
||||
buffer.Append(emojiNode.IsCustomEmoji ? $":{emojiNode.Name}:" : node.Lexeme);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
buffer.Append(node.Lexeme);
|
||||
}
|
||||
}
|
||||
|
||||
return $"{size:0.#} {units[unit]}";
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatColor(Color color)
|
||||
private string FormatMarkdownPlainText(string input)
|
||||
=> FormatMarkdownPlainText(MarkdownParser.Parse(input));
|
||||
|
||||
private string FormatMarkdownHtml(IReadOnlyList<Node> nodes, int depth = 0)
|
||||
{
|
||||
return $"{color.R},{color.G},{color.B},{color.A}";
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
if (node is TextNode textNode)
|
||||
{
|
||||
buffer.Append(textNode.Text.HtmlEncode());
|
||||
}
|
||||
|
||||
else if (node is FormattedNode formattedNode)
|
||||
{
|
||||
var innerHtml = FormatMarkdownHtml(formattedNode.Children, depth + 1);
|
||||
|
||||
if (formattedNode.Formatting == TextFormatting.Bold)
|
||||
buffer.Append($"<strong>{innerHtml}</strong>");
|
||||
|
||||
else if (formattedNode.Formatting == TextFormatting.Italic)
|
||||
buffer.Append($"<em>{innerHtml}</em>");
|
||||
|
||||
else if (formattedNode.Formatting == TextFormatting.Underline)
|
||||
buffer.Append($"<u>{innerHtml}</u>");
|
||||
|
||||
else if (formattedNode.Formatting == TextFormatting.Strikethrough)
|
||||
buffer.Append($"<s>{innerHtml}</s>");
|
||||
|
||||
else if (formattedNode.Formatting == TextFormatting.Spoiler)
|
||||
buffer.Append($"<span class=\"spoiler\">{innerHtml}</span>");
|
||||
}
|
||||
|
||||
else if (node is InlineCodeBlockNode inlineCodeBlockNode)
|
||||
{
|
||||
buffer.Append($"<span class=\"pre pre--inline\">{inlineCodeBlockNode.Code.HtmlEncode()}</span>");
|
||||
}
|
||||
|
||||
else if (node is MultilineCodeBlockNode multilineCodeBlockNode)
|
||||
{
|
||||
// Set language class for syntax highlighting
|
||||
var languageCssClass = multilineCodeBlockNode.Language.IsNotBlank()
|
||||
? "language-" + multilineCodeBlockNode.Language
|
||||
: null;
|
||||
|
||||
buffer.Append(
|
||||
$"<div class=\"pre pre--multiline {languageCssClass}\">{multilineCodeBlockNode.Code.HtmlEncode()}</div>");
|
||||
}
|
||||
|
||||
else if (node is MentionNode mentionNode)
|
||||
{
|
||||
if (mentionNode.Type == MentionType.Meta)
|
||||
{
|
||||
buffer.Append($"<span class=\"mention\">@{mentionNode.Id.HtmlEncode()}</span>");
|
||||
}
|
||||
|
||||
else if (mentionNode.Type == MentionType.User)
|
||||
{
|
||||
var user = _log.Mentionables.GetUser(mentionNode.Id);
|
||||
buffer.Append($"<span class=\"mention\" title=\"{user.FullName}\">@{user.Name.HtmlEncode()}</span>");
|
||||
}
|
||||
|
||||
else if (mentionNode.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = _log.Mentionables.GetChannel(mentionNode.Id);
|
||||
buffer.Append($"<span class=\"mention\">#{channel.Name.HtmlEncode()}</span>");
|
||||
}
|
||||
|
||||
else if (mentionNode.Type == MentionType.Role)
|
||||
{
|
||||
var role = _log.Mentionables.GetRole(mentionNode.Id);
|
||||
buffer.Append($"<span class=\"mention\">@{role.Name.HtmlEncode()}</span>");
|
||||
}
|
||||
}
|
||||
|
||||
else if (node is EmojiNode emojiNode)
|
||||
{
|
||||
// Get emoji image URL
|
||||
var emojiImageUrl = new Emoji(emojiNode.Id, emojiNode.Name, emojiNode.IsAnimated).ImageUrl;
|
||||
|
||||
// Emoji can be jumboable if it's the only top-level node
|
||||
var jumboableCssClass = depth == 0 && nodes.Count == 1
|
||||
? "emoji--large"
|
||||
: null;
|
||||
|
||||
buffer.Append($"<img class=\"emoji {jumboableCssClass}\" alt=\"{emojiNode.Name}\" title=\"{emojiNode.Name}\" src=\"{emojiImageUrl}\" />");
|
||||
}
|
||||
|
||||
else if (node is LinkNode linkNode)
|
||||
{
|
||||
var escapedUrl = Uri.EscapeUriString(linkNode.Url);
|
||||
buffer.Append($"<a href=\"{escapedUrl}\">{linkNode.Title.HtmlEncode()}</a>");
|
||||
}
|
||||
}
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatContentPlainText(string content)
|
||||
private string FormatMarkdownHtml(string input)
|
||||
=> FormatMarkdownHtml(MarkdownParser.Parse(input));
|
||||
|
||||
private string FormatMarkdown(string input)
|
||||
{
|
||||
// New lines
|
||||
content = content.Replace("\n", Environment.NewLine);
|
||||
|
||||
// User mentions (<@id> and <@!id>)
|
||||
var mentionedUserIds = Regex.Matches(content, "<@!?(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedUserId in mentionedUserIds)
|
||||
{
|
||||
var mentionedUser = _log.Mentionables.GetUser(mentionedUserId);
|
||||
content = Regex.Replace(content, $"<@!?{mentionedUserId}>", $"@{mentionedUser.FullName}");
|
||||
}
|
||||
|
||||
// Channel mentions (<#id>)
|
||||
var mentionedChannelIds = Regex.Matches(content, "<#(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedChannelId in mentionedChannelIds)
|
||||
{
|
||||
var mentionedChannel = _log.Mentionables.GetChannel(mentionedChannelId);
|
||||
content = content.Replace($"<#{mentionedChannelId}>", $"#{mentionedChannel.Name}");
|
||||
}
|
||||
|
||||
// Role mentions (<@&id>)
|
||||
var mentionedRoleIds = Regex.Matches(content, "<@&(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedRoleId in mentionedRoleIds)
|
||||
{
|
||||
var mentionedRole = _log.Mentionables.GetRole(mentionedRoleId);
|
||||
content = content.Replace($"<@&{mentionedRoleId}>", $"@{mentionedRole.Name}");
|
||||
}
|
||||
|
||||
// Custom emojis (<:name:id>)
|
||||
content = Regex.Replace(content, "<(:.*?:)\\d*>", "$1");
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
private string FormatContentHtml(string content, bool allowLinks = false)
|
||||
{
|
||||
// HTML-encode content
|
||||
content = HtmlEncode(content);
|
||||
|
||||
// Encode multiline codeblocks (```text```)
|
||||
content = Regex.Replace(content,
|
||||
@"```+(?:[^`]*?\n)?([^`]+)\n?```+",
|
||||
m => $"\x1AM{m.Groups[1].Value.Base64Encode()}\x1AM");
|
||||
|
||||
// Encode inline codeblocks (`text`)
|
||||
content = Regex.Replace(content,
|
||||
@"`([^`]+)`",
|
||||
m => $"\x1AI{m.Groups[1].Value.Base64Encode()}\x1AI");
|
||||
|
||||
// Encode links
|
||||
if (allowLinks)
|
||||
{
|
||||
content = Regex.Replace(content, @"\[(.*?)\]\((.*?)\)",
|
||||
m => $"\x1AL{m.Groups[1].Value.Base64Encode()}|{m.Groups[2].Value.Base64Encode()}\x1AL");
|
||||
}
|
||||
|
||||
// Encode URLs
|
||||
content = Regex.Replace(content,
|
||||
@"(\b(?:(?:https?|ftp|file)://|www\.|ftp\.)(?:\([-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];]*\)|[-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];])*(?:\([-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];]*\)|[-a-zA-Z0-9+&@#/%=~_|$]))",
|
||||
m => $"\x1AU{m.Groups[1].Value.Base64Encode()}\x1AU");
|
||||
|
||||
// Process bold (**text**)
|
||||
content = Regex.Replace(content, @"(\*\*)(?=\S)(.+?[*_]*)(?<=\S)\1", "<b>$2</b>");
|
||||
|
||||
// Process underline (__text__)
|
||||
content = Regex.Replace(content, @"(__)(?=\S)(.+?)(?<=\S)\1", "<u>$2</u>");
|
||||
|
||||
// Process italic (*text* or _text_)
|
||||
content = Regex.Replace(content, @"(\*|_)(?=\S)(.+?)(?<=\S)\1", "<i>$2</i>");
|
||||
|
||||
// Process strike through (~~text~~)
|
||||
content = Regex.Replace(content, @"(~~)(?=\S)(.+?)(?<=\S)\1", "<s>$2</s>");
|
||||
|
||||
// Decode and process multiline codeblocks
|
||||
content = Regex.Replace(content, "\x1AM(.*?)\x1AM",
|
||||
m => $"<div class=\"pre pre--multiline\">{m.Groups[1].Value.Base64Decode()}</div>");
|
||||
|
||||
// Decode and process inline codeblocks
|
||||
content = Regex.Replace(content, "\x1AI(.*?)\x1AI",
|
||||
m => $"<span class=\"pre pre--inline\">{m.Groups[1].Value.Base64Decode()}</span>");
|
||||
|
||||
// Decode and process links
|
||||
if (allowLinks)
|
||||
{
|
||||
content = Regex.Replace(content, "\x1AL(.*?)\\|(.*?)\x1AL",
|
||||
m => $"<a href=\"{m.Groups[2].Value.Base64Decode()}\">{m.Groups[1].Value.Base64Decode()}</a>");
|
||||
}
|
||||
|
||||
// Decode and process URLs
|
||||
content = Regex.Replace(content, "\x1AU(.*?)\x1AU",
|
||||
m => $"<a href=\"{m.Groups[1].Value.Base64Decode()}\">{m.Groups[1].Value.Base64Decode()}</a>");
|
||||
|
||||
// Process new lines
|
||||
content = content.Replace("\n", "<br />");
|
||||
|
||||
// Meta mentions (@everyone)
|
||||
content = content.Replace("@everyone", "<span class=\"mention\">@everyone</span>");
|
||||
|
||||
// Meta mentions (@here)
|
||||
content = content.Replace("@here", "<span class=\"mention\">@here</span>");
|
||||
|
||||
// User mentions (<@id> and <@!id>)
|
||||
var mentionedUserIds = Regex.Matches(content, "<@!?(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedUserId in mentionedUserIds)
|
||||
{
|
||||
var mentionedUser = _log.Mentionables.GetUser(mentionedUserId);
|
||||
content = Regex.Replace(content, $"<@!?{mentionedUserId}>",
|
||||
$"<span class=\"mention\" title=\"{HtmlEncode(mentionedUser.FullName)}\">" +
|
||||
$"@{HtmlEncode(mentionedUser.Name)}" +
|
||||
"</span>");
|
||||
}
|
||||
|
||||
// Channel mentions (<#id>)
|
||||
var mentionedChannelIds = Regex.Matches(content, "<#(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedChannelId in mentionedChannelIds)
|
||||
{
|
||||
var mentionedChannel = _log.Mentionables.GetChannel(mentionedChannelId);
|
||||
content = content.Replace($"<#{mentionedChannelId}>",
|
||||
"<span class=\"mention\">" +
|
||||
$"#{HtmlEncode(mentionedChannel.Name)}" +
|
||||
"</span>");
|
||||
}
|
||||
|
||||
// Role mentions (<@&id>)
|
||||
var mentionedRoleIds = Regex.Matches(content, "<@&(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedRoleId in mentionedRoleIds)
|
||||
{
|
||||
var mentionedRole = _log.Mentionables.GetRole(mentionedRoleId);
|
||||
content = content.Replace($"<@&{mentionedRoleId}>",
|
||||
"<span class=\"mention\">" +
|
||||
$"@{HtmlEncode(mentionedRole.Name)}" +
|
||||
"</span>");
|
||||
}
|
||||
|
||||
// Custom emojis (<:name:id>)
|
||||
var isJumboable = Regex.Replace(content, "<(:.*?:)(\\d*)>", "").IsBlank();
|
||||
var emojiClass = isJumboable ? "emoji emoji--large" : "emoji";
|
||||
content = Regex.Replace(content, "<(:.*?:)(\\d*)>",
|
||||
$"<img class=\"{emojiClass}\" title=\"$1\" src=\"https://cdn.discordapp.com/emojis/$2.png\" />");
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
private string FormatContentCsv(string content)
|
||||
{
|
||||
// Escape quotes
|
||||
content = content.Replace("\"", "\"\"");
|
||||
|
||||
// Escape commas and semicolons
|
||||
if (content.Contains(",") || content.Contains(";"))
|
||||
content = $"\"{content}\"";
|
||||
|
||||
// User mentions (<@id> and <@!id>)
|
||||
var mentionedUserIds = Regex.Matches(content, "<@!?(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedUserId in mentionedUserIds)
|
||||
{
|
||||
var mentionedUser = _log.Mentionables.GetUser(mentionedUserId);
|
||||
content = Regex.Replace(content, $"<@!?{mentionedUserId}>", $"@{mentionedUser.FullName}");
|
||||
}
|
||||
|
||||
// Channel mentions (<#id>)
|
||||
var mentionedChannelIds = Regex.Matches(content, "<#(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedChannelId in mentionedChannelIds)
|
||||
{
|
||||
var mentionedChannel = _log.Mentionables.GetChannel(mentionedChannelId);
|
||||
content = content.Replace($"<#{mentionedChannelId}>", $"#{mentionedChannel.Name}");
|
||||
}
|
||||
|
||||
// Role mentions (<@&id>)
|
||||
var mentionedRoleIds = Regex.Matches(content, "<@&(\\d+)>")
|
||||
.Cast<Match>()
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ExceptBlank()
|
||||
.ToArray();
|
||||
|
||||
foreach (var mentionedRoleId in mentionedRoleIds)
|
||||
{
|
||||
var mentionedRole = _log.Mentionables.GetRole(mentionedRoleId);
|
||||
content = content.Replace($"<@&{mentionedRoleId}>", $"@{mentionedRole.Name}");
|
||||
}
|
||||
|
||||
// Custom emojis (<:name:id>)
|
||||
content = Regex.Replace(content, "<(:.*?:)\\d*>", "$1");
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
private string FormatContent(string content, bool allowLinks = false)
|
||||
{
|
||||
if (_format == ExportFormat.PlainText)
|
||||
return FormatContentPlainText(content);
|
||||
|
||||
if (_format == ExportFormat.HtmlDark)
|
||||
return FormatContentHtml(content, allowLinks);
|
||||
|
||||
if (_format == ExportFormat.HtmlLight)
|
||||
return FormatContentHtml(content, allowLinks);
|
||||
|
||||
if (_format == ExportFormat.Csv)
|
||||
return FormatContentCsv(content);
|
||||
|
||||
throw new ArgumentOutOfRangeException(nameof(_format));
|
||||
return _format == ExportFormat.HtmlDark || _format == ExportFormat.HtmlLight
|
||||
? FormatMarkdownHtml(input)
|
||||
: FormatMarkdownPlainText(input);
|
||||
}
|
||||
|
||||
public ScriptObject GetScriptObject()
|
||||
@@ -349,16 +206,14 @@ namespace DiscordChatExporter.Core.Services
|
||||
// Create instance
|
||||
var scriptObject = new ScriptObject();
|
||||
|
||||
// Import chat log
|
||||
// Import model
|
||||
scriptObject.SetValue("Model", _log, true);
|
||||
|
||||
// Import functions
|
||||
scriptObject.Import(nameof(GroupMessages), new Func<IEnumerable<Message>, IEnumerable<MessageGroup>>(GroupMessages));
|
||||
scriptObject.Import(nameof(Format), new Func<IFormattable, string, string>(Format));
|
||||
scriptObject.Import(nameof(FormatDate), new Func<DateTime, string>(FormatDate));
|
||||
scriptObject.Import(nameof(FormatFileSize), new Func<long, string>(FormatFileSize));
|
||||
scriptObject.Import(nameof(FormatColor), new Func<Color, string>(FormatColor));
|
||||
scriptObject.Import(nameof(FormatContent), new Func<string, bool, string>(FormatContent));
|
||||
scriptObject.Import(nameof(FormatMarkdown), new Func<string, string>(FormatMarkdown));
|
||||
|
||||
return scriptObject;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Core.Internal;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Scriban;
|
||||
using Scriban.Runtime;
|
||||
@@ -7,11 +9,11 @@ using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public partial class ExportService : IExportService
|
||||
public partial class ExportService
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
public ExportService(ISettingsService settingsService)
|
||||
public ExportService(SettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
@@ -36,8 +38,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
};
|
||||
|
||||
// Create template model
|
||||
var templateModel = new TemplateModel(format, chatLog,
|
||||
_settingsService.DateFormat, _settingsService.MessageGroupLimit);
|
||||
var templateModel = new TemplateModel(format, chatLog, _settingsService.DateFormat);
|
||||
|
||||
context.PushGlobal(templateModel.GetScriptObject());
|
||||
|
||||
@@ -57,7 +58,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
}
|
||||
}
|
||||
|
||||
private void ExportChatLogPartitions(IReadOnlyList<ChatLog> partitions, string filePath, ExportFormat format)
|
||||
private void ExportChatLogPartitioned(IReadOnlyList<ChatLog> partitions, string filePath, ExportFormat format)
|
||||
{
|
||||
// Split file path into components
|
||||
var dirPath = Path.GetDirectoryName(filePath);
|
||||
@@ -69,7 +70,7 @@ namespace DiscordChatExporter.Core.Services
|
||||
foreach (var partition in partitions)
|
||||
{
|
||||
// Compose new file name
|
||||
var partitionFilePath = $"{fileNameWithoutExt}-{partitionNumber}{fileExt}";
|
||||
var partitionFilePath = $"{fileNameWithoutExt} [{partitionNumber} of {partitions.Count}]{fileExt}";
|
||||
|
||||
// Compose full file path
|
||||
if (dirPath.IsNotBlank())
|
||||
@@ -87,15 +88,19 @@ namespace DiscordChatExporter.Core.Services
|
||||
int? partitionLimit = null)
|
||||
{
|
||||
// If partitioning is disabled or there are fewer messages in chat log than the limit - process it without partitioning
|
||||
if (partitionLimit == null || chatLog.Messages.Count <= partitionLimit)
|
||||
if (partitionLimit == null || partitionLimit <= 0 || chatLog.Messages.Count <= partitionLimit)
|
||||
{
|
||||
ExportChatLogSingle(chatLog, filePath, format);
|
||||
}
|
||||
// Otherwise split into partitions and export separately
|
||||
else
|
||||
{
|
||||
var partitions = chatLog.SplitIntoPartitions(partitionLimit.Value);
|
||||
ExportChatLogPartitions(partitions, filePath, format);
|
||||
// Create partitions by grouping up to X adjacent messages into separate chat logs
|
||||
var partitions = chatLog.Messages.GroupAdjacentWhile(g => g.Count < partitionLimit.Value)
|
||||
.Select(g => new ChatLog(chatLog.Guild, chatLog.Channel, chatLog.From, chatLog.To, g, chatLog.Mentionables))
|
||||
.ToArray();
|
||||
|
||||
ExportChatLogPartitioned(partitions, filePath, format);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public interface IDataService
|
||||
{
|
||||
Task<Guild> GetGuildAsync(AuthToken token, string guildId);
|
||||
|
||||
Task<Channel> GetChannelAsync(AuthToken token, string channelId);
|
||||
|
||||
Task<IReadOnlyList<Guild>> GetUserGuildsAsync(AuthToken token);
|
||||
|
||||
Task<IReadOnlyList<Channel>> GetDirectMessageChannelsAsync(AuthToken token);
|
||||
|
||||
Task<IReadOnlyList<Channel>> GetGuildChannelsAsync(AuthToken token, string guildId);
|
||||
|
||||
Task<IReadOnlyList<Role>> GetGuildRolesAsync(AuthToken token, string guildId);
|
||||
|
||||
Task<IReadOnlyList<Message>> GetChannelMessagesAsync(AuthToken token, string channelId,
|
||||
DateTime? from = null, DateTime? to = null, IProgress<double> progress = null);
|
||||
|
||||
Task<Mentionables> GetMentionablesAsync(AuthToken token, string guildId,
|
||||
IEnumerable<Message> messages);
|
||||
|
||||
Task<ChatLog> GetChatLogAsync(AuthToken token, Guild guild, Channel channel,
|
||||
DateTime? from = null, DateTime? to = null, IProgress<double> progress = null);
|
||||
|
||||
Task<ChatLog> GetChatLogAsync(AuthToken token, string channelId,
|
||||
DateTime? from = null, DateTime? to = null, IProgress<double> progress = null);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public interface IExportService
|
||||
{
|
||||
void ExportChatLog(ChatLog chatLog, string filePath, ExportFormat format,
|
||||
int? partitionLimit = null);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public interface ISettingsService
|
||||
{
|
||||
bool IsAutoUpdateEnabled { get; set; }
|
||||
|
||||
string DateFormat { get; set; }
|
||||
int MessageGroupLimit { get; set; }
|
||||
|
||||
AuthToken LastToken { get; set; }
|
||||
ExportFormat LastExportFormat { get; set; }
|
||||
int? LastPartitionLimit { get; set; }
|
||||
|
||||
void Load();
|
||||
void Save();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public interface IUpdateService
|
||||
{
|
||||
bool NeedRestart { get; set; }
|
||||
|
||||
Task<Version> CheckPrepareUpdateAsync();
|
||||
|
||||
void FinalizeUpdate();
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,11 @@ using Tyrrrz.Settings;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public class SettingsService : SettingsManager, ISettingsService
|
||||
public class SettingsService : SettingsManager
|
||||
{
|
||||
public bool IsAutoUpdateEnabled { get; set; } = true;
|
||||
|
||||
public string DateFormat { get; set; } = "dd-MMM-yy hh:mm tt";
|
||||
public int MessageGroupLimit { get; set; } = 20;
|
||||
|
||||
public AuthToken LastToken { get; set; }
|
||||
public ExportFormat LastExportFormat { get; set; } = ExportFormat.HtmlDark;
|
||||
|
||||
@@ -5,23 +5,20 @@ using Onova.Services;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public class UpdateService : IUpdateService
|
||||
public class UpdateService
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
private readonly IUpdateManager _manager;
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
private readonly IUpdateManager _updateManager = new UpdateManager(
|
||||
new GithubPackageResolver("Tyrrrz", "DiscordChatExporter", "DiscordChatExporter.zip"),
|
||||
new ZipPackageExtractor());
|
||||
|
||||
private Version _updateVersion;
|
||||
private bool _updateFinalized;
|
||||
private bool _updaterLaunched;
|
||||
|
||||
public bool NeedRestart { get; set; }
|
||||
|
||||
public UpdateService(ISettingsService settingsService)
|
||||
public UpdateService(SettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
|
||||
_manager = new UpdateManager(
|
||||
new GithubPackageResolver("Tyrrrz", "DiscordChatExporter", "DiscordChatExporter.zip"),
|
||||
new ZipPackageExtractor());
|
||||
}
|
||||
|
||||
public async Task<Version> CheckPrepareUpdateAsync()
|
||||
@@ -31,33 +28,33 @@ namespace DiscordChatExporter.Core.Services
|
||||
return null;
|
||||
|
||||
// Cleanup leftover files
|
||||
_manager.Cleanup();
|
||||
_updateManager.Cleanup();
|
||||
|
||||
// Check for updates
|
||||
var check = await _manager.CheckForUpdatesAsync();
|
||||
var check = await _updateManager.CheckForUpdatesAsync();
|
||||
if (!check.CanUpdate)
|
||||
return null;
|
||||
|
||||
// Prepare the update
|
||||
if (!_manager.IsUpdatePrepared(check.LastVersion))
|
||||
await _manager.PrepareUpdateAsync(check.LastVersion);
|
||||
if (!_updateManager.IsUpdatePrepared(check.LastVersion))
|
||||
await _updateManager.PrepareUpdateAsync(check.LastVersion);
|
||||
|
||||
return _updateVersion = check.LastVersion;
|
||||
}
|
||||
|
||||
public void FinalizeUpdate()
|
||||
public void FinalizeUpdate(bool needRestart)
|
||||
{
|
||||
// Check if an update is pending
|
||||
if (_updateVersion == null)
|
||||
return;
|
||||
|
||||
// Check if the update has already been finalized
|
||||
if (_updateFinalized)
|
||||
// Check if the updater has already been launched
|
||||
if (_updaterLaunched)
|
||||
return;
|
||||
|
||||
// Launch the updater
|
||||
_manager.LaunchUpdater(_updateVersion, NeedRestart);
|
||||
_updateFinalized = true;
|
||||
_updateManager.LaunchUpdater(_updateVersion, needRestart);
|
||||
_updaterLaunched = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,19 @@
|
||||
x:Class="DiscordChatExporter.Gui.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters"
|
||||
xmlns:local="clr-namespace:DiscordChatExporter.Gui"
|
||||
DispatcherUnhandledException="App_OnDispatcherUnhandledException"
|
||||
StartupUri="Views/MainWindow.xaml">
|
||||
xmlns:s="https://github.com/canton7/Stylet">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<s:ApplicationLoader>
|
||||
<!-- Bootstrapper -->
|
||||
<s:ApplicationLoader.Bootstrapper>
|
||||
<local:Bootstrapper />
|
||||
</s:ApplicationLoader.Bootstrapper>
|
||||
|
||||
<!-- Merged dictionaries -->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
|
||||
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
|
||||
<ResourceDictionary Source="pack://application:,,,/Tyrrrz.WpfExtensions;component/ConvertersDictionary.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- Colors -->
|
||||
@@ -74,9 +77,16 @@
|
||||
Color="{DynamicResource InverseTextColor}" />
|
||||
|
||||
<!-- Styles -->
|
||||
<Style TargetType="{x:Type Image}">
|
||||
<Style x:Key="MaterialDesignRoot" TargetType="{x:Type Control}">
|
||||
<Setter Property="FontFamily" Value="{DynamicResource MaterialDesignFont}" />
|
||||
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
|
||||
<Setter Property="RenderOptions.EdgeMode" Value="Aliased" />
|
||||
<Setter Property="SnapsToDevicePixels" Value="True" />
|
||||
<Setter Property="TextElement.FontSize" Value="13" />
|
||||
<Setter Property="TextElement.FontWeight" Value="Regular" />
|
||||
<Setter Property="TextElement.Foreground" Value="{DynamicResource SecondaryTextBrush}" />
|
||||
<Setter Property="TextOptions.TextFormattingMode" Value="Ideal" />
|
||||
<Setter Property="TextOptions.TextRenderingMode" Value="Auto" />
|
||||
<Setter Property="UseLayoutRounding" Value="True" />
|
||||
</Style>
|
||||
|
||||
<Style BasedOn="{StaticResource MaterialDesignLinearProgressBar}" TargetType="{x:Type ProgressBar}">
|
||||
@@ -95,6 +105,21 @@
|
||||
<Setter Property="Foreground" Value="{DynamicResource PrimaryTextBrush}" />
|
||||
</Style>
|
||||
|
||||
<Style BasedOn="{StaticResource MaterialDesignDatePicker}" TargetType="{x:Type DatePicker}">
|
||||
<Setter Property="Foreground" Value="{DynamicResource PrimaryTextBrush}" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="MaterialDesignFlatDarkButton"
|
||||
BasedOn="{StaticResource MaterialDesignFlatButton}"
|
||||
TargetType="{x:Type Button}">
|
||||
<Style.Resources>
|
||||
<SolidColorBrush x:Key="MaterialDesignFlatButtonClick" Color="#4C4C4C" />
|
||||
</Style.Resources>
|
||||
|
||||
<Setter Property="Foreground" Value="{DynamicResource PrimaryHueMidForegroundBrush}" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="MaterialDesignFlatActionToggleButton"
|
||||
BasedOn="{StaticResource MaterialDesignActionToggleButton}"
|
||||
@@ -109,12 +134,6 @@
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- Converters -->
|
||||
<converters:ExportFormatToStringConverter x:Key="ExportFormatToStringConverter" />
|
||||
|
||||
<!-- Container -->
|
||||
<local:Container x:Key="Container" />
|
||||
</ResourceDictionary>
|
||||
</s:ApplicationLoader>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -1,13 +1,6 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace DiscordChatExporter.Gui
|
||||
namespace DiscordChatExporter.Gui
|
||||
{
|
||||
public partial class App
|
||||
{
|
||||
private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
|
||||
{
|
||||
MessageBox.Show(args.Exception.ToString(), "Error occured", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using DiscordChatExporter.Gui.ViewModels.Components;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Behaviors
|
||||
{
|
||||
public class ChannelViewModelMultiSelectionListBoxBehavior : MultiSelectionListBoxBehavior<ChannelViewModel>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Interactivity;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Behaviors
|
||||
{
|
||||
public class MultiSelectionListBoxBehavior<T> : Behavior<ListBox>
|
||||
{
|
||||
public static readonly DependencyProperty SelectedItemsProperty =
|
||||
DependencyProperty.Register(nameof(SelectedItems), typeof(IList),
|
||||
typeof(MultiSelectionListBoxBehavior<T>),
|
||||
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
|
||||
OnSelectedItemsChanged));
|
||||
|
||||
private static void OnSelectedItemsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
|
||||
{
|
||||
var behavior = (MultiSelectionListBoxBehavior<T>) sender;
|
||||
if (behavior._modelHandled) return;
|
||||
|
||||
if (behavior.AssociatedObject == null)
|
||||
return;
|
||||
|
||||
behavior._modelHandled = true;
|
||||
behavior.SelectItems();
|
||||
behavior._modelHandled = false;
|
||||
}
|
||||
|
||||
private bool _viewHandled;
|
||||
private bool _modelHandled;
|
||||
|
||||
public IList SelectedItems
|
||||
{
|
||||
get => (IList) GetValue(SelectedItemsProperty);
|
||||
set => SetValue(SelectedItemsProperty, value);
|
||||
}
|
||||
|
||||
// Propagate selected items from model to view
|
||||
private void SelectItems()
|
||||
{
|
||||
_viewHandled = true;
|
||||
|
||||
AssociatedObject.SelectedItems.Clear();
|
||||
if (SelectedItems != null)
|
||||
{
|
||||
foreach (var item in SelectedItems)
|
||||
AssociatedObject.SelectedItems.Add(item);
|
||||
}
|
||||
|
||||
_viewHandled = false;
|
||||
}
|
||||
|
||||
// Propagate selected items from view to model
|
||||
private void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs args)
|
||||
{
|
||||
if (_viewHandled) return;
|
||||
if (AssociatedObject.Items.SourceCollection == null) return;
|
||||
|
||||
SelectedItems = AssociatedObject.SelectedItems.Cast<T>().ToArray();
|
||||
}
|
||||
|
||||
// Re-select items when the set of items changes
|
||||
private void OnListBoxItemsChanged(object sender, NotifyCollectionChangedEventArgs args)
|
||||
{
|
||||
if (_viewHandled) return;
|
||||
if (AssociatedObject.Items.SourceCollection == null) return;
|
||||
SelectItems();
|
||||
}
|
||||
|
||||
protected override void OnAttached()
|
||||
{
|
||||
base.OnAttached();
|
||||
|
||||
AssociatedObject.SelectionChanged += OnListBoxSelectionChanged;
|
||||
((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged += OnListBoxItemsChanged;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnDetaching()
|
||||
{
|
||||
base.OnDetaching();
|
||||
|
||||
if (AssociatedObject != null)
|
||||
{
|
||||
AssociatedObject.SelectionChanged -= OnListBoxSelectionChanged;
|
||||
((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged -= OnListBoxItemsChanged;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
using Stylet;
|
||||
using StyletIoC;
|
||||
|
||||
namespace DiscordChatExporter.Gui
|
||||
{
|
||||
public class Bootstrapper : Bootstrapper<RootViewModel>
|
||||
{
|
||||
protected override void ConfigureIoC(IStyletIoCBuilder builder)
|
||||
{
|
||||
base.ConfigureIoC(builder);
|
||||
|
||||
// Autobind services in the .Core assembly
|
||||
builder.Autobind(typeof(DataService).Assembly);
|
||||
|
||||
// Bind settings as singleton
|
||||
builder.Bind<SettingsService>().ToSelf().InSingletonScope();
|
||||
|
||||
// Bind view model factory
|
||||
builder.Bind<IViewModelFactory>().ToAbstractFactory();
|
||||
}
|
||||
|
||||
protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
base.OnUnhandledException(e);
|
||||
|
||||
MessageBox.Show(e.Exception.ToString(), "Error occured", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
using CommonServiceLocator;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels;
|
||||
using GalaSoft.MvvmLight.Ioc;
|
||||
|
||||
namespace DiscordChatExporter.Gui
|
||||
{
|
||||
public class Container
|
||||
{
|
||||
public IExportSetupViewModel ExportSetupViewModel => Resolve<IExportSetupViewModel>();
|
||||
public IMainViewModel MainViewModel => Resolve<IMainViewModel>();
|
||||
public ISettingsViewModel SettingsViewModel => Resolve<ISettingsViewModel>();
|
||||
|
||||
public Container()
|
||||
{
|
||||
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
|
||||
SimpleIoc.Default.Reset();
|
||||
|
||||
// Services
|
||||
SimpleIoc.Default.Register<IDataService, DataService>();
|
||||
SimpleIoc.Default.Register<IExportService, ExportService>();
|
||||
SimpleIoc.Default.Register<ISettingsService, SettingsService>();
|
||||
SimpleIoc.Default.Register<IUpdateService, UpdateService>();
|
||||
|
||||
// View models
|
||||
SimpleIoc.Default.Register<IExportSetupViewModel, ExportSetupViewModel>(true);
|
||||
SimpleIoc.Default.Register<IMainViewModel, MainViewModel>(true);
|
||||
SimpleIoc.Default.Register<ISettingsViewModel, SettingsViewModel>(true);
|
||||
}
|
||||
|
||||
private T Resolve<T>(string key = null)
|
||||
{
|
||||
return ServiceLocator.Current.GetInstance<T>(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@ namespace DiscordChatExporter.Gui.Converters
|
||||
[ValueConversion(typeof(ExportFormat), typeof(string))]
|
||||
public class ExportFormatToStringConverter : IValueConverter
|
||||
{
|
||||
public static ExportFormatToStringConverter Instance { get; } = new ExportFormatToStringConverter();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
var format = (ExportFormat) value;
|
||||
return format.GetDisplayName();
|
||||
var format = value as ExportFormat?;
|
||||
return format?.GetDisplayName();
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
<Reference Include="System.Xaml">
|
||||
<RequiredTargetFramework>4.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="Tyrrrz.Settings, Version=1.3.2.0, Culture=neutral, PublicKeyToken=null" />
|
||||
<Reference Include="WindowsBase" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
@@ -56,26 +55,27 @@
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Behaviors\ChannelViewModelMultiSelectionListBoxBehavior.cs" />
|
||||
<Compile Include="Behaviors\MultiSelectionListBoxBehavior.cs" />
|
||||
<Compile Include="Bootstrapper.cs" />
|
||||
<Compile Include="Converters\ExportFormatToStringConverter.cs" />
|
||||
<Compile Include="Messages\ShowExportSetupMessage.cs" />
|
||||
<Compile Include="Messages\ShowNotificationMessage.cs" />
|
||||
<Compile Include="Messages\ShowSettingsMessage.cs" />
|
||||
<Compile Include="Messages\StartExportMessage.cs" />
|
||||
<Compile Include="ViewModels\ExportSetupViewModel.cs" />
|
||||
<Compile Include="ViewModels\IExportSetupViewModel.cs" />
|
||||
<Compile Include="ViewModels\ISettingsViewModel.cs" />
|
||||
<Compile Include="ViewModels\SettingsViewModel.cs" />
|
||||
<Compile Include="Container.cs" />
|
||||
<Compile Include="ViewModels\IMainViewModel.cs" />
|
||||
<Compile Include="ViewModels\MainViewModel.cs" />
|
||||
<Compile Include="Views\ExportSetupDialog.xaml.cs">
|
||||
<DependentUpon>ExportSetupDialog.xaml</DependentUpon>
|
||||
<Compile Include="ViewModels\Components\ChannelViewModel.cs" />
|
||||
<Compile Include="ViewModels\Components\GuildViewModel.cs" />
|
||||
<Compile Include="ViewModels\Dialogs\ExportSetupViewModel.cs" />
|
||||
<Compile Include="ViewModels\Framework\DialogManager.cs" />
|
||||
<Compile Include="ViewModels\Framework\DialogScreen.cs" />
|
||||
<Compile Include="ViewModels\Framework\Extensions.cs" />
|
||||
<Compile Include="ViewModels\Framework\IViewModelFactory.cs" />
|
||||
<Compile Include="ViewModels\Dialogs\SettingsViewModel.cs" />
|
||||
<Compile Include="ViewModels\RootViewModel.cs" />
|
||||
<Compile Include="Views\Dialogs\ExportSetupView.xaml.cs">
|
||||
<DependentUpon>ExportSetupView.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Views\MainWindow.xaml.cs">
|
||||
<DependentUpon>MainWindow.xaml</DependentUpon>
|
||||
<Compile Include="Views\RootView.xaml.cs">
|
||||
<DependentUpon>RootView.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Views\SettingsDialog.xaml.cs">
|
||||
<DependentUpon>SettingsDialog.xaml</DependentUpon>
|
||||
<Compile Include="Views\Dialogs\SettingsView.xaml.cs">
|
||||
<DependentUpon>SettingsView.xaml</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
@@ -91,7 +91,6 @@
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
<None Include="app.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Resource Include="..\favicon.ico" />
|
||||
@@ -107,38 +106,45 @@
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="Views\ExportSetupDialog.xaml">
|
||||
<Page Include="Views\Dialogs\ExportSetupView.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
<Page Include="Views\MainWindow.xaml">
|
||||
<Page Include="Views\RootView.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
<Page Include="Views\SettingsDialog.xaml">
|
||||
<Page Include="Views\Dialogs\SettingsView.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommonServiceLocator">
|
||||
<Version>2.0.3</Version>
|
||||
<PackageReference Include="Gress">
|
||||
<Version>1.0.2</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="MaterialDesignColors">
|
||||
<Version>1.1.3</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="MaterialDesignThemes">
|
||||
<Version>2.4.0.1044</Version>
|
||||
<Version>2.5.0.1205</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="MvvmLightLibs">
|
||||
<Version>5.4.1</Version>
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf">
|
||||
<Version>1.0.0</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="PropertyChanged.Fody">
|
||||
<Version>2.6.0</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Stylet">
|
||||
<Version>1.1.22</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="System.Windows.Interactivity.WPF">
|
||||
<Version>2.0.20525</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Tyrrrz.Extensions">
|
||||
<Version>1.5.1</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Tyrrrz.WpfExtensions">
|
||||
<Version>1.0.5</Version>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup />
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||
<PropertyChanged />
|
||||
</Weavers>
|
||||
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuild. -->
|
||||
<xs:element name="Weavers">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="PropertyChanged" minOccurs="0" maxOccurs="1">
|
||||
<xs:complexType>
|
||||
<xs:attribute name="InjectOnPropertyNameChanged" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the On_PropertyName_Changed feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="EventInvokerNames" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to change the name of the method that fires the notify event. This is a string that accepts multiple values in a comma separated form.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEquality" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should be inserted. If false, equality checking will be disabled for the project.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEqualityUsingBaseEquals" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="UseStaticEqualsFromBase" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the static Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:all>
|
||||
<xs:attribute name="VerifyAssembly" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'true' to run assembly verification on the target assembly after all weavers have been finished.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>A comma separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
@@ -1,17 +0,0 @@
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Messages
|
||||
{
|
||||
public class ShowExportSetupMessage
|
||||
{
|
||||
public Guild Guild { get; }
|
||||
|
||||
public Channel Channel { get; }
|
||||
|
||||
public ShowExportSetupMessage(Guild guild, Channel channel)
|
||||
{
|
||||
Guild = guild;
|
||||
Channel = channel;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Messages
|
||||
{
|
||||
public class ShowNotificationMessage
|
||||
{
|
||||
public string Message { get; }
|
||||
|
||||
public string CallbackCaption { get; }
|
||||
|
||||
public Action Callback { get; }
|
||||
|
||||
public ShowNotificationMessage(string message)
|
||||
{
|
||||
Message = message;
|
||||
}
|
||||
|
||||
public ShowNotificationMessage(string message, string callbackCaption, Action callback)
|
||||
: this(message)
|
||||
{
|
||||
CallbackCaption = callbackCaption;
|
||||
Callback = callback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace DiscordChatExporter.Gui.Messages
|
||||
{
|
||||
public class ShowSettingsMessage
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
using System;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Messages
|
||||
{
|
||||
public class StartExportMessage
|
||||
{
|
||||
public Channel Channel { get; }
|
||||
|
||||
public string FilePath { get; }
|
||||
|
||||
public ExportFormat Format { get; }
|
||||
|
||||
public DateTime? From { get; }
|
||||
|
||||
public DateTime? To { get; }
|
||||
|
||||
public int? PartitionLimit { get; }
|
||||
|
||||
public StartExportMessage(Channel channel, string filePath, ExportFormat format,
|
||||
DateTime? from, DateTime? to, int? partitionLimit)
|
||||
{
|
||||
Channel = channel;
|
||||
FilePath = filePath;
|
||||
Format = format;
|
||||
From = from;
|
||||
To = to;
|
||||
PartitionLimit = partitionLimit;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
[assembly: AssemblyTitle("DiscordChatExporter")]
|
||||
[assembly: AssemblyCompany("Tyrrrz")]
|
||||
[assembly: AssemblyCopyright("Copyright (c) 2017-2018 Alexey Golub")]
|
||||
[assembly: AssemblyVersion("2.8")]
|
||||
[assembly: AssemblyFileVersion("2.8")]
|
||||
[assembly: AssemblyCopyright("Copyright (c) Alexey Golub")]
|
||||
[assembly: AssemblyVersion("2.10.2")]
|
||||
[assembly: AssemblyFileVersion("2.10.2")]
|
||||
@@ -0,0 +1,17 @@
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Stylet;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Components
|
||||
{
|
||||
public partial class ChannelViewModel : PropertyChangedBase
|
||||
{
|
||||
public Channel Model { get; set; }
|
||||
|
||||
public string Category { get; set; }
|
||||
}
|
||||
|
||||
public partial class ChannelViewModel
|
||||
{
|
||||
public static implicit operator Channel(ChannelViewModel viewModel) => viewModel.Model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Stylet;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Components
|
||||
{
|
||||
public partial class GuildViewModel : PropertyChangedBase
|
||||
{
|
||||
public Guild Model { get; set; }
|
||||
|
||||
public IReadOnlyList<ChannelViewModel> Channels { get; set; }
|
||||
}
|
||||
|
||||
public partial class GuildViewModel
|
||||
{
|
||||
public static implicit operator Guild(GuildViewModel viewModel) => viewModel.Model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Core.Helpers;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels.Components;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Dialogs
|
||||
{
|
||||
public class ExportSetupViewModel : DialogScreen
|
||||
{
|
||||
private readonly DialogManager _dialogManager;
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
public GuildViewModel Guild { get; set; }
|
||||
|
||||
public IReadOnlyList<ChannelViewModel> Channels { get; set; }
|
||||
|
||||
public bool IsSingleChannel => Channels.Count == 1;
|
||||
|
||||
public string OutputPath { get; set; }
|
||||
|
||||
public IReadOnlyList<ExportFormat> AvailableFormats =>
|
||||
Enum.GetValues(typeof(ExportFormat)).Cast<ExportFormat>().ToArray();
|
||||
|
||||
public ExportFormat SelectedFormat { get; set; } = ExportFormat.HtmlDark;
|
||||
|
||||
public DateTime? From { get; set; }
|
||||
|
||||
public DateTime? To { get; set; }
|
||||
|
||||
public int? PartitionLimit { get; set; }
|
||||
|
||||
public ExportSetupViewModel(DialogManager dialogManager, SettingsService settingsService)
|
||||
{
|
||||
_dialogManager = dialogManager;
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
|
||||
protected override void OnViewLoaded()
|
||||
{
|
||||
base.OnViewLoaded();
|
||||
|
||||
// Persist preferences
|
||||
SelectedFormat = _settingsService.LastExportFormat;
|
||||
PartitionLimit = _settingsService.LastPartitionLimit;
|
||||
}
|
||||
|
||||
public void Confirm()
|
||||
{
|
||||
// Persist preferences
|
||||
_settingsService.LastExportFormat = SelectedFormat;
|
||||
_settingsService.LastPartitionLimit = PartitionLimit;
|
||||
|
||||
// Clamp 'from' and 'to' values
|
||||
if (From > To)
|
||||
From = To;
|
||||
if (To < From)
|
||||
To = From;
|
||||
|
||||
// If single channel - prompt file path
|
||||
if (IsSingleChannel)
|
||||
{
|
||||
// Get single channel
|
||||
var channel = Channels.Single();
|
||||
|
||||
// Generate default file name
|
||||
var defaultFileName = ExportHelper.GetDefaultExportFileName(SelectedFormat, Guild, channel, From, To);
|
||||
|
||||
// Generate filter
|
||||
var ext = SelectedFormat.GetFileExtension();
|
||||
var filter = $"{ext.ToUpperInvariant()} files|*.{ext}";
|
||||
|
||||
// Prompt user
|
||||
OutputPath = _dialogManager.PromptSaveFilePath(filter, defaultFileName);
|
||||
}
|
||||
// If multiple channels - prompt dir path
|
||||
else
|
||||
{
|
||||
// Prompt user
|
||||
OutputPath = _dialogManager.PromptDirectoryPath();
|
||||
}
|
||||
|
||||
// If canceled - return
|
||||
if (OutputPath.IsBlank())
|
||||
return;
|
||||
|
||||
// Close dialog
|
||||
Close(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Dialogs
|
||||
{
|
||||
public class SettingsViewModel : DialogScreen
|
||||
{
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
public bool IsAutoUpdateEnabled
|
||||
{
|
||||
get => _settingsService.IsAutoUpdateEnabled;
|
||||
set => _settingsService.IsAutoUpdateEnabled = value;
|
||||
}
|
||||
|
||||
public string DateFormat
|
||||
{
|
||||
get => _settingsService.DateFormat;
|
||||
set => _settingsService.DateFormat = value;
|
||||
}
|
||||
|
||||
public SettingsViewModel(SettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.Messages;
|
||||
using GalaSoft.MvvmLight;
|
||||
using GalaSoft.MvvmLight.CommandWpf;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public class ExportSetupViewModel : ViewModelBase, IExportSetupViewModel
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
|
||||
private string _filePath;
|
||||
private ExportFormat _format;
|
||||
private DateTime? _from;
|
||||
private DateTime? _to;
|
||||
private int? _partitionLimit;
|
||||
|
||||
public Guild Guild { get; private set; }
|
||||
|
||||
public Channel Channel { get; private set; }
|
||||
|
||||
public string FilePath
|
||||
{
|
||||
get => _filePath;
|
||||
set
|
||||
{
|
||||
Set(ref _filePath, value);
|
||||
ExportCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<ExportFormat> AvailableFormats =>
|
||||
Enum.GetValues(typeof(ExportFormat)).Cast<ExportFormat>().ToArray();
|
||||
|
||||
public ExportFormat SelectedFormat
|
||||
{
|
||||
get => _format;
|
||||
set
|
||||
{
|
||||
Set(ref _format, value);
|
||||
|
||||
// Replace extension in path
|
||||
var ext = value.GetFileExtension();
|
||||
if (FilePath != null)
|
||||
FilePath = Path.ChangeExtension(FilePath, ext);
|
||||
}
|
||||
}
|
||||
|
||||
public DateTime? From
|
||||
{
|
||||
get => _from;
|
||||
set => Set(ref _from, value);
|
||||
}
|
||||
|
||||
public DateTime? To
|
||||
{
|
||||
get => _to;
|
||||
set => Set(ref _to, value);
|
||||
}
|
||||
|
||||
public int? PartitionLimit
|
||||
{
|
||||
get => _partitionLimit;
|
||||
set => Set(ref _partitionLimit, value);
|
||||
}
|
||||
|
||||
// Commands
|
||||
public RelayCommand ExportCommand { get; }
|
||||
|
||||
public ExportSetupViewModel(ISettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
|
||||
// Commands
|
||||
ExportCommand = new RelayCommand(Export, () => FilePath.IsNotBlank());
|
||||
|
||||
// Messages
|
||||
MessengerInstance.Register<ShowExportSetupMessage>(this, m =>
|
||||
{
|
||||
Guild = m.Guild;
|
||||
Channel = m.Channel;
|
||||
SelectedFormat = _settingsService.LastExportFormat;
|
||||
FilePath = $"{Guild.Name} - {Channel.Name}.{SelectedFormat.GetFileExtension()}"
|
||||
.Replace(Path.GetInvalidFileNameChars(), '_');
|
||||
From = null;
|
||||
To = null;
|
||||
PartitionLimit = _settingsService.LastPartitionLimit;
|
||||
});
|
||||
}
|
||||
|
||||
private void Export()
|
||||
{
|
||||
// Persist preferences
|
||||
_settingsService.LastExportFormat = SelectedFormat;
|
||||
_settingsService.LastPartitionLimit = PartitionLimit;
|
||||
|
||||
// Clamp 'from' and 'to' values
|
||||
if (From > To)
|
||||
From = To;
|
||||
if (To < From)
|
||||
To = From;
|
||||
|
||||
// Start export
|
||||
MessengerInstance.Send(new StartExportMessage(Channel, FilePath, SelectedFormat, From, To, PartitionLimit));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MaterialDesignThemes.Wpf;
|
||||
using Microsoft.Win32;
|
||||
using Ookii.Dialogs.Wpf;
|
||||
using Stylet;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Framework
|
||||
{
|
||||
public class DialogManager
|
||||
{
|
||||
private readonly IViewManager _viewManager;
|
||||
|
||||
public DialogManager(IViewManager viewManager)
|
||||
{
|
||||
_viewManager = viewManager;
|
||||
}
|
||||
|
||||
public async Task<T> ShowDialogAsync<T>(DialogScreen<T> dialogScreen)
|
||||
{
|
||||
// Get the view that renders this viewmodel
|
||||
var view = _viewManager.CreateAndBindViewForModelIfNecessary(dialogScreen);
|
||||
|
||||
// Set up event routing that will close the view when called from viewmodel
|
||||
DialogOpenedEventHandler onDialogOpened = (sender, e) =>
|
||||
{
|
||||
// Delegate to close the dialog and unregister event handler
|
||||
void OnScreenClosed(object o, CloseEventArgs args)
|
||||
{
|
||||
e.Session.Close();
|
||||
dialogScreen.Closed -= OnScreenClosed;
|
||||
}
|
||||
|
||||
dialogScreen.Closed += OnScreenClosed;
|
||||
};
|
||||
|
||||
// Show view
|
||||
await DialogHost.Show(view, onDialogOpened);
|
||||
|
||||
// Return the result
|
||||
return dialogScreen.DialogResult;
|
||||
}
|
||||
|
||||
public string PromptSaveFilePath(string filter = "All files|*.*", string initialFilePath = "")
|
||||
{
|
||||
// Create dialog
|
||||
var dialog = new SaveFileDialog
|
||||
{
|
||||
Filter = filter,
|
||||
AddExtension = true,
|
||||
FileName = initialFilePath,
|
||||
DefaultExt = Path.GetExtension(initialFilePath) ?? ""
|
||||
};
|
||||
|
||||
// Show dialog and return result
|
||||
return dialog.ShowDialog() == true ? dialog.FileName : null;
|
||||
}
|
||||
|
||||
public string PromptDirectoryPath(string initialDirPath = "")
|
||||
{
|
||||
// Create dialog
|
||||
var dialog = new VistaFolderBrowserDialog
|
||||
{
|
||||
SelectedPath = initialDirPath
|
||||
};
|
||||
|
||||
// Show dialog and return result
|
||||
return dialog.ShowDialog() == true ? dialog.SelectedPath : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Stylet;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Framework
|
||||
{
|
||||
public abstract class DialogScreen<T> : Screen
|
||||
{
|
||||
public T DialogResult { get; private set; }
|
||||
|
||||
public void Close(T dialogResult = default(T))
|
||||
{
|
||||
// Set the result
|
||||
DialogResult = dialogResult;
|
||||
|
||||
// If there is a parent - ask them to close this dialog
|
||||
if (Parent != null)
|
||||
RequestClose(Equals(dialogResult, default(T)));
|
||||
// Otherwise close ourselves
|
||||
else
|
||||
((IScreenState) this).Close();
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class DialogScreen : DialogScreen<bool?>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Gui.ViewModels.Components;
|
||||
using DiscordChatExporter.Gui.ViewModels.Dialogs;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Framework
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static ChannelViewModel CreateChannelViewModel(this IViewModelFactory factory, Channel model,
|
||||
string category = null)
|
||||
{
|
||||
var viewModel = factory.CreateChannelViewModel();
|
||||
viewModel.Model = model;
|
||||
viewModel.Category = category;
|
||||
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
public static GuildViewModel CreateGuildViewModel(this IViewModelFactory factory, Guild model,
|
||||
IReadOnlyList<ChannelViewModel> channels)
|
||||
{
|
||||
var viewModel = factory.CreateGuildViewModel();
|
||||
viewModel.Model = model;
|
||||
viewModel.Channels = channels;
|
||||
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
public static ExportSetupViewModel CreateExportSetupViewModel(this IViewModelFactory factory,
|
||||
GuildViewModel guild, IReadOnlyList<ChannelViewModel> channels)
|
||||
{
|
||||
var viewModel = factory.CreateExportSetupViewModel();
|
||||
viewModel.Guild = guild;
|
||||
viewModel.Channels = channels;
|
||||
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
public static ExportSetupViewModel CreateExportSetupViewModel(this IViewModelFactory factory,
|
||||
GuildViewModel guild, ChannelViewModel channel)
|
||||
=> factory.CreateExportSetupViewModel(guild, new[] {channel});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using DiscordChatExporter.Gui.ViewModels.Components;
|
||||
using DiscordChatExporter.Gui.ViewModels.Dialogs;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Framework
|
||||
{
|
||||
// Used to instantiate new view models while making use of dependency injection
|
||||
public interface IViewModelFactory
|
||||
{
|
||||
ChannelViewModel CreateChannelViewModel();
|
||||
|
||||
GuildViewModel CreateGuildViewModel();
|
||||
|
||||
ExportSetupViewModel CreateExportSetupViewModel();
|
||||
|
||||
SettingsViewModel CreateSettingsViewModel();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using GalaSoft.MvvmLight.CommandWpf;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public interface IExportSetupViewModel
|
||||
{
|
||||
Guild Guild { get; }
|
||||
Channel Channel { get; }
|
||||
string FilePath { get; set; }
|
||||
IReadOnlyList<ExportFormat> AvailableFormats { get; }
|
||||
ExportFormat SelectedFormat { get; set; }
|
||||
DateTime? From { get; set; }
|
||||
DateTime? To { get; set; }
|
||||
int? PartitionLimit { get; set; }
|
||||
|
||||
RelayCommand ExportCommand { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using GalaSoft.MvvmLight.CommandWpf;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public interface IMainViewModel
|
||||
{
|
||||
bool IsBusy { get; }
|
||||
bool IsDataAvailable { get; }
|
||||
|
||||
bool IsProgressIndeterminate { get; }
|
||||
double Progress { get; }
|
||||
|
||||
bool IsBotToken { get; set; }
|
||||
string TokenValue { get; set; }
|
||||
|
||||
IReadOnlyList<Guild> AvailableGuilds { get; }
|
||||
Guild SelectedGuild { get; set; }
|
||||
IReadOnlyList<Channel> AvailableChannels { get; }
|
||||
|
||||
RelayCommand ViewLoadedCommand { get; }
|
||||
RelayCommand ViewClosedCommand { get; }
|
||||
RelayCommand PullDataCommand { get; }
|
||||
RelayCommand ShowSettingsCommand { get; }
|
||||
RelayCommand ShowAboutCommand { get; }
|
||||
RelayCommand<Channel> ShowExportSetupCommand { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public interface ISettingsViewModel
|
||||
{
|
||||
bool IsAutoUpdateEnabled { get; set; }
|
||||
|
||||
string DateFormat { get; set; }
|
||||
int MessageGroupLimit { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.Messages;
|
||||
using GalaSoft.MvvmLight;
|
||||
using GalaSoft.MvvmLight.CommandWpf;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public class MainViewModel : ViewModelBase, IMainViewModel
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
private readonly IUpdateService _updateService;
|
||||
private readonly IDataService _dataService;
|
||||
private readonly IExportService _exportService;
|
||||
|
||||
private readonly Dictionary<Guild, IReadOnlyList<Channel>> _guildChannelsMap;
|
||||
|
||||
private bool _isBusy;
|
||||
private double _progress;
|
||||
private bool _isBotToken;
|
||||
private string _tokenValue;
|
||||
private IReadOnlyList<Guild> _availableGuilds;
|
||||
private Guild _selectedGuild;
|
||||
private IReadOnlyList<Channel> _availableChannels;
|
||||
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _isBusy;
|
||||
private set
|
||||
{
|
||||
Set(ref _isBusy, value);
|
||||
PullDataCommand.RaiseCanExecuteChanged();
|
||||
ShowExportSetupCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDataAvailable => AvailableGuilds.NotNullAndAny();
|
||||
|
||||
public bool IsProgressIndeterminate => Progress <= 0;
|
||||
|
||||
public double Progress
|
||||
{
|
||||
get => _progress;
|
||||
private set
|
||||
{
|
||||
Set(ref _progress, value);
|
||||
RaisePropertyChanged(() => IsProgressIndeterminate);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBotToken
|
||||
{
|
||||
get => _isBotToken;
|
||||
set => Set(ref _isBotToken, value);
|
||||
}
|
||||
|
||||
public string TokenValue
|
||||
{
|
||||
get => _tokenValue;
|
||||
set
|
||||
{
|
||||
// Remove invalid chars
|
||||
value = value?.Trim('"');
|
||||
|
||||
Set(ref _tokenValue, value);
|
||||
PullDataCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<Guild> AvailableGuilds
|
||||
{
|
||||
get => _availableGuilds;
|
||||
private set
|
||||
{
|
||||
Set(ref _availableGuilds, value);
|
||||
RaisePropertyChanged(() => IsDataAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
public Guild SelectedGuild
|
||||
{
|
||||
get => _selectedGuild;
|
||||
set
|
||||
{
|
||||
Set(ref _selectedGuild, value);
|
||||
AvailableChannels = value != null ? _guildChannelsMap[value] : Array.Empty<Channel>();
|
||||
ShowExportSetupCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<Channel> AvailableChannels
|
||||
{
|
||||
get => _availableChannels;
|
||||
private set => Set(ref _availableChannels, value);
|
||||
}
|
||||
|
||||
public RelayCommand ViewLoadedCommand { get; }
|
||||
public RelayCommand ViewClosedCommand { get; }
|
||||
public RelayCommand PullDataCommand { get; }
|
||||
public RelayCommand ShowSettingsCommand { get; }
|
||||
public RelayCommand ShowAboutCommand { get; }
|
||||
public RelayCommand<Channel> ShowExportSetupCommand { get; }
|
||||
|
||||
public MainViewModel(ISettingsService settingsService, IUpdateService updateService, IDataService dataService,
|
||||
IExportService exportService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
_updateService = updateService;
|
||||
_dataService = dataService;
|
||||
_exportService = exportService;
|
||||
|
||||
_guildChannelsMap = new Dictionary<Guild, IReadOnlyList<Channel>>();
|
||||
|
||||
// Commands
|
||||
ViewLoadedCommand = new RelayCommand(ViewLoaded);
|
||||
ViewClosedCommand = new RelayCommand(ViewClosed);
|
||||
PullDataCommand = new RelayCommand(PullData, () => TokenValue.IsNotBlank() && !IsBusy);
|
||||
ShowSettingsCommand = new RelayCommand(ShowSettings);
|
||||
ShowAboutCommand = new RelayCommand(ShowAbout);
|
||||
ShowExportSetupCommand = new RelayCommand<Channel>(ShowExportSetup, _ => !IsBusy);
|
||||
|
||||
// Messages
|
||||
MessengerInstance.Register<StartExportMessage>(this,
|
||||
m => Export(m.Channel, m.FilePath, m.Format, m.From, m.To, m.PartitionLimit));
|
||||
}
|
||||
|
||||
private async void ViewLoaded()
|
||||
{
|
||||
// Load settings
|
||||
_settingsService.Load();
|
||||
|
||||
// Get last token
|
||||
if (_settingsService.LastToken != null)
|
||||
{
|
||||
IsBotToken = _settingsService.LastToken.Type == AuthTokenType.Bot;
|
||||
TokenValue = _settingsService.LastToken.Value;
|
||||
}
|
||||
|
||||
// Check and prepare update
|
||||
try
|
||||
{
|
||||
var updateVersion = await _updateService.CheckPrepareUpdateAsync();
|
||||
if (updateVersion != null)
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage(
|
||||
$"Update to DiscordChatExporter v{updateVersion} will be installed when you exit",
|
||||
"INSTALL NOW", () =>
|
||||
{
|
||||
_updateService.NeedRestart = true;
|
||||
Application.Current.Shutdown();
|
||||
}));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage("Failed to perform application auto-update"));
|
||||
}
|
||||
}
|
||||
|
||||
private void ViewClosed()
|
||||
{
|
||||
// Save settings
|
||||
_settingsService.Save();
|
||||
|
||||
// Finalize updates if available
|
||||
_updateService.FinalizeUpdate();
|
||||
}
|
||||
|
||||
private async void PullData()
|
||||
{
|
||||
IsBusy = true;
|
||||
|
||||
// Create token
|
||||
var token = new AuthToken(
|
||||
IsBotToken ? AuthTokenType.Bot : AuthTokenType.User,
|
||||
TokenValue);
|
||||
|
||||
// Save token
|
||||
_settingsService.LastToken = token;
|
||||
|
||||
// Clear existing
|
||||
_guildChannelsMap.Clear();
|
||||
|
||||
try
|
||||
{
|
||||
// Get DM channels
|
||||
{
|
||||
var channels = await _dataService.GetDirectMessageChannelsAsync(token);
|
||||
var guild = Guild.DirectMessages;
|
||||
_guildChannelsMap[guild] = channels.OrderBy(c => c.Name).ToArray();
|
||||
}
|
||||
|
||||
// Get guild channels
|
||||
{
|
||||
var guilds = await _dataService.GetUserGuildsAsync(token);
|
||||
foreach (var guild in guilds)
|
||||
{
|
||||
var channels = await _dataService.GetGuildChannelsAsync(token, guild.Id);
|
||||
_guildChannelsMap[guild] = channels.Where(c => c.Type == ChannelType.GuildTextChat)
|
||||
.OrderBy(c => c.Name)
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage("Unauthorized – make sure the token is valid"));
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage("Forbidden – account may be locked by 2FA"));
|
||||
}
|
||||
|
||||
AvailableGuilds = _guildChannelsMap.Keys.ToArray();
|
||||
SelectedGuild = AvailableGuilds.FirstOrDefault();
|
||||
IsBusy = false;
|
||||
}
|
||||
|
||||
private void ShowSettings()
|
||||
{
|
||||
MessengerInstance.Send(new ShowSettingsMessage());
|
||||
}
|
||||
|
||||
private void ShowAbout()
|
||||
{
|
||||
Process.Start("https://github.com/Tyrrrz/DiscordChatExporter");
|
||||
}
|
||||
|
||||
private void ShowExportSetup(Channel channel)
|
||||
{
|
||||
MessengerInstance.Send(new ShowExportSetupMessage(SelectedGuild, channel));
|
||||
}
|
||||
|
||||
private async void Export(Channel channel, string filePath, ExportFormat format,
|
||||
DateTime? from, DateTime? to, int? partitionLimit)
|
||||
{
|
||||
IsBusy = true;
|
||||
|
||||
// Get last used token
|
||||
var token = _settingsService.LastToken;
|
||||
|
||||
// Get guild
|
||||
var guild = SelectedGuild;
|
||||
|
||||
// Create progress handler
|
||||
var progressHandler = new Progress<double>(p => Progress = p);
|
||||
|
||||
try
|
||||
{
|
||||
// Get chat log
|
||||
var chatLog = await _dataService.GetChatLogAsync(token, guild, channel, from, to, progressHandler);
|
||||
|
||||
// Export
|
||||
_exportService.ExportChatLog(chatLog, filePath, format, partitionLimit);
|
||||
|
||||
// Notify completion
|
||||
MessengerInstance.Send(new ShowNotificationMessage("Export complete"));
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage("You don't have access to this channel"));
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
MessengerInstance.Send(new ShowNotificationMessage("This channel doesn't exist"));
|
||||
}
|
||||
|
||||
Progress = 0;
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Helpers;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels.Components;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
using Gress;
|
||||
using MaterialDesignThemes.Wpf;
|
||||
using Stylet;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public class RootViewModel : Screen
|
||||
{
|
||||
private readonly IViewModelFactory _viewModelFactory;
|
||||
private readonly DialogManager _dialogManager;
|
||||
private readonly SettingsService _settingsService;
|
||||
private readonly UpdateService _updateService;
|
||||
private readonly DataService _dataService;
|
||||
private readonly ExportService _exportService;
|
||||
|
||||
public ISnackbarMessageQueue Notifications { get; } = new SnackbarMessageQueue(TimeSpan.FromSeconds(5));
|
||||
|
||||
public IProgressManager ProgressManager { get; } = new ProgressManager();
|
||||
|
||||
public bool IsBusy { get; private set; }
|
||||
|
||||
public bool IsProgressIndeterminate { get; private set; }
|
||||
|
||||
public bool IsBotToken { get; set; }
|
||||
|
||||
public string TokenValue { get; set; }
|
||||
|
||||
public IReadOnlyList<GuildViewModel> AvailableGuilds { get; private set; }
|
||||
|
||||
public GuildViewModel SelectedGuild { get; set; }
|
||||
|
||||
public IReadOnlyList<ChannelViewModel> SelectedChannels { get; set; }
|
||||
|
||||
public RootViewModel(IViewModelFactory viewModelFactory, DialogManager dialogManager,
|
||||
SettingsService settingsService, UpdateService updateService, DataService dataService,
|
||||
ExportService exportService)
|
||||
{
|
||||
_viewModelFactory = viewModelFactory;
|
||||
_dialogManager = dialogManager;
|
||||
_settingsService = settingsService;
|
||||
_updateService = updateService;
|
||||
_dataService = dataService;
|
||||
_exportService = exportService;
|
||||
|
||||
// Set title
|
||||
var version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
|
||||
DisplayName = $"DiscordChatExporter v{version}";
|
||||
|
||||
// Update busy state when progress manager changes
|
||||
ProgressManager.Bind(o => o.IsActive, (sender, args) => IsBusy = ProgressManager.IsActive);
|
||||
ProgressManager.Bind(o => o.IsActive,
|
||||
(sender, args) => IsProgressIndeterminate = ProgressManager.IsActive && ProgressManager.Progress <= 0);
|
||||
ProgressManager.Bind(o => o.Progress,
|
||||
(sender, args) => IsProgressIndeterminate = ProgressManager.IsActive && ProgressManager.Progress <= 0);
|
||||
}
|
||||
|
||||
protected override async void OnViewLoaded()
|
||||
{
|
||||
base.OnViewLoaded();
|
||||
|
||||
// Load settings
|
||||
_settingsService.Load();
|
||||
|
||||
// Get last token
|
||||
if (_settingsService.LastToken != null)
|
||||
{
|
||||
IsBotToken = _settingsService.LastToken.Type == AuthTokenType.Bot;
|
||||
TokenValue = _settingsService.LastToken.Value;
|
||||
}
|
||||
|
||||
// Check and prepare update
|
||||
try
|
||||
{
|
||||
var updateVersion = await _updateService.CheckPrepareUpdateAsync();
|
||||
if (updateVersion != null)
|
||||
{
|
||||
Notifications.Enqueue(
|
||||
$"Update to DiscordChatExporter v{updateVersion} will be installed when you exit",
|
||||
"INSTALL NOW", () =>
|
||||
{
|
||||
_updateService.FinalizeUpdate(true);
|
||||
RequestClose();
|
||||
});
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
Notifications.Enqueue("Failed to perform application auto-update");
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnClose()
|
||||
{
|
||||
base.OnClose();
|
||||
|
||||
// Save settings
|
||||
_settingsService.Save();
|
||||
|
||||
// Finalize updates if necessary
|
||||
_updateService.FinalizeUpdate(false);
|
||||
}
|
||||
|
||||
public async void ShowSettings()
|
||||
{
|
||||
// Create dialog
|
||||
var dialog = _viewModelFactory.CreateSettingsViewModel();
|
||||
|
||||
// Show dialog
|
||||
await _dialogManager.ShowDialogAsync(dialog);
|
||||
}
|
||||
|
||||
public bool CanPopulateGuildsAndChannels => !IsBusy && TokenValue.IsNotBlank();
|
||||
|
||||
public async void PopulateGuildsAndChannels()
|
||||
{
|
||||
// Create progress operation
|
||||
var operation = ProgressManager.CreateOperation();
|
||||
|
||||
try
|
||||
{
|
||||
// Sanitize token
|
||||
TokenValue = TokenValue.Trim('"');
|
||||
|
||||
// Create token
|
||||
var token = new AuthToken(
|
||||
IsBotToken ? AuthTokenType.Bot : AuthTokenType.User,
|
||||
TokenValue);
|
||||
|
||||
// Save token
|
||||
_settingsService.LastToken = token;
|
||||
|
||||
// Prepare available guild list
|
||||
var availableGuilds = new List<GuildViewModel>();
|
||||
|
||||
// Get direct messages
|
||||
{
|
||||
// Get fake guild
|
||||
var guild = Guild.DirectMessages;
|
||||
|
||||
// Get channels
|
||||
var channels = await _dataService.GetDirectMessageChannelsAsync(token);
|
||||
|
||||
// Create channel view models
|
||||
var channelViewModels = new List<ChannelViewModel>();
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
// Get fake category
|
||||
var category = channel.Type == ChannelType.DirectTextChat ? "Private" : "Group";
|
||||
|
||||
// Create channel view model
|
||||
var channelViewModel = _viewModelFactory.CreateChannelViewModel(channel, category);
|
||||
|
||||
// Add to list
|
||||
channelViewModels.Add(channelViewModel);
|
||||
}
|
||||
|
||||
// Create guild view model
|
||||
var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild,
|
||||
channelViewModels.OrderBy(c => c.Category)
|
||||
.ThenBy(c => c.Model.Name)
|
||||
.ToArray());
|
||||
|
||||
// Add to list
|
||||
availableGuilds.Add(guildViewModel);
|
||||
}
|
||||
|
||||
// Get guilds
|
||||
var guilds = await _dataService.GetUserGuildsAsync(token);
|
||||
foreach (var guild in guilds)
|
||||
{
|
||||
// Get channels
|
||||
var channels = await _dataService.GetGuildChannelsAsync(token, guild.Id);
|
||||
|
||||
// Get category channels
|
||||
var categoryChannels = channels.Where(c => c.Type == ChannelType.Category).ToArray();
|
||||
|
||||
// Get text channels
|
||||
var textChannels = channels.Where(c => c.Type == ChannelType.GuildTextChat).ToArray();
|
||||
|
||||
// Create channel view models
|
||||
var channelViewModels = new List<ChannelViewModel>();
|
||||
foreach (var channel in textChannels)
|
||||
{
|
||||
// Get category
|
||||
var category = categoryChannels.FirstOrDefault(c => c.Id == channel.ParentId)?.Name;
|
||||
|
||||
// Create channel view model
|
||||
var channelViewModel = _viewModelFactory.CreateChannelViewModel(channel, category);
|
||||
|
||||
// Add to list
|
||||
channelViewModels.Add(channelViewModel);
|
||||
}
|
||||
|
||||
// Create guild view model
|
||||
var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild,
|
||||
channelViewModels.OrderBy(c => c.Category)
|
||||
.ThenBy(c => c.Model.Name)
|
||||
.ToArray());
|
||||
|
||||
// Add to list
|
||||
availableGuilds.Add(guildViewModel);
|
||||
}
|
||||
|
||||
// Update available guild list
|
||||
AvailableGuilds = availableGuilds;
|
||||
|
||||
// Pre-select first guild
|
||||
SelectedGuild = AvailableGuilds.FirstOrDefault();
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
Notifications.Enqueue("Unauthorized – make sure the token is valid");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
Notifications.Enqueue("Forbidden – account may be locked by 2FA");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Dispose progress operation
|
||||
operation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanExportChannels => !IsBusy && SelectedChannels.NotNullAndAny();
|
||||
|
||||
public async void ExportChannels()
|
||||
{
|
||||
// Get last used token
|
||||
var token = _settingsService.LastToken;
|
||||
|
||||
// Create dialog
|
||||
var dialog = _viewModelFactory.CreateExportSetupViewModel(SelectedGuild, SelectedChannels);
|
||||
|
||||
// Show dialog, if canceled - return
|
||||
if (await _dialogManager.ShowDialogAsync(dialog) != true)
|
||||
return;
|
||||
|
||||
// Create a progress operation for each channel to export
|
||||
var operations = ProgressManager.CreateOperations(dialog.Channels.Count);
|
||||
|
||||
// Export channels
|
||||
for (var i = 0; i < dialog.Channels.Count; i++)
|
||||
{
|
||||
// Get operation and channel
|
||||
var operation = operations[i];
|
||||
var channel = dialog.Channels[i];
|
||||
|
||||
try
|
||||
{
|
||||
// Generate file path if necessary
|
||||
var filePath = dialog.OutputPath;
|
||||
if (ExportHelper.IsDirectoryPath(filePath))
|
||||
{
|
||||
// Generate default file name
|
||||
var fileName = ExportHelper.GetDefaultExportFileName(dialog.SelectedFormat, dialog.Guild,
|
||||
channel, dialog.From, dialog.To);
|
||||
|
||||
// Combine paths
|
||||
filePath = Path.Combine(filePath, fileName);
|
||||
}
|
||||
|
||||
// Get chat log
|
||||
var chatLog = await _dataService.GetChatLogAsync(token, dialog.Guild, channel,
|
||||
dialog.From, dialog.To, operation);
|
||||
|
||||
// Export
|
||||
_exportService.ExportChatLog(chatLog, filePath, dialog.SelectedFormat,
|
||||
dialog.PartitionLimit);
|
||||
|
||||
// Notify completion
|
||||
Notifications.Enqueue($"Channel [{channel.Model.Name}] successfully exported");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
Notifications.Enqueue($"You don't have access to channel [{channel.Model.Name}]");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
Notifications.Enqueue($"Channel [{channel.Model.Name}] doesn't exist");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Dispose progress operation
|
||||
operation.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using GalaSoft.MvvmLight;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels
|
||||
{
|
||||
public class SettingsViewModel : ViewModelBase, ISettingsViewModel
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
|
||||
public bool IsAutoUpdateEnabled
|
||||
{
|
||||
get => _settingsService.IsAutoUpdateEnabled;
|
||||
set => _settingsService.IsAutoUpdateEnabled = value;
|
||||
}
|
||||
|
||||
public string DateFormat
|
||||
{
|
||||
get => _settingsService.DateFormat;
|
||||
set => _settingsService.DateFormat = value;
|
||||
}
|
||||
|
||||
public int MessageGroupLimit
|
||||
{
|
||||
get => _settingsService.MessageGroupLimit;
|
||||
set => _settingsService.MessageGroupLimit = value.ClampMin(0);
|
||||
}
|
||||
|
||||
public SettingsViewModel(ISettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<UserControl
|
||||
x:Class="DiscordChatExporter.Gui.Views.Dialogs.ExportSetupView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:converters="clr-namespace:DiscordChatExporter.Gui.Converters"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:dialogs="clr-namespace:DiscordChatExporter.Gui.ViewModels.Dialogs"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:s="https://github.com/canton7/Stylet"
|
||||
Width="380"
|
||||
d:DataContext="{d:DesignInstance Type=dialogs:ExportSetupViewModel}"
|
||||
Style="{DynamicResource MaterialDesignRoot}"
|
||||
mc:Ignorable="d">
|
||||
<StackPanel>
|
||||
<!-- Guild/channel info -->
|
||||
<Grid Margin="16">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Guild icon -->
|
||||
<Ellipse
|
||||
Grid.Column="0"
|
||||
Width="32"
|
||||
Height="32">
|
||||
<Ellipse.Fill>
|
||||
<ImageBrush ImageSource="{Binding Guild.Model.IconUrl}" />
|
||||
</Ellipse.Fill>
|
||||
</Ellipse>
|
||||
|
||||
<!-- Placeholder (for multiple channels) -->
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
Margin="8,0,0,0"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="19"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}">
|
||||
<Run Text="{Binding Channels.Count, Mode=OneWay}" />
|
||||
<Run Text="channels selected" />
|
||||
</TextBlock>
|
||||
|
||||
<!-- Category and channel name (for single channel) -->
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
Margin="8,0,0,0"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="19"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
Visibility="{Binding IsSingleChannel, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
|
||||
<Run Text="{Binding Channels[0].Category, Mode=OneWay}" ToolTip="{Binding Channels[0].Category, Mode=OneWay}" />
|
||||
<Run Text="/" />
|
||||
<Run
|
||||
Foreground="{DynamicResource PrimaryTextBrush}"
|
||||
Text="{Binding Channels[0].Model.Name, Mode=OneWay}"
|
||||
ToolTip="{Binding Channels[0].Model.Name, Mode=OneWay}" />
|
||||
</TextBlock>
|
||||
</Grid>
|
||||
|
||||
<!-- Format -->
|
||||
<ComboBox
|
||||
Margin="16,8"
|
||||
materialDesign:HintAssist.Hint="Format"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
IsReadOnly="True"
|
||||
ItemsSource="{Binding AvailableFormats}"
|
||||
SelectedItem="{Binding SelectedFormat}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={x:Static converters:ExportFormatToStringConverter.Instance}}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
|
||||
<!-- Date limits -->
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<DatePicker
|
||||
Grid.Row="0"
|
||||
Grid.Column="0"
|
||||
Margin="16,8"
|
||||
materialDesign:HintAssist.Hint="From (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
DisplayDateEnd="{Binding To}"
|
||||
SelectedDate="{Binding From}"
|
||||
ToolTip="If this is set, only messages sent after this date will be exported" />
|
||||
<DatePicker
|
||||
Grid.Row="0"
|
||||
Grid.Column="1"
|
||||
Margin="16,8"
|
||||
materialDesign:HintAssist.Hint="To (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
DisplayDateStart="{Binding From}"
|
||||
SelectedDate="{Binding To}"
|
||||
ToolTip="If this is set, only messages sent before this date will be exported" />
|
||||
</Grid>
|
||||
|
||||
<!-- Partitioning -->
|
||||
<TextBox
|
||||
Margin="16,8"
|
||||
materialDesign:HintAssist.Hint="Messages per partition (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
Text="{Binding PartitionLimit, TargetNullValue=''}"
|
||||
ToolTip="If this is set, the exported file will be split into multiple partitions, each containing no more than specified number of messages" />
|
||||
|
||||
<!-- Buttons -->
|
||||
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
|
||||
<Button
|
||||
Margin="8"
|
||||
Command="{s:Action Confirm}"
|
||||
Content="EXPORT"
|
||||
IsDefault="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}" />
|
||||
<Button
|
||||
Margin="8"
|
||||
Command="{s:Action Close}"
|
||||
Content="CANCEL"
|
||||
IsCancel="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DiscordChatExporter.Gui.Views.Dialogs
|
||||
{
|
||||
public partial class ExportSetupView
|
||||
{
|
||||
public ExportSetupView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-14
@@ -1,33 +1,38 @@
|
||||
<UserControl
|
||||
x:Class="DiscordChatExporter.Gui.Views.SettingsDialog"
|
||||
x:Class="DiscordChatExporter.Gui.Views.Dialogs.SettingsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:dialogs="clr-namespace:DiscordChatExporter.Gui.ViewModels.Dialogs"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
Width="250"
|
||||
DataContext="{Binding SettingsViewModel, Source={StaticResource Container}}">
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:s="https://github.com/canton7/Stylet"
|
||||
Width="300"
|
||||
d:DataContext="{d:DesignInstance Type=dialogs:SettingsViewModel}"
|
||||
Style="{DynamicResource MaterialDesignRoot}"
|
||||
mc:Ignorable="d">
|
||||
<StackPanel>
|
||||
<TextBlock
|
||||
Margin="16"
|
||||
FontSize="17"
|
||||
Foreground="{DynamicResource PrimaryTextBrush}"
|
||||
Text="Settings" />
|
||||
|
||||
<!-- Date format -->
|
||||
<TextBox
|
||||
Margin="16,16,16,8"
|
||||
Margin="16,8"
|
||||
materialDesign:HintAssist.Hint="Date format"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
Text="{Binding DateFormat}" />
|
||||
|
||||
<!-- Message group limit -->
|
||||
<TextBox
|
||||
Margin="16,8,16,8"
|
||||
materialDesign:HintAssist.Hint="Message group limit"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
Text="{Binding MessageGroupLimit}" />
|
||||
|
||||
<!-- Auto-updates -->
|
||||
<DockPanel LastChildFill="False">
|
||||
<TextBlock
|
||||
Margin="16,8,16,8"
|
||||
Margin="16,8"
|
||||
DockPanel.Dock="Left"
|
||||
Text="Auto-updates" />
|
||||
<ToggleButton
|
||||
Margin="16,8,16,8"
|
||||
Margin="16,8"
|
||||
DockPanel.Dock="Right"
|
||||
IsChecked="{Binding IsAutoUpdateEnabled}" />
|
||||
</DockPanel>
|
||||
@@ -36,7 +41,7 @@
|
||||
<Button
|
||||
Margin="8"
|
||||
HorizontalAlignment="Right"
|
||||
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
|
||||
Command="{s:Action Close}"
|
||||
Content="SAVE"
|
||||
IsCancel="True"
|
||||
IsDefault="True"
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DiscordChatExporter.Gui.Views.Dialogs
|
||||
{
|
||||
public partial class SettingsView
|
||||
{
|
||||
public SettingsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
<UserControl
|
||||
x:Class="DiscordChatExporter.Gui.Views.ExportSetupDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
Width="325"
|
||||
DataContext="{Binding ExportSetupViewModel, Source={StaticResource Container}}">
|
||||
<StackPanel>
|
||||
<!-- File path -->
|
||||
<TextBox
|
||||
Margin="16,16,16,8"
|
||||
materialDesign:HintAssist.Hint="Output file"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
IsReadOnly="True"
|
||||
Text="{Binding FilePath, UpdateSourceTrigger=PropertyChanged}" />
|
||||
|
||||
<!-- Format -->
|
||||
<ComboBox
|
||||
Margin="16,8,16,8"
|
||||
materialDesign:HintAssist.Hint="Export format"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
IsReadOnly="True"
|
||||
ItemsSource="{Binding AvailableFormats}"
|
||||
SelectedItem="{Binding SelectedFormat}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={StaticResource ExportFormatToStringConverter}}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
|
||||
<!-- Date limits -->
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<DatePicker
|
||||
x:Name="FromDatePicker"
|
||||
Grid.Row="0"
|
||||
Grid.Column="0"
|
||||
Margin="16,20,8,8"
|
||||
materialDesign:HintAssist.Hint="From (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
DisplayDateEnd="{Binding SelectedDate, ElementName=ToDatePicker}"
|
||||
SelectedDate="{Binding From}" />
|
||||
<DatePicker
|
||||
x:Name="ToDatePicker"
|
||||
Grid.Row="0"
|
||||
Grid.Column="1"
|
||||
Margin="8,20,16,8"
|
||||
materialDesign:HintAssist.Hint="To (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
DisplayDateStart="{Binding SelectedDate, ElementName=FromDatePicker}"
|
||||
SelectedDate="{Binding To}" />
|
||||
</Grid>
|
||||
|
||||
<!-- Partitioning -->
|
||||
<TextBox
|
||||
Margin="16,8,16,8"
|
||||
materialDesign:HintAssist.Hint="Messages per partition (optional)"
|
||||
materialDesign:HintAssist.IsFloating="True"
|
||||
Text="{Binding PartitionLimit, TargetNullValue=''}" />
|
||||
|
||||
<!-- Buttons -->
|
||||
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
|
||||
<Button
|
||||
x:Name="BrowseButton"
|
||||
Margin="8"
|
||||
Click="BrowseButton_Click"
|
||||
Content="BROWSE"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}" />
|
||||
<Button
|
||||
x:Name="ExportButton"
|
||||
Margin="8"
|
||||
Click="ExportButton_Click"
|
||||
Command="{Binding ExportCommand}"
|
||||
Content="EXPORT"
|
||||
IsDefault="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}" />
|
||||
<Button
|
||||
Margin="8"
|
||||
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"
|
||||
Content="CANCEL"
|
||||
IsCancel="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -1,44 +0,0 @@
|
||||
using System.Windows;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Gui.ViewModels;
|
||||
using MaterialDesignThemes.Wpf;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Views
|
||||
{
|
||||
public partial class ExportSetupDialog
|
||||
{
|
||||
private IExportSetupViewModel ViewModel => (IExportSetupViewModel)DataContext;
|
||||
|
||||
public ExportSetupDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void BrowseButton_Click(object sender, RoutedEventArgs args)
|
||||
{
|
||||
// Get file extension of the selected format
|
||||
var ext = ViewModel.SelectedFormat.GetFileExtension();
|
||||
|
||||
// Open dialog
|
||||
var sfd = new SaveFileDialog
|
||||
{
|
||||
FileName = ViewModel.FilePath,
|
||||
Filter = $"{ext.ToUpperInvariant()} Files|*.{ext}|All Files|*.*",
|
||||
AddExtension = true,
|
||||
Title = "Select output file"
|
||||
};
|
||||
|
||||
// Assign new file path if dialog was successful
|
||||
if (sfd.ShowDialog() == true)
|
||||
{
|
||||
ViewModel.FilePath = sfd.FileName;
|
||||
}
|
||||
}
|
||||
|
||||
public void ExportButton_Click(object sender, RoutedEventArgs args)
|
||||
{
|
||||
DialogHost.CloseDialogCommand.Execute(null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
<Window
|
||||
x:Class="DiscordChatExporter.Gui.Views.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
Title="DiscordChatExporter"
|
||||
Width="600"
|
||||
Height="550"
|
||||
Background="{DynamicResource MaterialDesignPaper}"
|
||||
DataContext="{Binding MainViewModel, Source={StaticResource Container}}"
|
||||
FocusManager.FocusedElement="{Binding ElementName=TokenValueTextBox}"
|
||||
FontFamily="{DynamicResource MaterialDesignFont}"
|
||||
Icon="/DiscordChatExporter;component/favicon.ico"
|
||||
SnapsToDevicePixels="True"
|
||||
TextElement.FontSize="13"
|
||||
TextElement.FontWeight="Regular"
|
||||
TextElement.Foreground="{DynamicResource SecondaryTextBrush}"
|
||||
TextOptions.TextFormattingMode="Ideal"
|
||||
TextOptions.TextRenderingMode="Auto"
|
||||
UseLayoutRounding="True"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<i:Interaction.Triggers>
|
||||
<i:EventTrigger EventName="Loaded">
|
||||
<i:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
|
||||
</i:EventTrigger>
|
||||
<i:EventTrigger EventName="Closed">
|
||||
<i:InvokeCommandAction Command="{Binding ViewClosedCommand}" />
|
||||
</i:EventTrigger>
|
||||
</i:Interaction.Triggers>
|
||||
<materialDesign:DialogHost SnackbarMessageQueue="{Binding ElementName=Snackbar}">
|
||||
<DockPanel>
|
||||
<!-- Toolbar -->
|
||||
<Border
|
||||
Background="{DynamicResource PrimaryHueMidBrush}"
|
||||
DockPanel.Dock="Top"
|
||||
IsEnabled="{Binding IsBusy, Converter={StaticResource InvertBoolConverter}}"
|
||||
TextElement.Foreground="{DynamicResource SecondaryInverseTextBrush}">
|
||||
<StackPanel>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<materialDesign:Card
|
||||
Grid.Row="0"
|
||||
Grid.Column="0"
|
||||
Margin="6,6,0,6">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Token type -->
|
||||
<ToggleButton
|
||||
Grid.Column="0"
|
||||
Margin="6"
|
||||
IsChecked="{Binding IsBotToken}"
|
||||
Style="{StaticResource MaterialDesignFlatActionToggleButton}"
|
||||
ToolTip="Switch between user token and bot token">
|
||||
<ToggleButton.Content>
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="Account" />
|
||||
</ToggleButton.Content>
|
||||
<materialDesign:ToggleButtonAssist.OnContent>
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="Robot" />
|
||||
</materialDesign:ToggleButtonAssist.OnContent>
|
||||
</ToggleButton>
|
||||
|
||||
<!-- Token value -->
|
||||
<TextBox
|
||||
x:Name="TokenValueTextBox"
|
||||
Grid.Column="1"
|
||||
Margin="2,6,6,7"
|
||||
materialDesign:HintAssist.Hint="Token"
|
||||
materialDesign:TextFieldAssist.DecorationVisibility="Hidden"
|
||||
materialDesign:TextFieldAssist.TextBoxViewMargin="0,0,2,0"
|
||||
BorderThickness="0"
|
||||
FontSize="16"
|
||||
Text="{Binding TokenValue, UpdateSourceTrigger=PropertyChanged}" />
|
||||
|
||||
<!-- Pull data button -->
|
||||
<Button
|
||||
Grid.Column="2"
|
||||
Margin="0,6,6,6"
|
||||
Padding="4"
|
||||
Command="{Binding PullDataCommand}"
|
||||
IsDefault="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}">
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="ArrowRight" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</materialDesign:Card>
|
||||
|
||||
<!-- Menu -->
|
||||
<materialDesign:PopupBox
|
||||
Grid.Row="0"
|
||||
Grid.Column="1"
|
||||
Foreground="{DynamicResource PrimaryHueMidForegroundBrush}"
|
||||
PlacementMode="LeftAndAlignTopEdges">
|
||||
<StackPanel>
|
||||
<Button Command="{Binding ShowSettingsCommand}" Content="Settings" />
|
||||
<Button Command="{Binding ShowAboutCommand}" Content="About" />
|
||||
</StackPanel>
|
||||
</materialDesign:PopupBox>
|
||||
</Grid>
|
||||
|
||||
<!-- Progress bar -->
|
||||
<ProgressBar
|
||||
Background="Transparent"
|
||||
IsIndeterminate="{Binding IsProgressIndeterminate}"
|
||||
Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibilityConverter}}"
|
||||
Value="{Binding Progress, Mode=OneWay}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Content -->
|
||||
<Grid>
|
||||
<DockPanel
|
||||
Background="{DynamicResource MaterialDesignCardBackground}"
|
||||
IsEnabled="{Binding IsBusy, Converter={StaticResource InvertBoolConverter}}"
|
||||
Visibility="{Binding IsDataAvailable, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
|
||||
<!-- Guilds -->
|
||||
<Border
|
||||
BorderBrush="{DynamicResource DividerBrush}"
|
||||
BorderThickness="0,0,1,0"
|
||||
DockPanel.Dock="Left">
|
||||
<ListBox
|
||||
ItemsSource="{Binding AvailableGuilds}"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Hidden"
|
||||
SelectedItem="{Binding SelectedGuild}"
|
||||
VirtualizingStackPanel.IsVirtualizing="False">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<materialDesign:TransitioningContent>
|
||||
<materialDesign:TransitioningContent.OpeningEffect>
|
||||
<materialDesign:TransitionEffect Kind="SlideInFromLeft" Duration="0:0:0.3" />
|
||||
</materialDesign:TransitioningContent.OpeningEffect>
|
||||
<Grid
|
||||
Margin="-8"
|
||||
Background="Transparent"
|
||||
Cursor="Hand"
|
||||
ToolTip="{Binding Name}">
|
||||
<!-- Guild icon placeholder -->
|
||||
<Ellipse
|
||||
Width="48"
|
||||
Height="48"
|
||||
Margin="12,4,12,4"
|
||||
Fill="{DynamicResource DividerBrush}" />
|
||||
|
||||
<!-- Guild icon -->
|
||||
<Ellipse
|
||||
Width="48"
|
||||
Height="48"
|
||||
Margin="12,4,12,4">
|
||||
<Ellipse.Fill>
|
||||
<ImageBrush ImageSource="{Binding IconUrl}" />
|
||||
</Ellipse.Fill>
|
||||
</Ellipse>
|
||||
</Grid>
|
||||
</materialDesign:TransitioningContent>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
|
||||
<!-- Channels -->
|
||||
<Border>
|
||||
<ListBox
|
||||
HorizontalContentAlignment="Stretch"
|
||||
ItemsSource="{Binding AvailableChannels}"
|
||||
VirtualizingStackPanel.IsVirtualizing="False">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<materialDesign:TransitioningContent>
|
||||
<materialDesign:TransitioningContent.OpeningEffect>
|
||||
<materialDesign:TransitionEffect Kind="SlideInFromLeft" Duration="0:0:0.3" />
|
||||
</materialDesign:TransitioningContent.OpeningEffect>
|
||||
<StackPanel
|
||||
Margin="-8"
|
||||
Background="Transparent"
|
||||
Cursor="Hand"
|
||||
Orientation="Horizontal">
|
||||
<StackPanel.InputBindings>
|
||||
<MouseBinding
|
||||
Command="{Binding DataContext.ShowExportSetupCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
|
||||
CommandParameter="{Binding}"
|
||||
MouseAction="LeftClick" />
|
||||
</StackPanel.InputBindings>
|
||||
<materialDesign:PackIcon
|
||||
Margin="16,7,0,6"
|
||||
VerticalAlignment="Center"
|
||||
Kind="Pound" />
|
||||
<TextBlock
|
||||
Margin="3,8,8,8"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="14"
|
||||
Text="{Binding Name}" />
|
||||
</StackPanel>
|
||||
</materialDesign:TransitioningContent>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
</DockPanel>
|
||||
|
||||
<!-- Usage instructions -->
|
||||
<Grid Margin="32,32,8,8" Visibility="{Binding IsDataAvailable, Converter={StaticResource InvertBoolToVisibilityConverter}}">
|
||||
<!-- User token -->
|
||||
<StackPanel Visibility="{Binding IsBotToken, Converter={StaticResource InvertBoolToVisibilityConverter}}">
|
||||
<TextBlock FontSize="18" Text="DiscordChatExporter needs your user token to work." />
|
||||
<TextBlock
|
||||
Margin="0,8,0,0"
|
||||
FontSize="16"
|
||||
Text="To obtain it, follow these steps:" />
|
||||
<TextBlock Margin="8,0,0,0" FontSize="14">
|
||||
<Run Text="1. Open the Discord app" />
|
||||
<LineBreak />
|
||||
<Run Text="2. Log in if you haven't" />
|
||||
<LineBreak />
|
||||
<Run Text="3. Press" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Ctrl+Shift+I" />
|
||||
<Run Text="to show developer tools" />
|
||||
<LineBreak />
|
||||
<Run Text="4. Press" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Ctrl+R" />
|
||||
<Run Text="to trigger reload" />
|
||||
<LineBreak />
|
||||
<Run Text="5. Navigate to the" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Application" />
|
||||
<Run Text="tab" />
|
||||
<LineBreak />
|
||||
<Run Text="6. Select" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Local Storage" />
|
||||
<Run Text=">" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="https://discordapp.com" />
|
||||
<Run Text="on the left" />
|
||||
<LineBreak />
|
||||
<Run Text="7. Find" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="token" />
|
||||
<Run Text="under key and copy the value" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Bot token -->
|
||||
<StackPanel Visibility="{Binding IsBotToken, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
<TextBlock FontSize="18" Text="DiscordChatExporter needs your bot token to work." />
|
||||
<TextBlock
|
||||
Margin="0,8,0,0"
|
||||
FontSize="16"
|
||||
Text="To obtain it, follow these steps:" />
|
||||
<TextBlock Margin="8,0,0,0" FontSize="14">
|
||||
<Run Text="1. Go to Discord developer portal" />
|
||||
<LineBreak />
|
||||
<Run Text="2. Log in if you haven't" />
|
||||
<LineBreak />
|
||||
<Run Text="3. Open your application's settings" />
|
||||
<LineBreak />
|
||||
<Run Text="4. Navigate to the" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Bot" />
|
||||
<Run Text="section on the left" />
|
||||
<LineBreak />
|
||||
<Run Text="5. Under" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Token" />
|
||||
<Run Text="click" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Copy" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<materialDesign:Snackbar x:Name="Snackbar" />
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
</materialDesign:DialogHost>
|
||||
</Window>
|
||||
@@ -1,35 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using DiscordChatExporter.Gui.Messages;
|
||||
using GalaSoft.MvvmLight.Messaging;
|
||||
using MaterialDesignThemes.Wpf;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Views
|
||||
{
|
||||
public partial class MainWindow
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Title += $" v{Assembly.GetExecutingAssembly().GetName().Version}";
|
||||
|
||||
Snackbar.MessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Notification messages
|
||||
Messenger.Default.Register<ShowNotificationMessage>(this, m =>
|
||||
{
|
||||
if (m.CallbackCaption != null && m.Callback != null)
|
||||
Snackbar.MessageQueue.Enqueue(m.Message, m.CallbackCaption, m.Callback);
|
||||
else
|
||||
Snackbar.MessageQueue.Enqueue(m.Message);
|
||||
});
|
||||
|
||||
// Dialog messages
|
||||
Messenger.Default.Register<ShowExportSetupMessage>(this,
|
||||
m => DialogHost.Show(new ExportSetupDialog()).Forget());
|
||||
Messenger.Default.Register<ShowSettingsMessage>(this,
|
||||
m => DialogHost.Show(new SettingsDialog()).Forget());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
<Window
|
||||
x:Class="DiscordChatExporter.Gui.Views.RootView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:behaviors="clr-namespace:DiscordChatExporter.Gui.Behaviors"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:s="https://github.com/canton7/Stylet"
|
||||
xmlns:viewModels="clr-namespace:DiscordChatExporter.Gui.ViewModels"
|
||||
Width="600"
|
||||
Height="550"
|
||||
MinWidth="325"
|
||||
d:DataContext="{d:DesignInstance Type=viewModels:RootViewModel}"
|
||||
Background="{DynamicResource MaterialDesignPaper}"
|
||||
FocusManager.FocusedElement="{Binding ElementName=TokenValueTextBox}"
|
||||
Icon="/DiscordChatExporter;component/favicon.ico"
|
||||
Style="{DynamicResource MaterialDesignRoot}"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
mc:Ignorable="d">
|
||||
<Window.TaskbarItemInfo>
|
||||
<TaskbarItemInfo ProgressState="Normal" ProgressValue="{Binding ProgressManager.Progress}" />
|
||||
</Window.TaskbarItemInfo>
|
||||
<materialDesign:DialogHost SnackbarMessageQueue="{Binding Notifications}" Style="{DynamicResource MaterialDesignEmbeddedDialogHost}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Toolbar -->
|
||||
<Grid
|
||||
Grid.Row="0"
|
||||
Background="{DynamicResource PrimaryHueMidBrush}"
|
||||
TextElement.Foreground="{DynamicResource SecondaryInverseTextBrush}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Token and pull data button -->
|
||||
<materialDesign:Card
|
||||
Grid.Row="0"
|
||||
Grid.Column="0"
|
||||
Margin="12,12,0,12">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Token type -->
|
||||
<ToggleButton
|
||||
Grid.Column="0"
|
||||
Margin="6"
|
||||
IsChecked="{Binding IsBotToken}"
|
||||
Style="{StaticResource MaterialDesignFlatActionToggleButton}"
|
||||
ToolTip="Switch between user token and bot token">
|
||||
<ToggleButton.Content>
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="Account" />
|
||||
</ToggleButton.Content>
|
||||
<materialDesign:ToggleButtonAssist.OnContent>
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="Robot" />
|
||||
</materialDesign:ToggleButtonAssist.OnContent>
|
||||
</ToggleButton>
|
||||
|
||||
<!-- Token value -->
|
||||
<TextBox
|
||||
x:Name="TokenValueTextBox"
|
||||
Grid.Column="1"
|
||||
Margin="2,6,6,7"
|
||||
materialDesign:HintAssist.Hint="Token"
|
||||
materialDesign:TextFieldAssist.DecorationVisibility="Hidden"
|
||||
materialDesign:TextFieldAssist.TextBoxViewMargin="0,0,2,0"
|
||||
BorderThickness="0"
|
||||
FontSize="16"
|
||||
Text="{Binding TokenValue, UpdateSourceTrigger=PropertyChanged}" />
|
||||
|
||||
<!-- Pull data button -->
|
||||
<Button
|
||||
Grid.Column="2"
|
||||
Margin="0,6,6,6"
|
||||
Padding="4"
|
||||
Command="{s:Action PopulateGuildsAndChannels}"
|
||||
IsDefault="True"
|
||||
Style="{DynamicResource MaterialDesignFlatButton}">
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="ArrowRight" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</materialDesign:Card>
|
||||
|
||||
<!-- Settings button -->
|
||||
<Button
|
||||
Grid.Column="1"
|
||||
Margin="6"
|
||||
Padding="4"
|
||||
Command="{s:Action ShowSettings}"
|
||||
Style="{DynamicResource MaterialDesignFlatDarkButton}">
|
||||
<materialDesign:PackIcon
|
||||
Width="24"
|
||||
Height="24"
|
||||
Kind="Settings" />
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Progress bar -->
|
||||
<ProgressBar
|
||||
Grid.Row="1"
|
||||
Background="{DynamicResource PrimaryHueMidBrush}"
|
||||
IsIndeterminate="{Binding IsProgressIndeterminate}"
|
||||
Value="{Binding ProgressManager.Progress, Mode=OneWay}" />
|
||||
|
||||
<!-- Content -->
|
||||
<Grid Grid.Row="2">
|
||||
<!-- Placeholder / usage instructions -->
|
||||
<Grid Margin="32,32,8,8" Visibility="{Binding AvailableGuilds, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}">
|
||||
<!-- For user token -->
|
||||
<StackPanel Visibility="{Binding IsBotToken, Converter={x:Static s:BoolToVisibilityConverter.InverseInstance}}">
|
||||
<TextBlock FontSize="18" Text="Please provide your user token to authorize" />
|
||||
<TextBlock Margin="8,8,0,0" FontSize="14">
|
||||
<Run Text="1. Open Discord" />
|
||||
<LineBreak />
|
||||
<Run Text="2. Press" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Ctrl+Shift+I" />
|
||||
<Run Text="to show developer tools" />
|
||||
<LineBreak />
|
||||
<Run Text="3. Press" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Ctrl+R" />
|
||||
<Run Text="to reload" />
|
||||
<LineBreak />
|
||||
<Run Text="4. Navigate to the" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Application" />
|
||||
<Run Text="tab" />
|
||||
<LineBreak />
|
||||
<Run Text="5. Select" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Local Storage" />
|
||||
<Run Text=">" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="https://discordapp.com" />
|
||||
<Run Text="on the left" />
|
||||
<LineBreak />
|
||||
<Run Text="6. Find" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="token" />
|
||||
<Run Text="under key and copy the value" />
|
||||
</TextBlock>
|
||||
<TextBlock Margin="0,24,0,0" FontSize="14">
|
||||
<Run Text="To authorize using bot token instead, click" />
|
||||
<InlineUIContainer>
|
||||
<materialDesign:PackIcon Margin="1,0,0,-3" Kind="Account" />
|
||||
</InlineUIContainer>
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
|
||||
<!-- For bot token -->
|
||||
<StackPanel Visibility="{Binding IsBotToken, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
|
||||
<TextBlock FontSize="18" Text="Please provide your bot token to authorize" />
|
||||
<TextBlock Margin="8,8,0,0" FontSize="14">
|
||||
<Run Text="1. Open Discord developer portal" />
|
||||
<LineBreak />
|
||||
<Run Text="2. Open your application's settings" />
|
||||
<LineBreak />
|
||||
<Run Text="3. Navigate to the" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Bot" />
|
||||
<Run Text="section on the left" />
|
||||
<LineBreak />
|
||||
<Run Text="4. Under" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Token" />
|
||||
<Run Text="click" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="Copy" />
|
||||
</TextBlock>
|
||||
<TextBlock Margin="0,24,0,0" FontSize="14">
|
||||
<Run Text="To authorize using user token instead, click" />
|
||||
<InlineUIContainer>
|
||||
<materialDesign:PackIcon Margin="1,0,0,-1" Kind="Robot" />
|
||||
</InlineUIContainer>
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Guilds and channels -->
|
||||
<Grid Background="{DynamicResource MaterialDesignCardBackground}" Visibility="{Binding AvailableGuilds, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Guilds -->
|
||||
<Border
|
||||
Grid.Column="0"
|
||||
BorderBrush="{DynamicResource DividerBrush}"
|
||||
BorderThickness="0,0,1,0">
|
||||
<ListBox
|
||||
ItemsSource="{Binding AvailableGuilds}"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Hidden"
|
||||
SelectedItem="{Binding SelectedGuild}"
|
||||
SelectionMode="Single">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid
|
||||
Margin="-8"
|
||||
Background="Transparent"
|
||||
Cursor="Hand"
|
||||
ToolTip="{Binding Model.Name}">
|
||||
<!-- Guild icon placeholder -->
|
||||
<Ellipse
|
||||
Width="48"
|
||||
Height="48"
|
||||
Margin="12,4,12,4"
|
||||
Fill="{DynamicResource DividerBrush}" />
|
||||
|
||||
<!-- Guild icon -->
|
||||
<Ellipse
|
||||
Width="48"
|
||||
Height="48"
|
||||
Margin="12,4,12,4">
|
||||
<Ellipse.Fill>
|
||||
<ImageBrush ImageSource="{Binding Model.IconUrl}" />
|
||||
</Ellipse.Fill>
|
||||
</Ellipse>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
|
||||
<!-- Channels -->
|
||||
<Border Grid.Column="1">
|
||||
<ListBox
|
||||
HorizontalContentAlignment="Stretch"
|
||||
ItemsSource="{Binding SelectedGuild.Channels}"
|
||||
SelectionMode="Extended">
|
||||
<i:Interaction.Behaviors>
|
||||
<behaviors:ChannelViewModelMultiSelectionListBoxBehavior SelectedItems="{Binding SelectedChannels}" />
|
||||
</i:Interaction.Behaviors>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid Margin="-8" Background="Transparent">
|
||||
<Grid.InputBindings>
|
||||
<MouseBinding Command="{s:Action ExportChannels}" MouseAction="LeftDoubleClick" />
|
||||
</Grid.InputBindings>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Channel icon -->
|
||||
<materialDesign:PackIcon
|
||||
Grid.Column="0"
|
||||
Margin="16,7,0,6"
|
||||
VerticalAlignment="Center"
|
||||
Kind="Pound" />
|
||||
|
||||
<!-- Channel category / name -->
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
Margin="3,8,8,8"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="14">
|
||||
<Run Foreground="{DynamicResource SecondaryTextBrush}" Text="{Binding Category, Mode=OneWay}" />
|
||||
<Run Text="/" />
|
||||
<Run Foreground="{DynamicResource PrimaryTextBrush}" Text="{Binding Model.Name, Mode=OneWay}" />
|
||||
</TextBlock>
|
||||
|
||||
<!-- Is selected checkmark -->
|
||||
<materialDesign:PackIcon
|
||||
Grid.Column="2"
|
||||
Width="24"
|
||||
Height="24"
|
||||
Margin="8,0"
|
||||
VerticalAlignment="Center"
|
||||
Kind="Check"
|
||||
Visibility="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Converter={x:Static s:BoolToVisibilityConverter.Instance}, Mode=OneWay}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<!-- Export button -->
|
||||
<Button
|
||||
Margin="32,24"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Bottom"
|
||||
Command="{s:Action ExportChannels}"
|
||||
Style="{StaticResource MaterialDesignFloatingActionAccentButton}"
|
||||
Visibility="{Binding CanExportChannels, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
|
||||
<materialDesign:PackIcon
|
||||
Width="32"
|
||||
Height="32"
|
||||
Kind="Download" />
|
||||
</Button>
|
||||
|
||||
<!-- Notifications snackbar -->
|
||||
<materialDesign:Snackbar MessageQueue="{Binding Notifications}" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</materialDesign:DialogHost>
|
||||
</Window>
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DiscordChatExporter.Gui.Views
|
||||
{
|
||||
public partial class RootView
|
||||
{
|
||||
public RootView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user